Don't translate exceptions in tests

Exception lines in unit tests won't ever be run in production, no reason to
translate them.

Added hacking rule for not importing i18n translation in tests.

Change-Id: I92f546166d4e0b2fa8dc2018c6d3e268b8ec4c0b
This commit is contained in:
Mike Durnosvistov 2014-11-18 15:19:31 +02:00
parent 9595d09e05
commit 6ab942dd19
21 changed files with 114 additions and 117 deletions

View File

@ -48,6 +48,7 @@ Nova Specific Commandments
assertIn/NotIn(A, B, message)
- [N335] Check for usage of deprecated assertRaisesRegexp
- [N336] Must use a dict comprehension instead of a dict constructor with a sequence of key-value pairs.
- [N337] Don't import translation in tests
Creating Unit Tests
-------------------

View File

@ -88,6 +88,8 @@ translated_log = re.compile(
mutable_default_args = re.compile(r"^\s*def .+\((.+=\{\}|.+=\[\])")
string_translation = re.compile(r"[^_]*_\(\s*('|\")")
underscore_import_check = re.compile(r"(.)*import _(.)*")
import_translation_for_log_or_exception = re.compile(
r"(.)*(from\snova.i18n\simport)\s_")
# We need this for cases where they have created their own _ function.
custom_underscore_check = re.compile(r"(.)*_\s*=\s*(.)*")
api_version_re = re.compile(r"@.*api_version")
@ -299,6 +301,22 @@ def no_translate_debug_logs(logical_line, filename):
yield(0, "N319 Don't translate debug level logs")
def no_import_translation_in_tests(logical_line, filename):
"""Check for 'from nova.i18n import _'
N337
"""
# TODO(Mike_D): Needs to be remove with:
# I610deb44f33a966de50296272ab0bfa35462eec9
if ('nova/tests/unit/scheduler/test_host_manager.py' in filename or
'nova/tests/unit/volume/encryptors/test_base.py' in filename or
'nova/tests/unit/virt/xenapi/test_vm_utils.py' in filename):
return
if 'nova/tests/' in filename:
res = import_translation_for_log_or_exception.match(logical_line)
if res:
yield(0, "N337 Don't import translation in tests")
def no_setting_conf_directly_in_tests(logical_line, filename):
"""Check for setting CONF.* attributes directly in tests
@ -507,6 +525,7 @@ def factory(register):
register(import_no_virt_driver_config_deps)
register(capital_cfg_help)
register(no_vi_headers)
register(no_import_translation_in_tests)
register(assert_true_instance)
register(assert_equal_type)
register(assert_equal_none)

View File

@ -17,7 +17,6 @@ import urllib
from oslo.serialization import jsonutils
import requests
from nova.i18n import _
from nova.openstack.common import log as logging
from nova.tests.unit.image import fake
@ -35,10 +34,10 @@ class OpenStackApiException(Exception):
_status = response.status_code
_body = response.content
message = (_('%(message)s\nStatus Code: %(_status)s\n'
'Body: %(_body)s') %
{'message': message, '_status': _status,
'_body': _body})
message = ('%(message)s\nStatus Code: %(_status)s\n'
'Body: %(_body)s' %
{'message': message, '_status': _status,
'_body': _body})
super(OpenStackApiException, self).__init__(message)
@ -46,7 +45,7 @@ class OpenStackApiException(Exception):
class OpenStackApiAuthenticationException(OpenStackApiException):
def __init__(self, response=None, message=None):
if not message:
message = _("Authentication error")
message = "Authentication error"
super(OpenStackApiAuthenticationException, self).__init__(message,
response)
@ -54,7 +53,7 @@ class OpenStackApiAuthenticationException(OpenStackApiException):
class OpenStackApiAuthorizationException(OpenStackApiException):
def __init__(self, response=None, message=None):
if not message:
message = _("Authorization error")
message = "Authorization error"
super(OpenStackApiAuthorizationException, self).__init__(message,
response)
@ -62,7 +61,7 @@ class OpenStackApiAuthorizationException(OpenStackApiException):
class OpenStackApiNotFoundException(OpenStackApiException):
def __init__(self, response=None, message=None):
if not message:
message = _("Item not found")
message = "Item not found"
super(OpenStackApiNotFoundException, self).__init__(message, response)
@ -140,8 +139,8 @@ class TestOpenStackClient(object):
raise OpenStackApiAuthorizationException(response=response)
else:
raise OpenStackApiException(
message=_("Unexpected status code"),
response=response)
message="Unexpected status code",
response=response)
return response

View File

@ -21,7 +21,6 @@ from oslo.serialization import jsonutils
from oslo.utils import importutils
import six
from nova.i18n import _
from nova import test
from nova.tests.functional import integrated_helpers
@ -111,7 +110,7 @@ class ApiSampleTestBase(integrated_helpers._IntegratedTestBase):
matched_value = None
if isinstance(expected, dict):
if not isinstance(result, dict):
raise NoMatch(_('%(result_str)s: %(result)s is not a dict.')
raise NoMatch('%(result_str)s: %(result)s is not a dict.'
% {'result_str': result_str, 'result': result})
ex_keys = sorted(expected.keys())
res_keys = sorted(result.keys())
@ -125,9 +124,9 @@ class ApiSampleTestBase(integrated_helpers._IntegratedTestBase):
if key not in ex_keys:
res_delta.append(key)
raise NoMatch(
_('Dictionary key mismatch:\n'
'Dictionary key mismatch:\n'
'Extra key(s) in template:\n%(ex_delta)s\n'
'Extra key(s) in %(result_str)s:\n%(res_delta)s\n') %
'Extra key(s) in %(result_str)s:\n%(res_delta)s\n' %
{'ex_delta': ex_delta, 'result_str': result_str,
'res_delta': res_delta})
for key in ex_keys:
@ -137,7 +136,7 @@ class ApiSampleTestBase(integrated_helpers._IntegratedTestBase):
elif isinstance(expected, list):
if not isinstance(result, list):
raise NoMatch(
_('%(result_str)s: %(result)s is not a list.') %
'%(result_str)s: %(result)s is not a list.' %
{'result_str': result_str, 'result': result})
expected = expected[:]
@ -157,12 +156,12 @@ class ApiSampleTestBase(integrated_helpers._IntegratedTestBase):
error = []
if expected:
error.append(_('Extra list items in template:'))
error.append('Extra list items in template:')
error.extend([repr(o) for o in expected])
if extra:
error.append(_('Extra list items in %(result_str)s:') %
{'result_str': result_str})
error.append('Extra list items in %(result_str)s:' %
{'result_str': result_str})
error.extend([repr(o) for o in extra])
if error:
@ -182,8 +181,8 @@ class ApiSampleTestBase(integrated_helpers._IntegratedTestBase):
match = re.match(expected, result)
if not match:
raise NoMatch(
_('Values do not match:\n'
'Template: %(expected)s\n%(result_str)s: %(result)s') %
'Values do not match:\n'
'Template: %(expected)s\n%(result_str)s: %(result)s' %
{'expected': expected, 'result_str': result_str,
'result': result})
try:
@ -199,11 +198,11 @@ class ApiSampleTestBase(integrated_helpers._IntegratedTestBase):
result = result.strip()
if expected != result:
raise NoMatch(
_('Values do not match:\n'
'Values do not match:\n'
'Template: %(expected)s\n%(result_str)s: '
'%(result)s') % {'expected': expected,
'result_str': result_str,
'result': result})
'%(result)s' % {'expected': expected,
'result_str': result_str,
'result': result})
return matched_value
def generalize_subs(self, subs, vanilla_regexes):

View File

@ -19,7 +19,6 @@ from nova.api.openstack.compute.plugins.v3 import fixed_ips as fixed_ips_v21
from nova import context
from nova import db
from nova import exception
from nova.i18n import _
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit.objects import test_network
@ -75,7 +74,7 @@ fake_fixed_ips = [{'id': 1,
def fake_fixed_ip_get_by_address(context, address, columns_to_join=None):
if address == 'inv.ali.d.ip':
msg = _("Invalid fixed IP Address %s in request") % address
msg = "Invalid fixed IP Address %s in request" % address
raise exception.FixedIpInvalid(msg)
for fixed_ip in fake_fixed_ips:
if fixed_ip['address'] == address and not fixed_ip['deleted']:

View File

@ -50,7 +50,6 @@ from nova import context
from nova import db
from nova.db.sqlalchemy import models
from nova import exception
from nova.i18n import _
from nova.image import glance
from nova.network import manager
from nova.network.neutronv2 import api as neutron_api
@ -2489,18 +2488,18 @@ class ServersControllerCreateTest(test.TestCase):
self.assertEqual(e.explanation, expected_msg)
def test_create_instance_above_quota_instances(self):
msg = _('Quota exceeded for instances: Requested 1, but'
' already used 10 of 10 instances')
msg = ('Quota exceeded for instances: Requested 1, but'
' already used 10 of 10 instances')
self._do_test_create_instance_above_quota('instances', 0, 10, msg)
def test_create_instance_above_quota_ram(self):
msg = _('Quota exceeded for ram: Requested 4096, but'
' already used 8192 of 10240 ram')
msg = ('Quota exceeded for ram: Requested 4096, but'
' already used 8192 of 10240 ram')
self._do_test_create_instance_above_quota('ram', 2048, 10 * 1024, msg)
def test_create_instance_above_quota_cores(self):
msg = _('Quota exceeded for cores: Requested 2, but'
' already used 9 of 10 cores')
msg = ('Quota exceeded for cores: Requested 2, but'
' already used 9 of 10 cores')
self._do_test_create_instance_above_quota('cores', 1, 10, msg)
def test_create_instance_above_quota_server_group_members(self):
@ -2597,9 +2596,9 @@ class ServersControllerCreateTest(test.TestCase):
self.body['server']['max_count'] = 2
def fake_create(*args, **kwargs):
msg = _("Unable to launch multiple instances with"
" a single configured port ID. Please launch your"
" instance one by one with different ports.")
msg = ("Unable to launch multiple instances with"
" a single configured port ID. Please launch your"
" instance one by one with different ports.")
raise exception.MultiplePortsNotApplicable(reason=msg)
self.stubs.Set(compute_api.API, 'create', fake_create)

View File

@ -43,7 +43,6 @@ from nova import context
from nova import db
from nova.db.sqlalchemy import models
from nova import exception
from nova.i18n import _
from nova.image import glance
from nova.network import manager
from nova.network.neutronv2 import api as neutron_api
@ -2655,9 +2654,9 @@ class ServersControllerCreateTest(test.TestCase):
params = {'networks': requested_networks}
def fake_create(*args, **kwargs):
msg = _("Unable to launch multiple instances with"
" a single configured port ID. Please launch your"
" instance one by one with different ports.")
msg = ("Unable to launch multiple instances with"
" a single configured port ID. Please launch your"
" instance one by one with different ports.")
raise exception.MultiplePortsNotApplicable(reason=msg)
self.stubs.Set(compute_api.API, 'create', fake_create)
@ -2735,18 +2734,18 @@ class ServersControllerCreateTest(test.TestCase):
self.assertEqual(e.explanation, expected_msg)
def test_create_instance_above_quota_instances(self):
msg = _('Quota exceeded for instances: Requested 1, but'
' already used 10 of 10 instances')
msg = ('Quota exceeded for instances: Requested 1, but'
' already used 10 of 10 instances')
self._do_test_create_instance_above_quota('instances', 0, 10, msg)
def test_create_instance_above_quota_ram(self):
msg = _('Quota exceeded for ram: Requested 4096, but'
' already used 8192 of 10240 ram')
msg = ('Quota exceeded for ram: Requested 4096, but'
' already used 8192 of 10240 ram')
self._do_test_create_instance_above_quota('ram', 2048, 10 * 1024, msg)
def test_create_instance_above_quota_cores(self):
msg = _('Quota exceeded for cores: Requested 2, but'
' already used 9 of 10 cores')
msg = ('Quota exceeded for cores: Requested 2, but'
' already used 9 of 10 cores')
self._do_test_create_instance_above_quota('cores', 1, 10, msg)
def test_create_instance_above_quota_group_members(self):

View File

@ -23,7 +23,6 @@ import webob.exc
import nova.api.openstack
from nova.api.openstack import wsgi
from nova import exception
from nova.i18n import _
from nova import test
@ -40,7 +39,7 @@ class TestFaultWrapper(test.NoDBTestCase):
# Create an exception, passing a translatable message with a
# known value we can test for later.
safe_exception = exception.NotFound(_('Should be translated.'))
safe_exception = exception.NotFound('Should be translated.')
safe_exception.safe = True
safe_exception.code = 404

View File

@ -19,7 +19,6 @@ import webob
import webob.exc
import nova.api.auth
from nova.i18n import _
from nova import test
CONF = cfg.CONF
@ -94,7 +93,7 @@ class TestKeystoneMiddlewareRoles(test.NoDBTestCase):
elif context.roles == ['']:
return webob.Response(status="200 No Roles")
else:
raise webob.exc.HTTPBadRequest(_("unexpected role header"))
raise webob.exc.HTTPBadRequest("unexpected role header")
self.middleware = nova.api.auth.NovaKeystoneContext(role_check_app)
self.request = webob.Request.blank('/')

View File

@ -58,7 +58,6 @@ from nova.console import type as ctype
from nova import context
from nova import db
from nova import exception
from nova.i18n import _
from nova.image import glance
from nova.network import api as network_api
from nova.network import model as network_model
@ -6444,7 +6443,7 @@ class ComputeTestCase(BaseTestCase):
def test_instance_update_host_check(self):
# make sure rt usage doesn't happen if the host or node is different
def fail_get(nodename):
raise test.TestingException(_("wrong host/node"))
raise test.TestingException("wrong host/node")
self.stubs.Set(self.compute, '_get_resource_tracker', fail_get)
instance = self._create_fake_instance_obj({'host': 'someotherhost'})
@ -11142,7 +11141,7 @@ class ComputeInjectedFilesTestCase(BaseTestCase):
def spawn_explode(context, instance, image_meta, injected_files,
admin_password, nw_info, block_device_info):
# force reschedule logic to execute
raise test.TestingException(_("spawn error"))
raise test.TestingException("spawn error")
self.stubs.Set(self.compute.driver, 'spawn', spawn_explode)
self.stubs.Set(self.compute, '_reschedule_or_error', _roe)

View File

@ -21,7 +21,6 @@ from nova.compute import api as compute_api
from nova import context
from nova import db
from nova import exception
from nova.i18n import _
from nova import quota
from nova.tests.unit.compute import test_compute
from nova.tests.unit import fake_notifier
@ -121,21 +120,21 @@ class CreateImportSharedTestMixIn(object):
self.assertEqual(expected_message, six.text_type(exc))
def assertInvalidKeypair(self, expected_message, name):
msg = _('Keypair data is invalid: %s') % expected_message
msg = 'Keypair data is invalid: %s' % expected_message
self.assertKeyNameRaises(exception.InvalidKeypair, msg, name)
def test_name_too_short(self):
msg = _('Keypair name must be string and between 1 '
'and 255 characters long')
msg = ('Keypair name must be string and between 1 '
'and 255 characters long')
self.assertInvalidKeypair(msg, '')
def test_name_too_long(self):
msg = _('Keypair name must be string and between 1 '
'and 255 characters long')
msg = ('Keypair name must be string and between 1 '
'and 255 characters long')
self.assertInvalidKeypair(msg, 'x' * 256)
def test_invalid_chars(self):
msg = _("Keypair name contains unsafe characters")
msg = "Keypair name contains unsafe characters"
self.assertInvalidKeypair(msg, '* BAD CHARACTERS! *')
def test_already_exists(self):
@ -144,7 +143,7 @@ class CreateImportSharedTestMixIn(object):
self.stubs.Set(db, "key_pair_create", db_key_pair_create_duplicate)
msg = (_("Key pair '%(key_name)s' already exists.") %
msg = ("Key pair '%(key_name)s' already exists." %
{'key_name': self.existing_key_name})
self.assertKeyNameRaises(exception.KeyPairExists, msg,
self.existing_key_name)
@ -155,7 +154,7 @@ class CreateImportSharedTestMixIn(object):
self.stubs.Set(QUOTAS, "count", fake_quotas_count)
msg = _("Maximum number of key pairs exceeded")
msg = "Maximum number of key pairs exceeded"
self.assertKeyNameRaises(exception.KeypairLimitExceeded, msg, 'foo')

View File

@ -24,7 +24,6 @@ from nova.compute import resources
from nova.compute.resources import base
from nova.compute.resources import vcpu
from nova import context
from nova.i18n import _
from nova.objects import flavor as flavor_obj
from nova import test
from nova.tests.unit import fake_instance
@ -75,7 +74,7 @@ class FakeResource(base.Resource):
if requested <= free:
return
else:
return (_('Free %(free)d < requested %(requested)d ') %
return ('Free %(free)d < requested %(requested)d ' %
{'free': free, 'requested': requested})
def add_instance(self, usage):
@ -326,7 +325,7 @@ class TestVCPU(test.TestCase):
def test_test_fail(self):
result = self._vcpu.test(self._flavor, {'vcpu': 2})
expected = _('Free CPUs 2.00 VCPUs < requested 5 VCPUs')
expected = 'Free CPUs 2.00 VCPUs < requested 5 VCPUs'
self.assertEqual(expected, result)
def test_write(self):

View File

@ -51,7 +51,6 @@ from nova.db.sqlalchemy import migrate_repo
from nova.db.sqlalchemy import migration as sa_migration
from nova.db.sqlalchemy import utils as db_utils
from nova import exception
from nova.i18n import _
from nova import test
@ -637,6 +636,6 @@ class ProjectTestCase(test.NoDBTestCase):
fname = os.path.basename(path)
missing_downgrade.append(fname)
helpful_msg = (_("The following migrations are missing a downgrade:"
"\n\t%s") % '\n\t'.join(sorted(missing_downgrade)))
helpful_msg = ("The following migrations are missing a downgrade:"
"\n\t%s" % '\n\t'.join(sorted(missing_downgrade)))
self.assertFalse(missing_downgrade, helpful_msg)

View File

@ -25,13 +25,11 @@ import fnmatch
from oslo.serialization import jsonutils
from nova.i18n import _
class Store(object):
def __init__(self):
if hasattr(self.__class__, '_instance'):
raise Exception(_('Attempted to instantiate singleton'))
raise Exception('Attempted to instantiate singleton')
@classmethod
def instance(cls):

View File

@ -18,7 +18,6 @@ from oslo.config import cfg
from oslo.utils import timeutils
from nova import exception
from nova.i18n import _
from nova.openstack.common import log as logging
@ -184,20 +183,20 @@ class API(object):
def check_attach(self, context, volume, instance=None):
if volume['status'] != 'available':
msg = _("status must be available")
msg = "status must be available"
msg = "%s" % volume
raise exception.InvalidVolume(reason=msg)
if volume['attach_status'] == 'attached':
msg = _("already attached")
msg = "already attached"
raise exception.InvalidVolume(reason=msg)
if instance and not CONF.cinder.cross_az_attach:
if instance['availability_zone'] != volume['availability_zone']:
msg = _("Instance and volume not in same availability_zone")
msg = "Instance and volume not in same availability_zone"
raise exception.InvalidVolume(reason=msg)
def check_detach(self, context, volume):
if volume['status'] == "available":
msg = _("already detached")
msg = "already detached"
raise exception.InvalidVolume(reason=msg)
def attach(self, context, volume_id, instance_uuid, mountpoint, mode='rw'):

View File

@ -24,7 +24,6 @@ from nova import context
from nova import db
from nova.db import migration
from nova import exception
from nova.i18n import _
from nova import test
from nova.tests.unit.db import fakes as db_fakes
from nova.tests.unit.objects import test_network
@ -217,15 +216,15 @@ class NetworkCommandsTestCase(test.TestCase):
_fmt = "\t".join(["%(id)-5s", "%(cidr)-18s", "%(cidr_v6)-15s",
"%(dhcp_start)-15s", "%(dns1)-15s", "%(dns2)-15s",
"%(vlan)-15s", "%(project_id)-15s", "%(uuid)-15s"])
head = _fmt % {'id': _('id'),
'cidr': _('IPv4'),
'cidr_v6': _('IPv6'),
'dhcp_start': _('start address'),
'dns1': _('DNS1'),
'dns2': _('DNS2'),
'vlan': _('VlanID'),
'project_id': _('project'),
'uuid': _("uuid")}
head = _fmt % {'id': 'id',
'cidr': 'IPv4',
'cidr_v6': 'IPv6',
'dhcp_start': 'start address',
'dns1': 'DNS1',
'dns2': 'DNS2',
'vlan': 'VlanID',
'project_id': 'project',
'uuid': "uuid"}
body = _fmt % {'id': self.net['id'],
'cidr': self.net['cidr'],
'cidr_v6': self.net['cidr_v6'],

View File

@ -31,7 +31,6 @@ from nova.compute import power_state
from nova import context
from nova import db
from nova import exception
from nova.i18n import _
from nova.image import glance
from nova.openstack.common import fileutils
from nova import test
@ -594,8 +593,8 @@ class HyperVAPITestCase(HyperVAPIBaseTestCase):
if admin_permissions:
m.AndReturn(None)
else:
m.AndRaise(vmutils.HyperVAuthorizationException(_(
'Simulated failure')))
m.AndRaise(vmutils.HyperVAuthorizationException(
'Simulated failure'))
def _setup_log_vm_output_mocks(self):
m = fake.PathUtils.get_vm_console_log_paths(mox.IsA(str))

View File

@ -20,7 +20,6 @@ from lxml import etree
import mock
from nova.compute import arch
from nova.i18n import _
# Allow passing None to the various connect methods
# (i.e. allow the client to rely on default URLs)
@ -1072,15 +1071,13 @@ class Connection(object):
def openAuth(uri, auth, flags):
if type(auth) != list:
raise Exception(_("Expected a list for 'auth' parameter"))
raise Exception("Expected a list for 'auth' parameter")
if type(auth[0]) != list:
raise Exception(
_("Expected a function in 'auth[0]' parameter"))
raise Exception("Expected a function in 'auth[0]' parameter")
if not callable(auth[1]):
raise Exception(
_("Expected a function in 'auth[1]' parameter"))
raise Exception("Expected a function in 'auth[1]' parameter")
return Connection(uri, (flags == VIR_CONNECT_RO))
@ -1091,8 +1088,8 @@ def virEventRunDefaultImpl():
def virEventRegisterDefaultImpl():
if connection_used:
raise Exception(_("virEventRegisterDefaultImpl() must be \
called before connection is used."))
raise Exception("virEventRegisterDefaultImpl() must be "
"called before connection is used.")
def registerErrorHandler(handler, ctxt):

View File

@ -27,7 +27,6 @@ from oslo.utils import units
from oslo.vmware import exceptions as vexc
from nova import exception
from nova.i18n import _
from nova.openstack.common import log as logging
from nova.openstack.common import uuidutils
from nova.virt.vmwareapi import constants
@ -264,7 +263,7 @@ class ManagedObject(object):
for elem in self.propSet:
if elem.name == attr:
return elem.val
msg = _("Property %(attr)s not set for the managed object %(name)s")
msg = "Property %(attr)s not set for the managed object %(name)s"
raise exception.NovaException(msg % {'attr': attr,
'name': self.__class__.__name__})
@ -1074,10 +1073,10 @@ def fake_fetch_image(context, instance, host, port, dc_name, ds_name,
def _get_vm_mdo(vm_ref):
"""Gets the Virtual Machine with the ref from the db."""
if _db_content.get("VirtualMachine", None) is None:
raise exception.NotFound(_("There is no VM registered"))
raise exception.NotFound("There is no VM registered")
if vm_ref not in _db_content.get("VirtualMachine"):
raise exception.NotFound(_("Virtual Machine with ref %s is not "
"there") % vm_ref)
raise exception.NotFound("Virtual Machine with ref %s is not "
"there" % vm_ref)
return _db_content.get("VirtualMachine")[vm_ref]
@ -1223,9 +1222,8 @@ class FakeVim(object):
if (self._session is None or self._session not in
_db_content['session']):
LOG.debug("Session is faulty")
raise vexc.VimFaultException(
[vexc.NOT_AUTHENTICATED],
_("Session Invalid"))
raise vexc.VimFaultException([vexc.NOT_AUTHENTICATED],
"Session Invalid")
def _session_is_active(self, *args, **kwargs):
try:
@ -1433,11 +1431,11 @@ class FakeVim(object):
def _set_power_state(self, method, vm_ref, pwr_state="poweredOn"):
"""Sets power state for the VM."""
if _db_content.get("VirtualMachine", None) is None:
raise exception.NotFound(_("No Virtual Machine has been "
"registered yet"))
raise exception.NotFound("No Virtual Machine has been "
"registered yet")
if vm_ref not in _db_content.get("VirtualMachine"):
raise exception.NotFound(_("Virtual Machine with ref %s is not "
"there") % vm_ref)
raise exception.NotFound("Virtual Machine with ref %s is not "
"there" % vm_ref)
vm_mdo = _db_content.get("VirtualMachine").get(vm_ref)
vm_mdo.set("runtime.powerState", pwr_state)
task_mdo = create_task(method, "success")

View File

@ -21,7 +21,6 @@ from oslo.vmware import exceptions as vexc
from testtools import matchers
from nova import exception
from nova.i18n import _
from nova import test
from nova.tests.unit.virt.vmwareapi import fake
from nova.virt.vmwareapi import ds_util
@ -288,7 +287,7 @@ class DsUtilTestCase(test.NoDBTestCase):
# Test with a regex that has no match
# Checks if code raises DatastoreNotFound with a specific message
datastore_invalid_regex = re.compile("unknown-ds")
exp_message = (_("Datastore regex %s did not match any datastores")
exp_message = ("Datastore regex %s did not match any datastores"
% datastore_invalid_regex.pattern)
fake_objects = fake.FakeRetrieveResult()
fake_objects.add_object(fake.Datastore("fake-ds0"))

View File

@ -18,7 +18,6 @@ import pkg_resources
import six
from nova import context
from nova.i18n import _
from nova import test
from nova.tests.unit.virt.xenapi import stubs
from nova.virt.xenapi import driver as xenapi_conn
@ -124,9 +123,9 @@ class LookupTorrentURLTestCase(test.NoDBTestCase):
exc = self.assertRaises(
RuntimeError, self.store._lookup_torrent_url_fn)
self.assertEqual(_('Cannot create default bittorrent URL without'
' torrent_base_url set'
' or torrent URL fetcher extension'),
self.assertEqual('Cannot create default bittorrent URL without'
' torrent_base_url set'
' or torrent URL fetcher extension',
six.text_type(exc))
def test_default_fetch_url_base_url_is_set(self):
@ -158,6 +157,6 @@ class LookupTorrentURLTestCase(test.NoDBTestCase):
exc = self.assertRaises(
RuntimeError, self.store._lookup_torrent_url_fn)
self.assertEqual(_('Multiple torrent URL fetcher extensions found.'
' Failing.'),
self.assertEqual('Multiple torrent URL fetcher extensions found.'
' Failing.',
six.text_type(exc))