volume = db.volume_get(ctx, volume['id'])
self.assertEqual('in-use', volume['status'])
self.assertEqual(stubs.FAKE_UUID, attachment['instance_uuid'])
- self.assertEqual(attachment['mountpoint'], mountpoint)
+ self.assertEqual(mountpoint, attachment['mountpoint'])
self.assertEqual('attached', attachment['attach_status'])
admin_metadata = volume['volume_admin_metadata']
self.assertEqual(2, len(admin_metadata))
conn_info = self.volume_api.initialize_connection(ctx,
volume,
connector)
- self.assertEqual(conn_info['data']['access_mode'], 'rw')
+ self.assertEqual('rw', conn_info['data']['access_mode'])
# build request to force detach
req = webob.Request.blank('/v2/fake/volumes/%s/action' % volume['id'])
req.method = 'POST'
volume = db.volume_get(ctx, volume['id'])
self.assertEqual('in-use', volume['status'])
self.assertIsNone(attachment['instance_uuid'])
- self.assertEqual(attachment['attached_host'], host_name)
- self.assertEqual(attachment['mountpoint'], mountpoint)
+ self.assertEqual(host_name, attachment['attached_host'])
+ self.assertEqual(mountpoint, attachment['mountpoint'])
self.assertEqual('attached', attachment['attach_status'])
admin_metadata = volume['volume_admin_metadata']
self.assertEqual(2, len(admin_metadata))
volume = db.volume_get(ctx, volume['id'])
self.assertEqual('in-use', volume['status'])
self.assertEqual(stubs.FAKE_UUID, attachment['instance_uuid'])
- self.assertEqual(attachment['mountpoint'], mountpoint)
+ self.assertEqual(mountpoint, attachment['mountpoint'])
self.assertEqual('attached', attachment['attach_status'])
admin_metadata = volume['volume_admin_metadata']
self.assertEqual(2, len(admin_metadata))
volume = db.volume_get(ctx, volume['id'])
self.assertEqual('in-use', volume['status'])
self.assertEqual(stubs.FAKE_UUID, attachment['instance_uuid'])
- self.assertEqual(attachment['mountpoint'], mountpoint)
+ self.assertEqual(mountpoint, attachment['mountpoint'])
self.assertEqual('attached', attachment['attach_status'])
admin_metadata = volume['volume_admin_metadata']
self.assertEqual(2, len(admin_metadata))
self.assertEqual('this is a test backup',
res_dict['backup']['description'])
self.assertEqual('test_backup', res_dict['backup']['name'])
- self.assertEqual(res_dict['backup']['id'], backup_id)
+ self.assertEqual(backup_id, res_dict['backup']['id'])
self.assertEqual(0, res_dict['backup']['object_count'])
self.assertEqual(0, res_dict['backup']['size'])
self.assertEqual('creating', res_dict['backup']['status'])
- self.assertEqual(res_dict['backup']['volume_id'], volume_id)
+ self.assertEqual(volume_id, res_dict['backup']['volume_id'])
db.backup_destroy(context.get_admin_context(), backup_id)
db.volume_destroy(context.get_admin_context(), volume_id)
self.assertEqual(404, res.status_int)
self.assertEqual(404, res_dict['itemNotFound']['code'])
- self.assertEqual(res_dict['itemNotFound']['message'],
- 'Backup 9999 could not be found.')
+ self.assertEqual('Backup 9999 could not be found.',
+ res_dict['itemNotFound']['message'])
def test_list_backups_json(self):
backup_id1 = self._create_backup()
self.assertEqual(200, res.status_int)
self.assertEqual(3, len(res_dict['backups'][0]))
- self.assertEqual(res_dict['backups'][0]['id'], backup_id1)
+ self.assertEqual(backup_id1, res_dict['backups'][0]['id'])
self.assertEqual('test_backup', res_dict['backups'][0]['name'])
self.assertEqual(3, len(res_dict['backups'][1]))
- self.assertEqual(res_dict['backups'][1]['id'], backup_id2)
+ self.assertEqual(backup_id2, res_dict['backups'][1]['id'])
self.assertEqual('test_backup', res_dict['backups'][1]['name'])
self.assertEqual(3, len(res_dict['backups'][2]))
- self.assertEqual(res_dict['backups'][2]['id'], backup_id3)
+ self.assertEqual(backup_id3, res_dict['backups'][2]['id'])
self.assertEqual('test_backup', res_dict['backups'][2]['name'])
db.backup_destroy(context.get_admin_context(), backup_id3)
backup_list = dom.getElementsByTagName('backup')
self.assertEqual(2, backup_list.item(0).attributes.length)
- self.assertEqual(backup_list.item(0).getAttribute('id'),
- backup_id1)
+ self.assertEqual(backup_id1,
+ backup_list.item(0).getAttribute('id'))
self.assertEqual(2, backup_list.item(1).attributes.length)
- self.assertEqual(backup_list.item(1).getAttribute('id'),
- backup_id2)
+ self.assertEqual(backup_id2,
+ backup_list.item(1).getAttribute('id'))
self.assertEqual(2, backup_list.item(2).attributes.length)
- self.assertEqual(backup_list.item(2).getAttribute('id'),
- backup_id3)
+ self.assertEqual(backup_id3,
+ backup_list.item(2).getAttribute('id'))
db.backup_destroy(context.get_admin_context(), backup_id3)
db.backup_destroy(context.get_admin_context(), backup_id2)
self.assertEqual(200, res.status_int)
self.assertEqual(12, len(res_dict['backups'][0]))
self.assertEqual('az1', res_dict['backups'][0]['availability_zone'])
- self.assertEqual(res_dict['backups'][0]['container'],
- 'volumebackups')
- self.assertEqual(res_dict['backups'][0]['description'],
- 'this is a test backup')
- self.assertEqual(res_dict['backups'][0]['name'],
- 'test_backup')
- self.assertEqual(res_dict['backups'][0]['id'], backup_id1)
- self.assertEqual(res_dict['backups'][0]['object_count'], 0)
- self.assertEqual(res_dict['backups'][0]['size'], 0)
- self.assertEqual(res_dict['backups'][0]['status'], 'creating')
- self.assertEqual(res_dict['backups'][0]['volume_id'], '1')
-
- self.assertEqual(len(res_dict['backups'][1]), 12)
- self.assertEqual(res_dict['backups'][1]['availability_zone'], 'az1')
- self.assertEqual(res_dict['backups'][1]['container'],
- 'volumebackups')
- self.assertEqual(res_dict['backups'][1]['description'],
- 'this is a test backup')
- self.assertEqual(res_dict['backups'][1]['name'],
- 'test_backup')
- self.assertEqual(res_dict['backups'][1]['id'], backup_id2)
- self.assertEqual(res_dict['backups'][1]['object_count'], 0)
- self.assertEqual(res_dict['backups'][1]['size'], 0)
- self.assertEqual(res_dict['backups'][1]['status'], 'creating')
- self.assertEqual(res_dict['backups'][1]['volume_id'], '1')
-
- self.assertEqual(len(res_dict['backups'][2]), 12)
- self.assertEqual(res_dict['backups'][2]['availability_zone'], 'az1')
- self.assertEqual(res_dict['backups'][2]['container'],
- 'volumebackups')
- self.assertEqual(res_dict['backups'][2]['description'],
- 'this is a test backup')
- self.assertEqual(res_dict['backups'][2]['name'],
- 'test_backup')
- self.assertEqual(res_dict['backups'][2]['id'], backup_id3)
- self.assertEqual(res_dict['backups'][2]['object_count'], 0)
- self.assertEqual(res_dict['backups'][2]['size'], 0)
- self.assertEqual(res_dict['backups'][2]['status'], 'creating')
- self.assertEqual(res_dict['backups'][2]['volume_id'], '1')
+ self.assertEqual('volumebackups',
+ res_dict['backups'][0]['container'])
+ self.assertEqual('this is a test backup',
+ res_dict['backups'][0]['description'])
+ self.assertEqual('test_backup',
+ res_dict['backups'][0]['name'])
+ self.assertEqual(backup_id1, res_dict['backups'][0]['id'])
+ self.assertEqual(0, res_dict['backups'][0]['object_count'])
+ self.assertEqual(0, res_dict['backups'][0]['size'])
+ self.assertEqual('creating', res_dict['backups'][0]['status'])
+ self.assertEqual('1', res_dict['backups'][0]['volume_id'])
+
+ self.assertEqual(12, len(res_dict['backups'][1]))
+ self.assertEqual('az1', res_dict['backups'][1]['availability_zone'])
+ self.assertEqual('volumebackups',
+ res_dict['backups'][1]['container'])
+ self.assertEqual('this is a test backup',
+ res_dict['backups'][1]['description'])
+ self.assertEqual('test_backup',
+ res_dict['backups'][1]['name'])
+ self.assertEqual(backup_id2, res_dict['backups'][1]['id'])
+ self.assertEqual(0, res_dict['backups'][1]['object_count'])
+ self.assertEqual(0, res_dict['backups'][1]['size'])
+ self.assertEqual('creating', res_dict['backups'][1]['status'])
+ self.assertEqual('1', res_dict['backups'][1]['volume_id'])
+
+ self.assertEqual(12, len(res_dict['backups'][2]))
+ self.assertEqual('az1', res_dict['backups'][2]['availability_zone'])
+ self.assertEqual('volumebackups',
+ res_dict['backups'][2]['container'])
+ self.assertEqual('this is a test backup',
+ res_dict['backups'][2]['description'])
+ self.assertEqual('test_backup',
+ res_dict['backups'][2]['name'])
+ self.assertEqual(backup_id3, res_dict['backups'][2]['id'])
+ self.assertEqual(0, res_dict['backups'][2]['object_count'])
+ self.assertEqual(0, res_dict['backups'][2]['size'])
+ self.assertEqual('creating', res_dict['backups'][2]['status'])
+ self.assertEqual('1', res_dict['backups'][2]['volume_id'])
db.backup_destroy(context.get_admin_context(), backup_id3)
db.backup_destroy(context.get_admin_context(), backup_id2)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(len(res_dict['backups']), 1)
- self.assertEqual(res.status_int, 200)
- self.assertEqual(res_dict['backups'][0]['id'], backup_id1)
+ self.assertEqual(1, len(res_dict['backups']))
+ self.assertEqual(200, res.status_int)
+ self.assertEqual(backup_id1, res_dict['backups'][0]['id'])
req = webob.Request.blank('/v2/fake/backups/detail?status=available')
req.method = 'GET'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(len(res_dict['backups']), 1)
- self.assertEqual(res.status_int, 200)
- self.assertEqual(res_dict['backups'][0]['id'], backup_id2)
+ self.assertEqual(1, len(res_dict['backups']))
+ self.assertEqual(200, res.status_int)
+ self.assertEqual(backup_id2, res_dict['backups'][0]['id'])
req = webob.Request.blank('/v2/fake/backups/detail?volume_id=4321')
req.method = 'GET'
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(len(res_dict['backups']), 1)
- self.assertEqual(res.status_int, 200)
- self.assertEqual(res_dict['backups'][0]['id'], backup_id3)
+ self.assertEqual(1, len(res_dict['backups']))
+ self.assertEqual(200, res.status_int)
+ self.assertEqual(backup_id3, res_dict['backups'][0]['id'])
db.backup_destroy(context.get_admin_context(), backup_id3)
db.backup_destroy(context.get_admin_context(), backup_id2)
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
- self.assertEqual(res.status_int, 200)
+ self.assertEqual(200, res.status_int)
dom = minidom.parseString(res.body)
backup_detail = dom.getElementsByTagName('backup')
- self.assertEqual(backup_detail.item(0).attributes.length, 11)
+ self.assertEqual(11, backup_detail.item(0).attributes.length)
self.assertEqual(
- backup_detail.item(0).getAttribute('availability_zone'), 'az1')
+ 'az1', backup_detail.item(0).getAttribute('availability_zone'))
self.assertEqual(
- backup_detail.item(0).getAttribute('container'), 'volumebackups')
+ 'volumebackups', backup_detail.item(0).getAttribute('container'))
self.assertEqual(
- backup_detail.item(0).getAttribute('description'),
- 'this is a test backup')
+ 'this is a test backup',
+ backup_detail.item(0).getAttribute('description'))
self.assertEqual(
- backup_detail.item(0).getAttribute('name'), 'test_backup')
+ 'test_backup', backup_detail.item(0).getAttribute('name'))
self.assertEqual(
- backup_detail.item(0).getAttribute('id'), backup_id1)
+ backup_id1, backup_detail.item(0).getAttribute('id'))
self.assertEqual(
- int(backup_detail.item(0).getAttribute('object_count')), 0)
+ 0, int(backup_detail.item(0).getAttribute('object_count')))
self.assertEqual(
- int(backup_detail.item(0).getAttribute('size')), 0)
+ 0, int(backup_detail.item(0).getAttribute('size')))
self.assertEqual(
- backup_detail.item(0).getAttribute('status'), 'creating')
+ 'creating', backup_detail.item(0).getAttribute('status'))
self.assertEqual(
- int(backup_detail.item(0).getAttribute('volume_id')), 1)
+ 1, int(backup_detail.item(0).getAttribute('volume_id')))
- self.assertEqual(backup_detail.item(1).attributes.length, 11)
+ self.assertEqual(11, backup_detail.item(1).attributes.length)
self.assertEqual(
- backup_detail.item(1).getAttribute('availability_zone'), 'az1')
+ 'az1', backup_detail.item(1).getAttribute('availability_zone'))
self.assertEqual(
- backup_detail.item(1).getAttribute('container'), 'volumebackups')
+ 'volumebackups', backup_detail.item(1).getAttribute('container'))
self.assertEqual(
- backup_detail.item(1).getAttribute('description'),
- 'this is a test backup')
+ 'this is a test backup',
+ backup_detail.item(1).getAttribute('description'))
self.assertEqual(
- backup_detail.item(1).getAttribute('name'), 'test_backup')
+ 'test_backup', backup_detail.item(1).getAttribute('name'))
self.assertEqual(
- backup_detail.item(1).getAttribute('id'), backup_id2)
+ backup_id2, backup_detail.item(1).getAttribute('id'))
self.assertEqual(
- int(backup_detail.item(1).getAttribute('object_count')), 0)
+ 0, int(backup_detail.item(1).getAttribute('object_count')))
self.assertEqual(
- int(backup_detail.item(1).getAttribute('size')), 0)
+ 0, int(backup_detail.item(1).getAttribute('size')))
self.assertEqual(
- backup_detail.item(1).getAttribute('status'), 'creating')
+ 'creating', backup_detail.item(1).getAttribute('status'))
self.assertEqual(
- int(backup_detail.item(1).getAttribute('volume_id')), 1)
+ 1, int(backup_detail.item(1).getAttribute('volume_id')))
- self.assertEqual(backup_detail.item(2).attributes.length, 11)
+ self.assertEqual(11, backup_detail.item(2).attributes.length)
self.assertEqual(
- backup_detail.item(2).getAttribute('availability_zone'), 'az1')
+ 'az1', backup_detail.item(2).getAttribute('availability_zone'))
self.assertEqual(
- backup_detail.item(2).getAttribute('container'), 'volumebackups')
+ 'volumebackups', backup_detail.item(2).getAttribute('container'))
self.assertEqual(
- backup_detail.item(2).getAttribute('description'),
- 'this is a test backup')
+ 'this is a test backup',
+ backup_detail.item(2).getAttribute('description'))
self.assertEqual(
- backup_detail.item(2).getAttribute('name'), 'test_backup')
+ 'test_backup', backup_detail.item(2).getAttribute('name'))
self.assertEqual(
- backup_detail.item(2).getAttribute('id'), backup_id3)
+ backup_id3, backup_detail.item(2).getAttribute('id'))
self.assertEqual(
- int(backup_detail.item(2).getAttribute('object_count')), 0)
+ 0, int(backup_detail.item(2).getAttribute('object_count')))
self.assertEqual(
- int(backup_detail.item(2).getAttribute('size')), 0)
+ 0, int(backup_detail.item(2).getAttribute('size')))
self.assertEqual(
- backup_detail.item(2).getAttribute('status'), 'creating')
+ 'creating', backup_detail.item(2).getAttribute('status'))
self.assertEqual(
- int(backup_detail.item(2).getAttribute('volume_id')), 1)
+ 1, int(backup_detail.item(2).getAttribute('volume_id')))
db.backup_destroy(context.get_admin_context(), backup_id3)
db.backup_destroy(context.get_admin_context(), backup_id2)
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 202)
+ self.assertEqual(202, res.status_int)
self.assertIn('id', res_dict['backup'])
self.assertTrue(_mock_service_get_all_by_topic.called)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 202)
+ self.assertEqual(202, res.status_int)
self.assertIn('id', res_dict['backup'])
self.assertTrue(_mock_service_get_all_by_topic.called)
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
- self.assertEqual(res.status_int, 202)
+ self.assertEqual(202, res.status_int)
dom = minidom.parseString(res.body)
backup = dom.getElementsByTagName('backup')
self.assertTrue(backup.item(0).hasAttribute('id'))
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
self.assertEqual("Missing required element 'backup' in request body.",
res_dict['badRequest']['message'])
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Incorrect request body format')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Incorrect request body format',
+ res_dict['badRequest']['message'])
def test_create_backup_with_VolumeNotFound(self):
body = {"backup": {"display_name": "nightly001",
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 404)
- self.assertEqual(res_dict['itemNotFound']['code'], 404)
- self.assertEqual(res_dict['itemNotFound']['message'],
- 'Volume 9999 could not be found.')
+ self.assertEqual(404, res.status_int)
+ self.assertEqual(404, res_dict['itemNotFound']['code'])
+ self.assertEqual('Volume 9999 could not be found.',
+ res_dict['itemNotFound']['message'])
def test_create_backup_with_InvalidVolume(self):
# need to create the volume referenced below first
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
@mock.patch('cinder.db.service_get_all_by_topic')
def test_create_backup_WithOUT_enabled_backup_service(
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 500)
- self.assertEqual(res_dict['computeFault']['code'], 500)
- self.assertEqual(res_dict['computeFault']['message'],
- 'Service cinder-backup could not be found.')
+ self.assertEqual(500, res.status_int)
+ self.assertEqual(500, res_dict['computeFault']['code'])
+ self.assertEqual('Service cinder-backup could not be found.',
+ res_dict['computeFault']['message'])
volume = self.volume_api.get(context.get_admin_context(), volume_id)
- self.assertEqual(volume['status'], 'available')
+ self.assertEqual('available', volume['status'])
@mock.patch('cinder.db.service_get_all_by_topic')
def test_create_incremental_backup_invalid_no_full(
volume = self.volume_api.get(context.get_admin_context(), volume_id)
# test empty service
- self.assertEqual(self.backup_api._is_backup_service_enabled(volume,
- test_host),
- False)
+ self.assertEqual(False,
+ self.backup_api._is_backup_service_enabled(volume,
+ test_host))
# test host not match service
- self.assertEqual(self.backup_api._is_backup_service_enabled(volume,
- test_host),
- False)
+ self.assertEqual(False,
+ self.backup_api._is_backup_service_enabled(volume,
+ test_host))
# test az not match service
- self.assertEqual(self.backup_api._is_backup_service_enabled(volume,
- test_host),
- False)
+ self.assertEqual(False,
+ self.backup_api._is_backup_service_enabled(volume,
+ test_host))
# test disabled service
- self.assertEqual(self.backup_api._is_backup_service_enabled(volume,
- test_host),
- False)
+ self.assertEqual(False,
+ self.backup_api._is_backup_service_enabled(volume,
+ test_host))
# test dead service
- self.assertEqual(self.backup_api._is_backup_service_enabled(volume,
- test_host),
- False)
+ self.assertEqual(False,
+ self.backup_api._is_backup_service_enabled(volume,
+ test_host))
# test multi services and the last service matches
- self.assertEqual(self.backup_api._is_backup_service_enabled(volume,
- test_host),
- True)
+ self.assertEqual(True,
+ self.backup_api._is_backup_service_enabled(volume,
+ test_host))
def test_delete_backup_available(self):
backup_id = self._create_backup(status='available')
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
- self.assertEqual(res.status_int, 202)
- self.assertEqual(self._get_backup_attrib(backup_id, 'status'),
- 'deleting')
+ self.assertEqual(202, res.status_int)
+ self.assertEqual('deleting',
+ self._get_backup_attrib(backup_id, 'status'))
db.backup_destroy(context.get_admin_context(), backup_id)
req.headers['Content-Type'] = 'application/json'
res = req.get_response(fakes.wsgi_app())
- self.assertEqual(res.status_int, 202)
- self.assertEqual(self._get_backup_attrib(backup_id, 'status'),
- 'deleting')
+ self.assertEqual(202, res.status_int)
+ self.assertEqual('deleting',
+ self._get_backup_attrib(backup_id, 'status'))
db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 404)
- self.assertEqual(res_dict['itemNotFound']['code'], 404)
- self.assertEqual(res_dict['itemNotFound']['message'],
- 'Backup 9999 could not be found.')
+ self.assertEqual(404, res.status_int)
+ self.assertEqual(404, res_dict['itemNotFound']['code'])
+ self.assertEqual('Backup 9999 could not be found.',
+ res_dict['itemNotFound']['message'])
def test_delete_backup_with_InvalidBackup(self):
backup_id = self._create_backup()
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Invalid backup: Backup status must be '
- 'available or error')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Invalid backup: Backup status must be '
+ 'available or error',
+ res_dict['badRequest']['message'])
db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 202)
- self.assertEqual(res_dict['restore']['backup_id'], backup_id)
- self.assertEqual(res_dict['restore']['volume_id'], volume_id)
+ self.assertEqual(202, res.status_int)
+ self.assertEqual(backup_id, res_dict['restore']['backup_id'])
+ self.assertEqual(volume_id, res_dict['restore']['volume_id'])
def test_restore_backup_volume_id_specified_xml(self):
backup_id = self._create_backup(status='available')
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
- self.assertEqual(res.status_int, 202)
+ self.assertEqual(202, res.status_int)
dom = minidom.parseString(res.body)
restore = dom.getElementsByTagName('restore')
- self.assertEqual(restore.item(0).getAttribute('backup_id'),
- backup_id)
- self.assertEqual(restore.item(0).getAttribute('volume_id'), volume_id)
+ self.assertEqual(backup_id,
+ restore.item(0).getAttribute('backup_id'))
+ self.assertEqual(volume_id, restore.item(0).getAttribute('volume_id'))
db.backup_destroy(context.get_admin_context(), backup_id)
db.volume_destroy(context.get_admin_context(), volume_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
self.assertEqual("Missing required element 'restore' in request body.",
res_dict['badRequest']['message'])
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
self.assertEqual("Missing required element 'restore' in request body.",
res_dict['badRequest']['message'])
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 202)
- self.assertEqual(res_dict['restore']['backup_id'], backup_id)
+ self.assertEqual(202, res.status_int)
+ self.assertEqual(backup_id, res_dict['restore']['backup_id'])
@mock.patch('cinder.volume.API.create')
def test_restore_backup_name_specified(self,
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Invalid input received: Invalid input')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Invalid input received: Invalid input',
+ res_dict['badRequest']['message'])
def test_restore_backup_with_InvalidVolume(self):
backup_id = self._create_backup(status='available')
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Invalid volume: Volume to be restored to must '
- 'be available')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Invalid volume: Volume to be restored to must '
+ 'be available',
+ res_dict['badRequest']['message'])
db.volume_destroy(context.get_admin_context(), volume_id)
db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Invalid backup: Backup status must be available')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Invalid backup: Backup status must be available',
+ res_dict['badRequest']['message'])
db.volume_destroy(context.get_admin_context(), volume_id)
db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 404)
- self.assertEqual(res_dict['itemNotFound']['code'], 404)
- self.assertEqual(res_dict['itemNotFound']['message'],
- 'Backup 9999 could not be found.')
+ self.assertEqual(404, res.status_int)
+ self.assertEqual(404, res_dict['itemNotFound']['code'])
+ self.assertEqual('Backup 9999 could not be found.',
+ res_dict['itemNotFound']['message'])
db.volume_destroy(context.get_admin_context(), volume_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 404)
- self.assertEqual(res_dict['itemNotFound']['code'], 404)
- self.assertEqual(res_dict['itemNotFound']['message'],
- 'Volume 9999 could not be found.')
+ self.assertEqual(404, res.status_int)
+ self.assertEqual(404, res_dict['itemNotFound']['code'])
+ self.assertEqual('Volume 9999 could not be found.',
+ res_dict['itemNotFound']['message'])
db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 413)
- self.assertEqual(res_dict['overLimit']['code'], 413)
- self.assertEqual(res_dict['overLimit']['message'],
- 'Requested volume or snapshot exceeds allowed '
+ self.assertEqual(413, res.status_int)
+ self.assertEqual(413, res_dict['overLimit']['code'])
+ self.assertEqual('Requested volume or snapshot exceeds allowed '
'gigabytes quota. Requested 2G, quota is 3G and '
- '2G has been consumed.')
+ '2G has been consumed.',
+ res_dict['overLimit']['message'])
@mock.patch('cinder.backup.API.restore')
def test_restore_backup_with_VolumeLimitExceeded(self,
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Invalid volume: volume size %d is too '
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Invalid volume: volume size %d is too '
'small to restore backup of size %d.'
- % (volume_size, backup_size))
+ % (volume_size, backup_size),
+ res_dict['badRequest']['message'])
db.volume_destroy(context.get_admin_context(), volume_id)
db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 202)
- self.assertEqual(res_dict['restore']['backup_id'], backup_id)
- self.assertEqual(res_dict['restore']['volume_id'], volume_id)
+ self.assertEqual(202, res.status_int)
+ self.assertEqual(backup_id, res_dict['restore']['backup_id'])
+ self.assertEqual(volume_id, res_dict['restore']['volume_id'])
db.volume_destroy(context.get_admin_context(), volume_id)
db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app())
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 202)
- self.assertEqual(res_dict['restore']['backup_id'], backup_id)
- self.assertEqual(res_dict['restore']['volume_id'], volume_id)
+ self.assertEqual(202, res.status_int)
+ self.assertEqual(backup_id, res_dict['restore']['backup_id'])
+ self.assertEqual(volume_id, res_dict['restore']['volume_id'])
mock_restore_backup.assert_called_once_with(mock.ANY, u'HostB',
mock.ANY, volume_id)
# Manually check if restore_backup was called with appropriate backup.
res = req.get_response(fakes.wsgi_app())
# request is not authorized
- self.assertEqual(res.status_int, 403)
+ self.assertEqual(403, res.status_int)
@mock.patch('cinder.backup.rpcapi.BackupAPI.export_record')
def test_export_backup_record_id_specified_json(self,
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
# verify that request is successful
- self.assertEqual(res.status_int, 200)
- self.assertEqual(res_dict['backup-record']['backup_service'],
- backup_service)
- self.assertEqual(res_dict['backup-record']['backup_url'],
- backup_url)
+ self.assertEqual(200, res.status_int)
+ self.assertEqual(backup_service,
+ res_dict['backup-record']['backup_service'])
+ self.assertEqual(backup_url,
+ res_dict['backup-record']['backup_url'])
db.backup_destroy(context.get_admin_context(), backup_id)
@mock.patch('cinder.backup.rpcapi.BackupAPI.export_record')
req.headers['Content-Type'] = 'application/xml'
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
- self.assertEqual(res.status_int, 200)
+ self.assertEqual(200, res.status_int)
dom = minidom.parseString(res.body)
export = dom.getElementsByTagName('backup-record')
- self.assertEqual(export.item(0).getAttribute('backup_service'),
- backup_service)
- self.assertEqual(export.item(0).getAttribute('backup_url'),
- backup_url)
+ self.assertEqual(backup_service,
+ export.item(0).getAttribute('backup_service'))
+ self.assertEqual(backup_url,
+ export.item(0).getAttribute('backup_url'))
# db.backup_destroy(context.get_admin_context(), backup_id)
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 404)
- self.assertEqual(res_dict['itemNotFound']['code'], 404)
- self.assertEqual(res_dict['itemNotFound']['message'],
- 'Backup %s could not be found.' % backup_id)
+ self.assertEqual(404, res.status_int)
+ self.assertEqual(404, res_dict['itemNotFound']['code'])
+ self.assertEqual('Backup %s could not be found.' % backup_id,
+ res_dict['itemNotFound']['message'])
def test_export_record_for_unavailable_backup(self):
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Invalid backup: Backup status must be available '
- 'and not restoring.')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Invalid backup: Backup status must be available '
+ 'and not restoring.',
+ res_dict['badRequest']['message'])
db.backup_destroy(context.get_admin_context(), backup_id)
@mock.patch('cinder.backup.rpcapi.BackupAPI.export_record')
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Invalid backup: %s' % msg)
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Invalid backup: %s' % msg,
+ res_dict['badRequest']['message'])
db.backup_destroy(context.get_admin_context(), backup_id)
def test_import_record_as_non_admin(self):
res = req.get_response(fakes.wsgi_app())
# request is not authorized
- self.assertEqual(res.status_int, 403)
+ self.assertEqual(403, res.status_int)
@mock.patch('cinder.backup.api.API._list_backup_services')
@mock.patch('cinder.backup.rpcapi.BackupAPI.import_record')
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
# verify that request is successful
- self.assertEqual(res.status_int, 201)
+ self.assertEqual(201, res.status_int)
self.assertTrue('id' in res_dict['backup'])
@mock.patch('cinder.backup.api.API._list_backup_services')
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
- self.assertEqual(res.status_int, 201)
+ self.assertEqual(201, res.status_int)
dom = minidom.parseString(res.body)
backup = dom.getElementsByTagName('backup')
self.assertTrue(backup.item(0).hasAttribute('id'))
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 500)
- self.assertEqual(res_dict['computeFault']['code'], 500)
- self.assertEqual(res_dict['computeFault']['message'],
- 'Service %s could not be found.'
- % backup_service)
+ self.assertEqual(500, res.status_int)
+ self.assertEqual(500, res_dict['computeFault']['code'])
+ self.assertEqual('Service %s could not be found.'
+ % backup_service,
+ res_dict['computeFault']['message'])
@mock.patch('cinder.backup.api.API._list_backup_services')
@mock.patch('cinder.backup.rpcapi.BackupAPI.import_record')
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 500)
- self.assertEqual(res_dict['computeFault']['code'], 500)
- self.assertEqual(res_dict['computeFault']['message'],
- 'Service %s could not be found.'
- % backup_service)
+ self.assertEqual(500, res.status_int)
+ self.assertEqual(500, res_dict['computeFault']['code'])
+ self.assertEqual('Service %s could not be found.'
+ % backup_service,
+ res_dict['computeFault']['message'])
def test_import_record_with_missing_body_elements(self):
ctx = context.RequestContext('admin', 'fake', is_admin=True)
req.headers['content-type'] = 'application/json'
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Incorrect request body format.')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Incorrect request body format.',
+ res_dict['badRequest']['message'])
# test with no backup_url
req = webob.Request.blank('/v2/fake/backups/import_record')
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Incorrect request body format.')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Incorrect request body format.',
+ res_dict['badRequest']['message'])
# test with no backup_url and backup_url
req = webob.Request.blank('/v2/fake/backups/import_record')
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
- self.assertEqual(res_dict['badRequest']['message'],
- 'Incorrect request body format.')
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
+ self.assertEqual('Incorrect request body format.',
+ res_dict['badRequest']['message'])
def test_import_record_with_no_body(self):
ctx = context.RequestContext('admin', 'fake', is_admin=True)
res = req.get_response(fakes.wsgi_app(fake_auth_context=ctx))
res_dict = json.loads(res.body)
# verify that request is successful
- self.assertEqual(res.status_int, 400)
- self.assertEqual(res_dict['badRequest']['code'], 400)
+ self.assertEqual(400, res.status_int)
+ self.assertEqual(400, res_dict['badRequest']['code'])
self.assertEqual("Missing required element 'backup-record' in "
"request body.",
res_dict['badRequest']['message'])
body = {"consistencygroup": {"force": True}}
req.body = json.dumps(body)
res = req.get_response(fakes.wsgi_app())
- self.assertEqual(res.status_int, 202)
+ self.assertEqual(202, res.status_int)
cg = db.consistencygroup_get(
context.get_admin_context(read_deleted='yes'),
req.headers['Accept'] = 'application/xml'
res = req.get_response(fakes.wsgi_app())
- self.assertEqual(res.status_int, 200)
+ self.assertEqual(200, res.status_int)
dom = minidom.parseString(res.body)
associations_response = dom.getElementsByTagName('associations')
association = associations_response.item(0)
root = etree.XML(output)
xmlutil.validate_schema(root, 'qos_specs')
qos_elems = root.findall("qos_spec")
- self.assertEqual(len(qos_elems), 2)
+ self.assertEqual(2, len(qos_elems))
for i, qos_elem in enumerate(qos_elems):
qos_dict = fixture['qos_specs'][i]
# check qos_spec attributes
for key in ['name', 'id', 'consumer']:
- self.assertEqual(qos_elem.get(key), str(qos_dict[key]))
+ self.assertEqual(str(qos_dict[key]), qos_elem.get(key))
# check specs
specs = qos_elem.find("specs")
root = etree.XML(output)
xmlutil.validate_schema(root, 'qos_associations')
association_elems = root.findall("associations")
- self.assertEqual(len(association_elems), 2)
+ self.assertEqual(2, len(association_elems))
for i, association_elem in enumerate(association_elems):
association_dict = fixture['qos_associations'][i]
# check qos_spec attributes
for key in ['name', 'id', 'association_type']:
- self.assertEqual(association_elem.get(key),
- str(association_dict[key]))
+ self.assertEqual(str(association_dict[key]),
+ association_elem.get(key))
class TestQoSSpecsKeyDeserializer(test.TestCase):
expected = {
"keys": ["xyz", "abc"]
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_bad_format(self):
self_request = """
quota_set = make_body(root=False)
text = serializer.serialize({'quota_set': quota_set})
tree = etree.fromstring(text)
- self.assertEqual(tree.tag, 'quota_set')
- self.assertEqual(tree.get('id'), quota_set['id'])
+ self.assertEqual('quota_set', tree.tag)
+ self.assertEqual(quota_set['id'], tree.get('id'))
body = make_body(root=False, tenant_id=None)
for node in tree:
self.assertIn(node.tag, body)
self.assertEqual(202, res.status_int, res)
# Check that the manage API was called with the correct arguments.
- self.assertEqual(mock_api_manage.call_count, 1)
+ self.assertEqual(1, mock_api_manage.call_count)
args = mock_api_manage.call_args[0]
self.assertEqual(args[1], body['volume']['host'])
self.assertEqual(args[2], body['volume']['ref'])
'volume_type':
'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'}}
res = self._get_resp(body)
- self.assertEqual(res.status_int, 404, res)
+ self.assertEqual(404, res.status_int, res)
pass
def test_manage_volume_bad_volume_type_by_name(self):
req.environ['cinder.context'] = ctx
res = req.get_response(app())
vol = json.loads(res.body)['volume']
- self.assertEqual(vol['os-vol-mig-status-attr:migstat'], 'migrating')
- self.assertEqual(vol['os-vol-mig-status-attr:name_id'], 'fake2')
+ self.assertEqual('migrating', vol['os-vol-mig-status-attr:migstat'])
+ self.assertEqual('fake2', vol['os-vol-mig-status-attr:name_id'])
def test_get_volume_unallowed(self):
ctx = context.RequestContext('non-admin', 'fake', False)
req.environ['cinder.context'] = ctx
res = req.get_response(app())
vol = json.loads(res.body)['volumes']
- self.assertEqual(vol[0]['os-vol-mig-status-attr:migstat'], 'migrating')
- self.assertEqual(vol[0]['os-vol-mig-status-attr:name_id'], 'fake2')
+ self.assertEqual('migrating', vol[0]['os-vol-mig-status-attr:migstat'])
+ self.assertEqual('fake2', vol[0]['os-vol-mig-status-attr:name_id'])
def test_list_detail_volumes_unallowed(self):
ctx = context.RequestContext('non-admin', 'fake', False)
vol = etree.XML(res.body)
mig_key = ('{http://docs.openstack.org/volume/ext/'
'volume_mig_status_attribute/api/v1}migstat')
- self.assertEqual(vol.get(mig_key), 'migrating')
+ self.assertEqual('migrating', vol.get(mig_key))
mig_key = ('{http://docs.openstack.org/volume/ext/'
'volume_mig_status_attribute/api/v1}name_id')
- self.assertEqual(vol.get(mig_key), 'fake2')
+ self.assertEqual('fake2', vol.get(mig_key))
def test_list_volumes_detail_xml(self):
ctx = context.RequestContext('admin', 'fake', True)
vol = list(etree.XML(res.body))[0]
mig_key = ('{http://docs.openstack.org/volume/ext/'
'volume_mig_status_attribute/api/v1}migstat')
- self.assertEqual(vol.get(mig_key), 'migrating')
+ self.assertEqual('migrating', vol.get(mig_key))
mig_key = ('{http://docs.openstack.org/volume/ext/'
'volume_mig_status_attribute/api/v1}name_id')
- self.assertEqual(vol.get(mig_key), 'fake2')
+ self.assertEqual('fake2', vol.get(mig_key))
self.assertTrue(transfer.item(0).hasAttribute('id'))
self.assertTrue(transfer.item(0).hasAttribute('auth_key'))
self.assertTrue(transfer.item(0).hasAttribute('created_at'))
- self.assertEqual(transfer.item(0).getAttribute('name'), 'transfer-001')
+ self.assertEqual('transfer-001', transfer.item(0).getAttribute('name'))
self.assertTrue(transfer.item(0).hasAttribute('volume_id'))
db.volume_destroy(context.get_admin_context(), volume_id)
request = wsgi.Request.blank('/tests/123')
request.headers["Content-Type"] = "application/json; charset=UTF-8"
result = request.get_content_type()
- self.assertEqual(result, "application/json")
+ self.assertEqual("application/json", result)
def test_content_type_from_accept(self):
for content_type in ('application/xml',
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = content_type
result = request.best_match_content_type()
- self.assertEqual(result, content_type)
+ self.assertEqual(content_type, result)
def test_content_type_from_accept_best(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = "application/xml, application/json"
result = request.best_match_content_type()
- self.assertEqual(result, "application/json")
+ self.assertEqual("application/json", result)
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = ("application/json; q=0.3, "
"application/xml; q=0.9")
result = request.best_match_content_type()
- self.assertEqual(result, "application/xml")
+ self.assertEqual("application/xml", result)
def test_content_type_from_query_extension(self):
request = wsgi.Request.blank('/tests/123.xml')
result = request.best_match_content_type()
- self.assertEqual(result, "application/xml")
+ self.assertEqual("application/xml", result)
request = wsgi.Request.blank('/tests/123.json')
result = request.best_match_content_type()
- self.assertEqual(result, "application/json")
+ self.assertEqual("application/json", result)
request = wsgi.Request.blank('/tests/123.invalid')
result = request.best_match_content_type()
- self.assertEqual(result, "application/json")
+ self.assertEqual("application/json", result)
def test_content_type_accept_and_query_extension(self):
request = wsgi.Request.blank('/tests/123.xml')
request.headers["Accept"] = "application/json"
result = request.best_match_content_type()
- self.assertEqual(result, "application/xml")
+ self.assertEqual("application/xml", result)
def test_content_type_accept_default(self):
request = wsgi.Request.blank('/tests/123.unsupported')
request.headers["Accept"] = "application/unsupported1"
result = request.best_match_content_type()
- self.assertEqual(result, "application/json")
+ self.assertEqual("application/json", result)
def test_best_match_language(self):
# Test that we are actually invoking language negotiation by webob
# Store 1
getattr(r, cache_one_func)(resources[2])
- self.assertEqual(getattr(r, get_db_one_func)('id0'), resources[0])
- self.assertEqual(getattr(r, get_db_one_func)('id1'), resources[1])
- self.assertEqual(getattr(r, get_db_one_func)('id2'), resources[2])
+ self.assertEqual(resources[0], getattr(r, get_db_one_func)('id0'))
+ self.assertEqual(resources[1], getattr(r, get_db_one_func)('id1'))
+ self.assertEqual(resources[2], getattr(r, get_db_one_func)('id2'))
self.assertIsNone(getattr(r, get_db_one_func)('id3'))
- self.assertEqual(getattr(r, get_db_all_func)(), {
- 'id0': resources[0],
- 'id1': resources[1],
- 'id2': resources[2]})
+ self.assertEqual({'id0': resources[0],
+ 'id1': resources[1],
+ 'id2': resources[2]}, getattr(r, get_db_all_func)())
class ActionDispatcherTest(test.TestCase):
def test_dispatch(self):
serializer = wsgi.ActionDispatcher()
serializer.create = lambda x: 'pants'
- self.assertEqual(serializer.dispatch({}, action='create'), 'pants')
+ self.assertEqual('pants', serializer.dispatch({}, action='create'))
def test_dispatch_action_None(self):
serializer = wsgi.ActionDispatcher()
serializer.create = lambda x: 'pants'
serializer.default = lambda x: 'trousers'
- self.assertEqual(serializer.dispatch({}, action=None), 'trousers')
+ self.assertEqual('trousers', serializer.dispatch({}, action=None))
def test_dispatch_default(self):
serializer = wsgi.ActionDispatcher()
serializer.create = lambda x: 'pants'
serializer.default = lambda x: 'trousers'
- self.assertEqual(serializer.dispatch({}, action='update'), 'trousers')
+ self.assertEqual('trousers', serializer.dispatch({}, action='update'))
class DictSerializerTest(test.TestCase):
def test_dispatch_default(self):
serializer = wsgi.DictSerializer()
- self.assertEqual(serializer.serialize({}, 'update'), '')
+ self.assertEqual('', serializer.serialize({}, 'update'))
class XMLDictSerializerTest(test.TestCase):
serializer = wsgi.XMLDictSerializer(xmlns="asdf")
result = serializer.serialize(input_dict)
result = result.replace('\n', '').replace(' ', '')
- self.assertEqual(result, expected_xml)
+ self.assertEqual(expected_xml, result)
class JSONDictSerializerTest(test.TestCase):
serializer = wsgi.JSONDictSerializer()
result = serializer.serialize(input_dict)
result = result.replace('\n', '').replace(' ', '')
- self.assertEqual(result, expected_json)
+ self.assertEqual(expected_json, result)
class TextDeserializerTest(test.TestCase):
def test_dispatch_default(self):
deserializer = wsgi.TextDeserializer()
- self.assertEqual(deserializer.deserialize({}, 'update'), {})
+ self.assertEqual({}, deserializer.deserialize({}, 'update'))
class JSONDeserializerTest(test.TestCase):
},
}
deserializer = wsgi.JSONDeserializer()
- self.assertEqual(deserializer.deserialize(data), as_dict)
+ self.assertEqual(as_dict, deserializer.deserialize(data))
class XMLDeserializerTest(test.TestCase):
}
metadata = {'plurals': {'bs': 'b', 'ts': 't'}}
deserializer = wsgi.XMLDeserializer(metadata=metadata)
- self.assertEqual(deserializer.deserialize(xml), as_dict)
+ self.assertEqual(as_dict, deserializer.deserialize(xml))
def test_xml_empty(self):
xml = """<a></a>"""
as_dict = {"body": {"a": {}}}
deserializer = wsgi.XMLDeserializer()
- self.assertEqual(deserializer.deserialize(xml), as_dict)
+ self.assertEqual(as_dict, deserializer.deserialize(xml))
class MetadataXMLDeserializerTest(test.TestCase):
req = webob.Request.blank('/tests')
app = fakes.TestRouter(Controller())
response = req.get_response(app)
- self.assertEqual(response.body, 'off')
- self.assertEqual(response.status_int, 200)
+ self.assertEqual('off', response.body)
+ self.assertEqual(200, response.status_int)
def test_resource_not_authorized(self):
class Controller(object):
req = webob.Request.blank('/tests')
app = fakes.TestRouter(Controller())
response = req.get_response(app)
- self.assertEqual(response.status_int, 403)
+ self.assertEqual(403, response.status_int)
def test_dispatch(self):
class Controller(object):
method, _extensions = resource.get_method(None, 'index', None, '')
actual = resource.dispatch(method, None, {'pants': 'off'})
expected = 'off'
- self.assertEqual(actual, expected)
+ self.assertEqual(expected, actual)
def test_get_method_undefined_controller_action(self):
class Controller(object):
expected = {'action': 'update', 'id': 12}
- self.assertEqual(resource.get_action_args(env), expected)
+ self.assertEqual(expected, resource.get_action_args(env))
def test_get_body_bad_content(self):
class Controller(object):
content_type, body = resource.get_body(request)
self.assertIsNone(content_type)
- self.assertEqual(body, '')
+ self.assertEqual('', body)
def test_get_body_no_content_type(self):
class Controller(object):
content_type, body = resource.get_body(request)
self.assertIsNone(content_type)
- self.assertEqual(body, '')
+ self.assertEqual('', body)
def test_get_body_no_content_body(self):
class Controller(object):
content_type, body = resource.get_body(request)
self.assertIsNone(content_type)
- self.assertEqual(body, '')
+ self.assertEqual('', body)
def test_get_body(self):
class Controller(object):
request.body = 'foo'
content_type, body = resource.get_body(request)
- self.assertEqual(content_type, 'application/json')
- self.assertEqual(body, 'foo')
+ self.assertEqual('application/json', content_type)
+ self.assertEqual('foo', body)
def test_deserialize_badtype(self):
class Controller(object):
resource = wsgi.Resource(controller, json=JSONDeserializer)
obj = resource.deserialize(controller.index, 'application/json', 'foo')
- self.assertEqual(obj, 'json')
+ self.assertEqual('json', obj)
def test_deserialize_decorator(self):
class JSONDeserializer(object):
resource = wsgi.Resource(controller, json=JSONDeserializer)
obj = resource.deserialize(controller.index, 'application/xml', 'foo')
- self.assertEqual(obj, 'xml')
+ self.assertEqual('xml', obj)
def test_register_actions(self):
class Controller(object):
resource = wsgi.Resource(controller)
resource.register_extensions(extended)
method, extensions = resource.get_method(None, 'index', None, '')
- self.assertEqual(method, controller.index)
- self.assertEqual(extensions, [extended.index])
+ self.assertEqual(controller.index, method)
+ self.assertEqual([extended.index], extensions)
def test_get_method_action_extensions(self):
class Controller(wsgi.Controller):
method, extensions = resource.get_method(None, 'action',
'application/json',
'{"fooAction": true}')
- self.assertEqual(method, controller._action_foo)
- self.assertEqual(extensions, [extended._action_foo])
+ self.assertEqual(controller._action_foo, method)
+ self.assertEqual([extended._action_foo], extensions)
def test_get_method_action_whitelist_extensions(self):
class Controller(wsgi.Controller):
method, extensions = resource.get_method(None, 'create',
'application/json',
'{"create": true}')
- self.assertEqual(method, extended._create)
- self.assertEqual(extensions, [])
+ self.assertEqual(extended._create, method)
+ self.assertEqual([], extensions)
method, extensions = resource.get_method(None, 'delete', None, None)
- self.assertEqual(method, extended._delete)
- self.assertEqual(extensions, [])
+ self.assertEqual(extended._delete, method)
+ self.assertEqual([], extensions)
def test_pre_process_extensions_regular(self):
class Controller(object):
extensions = [extension1, extension2]
response, post = resource.pre_process_extensions(extensions, None, {})
- self.assertEqual(called, [])
+ self.assertEqual([], called)
self.assertIsNone(response)
- self.assertEqual(list(post), [extension2, extension1])
+ self.assertEqual([extension2, extension1], list(post))
def test_pre_process_extensions_generator(self):
class Controller(object):
extensions = [extension1, extension2]
response, post = resource.pre_process_extensions(extensions, None, {})
post = list(post)
- self.assertEqual(called, ['pre1', 'pre2'])
+ self.assertEqual(['pre1', 'pre2'], called)
self.assertIsNone(response)
- self.assertEqual(len(post), 2)
+ self.assertEqual(2, len(post))
self.assertTrue(inspect.isgenerator(post[0]))
self.assertTrue(inspect.isgenerator(post[1]))
except StopIteration:
continue
- self.assertEqual(called, ['pre1', 'pre2', 'post2', 'post1'])
+ self.assertEqual(['pre1', 'pre2', 'post2', 'post1'], called)
def test_pre_process_extensions_generator_response(self):
class Controller(object):
extensions = [extension1, extension2]
response, post = resource.pre_process_extensions(extensions, None, {})
- self.assertEqual(called, ['pre1'])
- self.assertEqual(response, 'foo')
- self.assertEqual(post, [])
+ self.assertEqual(['pre1'], called)
+ self.assertEqual('foo', response)
+ self.assertEqual([], post)
def test_post_process_extensions_regular(self):
class Controller(object):
response = resource.post_process_extensions([extension2, extension1],
None, None, {})
- self.assertEqual(called, [2, 1])
+ self.assertEqual([2, 1], called)
self.assertIsNone(response)
def test_post_process_extensions_regular_response(self):
response = resource.post_process_extensions([extension2, extension1],
None, None, {})
- self.assertEqual(called, [2])
- self.assertEqual(response, 'foo')
+ self.assertEqual([2], called)
+ self.assertEqual('foo', response)
def test_post_process_extensions_generator(self):
class Controller(object):
response = resource.post_process_extensions([ext2, ext1],
None, None, {})
- self.assertEqual(called, [2, 1])
+ self.assertEqual([2, 1], called)
self.assertIsNone(response)
def test_post_process_extensions_generator_response(self):
response = resource.post_process_extensions([ext2, ext1],
None, None, {})
- self.assertEqual(called, [2])
- self.assertEqual(response, 'foo')
+ self.assertEqual([2], called)
+ self.assertEqual('foo', response)
class ResponseObjectTest(test.TestCase):
def test_default_code(self):
robj = wsgi.ResponseObject({})
- self.assertEqual(robj.code, 200)
+ self.assertEqual(200, robj.code)
def test_modified_code(self):
robj = wsgi.ResponseObject({})
robj._default_code = 202
- self.assertEqual(robj.code, 202)
+ self.assertEqual(202, robj.code)
def test_override_default_code(self):
robj = wsgi.ResponseObject({}, code=404)
- self.assertEqual(robj.code, 404)
+ self.assertEqual(404, robj.code)
def test_override_modified_code(self):
robj = wsgi.ResponseObject({}, code=404)
robj._default_code = 202
- self.assertEqual(robj.code, 404)
+ self.assertEqual(404, robj.code)
def test_set_header(self):
robj = wsgi.ResponseObject({})
robj['Header'] = 'foo'
- self.assertEqual(robj.headers, {'header': 'foo'})
+ self.assertEqual({'header': 'foo'}, robj.headers)
def test_get_header(self):
robj = wsgi.ResponseObject({})
robj['Header'] = 'foo'
- self.assertEqual(robj['hEADER'], 'foo')
+ self.assertEqual('foo', robj['hEADER'])
def test_del_header(self):
robj = wsgi.ResponseObject({})
robj['Header'] = 'foo'
hdrs = robj.headers
hdrs['hEADER'] = 'bar'
- self.assertEqual(robj['hEADER'], 'foo')
+ self.assertEqual('foo', robj['hEADER'])
def test_default_serializers(self):
robj = wsgi.ResponseObject({})
- self.assertEqual(robj.serializers, {})
+ self.assertEqual({}, robj.serializers)
def test_bind_serializers(self):
robj = wsgi.ResponseObject({}, json='foo')
robj._bind_method_serializers(dict(xml='bar', json='baz'))
- self.assertEqual(robj.serializers, dict(xml='bar', json='foo'))
+ self.assertEqual(dict(xml='bar', json='foo'), robj.serializers)
def test_get_serializer(self):
robj = wsgi.ResponseObject({}, json='json', xml='xml', atom='atom')
for content_type, mtype in wsgi._MEDIA_TYPE_MAP.items():
_mtype, serializer = robj.get_serializer(content_type)
- self.assertEqual(serializer, mtype)
+ self.assertEqual(mtype, serializer)
def test_get_serializer_defaults(self):
robj = wsgi.ResponseObject({})
robj.get_serializer, content_type)
_mtype, serializer = robj.get_serializer(content_type,
default_serializers)
- self.assertEqual(serializer, mtype)
+ self.assertEqual(mtype, serializer)
def test_serialize(self):
class JSONSerializer(object):
request = wsgi.Request.blank('/tests/123')
response = robj.serialize(request, content_type)
- self.assertEqual(response.headers['Content-Type'], content_type)
- self.assertEqual(response.headers['X-header1'], 'header1')
- self.assertEqual(response.headers['X-header2'], 'header2')
- self.assertEqual(response.status_int, 202)
- self.assertEqual(response.body, mtype)
+ self.assertEqual(content_type, response.headers['Content-Type'])
+ self.assertEqual('header1', response.headers['X-header1'])
+ self.assertEqual('header2', response.headers['X-header2'])
+ self.assertEqual(202, response.status_int)
+ self.assertEqual(mtype, response.body)
class ValidBodyTest(test.TestCase):
def test_limiter_offset_zero(self):
"""Test offset key works with 0."""
req = webob.Request.blank('/?offset=0')
- self.assertEqual(common.limited(self.tiny, req), self.tiny)
- self.assertEqual(common.limited(self.small, req), self.small)
- self.assertEqual(common.limited(self.medium, req), self.medium)
- self.assertEqual(common.limited(self.large, req), self.large[:1000])
+ self.assertEqual(self.tiny, common.limited(self.tiny, req))
+ self.assertEqual(self.small, common.limited(self.small, req))
+ self.assertEqual(self.medium, common.limited(self.medium, req))
+ self.assertEqual(self.large[:1000], common.limited(self.large, req))
def test_limiter_offset_medium(self):
"""Test offset key works with a medium sized number."""
req = webob.Request.blank('/?offset=10')
- self.assertEqual(common.limited(self.tiny, req), [])
- self.assertEqual(common.limited(self.small, req), self.small[10:])
- self.assertEqual(common.limited(self.medium, req), self.medium[10:])
- self.assertEqual(common.limited(self.large, req), self.large[10:1010])
+ self.assertEqual([], common.limited(self.tiny, req))
+ self.assertEqual(self.small[10:], common.limited(self.small, req))
+ self.assertEqual(self.medium[10:], common.limited(self.medium, req))
+ self.assertEqual(self.large[10:1010], common.limited(self.large, req))
def test_limiter_offset_over_max(self):
"""Test offset key works with a number over 1000 (max_limit)."""
def test_limiter_nothing(self):
"""Test request with no offset or limit."""
req = webob.Request.blank('/')
- self.assertEqual(common.limited(self.tiny, req), self.tiny)
- self.assertEqual(common.limited(self.small, req), self.small)
- self.assertEqual(common.limited(self.medium, req), self.medium)
- self.assertEqual(common.limited(self.large, req), self.large[:1000])
+ self.assertEqual(self.tiny, common.limited(self.tiny, req))
+ self.assertEqual(self.small, common.limited(self.small, req))
+ self.assertEqual(self.medium, common.limited(self.medium, req))
+ self.assertEqual(self.large[:1000], common.limited(self.large, req))
def test_limiter_limit_zero(self):
"""Test limit of zero."""
req = webob.Request.blank('/?limit=0')
- self.assertEqual(common.limited(self.tiny, req), self.tiny)
- self.assertEqual(common.limited(self.small, req), self.small)
- self.assertEqual(common.limited(self.medium, req), self.medium)
- self.assertEqual(common.limited(self.large, req), self.large[:1000])
+ self.assertEqual(self.tiny, common.limited(self.tiny, req))
+ self.assertEqual(self.small, common.limited(self.small, req))
+ self.assertEqual(self.medium, common.limited(self.medium, req))
+ self.assertEqual(self.large[:1000], common.limited(self.large, req))
def test_limiter_limit_bad(self):
"""Test with a bad limit."""
def test_limiter_limit_medium(self):
"""Test limit of 10."""
req = webob.Request.blank('/?limit=10')
- self.assertEqual(common.limited(self.tiny, req), self.tiny)
- self.assertEqual(common.limited(self.small, req), self.small)
- self.assertEqual(common.limited(self.medium, req), self.medium[:10])
- self.assertEqual(common.limited(self.large, req), self.large[:10])
+ self.assertEqual(self.tiny, common.limited(self.tiny, req))
+ self.assertEqual(self.small, common.limited(self.small, req))
+ self.assertEqual(self.medium[:10], common.limited(self.medium, req))
+ self.assertEqual(self.large[:10], common.limited(self.large, req))
def test_limiter_limit_over_max(self):
"""Test limit of 3000."""
req = webob.Request.blank('/?limit=3000')
- self.assertEqual(common.limited(self.tiny, req), self.tiny)
- self.assertEqual(common.limited(self.small, req), self.small)
- self.assertEqual(common.limited(self.medium, req), self.medium)
- self.assertEqual(common.limited(self.large, req), self.large[:1000])
+ self.assertEqual(self.tiny, common.limited(self.tiny, req))
+ self.assertEqual(self.small, common.limited(self.small, req))
+ self.assertEqual(self.medium, common.limited(self.medium, req))
+ self.assertEqual(self.large[:1000], common.limited(self.large, req))
def test_limiter_limit_and_offset(self):
"""Test request with both limit and offset."""
items = range(2000)
req = webob.Request.blank('/?offset=1&limit=3')
- self.assertEqual(common.limited(items, req), items[1:4])
+ self.assertEqual(items[1:4], common.limited(items, req))
req = webob.Request.blank('/?offset=3&limit=0')
- self.assertEqual(common.limited(items, req), items[3:1003])
+ self.assertEqual(items[3:1003], common.limited(items, req))
req = webob.Request.blank('/?offset=3&limit=1500')
- self.assertEqual(common.limited(items, req), items[3:1003])
+ self.assertEqual(items[3:1003], common.limited(items, req))
req = webob.Request.blank('/?offset=3000&limit=10')
- self.assertEqual(common.limited(items, req), [])
+ self.assertEqual([], common.limited(items, req))
def test_limiter_custom_max_limit(self):
"""Test a max_limit other than 1000."""
items = range(2000)
req = webob.Request.blank('/?offset=1&limit=3')
self.assertEqual(
- common.limited(items, req, max_limit=2000), items[1:4])
+ items[1:4], common.limited(items, req, max_limit=2000))
req = webob.Request.blank('/?offset=3&limit=0')
self.assertEqual(
- common.limited(items, req, max_limit=2000), items[3:])
+ items[3:], common.limited(items, req, max_limit=2000))
req = webob.Request.blank('/?offset=3&limit=2500')
self.assertEqual(
- common.limited(items, req, max_limit=2000), items[3:])
+ items[3:], common.limited(items, req, max_limit=2000))
req = webob.Request.blank('/?offset=3000&limit=10')
- self.assertEqual(common.limited(items, req, max_limit=2000), [])
+ self.assertEqual([], common.limited(items, req, max_limit=2000))
def test_limiter_negative_limit(self):
"""Test a negative limit."""
super(Router, self).__init__(mapper)
result = webob.Request.blank('/test').get_response(Router())
- self.assertEqual(result.body, "Router result")
+ self.assertEqual("Router result", result.body)
result = webob.Request.blank('/bad').get_response(Router())
self.assertNotEqual("Router result", result.body)
def test_empty_selector(self):
sel = xmlutil.Selector()
self.assertEqual(0, len(sel.chain))
- self.assertEqual(sel(self.obj_for_test), self.obj_for_test)
+ self.assertEqual(self.obj_for_test, sel(self.obj_for_test))
def test_dict_selector(self):
sel = xmlutil.Selector('test')
self.assertEqual(1, len(sel.chain))
self.assertEqual('test', sel.chain[0])
- self.assertEqual(sel(self.obj_for_test),
- self.obj_for_test['test'])
+ self.assertEqual(self.obj_for_test['test'],
+ sel(self.obj_for_test))
def test_datum_selector(self):
sel = xmlutil.Selector('test', 'name')
def test_items_selector(self):
sel = xmlutil.Selector('test', 'attrs', xmlutil.get_items)
self.assertEqual(3, len(sel.chain))
- self.assertEqual(sel.chain[2], xmlutil.get_items)
+ self.assertEqual(xmlutil.get_items, sel.chain[2])
for key, val in sel(self.obj_for_test):
self.assertEqual(self.obj_for_test['test']['attrs'][key], val)
# Verify all the attributes are as expected
expected = dict(a=1, b=2, c=4, d=5, e=6)
for k, v in expected.items():
- self.assertEqual(elem.attrib[k].chain[0], v)
+ self.assertEqual(v, elem.attrib[k].chain[0])
def test_element_get_attributes(self):
expected = dict(a=1, b=2, c=3)
# Verify that get() retrieves the attributes
for k, v in expected.items():
- self.assertEqual(elem.get(k).chain[0], v)
+ self.assertEqual(v, elem.get(k).chain[0])
def test_element_set_attributes(self):
attrs = dict(a=None, b='foo', c=xmlutil.Selector('foo', 'bar'))
self.assertEqual('a', elem.attrib['a'].chain[0])
self.assertEqual(1, len(elem.attrib['b'].chain))
self.assertEqual('foo', elem.attrib['b'].chain[0])
- self.assertEqual(elem.attrib['c'], attrs['c'])
+ self.assertEqual(attrs['c'], elem.attrib['c'])
def test_element_attribute_keys(self):
attrs = dict(a=1, b=2, c=3, d=4)
# Create a template element with an explicit selector
elem = xmlutil.TemplateElement('test', selector=sel)
- self.assertEqual(elem.selector, sel)
+ self.assertEqual(sel, elem.selector)
def test_element_subselector_none(self):
# Create a template element with no subselector
# Create a template element with an explicit subselector
elem = xmlutil.TemplateElement('test', subselector=sel)
- self.assertEqual(elem.subselector, sel)
+ self.assertEqual(sel, elem.subselector)
def test_element_append_child(self):
# Create an element
# Verify that the child was added
self.assertEqual(1, len(elem))
- self.assertEqual(elem[0], child)
+ self.assertEqual(child, elem[0])
self.assertIn('child', elem)
- self.assertEqual(elem['child'], child)
+ self.assertEqual(child, elem['child'])
# Ensure that multiple children of the same name are rejected
child2 = xmlutil.TemplateElement('child')
elem.extend(children)
# Verify that the children were added
- self.assertEqual(len(elem), 3)
+ self.assertEqual(3, len(elem))
for idx in range(len(elem)):
self.assertEqual(children[idx], elem[idx])
self.assertIn(children[idx].tag, elem)
- self.assertEqual(elem[children[idx].tag], children[idx])
+ self.assertEqual(children[idx], elem[children[idx].tag])
# Ensure that multiple children of the same name are rejected
children2 = [xmlutil.TemplateElement('child4'),
for idx in range(len(elem)):
self.assertEqual(children[idx], elem[idx])
self.assertIn(children[idx].tag, elem)
- self.assertEqual(elem[children[idx].tag], children[idx])
+ self.assertEqual(children[idx], elem[children[idx].tag])
# Ensure that multiple children of the same name are rejected
child2 = xmlutil.TemplateElement('child2')
# Now make up a selector and try setting the text to that
sel = xmlutil.Selector()
elem.text = sel
- self.assertEqual(elem.text, sel)
+ self.assertEqual(sel, elem.text)
# Finally, try deleting the text and see what happens
del elem.text
# Check the results
for idx in range(len(obj)):
- self.assertEqual(elems[idx][0].text, obj[idx])
- self.assertEqual(elems[idx][1], obj[idx])
+ self.assertEqual(obj[idx], elems[idx][0].text)
+ self.assertEqual(obj[idx], elems[idx][1])
def test_subelement(self):
# Try the SubTemplateElement constructor
def test_wrap(self):
# These are strange methods, but they make things easier
elem = xmlutil.TemplateElement('test')
- self.assertEqual(elem.unwrap(), elem)
- self.assertEqual(elem.wrap().root, elem)
+ self.assertEqual(elem, elem.unwrap())
+ self.assertEqual(elem, elem.wrap().root)
def test_dyntag(self):
obj = ['a', 'b', 'c']
# Verify the particulars of the render
self.assertEqual(len(obj), len(elems))
for idx in range(len(obj)):
- self.assertEqual(elems[idx][0].tag, obj[idx])
+ self.assertEqual(obj[idx], elems[idx][0].tag)
class TemplateTest(test.TestCase):
# These are strange methods, but they make things easier
elem = xmlutil.TemplateElement('test')
tmpl = xmlutil.Template(elem)
- self.assertEqual(tmpl.unwrap(), elem)
- self.assertEqual(tmpl.wrap(), tmpl)
+ self.assertEqual(elem, tmpl.unwrap())
+ self.assertEqual(tmpl, tmpl.wrap())
def test__siblings(self):
# Set up a basic template
# Check that we get the right siblings
siblings = tmpl._siblings()
self.assertEqual(1, len(siblings))
- self.assertEqual(siblings[0], elem)
+ self.assertEqual(elem, siblings[0])
def test__splitTagName(self):
test_cases = [
tmpl = xmlutil.MasterTemplate(elem, 1)
# Make sure it has a root but no slaves
- self.assertEqual(tmpl.root, elem)
+ self.assertEqual(elem, tmpl.root)
self.assertEqual(0, len(tmpl.slaves))
# Try to attach an invalid slave
self.assertEqual('bar', result.nsmap['b'])
self.assertEqual(result.get('name'), obj['test']['name'])
for idx, val in enumerate(obj['test']['values']):
- self.assertEqual(result[idx].tag, 'value')
- self.assertEqual(result[idx].text, str(val))
+ self.assertEqual('value', result[idx].tag)
+ self.assertEqual(str(val), result[idx].text)
idx += 1
- self.assertEqual(result[idx].tag, 'attrs')
+ self.assertEqual('attrs', result[idx].tag)
for attr in result[idx]:
self.assertEqual('attr', attr.tag)
self.assertEqual(str(obj['test']['attrs'][attr.get('key')]),
request = webob.Request.blank("/")
response = request.get_response(self.app)
- self.assertEqual(response.status_int, 413)
+ self.assertEqual(413, response.status_int)
self.assertIn('Retry-After', response.headers)
retry_after = int(response.headers['Retry-After'])
body = jsonutils.loads(response.body)
expected = "Only 1 GET request(s) can be made to * every minute."
value = body["overLimitFault"]["details"].strip()
- self.assertEqual(value, expected)
+ self.assertEqual(expected, value)
def test_limited_request_xml(self):
"""Test a rate-limited (413) response as XML."""
request = webob.Request.blank("/")
request.accept = "application/xml"
response = request.get_response(self.app)
- self.assertEqual(response.status_int, 413)
+ self.assertEqual(413, response.status_int)
root = minidom.parseString(response.body).childNodes[0]
expected = "Only 1 GET request(s) can be made to * every minute."
details = root.getElementsByTagName("details")
- self.assertEqual(details.length, 1)
+ self.assertEqual(1, details.length)
value = details.item(0).firstChild.data.strip()
- self.assertEqual(value, expected)
+ self.assertEqual(expected, value)
class LimitTest(BaseLimitTestSuite):
assert False, e
# Make sure the number of returned limits are correct
- self.assertEqual(len(l), 4)
+ self.assertEqual(4, len(l))
# Check all the verbs...
expected = ['GET', 'PUT', 'POST', 'SAY']
- self.assertEqual([t.verb for t in l], expected)
+ self.assertEqual(expected, [t.verb for t in l])
# ...the URIs...
expected = ['*', '/foo*', '/bar*', '/derp*']
- self.assertEqual([t.uri for t in l], expected)
+ self.assertEqual(expected, [t.uri for t in l])
# ...the regexes...
expected = ['.*', '/foo.*', '/bar.*', '/derp.*']
- self.assertEqual([t.regex for t in l], expected)
+ self.assertEqual(expected, [t.regex for t in l])
# ...the values...
expected = [20, 10, 5, 1]
- self.assertEqual([t.value for t in l], expected)
+ self.assertEqual(expected, [t.value for t in l])
# ...and the units...
expected = [limits.PER_MINUTE, limits.PER_HOUR,
limits.PER_SECOND, limits.PER_DAY]
- self.assertEqual([t.unit for t in l], expected)
+ self.assertEqual(expected, [t.unit for t in l])
class LimiterTest(BaseLimitTestSuite):
def test_no_delay_GET(self):
"""no delay on a single call for a limit verb we didn"t set."""
delay = self.limiter.check_for_delay("GET", "/anything")
- self.assertEqual(delay, (None, None))
+ self.assertEqual((None, None), delay)
def test_no_delay_PUT(self):
"""no delay on a single call for a known limit."""
delay = self.limiter.check_for_delay("PUT", "/anything")
- self.assertEqual(delay, (None, None))
+ self.assertEqual((None, None), delay)
def test_delay_PUT(self):
"""test delay on 11th put request.
def test_user_limit(self):
"""Test user-specific limits."""
- self.assertEqual(self.limiter.levels['user3'], [])
- self.assertEqual(len(self.limiter.levels['user0']), 2)
+ self.assertEqual([], self.limiter.levels['user3'])
+ self.assertEqual(2, len(self.limiter.levels['user0']))
def test_multiple_users(self):
"""Tests involving multiple users."""
response = request.get_response(self.app)
if "X-Wait-Seconds" in response.headers:
- self.assertEqual(response.status_int, 403)
+ self.assertEqual(403, response.status_int)
return response.headers["X-Wait-Seconds"]
- self.assertEqual(response.status_int, 204)
+ self.assertEqual(204, response.status_int)
def test_invalid_methods(self):
"""Only POSTs should work."""
for method in ["GET", "PUT", "DELETE", "HEAD", "OPTIONS"]:
request = webob.Request.blank("/", method=method)
response = request.get_response(self.app)
- self.assertEqual(response.status_int, 405)
+ self.assertEqual(405, response.status_int)
def test_good_url(self):
delay = self._request("GET", "/something")
self.assertIsNone(delay)
delay = self._request("GET", "/delayed")
- self.assertEqual(delay, '60.00')
+ self.assertEqual('60.00', delay)
def test_response_to_delays_usernames(self):
delay = self._request("GET", "/delayed", "user1")
self.assertIsNone(delay)
delay = self._request("GET", "/delayed", "user1")
- self.assertEqual(delay, '60.00')
+ self.assertEqual('60.00', delay)
delay = self._request("GET", "/delayed", "user2")
- self.assertEqual(delay, '60.00')
+ self.assertEqual('60.00', delay)
class FakeHttplibSocket(object):
def test_200(self):
"""Successful request test."""
delay = self.proxy.check_for_delay("GET", "/anything")
- self.assertEqual(delay, (None, None))
+ self.assertEqual((None, None), delay)
def test_403(self):
"""Forbidden request test."""
delay = self.proxy.check_for_delay("GET", "/delayed")
- self.assertEqual(delay, (None, None))
+ self.assertEqual((None, None), delay)
delay, error = self.proxy.check_for_delay("GET", "/delayed")
error = error.strip()
expected = ("60.00", "403 Forbidden\n\nOnly 1 GET request(s) can be "
"made to /delayed every minute.")
- self.assertEqual((delay, error), expected)
+ self.assertEqual(expected, (delay, error))
class LimitsViewBuilderTest(test.TestCase):
# verify absolute limits
absolutes = root.xpath('ns:absolute/ns:limit', namespaces=NS)
- self.assertEqual(len(absolutes), 4)
+ self.assertEqual(4, len(absolutes))
for limit in absolutes:
name = limit.get('name')
value = limit.get('value')
- self.assertEqual(value, str(fixture['limits']['absolute'][name]))
+ self.assertEqual(str(fixture['limits']['absolute'][name]), value)
# verify rate limits
rates = root.xpath('ns:rates/ns:rate', namespaces=NS)
- self.assertEqual(len(rates), 2)
+ self.assertEqual(2, len(rates))
for i, rate in enumerate(rates):
for key in ['uri', 'regex']:
- self.assertEqual(rate.get(key),
- str(fixture['limits']['rate'][i][key]))
+ self.assertEqual(str(fixture['limits']['rate'][i][key]),
+ rate.get(key))
rate_limits = rate.xpath('ns:limit', namespaces=NS)
- self.assertEqual(len(rate_limits), 1)
+ self.assertEqual(1, len(rate_limits))
for j, limit in enumerate(rate_limits):
for key in ['verb', 'value', 'remaining', 'unit',
'next-available']:
self.assertEqual(
- limit.get(key),
- str(fixture['limits']['rate'][i]['limit'][j][key]))
+ str(fixture['limits']['rate'][i]['limit'][j][key]),
+ limit.get(key))
def test_index_no_limits(self):
serializer = limits.LimitsTemplate()
# verify absolute limits
absolutes = root.xpath('ns:absolute/ns:limit', namespaces=NS)
- self.assertEqual(len(absolutes), 0)
+ self.assertEqual(0, len(absolutes))
# verify rate limits
rates = root.xpath('ns:rates/ns:rate', namespaces=NS)
- self.assertEqual(len(rates), 0)
+ self.assertEqual(0, len(rates))
resp_dict = self.controller.create(req, body)
self.assertIn('snapshot', resp_dict)
- self.assertEqual(resp_dict['snapshot']['display_name'],
- snapshot['display_name'])
- self.assertEqual(resp_dict['snapshot']['display_description'],
- snapshot['display_description'])
+ self.assertEqual(snapshot['display_name'],
+ resp_dict['snapshot']['display_name'])
+ self.assertEqual(snapshot['display_description'],
+ resp_dict['snapshot']['display_description'])
def test_snapshot_create_force(self):
self.stubs.Set(volume.api.API,
resp_dict = self.controller.create(req, body)
self.assertIn('snapshot', resp_dict)
- self.assertEqual(resp_dict['snapshot']['display_name'],
- snapshot['display_name'])
- self.assertEqual(resp_dict['snapshot']['display_description'],
- snapshot['display_description'])
+ self.assertEqual(snapshot['display_name'],
+ resp_dict['snapshot']['display_name'])
+ self.assertEqual(snapshot['display_description'],
+ resp_dict['snapshot']['display_description'])
snapshot = {"volume_id": "12",
"force": "**&&^^%%$$##@@",
snapshot_id = UUID
req = fakes.HTTPRequest.blank('/v1/snapshots/%s' % snapshot_id)
resp = self.controller.delete(req, snapshot_id)
- self.assertEqual(resp.status_int, 202)
+ self.assertEqual(202, resp.status_int)
def test_snapshot_delete_invalid_id(self):
self.stubs.Set(volume.api.API, "delete_snapshot", stub_snapshot_delete)
resp_dict = self.controller.show(req, UUID)
self.assertIn('snapshot', resp_dict)
- self.assertEqual(resp_dict['snapshot']['id'], UUID)
+ self.assertEqual(UUID, resp_dict['snapshot']['id'])
def test_snapshot_show_invalid_id(self):
snapshot_id = INVALID_UUID
self.assertIn('snapshots', resp_dict)
resp_snapshots = resp_dict['snapshots']
- self.assertEqual(len(resp_snapshots), 1)
+ self.assertEqual(1, len(resp_snapshots))
resp_snapshot = resp_snapshots.pop()
- self.assertEqual(resp_snapshot['id'], UUID)
+ self.assertEqual(UUID, resp_snapshot['id'])
@mock.patch('cinder.db.snapshot_metadata_get', return_value=dict())
def test_admin_list_snapshots_limited_to_project(self,
class SnapshotSerializerTest(test.TestCase):
def _verify_snapshot(self, snap, tree):
- self.assertEqual(tree.tag, 'snapshot')
+ self.assertEqual('snapshot', tree.tag)
for attr in ('id', 'status', 'size', 'created_at',
'display_name', 'display_description', 'volume_id'):
expected_names = ['vol_type_1', 'vol_type_2', 'vol_type_3']
actual_names = map(lambda e: e['name'], res_dict['volume_types'])
- self.assertEqual(set(actual_names), set(expected_names))
+ self.assertEqual(set(expected_names), set(actual_names))
for entry in res_dict['volume_types']:
self.assertEqual('value1', entry['extra_specs']['key1'])
self.assertIn(child.tag, seen)
self.assertEqual(vtype['extra_specs'][child.tag], child.text)
seen.remove(child.tag)
- self.assertEqual(len(seen), 0)
+ self.assertEqual(0, len(seen))
def test_index_serializer(self):
serializer = types.VolumeTypesTemplate()
1, 1, 1),
'size': 100,
'encrypted': False}}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_create_with_type(self):
vol_type = CONF.default_volume_type
body.update(dict(volume=vol))
res_dict = self.controller.create(req, body)
self.assertIn('id', res_dict['volume'])
- self.assertEqual(len(res_dict), 1)
- self.assertEqual(res_dict['volume']['volume_type'],
- db_vol_type['name'])
+ self.assertEqual(1, len(res_dict))
+ self.assertEqual(db_vol_type['name'],
+ res_dict['volume']['volume_type'])
# Use correct volume type id
vol.update(dict(volume_type=db_vol_type['id']))
body.update(dict(volume=vol))
res_dict = self.controller.create(req, body)
self.assertIn('id', res_dict['volume'])
- self.assertEqual(len(res_dict), 1)
- self.assertEqual(res_dict['volume']['volume_type'],
- db_vol_type['name'])
+ self.assertEqual(1, len(res_dict))
+ self.assertEqual(db_vol_type['name'],
+ res_dict['volume']['volume_type'])
def test_volume_creation_fails_with_bad_size(self):
vol = {"size": '',
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
res_dict = self.controller.create(req, body)
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_create_with_image_id_is_integer(self):
self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create)
}
body = {"volume": updates}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
- self.assertEqual(len(self.notifier.notifications), 0)
+ self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller.update(req, '1', body)
expected = {'volume': {
'status': 'fakestatus',
'id': '1',
'created_at': datetime.datetime(1900, 1, 1, 1, 1, 1),
'size': 1}}
- self.assertEqual(res_dict, expected)
- self.assertEqual(len(self.notifier.notifications), 2)
+ self.assertEqual(expected, res_dict)
+ self.assertEqual(2, len(self.notifier.notifications))
def test_volume_update_metadata(self):
self.stubs.Set(db, 'volume_get', stubs.stub_volume_get_db)
}
body = {"volume": updates}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
- self.assertEqual(len(self.notifier.notifications), 0)
+ self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller.update(req, '1', body)
expected = {'volume': {
'status': 'fakestatus',
'created_at': datetime.datetime(1900, 1, 1, 1, 1, 1),
'size': 1
}}
- self.assertEqual(res_dict, expected)
- self.assertEqual(len(self.notifier.notifications), 2)
+ self.assertEqual(expected, res_dict)
+ self.assertEqual(2, len(self.notifier.notifications))
def test_volume_update_with_admin_metadata(self):
self.stubs.Set(volume_api.API, "update", stubs.stub_volume_update)
}
body = {"volume": updates}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
- self.assertEqual(len(self.notifier.notifications), 0)
+ self.assertEqual(0, len(self.notifier.notifications))
admin_ctx = context.RequestContext('admin', 'fakeproject', True)
req.environ['cinder.context'] = admin_ctx
res_dict = self.controller.update(req, '1', body)
'id': '1',
'created_at': datetime.datetime(1900, 1, 1, 1, 1, 1),
'size': 1}}
- self.assertEqual(res_dict, expected)
- self.assertEqual(len(self.notifier.notifications), 2)
+ self.assertEqual(expected, res_dict)
+ self.assertEqual(2, len(self.notifier.notifications))
def test_update_empty_body(self):
body = {}
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}]}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
# Finally test that we cached the returned volumes
self.assertEqual(1, len(req.cached_resource()))
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}]}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_list_detail(self):
self.stubs.Set(db, 'volume_get', stubs.stub_volume_get_db)
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}]}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
# Finally test that we cached the returned volumes
self.assertEqual(1, len(req.cached_resource()))
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}]}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_show(self):
self.stubs.Set(db, 'volume_get', stubs.stub_volume_get_db)
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
# Finally test that we cached the returned volume
self.assertIsNotNone(req.cached_resource_by_id('1'))
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_show_bootable(self):
def stub_volume_get(self, context, volume_id, **kwargs):
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_show_no_volume(self):
self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound)
use_admin_context=is_admin)
res_dict = self.controller.index(req)
volumes = res_dict['volumes']
- self.assertEqual(len(volumes), 1)
- self.assertEqual(volumes[0]['id'], 2)
+ self.assertEqual(1, len(volumes))
+ self.assertEqual(2, volumes[0]['id'])
# admin case
volume_detail_limit_offset(is_admin=True)
'created_at': datetime.datetime(1900, 1, 1,
1, 1, 1),
'size': 1}}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_show_with_encrypted_volume(self):
def stub_volume_get(self, context, volume_id, **kwargs):
req = fakes.HTTPRequest.blank('/v1/volumes/1')
res_dict = self.controller.show(req, 1)
- self.assertEqual(res_dict['volume']['encrypted'], True)
+ self.assertEqual(True, res_dict['volume']['encrypted'])
def test_volume_show_with_unencrypted_volume(self):
def stub_volume_get(self, context, volume_id, **kwargs):
req = fakes.HTTPRequest.blank('/v1/volumes/1')
res_dict = self.controller.show(req, 1)
- self.assertEqual(res_dict['volume']['encrypted'], False)
+ self.assertEqual(False, res_dict['volume']['encrypted'])
def test_volume_delete(self):
self.stubs.Set(db, 'volume_get', stubs.stub_volume_get_db)
req = fakes.HTTPRequest.blank('/v1/volumes/1')
resp = self.controller.delete(req, 1)
- self.assertEqual(resp.status_int, 202)
+ self.assertEqual(202, resp.status_int)
def test_volume_delete_no_volume(self):
self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound)
self.assertEqual(str(attach[attr]), tree.get(attr))
def _verify_volume(self, vol, tree):
- self.assertEqual(tree.tag, NS + 'volume')
+ self.assertEqual(NS + 'volume', tree.tag)
for attr in ('id', 'status', 'size', 'availability_zone', 'created_at',
'display_name', 'display_description', 'volume_type',
size="1"></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {"volume": {"size": "1", }, }
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_display_name(self):
self_request = """
"display_name": "Volume-xml",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_display_description(self):
self_request = """
"display_description": "description",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_volume_type(self):
self_request = """
"volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_availability_zone(self):
self_request = """
"availability_zone": "us-east1",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_metadata(self):
self_request = """
},
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_full_volume(self):
self_request = """
},
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_imageref(self):
self_request = """
def test_user_limit(self):
"""Test user-specific limits."""
- self.assertEqual(self.limiter.levels['user3'], [])
+ self.assertEqual([], self.limiter.levels['user3'])
self.assertEqual(2, len(self.limiter.levels['user0']))
def test_multiple_users(self):
req = fakes.HTTPRequest.blank('/v2/volumes?marker=1')
res_dict = self.controller.index(req)
volumes = res_dict['volumes']
- self.assertEqual(len(volumes), 2)
+ self.assertEqual(2, len(volumes))
self.assertEqual(1, volumes[0]['id'])
self.assertEqual(2, volumes[1]['id'])
req = fakes.HTTPRequest.blank('/v2/volumes?limit=0')
res_dict = self.controller.index(req)
expected = {'volumes': []}
- self.assertEqual(res_dict, expected)
+ self.assertEqual(expected, res_dict)
def test_volume_default_limit(self):
self.stubs.Set(volume_api.API, 'get', stubs.stub_volume_get)
def _verify_links(links, url_key):
"""Verify next link and url."""
- self.assertEqual(links[0]['rel'], 'next')
+ self.assertEqual('next', links[0]['rel'])
href_parts = urllib.parse.urlparse(links[0]['href'])
self.assertEqual('/v2/fakeproject/%s' % key, href_parts.path)
req = fakes.HTTPRequest.blank('/v2/%s?all_tenants=1' % key,
use_admin_context=True)
res_dict = fn(req)
- self.assertEqual(len(res_dict['volumes']), 100)
+ self.assertEqual(100, len(res_dict['volumes']))
self.assertFalse('volumes_links' in res_dict)
# Number of volumes more than the max, include next link
req = fakes.HTTPRequest.blank('/v2/%s?all_tenants=1' % key,
use_admin_context=True)
res_dict = fn(req)
- self.assertEqual(len(res_dict['volumes']), CONF.osapi_max_limit)
+ self.assertEqual(CONF.osapi_max_limit, len(res_dict['volumes']))
volumes_links = res_dict['volumes_links']
_verify_links(volumes_links, key)
# Pass a limit that is greater than the max and the total number of
% (key, CONF.osapi_max_limit * 2),
use_admin_context=True)
res_dict = fn(req)
- self.assertEqual(len(res_dict['volumes']), CONF.osapi_max_limit)
+ self.assertEqual(CONF.osapi_max_limit, len(res_dict['volumes']))
volumes_links = res_dict['volumes_links']
_verify_links(volumes_links, key)
sort_keys=None, sort_dirs=None,
filters=None,
viewable_admin_meta=False):
- self.assertEqual(filters['no_migration_targets'], True)
+ self.assertEqual(True, filters['no_migration_targets'])
self.assertFalse('all_tenants' in filters)
return [stubs.stub_volume(1, display_name='vol1')]
for params in ['', '?all_tenants=1']:
req = fakes.HTTPRequest.blank('/v2/volumes%s' % params)
resp = self.controller.index(req)
- self.assertEqual(len(resp['volumes']), 1)
- self.assertEqual(resp['volumes'][0]['name'], 'vol1')
+ self.assertEqual(1, len(resp['volumes']))
+ self.assertEqual('vol1', resp['volumes'][0]['name'])
# Admin, all_tenants is not set, project function should be called
# without no_migration_status
req = fakes.HTTPRequest.blank('/v2/volumes', use_admin_context=True)
resp = self.controller.index(req)
- self.assertEqual(len(resp['volumes']), 1)
- self.assertEqual(resp['volumes'][0]['name'], 'vol2')
+ self.assertEqual(1, len(resp['volumes']))
+ self.assertEqual('vol2', resp['volumes'][0]['name'])
# Admin, all_tenants is set, get_all function should be called
# without no_migration_status
req = fakes.HTTPRequest.blank('/v2/volumes?all_tenants=1',
use_admin_context=True)
resp = self.controller.index(req)
- self.assertEqual(len(resp['volumes']), 1)
- self.assertEqual(resp['volumes'][0]['name'], 'vol3')
+ self.assertEqual(1, len(resp['volumes']))
+ self.assertEqual('vol3', resp['volumes'][0]['name'])
def test_volume_show(self):
self.stubs.Set(volume_api.API, 'get', stubs.stub_volume_get)
req = fakes.HTTPRequest.blank('/v2/volumes/1')
res_dict = self.controller.show(req, 1)
- self.assertEqual(res_dict['volume']['encrypted'], True)
+ self.assertEqual(True, res_dict['volume']['encrypted'])
def test_volume_show_with_unencrypted_volume(self):
def stub_volume_get(self, context, volume_id, **kwargs):
req = fakes.HTTPRequest.blank('/v2/volumes/1')
res_dict = self.controller.show(req, 1)
- self.assertEqual(res_dict['volume']['encrypted'], False)
+ self.assertEqual(False, res_dict['volume']['encrypted'])
def test_volume_delete(self):
self.stubs.Set(volume_api.API, 'get', stubs.stub_volume_get)
req = fakes.HTTPRequest.blank('/v2/volumes/1')
resp = self.controller.delete(req, 1)
- self.assertEqual(resp.status_int, 202)
+ self.assertEqual(202, resp.status_int)
def test_volume_delete_attached(self):
def stub_volume_attached(self, context, volume, force=False):
self.assertEqual(str(attach[attr]), tree.get(attr))
def _verify_volume(self, vol, tree):
- self.assertEqual(tree.tag, NS + 'volume')
+ self.assertEqual(NS + 'volume', tree.tag)
for attr in ('id', 'status', 'size', 'availability_zone', 'created_at',
'name', 'description', 'volume_type', 'bootable',
"size": "1",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_name(self):
self_request = """
"name": "Volume-xml",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_description(self):
self_request = """
"description": "description",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_volume_type(self):
self_request = """
"volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_availability_zone(self):
self_request = """
"availability_zone": "us-east1",
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_metadata(self):
self_request = """
},
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_full_volume(self):
self_request = """
},
},
}
- self.assertEqual(request['body'], expected)
+ self.assertEqual(expected, request['body'])
def test_imageref(self):
self_request = """
return (data, "")
def test_create_lv_snapshot(self):
- self.assertEqual(self.vg.create_lv_snapshot('snapshot-1', 'fake-1'),
- None)
+ self.assertEqual(None,
+ self.vg.create_lv_snapshot('snapshot-1', 'fake-1'))
self.mox.StubOutWithMock(self.vg, 'get_volume')
self.vg.get_volume('fake-non-existent').AndReturn(None)
try:
self.vg.create_lv_snapshot('snapshot-1', 'fake-non-existent')
except exception.VolumeDeviceNotFound as e:
- self.assertEqual(e.kwargs['device'], 'fake-non-existent')
+ self.assertEqual('fake-non-existent', e.kwargs['device'])
else:
self.fail("Exception not raised")
def test_vg_exists(self):
- self.assertEqual(self.vg._vg_exists(), True)
+ self.assertEqual(True, self.vg._vg_exists())
def test_get_vg_uuid(self):
- self.assertEqual(self.vg._get_vg_uuid()[0],
- 'kVxztV-dKpG-Rz7E-xtKY-jeju-QsYU-SLG6Z1')
+ self.assertEqual('kVxztV-dKpG-Rz7E-xtKY-jeju-QsYU-SLG6Z1',
+ self.vg._get_vg_uuid()[0])
def test_get_all_volumes(self):
out = self.vg.get_volumes()
- self.assertEqual(out[0]['name'], 'fake-1')
- self.assertEqual(out[0]['size'], '1.00g')
- self.assertEqual(out[0]['vg'], 'fake-vg')
+ self.assertEqual('fake-1', out[0]['name'])
+ self.assertEqual('1.00g', out[0]['size'])
+ self.assertEqual('fake-vg', out[0]['vg'])
def test_get_volume(self):
- self.assertEqual(self.vg.get_volume('fake-1')['name'], 'fake-1')
+ self.assertEqual('fake-1', self.vg.get_volume('fake-1')['name'])
def test_get_volume_none(self):
- self.assertEqual(self.vg.get_volume('fake-unknown'), None)
+ self.assertEqual(None, self.vg.get_volume('fake-unknown'))
def test_get_lv_info_notfound(self):
# lv-nothere will raise lvm < 2.102.112 exception
def test_get_all_physical_volumes(self):
# Filtered VG version
pvs = self.vg.get_all_physical_volumes('sudo', 'fake-vg')
- self.assertEqual(len(pvs), 3)
+ self.assertEqual(3, len(pvs))
# Non-Filtered, all VG's
pvs = self.vg.get_all_physical_volumes('sudo')
- self.assertEqual(len(pvs), 4)
+ self.assertEqual(4, len(pvs))
def test_get_physical_volumes(self):
pvs = self.vg.get_physical_volumes()
- self.assertEqual(len(pvs), 3)
+ self.assertEqual(3, len(pvs))
def test_get_volume_groups(self):
- self.assertEqual(len(self.vg.get_all_volume_groups('sudo')), 3)
- self.assertEqual(len(self.vg.get_all_volume_groups('sudo',
- 'fake-vg')), 1)
+ self.assertEqual(3, len(self.vg.get_all_volume_groups('sudo')))
+ self.assertEqual(1,
+ len(self.vg.get_all_volume_groups('sudo', 'fake-vg')))
def test_thin_support(self):
# lvm.supports_thin() is a static method and doesn't
self.vg.create_thin_pool(pool_name, "1G")
self.vg.create_volume("test", "1G", lv_type='thin')
- self.assertEqual(self.vg.vg_thin_pool, pool_name)
+ self.assertEqual(pool_name, self.vg.vg_thin_pool)
def test_lv_has_snapshot(self):
self.assertTrue(self.vg.lv_has_snapshot('fake-vg'))
self.mox.VerifyAll()
def test_get_mirrored_available_capacity(self):
- self.assertEqual(self.vg.vg_mirror_free_space(1), 2.0)
+ self.assertEqual(2.0, self.vg.vg_mirror_free_space(1))
def test_lv_extend(self):
self.vg.deactivate_lv = mock.MagicMock()
connector))
def test_iscsi_protocol(self):
- self.assertEqual(self.target.iscsi_protocol, 'iser')
+ self.assertEqual('iser', self.target.iscsi_protocol)
class TestIserTgtDriver(tf.TargetDriverFixture):
configuration=self.configuration)
def test_iscsi_protocol(self):
- self.assertEqual(self.target.iscsi_protocol, 'iser')
+ self.assertEqual('iser', self.target.iscsi_protocol)
@mock.patch.object(tgt.TgtAdm, '_get_iscsi_properties')
def test_initialize_connection(self, mock_get_iscsi):
volume_get=lambda x, y: {'provider_auth': 'IncomingUser foo bar'})
def test_iscsi_protocol(self):
- self.assertEqual(self.target.iscsi_protocol, 'iser')
+ self.assertEqual('iser', self.target.iscsi_protocol)
@mock.patch('cinder.utils.execute')
@mock.patch.object(lio.LioAdm, '_get_iscsi_properties')
mock_get_iscsi.return_value = {}
ret = self.target.initialize_connection(self.testvol, connector)
driver_volume_type = ret['driver_volume_type']
- self.assertEqual(driver_volume_type, 'iser')
+ self.assertEqual('iser', driver_volume_type)
self.assertFalse(mpersist_cfg.called)
def test_iscsi_protocol(self):
- self.assertEqual(self.target.iscsi_protocol, 'iscsi')
+ self.assertEqual('iscsi', self.target.iscsi_protocol)
@mock.patch.object(lio.LioAdm, '_get_target_and_lun', return_value=(1, 2))
@mock.patch.object(lio.LioAdm, 'create_iscsi_target', return_value=3)
return getattr(self, value, default)
def test_iscsi_protocol(self):
- self.assertEqual(self.target.iscsi_protocol, 'iscsi')
+ self.assertEqual('iscsi', self.target.iscsi_protocol)
def test_get_target(self):
with mock.patch('cinder.utils.execute',
def test_unquote_header_value_without_quotes(self):
arg = 'TestString'
result = urlmap.unquote_header_value(arg)
- self.assertEqual(result, arg)
+ self.assertEqual(arg, result)
def test_unquote_header_value_with_quotes(self):
result = urlmap.unquote_header_value('"TestString"')
- self.assertEqual(result, 'TestString')
+ self.assertEqual('TestString', result)
def test_parse_list_header(self):
arg = 'token, "quoted value"'
result = urlmap.parse_list_header(arg)
- self.assertEqual(result, ['token', 'quoted value'])
+ self.assertEqual(['token', 'quoted value'], result)
def test_parse_options_header(self):
result = urlmap.parse_options_header('Content-Type: text/html;'
' mimetype=text/html')
- self.assertEqual(result, ('Content-Type:', {'mimetype': 'text/html'}))
+ self.assertEqual(('Content-Type:', {'mimetype': 'text/html'}), result)
def test_parse_options_header_without_value(self):
result = urlmap.parse_options_header(None)
- self.assertEqual(result, ('', {}))
+ self.assertEqual(('', {}), result)
class TestAccept(test.TestCase):
def test_best_match_ValueError(self):
arg = 'text/html; q=some_invalud_value'
accept = urlmap.Accept(arg)
- self.assertEqual(accept.best_match(['text/html']), (None, {}))
+ self.assertEqual((None, {}), accept.best_match(['text/html']))
def test_best_match(self):
arg = '*/*; q=0.7, application/json; q=0.7, text/html; q=-0.8'
accept = urlmap.Accept(arg)
- self.assertEqual(accept.best_match(['application/json',
- 'application/xml', 'text/html']),
- ('application/json', {'q': '0.7'}))
+ self.assertEqual(('application/json', {'q': '0.7'}),
+ accept.best_match(['application/json',
+ 'application/xml', 'text/html']))
def test_match_mask_one_asterisk(self):
arg = 'text/*; q=0.7'
accept = urlmap.Accept(arg)
- self.assertEqual(accept.best_match(['text/html']),
- ('text/html', {'q': '0.7'}))
+ self.assertEqual(('text/html', {'q': '0.7'}),
+ accept.best_match(['text/html']))
def test_match_mask_two_asterisk(self):
arg = '*/*; q=0.7'
accept = urlmap.Accept(arg)
- self.assertEqual(accept.best_match(['text/html']),
- ('text/html', {'q': '0.7'}))
+ self.assertEqual(('text/html', {'q': '0.7'}),
+ accept.best_match(['text/html']))
def test_match_mask_no_asterisk(self):
arg = 'application/json; q=0.7'
accept = urlmap.Accept(arg)
- self.assertEqual(accept.best_match(['text/html']), (None, {}))
+ self.assertEqual((None, {}), accept.best_match(['text/html']))
def test_content_type_params(self):
arg = "application/xml; q=0.1, application/json; q=0.2," \
" text/html; q=0.3"
accept = urlmap.Accept(arg)
- self.assertEqual(accept.content_type_params('application/json'),
- {'q': '0.2'})
+ self.assertEqual({'q': '0.2'},
+ accept.content_type_params('application/json'))
def test_content_type_params_wrong_content_type(self):
arg = 'application/xml; q=0.1, text/html; q=0.1'
accept = urlmap.Accept(arg)
- self.assertEqual(accept.content_type_params('application/json'), {})
+ self.assertEqual({}, accept.content_type_params('application/json'))
class TestUrlMapFactory(test.TestCase):
self.mox.ReplayAll()
expected_urlmap = urlmap.URLMap(not_found_app='app_local_loader')
expected_urlmap['http://foobar.com:20'] = 'some_app_loader'
- self.assertEqual(urlmap.urlmap_factory(self.loader, self.global_conf,
- **local_conf), expected_urlmap)
+ self.assertEqual(expected_urlmap,
+ urlmap.urlmap_factory(self.loader, self.global_conf,
+ **local_conf))
def test_not_found_app_not_in_local_conf(self):
local_conf = {'domain foobar.com port 20 /': 'some_app_local'}
expected_urlmap = urlmap.URLMap(not_found_app='app_global_loader')
expected_urlmap['http://foobar.com:20'] = 'some_app_returned'\
'_by_loader'
- self.assertEqual(urlmap.urlmap_factory(self.loader, self.global_conf,
- **local_conf), expected_urlmap)
+ self.assertEqual(expected_urlmap,
+ urlmap.urlmap_factory(self.loader, self.global_conf,
+ **local_conf))
def test_not_found_app_is_none(self):
local_conf = {'not_found_app': None,
expected_urlmap = urlmap.URLMap(not_found_app=None)
expected_urlmap['http://foobar.com:20'] = 'some_app_returned'\
'_by_loader'
- self.assertEqual(urlmap.urlmap_factory(self.loader, self.global_conf,
- **local_conf), expected_urlmap)
+ self.assertEqual(expected_urlmap,
+ urlmap.urlmap_factory(self.loader, self.global_conf,
+ **local_conf))
class TestURLMap(test.TestCase):
def test_match_with_applications(self):
self.urlmap[('http://10.20.30.40:50', '/path/somepath')] = 'app'
- self.assertEqual(self.urlmap._match('20.30.40.50', '20',
- 'path/somepath'), (None, None))
+ self.assertEqual((None, None),
+ self.urlmap._match('20.30.40.50', '20',
+ 'path/somepath'))
def test_match_without_applications(self):
- self.assertEqual(self.urlmap._match('host', 20, 'app_url/somepath'),
- (None, None))
+ self.assertEqual((None, None),
+ self.urlmap._match('host', 20, 'app_url/somepath'))
def test_match_path_info_equals_app_url(self):
self.urlmap[('http://20.30.40.50:60', '/app_url/somepath')] = 'app'
- self.assertEqual(self.urlmap._match('http://20.30.40.50', '60',
- '/app_url/somepath'),
- ('app', '/app_url/somepath'))
+ self.assertEqual(('app', '/app_url/somepath'),
+ self.urlmap._match('http://20.30.40.50', '60',
+ '/app_url/somepath'))
def test_match_path_info_equals_app_url_many_app(self):
self.urlmap[('http://20.30.40.50:60', '/path')] = 'app1'
self.urlmap[('http://20.30.40.50:60', '/path/somepath')] = 'app2'
self.urlmap[('http://20.30.40.50:60', '/path/somepath/elsepath')] = \
'app3'
- self.assertEqual(self.urlmap._match('http://20.30.40.50', '60',
- '/path/somepath/elsepath'),
- ('app3', '/path/somepath/elsepath'))
+ self.assertEqual(('app3', '/path/somepath/elsepath'),
+ self.urlmap._match('http://20.30.40.50', '60',
+ '/path/somepath/elsepath'))
def test_set_script_name(self):
app = self.mox.CreateMockAnything()
app.__call__(self.environ, start_response).AndReturn('value')
self.mox.ReplayAll()
wrap = self.urlmap._set_script_name(app, '/app_url')
- self.assertEqual(wrap(self.input_environ, start_response), 'value')
+ self.assertEqual('value', wrap(self.input_environ, start_response))
def test_munge_path(self):
app = self.mox.CreateMockAnything()
self.mox.ReplayAll()
wrap = self.urlmap._munge_path(app, '/app_url/resource.xml',
'/app_url')
- self.assertEqual(wrap(self.input_environ, start_response), 'value')
+ self.assertEqual('value', wrap(self.input_environ, start_response))
def test_content_type_strategy_without_version(self):
- self.assertEqual(self.urlmap._content_type_strategy('host', 20,
- self.environ),
- None)
+ self.assertEqual(None,
+ self.urlmap._content_type_strategy('host', 20,
+ self.environ))
def test_content_type_strategy_with_version(self):
environ = {'HTTP_ACCEPT': "application/vnd.openstack.melange+xml;"
self.mox.StubOutWithMock(self.urlmap, '_set_script_name')
self.urlmap._set_script_name('app', '/v2.0').AndReturn('value')
self.mox.ReplayAll()
- self.assertEqual(self.urlmap._content_type_strategy(
- 'http://10.20.30.40', '50', environ), 'value')
+ self.assertEqual('value',
+ self.urlmap._content_type_strategy(
+ 'http://10.20.30.40', '50', environ))
def test_path_strategy_wrong_path_info(self):
- self.assertEqual(self.urlmap._path_strategy('http://10.20.30.40', '50',
- '/resource'),
- (None, None, None))
+ self.assertEqual((None, None, None),
+ self.urlmap._path_strategy('http://10.20.30.40', '50',
+ '/resource'))
def test_path_strategy_mime_type_only(self):
- self.assertEqual(self.urlmap._path_strategy('http://10.20.30.40', '50',
- '/resource.xml'),
- ('application/xml', None, None))
+ self.assertEqual(('application/xml', None, None),
+ self.urlmap._path_strategy('http://10.20.30.40', '50',
+ '/resource.xml'))
def test_path_strategy(self):
self.urlmap[('http://10.20.30.40:50', '/path/elsepath/')] = 'app'
self.urlmap._munge_path('app', '/path/elsepath/resource.xml',
'/path/elsepath').AndReturn('value')
self.mox.ReplayAll()
- self.assertEqual(self.urlmap._path_strategy(
- 'http://10.20.30.40', '50', '/path/elsepath/resource.xml'),
- ('application/xml', 'value', '/path/elsepath'))
+ self.assertEqual(
+ ('application/xml', 'value', '/path/elsepath'),
+ self.urlmap._path_strategy('http://10.20.30.40', '50',
+ '/path/elsepath/resource.xml'))
def test_path_strategy_wrong_mime_type(self):
self.urlmap[('http://10.20.30.40:50', '/path/elsepath/')] = 'app'
self.urlmap._munge_path('app', '/path/elsepath/resource.abc',
'/path/elsepath').AndReturn('value')
self.mox.ReplayAll()
- self.assertEqual(self.urlmap._path_strategy(
- 'http://10.20.30.40', '50', '/path/elsepath/resource.abc'),
- (None, 'value', '/path/elsepath'))
+ self.assertEqual(
+ (None, 'value', '/path/elsepath'),
+ self.urlmap._path_strategy('http://10.20.30.40', '50',
+ '/path/elsepath/resource.abc'))
def test_accept_strategy_version_not_in_params(self):
environ = {'HTTP_ACCEPT': "application/xml; q=0.1, application/json; "
"q=0.2", 'REQUEST_METHOD': "GET",
'PATH_INFO': "/resource.xml",
'CONTENT_TYPE': 'application/xml; version=2.0'}
- self.assertEqual(self.urlmap._accept_strategy(
- 'http://10.20.30.40', '50', environ, ['application/xml']),
- ('application/xml', None))
+ self.assertEqual(('application/xml', None),
+ self.urlmap._accept_strategy('http://10.20.30.40',
+ '50',
+ environ,
+ ['application/xml']))
def test_accept_strategy_version(self):
environ = {'HTTP_ACCEPT': "application/xml; q=0.1; version=1.0,"
self.mox.StubOutWithMock(self.urlmap, '_set_script_name')
self.urlmap._set_script_name('app', '/v1.0').AndReturn('value')
self.mox.ReplayAll()
- self.assertEqual(self.urlmap._accept_strategy(
- 'http://10.20.30.40', '50', environ, ['application/xml']),
- ('application/xml', 'value'))
+ self.assertEqual(('application/xml', 'value'),
+ self.urlmap._accept_strategy('http://10.20.30.40',
+ '50',
+ environ,
+ ['application/xml']))
self.backup_mgr.init_host()
vol1 = db.volume_get(self.ctxt, vol1_id)
- self.assertEqual(vol1['status'], 'available')
+ self.assertEqual('available', vol1['status'])
vol2 = db.volume_get(self.ctxt, vol2_id)
- self.assertEqual(vol2['status'], 'error_restoring')
+ self.assertEqual('error_restoring', vol2['status'])
backup1 = db.backup_get(self.ctxt, backup1.id)
- self.assertEqual(backup1['status'], 'error')
+ self.assertEqual('error', backup1['status'])
backup2 = db.backup_get(self.ctxt, backup2.id)
- self.assertEqual(backup2['status'], 'available')
+ self.assertEqual('available', backup2['status'])
self.assertRaises(exception.BackupNotFound,
db.backup_get,
self.ctxt,
self.assertEqual('backing-up', vol['previous_status'])
backup = db.backup_get(self.ctxt, backup.id)
self.assertEqual('available', backup['status'])
- self.assertEqual(backup['size'], vol_size)
+ self.assertEqual(vol_size, backup['size'])
self.assertTrue(_mock_volume_backup.called)
@mock.patch('cinder.volume.utils.notify_about_backup_usage')
backup,
vol_id)
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'available')
+ self.assertEqual('available', backup['status'])
def test_restore_backup_with_bad_backup_status(self):
"""Test error handling.
backup,
vol_id)
vol = db.volume_get(self.ctxt, vol_id)
- self.assertEqual(vol['status'], 'error')
+ self.assertEqual('error', vol['status'])
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
@mock.patch('%s.%s' % (CONF.volume_driver, 'restore_backup'))
def test_restore_backup_with_driver_error(self, _mock_volume_restore):
backup,
vol_id)
vol = db.volume_get(self.ctxt, vol_id)
- self.assertEqual(vol['status'], 'error_restoring')
+ self.assertEqual('error_restoring', vol['status'])
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'available')
+ self.assertEqual('available', backup['status'])
self.assertTrue(_mock_volume_restore.called)
def test_restore_backup_with_bad_service(self):
backup,
vol_id)
vol = db.volume_get(self.ctxt, vol_id)
- self.assertEqual(vol['status'], 'error')
+ self.assertEqual('error', vol['status'])
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'available')
+ self.assertEqual('available', backup['status'])
@mock.patch('%s.%s' % (CONF.volume_driver, 'restore_backup'))
def test_restore_backup(self, _mock_volume_restore):
self.backup_mgr.restore_backup(self.ctxt, backup, vol_id)
vol = db.volume_get(self.ctxt, vol_id)
- self.assertEqual(vol['status'], 'available')
+ self.assertEqual('available', vol['status'])
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'available')
+ self.assertEqual('available', backup['status'])
self.assertTrue(_mock_volume_restore.called)
@mock.patch('cinder.volume.utils.notify_about_backup_usage')
self.ctxt,
backup)
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
def test_delete_backup_with_error(self):
"""Test error handling when an error occurs during backup deletion."""
self.ctxt,
backup)
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
def test_delete_backup_with_bad_service(self):
"""Test error handling.
self.ctxt,
backup)
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
def test_delete_backup_with_no_service(self):
"""Test error handling.
ctxt_read_deleted = context.get_admin_context('yes')
backup = db.backup_get(ctxt_read_deleted, backup.id)
- self.assertEqual(backup.deleted, True)
+ self.assertEqual(True, backup.deleted)
self.assertGreaterEqual(timeutils.utcnow(), backup.deleted_at)
- self.assertEqual(backup.status, 'deleted')
+ self.assertEqual('deleted', backup.status)
@mock.patch('cinder.volume.utils.notify_about_backup_usage')
def test_delete_backup_with_notify(self, notify):
def test_list_backup(self):
backups = db.backup_get_all_by_project(self.ctxt, 'project1')
- self.assertEqual(len(backups), 0)
+ self.assertEqual(0, len(backups))
self._create_backup_db_entry()
b2 = self._create_backup_db_entry(project_id='project1')
backups = db.backup_get_all_by_project(self.ctxt, 'project1')
- self.assertEqual(len(backups), 1)
+ self.assertEqual(1, len(backups))
self.assertEqual(backups[0].id, b2.id)
def test_backup_get_all_by_project_with_deleted(self):
Unless context.read_deleted is 'yes'.
"""
backups = db.backup_get_all_by_project(self.ctxt, 'fake')
- self.assertEqual(len(backups), 0)
+ self.assertEqual(0, len(backups))
backup_keep = self._create_backup_db_entry()
backup = self._create_backup_db_entry()
db.backup_destroy(self.ctxt, backup.id)
backups = db.backup_get_all_by_project(self.ctxt, 'fake')
- self.assertEqual(len(backups), 1)
+ self.assertEqual(1, len(backups))
self.assertEqual(backups[0].id, backup_keep.id)
ctxt_read_deleted = context.get_admin_context('yes')
backups = db.backup_get_all_by_project(ctxt_read_deleted, 'fake')
- self.assertEqual(len(backups), 2)
+ self.assertEqual(2, len(backups))
def test_backup_get_all_by_host_with_deleted(self):
"""Test deleted backups.
Unless context.read_deleted is 'yes'
"""
backups = db.backup_get_all_by_host(self.ctxt, 'testhost')
- self.assertEqual(len(backups), 0)
+ self.assertEqual(0, len(backups))
backup_keep = self._create_backup_db_entry()
backup = self._create_backup_db_entry()
db.backup_destroy(self.ctxt, backup.id)
backups = db.backup_get_all_by_host(self.ctxt, 'testhost')
- self.assertEqual(len(backups), 1)
+ self.assertEqual(1, len(backups))
self.assertEqual(backups[0].id, backup_keep.id)
ctxt_read_deleted = context.get_admin_context('yes')
backups = db.backup_get_all_by_host(ctxt_read_deleted, 'testhost')
- self.assertEqual(len(backups), 2)
+ self.assertEqual(2, len(backups))
def test_backup_manager_driver_name(self):
"""Test mapping between backup services and backup drivers."""
volume_id=vol_id)
export = self.backup_mgr.export_record(self.ctxt, backup)
- self.assertEqual(export['backup_service'], CONF.backup_driver)
+ self.assertEqual(CONF.backup_driver, export['backup_service'])
self.assertTrue('backup_url' in export)
def test_import_record_with_verify_not_implemented(self):
export['backup_url'],
backup_hosts)
backup = db.backup_get(self.ctxt, imported_record.id)
- self.assertEqual(backup['status'], 'available')
- self.assertEqual(backup['size'], vol_size)
+ self.assertEqual('available', backup['status'])
+ self.assertEqual(vol_size, backup['size'])
def test_import_record_with_bad_service(self):
"""Test error handling.
backup_hosts)
self.assertTrue(_mock_record_import.called)
backup = db.backup_get(self.ctxt, imported_record.id)
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
def test_not_supported_driver_to_force_delete(self):
"""Test force delete check method for not supported drivers."""
export['backup_url'],
backup_hosts)
backup = db.backup_get(self.ctxt, imported_record.id)
- self.assertEqual(backup['status'], 'available')
- self.assertEqual(backup['size'], vol_size)
+ self.assertEqual('available', backup['status'])
+ self.assertEqual(vol_size, backup['size'])
def test_import_record_with_verify_invalid_backup(self):
"""Test error handling.
backup_hosts)
self.assertTrue(_mock_record_verify.called)
backup = db.backup_get(self.ctxt, imported_record.id)
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
def test_backup_reset_status_from_nonrestoring_to_available(
self):
backup,
'available')
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'available')
+ self.assertEqual('available', backup['status'])
def test_backup_reset_status_to_available_invalid_backup(self):
volume = db.volume_create(self.ctxt, {'status': 'available',
backup,
'available')
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
def test_backup_reset_status_from_restoring_to_available(self):
volume = db.volume_create(self.ctxt,
self.backup_mgr.reset_status(self.ctxt, backup, 'available')
backup = db.backup_get(self.ctxt, backup.id)
- self.assertEqual(backup['status'], 'available')
+ self.assertEqual('available', backup['status'])
def test_backup_reset_status_to_error(self):
volume = db.volume_create(self.ctxt,
volume_id=volume['id'])
self.backup_mgr.reset_status(self.ctxt, backup, 'error')
backup = db.backup_get(self.ctxt, backup['id'])
- self.assertEqual(backup['status'], 'error')
+ self.assertEqual('error', backup['status'])
oldformat, features = self.service._get_rbd_support()
self.assertTrue(oldformat)
- self.assertEqual(features, 0)
+ self.assertEqual(0, features)
self.service.rbd.RBD_FEATURE_LAYERING = 1
oldformat, features = self.service._get_rbd_support()
self.assertFalse(oldformat)
- self.assertEqual(features, 1)
+ self.assertEqual(1, features)
self.service.rbd.RBD_FEATURE_STRIPINGV2 = 2
oldformat, features = self.service._get_rbd_support()
self.assertFalse(oldformat)
- self.assertEqual(features, 1 | 2)
+ self.assertEqual(1 | 2, features)
@common_mocks
def test_get_most_recent_snap(self):
name = self.service._get_backup_snap_name(self.service.rbd.Image(),
'base_foo',
self.backup_id)
- self.assertEqual(name, snap_name)
+ self.assertEqual(snap_name, name)
self.assertTrue(mock_get_backup_snaps.called)
@common_mocks
{'name': 'bbbackup.%s.snap.1321319.3235' % (uuid.uuid4())},
{'name': 'backup.%s.snap.3824923.1412' % (uuid.uuid4())}]
snaps = self.service.get_backup_snaps(image)
- self.assertEqual(len(snaps), 3)
+ self.assertEqual(3, len(snaps))
@common_mocks
def test_transfer_data_from_rbd_to_file(self):
def test_get_backup_base_name(self):
name = self.service._get_backup_base_name(self.volume_id,
diff_format=True)
- self.assertEqual(name, "volume-%s.backup.base" % (self.volume_id))
+ self.assertEqual("volume-%s.backup.base" % (self.volume_id), name)
self.assertRaises(exception.InvalidParameterValue,
self.service._get_backup_base_name,
self.volume_id)
name = self.service._get_backup_base_name(self.volume_id, '1234')
- self.assertEqual(name,
- "volume-%s.backup.%s" % (self.volume_id, '1234'))
+ self.assertEqual("volume-%s.backup.%s" % (self.volume_id, '1234'),
+ name)
@common_mocks
@mock.patch('fcntl.fcntl', spec=True)
rbdio = rbddriver.RBDImageIOWrapper(meta)
self.service.backup(self.backup, rbdio)
- self.assertEqual(self.callstack, ['popen_init',
- 'read',
- 'popen_init',
- 'write',
- 'stdout_close',
- 'communicate'])
+ self.assertEqual(['popen_init',
+ 'read',
+ 'popen_init',
+ 'write',
+ 'stdout_close',
+ 'communicate'], self.callstack)
self.assertFalse(mock_full_backup.called)
self.assertTrue(mock_get_backup_snaps.called)
wrapped_rbd = self._get_wrapped_rbd_io(image)
self.service._discard_bytes(wrapped_rbd, 0, 0)
- self.assertEqual(image.discard.call_count, 0)
+ self.assertEqual(0, image.discard.call_count)
self.service._discard_bytes(wrapped_rbd, 0, 1234)
- self.assertEqual(image.discard.call_count, 1)
+ self.assertEqual(1, image.discard.call_count)
image.reset_mock()
# Test discard with no remainder
self.service._discard_bytes(wrapped_rbd, 0,
self.service.chunk_size * 2)
- self.assertEqual(image.write.call_count, 2)
- self.assertEqual(image.flush.call_count, 2)
+ self.assertEqual(2, image.write.call_count)
+ self.assertEqual(2, image.flush.call_count)
self.assertFalse(image.discard.called)
image.reset_mock()
self.service._discard_bytes(wrapped_rbd, 0,
(self.service.chunk_size * 2) + 1)
- self.assertEqual(image.write.call_count, 3)
- self.assertEqual(image.flush.call_count, 3)
+ self.assertEqual(3, image.write.call_count)
+ self.assertEqual(3, image.flush.call_count)
self.assertFalse(image.discard.called)
@common_mocks
self.assertTrue(mock_get_backup_snap_name.called)
self.assertTrue(mock_get_backup_snaps.called)
- self.assertEqual(rem, (snap_name, 0))
+ self.assertEqual((snap_name, 0), rem)
@common_mocks
@mock.patch('cinder.backup.drivers.ceph.VolumeMetadataBackup', spec=True)
def test_delete(self, mock_meta_backup):
with mock.patch.object(self.service, '_try_delete_base_image'):
self.service.delete(self.backup)
- self.assertEqual(RAISED_EXCEPTIONS, [])
+ self.assertEqual([], RAISED_EXCEPTIONS)
@common_mocks
@mock.patch('cinder.backup.drivers.ceph.VolumeMetadataBackup', spec=True)
mock_del_base.side_effect = self.mock_rbd.ImageNotFound
# ImageNotFound exception is caught so that db entry can be cleared
self.service.delete(self.backup)
- self.assertEqual(RAISED_EXCEPTIONS, [MockImageNotFoundException])
+ self.assertEqual([MockImageNotFoundException], RAISED_EXCEPTIONS)
@common_mocks
def test_diff_restore_allowed_with_image_not_exists(self):
mock_fcntl.return_value = 0
self._setup_mock_popen(mock_popen, ['out', 'err'])
self.service._piped_execute(['foo'], ['bar'])
- self.assertEqual(self.callstack, ['popen_init', 'popen_init',
- 'stdout_close', 'communicate'])
+ self.assertEqual(['popen_init', 'popen_init',
+ 'stdout_close', 'communicate'], self.callstack)
@common_mocks
def test_restore_metdata(self):
self.service._restore_metadata(self.backup, self.volume_id)
except exception.BackupOperationError as exc:
msg = _("Metadata restore failed due to incompatible version")
- self.assertEqual(six.text_type(exc), msg)
+ self.assertEqual(msg, six.text_type(exc))
else:
# Force a test failure
self.assertFalse(True)
msg = (_("Failed to backup volume metadata - Metadata backup "
"object 'backup.%s.meta' already exists") %
(self.backup_id))
- self.assertEqual(six.text_type(e), msg)
+ self.assertEqual(msg, six.text_type(e))
else:
# Make the test fail
self.assertFalse(True)
@common_meta_backup_mocks
def test_name(self):
- self.assertEqual(self.mb.name, 'backup.%s.meta' % (self.backup_id))
+ self.assertEqual('backup.%s.meta' % (self.backup_id), self.mb.name)
@common_meta_backup_mocks
def test_exists(self):
self.mock_rados.ObjectNotFound)
self.assertFalse(self.mb.exists)
self.assertTrue(self.mock_rados.Object.return_value.stat.called)
- self.assertEqual(RAISED_EXCEPTIONS, [MockObjectNotFoundException])
+ self.assertEqual([MockObjectNotFoundException], RAISED_EXCEPTIONS)
@common_meta_backup_mocks
def test_set(self):
mock_write.side_effect = _mock_write
self.mb.set({'foo': 'bar'})
- self.assertEqual(self.mb.get(), {'foo': 'bar'})
+ self.assertEqual({'foo': 'bar'}, self.mb.get())
self.assertTrue(self.mb.get.called)
self.mb._exists = mock.Mock()
{'doo': 'dah'})
# check the meta obj state has not changed.
- self.assertEqual(self.mb.get(), {'foo': 'bar'})
+ self.assertEqual({'foo': 'bar'}, self.mb.get())
- self.assertEqual(called, ['write', 'read', 'read'])
+ self.assertEqual(['write', 'read', 'read'], called)
@common_meta_backup_mocks
def test_get(self):
self.mock_rados.Object.return_value.read.return_value = 'meta'
self.assertIsNone(self.mb.get())
self.mock_rados.Object.return_value.stat.side_effect = None
- self.assertEqual(self.mb.get(), 'meta')
+ self.assertEqual('meta', self.mb.get())
@common_meta_backup_mocks
def remove_if_exists(self):
mock_remove:
mock_remove.side_effect = self.mock_rados.ObjectNotFound
self.mb.remove_if_exists()
- self.assertEqual(RAISED_EXCEPTIONS, [MockObjectNotFoundException])
+ self.assertEqual([MockObjectNotFoundException], RAISED_EXCEPTIONS)
self.mock_rados.Object.remove.side_effect = None
self.mb.remove_if_exists()
- self.assertEqual(RAISED_EXCEPTIONS, [])
+ self.assertEqual([], RAISED_EXCEPTIONS)
def test_get_metadata(self):
json_metadata = self.driver.get_metadata(self.volume_id)
metadata = jsonutils.loads(json_metadata)
- self.assertEqual(metadata['version'], 2)
+ self.assertEqual(2, metadata['version'])
def test_put_metadata(self):
metadata = {'version': 1}
# Make sure we don't lose data when converting to string
for key in _backup_db_fields:
self.assertTrue(key in export_dict)
- self.assertEqual(self.backup[key], export_dict[key])
+ self.assertEqual(export_dict[key], self.backup[key])
def test_import_record(self):
export_string = self.driver.export_record(self.backup)
# Make sure we don't lose data when converting from string
for key in _backup_db_fields:
self.assertTrue(key in imported_backup)
- self.assertEqual(imported_backup[key], self.backup[key])
+ self.assertEqual(self.backup[key], imported_backup[key])
class BackupMetadataAPITestCase(test.TestCase):
meta = self.bak_meta_api.get(self.volume_id)
s1 = set(jsonutils.loads(meta).keys())
s2 = ['version', self.bak_meta_api.TYPE_TAG_VOL_BASE_META]
- self.assertEqual(s1.symmetric_difference(s2), set())
+ self.assertEqual(set(), s1.symmetric_difference(s2))
self._add_metadata(vol_glance_meta=True)
s1 = set(jsonutils.loads(meta).keys())
s2 = ['version', self.bak_meta_api.TYPE_TAG_VOL_BASE_META,
self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META]
- self.assertEqual(s1.symmetric_difference(s2), set())
+ self.assertEqual(set(), s1.symmetric_difference(s2))
self._add_metadata(vol_meta=True)
s2 = ['version', self.bak_meta_api.TYPE_TAG_VOL_BASE_META,
self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META,
self.bak_meta_api.TYPE_TAG_VOL_META]
- self.assertEqual(s1.symmetric_difference(s2), set())
+ self.assertEqual(set(), s1.symmetric_difference(s2))
def test_put(self):
meta = self.bak_meta_api.get(self.volume_id)
keys = [self.bak_meta_api.TYPE_TAG_VOL_META,
self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META]
- self.assertEqual(set(keys).symmetric_difference(set(fact.keys())),
- set([]))
+ self.assertEqual(set([]),
+ set(keys).symmetric_difference(set(fact.keys())))
meta_container = {self.bak_meta_api.TYPE_TAG_VOL_BASE_META:
{'display_name': 'vol-2',
self.bak_meta_api.TYPE_TAG_VOL_META,
self.bak_meta_api.TYPE_TAG_VOL_GLANCE_META]
- self.assertEqual(set(keys).symmetric_difference(set(fact.keys())),
- set([]))
+ self.assertEqual(set([]),
+ set(keys).symmetric_difference(set(fact.keys())))
for f in fact:
func = fact[f][0]
backup = objects.Backup.get_by_id(self.ctxt, 123)
service.backup(backup, self.volume_file)
backup = objects.Backup.get_by_id(self.ctxt, 123)
- self.assertEqual(backup['container'], 'volumebackups')
+ self.assertEqual('volumebackups', backup['container'])
@mock.patch('cinder.backup.drivers.swift.SwiftBackupDriver.'
'_send_progress_end')
backup = objects.Backup.get_by_id(self.ctxt, 123)
service.backup(backup, self.volume_file)
backup = objects.Backup.get_by_id(self.ctxt, 123)
- self.assertEqual(backup['container'], container_name)
+ self.assertEqual(container_name, backup['container'])
def test_backup_shafile(self):
backup = objects.Backup.get_by_id(self.ctxt, 123)
service.backup(backup, self.volume_file)
backup = objects.Backup.get_by_id(self.ctxt, 123)
- self.assertEqual(backup['container'], container_name)
+ self.assertEqual(container_name, backup['container'])
# Verify sha contents
content1 = service._read_sha256file(backup)
backup = objects.Backup.get_by_id(self.ctxt, 123)
service.backup(backup, self.volume_file)
backup = objects.Backup.get_by_id(self.ctxt, 123)
- self.assertEqual(backup['container'], container_name)
+ self.assertEqual(container_name, backup['container'])
# Create incremental backup with no change to contents
self._create_backup_db_entry(container=container_name, backup_id=124,
deltabackup = objects.Backup.get_by_id(self.ctxt, 124)
service.backup(deltabackup, self.volume_file)
deltabackup = objects.Backup.get_by_id(self.ctxt, 124)
- self.assertEqual(deltabackup['container'], container_name)
+ self.assertEqual(container_name, deltabackup['container'])
# Compare shas from both files
content1 = service._read_sha256file(backup)
backup = objects.Backup.get_by_id(self.ctxt, 123)
service.backup(backup, self.volume_file)
backup = objects.Backup.get_by_id(self.ctxt, 123)
- self.assertEqual(backup['container'], container_name)
+ self.assertEqual(container_name, backup['container'])
# Create incremental backup with no change to contents
self.volume_file.seek(2 * 8 * 1024)
deltabackup = objects.Backup.get_by_id(self.ctxt, 124)
service.backup(deltabackup, self.volume_file)
deltabackup = objects.Backup.get_by_id(self.ctxt, 124)
- self.assertEqual(deltabackup['container'], container_name)
+ self.assertEqual(container_name, deltabackup['container'])
content1 = service._read_sha256file(backup)
content2 = service._read_sha256file(deltabackup)
backup = objects.Backup.get_by_id(self.ctxt, 123)
service.backup(backup, self.volume_file)
backup = objects.Backup.get_by_id(self.ctxt, 123)
- self.assertEqual(backup['container'], container_name)
+ self.assertEqual(container_name, backup['container'])
# Create incremental backup with no change to contents
self.volume_file.seek(16 * 1024)
deltabackup = objects.Backup.get_by_id(self.ctxt, 124)
service.backup(deltabackup, self.volume_file)
deltabackup = objects.Backup.get_by_id(self.ctxt, 124)
- self.assertEqual(deltabackup['container'], container_name)
+ self.assertEqual(container_name, deltabackup['container'])
# Verify that two shas are changed at index 16 and 20
content1 = service._read_sha256file(backup)
compressor = service._get_compressor('None')
self.assertIsNone(compressor)
compressor = service._get_compressor('zlib')
- self.assertEqual(compressor, zlib)
+ self.assertEqual(zlib, compressor)
compressor = service._get_compressor('bz2')
- self.assertEqual(compressor, bz2)
+ self.assertEqual(bz2, compressor)
self.assertRaises(ValueError, service._get_compressor, 'fake')
def test_prepare_output_data_effective_compression(self):
with mock.patch.object(self.drv, 'find_appropriate_size_device',
return_value='dev_path') as fasd_mocked:
result = self.drv.create_volume(TEST_VOLUME)
- self.assertEqual(result, {
- 'provider_location': 'dev_path'})
+ self.assertEqual({'provider_location': 'dev_path'}, result)
fasd_mocked.assert_called_once_with(TEST_VOLUME['size'])
def test_update_volume_stats(self):
gud_mocked:
self.drv._update_volume_stats()
- self.assertEqual(self.drv._stats,
- {'total_capacity_gb': 2,
+ self.assertEqual({'total_capacity_gb': 2,
'free_capacity_gb': 2,
'reserved_percentage':
self.configuration.reserved_percentage,
'driver_version': self.drv.VERSION,
'storage_protocol': 'unknown',
'volume_backend_name': 'BlockDeviceDriver',
- })
+ }, self.drv._stats)
gud_mocked.assert_called_once_with()
ds_mocked.assert_called_once_with()
mock.sentinel,
execute=self.drv._execute)
- self.assertEqual(self.drv.create_cloned_volume(
- TEST_VOLUME, TEST_SRC),
- {'provider_location': '/dev/loop2'})
+ self.assertEqual({'provider_location': '/dev/loop2'},
+ self.drv.create_cloned_volume(TEST_VOLUME,
+ TEST_SRC))
fasd_mocked.assert_called_once_with(TEST_SRC['size'])
lp_mocked.assert_called_once_with(TEST_SRC)
gds_mocked.assert_called_once_with('/dev/loop2')
return_value=fake_local_path):
path1 = self.drv.local_path(TEST_VOLUME1)
path2 = self.drv.local_path(TEST_VOLUME2)
- self.assertEqual(self.drv._get_used_devices(),
- set([path1, path2]))
+ self.assertEqual(set([path1, path2]),
+ self.drv._get_used_devices())
def test_get_device_size(self):
dev_path = '/dev/loop1'
with mock.patch.object(self.drv,
'_execute',
return_value=(out, None)) as _execute:
- self.assertEqual(self.drv._get_device_size(dev_path), 1)
+ self.assertEqual(1, self.drv._get_device_size(dev_path))
_execute.assert_called_once_with('blockdev', '--getsz', dev_path,
run_as_root=True)
def test_devices_sizes(self):
with mock.patch.object(self.drv, '_get_device_size') as _get_dvc_size:
_get_dvc_size.return_value = 1
- self.assertEqual(self.drv._devices_sizes(),
- {'/dev/loop1': 1, '/dev/loop2': 1})
+ self.assertEqual({'/dev/loop1': 1, '/dev/loop2': 1},
+ self.drv._devices_sizes())
def test_find_appropriate_size_device_no_free_disks(self):
size = 1
_dvc_sizes.return_value = {'/dev/loop1': 2048,
'/dev/loop2': 1024}
_get_used_dvc.return_value = set()
- self.assertEqual(self.drv.find_appropriate_size_device(size),
- '/dev/loop2')
+ self.assertEqual('/dev/loop2',
+ self.drv.find_appropriate_size_device(size))
exit = self.assertRaises(SystemExit, volume_usage_audit.main)
get_admin_context.assert_called_once_with()
- self.assertEqual(CONF.project, 'cinder')
+ self.assertEqual('cinder', CONF.project)
self.assertEqual(CONF.version, version.version_string())
log_setup.assert_called_once_with(CONF, "cinder")
get_logger.assert_called_once_with('cinder')
ctxt = context.RequestContext('111',
'222',
roles=['admin', 'weasel'])
- self.assertEqual(ctxt.is_admin, True)
+ self.assertEqual(True, ctxt.is_admin)
def test_request_context_sets_is_admin_upcase(self):
ctxt = context.RequestContext('111',
'222',
roles=['Admin', 'weasel'])
- self.assertEqual(ctxt.is_admin, True)
+ self.assertEqual(True, ctxt.is_admin)
def test_request_context_read_deleted(self):
ctxt = context.RequestContext('111',
'222',
read_deleted='yes')
- self.assertEqual(ctxt.read_deleted, 'yes')
+ self.assertEqual('yes', ctxt.read_deleted)
ctxt.read_deleted = 'no'
- self.assertEqual(ctxt.read_deleted, 'no')
+ self.assertEqual('no', ctxt.read_deleted)
def test_request_context_read_deleted_invalid(self):
self.assertRaises(ValueError,
object_catalog = [{u'name': u'swift', u'type': u'object-store'}]
ctxt = context.RequestContext('111', '222',
service_catalog=service_catalog)
- self.assertEqual(len(ctxt.service_catalog), 3)
+ self.assertEqual(3, len(ctxt.service_catalog))
return_compute = [v for v in ctxt.service_catalog if
v['type'] == u'compute']
return_object = [v for v in ctxt.service_catalog if
v['type'] == u'object-store']
- self.assertEqual(return_compute, compute_catalog)
- self.assertEqual(return_object, object_catalog)
+ self.assertEqual(compute_catalog, return_compute)
+ self.assertEqual(object_catalog, return_object)
def test_user_identity(self):
ctx = context.RequestContext("user", "tenant",
volumes = db.volume_get_all(self.ctxt, None, None, ['created_at'],
['asc'], {'display_name': 'vol2'})
self.assertEqual(1, len(volumes))
- self.assertEqual(volumes[0]['display_name'], 'vol2')
+ self.assertEqual('vol2', volumes[0]['display_name'])
# filter no match
volumes = db.volume_get_all(self.ctxt, None, None, ['created_at'],
['asc'], {'display_name': 'vol4'})
['asc'], {'status': 'available',
'display_name': 'vol1'})
self.assertEqual(1, len(volumes))
- self.assertEqual(volumes[0]['display_name'], 'vol1')
+ self.assertEqual('vol1', volumes[0]['display_name'])
self.assertEqual('available', volumes[0]['status'])
# no match
volumes = db.volume_get_all(self.ctxt, None, None, ['created_at'],
def test_snapshot_data_get_for_project(self):
actual = db.snapshot_data_get_for_project(self.ctxt, 'project1')
- self.assertEqual(actual, (0, 0))
+ self.assertEqual((0, 0), actual)
db.volume_create(self.ctxt, {'id': 1,
'project_id': 'project1',
'size': 42})
def test_quota_create(self):
quota = db.quota_create(self.ctxt, 'project1', 'resource', 99)
- self.assertEqual(quota.resource, 'resource')
+ self.assertEqual('resource', quota.resource)
self.assertEqual(99, quota.hard_limit)
self.assertEqual('project1', quota.project_id)
db.quota_create(self.ctxt, 'proj%d' % i, 'res%d' % j, j)
for i in range(3):
quotas_db = db.quota_get_all_by_project(self.ctxt, 'proj%d' % i)
- self.assertEqual(quotas_db, {'project_id': 'proj%d' % i,
- 'res0': 0,
- 'res1': 1,
- 'res2': 2})
+ self.assertEqual({'project_id': 'proj%d' % i,
+ 'res0': 0,
+ 'res1': 1,
+ 'res2': 2}, quotas_db)
def test_quota_update(self):
db.quota_create(self.ctxt, 'project1', 'resource1', 41)
def test_quota_reserve(self):
reservations = _quota_reserve(self.ctxt, 'project1')
- self.assertEqual(len(reservations), 2)
+ self.assertEqual(2, len(reservations))
quota_usage = db.quota_usage_get_all_by_project(self.ctxt, 'project1')
self.assertEqual({'project_id': 'project1',
'gigabytes': {'reserved': 2, 'in_use': 0},
target = db.iscsi_target_create_safe(self.ctxt,
self._get_base_values())
self.assertTrue(target['id'])
- self.assertEqual(target['host'], 'fake_host')
- self.assertEqual(target['target_num'], 10)
+ self.assertEqual('fake_host', target['host'])
+ self.assertEqual(10, target['target_num'])
def test_iscsi_target_count_by_host(self):
for i in range(3):
values = self._get_base_values()
values['target_num'] += i
db.iscsi_target_create_safe(self.ctxt, values)
- self.assertEqual(db.iscsi_target_count_by_host(self.ctxt, 'fake_host'),
- 3)
+ self.assertEqual(3,
+ db.iscsi_target_count_by_host(self.ctxt, 'fake_host'))
def test_integrity_error(self):
values = self._get_base_values()
mock_open_connection,
mock_init):
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['storage_protocol'], 'FC')
+ self.assertEqual('FC', stats['storage_protocol'])
mock_get_storage_usage.called_once_with(64702)
@mock.patch.object(dell_storagecenter_api.StorageCenterApi,
mock_open_connection,
mock_init):
stats = self.driver.get_volume_stats(False)
- self.assertEqual(stats['storage_protocol'], 'FC')
+ self.assertEqual('FC', stats['storage_protocol'])
assert mock_get_storage_usage.called is False
volume = {'id': self.volume_name}
connector = self.connector
data = self.driver.initialize_connection(volume, connector)
- self.assertEqual(data['driver_volume_type'], 'iscsi')
+ self.assertEqual('iscsi', data['driver_volume_type'])
# verify find_volume has been called and that is has been called twice
mock_find_volume.assert_any_call(self.volume_name)
assert mock_find_volume.call_count == 2
connector = self.connector_multipath
data = self.driver.initialize_connection(volume, connector)
- self.assertEqual(data['driver_volume_type'], 'iscsi')
+ self.assertEqual('iscsi', data['driver_volume_type'])
# verify find_volume has been called and that is has been called twice
mock_find_volume.assert_any_call(self.volume_name)
assert mock_find_volume.call_count == 2
mock_open_connection,
mock_init):
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['storage_protocol'], 'iSCSI')
+ self.assertEqual('iSCSI', stats['storage_protocol'])
mock_get_storage_usage.called_once_with(64702)
@mock.patch.object(dell_storagecenter_api.StorageCenterApi,
mock_open_connection,
mock_init):
stats = self.driver.get_volume_stats(False)
- self.assertEqual(stats['storage_protocol'], 'iSCSI')
+ self.assertEqual('iSCSI', stats['storage_protocol'])
assert mock_get_storage_usage.called is False
@mock.patch.object(dell_storagecenter_api.StorageCenterApi,
mock_init):
# Test calling find_volume with no name or instanceid
res = self.scapi.find_volume(None)
- self.assertEqual(res, None, 'Expected None')
+ self.assertEqual(None, res, 'Expected None')
@mock.patch.object(dell_storagecenter_api.StorageCenterApi,
'_get_volume_list')
storageHardwareIDInstanceNames = (
self.driver.common.masking._create_hardware_ids(
conn, initiatorNames, self.data.storage_system))
- self.assertEqual(storageHardwareIDInstanceNames[0],
- self.data.iscsi_initiator)
+ self.assertEqual(self.data.iscsi_initiator,
+ storageHardwareIDInstanceNames[0])
def test_format_system_name(self):
v2array = ['SYMMETRIX', '000195900551', 'U', 'gold']
expectVolume['CreationClassName'] = 'Symm_StorageVolume'
expectVolume['DeviceID'] = self.data.test_volume['device_id']
expect = conn.GetInstance(expectVolume)
- self.assertEqual(volumeInstanceName, expect)
+ self.assertEqual(expect, volumeInstanceName)
def test_get_volume_element_name(self):
volumeId = 'ea95aa39-080b-4f11-9856-a03acf9112ad'
volumeElementName = utils.get_volume_element_name(volumeId)
expectVolumeElementName = (
emc_vmax_utils.VOLUME_ELEMENT_NAME_PREFIX + volumeId)
- self.assertEqual(volumeElementName, expectVolumeElementName)
+ self.assertEqual(expectVolumeElementName, volumeElementName)
def test_get_associated_replication_from_source_volume(self):
conn = self.fake_ecom_connection()
self.data.test_volume['device_id']))
expectInstanceName = (
conn.EnumerateInstanceNames('SE_StorageSynchronized_SV_SV')[0])
- self.assertEqual(repInstanceName, expectInstanceName)
+ self.assertEqual(expectInstanceName, repInstanceName)
def test_get_array_and_device_id_success(self):
deviceId = '0123'
}
utils = self.driver.common.utils
(arrId, devId) = utils.get_array_and_device_id(volume, external_ref)
- self.assertEqual(arrId, arrayId)
- self.assertEqual(devId, deviceId)
+ self.assertEqual(arrayId, arrId)
+ self.assertEqual(deviceId, devId)
def test_get_array_and_device_id_failed(self):
deviceId = '0123'
self.driver.create_volume(self.data.test_volume)
map_data = self.driver.initialize_connection(self.data.test_volume,
self.data.connector)
- self.assertEqual(map_data['data']['target_lun'], 1)
+ self.assertEqual(1, map_data['data']['target_lun'])
i1 = xms_data['initiators'][1]
i1['ig-id'] = ['', i1['ig-id'], 1]
i1['chap-authentication-initiator-password'] = 'chap_password1'
def test_get_stats(self, req):
req.side_effect = xms_request
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['volume_backend_name'],
- self.driver.backend_name)
+ self.assertEqual(self.driver.backend_name,
+ stats['volume_backend_name'])
def test_manage_unmanage(self, req):
req.side_effect = xms_request
self.driver.create_volume(self.data.test_volume)
map_data = self.driver.initialize_connection(self.data.test_volume,
self.data.connector)
- self.assertEqual(map_data['data']['target_lun'], 1)
+ self.assertEqual(1, map_data['data']['target_lun'])
self.driver.terminate_connection(self.data.test_volume,
self.data.connector)
self.driver.delete_volume(self.data.test_volume)
'_eql_execute') as mock_eql_execute:
mock_eql_execute.side_effect = my_side_effect
self.driver.do_setup(self._context)
- self.assertEqual(self.driver._group_ip, fake_group_ip)
+ self.assertEqual(fake_group_ip, self.driver._group_ip)
def test_update_volume_stats(self):
mock_attrs = {'args': ['pool', 'select',
def w_timeout(cmd, *args, **kwargs):
time.sleep(1)
- self.assertEqual(no_timeout('fake cmd'), 'no timeout')
+ self.assertEqual('no timeout', no_timeout('fake cmd'))
self.assertRaises(exception.VolumeBackendAPIException,
w_timeout, 'fake cmd', timeout=0.1)
message = "default message"
exc = FakeCinderException()
- self.assertEqual(six.text_type(exc), 'default message')
+ self.assertEqual('default message', six.text_type(exc))
def test_error_msg(self):
- self.assertEqual(six.text_type(exception.CinderException('test')),
- 'test')
+ self.assertEqual('test',
+ six.text_type(exception.CinderException('test')))
def test_default_error_msg_with_kwargs(self):
class FakeCinderException(exception.CinderException):
message = "default message: %(code)s"
exc = FakeCinderException(code=500)
- self.assertEqual(six.text_type(exc), 'default message: 500')
+ self.assertEqual('default message: 500', six.text_type(exc))
def test_error_msg_exception_with_kwargs(self):
# NOTE(dprince): disable format errors for this test
message = "default message: %(misspelled_code)s"
exc = FakeCinderException(code=500)
- self.assertEqual(six.text_type(exc),
- 'default message: %(misspelled_code)s')
+ self.assertEqual('default message: %(misspelled_code)s',
+ six.text_type(exc))
def test_default_error_code(self):
class FakeCinderException(exception.CinderException):
code = 404
exc = FakeCinderException()
- self.assertEqual(exc.kwargs['code'], 404)
+ self.assertEqual(404, exc.kwargs['code'])
def test_error_code_from_kwarg(self):
class FakeCinderException(exception.CinderException):
code = 500
exc = FakeCinderException(code=404)
- self.assertEqual(exc.kwargs['code'], 404)
+ self.assertEqual(404, exc.kwargs['code'])
def test_error_msg_is_exception_to_string(self):
msg = 'test message'
message = 'FakeCinderException: %(message)s'
exc = FakeCinderException(message='message')
- self.assertEqual(six.text_type(exc), 'FakeCinderException: message')
+ self.assertEqual('FakeCinderException: message', six.text_type(exc))
def test_message_and_kwarg_in_format_string(self):
class FakeCinderException(exception.CinderException):
message = 'Error %(code)d: %(message)s'
exc = FakeCinderException(message='message', code=404)
- self.assertEqual(six.text_type(exc), 'Error 404: message')
+ self.assertEqual('Error 404: message', six.text_type(exc))
def test_message_is_exception_in_format_string(self):
class FakeCinderException(exception.CinderException):
msg = 'test message'
exc1 = Exception(msg)
exc2 = FakeCinderException(message=exc1)
- self.assertEqual(six.text_type(exc2), 'Exception: test message')
+ self.assertEqual('Exception: test message', six.text_type(exc2))
self.assertFalse(gpfs._different(None))
def test_sizestr(self):
- self.assertEqual(gpfs._sizestr('10'), '10G')
+ self.assertEqual('10G', gpfs._sizestr('10'))
@mock.patch('cinder.utils.execute')
def test_gpfs_local_execute(self, mock_exec):
@mock.patch('cinder.utils.execute')
def test_can_migrate_locally(self, mock_exec):
host = {'host': 'foo', 'capabilities': ''}
- self.assertEqual(self.driver._can_migrate_locally(host), None)
+ self.assertEqual(None, self.driver._can_migrate_locally(host))
loc = 'GPFSDriver:%s' % self.driver._cluster_id
cap = {'location_info': loc}
host = {'host': 'foo', 'capabilities': cap}
- self.assertEqual(self.driver._can_migrate_locally(host), None)
+ self.assertEqual(None, self.driver._can_migrate_locally(host))
loc = 'GPFSDriver_:%s:testpath' % self.driver._cluster_id
cap = {'location_info': loc}
host = {'host': 'foo', 'capabilities': cap}
- self.assertEqual(self.driver._can_migrate_locally(host), None)
+ self.assertEqual(None, self.driver._can_migrate_locally(host))
loc = 'GPFSDriver:%s:testpath' % (self.driver._cluster_id + '_')
cap = {'location_info': loc}
host = {'host': 'foo', 'capabilities': cap}
- self.assertEqual(self.driver._can_migrate_locally(host), None)
+ self.assertEqual(None, self.driver._can_migrate_locally(host))
loc = 'GPFSDriver:%s:testpath' % self.driver._cluster_id
cap = {'location_info': loc}
host = {'host': 'foo', 'capabilities': cap}
- self.assertEqual(self.driver._can_migrate_locally(host), 'testpath')
+ self.assertEqual('testpath', self.driver._can_migrate_locally(host))
@mock.patch('cinder.volume.drivers.ibm.gpfs.GPFSDriver._verify_gpfs_pool')
@mock.patch('cinder.volume.drivers.ibm.gpfs.GPFSDriver.'
volume['consistencygroup_id'] = None
snapshot = self._fake_snapshot()
mock_snapshot_path.return_value = "/tmp/fakepath"
- self.assertEqual(self.driver.create_volume_from_snapshot(
- volume,
- snapshot
- ),
- {'size': 5.0})
+ self.assertEqual({'size': 5.0},
+ self.driver.create_volume_from_snapshot(volume,
+ snapshot))
@mock.patch('cinder.volume.drivers.ibm.gpfs.GPFSDriver.'
'_resize_volume_file')
self.assertTrue(self.driver._set_volume_attributes(volume, 'test',
metadata))
- self.assertEqual(self.driver.create_volume_from_snapshot(volume,
- snapshot),
- {'size': 5.0})
+ self.assertEqual({'size': 5.0},
+ self.driver.create_volume_from_snapshot(volume,
+ snapshot))
@mock.patch('cinder.volume.drivers.ibm.gpfs.GPFSDriver.'
'_resize_volume_file')
mock_resize_volume_file.return_value = 5 * units.Gi
volume = self._fake_volume()
src_volume = self._fake_volume()
- self.assertEqual(self.driver.create_cloned_volume(volume, src_volume),
- {'size': 5.0})
+ self.assertEqual({'size': 5.0},
+ self.driver.create_cloned_volume(volume, src_volume))
@mock.patch('cinder.volume.drivers.ibm.gpfs.GPFSDriver.'
'_resize_volume_file')
self.assertTrue(self.driver._set_volume_attributes(volume, 'test',
metadata))
- self.assertEqual(self.driver.create_cloned_volume(volume, src_volume),
- {'size': 5.0})
+ self.assertEqual({'size': 5.0},
+ self.driver.create_cloned_volume(volume, src_volume))
@mock.patch('cinder.utils.execute')
def test_delete_gpfs_file_ok(self, mock_exec):
volume = self._fake_volume()
mock_local_path.return_value = "/tmp/fakepath"
data = self.driver.initialize_connection(volume, '')
- self.assertEqual(data['data']['name'], 'test')
- self.assertEqual(data['data']['device_path'], "/tmp/fakepath")
- self.assertEqual(data['driver_volume_type'], 'gpfs')
+ self.assertEqual('test', data['data']['name'])
+ self.assertEqual("/tmp/fakepath", data['data']['device_path'])
+ self.assertEqual('gpfs', data['driver_volume_type'])
def test_terminate_connection(self):
self.assertEqual(None, self.driver.terminate_connection('', ''))
'_get_available_capacity',
return_value=(fake_avail, fake_size)):
stats = self.driver.get_volume_stats()
- self.assertEqual(stats['volume_backend_name'], 'GPFS')
- self.assertEqual(stats['storage_protocol'], 'file')
+ self.assertEqual('GPFS', stats['volume_backend_name'])
+ self.assertEqual('file', stats['storage_protocol'])
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['volume_backend_name'], 'GPFS')
- self.assertEqual(stats['storage_protocol'], 'file')
+ self.assertEqual('GPFS', stats['volume_backend_name'])
+ self.assertEqual('file', stats['storage_protocol'])
@mock.patch('cinder.volume.drivers.ibm.gpfs.GPFSDriver.'
'_update_volume_stats')
model_update, snapshots = self.driver.create_cgsnapshot(ctxt, cgsnap)
self.driver.create_snapshot.assert_called_once_with(snapshot1)
self.assertEqual({'status': cgsnap['status']}, model_update)
- self.assertEqual(snapshot1['status'], 'available')
+ self.assertEqual('available', snapshot1['status'])
self.driver.db.snapshot_get_all_for_cgsnapshot.\
assert_called_once_with(ctxt, cgsnap['id'])
model_update, snapshots = self.driver.delete_cgsnapshot(ctxt, cgsnap)
self.driver.delete_snapshot.assert_called_once_with(snapshot1)
self.assertEqual({'status': cgsnap['status']}, model_update)
- self.assertEqual(snapshot1['status'], 'deleted')
+ self.assertEqual('deleted', snapshot1['status'])
self.driver.db.snapshot_get_all_for_cgsnapshot.\
assert_called_once_with(ctxt, cgsnap['id'])
volume['name']
)
ret = self.driver.local_path(volume)
- self.assertEqual(ret, volume_path)
+ self.assertEqual(volume_path, ret)
def test_local_path_volume_in_cg(self):
volume = self._fake_volume()
volume['name']
)
ret = self.driver.local_path(volume)
- self.assertEqual(ret, volume_path)
+ self.assertEqual(volume_path, ret)
@mock.patch('cinder.context.get_admin_context')
@mock.patch('cinder.volume.drivers.ibm.gpfs.GPFSDriver.local_path')
snapshot = self._fake_snapshot()
ret = self.driver._get_snapshot_path(snapshot)
self.assertEqual(
- ret, os.path.join(os.path.dirname(volume_path), snapshot['name'])
+ os.path.join(os.path.dirname(volume_path), snapshot['name']), ret
)
@mock.patch('cinder.utils.execute')
ret = self.driver.create_volume(self._VOLUME)
vol = self._VOLUME.copy()
vol['provider_location'] = ret['provider_location']
- self.assertEqual(vol['provider_location'], '1')
+ self.assertEqual('1', vol['provider_location'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_common.HBSDCommon, 'get_volume_metadata')
def test_get_volume_stats(self, arg1, arg2):
"""test get_volume_stats."""
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['vendor_name'], 'Hitachi')
+ self.assertEqual('Hitachi', stats['vendor_name'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_horcm.HBSDHORCM, 'exec_raidcom',
"""test get_volume_stats."""
self.configuration.hitachi_pool_id = 29
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats, {})
+ self.assertEqual({}, stats)
self.configuration.hitachi_pool_id = 30
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
"""test create_snapshot."""
ret = self.driver.create_volume(self._VOLUME)
ret = self.driver.create_snapshot(self.test_snapshot)
- self.assertEqual(ret['provider_location'], '1')
+ self.assertEqual('1', ret['provider_location'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_common.HBSDCommon, 'get_snapshot_metadata',
"""test create_snapshot."""
ret = self.driver.create_volume(self.test_volume)
ret = self.driver.create_snapshot(self.test_snapshot_error)
- self.assertEqual(ret['provider_location'], '1')
+ self.assertEqual('1', ret['provider_location'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_horcm.HBSDHORCM, 'exec_raidcom',
"""test create_cloned_volume."""
vol = self.driver.create_cloned_volume(self.test_volume,
self._VOLUME)
- self.assertEqual(vol['provider_location'], '1')
+ self.assertEqual('1', vol['provider_location'])
return
@mock.patch.object(hbsd_common.HBSDCommon, 'get_volume_metadata',
connector = {'wwpns': ['12345678912345aa', '12345678912345bb'],
'ip': '127.0.0.1'}
rc = self.driver.initialize_connection(self._VOLUME, connector)
- self.assertEqual(rc['driver_volume_type'], 'fibre_channel')
- self.assertEqual(rc['data']['target_wwn'], ['50060E801053C2E0'])
- self.assertEqual(rc['data']['target_lun'], 0)
+ self.assertEqual('fibre_channel', rc['driver_volume_type'])
+ self.assertEqual(['50060E801053C2E0'], rc['data']['target_wwn'])
+ self.assertEqual(0, rc['data']['target_lun'])
return
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
connector = {'wwpns': ['12345678912345aa', '12345678912345bb'],
'ip': '127.0.0.1'}
rc = self.driver.terminate_connection(self._VOLUME, connector)
- self.assertEqual(rc['driver_volume_type'], 'fibre_channel')
- self.assertEqual(rc['data']['target_wwn'], ['50060E801053C2E0'])
+ self.assertEqual('fibre_channel', rc['driver_volume_type'])
+ self.assertEqual(['50060E801053C2E0'], rc['data']['target_wwn'])
return
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
ret = self.driver.create_volume(self._VOLUME)
vol = self._VOLUME.copy()
vol['provider_location'] = ret['provider_location']
- self.assertEqual(vol['provider_location'], '1')
+ self.assertEqual('1', vol['provider_location'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_common.HBSDCommon, 'get_volume_metadata')
def test_get_volume_stats(self, arg1, arg2):
"""test get_volume_stats."""
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['vendor_name'], 'Hitachi')
+ self.assertEqual('Hitachi', stats['vendor_name'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_snm2.HBSDSNM2, 'exec_hsnm', side_effect=_exec_hsnm)
"""test get_volume_stats."""
self.configuration.hitachi_pool_id = 29
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats, {})
+ self.assertEqual({}, stats)
self.configuration.hitachi_pool_id = 30
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
"""test create_snapshot."""
ret = self.driver.create_volume(self._VOLUME)
ret = self.driver.create_snapshot(self.test_snapshot)
- self.assertEqual(ret['provider_location'], '1')
+ self.assertEqual('1', ret['provider_location'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_common.HBSDCommon, 'get_snapshot_metadata',
"""test initialize connection."""
connector = {'wwpns': '0x100000', 'ip': '0xc0a80100'}
rc = self.driver.initialize_connection(self._VOLUME, connector)
- self.assertEqual(rc['driver_volume_type'], 'fibre_channel')
- self.assertEqual(rc['data']['target_wwn'], ['50060E801053C2E0'])
- self.assertEqual(rc['data']['target_lun'], 1)
+ self.assertEqual('fibre_channel', rc['driver_volume_type'])
+ self.assertEqual(['50060E801053C2E0'], rc['data']['target_wwn'])
+ self.assertEqual(1, rc['data']['target_lun'])
return
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
"""test terminate connection."""
connector = {'wwpns': '0x100000', 'ip': '0xc0a80100'}
rc = self.driver.terminate_connection(self._VOLUME, connector)
- self.assertEqual(rc['driver_volume_type'], 'fibre_channel')
- self.assertEqual(rc['data']['target_wwn'], ['50060E801053C2E0'])
+ self.assertEqual('fibre_channel', rc['driver_volume_type'])
+ self.assertEqual(['50060E801053C2E0'], rc['data']['target_wwn'])
return
@mock.patch.object(hbsd_snm2.HBSDSNM2, 'exec_hsnm', side_effect=_exec_hsnm)
ret = self.driver.create_volume(self._VOLUME)
vol = self._VOLUME.copy()
vol['provider_location'] = ret['provider_location']
- self.assertEqual(vol['provider_location'], '1')
+ self.assertEqual('1', vol['provider_location'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_common.HBSDCommon, 'get_volume_metadata')
def test_get_volume_stats(self, arg1, arg2):
"""test get_volume_stats."""
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['vendor_name'], 'Hitachi')
+ self.assertEqual('Hitachi', stats['vendor_name'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_snm2.HBSDSNM2, 'exec_hsnm', side_effect=_exec_hsnm)
"""test get_volume_stats."""
self.configuration.hitachi_pool_id = 29
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats, {})
+ self.assertEqual({}, stats)
self.configuration.hitachi_pool_id = 30
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
"""test create_snapshot."""
ret = self.driver.create_volume(self._VOLUME)
ret = self.driver.create_snapshot(self.test_snapshot)
- self.assertEqual(ret['provider_location'], '1')
+ self.assertEqual('1', ret['provider_location'])
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
@mock.patch.object(hbsd_common.HBSDCommon, 'get_snapshot_metadata',
'wwpns': '0x100000', 'ip': '0.0.0.0', 'initiator':
'iqn'}
rc = self.driver.initialize_connection(self._VOLUME, connector)
- self.assertEqual(rc['driver_volume_type'], 'iscsi')
- self.assertEqual(rc['data']['target_iqn'], 'iqn-target')
- self.assertEqual(rc['data']['target_lun'], 1)
+ self.assertEqual('iscsi', rc['driver_volume_type'])
+ self.assertEqual('iqn-target', rc['data']['target_iqn'])
+ self.assertEqual(1, rc['data']['target_lun'])
return
@mock.patch.object(hbsd_basiclib, 'get_process_lock')
self.assertIn('172.24.44.20', out)
self.assertIn('172.24.44.21', out)
self.assertIn('10.0.0.20', out)
- self.assertEqual(len(out.split('\n')), 4)
+ self.assertEqual(4, len(out.split('\n')))
@mock.patch.object(hnas_backend.HnasBackend, 'run_cmd')
def test_get_hdp_info(self, m_run_cmd):
out = self.hnas_bend.get_hdp_info("ssh", "0.0.0.0", "supervisor",
"supervisor")
- self.assertEqual(len(out.split('\n')), 10)
+ self.assertEqual(10, len(out.split('\n')))
self.assertIn('gold', out)
self.assertIn('silver', out)
line1 = out.split('\n')[0]
- self.assertEqual(len(line1.split()), 12)
+ self.assertEqual(12, len(line1.split()))
# test when there is only one evs
m_run_cmd.return_value = (HNAS_RESULT19, "")
out = self.hnas_bend.get_hdp_info("ssh", "0.0.0.0", "supervisor",
"supervisor")
- self.assertEqual(len(out.split('\n')), 3)
+ self.assertEqual(3, len(out.split('\n')))
self.assertIn('fs01-husvm', out)
self.assertIn('manage_test02', out)
line1 = out.split('\n')[0]
- self.assertEqual(len(line1.split()), 12)
+ self.assertEqual(12, len(line1.split()))
@mock.patch.object(hnas_backend.HnasBackend, 'run_cmd',
side_effect=m_run_cmd)
out = self.hnas_bend.get_nfs_info("ssh", "0.0.0.0", "supervisor",
"supervisor")
- self.assertEqual(len(out.split('\n')), 2)
+ self.assertEqual(2, len(out.split('\n')))
self.assertIn('/export01-husvm', out)
self.assertIn('172.24.44.20', out)
self.assertIn('10.0.0.20', out)
def test_get_volume_stats(self):
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats["vendor_name"], "HDS")
- self.assertEqual(stats["storage_protocol"], "iSCSI")
- self.assertEqual(len(stats['pools']), 2)
+ self.assertEqual("HDS", stats["vendor_name"])
+ self.assertEqual("iSCSI", stats["storage_protocol"])
+ self.assertEqual(2, len(stats['pools']))
def test_delete_volume(self):
vol = self._create_volume()
loc = self.driver.create_snapshot(svol)
out = "{'provider_location': \'" + _SHARE + "'}"
- self.assertEqual(str(loc), out)
+ self.assertEqual(out, str(loc))
@mock.patch.object(nfs.HDSNFSDriver, '_get_service')
@mock.patch.object(nfs.HDSNFSDriver, '_id_to_vol', side_effect=id_to_vol)
loc = self.driver.create_cloned_volume(vol, svol)
out = "{'provider_location': \'" + _SHARE + "'}"
- self.assertEqual(str(loc), out)
+ self.assertEqual(out, str(loc))
@mock.patch.object(nfs.HDSNFSDriver, '_ensure_shares_mounted')
@mock.patch.object(nfs.HDSNFSDriver, '_do_create_volume')
m_volume_not_present.return_value = True
self.driver.delete_snapshot(svol)
- self.assertEqual(svol['provider_location'], None)
+ self.assertEqual(None, svol['provider_location'])
@mock.patch.object(nfs.HDSNFSDriver, '_get_service')
@mock.patch.object(nfs.HDSNFSDriver, '_id_to_vol', side_effect=id_to_vol)
loc = self.driver.create_volume_from_snapshot(vol, svol)
out = "{'provider_location': \'" + _SHARE + "'}"
- self.assertEqual(str(loc), out)
+ self.assertEqual(out, str(loc))
@mock.patch.object(volume_types, 'get_volume_type_extra_specs',
return_value={'key': 'type', 'service_label': 'silver'})
def test_get_pool(self, m_ext_spec):
vol = _VOLUME.copy()
- self.assertEqual(self.driver.get_pool(vol), 'silver')
+ self.assertEqual('silver', self.driver.get_pool(vol))
mock.call.getTask(task_id)
]
mock_client.assert_has_calls(expected)
- self.assertEqual(status, self.STATUS_DONE)
+ self.assertEqual(self.STATUS_DONE, status)
def test_create_volume(self):
# setup_mock_client drive with default configuration
self.standard_login +
expected +
self.standard_logout)
- self.assertEqual(return_model, None)
+ self.assertEqual(None, return_model)
@mock.patch.object(volume_types, 'get_volume_type')
def test_unsupported_dedup_volume_type(self, _mock_volume_types):
self.standard_login +
expected +
self.standard_logout)
- self.assertEqual(return_model, None)
+ self.assertEqual(None, return_model)
@mock.patch.object(volume_types, 'get_volume_type')
def test_create_volume_dedup(self, _mock_volume_types):
self.standard_login +
expected +
self.standard_logout)
- self.assertEqual(return_model, None)
+ self.assertEqual(None, return_model)
@mock.patch.object(volume_types, 'get_volume_type')
def test_create_volume_flash_cache(self, _mock_volume_types):
self.standard_login +
expected +
self.standard_logout)
- self.assertEqual(return_model, None)
+ self.assertEqual(None, return_model)
@mock.patch.object(volume_types, 'get_volume_type')
def test_unsupported_flash_cache_volume(self, _mock_volume_types):
volume['host'] = volume_host
volume['source_volid'] = HP3PARBaseDriver.VOLUME_ID
model_update = self.driver.create_cloned_volume(volume, src_vref)
- self.assertEqual(model_update, None)
+ self.assertEqual(None, model_update)
expected = [
mock.call.getCPG(expected_cpg),
model_update = self.driver.create_volume_from_snapshot(
volume,
self.snapshot)
- self.assertEqual(model_update, None)
+ self.assertEqual(None, model_update)
comment = (
'{"snapshot_id": "2f823bdc-e36e-4dc8-bd15-de1c7a28ff31",'
model_update = self.driver.create_volume_from_snapshot(
volume,
self.snapshot)
- self.assertEqual(model_update, None)
+ self.assertEqual(None, model_update)
comment = (
'{"snapshot_id": "2f823bdc-e36e-4dc8-bd15-de1c7a28ff31",'
mock_create_client.return_value = mock_client
common = self.driver._login()
ports = common.get_ports()['members']
- self.assertEqual(len(ports), 3)
+ self.assertEqual(3, len(ports))
def test_get_by_qos_spec_with_scoping(self):
mock_client = self.setup_driver()
type_ref['id'])
type_ref = volume_types.get_volume_type(self.ctxt, type_ref['id'])
qos = common._get_qos_by_volume_type(type_ref)
- self.assertEqual(qos, {'maxIOPS': '1000', 'maxBWS': '50',
- 'minIOPS': '100', 'minBWS': '25',
- 'latency': '25', 'priority': 'low'})
+ self.assertEqual({'maxIOPS': '1000', 'maxBWS': '50',
+ 'minIOPS': '100', 'minBWS': '25',
+ 'latency': '25', 'priority': 'low'}, qos)
def test_get_by_qos_spec(self):
mock_client = self.setup_driver()
type_ref['id'])
type_ref = volume_types.get_volume_type(self.ctxt, type_ref['id'])
qos = common._get_qos_by_volume_type(type_ref)
- self.assertEqual(qos, {'maxIOPS': '1000', 'maxBWS': '50',
- 'minIOPS': '100', 'minBWS': '25',
- 'latency': '25', 'priority': 'low'})
+ self.assertEqual({'maxIOPS': '1000', 'maxBWS': '50',
+ 'minIOPS': '100', 'minBWS': '25',
+ 'latency': '25', 'priority': 'low'}, qos)
def test_get_by_qos_by_type_only(self):
mock_client = self.setup_driver()
"qos:priority": "high"})
type_ref = volume_types.get_volume_type(self.ctxt, type_ref['id'])
qos = common._get_qos_by_volume_type(type_ref)
- self.assertEqual(qos, {'maxIOPS': '100', 'maxBWS': '50',
- 'minIOPS': '10', 'minBWS': '20',
- 'latency': '5', 'priority': 'high'})
+ self.assertEqual({'maxIOPS': '100', 'maxBWS': '50',
+ 'minIOPS': '10', 'minBWS': '20',
+ 'latency': '5', 'priority': 'high'}, qos)
def test_create_vlun(self):
host = 'fake-host'
stats = self.driver.get_volume_stats(True)
const = 0.0009765625
- self.assertEqual(stats['storage_protocol'], 'FC')
- self.assertEqual(stats['total_capacity_gb'], 0)
- self.assertEqual(stats['free_capacity_gb'], 0)
- self.assertEqual(stats['pools'][0]['total_capacity_gb'], 24.0)
- self.assertEqual(stats['pools'][0]['free_capacity_gb'], 3.0)
- self.assertEqual(stats['pools'][0]['capacity_utilization'], 87.5)
- self.assertEqual(stats['pools'][0]['total_volumes'], 3)
- self.assertEqual(stats['pools'][0]['goodness_function'],
- GOODNESS_FUNCTION)
- self.assertEqual(stats['pools'][0]['filter_function'],
- FILTER_FUNCTION)
+ self.assertEqual('FC', stats['storage_protocol'])
+ self.assertEqual(0, stats['total_capacity_gb'])
+ self.assertEqual(0, stats['free_capacity_gb'])
+ self.assertEqual(24.0, stats['pools'][0]['total_capacity_gb'])
+ self.assertEqual(3.0, stats['pools'][0]['free_capacity_gb'])
+ self.assertEqual(87.5, stats['pools'][0]['capacity_utilization'])
+ self.assertEqual(3, stats['pools'][0]['total_volumes'])
+ self.assertEqual(GOODNESS_FUNCTION,
+ stats['pools'][0]['goodness_function'])
+ self.assertEqual(FILTER_FUNCTION,
+ stats['pools'][0]['filter_function'])
expected = [
mock.call.getStorageSystemInfo(),
expected +
self.standard_logout)
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['storage_protocol'], 'FC')
- self.assertEqual(stats['total_capacity_gb'], 0)
- self.assertEqual(stats['free_capacity_gb'], 0)
- self.assertEqual(stats['pools'][0]['total_capacity_gb'], 24.0)
- self.assertEqual(stats['pools'][0]['free_capacity_gb'], 3.0)
- self.assertEqual(stats['pools'][0]['capacity_utilization'], 87.5)
- self.assertEqual(stats['pools'][0]['total_volumes'], 3)
- self.assertEqual(stats['pools'][0]['goodness_function'],
- GOODNESS_FUNCTION)
- self.assertEqual(stats['pools'][0]['filter_function'],
- FILTER_FUNCTION)
+ self.assertEqual('FC', stats['storage_protocol'])
+ self.assertEqual(0, stats['total_capacity_gb'])
+ self.assertEqual(0, stats['free_capacity_gb'])
+ self.assertEqual(24.0, stats['pools'][0]['total_capacity_gb'])
+ self.assertEqual(3.0, stats['pools'][0]['free_capacity_gb'])
+ self.assertEqual(87.5, stats['pools'][0]['capacity_utilization'])
+ self.assertEqual(3, stats['pools'][0]['total_volumes'])
+ self.assertEqual(GOODNESS_FUNCTION,
+ stats['pools'][0]['goodness_function'])
+ self.assertEqual(FILTER_FUNCTION,
+ stats['pools'][0]['filter_function'])
cpg2 = self.cpgs[0].copy()
cpg2.update({'SDGrowth': {'limitMiB': 8192}})
mock_client.getCPG.return_value = cpg2
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['storage_protocol'], 'FC')
+ self.assertEqual('FC', stats['storage_protocol'])
total_capacity_gb = 8192 * const
- self.assertEqual(stats['total_capacity_gb'], 0)
- self.assertEqual(stats['pools'][0]['total_capacity_gb'],
- total_capacity_gb)
+ self.assertEqual(0, stats['total_capacity_gb'])
+ self.assertEqual(total_capacity_gb,
+ stats['pools'][0]['total_capacity_gb'])
free_capacity_gb = int(
(8192 - (self.cpgs[0]['UsrUsage']['usedMiB'] +
self.cpgs[0]['SDUsage']['usedMiB'])) * const)
- self.assertEqual(stats['free_capacity_gb'], 0)
- self.assertEqual(stats['pools'][0]['free_capacity_gb'],
- free_capacity_gb)
+ self.assertEqual(0, stats['free_capacity_gb'])
+ self.assertEqual(free_capacity_gb,
+ stats['pools'][0]['free_capacity_gb'])
cap_util = (float(total_capacity_gb - free_capacity_gb) /
float(total_capacity_gb)) * 100
- self.assertEqual(stats['pools'][0]['capacity_utilization'],
- cap_util)
- self.assertEqual(stats['pools'][0]['total_volumes'], 3)
- self.assertEqual(stats['pools'][0]['goodness_function'],
- GOODNESS_FUNCTION)
- self.assertEqual(stats['pools'][0]['filter_function'],
- FILTER_FUNCTION)
+ self.assertEqual(cap_util,
+ stats['pools'][0]['capacity_utilization'])
+ self.assertEqual(3, stats['pools'][0]['total_volumes'])
+ self.assertEqual(GOODNESS_FUNCTION,
+ stats['pools'][0]['goodness_function'])
+ self.assertEqual(FILTER_FUNCTION,
+ stats['pools'][0]['filter_function'])
common.client.deleteCPG(HP3PAR_CPG)
common.client.createCPG(HP3PAR_CPG, {})
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
+ self.assertEqual(self.FAKE_HOST, host['name'])
def test_create_invalid_host(self):
# setup_mock_client drive with default configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], 'fakehost.foo')
+ self.assertEqual('fakehost.foo', host['name'])
def test_create_modify_host(self):
# setup_mock_client drive with default configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
- self.assertEqual(len(host['FCPaths']), 2)
+ self.assertEqual(self.FAKE_HOST, host['name'])
+ self.assertEqual(2, len(host['FCPaths']))
def test_modify_host_with_new_wwn(self):
# setup_mock_client drive with default configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
- self.assertEqual(len(host['FCPaths']), 2)
+ self.assertEqual(self.FAKE_HOST, host['name'])
+ self.assertEqual(2, len(host['FCPaths']))
def test_modify_host_with_unknown_wwn_and_new_wwn(self):
# setup_mock_client drive with default configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
- self.assertEqual(len(host['FCPaths']), 3)
+ self.assertEqual(self.FAKE_HOST, host['name'])
+ self.assertEqual(3, len(host['FCPaths']))
class TestHP3PARISCSIDriver(HP3PARBaseDriver, test.TestCase):
stats = self.driver.get_volume_stats(True)
const = 0.0009765625
- self.assertEqual(stats['storage_protocol'], 'iSCSI')
- self.assertEqual(stats['total_capacity_gb'], 0)
- self.assertEqual(stats['free_capacity_gb'], 0)
- self.assertEqual(stats['pools'][0]['total_capacity_gb'], 24.0)
- self.assertEqual(stats['pools'][0]['free_capacity_gb'], 3.0)
- self.assertEqual(stats['pools'][0]['capacity_utilization'], 87.5)
- self.assertEqual(stats['pools'][0]['total_volumes'], 3)
- self.assertEqual(stats['pools'][0]['goodness_function'],
- GOODNESS_FUNCTION)
- self.assertEqual(stats['pools'][0]['filter_function'],
- FILTER_FUNCTION)
+ self.assertEqual('iSCSI', stats['storage_protocol'])
+ self.assertEqual(0, stats['total_capacity_gb'])
+ self.assertEqual(0, stats['free_capacity_gb'])
+ self.assertEqual(24.0, stats['pools'][0]['total_capacity_gb'])
+ self.assertEqual(3.0, stats['pools'][0]['free_capacity_gb'])
+ self.assertEqual(87.5, stats['pools'][0]['capacity_utilization'])
+ self.assertEqual(3, stats['pools'][0]['total_volumes'])
+ self.assertEqual(GOODNESS_FUNCTION,
+ stats['pools'][0]['goodness_function'])
+ self.assertEqual(FILTER_FUNCTION,
+ stats['pools'][0]['filter_function'])
expected = [
mock.call.getStorageSystemInfo(),
mock_client.getCPG.return_value = cpg2
stats = self.driver.get_volume_stats(True)
- self.assertEqual(stats['storage_protocol'], 'iSCSI')
+ self.assertEqual('iSCSI', stats['storage_protocol'])
total_capacity_gb = 8192 * const
- self.assertEqual(stats['total_capacity_gb'], 0)
- self.assertEqual(stats['pools'][0]['total_capacity_gb'],
- total_capacity_gb)
+ self.assertEqual(0, stats['total_capacity_gb'])
+ self.assertEqual(total_capacity_gb,
+ stats['pools'][0]['total_capacity_gb'])
free_capacity_gb = int(
(8192 - (self.cpgs[0]['UsrUsage']['usedMiB'] +
self.cpgs[0]['SDUsage']['usedMiB'])) * const)
- self.assertEqual(stats['free_capacity_gb'], 0)
- self.assertEqual(stats['pools'][0]['free_capacity_gb'],
- free_capacity_gb)
+ self.assertEqual(0, stats['free_capacity_gb'])
+ self.assertEqual(free_capacity_gb,
+ stats['pools'][0]['free_capacity_gb'])
cap_util = (float(total_capacity_gb - free_capacity_gb) /
float(total_capacity_gb)) * 100
- self.assertEqual(stats['pools'][0]['capacity_utilization'],
- cap_util)
- self.assertEqual(stats['pools'][0]['total_volumes'], 3)
- self.assertEqual(stats['pools'][0]['goodness_function'],
- GOODNESS_FUNCTION)
- self.assertEqual(stats['pools'][0]['filter_function'],
- FILTER_FUNCTION)
+ self.assertEqual(cap_util,
+ stats['pools'][0]['capacity_utilization'])
+ self.assertEqual(3, stats['pools'][0]['total_volumes'])
+ self.assertEqual(GOODNESS_FUNCTION,
+ stats['pools'][0]['goodness_function'])
+ self.assertEqual(FILTER_FUNCTION,
+ stats['pools'][0]['filter_function'])
def test_create_host(self):
# setup_mock_client drive with default configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
- self.assertEqual(auth_username, None)
- self.assertEqual(auth_password, None)
+ self.assertEqual(self.FAKE_HOST, host['name'])
+ self.assertEqual(None, auth_username)
+ self.assertEqual(None, auth_password)
def test_create_host_chap_enabled(self):
# setup_mock_client drive with CHAP enabled configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
- self.assertEqual(auth_username, 'test-user')
- self.assertEqual(auth_password, 'test-pass')
+ self.assertEqual(self.FAKE_HOST, host['name'])
+ self.assertEqual('test-user', auth_username)
+ self.assertEqual('test-pass', auth_password)
def test_create_invalid_host(self):
# setup_mock_client drive with default configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], 'fakehost.foo')
- self.assertEqual(auth_username, None)
- self.assertEqual(auth_password, None)
+ self.assertEqual('fakehost.foo', host['name'])
+ self.assertEqual(None, auth_username)
+ self.assertEqual(None, auth_password)
def test_create_invalid_host_chap_enabled(self):
# setup_mock_client drive with CHAP enabled configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], 'fakehost.foo')
- self.assertEqual(auth_username, 'test-user')
- self.assertEqual(auth_password, 'test-pass')
+ self.assertEqual('fakehost.foo', host['name'])
+ self.assertEqual('test-user', auth_username)
+ self.assertEqual('test-pass', auth_password)
def test_create_modify_host(self):
# setup_mock_client drive with default configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
- self.assertEqual(auth_username, None)
- self.assertEqual(auth_password, None)
- self.assertEqual(len(host['FCPaths']), 2)
+ self.assertEqual(self.FAKE_HOST, host['name'])
+ self.assertEqual(None, auth_username)
+ self.assertEqual(None, auth_password)
+ self.assertEqual(2, len(host['FCPaths']))
def test_create_modify_host_chap_enabled(self):
# setup_mock_client drive with CHAP enabled configuration
mock_client.assert_has_calls(expected)
- self.assertEqual(host['name'], self.FAKE_HOST)
- self.assertEqual(auth_username, 'test-user')
- self.assertEqual(auth_password, 'test-pass')
- self.assertEqual(len(host['FCPaths']), 2)
+ self.assertEqual(self.FAKE_HOST, host['name'])
+ self.assertEqual('test-user', auth_username)
+ self.assertEqual('test-pass', auth_password)
+ self.assertEqual(2, len(host['FCPaths']))
def test_get_least_used_nsp_for_host_single(self):
# setup_mock_client drive with default configuration
self.driver.initialize_iscsi_ports(common)
nsp = self.driver._get_least_used_nsp_for_host(common, 'newhost')
- self.assertEqual(nsp, "1:8:1")
+ self.assertEqual("1:8:1", nsp)
def test_get_least_used_nsp_for_host_new(self):
# setup_mock_client drive with default configuration
# Host 'newhost' does not yet have any iscsi paths,
# so the 'least used' is returned
nsp = self.driver._get_least_used_nsp_for_host(common, 'newhost')
- self.assertEqual(nsp, "1:8:2")
+ self.assertEqual("1:8:2", nsp)
def test_get_least_used_nsp_for_host_reuse(self):
# setup_mock_client drive with default configuration
# hosts 'foo' and 'bar' already have active iscsi paths
# the same one should be used
nsp = self.driver._get_least_used_nsp_for_host(common, 'foo')
- self.assertEqual(nsp, "1:8:2")
+ self.assertEqual("1:8:2", nsp)
nsp = self.driver._get_least_used_nsp_for_host(common, 'bar')
- self.assertEqual(nsp, "1:8:1")
+ self.assertEqual("1:8:1", nsp)
def test_get_least_used_nps_for_host_fc(self):
# setup_mock_client drive with default configuration
self.driver.initialize_iscsi_ports(common)
nsp = self.driver._get_least_used_nsp_for_host(common, 'newhost')
- self.assertNotEqual(nsp, "0:6:3")
- self.assertEqual(nsp, "1:8:1")
+ self.assertNotEqual("0:6:3", nsp)
+ self.assertEqual("1:8:1", nsp)
def test_invalid_iscsi_ip(self):
config = self.setup_configuration()
vluns = common.client.getVLUNs()
nsp = self.driver._get_least_used_nsp(common, vluns['members'],
['0:2:1', '1:8:1'])
- self.assertEqual(nsp, '1:8:1')
+ self.assertEqual('1:8:1', nsp)
ports = [
{'portPos': {'node': 1, 'slot': 2, 'cardPort': 1},
vluns = common.client.getVLUNs()
nsp = self.driver._get_least_used_nsp(common, vluns['members'],
['0:2:1', '1:2:1'])
- self.assertEqual(nsp, '1:2:1')
+ self.assertEqual('1:2:1', nsp)
ports = [
{'portPos': {'node': 1, 'slot': 2, 'cardPort': 1},
vluns = common.client.getVLUNs()
nsp = self.driver._get_least_used_nsp(common, vluns['members'],
['1:1:1', '1:2:1'])
- self.assertEqual(nsp, '1:1:1')
+ self.assertEqual('1:1:1', nsp)
def test_set_3par_chaps(self):
# setup_mock_client drive with default configuration
common = self.driver._login()
model = self.driver._do_export(common, volume)
mock_client.assert_has_calls(expected)
- self.assertEqual(model, expected_model)
+ self.assertEqual(expected_model, model)
def test_ensure_export(self):
# setup_mock_client drive with default configuration
self.standard_login +
expected +
self.standard_logout)
- self.assertEqual(model, expected_model)
+ self.assertEqual(expected_model, model)
mock_client.getAllVolumeMetaData.return_value = {
'total': 2,
self.standard_login +
expected +
self.standard_logout)
- self.assertEqual(model, expected_model)
+ self.assertEqual(expected_model, model)
def test_ensure_export_missing_volume(self):
# setup_mock_client drive with default configuration
self.standard_login +
expected +
self.standard_logout)
- self.assertEqual(model, expected_model)
+ self.assertEqual(expected_model, model)
@mock.patch.object(volume_types, 'get_volume_type')
def test_get_volume_settings_default_pool(self, _mock_volume_types):
'id': 'd03338a9-9115-48a3-8dfc-35cdfcdc15a7'}
pool = volume_utils.extract_host(volume['host'], 'pool')
model = common.get_volume_settings_from_type_id('gold-id', pool)
- self.assertEqual(model['cpg'], 'pool_foo')
+ self.assertEqual('pool_foo', model['cpg'])
def test_get_model_update(self):
mock_client = self.setup_driver()
common = self.driver._login()
model_update = common._get_model_update('xxx@yyy#zzz', 'CPG')
- self.assertEqual(model_update, {'host': 'xxx@yyy#CPG'})
+ self.assertEqual({'host': 'xxx@yyy#CPG'}, model_update)
VLUNS5_RET = ({'members':
[{'portPos': {'node': 0, 'slot': 8, 'cardPort': 2},
<response description="Operation succeeded."
name="CliqSuccess" processingTime="181" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['volumeName'], self.volume_name)
- self.assertEqual(cliq_args['thinProvision'], '1')
- self.assertEqual(cliq_args['size'], '1GB')
+ self.assertEqual(self.volume_name, cliq_args['volumeName'])
+ self.assertEqual('1', cliq_args['thinProvision'])
+ self.assertEqual('1GB', cliq_args['size'])
return output, None
def delete_volume(cliq_args):
<response description="Operation succeeded."
name="CliqSuccess" processingTime="164" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['volumeName'], self.volume_name)
- self.assertEqual(cliq_args['prompt'], 'false')
+ self.assertEqual(self.volume_name, cliq_args['volumeName'])
+ self.assertEqual('false', cliq_args['prompt'])
return output, None
def extend_volume(cliq_args):
<response description="Operation succeeded."
name="CliqSuccess" processingTime="181" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['volumeName'], self.volume_name)
- self.assertEqual(cliq_args['size'], '2GB')
+ self.assertEqual(self.volume_name, cliq_args['volumeName'])
+ self.assertEqual('2GB', cliq_args['size'])
return output, None
def assign_volume(cliq_args):
<response description="Operation succeeded."
name="CliqSuccess" processingTime="174" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['volumeName'], self.volume_name)
- self.assertEqual(cliq_args['serverName'],
- self.connector['host'])
+ self.assertEqual(self.volume_name, cliq_args['volumeName'])
+ self.assertEqual(self.connector['host'],
+ cliq_args['serverName'])
return output, None
def unassign_volume(cliq_args):
<response description="Operation succeeded."
name="CliqSuccess" processingTime="205" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['volumeName'], self.volume_name)
- self.assertEqual(cliq_args['serverName'],
- self.connector['host'])
+ self.assertEqual(self.volume_name, cliq_args['volumeName'])
+ self.assertEqual(self.connector['host'],
+ cliq_args['serverName'])
return output, None
def create_snapshot(cliq_args):
<response description="Operation succeeded."
name="CliqSuccess" processingTime="181" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['snapshotName'], self.snapshot_name)
- self.assertEqual(cliq_args['volumeName'], self.volume_name)
+ self.assertEqual(self.snapshot_name, cliq_args['snapshotName'])
+ self.assertEqual(self.volume_name, cliq_args['volumeName'])
return output, None
def delete_snapshot(cliq_args):
<response description="Operation succeeded."
name="CliqSuccess" processingTime="164" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['snapshotName'], self.snapshot_name)
- self.assertEqual(cliq_args['prompt'], 'false')
+ self.assertEqual(self.snapshot_name, cliq_args['snapshotName'])
+ self.assertEqual('false', cliq_args['prompt'])
return output, None
def create_volume_from_snapshot(cliq_args):
<response description="Operation succeeded."
name="CliqSuccess" processingTime="181" result="0"/>
</gauche>"""
- self.assertEqual(cliq_args['snapshotName'], self.snapshot_name)
- self.assertEqual(cliq_args['volumeName'], self.volume_name)
+ self.assertEqual(self.snapshot_name, cliq_args['snapshotName'])
+ self.assertEqual(self.volume_name, cliq_args['volumeName'])
return output, None
def get_cluster_info(cliq_args):
'</gauche>\n ')
return output, None
- self.assertEqual(cliq_args['output'], 'XML')
+ self.assertEqual('XML', cliq_args['output'])
try:
verbs = {'createVolume': create_volume,
'deleteVolume': delete_volume,
model_update = self.driver.create_volume(volume)
expected_iqn = "iqn.2003-10.com.lefthandnetworks:group01:25366:fakev 0"
expected_location = "10.0.1.6:3260,1 %s" % expected_iqn
- self.assertEqual(model_update['provider_location'], expected_location)
+ self.assertEqual(expected_location, model_update['provider_location'])
expected = [
mock.call(
volume = {'name': self.volume_name}
result = self.driver.initialize_connection(volume,
self.connector)
- self.assertEqual(result['driver_volume_type'], 'iscsi')
+ self.assertEqual('iscsi', result['driver_volume_type'])
self.assertDictMatch(result['data'], self.properties)
expected = [
snapshot)
expected_iqn = "iqn.2003-10.com.lefthandnetworks:group01:25366:fakev 0"
expected_location = "10.0.1.6:3260,1 %s" % expected_iqn
- self.assertEqual(model_update['provider_location'], expected_location)
+ self.assertEqual(expected_location, model_update['provider_location'])
expected = [
mock.call(
mock_cliq_run = self.setup_driver()
volume_stats = self.driver.get_volume_stats(True)
- self.assertEqual(volume_stats['vendor_name'], 'Hewlett-Packard')
- self.assertEqual(volume_stats['storage_protocol'], 'iSCSI')
+ self.assertEqual('Hewlett-Packard', volume_stats['vendor_name'])
+ self.assertEqual('iSCSI', volume_stats['storage_protocol'])
expected = [
mock.call('getClusterInfo', {
'_get_capacity_info',
return_value=(fake_avail, fake_size, fake_used)):
stats = drv.get_volume_stats()
- self.assertEqual(stats['volume_backend_name'], 'IBMNAS_NFS')
- self.assertEqual(stats['storage_protocol'], 'nfs')
- self.assertEqual(stats['driver_version'], '1.1.0')
- self.assertEqual(stats['vendor_name'], 'IBM')
+ self.assertEqual('IBMNAS_NFS', stats['volume_backend_name'])
+ self.assertEqual('nfs', stats['storage_protocol'])
+ self.assertEqual('1.1.0', stats['driver_version'])
+ self.assertEqual('IBM', stats['vendor_name'])
@mock.patch('cinder.volume.drivers.ibm.ibmnas.IBMNAS_NFSDriver._run_ssh')
def test_ssh_operation(self, mock_ssh):
mock.sentinel.disk_format,
run_as_root=True)
mock_info.assert_called_with(temp_file, run_as_root=True)
- self.assertEqual(mock_info.call_count, 2)
+ self.assertEqual(2, mock_info.call_count)
mock_open.assert_called_once_with(temp_file, 'rb')
image_service.update.assert_called_once_with(
ctxt, image_meta['id'], {},
mock.sentinel.disk_format,
run_as_root=True)
mock_info.assert_called_with(temp_file, run_as_root=True)
- self.assertEqual(mock_info.call_count, 2)
+ self.assertEqual(2, mock_info.call_count)
self.assertFalse(image_service.update.called)
connection_info = self.driver.initialize_connection(self.volume,
self.connector)
- self.assertEqual(connection_info['driver_volume_type'], 'iscsi')
+ self.assertEqual('iscsi', connection_info['driver_volume_type'])
properties = connection_info['data']
if not properties:
raise AssertionError('Target portal is none')
connector_new = {'initiator': 'iqn.1993-08.org.debian:01:1001'}
connection_info = self.driver.initialize_connection(self.volume,
connector_new)
- self.assertEqual(connection_info['driver_volume_type'], 'iscsi')
+ self.assertEqual('iscsi', connection_info['driver_volume_type'])
properties = connection_info['data']
if not properties:
raise AssertionError('Target portal is none')
def test_vol_stats(self):
self.mock_object(client_base.Client, 'provide_ems')
stats = self.driver.get_volume_stats(refresh=True)
- self.assertEqual(stats['vendor_name'], 'NetApp')
+ self.assertEqual('NetApp', stats['vendor_name'])
def test_create_vol_snapshot_diff_size_resize(self):
self.driver.create_volume(self.volume)
configuration.netapp_controller_ips = '127.0.0.1,127.0.0.3'
driver = common.NetAppDriver(configuration=configuration)
driver.do_setup(context='context')
- self.assertEqual(driver.library._client.get_system_id(),
- '1fa6efb5-f07b-4de4-9f0e-52e5f7ff5d1b')
+ self.assertEqual('1fa6efb5-f07b-4de4-9f0e-52e5f7ff5d1b',
+ driver.library._client.get_system_id())
def test_check_system_pwd_not_sync(self):
def list_system():
pool = self.driver.get_pool({'name_id': 'fake-uuid'})
- self.assertEqual(pool, 'ddp1')
+ self.assertEqual('ddp1', pool)
def test_get_pool_no_pools(self):
self.mock_object(self.library, '_get_volume',
pool = self.driver.get_pool({'name_id': 'fake-uuid'})
- self.assertEqual(pool, None)
+ self.assertEqual(None, pool)
@mock.patch.object(library.NetAppESeriesLibrary, '_create_volume',
mock.Mock())
portals = [{'controller': 'ctrl2', 'iqn': 'iqn2'},
{'controller': 'ctrl1', 'iqn': 'iqn1'}]
portal = self.library._get_iscsi_portal_for_vol(volume, portals)
- self.assertEqual(portal, {'controller': 'ctrl1', 'iqn': 'iqn1'})
+ self.assertEqual({'controller': 'ctrl1', 'iqn': 'iqn1'}, portal)
portal = self.library._get_iscsi_portal_for_vol(vol_nomatch, portals)
- self.assertEqual(portal, {'controller': 'ctrl2', 'iqn': 'iqn2'})
+ self.assertEqual({'controller': 'ctrl2', 'iqn': 'iqn2'}, portal)
def test_portal_for_vol_any_false(self):
vol_nomatch = {'id': 'vol_id', 'currentManager': 'ctrl3'}
loc = drv.create_volume_from_snapshot(volume, snapshot)
- self.assertEqual(loc, expected_result)
+ self.assertEqual(expected_result, loc)
mox.VerifyAll()
def test_get_pool(self):
pool = self._driver.get_pool({'provider_location': 'fake-share'})
- self.assertEqual(pool, 'fake-share')
+ self.assertEqual('fake-share', pool)
def _set_config(self, configuration):
configuration.netapp_storage_family = 'ontap_cluster'
def test_get_pool(self):
pool = self._driver.get_pool({'provider_location': 'fake-share'})
- self.assertEqual(pool, 'fake-share')
+ self.assertEqual('fake-share', pool)
def _set_config(self, configuration):
super(NetApp7modeNfsDriverTestCase, self)._set_config(
self.mox.VerifyAll()
for vol in res_vols:
if vol.id['name'] == 'volc':
- self.assertEqual(vol.sis['compression'], False)
- self.assertEqual(vol.sis['dedup'], False)
+ self.assertEqual(False, vol.sis['compression'])
+ self.assertEqual(False, vol.sis['dedup'])
else:
pass
na_server, vserver, volume='vola')
self.mox.VerifyAll()
- self.assertEqual(len(res_vols), 1)
+ self.assertEqual(1, len(res_vols))
def test_get_cluster_ssc(self):
"""Test get cluster ssc map."""
res_map = ssc_cmode.get_cluster_ssc(na_server, vserver)
self.mox.VerifyAll()
- self.assertEqual(len(res_map['mirrored']), 1)
- self.assertEqual(len(res_map['dedup']), 3)
- self.assertEqual(len(res_map['compression']), 1)
- self.assertEqual(len(res_map['thin']), 2)
- self.assertEqual(len(res_map['all']), 5)
+ self.assertEqual(1, len(res_map['mirrored']))
+ self.assertEqual(3, len(res_map['dedup']))
+ self.assertEqual(1, len(res_map['compression']))
+ self.assertEqual(2, len(res_map['thin']))
+ self.assertEqual(5, len(res_map['all']))
def test_vols_for_boolean_specs(self):
"""Test ssc for boolean specs."""
# type
extra_specs = {test_map[type][0]: 'true'}
res = ssc_cmode.get_volumes_for_specs(ssc_map, extra_specs)
- self.assertEqual(len(res), len(ssc_map[type]))
+ self.assertEqual(len(ssc_map[type]), len(res))
# opposite type
extra_specs = {test_map[type][1]: 'true'}
res = ssc_cmode.get_volumes_for_specs(ssc_map, extra_specs)
- self.assertEqual(len(res), len(ssc_map['all'] - ssc_map[type]))
+ self.assertEqual(len(ssc_map['all'] - ssc_map[type]), len(res))
# both types
extra_specs =\
{test_map[type][0]: 'true', test_map[type][1]: 'true'}
res = ssc_cmode.get_volumes_for_specs(ssc_map, extra_specs)
- self.assertEqual(len(res), len(ssc_map['all']))
+ self.assertEqual(len(ssc_map['all']), len(res))
def test_vols_for_optional_specs(self):
"""Test ssc for optional specs."""
{'netapp_dedup': 'true',
'netapp:raid_type': 'raid4', 'netapp:disk_type': 'SSD'}
res = ssc_cmode.get_volumes_for_specs(self.ssc_map, extra_specs)
- self.assertEqual(len(res), 1)
+ self.assertEqual(1, len(res))
def test_get_volumes_for_specs_none_specs(self):
none_specs = None
na_server = api.NaServer('127.0.0.1')
na_server.set_api_version(1, 15)
vols = ssc_cmode.query_cluster_vols_for_ssc(na_server, 'Openstack')
- self.assertEqual(len(vols), 2)
+ self.assertEqual(2, len(vols))
for vol in vols:
if vol.id['name'] != 'iscsi' or vol.id['name'] != 'nfsvol':
pass
na_server = api.NaServer('127.0.0.1')
aggr_attribs = ssc_cmode.query_aggr_options(na_server, 'aggr0')
if aggr_attribs:
- self.assertEqual(aggr_attribs['ha_policy'], 'cfo')
- self.assertEqual(aggr_attribs['raid_type'], 'raid_dp')
+ self.assertEqual('cfo', aggr_attribs['ha_policy'])
+ self.assertEqual('raid_dp', aggr_attribs['raid_type'])
else:
raise exception.InvalidParameterValue("Incorrect aggr options")
def test_query_aggr_storage_disk(self):
na_server = api.NaServer('127.0.0.1')
eff_disk_type = ssc_cmode.query_aggr_storage_disk(na_server, 'aggr0')
- self.assertEqual(eff_disk_type, 'SATA')
+ self.assertEqual('SATA', eff_disk_type)
{'key1': 'newvalue1',
'key2': 'value2'})
specs = qos_specs.get_qos_specs(self.ctxt, specs_id)
- self.assertEqual(specs['specs']['key1'], 'newvalue1')
- self.assertEqual(specs['specs']['key2'], 'value2')
+ self.assertEqual('newvalue1', specs['specs']['key1'])
+ self.assertEqual('value2', specs['specs']['key2'])
self.stubs.Set(db, 'qos_specs_update', fake_db_update)
self.assertRaises(exception.QoSSpecsUpdateFailed,
qos_specs.associate_qos_with_type(self.ctxt, specs_id,
type_ref['id'])
res = qos_specs.get_associations(self.ctxt, specs_id)
- self.assertEqual(len(res), 1)
+ self.assertEqual(1, len(res))
self.assertEqual('TypeName', res[0]['name'])
self.assertEqual(type_ref['id'], res[0]['id'])
qos_specs.associate_qos_with_type(self.ctxt, specs_id,
type_ref['id'])
res = qos_specs.get_associations(self.ctxt, specs_id)
- self.assertEqual(len(res), 1)
+ self.assertEqual(1, len(res))
qos_specs.disassociate_qos_specs(self.ctxt, specs_id, type_ref['id'])
res = qos_specs.get_associations(self.ctxt, specs_id)
- self.assertEqual(len(res), 0)
+ self.assertEqual(0, len(res))
self.stubs.Set(db, 'qos_specs_disassociate',
fake_db_disassociate)
qos_specs.associate_qos_with_type(self.ctxt, specs_id,
type2_ref['id'])
res = qos_specs.get_associations(self.ctxt, specs_id)
- self.assertEqual(len(res), 2)
+ self.assertEqual(2, len(res))
qos_specs.disassociate_all(self.ctxt, specs_id)
res = qos_specs.get_associations(self.ctxt, specs_id)
- self.assertEqual(len(res), 0)
+ self.assertEqual(0, len(res))
self.stubs.Set(db, 'qos_specs_disassociate_all',
fake_db_disassociate_all)
'key3': 'value3',
'key4': 'value4'}}
res = qos_specs.get_all_specs(self.ctxt)
- self.assertEqual(len(res), 2)
+ self.assertEqual(2, len(res))
self.assertIn(expected1, res)
self.assertIn(expected2, res)
'consumer': 'both'}
id = self._create_qos_specs('Specs1', input)
specs = qos_specs.get_qos_specs(self.ctxt, id)
- self.assertEqual(specs['specs']['key1'], one_time_value)
+ self.assertEqual(one_time_value, specs['specs']['key1'])
self.assertRaises(exception.InvalidQoSSpecs,
qos_specs.get_qos_specs, self.ctxt, None)
self._create_qos_specs(one_time_value, input)
specs = qos_specs.get_qos_specs_by_name(self.ctxt,
one_time_value)
- self.assertEqual(specs['specs']['key1'], one_time_value)
+ self.assertEqual(one_time_value, specs['specs']['key1'])
self.assertRaises(exception.InvalidQoSSpecs,
qos_specs.get_qos_specs_by_name, self.ctxt, None)
volume = {'name': volume_type_name, 'id': 'myid'}
resource = quota.VolumeTypeResource('volumes', volume)
- self.assertEqual(resource.name, 'volumes_%s' % volume_type_name)
+ self.assertEqual('volumes_%s' % volume_type_name, resource.name)
self.assertIsNone(resource.flag)
self.assertEqual(-1, resource.default)
context,
quota_obj.resources,
parent_project_id), ], driver.called)
- self.assertEqual(result, quota_obj.resources)
+ self.assertEqual(quota_obj.resources, result)
def test_get_class_quotas(self):
context = FakeContext(None, None)
('get_class_quotas',
context, quota_obj.resources,
'test_class', False), ], driver.called)
- self.assertEqual(result1, quota_obj.resources)
- self.assertEqual(result2, quota_obj.resources)
+ self.assertEqual(quota_obj.resources, result1)
+ self.assertEqual(quota_obj.resources, result2)
def test_get_project_quotas(self):
context = FakeContext(None, None)
False,
False,
parent_project_id), ], driver.called)
- self.assertEqual(result1, quota_obj.resources)
- self.assertEqual(result2, quota_obj.resources)
+ self.assertEqual(quota_obj.resources, result1)
+ self.assertEqual(quota_obj.resources, result2)
def test_get_subproject_quotas(self):
context = FakeContext(None, None)
False,
False,
parent_project_id), ], driver.called)
- self.assertEqual(result1, quota_obj.resources)
- self.assertEqual(result2, quota_obj.resources)
+ self.assertEqual(quota_obj.resources, result1)
+ self.assertEqual(quota_obj.resources, result2)
def test_count_no_resource(self):
context = FakeContext(None, None)
quota_obj.limit_check(context, test_resource1=4, test_resource2=3,
test_resource3=2, test_resource4=1)
- self.assertEqual(driver.called, [
+ self.assertEqual([
('limit_check',
context,
quota_obj.resources,
test_resource2=3,
test_resource3=2,
test_resource4=1,),
- None), ])
+ None), ],
+ driver.called)
def test_reserve(self):
context = FakeContext(None, None)
quota_obj = self._make_quota_obj(driver)
quota_obj.commit(context, ['resv-01', 'resv-02', 'resv-03'])
- self.assertEqual(driver.called,
- [('commit',
+ self.assertEqual([('commit',
context,
['resv-01',
'resv-02',
'resv-03'],
- None), ])
+ None), ],
+ driver.called)
def test_rollback(self):
context = FakeContext(None, None)
quota_obj = self._make_quota_obj(driver)
quota_obj.rollback(context, ['resv-01', 'resv-02', 'resv-03'])
- self.assertEqual(driver.called,
- [('rollback',
+ self.assertEqual([('rollback',
context,
['resv-01',
'resv-02',
'resv-03'],
- None), ])
+ None), ],
+ driver.called)
def test_destroy_by_project(self):
context = FakeContext(None, None)
quota_obj = self._make_quota_obj(driver)
quota_obj.destroy_by_project(context, 'test_project')
- self.assertEqual(driver.called,
- [('destroy_by_project',
+ self.assertEqual([('destroy_by_project',
context,
- 'test_project'), ])
+ 'test_project'), ],
+ driver.called)
def test_expire(self):
context = FakeContext(None, None)
quota_obj = self._make_quota_obj(driver)
quota_obj.expire(context)
- self.assertEqual(driver.called, [('expire', context), ])
+ self.assertEqual([('expire', context), ], driver.called)
def test_resource_names(self):
quota_obj = self._make_quota_obj(None)
- self.assertEqual(quota_obj.resource_names,
- ['test_resource1', 'test_resource2',
- 'test_resource3', 'test_resource4'])
+ self.assertEqual(['test_resource1', 'test_resource2',
+ 'test_resource3', 'test_resource4'],
+ quota_obj.resource_names)
class VolumeTypeQuotaEngineTestCase(test.TestCase):
self.stubs.Set(db, 'volume_type_get_all', fake_vtga)
engine = quota.VolumeTypeQuotaEngine()
- self.assertEqual(engine.resource_names,
- ['backup_gigabytes', 'backups',
+ self.assertEqual(['backup_gigabytes', 'backups',
'gigabytes', 'per_volume_gigabytes',
- 'snapshots', 'volumes'])
+ 'snapshots', 'volumes'],
+ engine.resource_names)
def test_volume_type_resources(self):
ctx = context.RequestContext('admin', 'admin', is_admin=True)
result = self.driver.get_class_quotas(None, quota.QUOTAS.resources,
'test_class', False)
- self.assertEqual(self.calls, ['quota_class_get_all_by_name'])
- self.assertEqual(result, dict(volumes=10,
- gigabytes=500,
- snapshots=10,
- backups=10,
- backup_gigabytes=500))
+ self.assertEqual(['quota_class_get_all_by_name'], self.calls)
+ self.assertEqual(dict(volumes=10,
+ gigabytes=500,
+ snapshots=10,
+ backups=10,
+ backup_gigabytes=500), result)
def _stub_get_by_project(self):
def fake_qgabp(context, project_id):
FakeContext('test_project', 'test_class'),
quota.QUOTAS.resources, 'test_project')
- self.assertEqual(self.calls, ['quota_get_all_by_project',
- 'quota_usage_get_all_by_project',
- 'quota_class_get_all_by_name',
- 'quota_class_get_default', ])
- self.assertEqual(result, dict(volumes=dict(limit=10,
- in_use=2,
- reserved=0, ),
- snapshots=dict(limit=10,
- in_use=2,
- reserved=0, ),
- gigabytes=dict(limit=50,
- in_use=10,
- reserved=0, ),
- backups=dict(limit=10,
- in_use=2,
- reserved=0, ),
- backup_gigabytes=dict(limit=50,
- in_use=10,
- reserved=0, ),
- per_volume_gigabytes=dict(in_use=0,
- limit=-1,
- reserved= 0)
- ))
+ self.assertEqual(['quota_get_all_by_project',
+ 'quota_usage_get_all_by_project',
+ 'quota_class_get_all_by_name',
+ 'quota_class_get_default', ], self.calls)
+ self.assertEqual(dict(volumes=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ snapshots=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ gigabytes=dict(limit=50,
+ in_use=10,
+ reserved=0, ),
+ backups=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ backup_gigabytes=dict(limit=50,
+ in_use=10,
+ reserved=0, ),
+ per_volume_gigabytes=dict(in_use=0,
+ limit=-1,
+ reserved= 0)
+ ), result)
def test_get_subproject_quotas(self):
self._stub_get_by_subproject()
quota.QUOTAS.resources, 'test_project',
parent_project_id=parent_project_id)
- self.assertEqual(self.calls, ['quota_get_all_by_project',
- 'quota_usage_get_all_by_project', ])
- self.assertEqual(result, dict(volumes=dict(limit=10,
- in_use=2,
- reserved=0, ),
- snapshots=dict(limit=0,
- in_use=0,
- reserved=0, ),
- gigabytes=dict(limit=50,
- in_use=10,
- reserved=0, ),
- backups=dict(limit=0,
- in_use=0,
- reserved=0, ),
- backup_gigabytes=dict(limit=0,
- in_use=0,
- reserved=0, ),
- per_volume_gigabytes=dict(in_use=0,
- limit=0,
- reserved= 0)
- ))
+ self.assertEqual(['quota_get_all_by_project',
+ 'quota_usage_get_all_by_project', ], self.calls)
+ self.assertEqual(dict(volumes=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ snapshots=dict(limit=0,
+ in_use=0,
+ reserved=0, ),
+ gigabytes=dict(limit=50,
+ in_use=10,
+ reserved=0, ),
+ backups=dict(limit=0,
+ in_use=0,
+ reserved=0, ),
+ backup_gigabytes=dict(limit=0,
+ in_use=0,
+ reserved=0, ),
+ per_volume_gigabytes=dict(in_use=0,
+ limit=0,
+ reserved= 0)
+ ), result)
def test_get_project_quotas_alt_context_no_class(self):
self._stub_get_by_project()
FakeContext('other_project', 'other_class'),
quota.QUOTAS.resources, 'test_project')
- self.assertEqual(self.calls, ['quota_get_all_by_project',
- 'quota_usage_get_all_by_project',
- 'quota_class_get_default', ])
- self.assertEqual(result, dict(volumes=dict(limit=10,
- in_use=2,
- reserved=0, ),
- snapshots=dict(limit=10,
- in_use=2,
- reserved=0, ),
- gigabytes=dict(limit=50,
- in_use=10,
- reserved=0, ),
- backups=dict(limit=10,
- in_use=2,
- reserved=0, ),
- backup_gigabytes=dict(limit=50,
- in_use=10,
- reserved=0, ),
- per_volume_gigabytes=dict(in_use=0,
- limit=-1,
- reserved=0)
-
- ))
+ self.assertEqual(['quota_get_all_by_project',
+ 'quota_usage_get_all_by_project',
+ 'quota_class_get_default', ], self.calls)
+ self.assertEqual(dict(volumes=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ snapshots=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ gigabytes=dict(limit=50,
+ in_use=10,
+ reserved=0, ),
+ backups=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ backup_gigabytes=dict(limit=50,
+ in_use=10,
+ reserved=0, ),
+ per_volume_gigabytes=dict(in_use=0,
+ limit=-1,
+ reserved=0)
+ ), result)
def test_get_project_quotas_alt_context_with_class(self):
self._stub_get_by_project()
FakeContext('other_project', 'other_class'),
quota.QUOTAS.resources, 'test_project', quota_class='test_class')
- self.assertEqual(self.calls, ['quota_get_all_by_project',
- 'quota_usage_get_all_by_project',
- 'quota_class_get_all_by_name',
- 'quota_class_get_default', ])
- self.assertEqual(result, dict(volumes=dict(limit=10,
- in_use=2,
- reserved=0, ),
- snapshots=dict(limit=10,
- in_use=2,
- reserved=0, ),
- gigabytes=dict(limit=50,
- in_use=10,
- reserved=0, ),
- backups=dict(limit=10,
- in_use=2,
- reserved=0, ),
- backup_gigabytes=dict(limit=50,
- in_use=10,
- reserved=0, ),
- per_volume_gigabytes=dict(in_use=0,
- limit=-1,
- reserved= 0)
-
- ))
+ self.assertEqual(['quota_get_all_by_project',
+ 'quota_usage_get_all_by_project',
+ 'quota_class_get_all_by_name',
+ 'quota_class_get_default', ], self.calls)
+ self.assertEqual(dict(volumes=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ snapshots=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ gigabytes=dict(limit=50,
+ in_use=10,
+ reserved=0, ),
+ backups=dict(limit=10,
+ in_use=2,
+ reserved=0, ),
+ backup_gigabytes=dict(limit=50,
+ in_use=10,
+ reserved=0, ),
+ per_volume_gigabytes=dict(in_use=0,
+ limit=-1,
+ reserved= 0)),
+ result)
def test_get_project_quotas_no_defaults(self):
self._stub_get_by_project()
FakeContext('test_project', 'test_class'),
quota.QUOTAS.resources, 'test_project', defaults=False)
- self.assertEqual(self.calls, ['quota_get_all_by_project',
- 'quota_usage_get_all_by_project',
- 'quota_class_get_all_by_name',
- 'quota_class_get_default', ])
- self.assertEqual(result,
- dict(backups=dict(limit=10,
+ self.assertEqual(['quota_get_all_by_project',
+ 'quota_usage_get_all_by_project',
+ 'quota_class_get_all_by_name',
+ 'quota_class_get_default', ], self.calls)
+ self.assertEqual(dict(backups=dict(limit=10,
in_use=2,
reserved=0, ),
backup_gigabytes=dict(limit=50,
in_use=2,
reserved=0, ),
- ))
+ ), result)
def test_get_project_quotas_no_usages(self):
self._stub_get_by_project()
FakeContext('test_project', 'test_class'),
quota.QUOTAS.resources, 'test_project', usages=False)
- self.assertEqual(self.calls, ['quota_get_all_by_project',
- 'quota_class_get_all_by_name',
- 'quota_class_get_default', ])
- self.assertEqual(result, dict(volumes=dict(limit=10, ),
- snapshots=dict(limit=10, ),
- backups=dict(limit=10, ),
- gigabytes=dict(limit=50, ),
- backup_gigabytes=dict(limit=50, ),
- per_volume_gigabytes=dict(limit=-1, )))
+ self.assertEqual(['quota_get_all_by_project',
+ 'quota_class_get_all_by_name',
+ 'quota_class_get_default', ], self.calls)
+ self.assertEqual(dict(volumes=dict(limit=10, ),
+ snapshots=dict(limit=10, ),
+ backups=dict(limit=10, ),
+ gigabytes=dict(limit=50, ),
+ backup_gigabytes=dict(limit=50, ),
+ per_volume_gigabytes=dict(limit=-1, )), result)
def _stub_get_project_quotas(self):
def fake_get_project_quotas(context, resources, project_id,
self.driver._get_quotas,
None, quota.QUOTAS.resources,
['unknown'], True)
- self.assertEqual(self.calls, [])
+ self.assertEqual([], self.calls)
def test_get_quotas_no_sync_unknown(self):
self._stub_get_project_quotas()
self.driver._get_quotas,
None, quota.QUOTAS.resources,
['unknown'], False)
- self.assertEqual(self.calls, [])
+ self.assertEqual([], self.calls)
def test_get_quotas_has_sync_no_sync_resource(self):
self._stub_get_project_quotas()
self.driver._get_quotas,
None, quota.QUOTAS.resources,
['metadata_items'], True)
- self.assertEqual(self.calls, [])
+ self.assertEqual([], self.calls)
def test_get_quotas_no_sync_has_sync_resource(self):
self._stub_get_project_quotas()
self.driver._get_quotas,
None, quota.QUOTAS.resources,
['volumes'], False)
- self.assertEqual(self.calls, [])
+ self.assertEqual([], self.calls)
def test_get_quotas_has_sync(self):
self._stub_get_project_quotas()
['volumes', 'gigabytes'],
True)
- self.assertEqual(self.calls, ['get_project_quotas'])
- self.assertEqual(result, dict(volumes=10, gigabytes=1000, ))
+ self.assertEqual(['get_project_quotas'], self.calls)
+ self.assertEqual(dict(volumes=10, gigabytes=1000, ), result)
def _stub_quota_reserve(self):
def fake_quota_reserve(context, resources, quotas, deltas, expire,
FakeContext('test_project', 'test_class'),
quota.QUOTAS.resources,
dict(volumes=2), expire='invalid')
- self.assertEqual(self.calls, [])
+ self.assertEqual([], self.calls)
def test_reserve_default_expire(self):
self._stub_get_project_quotas()
dict(volumes=2))
expire = timeutils.utcnow() + datetime.timedelta(seconds=86400)
- self.assertEqual(self.calls, ['get_project_quotas',
- ('quota_reserve', expire, 0, 0), ])
- self.assertEqual(result, ['resv-1', 'resv-2', 'resv-3'])
+ self.assertEqual(['get_project_quotas',
+ ('quota_reserve', expire, 0, 0), ], self.calls)
+ self.assertEqual(['resv-1', 'resv-2', 'resv-3'], result)
def test_reserve_int_expire(self):
self._stub_get_project_quotas()
dict(volumes=2), expire=3600)
expire = timeutils.utcnow() + datetime.timedelta(seconds=3600)
- self.assertEqual(self.calls, ['get_project_quotas',
- ('quota_reserve', expire, 0, 0), ])
- self.assertEqual(result, ['resv-1', 'resv-2', 'resv-3'])
+ self.assertEqual(['get_project_quotas',
+ ('quota_reserve', expire, 0, 0), ], self.calls)
+ self.assertEqual(['resv-1', 'resv-2', 'resv-3'], result)
def test_reserve_timedelta_expire(self):
self._stub_get_project_quotas()
dict(volumes=2), expire=expire_delta)
expire = timeutils.utcnow() + expire_delta
- self.assertEqual(self.calls, ['get_project_quotas',
- ('quota_reserve', expire, 0, 0), ])
- self.assertEqual(result, ['resv-1', 'resv-2', 'resv-3'])
+ self.assertEqual(['get_project_quotas',
+ ('quota_reserve', expire, 0, 0), ], self.calls)
+ self.assertEqual(['resv-1', 'resv-2', 'resv-3'], result)
def test_reserve_datetime_expire(self):
self._stub_get_project_quotas()
quota.QUOTAS.resources,
dict(volumes=2), expire=expire)
- self.assertEqual(self.calls, ['get_project_quotas',
- ('quota_reserve', expire, 0, 0), ])
- self.assertEqual(result, ['resv-1', 'resv-2', 'resv-3'])
+ self.assertEqual(['get_project_quotas',
+ ('quota_reserve', expire, 0, 0), ], self.calls)
+ self.assertEqual(['resv-1', 'resv-2', 'resv-3'], result)
def test_reserve_until_refresh(self):
self._stub_get_project_quotas()
quota.QUOTAS.resources,
dict(volumes=2), expire=expire)
- self.assertEqual(self.calls, ['get_project_quotas',
- ('quota_reserve', expire, 500, 0), ])
- self.assertEqual(result, ['resv-1', 'resv-2', 'resv-3'])
+ self.assertEqual(['get_project_quotas',
+ ('quota_reserve', expire, 500, 0), ], self.calls)
+ self.assertEqual(['resv-1', 'resv-2', 'resv-3'], result)
def test_reserve_max_age(self):
self._stub_get_project_quotas()
quota.QUOTAS.resources,
dict(volumes=2), expire=expire)
- self.assertEqual(self.calls, ['get_project_quotas',
- ('quota_reserve', expire, 0, 86400), ])
- self.assertEqual(result, ['resv-1', 'resv-2', 'resv-3'])
+ self.assertEqual(['get_project_quotas',
+ ('quota_reserve', expire, 0, 86400), ], self.calls)
+ self.assertEqual(['resv-1', 'resv-2', 'resv-3'], result)
def _stub_quota_destroy_by_project(self):
def fake_quota_destroy_by_project(context, project_id):
self.driver.destroy_by_project(FakeContext('test_project',
'test_class'),
'test_project')
- self.assertEqual(self.calls, [('quota_destroy_by_project',
- ('test_project')), ])
+ self.assertEqual([('quota_destroy_by_project', ('test_project')), ],
+ self.calls)
class FakeSession(object):
resource = usage['resource']
for key, value in usage.items():
actual = getattr(usage_dict[resource], key)
- self.assertEqual(actual, value,
+ self.assertEqual(value, actual,
"%s != %s on usage for resource %s" %
(actual, value, resource))
for key, value in resv.items():
actual = getattr(resv_obj, key)
- self.assertEqual(actual, value,
+ self.assertEqual(value, actual,
"%s != %s on reservation for resource %s" %
(actual, value, resource))
- self.assertEqual(len(reservations), 0)
+ self.assertEqual(0, len(reservations))
def test_quota_reserve_create_usages(self):
context = FakeContext('test_project', 'test_class')
result = sqa_api.quota_reserve(context, self.resources, quotas,
deltas, self.expire, 0, 0)
- self.assertEqual(self.sync_called, set(['volumes', 'gigabytes']))
+ self.assertEqual(set(['volumes', 'gigabytes']), self.sync_called)
self.compare_usage(self.usages_created,
[dict(resource='volumes',
project_id='test_project',
result = sqa_api.quota_reserve(context, self.resources, quotas,
deltas, self.expire, 5, 0)
- self.assertEqual(self.sync_called, set(['volumes', 'gigabytes']))
+ self.assertEqual(set(['volumes', 'gigabytes']), self.sync_called)
self.compare_usage(self.usages, [dict(resource='volumes',
project_id='test_project',
in_use=2,
in_use=2,
reserved=2 * 1024,
until_refresh=5), ])
- self.assertEqual(self.usages_created, {})
+ self.assertEqual({}, self.usages_created)
self.compare_reservation(result,
[dict(resource='volumes',
usage_id=self.usages['volumes'],
result = sqa_api.quota_reserve(context, self.resources, quotas,
deltas, self.expire, 5, 0)
- self.assertEqual(self.sync_called, set(['volumes', 'gigabytes']))
+ self.assertEqual(set(['volumes', 'gigabytes']), self.sync_called)
self.compare_usage(self.usages, [dict(resource='volumes',
project_id='test_project',
in_use=2,
in_use=2,
reserved=2 * 1024,
until_refresh=5), ])
- self.assertEqual(self.usages_created, {})
+ self.assertEqual({}, self.usages_created)
self.compare_reservation(result,
[dict(resource='volumes',
usage_id=self.usages['volumes'],
result = sqa_api.quota_reserve(context, self.resources, quotas,
deltas, self.expire, 0, max_age)
- self.assertEqual(self.sync_called, set(['volumes', 'gigabytes']))
+ self.assertEqual(set(['volumes', 'gigabytes']), self.sync_called)
self.compare_usage(self.usages, [dict(resource='volumes',
project_id='test_project',
in_use=2,
in_use=2,
reserved=2 * 1024,
until_refresh=None), ])
- self.assertEqual(self.usages_created, {})
+ self.assertEqual({}, self.usages_created)
self.compare_reservation(result,
[dict(resource='volumes',
usage_id=self.usages['volumes'],
result = sqa_api.quota_reserve(context, self.resources, quotas,
deltas, self.expire, 0, 0)
- self.assertEqual(self.sync_called, set([]))
+ self.assertEqual(set([]), self.sync_called)
self.compare_usage(self.usages, [dict(resource='volumes',
project_id='test_project',
in_use=3,
in_use=3,
reserved=2 * 1024,
until_refresh=None), ])
- self.assertEqual(self.usages_created, {})
+ self.assertEqual({}, self.usages_created)
self.compare_reservation(result,
[dict(resource='volumes',
usage_id=self.usages['volumes'],
result = sqa_api.quota_reserve(context, self.resources, quotas,
deltas, self.expire, 0, 0)
- self.assertEqual(self.sync_called, set([]))
+ self.assertEqual(set([]), self.sync_called)
self.compare_usage(self.usages, [dict(resource='volumes',
project_id='test_project',
in_use=1,
in_use=1 * 1024,
reserved=0,
until_refresh=None), ])
- self.assertEqual(self.usages_created, {})
+ self.assertEqual({}, self.usages_created)
self.compare_reservation(result,
[dict(resource='volumes',
usage_id=self.usages['volumes'],
context, self.resources, quotas,
deltas, self.expire, 0, 0)
- self.assertEqual(self.sync_called, set([]))
+ self.assertEqual(set([]), self.sync_called)
self.compare_usage(self.usages, [dict(resource='volumes',
project_id='test_project',
in_use=4,
in_use=10 * 1024,
reserved=0,
until_refresh=None), ])
- self.assertEqual(self.usages_created, {})
- self.assertEqual(self.reservations_created, {})
+ self.assertEqual({}, self.usages_created)
+ self.assertEqual({}, self.reservations_created)
def test_quota_reserve_reduction(self):
self.init_usage('test_project', 'volumes', 10, 0)
result = sqa_api.quota_reserve(context, self.resources, quotas,
deltas, self.expire, 0, 0)
- self.assertEqual(self.sync_called, set([]))
+ self.assertEqual(set([]), self.sync_called)
self.compare_usage(self.usages, [dict(resource='volumes',
project_id='test_project',
in_use=10,
in_use=20 * 1024,
reserved=0,
until_refresh=None), ])
- self.assertEqual(self.usages_created, {})
+ self.assertEqual({}, self.usages_created)
self.compare_reservation(result,
[dict(resource='volumes',
usage_id=self.usages['volumes'],
info = self.driver._get_clone_info(volume, self.volume_name)
- self.assertEqual(info, parent_info)
+ self.assertEqual(parent_info, info)
self.assertFalse(volume.set_snap.called)
volume.parent_info.assert_called_once_with()
info = self.driver._get_clone_info(volume, self.volume_name,
snap=snapshot)
- self.assertEqual(info, parent_info)
+ self.assertEqual(parent_info, info)
- self.assertEqual(volume.set_snap.call_count, 2)
+ self.assertEqual(2, volume.set_snap.call_count)
volume.parent_info.assert_called_once_with()
@common_mocks
info = self.driver._get_clone_info(volume, self.volume_name,
snap=snapshot)
- self.assertEqual(info, (None, None, None))
+ self.assertEqual((None, None, None), info)
- self.assertEqual(volume.set_snap.call_count, 2)
+ self.assertEqual(2, volume.set_snap.call_count)
volume.parent_info.assert_called_once_with()
# Make sure the exception was raised
self.assertEqual(RAISED_EXCEPTIONS, [self.mock_rbd.ImageNotFound])
info = self.driver._get_clone_info(volume,
"%s.deleted" % (self.volume_name))
- self.assertEqual(info, parent_info)
+ self.assertEqual(parent_info, info)
self.assertFalse(volume.set_snap.called)
volume.parent_info.assert_called_once_with()
kwargs = {'features': client.features}
self.mock_rbd.RBD.return_value.clone.assert_called_once_with(
*args, **kwargs)
- self.assertEqual(client.__enter__.call_count, 2)
+ self.assertEqual(2, client.__enter__.call_count)
@common_mocks
def test_extend_volume(self):
# Expect no timeout if default is used
self.mock_rados.Rados.return_value.connect.assert_called_once_with()
self.assertTrue(self.mock_rados.Rados.return_value.open_ioctx.called)
- self.assertEqual(ret[1], self.mock_rados.Rados.return_value.ioctx)
+ self.assertEqual(self.mock_rados.Rados.return_value.ioctx, ret[1])
self.mock_rados.Rados.return_value.open_ioctx.assert_called_with(
self.cfg.rbd_pool)
ret = self.driver._connect_to_rados('alt_pool')
self.assertTrue(self.mock_rados.Rados.return_value.connect.called)
self.assertTrue(self.mock_rados.Rados.return_value.open_ioctx.called)
- self.assertEqual(ret[1], self.mock_rados.Rados.return_value.ioctx)
+ self.assertEqual(self.mock_rados.Rados.return_value.ioctx, ret[1])
self.mock_rados.Rados.return_value.open_ioctx.assert_called_with(
'alt_pool')
def test_init(self):
self.assertEqual(self.mock_rbd_wrapper._rbd_meta, self.meta)
- self.assertEqual(self.mock_rbd_wrapper._offset, 0)
+ self.assertEqual(0, self.mock_rbd_wrapper._offset)
def test_inc_offset(self):
self.mock_rbd_wrapper._inc_offset(10)
self.mock_rbd_wrapper._inc_offset(10)
- self.assertEqual(self.mock_rbd_wrapper._offset, 20)
+ self.assertEqual(20, self.mock_rbd_wrapper._offset)
def test_rbd_image(self):
self.assertEqual(self.mock_rbd_wrapper.rbd_image, self.meta.image)
self.meta.image.size.return_value = self.data_length
data = self.mock_rbd_wrapper.read()
- self.assertEqual(data, self.full_data)
+ self.assertEqual(self.full_data, data)
data = self.mock_rbd_wrapper.read()
- self.assertEqual(data, '')
+ self.assertEqual('', data)
self.mock_rbd_wrapper.seek(0)
data = self.mock_rbd_wrapper.read()
- self.assertEqual(data, self.full_data)
+ self.assertEqual(self.full_data, data)
self.mock_rbd_wrapper.seek(0)
data = self.mock_rbd_wrapper.read(10)
- self.assertEqual(data, self.full_data[:10])
+ self.assertEqual(self.full_data[:10], data)
def test_write(self):
self.mock_rbd_wrapper.write(self.full_data)
- self.assertEqual(self.mock_rbd_wrapper._offset, 1024)
+ self.assertEqual(1024, self.mock_rbd_wrapper._offset)
def test_seekable(self):
self.assertTrue(self.mock_rbd_wrapper.seekable)
def test_seek(self):
- self.assertEqual(self.mock_rbd_wrapper._offset, 0)
+ self.assertEqual(0, self.mock_rbd_wrapper._offset)
self.mock_rbd_wrapper.seek(10)
- self.assertEqual(self.mock_rbd_wrapper._offset, 10)
+ self.assertEqual(10, self.mock_rbd_wrapper._offset)
self.mock_rbd_wrapper.seek(10)
- self.assertEqual(self.mock_rbd_wrapper._offset, 10)
+ self.assertEqual(10, self.mock_rbd_wrapper._offset)
self.mock_rbd_wrapper.seek(10, 1)
- self.assertEqual(self.mock_rbd_wrapper._offset, 20)
+ self.assertEqual(20, self.mock_rbd_wrapper._offset)
self.mock_rbd_wrapper.seek(0)
self.mock_rbd_wrapper.write(self.full_data)
self.meta.image.size.return_value = self.data_length
self.mock_rbd_wrapper.seek(0)
- self.assertEqual(self.mock_rbd_wrapper._offset, 0)
+ self.assertEqual(0, self.mock_rbd_wrapper._offset)
self.mock_rbd_wrapper.seek(10, 2)
- self.assertEqual(self.mock_rbd_wrapper._offset, self.data_length + 10)
+ self.assertEqual(self.data_length + 10, self.mock_rbd_wrapper._offset)
self.mock_rbd_wrapper.seek(-10, 2)
- self.assertEqual(self.mock_rbd_wrapper._offset, self.data_length - 10)
+ self.assertEqual(self.data_length - 10, self.mock_rbd_wrapper._offset)
# test exceptions.
self.assertRaises(IOError, self.mock_rbd_wrapper.seek, 0, 3)
self.assertRaises(IOError, self.mock_rbd_wrapper.seek, -1)
# offset should not have been changed by any of the previous
# operations.
- self.assertEqual(self.mock_rbd_wrapper._offset, self.data_length - 10)
+ self.assertEqual(self.data_length - 10, self.mock_rbd_wrapper._offset)
def test_tell(self):
- self.assertEqual(self.mock_rbd_wrapper.tell(), 0)
+ self.assertEqual(0, self.mock_rbd_wrapper.tell())
self.mock_rbd_wrapper._inc_offset(10)
- self.assertEqual(self.mock_rbd_wrapper.tell(), 10)
+ self.assertEqual(10, self.mock_rbd_wrapper.tell())
def test_flush(self):
with mock.patch.object(driver, 'LOG') as mock_logger:
request_spec={'image_id': image_id})
volume = db.volume_get(self.context, volume_id)
- self.assertEqual(volume['status'], expected_status)
+ self.assertEqual(expected_status, volume['status'])
finally:
# cleanup
db.volume_destroy(self.context, volume_id)
{'replication_status': 'inactive'}
self.manager.promote_replica(self.adm_ctxt, vol['id'])
vol_after = db.volume_get(self.ctxt, vol['id'])
- self.assertEqual(vol_after['replication_status'], 'inactive')
+ self.assertEqual('inactive', vol_after['replication_status'])
def test_promote_replica_fail(self):
"""Test promote replication when promote fails."""
{'replication_status': 'copying'}
self.manager.reenable_replication(self.adm_ctxt, vol['id'])
vol_after = db.volume_get(self.ctxt, vol['id'])
- self.assertEqual(vol_after['replication_status'], 'copying')
+ self.assertEqual('copying', vol_after['replication_status'])
@mock.patch('cinder.utils.require_driver_initialized')
def test_reenable_replication_uninit_driver(self, _init):
def test_local_path(self):
"""Expected behaviour for local_path."""
- self.assertEqual(self._driver.local_path(self.TEST_VOLUME),
- self.TEST_VOLPATH)
+ self.assertEqual(self.TEST_VOLPATH,
+ self._driver.local_path(self.TEST_VOLUME))
def test_create_volume(self):
"""Expected behaviour for create_volume."""
ret = self._driver.create_volume(self.TEST_VOLUME)
- self.assertEqual(ret['provider_location'],
- os.path.join(self.TEST_VOLDIR,
- self.TEST_VOLNAME))
+ self.assertEqual(os.path.join(self.TEST_VOLDIR,
+ self.TEST_VOLNAME),
+ ret['provider_location'])
self.assertTrue(os.path.isfile(self.TEST_VOLPATH))
- self.assertEqual(os.stat(self.TEST_VOLPATH).st_size,
- 1 * units.Gi)
+ self.assertEqual(1 * units.Gi,
+ os.stat(self.TEST_VOLPATH).st_size)
def test_delete_volume(self):
"""Expected behaviour for delete_volume."""
def test_initialize_connection(self):
"""Expected behaviour for initialize_connection."""
ret = self._driver.initialize_connection(self.TEST_VOLUME, None)
- self.assertEqual(ret['driver_volume_type'], 'scality')
- self.assertEqual(ret['data']['sofs_path'],
- os.path.join(self.TEST_VOLDIR,
- self.TEST_VOLNAME))
+ self.assertEqual('scality', ret['driver_volume_type'])
+ self.assertEqual(os.path.join(self.TEST_VOLDIR, self.TEST_VOLNAME),
+ ret['data']['sofs_path'])
self.assertEqual(self.TEST_VOLDIR, ret['data']['export'])
self.assertEqual(self.TEST_VOLNAME, ret['data']['name'])
else:
self._smbfs_driver.do_setup(mock.sentinel.context)
mock_check_qemu_img_version.assert_called_once_with()
- self.assertEqual(self._smbfs_driver.shares, {})
+ self.assertEqual({}, self._smbfs_driver.shares)
fake_ensure_mounted.assert_called_once_with()
def test_setup_missing_shares_config_option(self):
self._FAKE_VOLUME['size'])
# The eligible share with the minimum allocated space
# will be selected
- self.assertEqual(ret_value, 'fake_share3')
+ self.assertEqual('fake_share3', ret_value)
def test_find_share(self):
self._test_find_share()
def test_get_existing_raw_volume_format(self):
fmt = self._mock_get_volume_format()
- self.assertEqual(fmt, 'raw')
+ self.assertEqual('raw', fmt)
def test_get_new_vhd_volume_format(self):
expected_fmt = 'vhd'
self.configuration.sf_emulate_512 = False
model_update = sfv.create_volume(testvol)
self.configuration.sf_emulate_512 = True
- self.assertEqual(model_update.get('provider_geometry', None),
- '4096 4096')
+ self.assertEqual('4096 4096',
+ model_update.get('provider_geometry', None))
def test_create_delete_snapshot(self):
testsnap = {'project_id': 'testprjid',
qos_ref['id'],
type_ref['id'])
qos = sfv._set_qos_by_volume_type(self.ctxt, type_ref['id'])
- self.assertEqual(qos, self.expected_qos_results)
+ self.assertEqual(self.expected_qos_results, qos)
def test_set_by_qos_spec(self):
sfv = solidfire.SolidFireDriver(configuration=self.configuration)
qos_ref['id'],
type_ref['id'])
qos = sfv._set_qos_by_volume_type(self.ctxt, type_ref['id'])
- self.assertEqual(qos, self.expected_qos_results)
+ self.assertEqual(self.expected_qos_results, qos)
def test_set_by_qos_by_type_only(self):
sfv = solidfire.SolidFireDriver(configuration=self.configuration)
"qos:burstIOPS": "300",
"qos:maxIOPS": "200"})
qos = sfv._set_qos_by_volume_type(self.ctxt, type_ref['id'])
- self.assertEqual(qos, {'minIOPS': 100,
- 'maxIOPS': 200,
- 'burstIOPS': 300})
+ self.assertEqual({'minIOPS': 100,
+ 'maxIOPS': 200,
+ 'burstIOPS': 300}, qos)
def test_accept_transfer(self):
sfv = solidfire.SolidFireDriver(configuration=self.configuration)
'id': 'a720b3c0-d1f0-11e1-9b23-0800200c9a66',
'created_at': timeutils.utcnow()}
expected = {'provider_auth': 'CHAP cinder-new_project 123456789012'}
- self.assertEqual(sfv.accept_transfer(self.ctxt,
+ self.assertEqual(expected,
+ sfv.accept_transfer(self.ctxt,
testvol,
- 'new_user', 'new_project'),
- expected)
+ 'new_user', 'new_project'))
def test_accept_transfer_volume_not_found_raises(self):
sfv = solidfire.SolidFireDriver(configuration=self.configuration)
self.fake_issue_api_request)
sfv = solidfire.SolidFireDriver(configuration=self.configuration)
sfv._update_cluster_status()
- self.assertEqual(sfv.cluster_stats['free_capacity_gb'], 99.0)
- self.assertEqual(sfv.cluster_stats['total_capacity_gb'], 100.0)
+ self.assertEqual(99.0, sfv.cluster_stats['free_capacity_gb'])
+ self.assertEqual(100.0, sfv.cluster_stats['total_capacity_gb'])
def test_manage_existing_volume(self):
external_ref = {'name': 'existing volume', 'source-id': 5}
def _assert_vol_exists(self, name, exists):
is_vol_defined = self.driver._helpers.is_vdisk_defined(name)
- self.assertEqual(is_vol_defined, exists)
+ self.assertEqual(exists, is_vol_defined)
def test_storwize_svc_connectivity(self):
# Make sure we detect if the pool doesn't exist
try:
if k[0] == '-':
k = k[1:]
- self.assertNotEqual(attrs[k], v)
+ self.assertNotEqual(v, attrs[k])
else:
- self.assertEqual(attrs[k], v)
+ self.assertEqual(v, attrs[k])
except processutils.ProcessExecutionError as e:
if 'CMMVC7050E' not in e.stderr:
raise
# Initialize connection from the first volume to a host
ret = self.driver.initialize_connection(volume1, self._connector)
- self.assertEqual(ret['driver_volume_type'],
- expected[protocol]['driver_volume_type'])
+ self.assertEqual(expected[protocol]['driver_volume_type'],
+ ret['driver_volume_type'])
for k, v in expected[protocol]['data'].items():
- self.assertEqual(ret['data'][k], v)
+ self.assertEqual(v, ret['data'][k])
# Initialize again, should notice it and do nothing
ret = self.driver.initialize_connection(volume1, self._connector)
- self.assertEqual(ret['driver_volume_type'],
- expected[protocol]['driver_volume_type'])
+ self.assertEqual(expected[protocol]['driver_volume_type'],
+ ret['driver_volume_type'])
for k, v in expected[protocol]['data'].items():
- self.assertEqual(ret['data'][k], v)
+ self.assertEqual(v, ret['data'][k])
# Try to delete the 1st volume (should fail because it is mapped)
self.assertRaises(exception.VolumeBackendAPIException,
ret = self.driver.initialize_connection(volume2,
self._connector)
self.assertEqual(
- ret['driver_volume_type'],
- expected_fc_npiv['driver_volume_type'])
+ expected_fc_npiv['driver_volume_type'],
+ ret['driver_volume_type'])
for k, v in expected_fc_npiv['data'].items():
- self.assertEqual(ret['data'][k], v)
+ self.assertEqual(v, ret['data'][k])
self._set_flag('storwize_svc_npiv_compatibility_mode',
False)
stats = self.driver.get_volume_stats()
self.assertLessEqual(stats['free_capacity_gb'],
stats['total_capacity_gb'])
- self.assertEqual(stats['reserved_percentage'], 25)
+ self.assertEqual(25, stats['reserved_percentage'])
pool = self.driver.configuration.local_conf.storwize_svc_volpool_name
if self.USESIM:
expected = 'storwize-svc-sim_' + pool
- self.assertEqual(stats['volume_backend_name'], expected)
- self.assertAlmostEqual(stats['total_capacity_gb'], 3328.0)
- self.assertAlmostEqual(stats['free_capacity_gb'], 3287.5)
+ self.assertEqual(expected, stats['volume_backend_name'])
+ self.assertAlmostEqual(3328.0, stats['total_capacity_gb'])
+ self.assertAlmostEqual(3287.5, stats['free_capacity_gb'])
def test_storwize_svc_extend_volume(self):
volume = self._create_volume()
vol = {'name': 'test', 'id': 1, 'size': 1}
ctxt = context.get_admin_context()
moved, model_update = self.driver.migrate_volume(ctxt, vol, host)
- self.assertEqual(moved, expected['moved'])
- self.assertEqual(model_update, expected['model_update'])
+ self.assertEqual(expected['moved'], moved)
+ self.assertEqual(expected['model_update'], model_update)
def test_storwize_svc_migrate_bad_loc_info(self):
self._check_loc_info({}, {'moved': False, 'model_update': None})
init_ret = self.driver.initialize_connection(volume, connector)
# Make sure we use the preferred WWPN.
- self.assertEqual(init_ret['data']['target_wwn'],
- 'AABBCCDDEEFF0010')
+ self.assertEqual('AABBCCDDEEFF0010',
+ init_ret['data']['target_wwn'])
def test_storwize_initiator_multiple_preferred_nodes_no_matching(self):
# Generate us a test volume
init_ret = self.driver.initialize_connection(volume, connector)
# Make sure we use the first available WWPN.
- self.assertEqual(init_ret['data']['target_wwn'],
- 'AABBCCDDEEFF0001')
+ self.assertEqual('AABBCCDDEEFF0001',
+ init_ret['data']['target_wwn'])
def test_storwize_initiator_single_preferred_node_matching(self):
# Generate us a test volume
init_ret = self.driver.initialize_connection(volume, connector)
# Make sure we use the preferred WWPN.
- self.assertEqual(init_ret['data']['target_wwn'],
- 'AABBCCDDEEFF0012')
+ self.assertEqual('AABBCCDDEEFF0012',
+ init_ret['data']['target_wwn'])
def test_storwize_terminate_connection(self):
# create a FC volume
model_update = self.driver.create_consistencygroup(self.ctxt, cg)
- self.assertEqual(model_update['status'],
- 'available',
+ self.assertEqual('available',
+ model_update['status'],
"CG created failed")
# Add volumes to CG
self._create_volume(volume_type_id=cg_type['id'],
# Submit the request to manage it.
ref = {'source-id': uid}
size = self.driver.manage_existing_get_size(new_volume, ref)
- self.assertEqual(size, 10)
+ self.assertEqual(10, size)
self.driver.manage_existing(new_volume, ref)
# Assert that there is a disk named after the new volume that has the
# manage a volume that is already attached.
ref = {'source-id': uid, 'manage_if_in_use': True}
size = self.driver.manage_existing_get_size(new_volume, ref)
- self.assertEqual(size, 10)
+ self.assertEqual(10, size)
self.driver.manage_existing(new_volume, ref)
# Assert that there is a disk named after the new volume that has the
home address!s4
'''
resp = ssh.CLIResponse(raw, with_header=False)
- self.assertEqual(list(resp.select('home address', 'name',
- 'home address')),
- [('s1', 'Bill', 's1'), ('s2', 'Bill2', 's2'),
- ('s3', 'John', 's3'), ('s4', 'John2', 's4')])
+ self.assertEqual([('s1', 'Bill', 's1'), ('s2', 'Bill2', 's2'),
+ ('s3', 'John', 's3'), ('s4', 'John2', 's4')],
+ list(resp.select('home address', 'name',
+ 'home address')))
def test_lsnode_all(self):
raw = r'''id!name!UPS_serial_number!WWNN!status
resp = ssh.CLIResponse(raw, with_header=False)
self.assertEqual(1, len(resp))
self.assertEqual('1', resp[0]['id'])
- self.assertEqual(list(resp.select('port_id', 'port_status')),
- [('500507680210C744', 'active'),
- ('500507680240C744', 'inactive')])
+ self.assertEqual([('500507680210C744', 'active'),
+ ('500507680240C744', 'inactive')],
+ list(resp.select('port_id', 'port_status')))
class StorwizeHelpersTestCase(test.TestCase):
test_file = '/var/tmp/made_up_file'
mock_stat.return_value = stat_result
mode = utils.get_file_mode(test_file)
- self.assertEqual(mode, 0o777)
+ self.assertEqual(0o777, mode)
mock_stat.assert_called_once_with(test_file)
@mock.patch('os.stat')
test_file = '/var/tmp/made_up_file'
mock_stat.return_value = stat_result
gid = utils.get_file_gid(test_file)
- self.assertEqual(gid, 33333)
+ self.assertEqual(33333, gid)
mock_stat.assert_called_once_with(test_file)
@mock.patch('cinder.utils.CONF')
class_pairs = zip((D, B, E),
utils.walk_class_hierarchy(A, encountered=[C]))
for actual, expected in class_pairs:
- self.assertEqual(actual, expected)
+ self.assertEqual(expected, actual)
class_pairs = zip((D, B, C, E), utils.walk_class_hierarchy(A))
for actual, expected in class_pairs:
- self.assertEqual(actual, expected)
+ self.assertEqual(expected, actual)
class GetDiskOfPartitionTestCase(test.TestCase):
exampleA = example_a.ExampleClassA()
exampleA.example_method()
ret_a = exampleA.example_method_add(3, 5)
- self.assertEqual(ret_a, 8)
+ self.assertEqual(8, ret_a)
self.assertEqual('Example function', example_b.example_function_b())
exampleB = example_b.ExampleClassB()
exampleB.example_method()
ret_b = exampleB.example_method_add(3, 5)
- self.assertEqual(ret_b, 8)
+ self.assertEqual(8, ret_b)
package_a = self.example_package + 'example_a.'
self.assertTrue(
package_a + 'example_function_a'
def test_hour(self):
begin, end = utils.last_completed_audit_period(unit='hour')
- self.assertEqual(begin,
- datetime.datetime(hour=7,
- day=5,
- month=3,
- year=2012))
- self.assertEqual(end, datetime.datetime(hour=8,
- day=5,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(hour=7, day=5, month=3, year=2012),
+ begin)
+ self.assertEqual(datetime.datetime(hour=8, day=5, month=3, year=2012),
+ end)
def test_hour_with_offset_before_current(self):
begin, end = utils.last_completed_audit_period(unit='hour@10')
- self.assertEqual(begin, datetime.datetime(minute=10,
- hour=7,
- day=5,
- month=3,
- year=2012))
- self.assertEqual(end, datetime.datetime(minute=10,
- hour=8,
- day=5,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(minute=10,
+ hour=7,
+ day=5,
+ month=3,
+ year=2012),
+ begin)
+ self.assertEqual(datetime.datetime(minute=10,
+ hour=8,
+ day=5,
+ month=3,
+ year=2012),
+ end)
def test_hour_with_offset_after_current(self):
begin, end = utils.last_completed_audit_period(unit='hour@30')
- self.assertEqual(begin, datetime.datetime(minute=30,
- hour=6,
- day=5,
- month=3,
- year=2012))
- self.assertEqual(end, datetime.datetime(minute=30,
- hour=7,
- day=5,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(minute=30,
+ hour=6,
+ day=5,
+ month=3,
+ year=2012),
+ begin)
+ self.assertEqual(datetime.datetime(minute=30,
+ hour=7,
+ day=5,
+ month=3,
+ year=2012),
+ end)
def test_day(self):
begin, end = utils.last_completed_audit_period(unit='day')
- self.assertEqual(begin, datetime.datetime(day=4,
- month=3,
- year=2012))
- self.assertEqual(end, datetime.datetime(day=5,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(day=4, month=3, year=2012), begin)
+ self.assertEqual(datetime.datetime(day=5, month=3, year=2012), end)
def test_day_with_offset_before_current(self):
begin, end = utils.last_completed_audit_period(unit='day@6')
- self.assertEqual(begin, datetime.datetime(hour=6,
- day=4,
- month=3,
- year=2012))
- self.assertEqual(end, datetime.datetime(hour=6,
- day=5,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(hour=6, day=4, month=3, year=2012),
+ begin)
+ self.assertEqual(datetime.datetime(hour=6, day=5, month=3, year=2012),
+ end)
def test_day_with_offset_after_current(self):
begin, end = utils.last_completed_audit_period(unit='day@10')
- self.assertEqual(begin, datetime.datetime(hour=10,
- day=3,
- month=3,
- year=2012))
- self.assertEqual(end, datetime.datetime(hour=10,
- day=4,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(hour=10, day=3, month=3, year=2012),
+ begin)
+ self.assertEqual(datetime.datetime(hour=10, day=4, month=3, year=2012),
+ end)
def test_month(self):
begin, end = utils.last_completed_audit_period(unit='month')
- self.assertEqual(begin, datetime.datetime(day=1,
- month=2,
- year=2012))
- self.assertEqual(end, datetime.datetime(day=1,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(day=1, month=2, year=2012), begin)
+ self.assertEqual(datetime.datetime(day=1, month=3, year=2012), end)
def test_month_with_offset_before_current(self):
begin, end = utils.last_completed_audit_period(unit='month@2')
- self.assertEqual(begin, datetime.datetime(day=2,
- month=2,
- year=2012))
- self.assertEqual(end, datetime.datetime(day=2,
- month=3,
- year=2012))
+ self.assertEqual(datetime.datetime(day=2, month=2, year=2012), begin)
+ self.assertEqual(datetime.datetime(day=2, month=3, year=2012), end)
def test_month_with_offset_after_current(self):
begin, end = utils.last_completed_audit_period(unit='month@15')
- self.assertEqual(begin, datetime.datetime(day=15,
- month=1,
- year=2012))
- self.assertEqual(end, datetime.datetime(day=15,
- month=2,
- year=2012))
+ self.assertEqual(datetime.datetime(day=15, month=1, year=2012), begin)
+ self.assertEqual(datetime.datetime(day=15, month=2, year=2012), end)
@mock.patch('oslo_utils.timeutils.utcnow',
return_value=datetime.datetime(day=1,
def test_year(self):
begin, end = utils.last_completed_audit_period(unit='year')
- self.assertEqual(begin, datetime.datetime(day=1,
- month=1,
- year=2011))
- self.assertEqual(end, datetime.datetime(day=1,
- month=1,
- year=2012))
+ self.assertEqual(datetime.datetime(day=1, month=1, year=2011), begin)
+ self.assertEqual(datetime.datetime(day=1, month=1, year=2012), end)
def test_year_with_offset_before_current(self):
begin, end = utils.last_completed_audit_period(unit='year@2')
- self.assertEqual(begin, datetime.datetime(day=1,
- month=2,
- year=2011))
- self.assertEqual(end, datetime.datetime(day=1,
- month=2,
- year=2012))
+ self.assertEqual(datetime.datetime(day=1, month=2, year=2011), begin)
+ self.assertEqual(datetime.datetime(day=1, month=2, year=2012), end)
def test_year_with_offset_after_current(self):
begin, end = utils.last_completed_audit_period(unit='year@6')
- self.assertEqual(begin, datetime.datetime(day=1,
- month=6,
- year=2010))
- self.assertEqual(end, datetime.datetime(day=1,
- month=6,
- year=2011))
+ self.assertEqual(datetime.datetime(day=1, month=6, year=2010), begin)
+ self.assertEqual(datetime.datetime(day=1, month=6, year=2011), end)
def test_invalid_unit(self):
self.assertRaises(ValueError,
ret = succeeds()
self.assertFalse(mock_sleep.called)
- self.assertEqual(ret, 'success')
- self.assertEqual(self.counter, 1)
+ self.assertEqual('success', ret)
+ self.assertEqual(1, self.counter)
def test_retries_once(self):
self.counter = 0
return 'success'
ret = fails_once()
- self.assertEqual(ret, 'success')
- self.assertEqual(self.counter, 2)
- self.assertEqual(mock_sleep.call_count, 1)
+ self.assertEqual('success', ret)
+ self.assertEqual(2, self.counter)
+ self.assertEqual(1, mock_sleep.call_count)
mock_sleep.assert_called_with(interval * backoff_rate)
def test_limit_is_reached(self):
class VersionTestCase(test.TestCase):
def test_convert_version_to_int(self):
- self.assertEqual(utils.convert_version_to_int('6.2.0'), 6002000)
- self.assertEqual(utils.convert_version_to_int((6, 4, 3)), 6004003)
- self.assertEqual(utils.convert_version_to_int((5, )), 5)
+ self.assertEqual(6002000, utils.convert_version_to_int('6.2.0'))
+ self.assertEqual(6004003, utils.convert_version_to_int((6, 4, 3)))
+ self.assertEqual(5, utils.convert_version_to_int((5, )))
self.assertRaises(exception.CinderException,
utils.convert_version_to_int, '5a.6b')
def test_convert_version_to_string(self):
- self.assertEqual(utils.convert_version_to_str(6007000), '6.7.0')
- self.assertEqual(utils.convert_version_to_str(4), '4')
+ self.assertEqual('6.7.0', utils.convert_version_to_str(6007000))
+ self.assertEqual('4', utils.convert_version_to_str(4))
def test_convert_version_to_tuple(self):
- self.assertEqual(utils.convert_version_to_tuple('6.7.0'), (6, 7, 0))
+ self.assertEqual((6, 7, 0), utils.convert_version_to_tuple('6.7.0'))
class LogTracingTestCase(test.TestCase):
self.driver._export_lun.assert_called_with(VOLUME, CONNECTOR)
self.driver._build_initiator_target_map.assert_called_with(
CONNECTOR)
- self.assertEqual(props['driver_volume_type'], "fibre_channel")
- self.assertEqual(props['data']['target_discovered'], True)
- self.assertEqual(props['data']['target_wwn'],
- self.driver.gateway_fc_wwns)
- self.assertEqual(props['data']['target_lun'], lun_id)
+ self.assertEqual("fibre_channel", props['driver_volume_type'])
+ self.assertEqual(True, props['data']['target_discovered'])
+ self.assertEqual(self.driver.gateway_fc_wwns,
+ props['data']['target_wwn'])
+ self.assertEqual(lun_id, props['data']['target_lun'])
def test_terminate_connection(self):
target_wwns = self.driver.gateway_fc_wwns
def test_split_datastore_path(self):
test1 = '[datastore1] myfolder/mysubfolder/myvm.vmx'
(datastore, folder, file_name) = volumeops.split_datastore_path(test1)
- self.assertEqual(datastore, 'datastore1')
- self.assertEqual(folder, 'myfolder/mysubfolder/')
- self.assertEqual(file_name, 'myvm.vmx')
+ self.assertEqual('datastore1', datastore)
+ self.assertEqual('myfolder/mysubfolder/', folder)
+ self.assertEqual('myvm.vmx', file_name)
test2 = '[datastore2 ] myfolder/myvm.vmdk'
(datastore, folder, file_name) = volumeops.split_datastore_path(test2)
- self.assertEqual(datastore, 'datastore2')
- self.assertEqual(folder, 'myfolder/')
- self.assertEqual(file_name, 'myvm.vmdk')
+ self.assertEqual('datastore2', datastore)
+ self.assertEqual('myfolder/', folder)
+ self.assertEqual('myvm.vmdk', file_name)
test3 = 'myfolder/myvm.vmdk'
self.assertRaises(IndexError, volumeops.split_datastore_path, test3)
child = mock.Mock(spec=object)
child._type = 'Parent'
ret = self.vops._get_parent(child, 'Parent')
- self.assertEqual(ret, child)
+ self.assertEqual(child, ret)
# Recursive
parent = mock.Mock(spec=object)
child._type = 'Child'
self.session.invoke_api.return_value = parent
ret = self.vops._get_parent(child, 'Parent')
- self.assertEqual(ret, parent)
+ self.assertEqual(parent, ret)
self.session.invoke_api.assert_called_with(vim_util,
'get_object_property',
self.session.vim, child,
node.name = name
node.snapshot = snapshot
ret = volops._get_snapshot_from_tree(name, node)
- self.assertEqual(ret, snapshot)
+ self.assertEqual(snapshot, ret)
# Test root.childSnapshotList == None
root = mock.Mock(spec=object)
root.name = 'root'
# Test root.child == snapshot
root.childSnapshotList = [node]
ret = volops._get_snapshot_from_tree(name, root)
- self.assertEqual(ret, snapshot)
+ self.assertEqual(snapshot, ret)
def test_get_snapshot(self):
# build out the root snapshot tree
ret = {}
for item in admin_metadata:
ret.update({item['key']: item['value']})
- self.assertDictMatch(ret, expected)
+ self.assertDictMatch(expected, ret)
connector = {'initiator': 'iqn.2012-07.org.fake:01'}
conn_info = self.volume.initialize_connection(self.context,
ret = {}
for item in admin_metadata:
ret.update({item['key']: item['value']})
- self.assertDictMatch(ret, expected)
+ self.assertDictMatch(expected, ret)
connector = {'initiator': 'iqn.2012-07.org.fake:01'}
conn_info = self.volume.initialize_connection(self.context,
ret = {}
for item in admin_metadata:
ret.update({item['key']: item['value']})
- self.assertDictMatch(ret, expected)
+ self.assertDictMatch(expected, ret)
connector = {'initiator': 'iqn.2012-07.org.fake:01'}
conn_info = self.volume.initialize_connection(self.context,
volume_id, connector)
ret = {}
for item in admin_metadata:
ret.update({item['key']: item['value']})
- self.assertDictMatch(ret, expected)
+ self.assertDictMatch(expected, ret)
connector = {'initiator': 'iqn.2012-07.org.fake:01'}
conn_info = self.volume.initialize_connection(self.context,
volume_id, connector)
attachment = vol['volume_attachment']
self.assertEqual('available', vol['status'])
self.assertEqual('detached', vol['attach_status'])
- self.assertEqual(attachment, [])
+ self.assertEqual([], attachment)
admin_metadata = vol['volume_admin_metadata']
self.assertEqual(1, len(admin_metadata))
self.assertEqual('readonly', admin_metadata[0]['key'])
ret = {}
for item in admin_metadata:
ret.update({item['key']: item['value']})
- self.assertDictMatch(ret, expected)
+ self.assertDictMatch(expected, ret)
connector = {'initiator': 'iqn.2012-07.org.fake:01'}
conn_info = self.volume.initialize_connection(self.context,
volume_id, connector)
attachment = vol['volume_attachment']
self.assertEqual('available', vol['status'])
self.assertEqual('detached', vol['attach_status'])
- self.assertEqual(attachment, [])
+ self.assertEqual([], attachment)
admin_metadata = vol['volume_admin_metadata']
self.assertEqual(1, len(admin_metadata))
self.assertEqual('readonly', admin_metadata[0]['key'])
ret = {}
for item in admin_metadata:
ret.update({item['key']: item['value']})
- self.assertDictMatch(ret, expected)
+ self.assertDictMatch(expected, ret)
db.volume_update(self.context, volume_id, {'status': 'available'})
self.assertRaises(exception.InvalidVolumeAttachMode,
ret = {}
for item in admin_metadata:
ret.update({item['key']: item['value']})
- self.assertDictMatch(ret, expected)
+ self.assertDictMatch(expected, ret)
def test_run_api_attach_detach_volume_with_wrong_attach_mode(self):
# Not allow using 'read-write' mode attach readonly volume
self.assertIn('host', group)
host = group.host
pool = volutils.extract_host(host, level='pool')
- self.assertEqual(pool, 'fakepool')
+ self.assertEqual('fakepool', pool)
return {'status': 'available'}
self.stubs.Set(self.volume.driver, 'create_consistencygroup',
}
self.assertDictMatch(expected, msg['payload'])
msg = self.notifier.notifications[1]
- self.assertEqual(msg['event_type'], 'consistencygroup.create.end')
+ self.assertEqual('consistencygroup.create.end', msg['event_type'])
self.assertDictMatch(expected, msg['payload'])
self.assertEqual(
group.id,
transfer['id'],
transfer['auth_key'])
volume = db.volume_get(self.ctxt, '1')
- self.assertEqual(volume['project_id'], 'new_project_id',
+ self.assertEqual('new_project_id', volume['project_id'],
'Unexpected project id')
- self.assertEqual(volume['user_id'], 'new_user_id',
+ self.assertEqual('new_user_id', volume['user_id'],
'Unexpected user id')
self.assertEqual(volume['id'], response['volume_id'],
"""Ensures default volume type can be retrieved."""
volume_types.create(self.ctxt, conf_fixture.def_vol_type, {})
default_vol_type = volume_types.get_default_volume_type()
- self.assertEqual(default_vol_type.get('name'),
- conf_fixture.def_vol_type)
+ self.assertEqual(conf_fixture.def_vol_type,
+ default_vol_type.get('name'))
def test_default_volume_type_missing_in_db(self):
"""Test default volume type is missing in database.
is not in database.
"""
default_vol_type = volume_types.get_default_volume_type()
- self.assertEqual(default_vol_type, {})
+ self.assertEqual({}, default_vol_type)
def test_get_default_volume_type_under_non_default(self):
cfg.CONF.set_default('default_volume_type', None)
search_opts={'extra_specs': {"key1": "val1"}})
self.assertEqual(1, len(vol_types))
self.assertIn("type1", vol_types.keys())
- self.assertEqual(vol_types['type1']['extra_specs'],
- {"key1": "val1", "key2": "val2"})
+ self.assertEqual({"key1": "val1", "key2": "val2"},
+ vol_types['type1']['extra_specs'])
vol_types = volume_types.get_all_types(
self.ctxt,
self.ctxt,
search_opts={'extra_specs': {"key1": "val1",
"key3": "val3"}})
- self.assertEqual(len(vol_types), 2)
+ self.assertEqual(2, len(vol_types))
self.assertIn("type1", vol_types.keys())
self.assertIn("type3", vol_types.keys())
- self.assertEqual(vol_types['type1']['extra_specs'],
- {"key1": "val1", "key2": "val2", "key3": "val3"})
- self.assertEqual(vol_types['type3']['extra_specs'],
- {"key1": "val1", "key3": "val3", "key4": "val4"})
+ self.assertEqual({"key1": "val1", "key2": "val2", "key3": "val3"},
+ vol_types['type1']['extra_specs'])
+ self.assertEqual({"key1": "val1", "key3": "val3", "key4": "val4"},
+ vol_types['type3']['extra_specs'])
def test_is_encrypted(self):
volume_type = volume_types.create(self.ctxt, "type1")
diff, same = volume_types.volume_types_diff(self.ctxt, type_ref1['id'],
type_ref2['id'])
self.assertTrue(same)
- self.assertEqual(diff['extra_specs']['key1'], ('val1', 'val1'))
+ self.assertEqual(('val1', 'val1'), diff['extra_specs']['key1'])
diff, same = volume_types.volume_types_diff(self.ctxt, type_ref1['id'],
type_ref3['id'])
self.assertFalse(same)
- self.assertEqual(diff['extra_specs']['key1'], ('val1', 'val0'))
+ self.assertEqual(('val1', 'val0'), diff['extra_specs']['key1'])
# qos_ref 1 and 2 have the same specs, while 3 has different
qos_keyvals1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
diff, same = volume_types.volume_types_diff(self.ctxt, type_ref1['id'],
type_ref2['id'])
self.assertTrue(same)
- self.assertEqual(diff['extra_specs']['key1'], ('val1', 'val1'))
- self.assertEqual(diff['qos_specs']['k1'], ('v1', 'v1'))
+ self.assertEqual(('val1', 'val1'), diff['extra_specs']['key1'])
+ self.assertEqual(('v1', 'v1'), diff['qos_specs']['k1'])
qos_specs.disassociate_qos_specs(self.ctxt, qos_ref2['id'],
type_ref2['id'])
qos_specs.associate_qos_with_type(self.ctxt, qos_ref3['id'],
diff, same = volume_types.volume_types_diff(self.ctxt, type_ref1['id'],
type_ref2['id'])
self.assertFalse(same)
- self.assertEqual(diff['extra_specs']['key1'], ('val1', 'val1'))
- self.assertEqual(diff['qos_specs']['k1'], ('v1', 'v0'))
+ self.assertEqual(('val1', 'val1'), diff['extra_specs']['key1'])
+ self.assertEqual(('v1', 'v0'), diff['qos_specs']['k1'])
qos_specs.disassociate_qos_specs(self.ctxt, qos_ref3['id'],
type_ref2['id'])
qos_specs.associate_qos_with_type(self.ctxt, qos_ref2['id'],
diff, same = volume_types.volume_types_diff(self.ctxt, type_ref1['id'],
type_ref2['id'])
self.assertFalse(same)
- self.assertEqual(diff['extra_specs']['key1'], ('val1', 'val1'))
- self.assertEqual(diff['qos_specs']['k1'], ('v1', 'v1'))
- self.assertEqual(diff['encryption']['key_size'], (256, 128))
+ self.assertEqual(('val1', 'val1'), diff['extra_specs']['key1'])
+ self.assertEqual(('v1', 'v1'), diff['qos_specs']['k1'])
+ self.assertEqual((256, 128), diff['encryption']['key_size'])
# Check diff equals type specs when one type is None
diff, same = volume_types.volume_types_diff(self.ctxt, None,
'zfssa:compression': 'gzip'
}
ret = self.drv._get_voltype_specs(volume)
- self.assertEqual(ret.get('volblocksize'), '128k')
- self.assertEqual(ret.get('sparse'),
- self.configuration.zfssa_lun_sparse)
- self.assertEqual(ret.get('compression'), 'gzip')
- self.assertEqual(ret.get('logbias'),
- self.configuration.zfssa_lun_logbias)
+ self.assertEqual('128k', ret.get('volblocksize'))
+ self.assertEqual(self.configuration.zfssa_lun_sparse,
+ ret.get('sparse'))
+ self.assertEqual('gzip', ret.get('compression'))
+ self.assertEqual(self.configuration.zfssa_lun_logbias,
+ ret.get('logbias'))
def tearDown(self):
super(TestZFSSAISCSIDriver, self).tearDown()
root = netapp_api.NaElement('root')
child = {'e1': 'v1', 'e2': 'v2', 'e3': 'v3'}
root.translate_struct(child)
- self.assertEqual(len(root.get_children()), 3)
- self.assertEqual(root.get_child_content('e1'), 'v1')
- self.assertEqual(root.get_child_content('e2'), 'v2')
- self.assertEqual(root.get_child_content('e3'), 'v3')
+ self.assertEqual(3, len(root.get_children()))
+ self.assertEqual('v1', root.get_child_content('e1'))
+ self.assertEqual('v2', root.get_child_content('e2'))
+ self.assertEqual('v3', root.get_child_content('e3'))
def test_translate_struct_dict_nonunique_key(self):
"""Tests if list/dict gets properly converted to NaElements."""
root = netapp_api.NaElement('root')
child = [{'e1': 'v1', 'e2': 'v2'}, {'e1': 'v3'}]
root.translate_struct(child)
- self.assertEqual(len(root.get_children()), 3)
+ self.assertEqual(3, len(root.get_children()))
children = root.get_children()
for c in children:
if c.get_name() == 'e1':
self.assertIn(c.get_content(), ['v1', 'v3'])
else:
- self.assertEqual(c.get_content(), 'v2')
+ self.assertEqual('v2', c.get_content())
def test_translate_struct_list(self):
"""Tests if list gets properly converted to NaElements."""
root = netapp_api.NaElement('root')
child = ['e1', 'e2']
root.translate_struct(child)
- self.assertEqual(len(root.get_children()), 2)
+ self.assertEqual(2, len(root.get_children()))
self.assertIsNone(root.get_child_content('e1'))
self.assertIsNone(root.get_child_content('e2'))
root = netapp_api.NaElement('root')
child = ('e1', 'e2')
root.translate_struct(child)
- self.assertEqual(len(root.get_children()), 2)
+ self.assertEqual(2, len(root.get_children()))
self.assertIsNone(root.get_child_content('e1'))
self.assertIsNone(root.get_child_content('e2'))
root['e2'] = 1
root['e3'] = 2.0
root['e4'] = 8l
- self.assertEqual(len(root.get_children()), 4)
- self.assertEqual(root.get_child_content('e1'), 'v1')
- self.assertEqual(root.get_child_content('e2'), '1')
- self.assertEqual(root.get_child_content('e3'), '2.0')
- self.assertEqual(root.get_child_content('e4'), '8')
+ self.assertEqual(4, len(root.get_children()))
+ self.assertEqual('v1', root.get_child_content('e1'))
+ self.assertEqual('1', root.get_child_content('e2'))
+ self.assertEqual('2.0', root.get_child_content('e3'))
+ self.assertEqual('8', root.get_child_content('e4'))
def test_setter_na_element(self):
"""Tests na_element gets appended as child."""
root = netapp_api.NaElement('root')
root['e1'] = netapp_api.NaElement('nested')
- self.assertEqual(len(root.get_children()), 1)
+ self.assertEqual(1, len(root.get_children()))
e1 = root.get_child_by_name('e1')
self.assertIsInstance(e1, netapp_api.NaElement)
self.assertIsInstance(e1.get_child_by_name('nested'),
e1 = root.get_child_by_name('d')
self.assertIsInstance(e1, netapp_api.NaElement)
sub_ch = e1.get_children()
- self.assertEqual(len(sub_ch), 2)
+ self.assertEqual(2, len(sub_ch))
for c in sub_ch:
self.assertIn(c.get_name(), ['e1', 'e2'])
if c.get_name() == 'e1':
- self.assertEqual(c.get_content(), 'v1')
+ self.assertEqual('v1', c.get_content())
else:
- self.assertEqual(c.get_content(), 'v2')
+ self.assertEqual('v2', c.get_content())
def test_setter_child_list_tuple(self):
"""Tests list/tuple are appended as child to root."""
self.assertEqual(expected_flex_vol, actual_flex_vol)
self.assertEqual(expected_src_path, actual_src_path)
self.assertEqual(expected_dest_path, actual_dest_path)
- self.assertEqual(actual_request.get_child_by_name(
- 'destination-exists').get_content(), 'true')
+ self.assertEqual('true',
+ actual_request.get_child_by_name(
+ 'destination-exists').get_content())
def test_clone_file_when_destination_exists_and_version_less_than_1_20(
self):
self.assertEqual(expected_flex_vol, actual_flex_vol)
self.assertEqual(expected_src_path, actual_src_path)
self.assertEqual(expected_dest_path, actual_dest_path)
- self.assertEqual(actual_request.get_child_by_name(
- 'destination-exists'), None)
+ self.assertEqual(None,
+ actual_request.get_child_by_name(
+ 'destination-exists'))
def test_get_file_usage(self):
expected_bytes = "2048"
(igroup, lun_id) = self.library._find_mapped_lun_igroup('path',
initiators)
- self.assertEqual(igroup, fake.IGROUP1_NAME)
- self.assertEqual(lun_id, '2')
+ self.assertEqual(fake.IGROUP1_NAME, igroup)
+ self.assertEqual('2', lun_id)
def test_find_mapped_lun_igroup_initiator_mismatch(self):
response = netapp_api.NaElement(etree.XML("""
self.library.get_volume_stats(refresh=True)
- self.assertEqual(self.library.zapi_client.provide_ems.call_count, 1)
+ self.assertEqual(1, self.library.zapi_client.provide_ems.call_count)
def test_create_lun(self):
self.library.vol_refresh_voluntary = False
mock.Mock(return_value={'Volume': 'vol1'}))
def test_get_pool(self):
pool = self.library.get_pool({'name': 'volume-fake-uuid'})
- self.assertEqual(pool, 'vol1')
+ self.assertEqual('vol1', pool)
@mock.patch.object(block_base.NetAppBlockStorageLibrary,
'_get_lun_attr',
mock.Mock(return_value=None))
def test_get_pool_no_metadata(self):
pool = self.library.get_pool({'name': 'volume-fake-uuid'})
- self.assertEqual(pool, None)
+ self.assertEqual(None, pool)
@mock.patch.object(block_base.NetAppBlockStorageLibrary,
'_get_lun_attr',
mock.Mock(return_value=dict()))
def test_get_pool_volume_unknown(self):
pool = self.library.get_pool({'name': 'volume-fake-uuid'})
- self.assertEqual(pool, None)
+ self.assertEqual(None, pool)
def test_create_volume(self):
volume_size_in_bytes = int(fake.SIZE) * units.Gi
fake.FC_FORMATTED_INITIATORS,
protocol, None)
- self.assertEqual(lun_id, '1')
+ self.assertEqual('1', lun_id)
mock_get_or_create_igroup.assert_called_once_with(
fake.FC_FORMATTED_INITIATORS, protocol, os)
self.zapi_client.map_lun.assert_called_once_with(
lun_id = self.library._map_lun(
'fake_volume', fake.FC_FORMATTED_INITIATORS, protocol, None)
- self.assertEqual(lun_id, '2')
+ self.assertEqual('2', lun_id)
mock_find_mapped_lun_igroup.assert_called_once_with(
fake.LUN_PATH, fake.FC_FORMATTED_INITIATORS)
igroup_name, os, ig_type = self.library._get_or_create_igroup(
fake.FC_FORMATTED_INITIATORS, 'fcp', 'linux')
- self.assertEqual(igroup_name, 'openstack-' + fake.UUID1)
+ self.assertEqual('openstack-' + fake.UUID1, igroup_name)
self.zapi_client.create_igroup.assert_called_once_with(
igroup_name, 'fcp', 'linux')
self.assertEqual(len(fake.FC_FORMATTED_INITIATORS),
self.library.get_volume_stats(refresh=True)
- self.assertEqual(self.library.zapi_client.provide_ems.call_count, 1)
+ self.assertEqual(1, self.library.zapi_client.provide_ems.call_count)
def test_create_lun(self):
self.library._update_stale_vols = mock.Mock()
def test_convert_uuid_to_es_fmt(self):
value = 'e67e931a-b2ed-4890-938b-3acc6a517fac'
result = utils.convert_uuid_to_es_fmt(value)
- self.assertEqual(result, '4Z7JGGVS5VEJBE4LHLGGUUL7VQ')
+ self.assertEqual('4Z7JGGVS5VEJBE4LHLGGUUL7VQ', result)
def test_convert_es_fmt_to_uuid(self):
value = '4Z7JGGVS5VEJBE4LHLGGUUL7VQ'
result = six.text_type(utils.convert_es_fmt_to_uuid(value))
- self.assertEqual(result, 'e67e931a-b2ed-4890-938b-3acc6a517fac')
+ self.assertEqual('e67e931a-b2ed-4890-938b-3acc6a517fac', result)
def test_validate_instantiation_proxy(self):
kwargs = {'netapp_mode': 'proxy'}
na_utils.validate_instantiation(**kwargs)
- self.assertEqual(na_utils.LOG.warning.call_count, 0)
+ self.assertEqual(0, na_utils.LOG.warning.call_count)
@mock.patch.object(na_utils, 'LOG', mock.Mock())
def test_validate_instantiation_no_proxy(self):
kwargs = {'netapp_mode': 'asdf'}
na_utils.validate_instantiation(**kwargs)
- self.assertEqual(na_utils.LOG.warning.call_count, 1)
+ self.assertEqual(1, na_utils.LOG.warning.call_count)
def test_check_flags(self):
fake_object.fake_attr = 'fake_value'
self.assertFalse(na_utils.set_safe_attr(fake_object, 'fake_attr',
'fake_value'))
- self.assertEqual(fake_object.fake_attr, 'fake_value')
+ self.assertEqual('fake_value', fake_object.fake_attr)
# test value is changed if it should be and retval is True
self.assertTrue(na_utils.set_safe_attr(fake_object, 'fake_attr',
'new_fake_value'))
- self.assertEqual(fake_object.fake_attr, 'new_fake_value')
+ self.assertEqual('new_fake_value', fake_object.fake_attr)
def test_round_down(self):
self.assertAlmostEqual(na_utils.round_down(5.567, '0.00'), 5.56)
expected_ret_val = [int(x) for x in [self._FAKE_TOTAL_SIZE,
self._FAKE_TOTAL_AVAILABLE,
self._FAKE_TOTAL_ALLOCATED]]
- self.assertEqual(ret_val, expected_ret_val)
+ self.assertEqual(expected_ret_val, ret_val)
def test_get_total_allocated(self):
fake_listdir = mock.Mock(side_effect=[self._FAKE_LISTDIR,
with mock.patch('os.listdir', fake_listdir):
ret_val = self._smbfs_driver._get_total_allocated(
self._FAKE_SHARE)
- self.assertEqual(ret_val, 4)
+ self.assertEqual(4, ret_val)
def _test_get_img_info(self, backing_file=None):
self._smbfs_driver.vhdutils.get_vhd_parent_path.return_value = (
mock_args['known_hosts_file'] = 'dummy_host_key_file'
mock_args['missing_key_policy'] = paramiko.RejectPolicy()
ssh_client = self.create_ssh_client(**mock_args)
- self.assertEqual(ssh_client._host_keys_filename, 'dummy_host_key_file')
+ self.assertEqual('dummy_host_key_file', ssh_client._host_keys_filename)
self.assertTrue(isinstance(ssh_client._policy, paramiko.RejectPolicy))
mock_args = {}
ssh_client = self.create_ssh_client(**mock_args)
'20:1a:00:05:1e:e8:e3:29']
get_switch_data_mock.return_value = (switch_data)
ns_info_list = self.get_nameserver_info()
- self.assertEqual(ns_info_list, ns_info_list_expected)
+ self.assertEqual(ns_info_list_expected, ns_info_list)
def test__get_switch_data(self):
cmd = fc_zone_constants.NS_SHOW
Stream(nsshow),
Stream())
switch_data = self._get_switch_data(cmd)
- self.assertEqual(switch_data, nsshow)
+ self.assertEqual(nsshow, switch_data)
exec_command_mock.assert_called_once_with(cmd)
def test__parse_ns_output(self):
return_wwn_list = []
expected_wwn_list = ['20:1a:00:05:1e:e8:e3:29']
return_wwn_list = self._parse_ns_output(switch_data)
- self.assertEqual(return_wwn_list, expected_wwn_list)
+ self.assertEqual(expected_wwn_list, return_wwn_list)
self.assertRaises(exception.InvalidParameterValue,
self._parse_ns_output, invalid_switch_data)
return_wwn_list = []
expected_wwn_list = ['10:00:8c:7c:ff:52:3b:01']
return_wwn_list.append(self.get_formatted_wwn(wwn_list[0]))
- self.assertEqual(return_wwn_list, expected_wwn_list)
+ self.assertEqual(expected_wwn_list, return_wwn_list)
class Channel(object):
ns_info_list_expected = ['20:1a:00:05:1e:e8:e3:29']
get_switch_info_mock.return_value = (switch_data)
ns_info_list = self.get_nameserver_info()
- self.assertEqual(ns_info_list, ns_info_list_expected)
+ self.assertEqual(ns_info_list_expected, ns_info_list)
@mock.patch.object(client_cli.BrcdFCZoneClientCLI, '_run_ssh')
def test_get_nameserver_info_ssh_error(self, run_ssh_mock):
nsshow_list = [nsshow]
run_ssh_mock.return_value = (Stream(nsshow), Stream())
switch_data = self._get_switch_info(cmd_list)
- self.assertEqual(switch_data, nsshow_list)
+ self.assertEqual(nsshow_list, switch_data)
run_ssh_mock.assert_called_once_with(cmd_list, True, 1)
def test__parse_ns_output(self):
return_wwn_list = []
expected_wwn_list = ['20:1a:00:05:1e:e8:e3:29']
return_wwn_list = self._parse_ns_output(switch_data)
- self.assertEqual(return_wwn_list, expected_wwn_list)
+ self.assertEqual(expected_wwn_list, return_wwn_list)
self.assertRaises(exception.InvalidParameterValue,
self._parse_ns_output, invalid_switch_data)
'10:00:00:49:c9:28:c7:01']
get_switch_data_mock.return_value = (switch_data)
ns_info_list = self.get_nameserver_info('304')
- self.assertEqual(ns_info_list, ns_info_list_expected)
+ self.assertEqual(ns_info_list_expected, ns_info_list)
def test_parse_ns_output(self):
invalid_switch_data = [' N 011a00;20:1a:00:05:1e:e8:e3:29']
expected_wwn_list = ['20:1a:00:05:1e:e8:e3:29',
'10:00:00:49:c9:28:c7:01']
return_wwn_list = self._parse_ns_output(switch_data)
- self.assertEqual(return_wwn_list, expected_wwn_list)
+ self.assertEqual(expected_wwn_list, return_wwn_list)
self.assertRaises(exception.InvalidParameterValue,
self._parse_ns_output, invalid_switch_data)
return_wwn_list = []
expected_wwn_list = ['10:00:8c:7c:ff:52:3b:01']
return_wwn_list.append(zm_utils.get_formatted_wwn(wwn_list[0]))
- self.assertEqual(return_wwn_list, expected_wwn_list)
+ self.assertEqual(expected_wwn_list, return_wwn_list)
@mock.patch.object(cisco_lookup.CiscoFCSanLookupService,
'_run_ssh')
nsshow_list = [nsshow]
run_ssh_mock.return_value = (Stream(nsshow), Stream())
switch_data = self._get_switch_info(cmd_list)
- self.assertEqual(switch_data, nsshow_list)
+ self.assertEqual(nsshow_list, switch_data)
run_ssh_mock.assert_called_once_with(cmd_list, True, 1)
ns_info_list_expected = ['20:1a:00:05:1e:e8:e3:29']
get_switch_info_mock.return_value = (switch_data)
ns_info_list = self.get_nameserver_info()
- self.assertEqual(ns_info_list, ns_info_list_expected)
+ self.assertEqual(ns_info_list_expected, ns_info_list)
@mock.patch.object(cli.CiscoFCZoneClientCLI, '_run_ssh')
def test_get_nameserver_info_ssh_error(self, run_ssh_mock):
nsshow_list = [nsshow]
run_ssh_mock.return_value = (Stream(nsshow), Stream())
switch_data = self._get_switch_info(cmd_list)
- self.assertEqual(switch_data, nsshow_list)
+ self.assertEqual(nsshow_list, switch_data)
run_ssh_mock.assert_called_once_with(cmd_list, True, 1)
def test__parse_ns_output(self):
return_wwn_list = []
expected_wwn_list = ['20:1a:00:05:1e:e8:e3:29']
return_wwn_list = self._parse_ns_output(switch_data)
- self.assertEqual(return_wwn_list, expected_wwn_list)
+ self.assertEqual(expected_wwn_list, return_wwn_list)
class Channel(object):