Here are the examples of the python api mock.DEFAULT taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
32 Examples
5
Example 1
Project: scalarizr Source File: test_base.py
def test_ensure(self):
vol = base.Volume(device='/dev/sdb2')
with mock.patch.multiple(vol, config=mock.DEFAULT, mkfs=mock.DEFAULT, mount=mock.DEFAULT):
vol.ensure()
vol.config.assert_called_once_with()
assert vol.mkfs.call_count == 0, "mkfs wasn't called"
assert vol.mount.call_count == 0, "mount wasn't called"
5
Example 2
Project: build-relengapi Source File: test_badpenny.py
def test_cron_run():
"""The `relengapi badpenny-cron` script syncs tasks, gets the list of runnable tasks,
and then runs them."""
cmd = cron.BadpennyCron()
with mock.patch.multiple('relengapi.blueprints.badpenny.cron.BadpennyCron',
sync_tasks=mock.DEFAULT,
runnable_tasks=mock.DEFAULT,
run_task=mock.DEFAULT) as mocks:
tasks = [tables.BadpennyTask(name=n) for n in '01']
mocks['runnable_tasks'].return_value = tasks
cmd.run(None, None)
mocks['sync_tasks'].assert_called_with()
mocks['runnable_tasks'].assert_called_with(mock.ANY)
eq_(mocks['run_task'].mock_calls, [
mock.call(tasks[0]), mock.call(tasks[1])])
5
Example 3
Project: oslo.version Source File: test_version.py
def test_vendor(self):
with mock.patch.multiple(version.VersionInfo,
_get_provider=mock.DEFAULT,
_load_from_pkg_info=mock.DEFAULT,
_load_from_setup_cfg=mock.DEFAULT):
path = self.write_to_tempfile("""[myfoo]
vendor=bigco
product=product123
package=mysuffix
""")
with mock.patch.object(version,
'_find_config_files',
return_value=path):
v = version.VersionInfo('myfoo')
self.assertEqual('myfoo', v.package)
self.assertEqual('bigco', v.vendor)
self.assertEqual('product123', v.product)
self.assertEqual('mysuffix', v.suffix)
3
Example 4
def test_insert_error(self):
"""Check that errors propagate from asynchronous API calls to synchronous ones."""
class CustomException(Exception):
pass
def async_mock(metric, datapoints, on_done):
on_done(CustomException("fake failure"))
return mock.DEFAULT
with mock.patch.object(self.accessor, "insert_points_async", side_effect=async_mock):
self.assertRaises(
CustomException,
self.accessor.insert_points, _METRIC, (0, 42),
)
3
Example 5
Project: spreads Source File: gui_test.py
def test_capture_page(wizard, workflow):
wizard.workflow = workflow
with mock.patch.multiple("spreadsplug.gui.gui.QtGui", QImage=mock.DEFAULT,
QPixmap=mock.DEFAULT) as values:
values["QPixmap"].fromImage = mock.Mock(
return_value=values["QImage"]())
page = wizard.page(1)
page.initializePage()
# TODO: Test capture triggering, logbox updates, etc
assert page.validatePage()
3
Example 6
Project: spreads Source File: web_test.py
@pytest.yield_fixture
def mock_dbus(tmpdir):
with mock.patch.multiple('dbus', SystemBus=mock.DEFAULT,
Interface=mock.DEFAULT) as values:
stickdir = tmpdir.join('stick')
stickdir.mkdir()
mockdevs = [mock.Mock(), mock.Mock()]*2
mockobj = mock.MagicMock()
mockobj.get_dbus_method.return_value.return_value = unicode(
stickdir)
mockobj.EnumerateDevices.return_value = mockdevs
mockobj.Get.side_effect = [True, 'usb', True]*2
values['Interface'].return_value = mockobj
yield mockobj
3
Example 7
Project: edx-platform Source File: test_tasks.py
def _make_side_effect(self, side_effects):
"""
DRY helper. Returns a side effect function for use with mocks that
will be called multiple times, permitting Exceptions to be raised
(or not) in a specified order.
See Also:
http://www.voidspace.org.uk/python/mock/examples.html#multiple-calls-with-different-effects
http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.side_effect
"""
def side_effect(*_a): # pylint: disable=missing-docstring
if side_effects:
exc = side_effects.pop(0)
if exc:
raise exc
return mock.DEFAULT
return side_effect
3
Example 8
@pytest.fixture
def vim():
"""A wide-open mock vim object.
We'll just have to be careful since we can't import a real vim object to
use autospec and guarantee that we're calling real APIs.
"""
def vimeval(expr):
# Default Editor.isneovim to False.
# TODO: easy way to override this; neovim mock fixture?
if expr == "has('nvim')":
return False
else:
return mock.DEFAULT
attrs = {'eval.side_effect': vimeval}
return mock.NonCallableMock(name='mockvim', **attrs)
3
Example 9
Project: ganeti Source File: netutils_mock.py
def _GetHostnameMock(cfg, mock_fct, name=None, family=None):
if _IsOverwrittenReturnValue(mock_fct.return_value):
return mock.DEFAULT
if name is None:
name = cfg.GetMasterNodeName()
if name == cfg.GetClusterName():
cluster = cfg.GetClusterInfo()
return HostnameMock(cluster.cluster_name, cluster.master_ip)
node = cfg.GetNodeInfoByName(name)
if node is not None:
return HostnameMock(node.name, node.primary_ip)
return HostnameMock(name, "203.0.113.253")
3
Example 10
Project: ganeti Source File: netutils_mock.py
def _TcpPingMock(cfg, mock_fct, target, port, timeout=None,
live_port_needed=None, source=None):
if _IsOverwrittenReturnValue(mock_fct.return_value):
return mock.DEFAULT
if target == cfg.GetClusterName():
return True
if cfg.GetNodeInfoByName(target) is not None:
return True
if target in [node.primary_ip for node in cfg.GetAllNodesInfo().values()]:
return True
if target in [node.secondary_ip for node in cfg.GetAllNodesInfo().values()]:
return True
return False
3
Example 11
def test_get_rdp_console(self):
mock_get_host_ip = self.rdpconsoleops._hostops.get_host_ip_addr
mock_get_rdp_port = (
self.rdpconsoleops._rdpconsoleutils.get_rdp_console_port)
mock_get_vm_id = self.rdpconsoleops._vmutils.get_vm_id
connect_info = self.rdpconsoleops.get_rdp_console(mock.DEFAULT)
self.assertEqual(mock_get_host_ip.return_value, connect_info.host)
self.assertEqual(mock_get_rdp_port.return_value, connect_info.port)
self.assertEqual(mock_get_vm_id.return_value,
connect_info.internal_access_path)
3
Example 12
Project: fuel-octane Source File: conftest.py
def assert_popen_args(expected_kwargs, cmd, **kwargs):
assert isinstance(cmd, list)
for e in cmd:
assert isinstance(e, str)
assert expected_kwargs.issuperset(kwargs.keys())
if 'popen_class' in expected_kwargs:
assert kwargs.get('popen_class') in (None, ssh.SSHPopen)
return mock.DEFAULT
3
Example 13
Project: fuel-octane Source File: test_docker.py
def test_wait_for_puppet_in_container(mocker, mock_subprocess):
mock_subprocess.side_effect = [
mock.DEFAULT,
subprocess.CalledProcessError(1, 'test_error')
]
docker._wait_for_puppet_in_container(test_container, attempts, delay)
assert 2 == mock_subprocess.call_count
3
Example 14
Project: fuel-octane Source File: test_patch_puppet.py
def _read_in_subprocess(*args, **kwargs):
stdin = kwargs['stdin']
stdin.call_args.append((args, kwargs))
assert 0 == stdin.seek_point
if stdin.raise_exception_on_revert and '-R' in args[0]:
raise subprocess.CalledProcessError(1, 'cmd')
stdin.read()
return mock.DEFAULT
3
Example 15
Project: git-upstream Source File: test_execute.py
def test_command(self):
"""Test that help command runs successfully"""
with mock.patch.multiple('sys', stdout=mock.DEFAULT,
stderr=mock.DEFAULT):
if getattr(self, 'exception', None):
e = self.assertRaises(self.exception, main.main, self.args)
self.assertThat(getattr(e, self.exc_attr),
matchers.Equals(self.exc_value),
message=self.failure)
else:
self.assertThat(main.main(self.args), matchers.Equals(0),
message=self.failure)
3
Example 16
Project: magnum Source File: test_local.py
def _get_cert_with_fail(self, cert_id, failed='crt'):
def fake_open(path, mode):
if path == os.path.join('/tmp/{0}.{1}'.format(cert_id, failed)):
raise IOError()
return mock.DEFAULT
file_mock = mock.mock_open()
file_mock.side_effect = fake_open
# Attempt to retrieve the cert
with mock.patch('six.moves.builtins.open', file_mock, create=True):
self.assertRaises(
exception.CertificateStorageException,
local_cert_manager.CertManager.get_cert,
cert_id
)
3
Example 17
Project: networking-mlnx Source File: test_db.py
def test_get_oldest_pending_row_when_deadlock(self):
db.create_pending_row(self.db_session, *self.UPDATE_ROW)
update_mock = (
mock.MagicMock(side_effect=(exception.DBDeadlock, mock.DEFAULT)))
# Mocking is mandatory to achieve a deadlock regardless of the DB
# backend being used when running the tests
with mock.patch.object(db, 'update_db_row_state', new=update_mock):
row = db.get_oldest_pending_db_row_with_lock(self.db_session)
self.assertIsNotNone(row)
self.assertEqual(2, update_mock.call_count)
3
Example 18
Project: networking-odl Source File: test_db.py
def test_get_oldest_pending_row_when_deadlock(self):
db.create_pending_row(self.db_session, *self.UPDATE_ROW)
update_mock = mock.MagicMock(side_effect=(DBDeadlock, mock.DEFAULT))
# Mocking is mandatory to achieve a deadlock regardless of the DB
# backend being used when running the tests
with mock.patch.object(db, 'update_db_row_state', new=update_mock):
row = db.get_oldest_pending_db_row_with_lock(self.db_session)
self.assertIsNotNone(row)
self.assertEqual(2, update_mock.call_count)
2
Example 19
Project: astara Source File: test_router_config.py
def test_build_config(self):
methods = {
'load_provider_rules': mock.DEFAULT,
'generate_network_config': mock.DEFAULT,
'generate_floating_config': mock.DEFAULT,
'get_default_v4_gateway': mock.DEFAULT,
}
fake_orchestrator = {
'host': 'foohost',
'adddress': '10.0.0.1',
'metadata_port': 80,
}
mock_client = mock.Mock()
mock_context = mock.Mock(
neutron=mock_client,
config=fake_orchestrator,
)
ifaces = []
provider_rules = {'labels': {'ext': ['192.168.1.1']}}
network_config = [
{'interface': 1,
'network_id': 2,
'v4_conf_service': 'static',
'v6_conf_service': 'static',
'network_type': 'external',
'subnets': [
{'cidr': '192.168.1.0/24',
'dhcp_enabled': True,
'dns_nameservers': [],
'host_routes': [],
'gateway_ip': '192.168.1.1',
},
{'cidr': '10.0.0.0/24',
'dhcp_enabled': True,
'dns_nameservers': [],
'host_routes': [],
'gateway_ip': '10.0.0.1',
}, ],
'allocations': []}
]
with mock.patch.multiple(conf_mod, **methods) as mocks:
mocks['load_provider_rules'].return_value = provider_rules
mocks['generate_network_config'].return_value = network_config
mocks['generate_floating_config'].return_value = 'floating_config'
mocks['get_default_v4_gateway'].return_value = 'default_gw'
config = conf_mod.build_config(mock_context, fakes.fake_router,
fakes.fake_mgt_port, ifaces)
expected = {
'default_v4_gateway': 'default_gw',
'networks': network_config,
'labels': {'ext': ['192.168.1.1']},
'floating_ips': 'floating_config',
'asn': 64512,
'neighbor_asn': 64512,
'tenant_id': 'tenant_id',
'ha_resource': False,
'hostname': 'ak-tenant_id',
'orchestrator': {
'host': 'foohost',
'adddress': '10.0.0.1',
'metadata_port': 80,
},
'vpn': {}
}
self.assertEqual(expected, config)
mocks['load_provider_rules'].assert_called_once_with('/the/path')
mocks['generate_network_config'].assert_called_once_with(
mock_client, fakes.fake_router, fakes.fake_mgt_port, ifaces)
2
Example 20
Project: nova-docker Source File: test_hostutils.py
def _test_sys_uptime(self, is_nt_os=False):
expect_uptime = ("fake_time up 0:00:00, 0 users, "
"load average: 0, 0, 0")
fake_tick_count = 0
fake_time = 'fake_time'
with mock.patch.multiple(hostutils, os=mock.DEFAULT, time=mock.DEFAULT,
ctypes=mock.DEFAULT, utils=mock.DEFAULT,
create=True) as lib_mocks:
lib_mocks['os'].name = 'nt' if is_nt_os else ''
lib_mocks['time'].strftime.return_value = fake_time
lib_mocks['utils'].execute.return_value = (expect_uptime, None)
tick_count = lib_mocks['ctypes'].windll.kernel32.GetTickCount64
tick_count.return_value = fake_tick_count
uptime = hostutils.sys_uptime()
if is_nt_os:
tick_count.assert_called_once_with()
lib_mocks['time'].strftime.assert_called_once_with("%H:%M:%S")
else:
lib_mocks['utils'].execute.assert_called_once_with(
'env', 'LANG=C', 'uptime')
self.assertEqual(expect_uptime, uptime)
2
Example 21
Project: watcher Source File: test_action_plan.py
def test_destroy(self):
efficacy_indicator = utils.get_test_efficacy_indicator(
action_plan_id=self.fake_action_plan['id'])
uuid = self.fake_action_plan['uuid']
with mock.patch.multiple(
self.dbapi, autospec=True,
get_action_plan_by_uuid=mock.DEFAULT,
destroy_action_plan=mock.DEFAULT,
get_efficacy_indicator_list=mock.DEFAULT,
destroy_efficacy_indicator=mock.DEFAULT,
) as m_dict:
m_get_action_plan = m_dict['get_action_plan_by_uuid']
m_destroy_action_plan = m_dict['destroy_action_plan']
m_get_efficacy_indicator_list = (
m_dict['get_efficacy_indicator_list'])
m_destroy_efficacy_indicator = m_dict['destroy_efficacy_indicator']
m_get_action_plan.return_value = self.fake_action_plan
m_get_efficacy_indicator_list.return_value = [efficacy_indicator]
action_plan = objects.ActionPlan.get_by_uuid(self.context, uuid)
action_plan.destroy()
m_get_action_plan.assert_called_once_with(self.context, uuid)
m_get_efficacy_indicator_list.assert_called_once_with(
self.context, filters={"action_plan_uuid": uuid},
limit=None, marker=None, sort_dir=None, sort_key=None)
m_destroy_action_plan.assert_called_once_with(uuid)
m_destroy_efficacy_indicator.assert_called_once_with(
efficacy_indicator['uuid'])
self.assertEqual(self.context, action_plan._context)
2
Example 22
Project: watcher Source File: test_action_plan.py
def test_soft_delete(self):
efficacy_indicator = utils.get_test_efficacy_indicator(
action_plan_id=self.fake_action_plan['id'])
uuid = self.fake_action_plan['uuid']
with mock.patch.multiple(
self.dbapi, autospec=True,
get_action_plan_by_uuid=mock.DEFAULT,
soft_delete_action_plan=mock.DEFAULT,
update_action_plan=mock.DEFAULT,
get_efficacy_indicator_list=mock.DEFAULT,
soft_delete_efficacy_indicator=mock.DEFAULT,
) as m_dict:
m_get_action_plan = m_dict['get_action_plan_by_uuid']
m_soft_delete_action_plan = m_dict['soft_delete_action_plan']
m_get_efficacy_indicator_list = (
m_dict['get_efficacy_indicator_list'])
m_soft_delete_efficacy_indicator = (
m_dict['soft_delete_efficacy_indicator'])
m_update_action_plan = m_dict['update_action_plan']
m_get_action_plan.return_value = self.fake_action_plan
m_get_efficacy_indicator_list.return_value = [efficacy_indicator]
action_plan = objects.ActionPlan.get_by_uuid(self.context, uuid)
action_plan.soft_delete()
m_get_action_plan.assert_called_once_with(self.context, uuid)
m_get_efficacy_indicator_list.assert_called_once_with(
self.context, filters={"action_plan_uuid": uuid},
limit=None, marker=None, sort_dir=None, sort_key=None)
m_soft_delete_action_plan.assert_called_once_with(uuid)
m_soft_delete_efficacy_indicator.assert_called_once_with(
efficacy_indicator['uuid'])
m_update_action_plan.assert_called_once_with(
uuid, {'state': 'DELETED'})
self.assertEqual(self.context, action_plan._context)
0
Example 23
Project: pyudev Source File: mock_libudev.py
@contextmanager
def libudev_list(libudev, function, items):
"""
Mock a libudev linked list::
with pytest.libudev_list(device._libudev, 'udev_device_get_tag_list_entry', ['foo', 'bar']):
assert list(device.tags) == ['foo', 'bar']
``function`` is a string containing the name of the libudev function that
returns the list. ``items`` is an iterable yielding items which shall be
returned by the mocked list function. An item in ``items`` can either be a
tuple with two components, where the first component is the item name, and
the second the item value, or a single element, which is the item name.
The item value is ``None`` in this case.
"""
functions_to_patch = [function, 'udev_list_entry_get_next',
'udev_list_entry_get_name',
'udev_list_entry_get_value']
mocks = dict((f, mock.DEFAULT) for f in functions_to_patch)
with mock.patch.multiple(libudev, **mocks):
udev_list = LinkedList.from_iterable(items)
getattr(libudev, function).return_value = udev_list.first
libudev.udev_list_entry_get_name.side_effect = attrgetter('name')
libudev.udev_list_entry_get_value.side_effect = attrgetter('value')
libudev.udev_list_entry_get_next.side_effect = attrgetter('next')
yield
0
Example 24
def test_to_taskwarrior(self):
arbitrary_project = 'one'
arbitrary_url = 'http://one.com/'
issue = self.service.get_issue_for_record(self.arbitrary_issue)
expected_output = {
'project': arbitrary_project,
'priority': self.service.default_priority,
issue.FOREIGN_ID: self.arbitrary_issue['Id'],
issue.URL: arbitrary_url,
issue.TITLE: self.name_parts[-1]
}
def get_url(*args):
return arbitrary_url
def get_project(*args):
return arbitrary_project
with mock.patch.multiple(
issue, get_project=mock.DEFAULT, get_issue_url=mock.DEFAULT
) as mocked:
mocked['get_project'].side_effect = get_project
mocked['get_issue_url'].side_effect = get_url
actual_output = issue.to_taskwarrior()
self.assertEqual(actual_output, expected_output)
0
Example 25
Project: exporters Source File: test_readers.py
def patch_scanners(self):
return mock.patch.multiple('kafka_scanner', KafkaScanner=mock.DEFAULT,
KafkaScannerSimple=mock.DEFAULT)
0
Example 26
Project: ganeti Source File: netutils_mock.py
def _IsOverwrittenReturnValue(value):
return value is not None and value != mock.DEFAULT and \
not isinstance(value, mock.Mock)
0
Example 27
def test_calls(self):
"""
This method tests that each validation method on ExtensionValidator is
correctly called. Whenever adding a validation method, take care to
include its name in the `validation_methods` list.
"""
validation_methods = [
'validate_author',
'validate_description',
'validate_file',
'validate_icons',
'validate_json',
'validate_name',
'validate_version',
]
mocks = {method: mock.DEFAULT for method in validation_methods}
with mock.patch.multiple(ExtensionValidator, **mocks):
self.test_full()
for method in validation_methods:
mocked = getattr(ExtensionValidator, method)
eq_(mocked.call_count, 1)
0
Example 28
Project: server-tools Source File: test_password_security_home.py
@contextmanager
def mock_assets(self):
""" It mocks and returns assets used by this controller """
methods = ['do_signup', 'web_login', 'web_auth_signup',
'web_auth_reset_password',
]
with mock.patch.multiple(
main.AuthSignupHome, **{m: mock.DEFAULT for m in methods}
) as _super:
mocks = {}
for method in methods:
mocks[method] = _super[method]
mocks[method].return_value = MockResponse()
with mock.patch('%s.request' % IMPORT) as request:
with mock.patch('%s.ensure_db' % IMPORT) as ensure:
with mock.patch('%s.http' % IMPORT) as http:
http.redirect_with_hash.return_value = \
MockResponse()
mocks.update({
'request': request,
'ensure_db': ensure,
'http': http,
})
yield mocks
0
Example 29
Project: barbican Source File: test_p11_crypto.py
def test_encrypt_bad_session(self):
self.pkcs11.get_session.return_value = mock.DEFAULT
self.pkcs11.get_session.side_effect = ex.P11CryptoPluginException(
'Testing error handling'
)
payload = b'test payload'
encrypt_dto = plugin_import.EncryptDTO(payload)
kek_meta = mock.MagicMock()
kek_meta.kek_label = 'pkek'
kek_meta.plugin_meta = ('{"iv": "iv==",'
'"hmac": "hmac",'
'"wrapped_key": "wrappedkey==",'
'"mkek_label": "mkek_label",'
'"hmac_label": "hmac_label"}')
self.assertRaises(ex.P11CryptoPluginException,
self.plugin._encrypt,
encrypt_dto,
kek_meta,
mock.MagicMock())
self.assertEqual(2, self.pkcs11.get_key_handle.call_count)
self.assertEqual(2, self.pkcs11.get_session.call_count)
self.assertEqual(1, self.pkcs11.verify_hmac.call_count)
self.assertEqual(1, self.pkcs11.unwrap_key.call_count)
self.assertEqual(0, self.pkcs11.encrypt.call_count)
self.assertEqual(0, self.pkcs11.return_session.call_count)
0
Example 30
Project: barbican Source File: test_p11_crypto.py
def test_decrypt_bad_session(self):
self.pkcs11.get_session.return_value = mock.DEFAULT
self.pkcs11.get_session.side_effect = ex.P11CryptoPluginException(
'Testing error handling'
)
ct = b'ctct'
kek_meta_extended = '{"iv":"AAAA"}'
decrypt_dto = plugin_import.DecryptDTO(ct)
kek_meta = mock.MagicMock()
kek_meta.kek_label = 'pkek'
kek_meta.plugin_meta = ('{"iv": "iv==",'
'"hmac": "hmac",'
'"wrapped_key": "wrappedkey==",'
'"mkek_label": "mkek_label",'
'"hmac_label": "hmac_label"}')
self.assertRaises(ex.P11CryptoPluginException,
self.plugin._decrypt,
decrypt_dto,
kek_meta,
kek_meta_extended,
mock.MagicMock())
self.assertEqual(2, self.pkcs11.get_key_handle.call_count)
self.assertEqual(2, self.pkcs11.get_session.call_count)
self.assertEqual(1, self.pkcs11.verify_hmac.call_count)
self.assertEqual(1, self.pkcs11.unwrap_key.call_count)
self.assertEqual(0, self.pkcs11.decrypt.call_count)
self.assertEqual(0, self.pkcs11.return_session.call_count)
0
Example 31
Project: fuel-octane Source File: test_upgrade_db.py
@pytest.mark.parametrize(("calls", "graph_names", "catch"), [
# Orig is fine, seed is fine and there is no need to rollback.
(
[
("upgrade-db", False),
("upgrade-db", False),
],
["upgrade-db", "upgrade-db-rollback", "upgrade-db"],
None,
),
# Orig is fine, seed fails and there is no rollback.
(
[
("upgrade-db", False),
("upgrade-db", True),
],
["upgrade-db", "upgrade-db"],
"upgrade-db",
),
# Orig is fine, seed fails and rollback is fine.
(
[
("upgrade-db", False),
("upgrade-db", True),
("upgrade-db-rollback", False),
],
["upgrade-db", "upgrade-db-rollback", "upgrade-db"],
"upgrade-db",
),
# Orig is fine, seed fails and rollback fails too.
(
[
("upgrade-db", False),
("upgrade-db", True),
("upgrade-db-rollback", True),
],
["upgrade-db", "upgrade-db-rollback", "upgrade-db"],
"upgrade-db-rollback",
),
# Orig fails and there is no rollback.
(
[
("upgrade-db", True),
],
["upgrade-db", "upgrade-db"],
"upgrade-db",
),
# Orig fails, rollback is fine.
(
[
("upgrade-db", True),
("upgrade-db-rollback", False),
],
["upgrade-db", "upgrade-db-rollback", "upgrade-db"],
"upgrade-db",
),
# Orig fails, rollback is also fails.
(
[
("upgrade-db", True),
("upgrade-db-rollback", True),
],
["upgrade-db", "upgrade-db-rollback", "upgrade-db"],
"upgrade-db-rollback",
),
])
def test_upgrade_db_with_graph(mocker, calls, graph_names, catch):
class ExecutionError(Exception):
pass
def execute_graph(graph_name, env_id):
assert graph_name in results, \
"Unxpected execution of the graph {0}".format(graph_name)
result = results[graph_name]
if result is not None:
raise result
return mock.DEFAULT
results = {
graph_name: ExecutionError(graph_name) if is_error else None
for graph_name, is_error in calls
}
expected_exception = None
if catch is not None:
expected_exception = results[catch]
mock_settings_hash = {'editable': {'common': {}}}
mocker.patch("octane.util.deployment.upload_graphs")
mocker.patch("octane.util.deployment.execute_graph_and_wait",
side_effect=execute_graph)
mocker.patch("octane.util.deployment.get_cluster_graph_names",
return_value=graph_names)
mocker.patch("fuelclient.objects.Environment.get_settings_data",
return_value=mock_settings_hash)
mocker.patch("fuelclient.objects.Environment.set_settings_data")
mocker.patch("fuelclient.objects.BaseObject.data",
return_value=mock_settings_hash)
if expected_exception is not None:
with pytest.raises(ExecutionError) as excinfo:
upgrade_db.upgrade_db_with_graph(1, 2)
assert excinfo.value is expected_exception
else:
upgrade_db.upgrade_db_with_graph(1, 2)
0
Example 32
Project: networking-cisco Source File: test_cisco_nexus_base.py
def _config_side_effects_on_count(self, match_config, exc,
match_range=None):
"""Generates config-dependent side effect for ncclient.
This method was written to configure side_effects for both
ncclient edit_config and get_config drivers. In the case
of edit_config, the arguments target and config are passed
into _side_effect_method. In the case of get, the argument
filter is passed into _side_effect_method. For the sake of
simplicity, the _side_effect_method was written to handle
either case.
Additionally, arguments start and count were passed in to
handle the number of times to raise exception for a given
match. Also match_config if passed in as an empty string,
is interpreted as match not desired.
Usage Examples:
First 2 times for the given mock side-effect, throw an exception.
_config_side_effects_on_count('', Exception(test_id), range(0,2))
Two times after 4th attempt for the given mock side-effect,
throw an exception.
_config_side_effects_on_count('', Exception(test_id), range(4,6))
First 2 time, for the given mock side-effect which the call
matches 'match string', throw an exception.
_config_side_effects_on_count('match string',
Exception(test_id), range(0,2))
do 'no range check' and for the given mock side-effect which the call
matches 'match string', throw an exception.
_config_side_effects_on_count('match string',
Exception(test_id))
"""
keywords = match_config.split()
def _side_effect_method(target=None, config=None, filter=None):
if not hasattr(self, "position"):
self.position = 0
if config is None:
config = filter[1]
match = True if not keywords else all(
word in config for word in keywords)
# If there is a match, check count in range; otherwise
# mark as unmatch
if match and match_range is not None:
match = self.position in match_range
self.position += 1
if match:
raise exc
else:
return mock.DEFAULT
return _side_effect_method