Move Fake objects to a special tests.fakes module

A set of Fake objects originally created for nova scenarios unit tests
turned out to be very useful for several other unit tests as well. Here,
we move all these Fake objects to a special tests.fakes module. This will
also simplify code reuse in future unit tests.

Blueprint unit-tests-refactoring

Change-Id: I2b3c6a3f1543a186fe498d886e3fd4bfe615dce8
This commit is contained in:
Mikhail Dubov 2013-12-15 01:09:37 +04:00
parent 743d8fcb75
commit 9b1ee113e8
5 changed files with 397 additions and 382 deletions

View File

@ -19,7 +19,7 @@ from rally.benchmark.scenarios.nova import servers
from rally.benchmark import utils as butils from rally.benchmark import utils as butils
from rally import exceptions as rally_exceptions from rally import exceptions as rally_exceptions
from rally import test from rally import test
from tests.benchmark.scenarios.nova import test_utils from tests import fakes
NOVA_SERVERS = "rally.benchmark.scenarios.nova.servers.NovaServers" NOVA_SERVERS = "rally.benchmark.scenarios.nova.servers.NovaServers"
@ -53,9 +53,9 @@ class NovaServersTestCase(test.TestCase):
kwargs = {'fakearg': 'f'} kwargs = {'fakearg': 'f'}
expected_kwargs = {'fakearg': 'f'} expected_kwargs = {'fakearg': 'f'}
fc = test_utils.FakeClients() fc = fakes.FakeClients()
mock_osclients.Clients.return_value = fc mock_osclients.Clients.return_value = fc
nova = test_utils.FakeNovaClient() nova = fakes.FakeNovaClient()
fc.get_nova_client = lambda: nova fc.get_nova_client = lambda: nova
temp_keys = ["username", "password", "tenant_name", "uri"] temp_keys = ["username", "password", "tenant_name", "uri"]
@ -239,7 +239,7 @@ class NovaServersTestCase(test.TestCase):
mock_random_name): mock_random_name):
fake_server = object() fake_server = object()
fake_image = test_utils.FakeImageManager().create() fake_image = fakes.FakeImageManager().create()
fake_image.id = "image_id" fake_image.id = "image_id"
mock_random_name.return_value = "random_name" mock_random_name.return_value = "random_name"

View File

@ -1,3 +1,4 @@
# Copyright 2013: Mirantis Inc.
# All Rights Reserved. # All Rights Reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -13,327 +14,12 @@
# under the License. # under the License.
import mock import mock
import uuid
from novaclient import exceptions
from rally.benchmark.scenarios.nova import utils from rally.benchmark.scenarios.nova import utils
from rally.benchmark import utils as butils from rally.benchmark import utils as butils
from rally import exceptions as rally_exceptions from rally import exceptions as rally_exceptions
from rally import test from rally import test
from tests import fakes
# NOTE(msdubov): A set of 'Fake' classes below is of great use in the test case
# for utils and also in the test cases for bechmark scenarios.
class FakeResource(object):
def __init__(self, manager=None):
self.name = uuid.uuid4()
self.status = "ACTIVE"
self.manager = manager
self.uuid = uuid.uuid4()
self.id = self.uuid
def __getattr__(self, name):
# NOTE(msdubov): e.g. server.delete() -> manager.delete(server)
def manager_func(*args, **kwargs):
getattr(self.manager, name)(self, *args, **kwargs)
return manager_func
class FakeServer(FakeResource):
def __init__(self, manager=None):
super(FakeServer, self).__init__(manager)
def suspend(self):
self.status = "SUSPENDED"
class FakeFailedServer(FakeResource):
def __init__(self, manager=None):
super(FakeFailedServer, self).__init__(manager)
self.status = "ERROR"
class FakeImage(FakeResource):
def __init__(self, manager=None):
super(FakeImage, self).__init__(manager)
class FakeFloatingIP(FakeResource):
pass
class FakeTenant(FakeResource):
pass
class FakeUser(FakeResource):
pass
class FakeNetwork(FakeResource):
pass
class FakeKeypair(FakeResource):
pass
class FakeSecurityGroup(FakeResource):
pass
class FakeVolume(FakeResource):
pass
class FakeVolumeType(FakeResource):
pass
class FakeVolumeTransfer(FakeResource):
pass
class FakeVolumeSnapshot(FakeResource):
pass
class FakeVolumeBackup(FakeResource):
pass
class FakeManager(object):
def __init__(self):
super(FakeManager, self).__init__()
self.cache = {}
def get(self, resource):
uuid = getattr(resource, 'uuid', None) or resource
return self.cache.get(uuid, None)
def delete(self, resource):
cached = self.get(resource)
if cached is not None:
del self.cache[cached.uuid]
def _cache(self, resource):
self.cache[resource.uuid] = resource
return resource
def list(self, **kwargs):
resources = []
for uuid in self.cache.keys():
resources.append(self.cache[uuid])
return resources
class FakeServerManager(FakeManager):
def __init__(self, image_mgr=None):
super(FakeServerManager, self).__init__()
self.images = image_mgr or FakeImageManager()
def get(self, resource):
server = self.cache.get(resource.uuid, None)
if server is not None:
return server
raise exceptions.NotFound("Server %s not found" % (resource.name))
def _create(self, server_class=FakeServer, name=None):
server = self._cache(server_class(self))
if name is not None:
server.name = name
return server
def create(self, name, image_id, flavor_id):
return self._create(name=name)
def create_image(self, server, name):
image = self.images.create()
return image.uuid
def add_floating_ip(self, server, fip):
pass
def remove_floating_ip(self, server, fip):
pass
class FakeFailedServerManager(FakeServerManager):
def create(self, name, image_id, flavor_id):
return self._create(FakeFailedServer, name)
class FakeImageManager(FakeManager):
def create(self):
return self._cache(FakeImage(self))
def delete(self, image):
cached = self.cache.get(image.uuid, None)
if cached is not None:
cached.status = "DELETED"
class FakeFloatingIPsManager(FakeManager):
def create(self):
return FakeFloatingIP(self)
class FakeTenantsManager(FakeManager):
def create(self, name):
return FakeTenant(self)
class FakeNetworkManager(FakeManager):
def create(self, net_id):
net = FakeNetwork(self)
net.id = net_id
return self._cache(net)
class FakeKeypairManager(FakeManager):
def create(self, name):
kp = FakeKeypair(self)
kp.name = name or kp.name
return self._cache(kp)
class FakeSecurityGroupManager(FakeManager):
def create(self, name):
sg = FakeSecurityGroup(self)
sg.name = name or sg.name
return self._cache(sg)
class FakeUsersManager(FakeManager):
def create(self, username, password, email, tenant_id):
return FakeUser(self)
class FakeVolumeManager(FakeManager):
def create(self, name=None):
volume = FakeVolume(self)
volume.name = name or volume.name
return self._cache(volume)
class FakeVolumeTypeManager(FakeManager):
def create(self, name):
vol_type = FakeVolumeType(self)
vol_type.name = name or vol_type.name
return self._cache(vol_type)
class FakeVolumeTransferManager(FakeManager):
def create(self, name):
transfer = FakeVolumeTransfer(self)
transfer.name = name or transfer.name
return self._cache(transfer)
class FakeVolumeSnapshotManager(FakeManager):
def create(self, name):
snapshot = FakeVolumeSnapshot(self)
snapshot.name = name or snapshot.name
return self._cache(snapshot)
class FakeVolumeBackupManager(FakeManager):
def create(self, name):
backup = FakeVolumeBackup(self)
backup.name = name or backup.name
return self._cache(backup)
class FakeGlanceClient(object):
def __init__(self, nova_client):
self.images = nova_client.images
class FakeCinderClient(object):
def __init__(self):
self.volumes = FakeVolumeManager()
self.volume_types = FakeVolumeTypeManager()
self.transfers = FakeVolumeTransferManager()
self.volume_snapshots = FakeVolumeSnapshotManager()
self.backups = FakeVolumeBackupManager()
class FakeNovaClient(object):
def __init__(self, failed_server_manager=False):
self.images = FakeImageManager()
if failed_server_manager:
self.servers = FakeFailedServerManager(self.images)
else:
self.servers = FakeServerManager(self.images)
self.floating_ips = FakeFloatingIPsManager()
self.networks = FakeNetworkManager()
self.keypairs = FakeKeypairManager()
self.security_groups = FakeSecurityGroupManager()
class FakeKeystoneClient(object):
def __init__(self):
self.tenants = FakeTenantsManager()
self.users = FakeUsersManager()
self.project_id = 'abc123'
class FakeClients(object):
def __init__(self):
self.nova = None
self.glance = None
self.keystone = None
self.cinder = None
def get_keystone_client(self):
if self.keystone is not None:
return self.keystone
self.keystone = FakeKeystoneClient()
return self.keystone
def get_nova_client(self):
if self.nova is not None:
return self.nova
self.nova = FakeNovaClient()
return self.nova
def get_glance_client(self):
if self.glance is not None:
return self.glance
self.glance = FakeGlanceClient(self.get_nova_client())
return self.glance
def get_cinder_client(self):
if self.cinder is not None:
return self.cinder
self.cinder = FakeCinderClient()
return self.cinder
class NovaScenarioTestCase(test.TestCase): class NovaScenarioTestCase(test.TestCase):
@ -348,7 +34,7 @@ class NovaScenarioTestCase(test.TestCase):
self.assertTrue(name.isalpha()) self.assertTrue(name.isalpha())
def test_failed_server_status(self): def test_failed_server_status(self):
server_manager = FakeFailedServerManager() server_manager = fakes.FakeFailedServerManager()
self.assertRaises(rally_exceptions.GetResourceFailure, self.assertRaises(rally_exceptions.GetResourceFailure,
butils.get_from_manager(), butils.get_from_manager(),
server_manager.create('fails', '1', '2')) server_manager.create('fails', '1', '2'))
@ -366,11 +52,11 @@ class NovaScenarioTestCase(test.TestCase):
mock_ris.return_value = _is_ready mock_ris.return_value = _is_ready
get_from_mgr = butils.get_from_manager() get_from_mgr = butils.get_from_manager()
fc = FakeClients() fc = fakes.FakeClients()
mock_osclients.Clients.return_value = fc mock_osclients.Clients.return_value = fc
fake_nova = FakeNovaClient() fake_nova = fakes.FakeNovaClient()
fc.get_nova_client = lambda: fake_nova fc.get_nova_client = lambda: fake_nova
fsm = FakeServerManager(fake_nova.images) fsm = fakes.FakeServerManager(fake_nova.images)
fake_server = fsm.create("s1", "i1", 1) fake_server = fsm.create("s1", "i1", 1)
fsm.create = lambda name, iid, fid: fake_server fsm.create = lambda name, iid, fid: fake_server
fake_nova.servers = fsm fake_nova.servers = fsm

View File

@ -22,7 +22,7 @@ from rally.benchmark import engine
from rally import consts from rally import consts
from rally import exceptions from rally import exceptions
from rally import test from rally import test
from tests.benchmark.scenarios.nova import test_utils from tests import fakes
class TestEngineTestCase(test.TestCase): class TestEngineTestCase(test.TestCase):
@ -156,7 +156,7 @@ class TestEngineTestCase(test.TestCase):
@mock.patch("rally.benchmark.utils.ScenarioRunner.run") @mock.patch("rally.benchmark.utils.ScenarioRunner.run")
@mock.patch("rally.benchmark.utils.osclients") @mock.patch("rally.benchmark.utils.osclients")
def test_benchmark(self, mock_osclients, mock_run): def test_benchmark(self, mock_osclients, mock_run):
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
tester = engine.TestEngine(self.valid_test_config_continuous_times, tester = engine.TestEngine(self.valid_test_config_continuous_times,
mock.MagicMock()) mock.MagicMock())
with tester.bind(self.valid_cloud_config): with tester.bind(self.valid_cloud_config):
@ -170,7 +170,7 @@ class TestEngineTestCase(test.TestCase):
fake_task = mock.MagicMock() fake_task = mock.MagicMock()
tester = engine.TestEngine(self.valid_test_config_continuous_times, tester = engine.TestEngine(self.valid_test_config_continuous_times,
fake_task) fake_task)
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
mock_run.return_value = self.run_success mock_run.return_value = self.run_success
mock_scenario_run.return_value = {} mock_scenario_run.return_value = {}
with tester.bind(self.valid_cloud_config): with tester.bind(self.valid_cloud_config):
@ -206,7 +206,7 @@ class TestEngineTestCase(test.TestCase):
fake_task = mock.MagicMock() fake_task = mock.MagicMock()
tester = engine.TestEngine(self.valid_test_config_continuous_times, tester = engine.TestEngine(self.valid_test_config_continuous_times,
fake_task) fake_task)
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
mock_run.return_value = self.run_success mock_run.return_value = self.run_success
mock_scenario_run.side_effect = exceptions.TestException() mock_scenario_run.side_effect = exceptions.TestException()
try: try:

View File

@ -20,37 +20,10 @@ import os
import tempfile import tempfile
import time import time
from rally.benchmark import base
from rally.benchmark import config from rally.benchmark import config
from rally.benchmark import utils from rally.benchmark import utils
from rally import test from rally import test
from rally import utils as rally_utils from tests import fakes
from tests.benchmark.scenarios.nova import test_utils
class FakeScenario(base.Scenario):
@classmethod
def class_init(cls, endpoints):
pass
@classmethod
def do_it(cls, **kwargs):
pass
@classmethod
def too_long(cls, **kwargs):
pass
@classmethod
def something_went_wrong(cls, **kwargs):
raise Exception("Something went wrong")
class FakeTimer(rally_utils.Timer):
def duration(self):
return 10
class MockedPool(object): class MockedPool(object):
@ -78,7 +51,7 @@ class ScenarioTestCase(test.TestCase):
def test_init_calls_register(self): def test_init_calls_register(self):
with mock.patch("rally.benchmark.utils.osclients") as mock_osclients: with mock.patch("rally.benchmark.utils.osclients") as mock_osclients:
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
with mock.patch("rally.benchmark.utils.base") as mock_base: with mock.patch("rally.benchmark.utils.base") as mock_base:
utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
self.assertEqual(mock_base.mock_calls, self.assertEqual(mock_base.mock_calls,
@ -86,7 +59,7 @@ class ScenarioTestCase(test.TestCase):
def test_create_temp_tenants_and_users(self): def test_create_temp_tenants_and_users(self):
with mock.patch("rally.benchmark.utils.osclients") as mock_osclients: with mock.patch("rally.benchmark.utils.osclients") as mock_osclients:
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
tenants = 10 tenants = 10
users_per_tenant = 5 users_per_tenant = 5
@ -99,7 +72,7 @@ class ScenarioTestCase(test.TestCase):
def test_run_scenario(self): def test_run_scenario(self):
with mock.patch("rally.benchmark.utils.osclients") as mock_osclients: with mock.patch("rally.benchmark.utils.osclients") as mock_osclients:
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
with mock.patch("rally.benchmark.utils.utils") as mock_utils: with mock.patch("rally.benchmark.utils.utils") as mock_utils:
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
utils.__openstack_clients__ = ["client"] utils.__openstack_clients__ = ["client"]
@ -107,9 +80,9 @@ class ScenarioTestCase(test.TestCase):
times = 3 times = 3
duration = 0.01 duration = 0.01
mock_utils.Timer = FakeTimer mock_utils.Timer = fakes.FakeTimer
results = runner._run_scenario(FakeScenario, "do_it", {}, results = runner._run_scenario(fakes.FakeScenario,
"continuous", "do_it", {}, "continuous",
{"times": times, {"times": times,
"active_users": active_users, "active_users": active_users,
"timeout": 2}) "timeout": 2})
@ -117,8 +90,8 @@ class ScenarioTestCase(test.TestCase):
for i in range(times)] for i in range(times)]
self.assertEqual(results, expected) self.assertEqual(results, expected)
results = runner._run_scenario(FakeScenario, "do_it", {}, results = runner._run_scenario(fakes.FakeScenario,
"continuous", "do_it", {}, "continuous",
{"duration": duration, {"duration": duration,
"active_users": active_users, "active_users": active_users,
"timeout": 2}) "timeout": 2})
@ -132,13 +105,13 @@ class ScenarioTestCase(test.TestCase):
def test_run_scenario_timeout(self, mock_time, mock_next, mock_osclients): def test_run_scenario_timeout(self, mock_time, mock_next, mock_osclients):
mock_time.side_effect = [1, 2, 3, 10] mock_time.side_effect = [1, 2, 3, 10]
mock_next.side_effect = multiprocessing.TimeoutError() mock_next.side_effect = multiprocessing.TimeoutError()
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
utils.__openstack_clients__ = ["client"] utils.__openstack_clients__ = ["client"]
times = 4 times = 4
active_users = 2 active_users = 2
results = runner._run_scenario(FakeScenario, "too_long", {}, results = runner._run_scenario(fakes.FakeScenario,
"continuous", "too_long", {}, "continuous",
{"times": times, {"times": times,
"active_users": active_users, "active_users": active_users,
"timeout": 0.01}) "timeout": 0.01})
@ -149,8 +122,8 @@ class ScenarioTestCase(test.TestCase):
str(multiprocessing.TimeoutError)) str(multiprocessing.TimeoutError))
duration = 0.1 duration = 0.1
results = runner._run_scenario(FakeScenario, "too_long", {}, results = runner._run_scenario(fakes.FakeScenario,
"continuous", "too_long", {}, "continuous",
{"duration": duration, {"duration": duration,
"active_users": active_users, "active_users": active_users,
"timeout": 0.01}) "timeout": 0.01})
@ -162,15 +135,15 @@ class ScenarioTestCase(test.TestCase):
def test_run_scenario_exception_inside_test(self): def test_run_scenario_exception_inside_test(self):
with mock.patch("rally.benchmark.utils.osclients") as mock_osclients: with mock.patch("rally.benchmark.utils.osclients") as mock_osclients:
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
utils.__openstack_clients__ = ["client"] utils.__openstack_clients__ = ["client"]
times = 1 times = 1
duration = 0.01 duration = 0.01
active_users = 2 active_users = 2
with mock.patch("rally.benchmark.utils.utils") as mock_utils: with mock.patch("rally.benchmark.utils.utils") as mock_utils:
mock_utils.Timer = FakeTimer mock_utils.Timer = fakes.FakeTimer
results = runner._run_scenario(FakeScenario, results = runner._run_scenario(fakes.FakeScenario,
"something_went_wrong", {}, "something_went_wrong", {},
"continuous", "continuous",
{"times": times, {"times": times,
@ -182,7 +155,7 @@ class ScenarioTestCase(test.TestCase):
self.assertEqual(r['error'][:2], self.assertEqual(r['error'][:2],
[str(Exception), "Something went wrong"]) [str(Exception), "Something went wrong"])
results = runner._run_scenario(FakeScenario, results = runner._run_scenario(fakes.FakeScenario,
"something_went_wrong", {}, "something_went_wrong", {},
"continuous", "continuous",
{"duration": duration, {"duration": duration,
@ -201,21 +174,22 @@ class ScenarioTestCase(test.TestCase):
@mock.patch("rally.benchmark.utils.osclients") @mock.patch("rally.benchmark.utils.osclients")
def test_run_scenario_continuously_for_times(self, mock_osclients, def test_run_scenario_continuously_for_times(self, mock_osclients,
mock_multi): mock_multi):
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
utils.__openstack_clients__ = ["client"] utils.__openstack_clients__ = ["client"]
times = 3 times = 3
active_users = 4 active_users = 4
timeout = 5 timeout = 5
mock_multi.Pool = mock.MagicMock() mock_multi.Pool = mock.MagicMock()
runner._run_scenario_continuously_for_times(FakeScenario, "do_it", {}, runner._run_scenario_continuously_for_times(fakes.FakeScenario,
"do_it", {},
times, active_users, times, active_users,
timeout) timeout)
expect = [ expect = [
mock.call(active_users), mock.call(active_users),
mock.call().imap( mock.call().imap(
utils._run_scenario_loop, utils._run_scenario_loop,
[(i, FakeScenario, "do_it", {}) [(i, fakes.FakeScenario, "do_it", {})
for i in xrange(times)] for i in xrange(times)]
) )
] ]
@ -231,7 +205,7 @@ class ScenarioTestCase(test.TestCase):
@mock.patch("rally.benchmark.utils.osclients") @mock.patch("rally.benchmark.utils.osclients")
def test_run_scenario_continuously_for_duration(self, mock_osclients, def test_run_scenario_continuously_for_duration(self, mock_osclients,
mock_multi, mock_generate): mock_multi, mock_generate):
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
utils.__openstack_clients__ = ["client"] utils.__openstack_clients__ = ["client"]
duration = 0 duration = 0
@ -239,7 +213,7 @@ class ScenarioTestCase(test.TestCase):
timeout = 5 timeout = 5
mock_multi.Pool = mock.MagicMock() mock_multi.Pool = mock.MagicMock()
mock_generate.return_value = {} mock_generate.return_value = {}
runner._run_scenario_continuously_for_duration(FakeScenario, runner._run_scenario_continuously_for_duration(fakes.FakeScenario,
"do_it", {}, duration, "do_it", {}, duration,
active_users, timeout) active_users, timeout)
expect = [ expect = [
@ -258,7 +232,7 @@ class ScenarioTestCase(test.TestCase):
FakeScenario = mock.MagicMock() FakeScenario = mock.MagicMock()
FakeScenario.init = mock.MagicMock(return_value={}) FakeScenario.init = mock.MagicMock(return_value={})
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
runner._run_scenario_continuously_for_times = \ runner._run_scenario_continuously_for_times = \
mock.MagicMock(return_value="result") mock.MagicMock(return_value="result")
@ -293,7 +267,7 @@ class ScenarioTestCase(test.TestCase):
FakeScenario = mock.MagicMock() FakeScenario = mock.MagicMock()
FakeScenario.init = mock.MagicMock(return_value={}) FakeScenario.init = mock.MagicMock(return_value={})
mock_osclients.Clients.return_value = test_utils.FakeClients() mock_osclients.Clients.return_value = fakes.FakeClients()
runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw) runner = utils.ScenarioRunner(mock.MagicMock(), self.fake_kw)
runner._run_scenario = mock.MagicMock(return_value="result") runner._run_scenario = mock.MagicMock(return_value="result")
runner._create_temp_tenants_and_users = mock.MagicMock( runner._create_temp_tenants_and_users = mock.MagicMock(
@ -349,8 +323,8 @@ class ScenarioTestCase(test.TestCase):
FakeScenario = mock.MagicMock() FakeScenario = mock.MagicMock()
FakeScenario.init = mock.MagicMock(return_value={}) FakeScenario.init = mock.MagicMock(return_value={})
mock_cms = [test_utils.FakeClients(), test_utils.FakeClients(), mock_cms = [fakes.FakeClients(), fakes.FakeClients(),
test_utils.FakeClients()] fakes.FakeClients()]
clients = [ clients = [
dict(( dict((
("nova", cl.get_nova_client()), ("nova", cl.get_nova_client()),

355
tests/fakes.py Normal file
View File

@ -0,0 +1,355 @@
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import uuid
from novaclient import exceptions
from rally.benchmark import base
from rally import utils as rally_utils
class FakeResource(object):
def __init__(self, manager=None):
self.name = uuid.uuid4()
self.status = "ACTIVE"
self.manager = manager
self.uuid = uuid.uuid4()
self.id = self.uuid
def __getattr__(self, name):
# NOTE(msdubov): e.g. server.delete() -> manager.delete(server)
def manager_func(*args, **kwargs):
getattr(self.manager, name)(self, *args, **kwargs)
return manager_func
class FakeServer(FakeResource):
def __init__(self, manager=None):
super(FakeServer, self).__init__(manager)
def suspend(self):
self.status = "SUSPENDED"
class FakeFailedServer(FakeResource):
def __init__(self, manager=None):
super(FakeFailedServer, self).__init__(manager)
self.status = "ERROR"
class FakeImage(FakeResource):
def __init__(self, manager=None):
super(FakeImage, self).__init__(manager)
class FakeFloatingIP(FakeResource):
pass
class FakeTenant(FakeResource):
pass
class FakeUser(FakeResource):
pass
class FakeNetwork(FakeResource):
pass
class FakeKeypair(FakeResource):
pass
class FakeSecurityGroup(FakeResource):
pass
class FakeVolume(FakeResource):
pass
class FakeVolumeType(FakeResource):
pass
class FakeVolumeTransfer(FakeResource):
pass
class FakeVolumeSnapshot(FakeResource):
pass
class FakeVolumeBackup(FakeResource):
pass
class FakeManager(object):
def __init__(self):
super(FakeManager, self).__init__()
self.cache = {}
def get(self, resource):
uuid = getattr(resource, 'uuid', None) or resource
return self.cache.get(uuid, None)
def delete(self, resource):
cached = self.get(resource)
if cached is not None:
del self.cache[cached.uuid]
def _cache(self, resource):
self.cache[resource.uuid] = resource
return resource
def list(self, **kwargs):
resources = []
for uuid in self.cache.keys():
resources.append(self.cache[uuid])
return resources
class FakeServerManager(FakeManager):
def __init__(self, image_mgr=None):
super(FakeServerManager, self).__init__()
self.images = image_mgr or FakeImageManager()
def get(self, resource):
server = self.cache.get(resource.uuid, None)
if server is not None:
return server
raise exceptions.NotFound("Server %s not found" % (resource.name))
def _create(self, server_class=FakeServer, name=None):
server = self._cache(server_class(self))
if name is not None:
server.name = name
return server
def create(self, name, image_id, flavor_id):
return self._create(name=name)
def create_image(self, server, name):
image = self.images.create()
return image.uuid
def add_floating_ip(self, server, fip):
pass
def remove_floating_ip(self, server, fip):
pass
class FakeFailedServerManager(FakeServerManager):
def create(self, name, image_id, flavor_id):
return self._create(FakeFailedServer, name)
class FakeImageManager(FakeManager):
def create(self):
return self._cache(FakeImage(self))
def delete(self, image):
cached = self.cache.get(image.uuid, None)
if cached is not None:
cached.status = "DELETED"
class FakeFloatingIPsManager(FakeManager):
def create(self):
return FakeFloatingIP(self)
class FakeTenantsManager(FakeManager):
def create(self, name):
return FakeTenant(self)
class FakeNetworkManager(FakeManager):
def create(self, net_id):
net = FakeNetwork(self)
net.id = net_id
return self._cache(net)
class FakeKeypairManager(FakeManager):
def create(self, name):
kp = FakeKeypair(self)
kp.name = name or kp.name
return self._cache(kp)
class FakeSecurityGroupManager(FakeManager):
def create(self, name):
sg = FakeSecurityGroup(self)
sg.name = name or sg.name
return self._cache(sg)
class FakeUsersManager(FakeManager):
def create(self, username, password, email, tenant_id):
return FakeUser(self)
class FakeVolumeManager(FakeManager):
def create(self, name=None):
volume = FakeVolume(self)
volume.name = name or volume.name
return self._cache(volume)
class FakeVolumeTypeManager(FakeManager):
def create(self, name):
vol_type = FakeVolumeType(self)
vol_type.name = name or vol_type.name
return self._cache(vol_type)
class FakeVolumeTransferManager(FakeManager):
def create(self, name):
transfer = FakeVolumeTransfer(self)
transfer.name = name or transfer.name
return self._cache(transfer)
class FakeVolumeSnapshotManager(FakeManager):
def create(self, name):
snapshot = FakeVolumeSnapshot(self)
snapshot.name = name or snapshot.name
return self._cache(snapshot)
class FakeVolumeBackupManager(FakeManager):
def create(self, name):
backup = FakeVolumeBackup(self)
backup.name = name or backup.name
return self._cache(backup)
class FakeGlanceClient(object):
def __init__(self, nova_client):
self.images = nova_client.images
class FakeCinderClient(object):
def __init__(self):
self.volumes = FakeVolumeManager()
self.volume_types = FakeVolumeTypeManager()
self.transfers = FakeVolumeTransferManager()
self.volume_snapshots = FakeVolumeSnapshotManager()
self.backups = FakeVolumeBackupManager()
class FakeNovaClient(object):
def __init__(self, failed_server_manager=False):
self.images = FakeImageManager()
if failed_server_manager:
self.servers = FakeFailedServerManager(self.images)
else:
self.servers = FakeServerManager(self.images)
self.floating_ips = FakeFloatingIPsManager()
self.networks = FakeNetworkManager()
self.keypairs = FakeKeypairManager()
self.security_groups = FakeSecurityGroupManager()
class FakeKeystoneClient(object):
def __init__(self):
self.tenants = FakeTenantsManager()
self.users = FakeUsersManager()
self.project_id = 'abc123'
class FakeClients(object):
def __init__(self):
self.nova = None
self.glance = None
self.keystone = None
self.cinder = None
def get_keystone_client(self):
if self.keystone is not None:
return self.keystone
self.keystone = FakeKeystoneClient()
return self.keystone
def get_nova_client(self):
if self.nova is not None:
return self.nova
self.nova = FakeNovaClient()
return self.nova
def get_glance_client(self):
if self.glance is not None:
return self.glance
self.glance = FakeGlanceClient(self.get_nova_client())
return self.glance
def get_cinder_client(self):
if self.cinder is not None:
return self.cinder
self.cinder = FakeCinderClient()
return self.cinder
class FakeScenario(base.Scenario):
@classmethod
def class_init(cls, endpoints):
pass
@classmethod
def do_it(cls, **kwargs):
pass
@classmethod
def too_long(cls, **kwargs):
pass
@classmethod
def something_went_wrong(cls, **kwargs):
raise Exception("Something went wrong")
class FakeTimer(rally_utils.Timer):
def duration(self):
return 10