'Test backup export import functionality.
Cinder allows exporting DB backup information through its API so it can
be imported back in case of a DB loss.'

@decorators.idempotent_id('a99c54a1-dd80-4724-8a13-13bf58d4068d')
def test_volume_backup_export_import(self):

    volume = self.create_volume()
    backup_name = data_utils.rand_name((self.__class__.__name__ + '-Backup'))
    backup = self.create_backup(backup_client=self.admin_backups_client, volume_id=volume['id'], name=backup_name)
    self.assertEqual(backup_name, backup['name'])
    export_backup = self.admin_backups_client.export_backup(backup['id'])['backup-record']
    self.assertIn('backup_service', export_backup)
    self.assertIn('backup_url', export_backup)
    self.assertTrue(export_backup['backup_service'].startswith('cinder.backup.drivers'))
    self.assertIsNotNone(export_backup['backup_url'])
    new_id = data_utils.rand_uuid()
    new_url = self._modify_backup_url(export_backup['backup_url'], {'id': new_id})
    import_backup = self.admin_backups_client.import_backup(backup_service=export_backup['backup_service'], backup_url=new_url)['backup']
    self.addCleanup(self._delete_backup, new_id)
    self.assertIn('id', import_backup)
    self.assertEqual(new_id, import_backup['id'])
    waiters.wait_for_volume_resource_status(self.admin_backups_client, import_backup['id'], 'available')
    backups = self.admin_backups_client.list_backups(detail=True)['backups']
    self.assertIn(new_id, [b['id'] for b in backups])
    restore = self.admin_backups_client.restore_backup(backup['id'])['restore']
    self.addCleanup(self.admin_volume_client.delete_volume, restore['volume_id'])
    self.assertEqual(backup['id'], restore['backup_id'])
    waiters.wait_for_volume_resource_status(self.admin_volume_client, restore['volume_id'], 'available')
    volumes = self.admin_volume_client.list_volumes()['volumes']
    self.assertIn(restore['volume_id'], [v['id'] for v in volumes])
    waiters.wait_for_volume_resource_status(self.admin_backups_client, import_backup['id'], 'available')
