def test_set_power_state_forcerestart(self): server = mock.Mock(id=self.uuid, power_state=1) self.nova_mock.return_value.get_server.return_value = server self.test_driver.set_power_state( self.uuid, 'ForceRestart') compute = self.nova_mock.return_value.compute compute.reboot_server.assert_called_once_with( self.uuid, reboot_type='HARD')
def test_ensure_no_retry(self): mock_callback = mock.Mock(side_effect=IOError) self.assertRaises(messaging.MessageDeliveryFailure, self.connection.ensure, mock_callback, retry=0) self.assertEqual(1, self.kombu_connect.call_count) self.assertEqual(2, mock_callback.call_count)
def test_listen(self): t = transport.Transport(_FakeDriver(cfg.CONF)) t._driver.listen = mock.Mock() t._listen(self._target, 1, None) t._driver.listen.assert_called_once_with(self._target, 1, None)
def mocked_config(): """Mock Pytest config for testing.""" mocked_config = mock.create_autospec(Config) mocked_config._reportportal_configured = True mocked_config.rootdir = py.path.local('/path/to') mocked_config.trace = TagTracer().get('root') mocked_config.pluginmanager = mock.Mock() return mocked_config
def _make_aggregate_request(self, aggregate_by, uuid): request = mock.Mock() request.query_params = { 'aggregate': aggregate_by, 'uuid': uuid, } return self.aggregate_filter.filter(request, self.queryset, None)
def setUp(self): super(EventletContextManagerSpawnTest, self).setUp() self.before = mock.Mock() self.callback = mock.Mock() self.after = mock.Mock() self.exception_call = mock.Mock() @contextlib.contextmanager def context_mgr(): self.before() try: yield lambda: self.callback() except ExceptedException: self.exception_call() self.after() self.mgr = context_mgr()
def mocked_item(mocked_session, mocked_module): """Mock Pytest item for testing.""" test_item = mock.Mock() test_item.session = mocked_session test_item.fspath = py.path.local('/path/to/test') test_item.name = 'test_item' test_item.parent = mocked_module return test_item
def test_dispatcher(self): endpoints = [ mock.Mock(spec=_FakeEndpoint, target=oslo_messaging.Target(**e)) for e in self.endpoints ] serializer = None target = oslo_messaging.Target() dispatcher = oslo_messaging.RPCDispatcher(target, endpoints, serializer) def check_reply(reply=None, failure=None, log_failure=True): if self.ex and failure is not None: ex = failure[1] self.assertFalse(self.success, ex) self.assertIsNotNone(self.ex, ex) self.assertIsInstance(ex, self.ex, ex) if isinstance(ex, oslo_messaging.NoSuchMethod): self.assertEqual(self.msg.get('method'), ex.method) elif isinstance(ex, oslo_messaging.UnsupportedVersion): self.assertEqual(self.msg.get('version', '1.0'), ex.version) if ex.method: self.assertEqual(self.msg.get('method'), ex.method) else: self.assertTrue(self.success, failure) self.assertIsNone(failure) incoming = mock.Mock(ctxt=self.ctxt, message=self.msg) incoming.reply.side_effect = check_reply callback = dispatcher(incoming) callback.run() callback.done() for n, endpoint in enumerate(endpoints): for method_name in ['foo', 'bar']: method = getattr(endpoint, method_name) if self.dispatch_to and n == self.dispatch_to['endpoint'] and \ method_name == self.dispatch_to['method']: method.assert_called_once_with(self.ctxt, **self.msg.get('args', {})) else: self.assertEqual(0, method.call_count) self.assertEqual(1, incoming.reply.call_count)
def test_wait_launch(time_mock): """Test wait_launch() function for the correct behavior.""" time_mock.time.side_effect = [0, 1, 2] rp_client = mock.Mock() rp_client.launch_id = None with pytest.raises(Exception) as err: wait_launch(rp_client) assert str(err.value) == 'Launch has not started.'
def test_send_no_timeout(self, fake_publish): transport = oslo_messaging.get_transport(self.conf, 'kombu+memory:////') with transport._driver._get_connection( driver_common.PURPOSE_SEND) as pool_conn: conn = pool_conn.connection conn._publish(mock.Mock(), 'msg', routing_key='routing_key') fake_publish.assert_called_with('msg', expiration=None)
def test_yum_is_modified(monkeypatch, pkg_type, subprocess_ret, expected_result): monkeypatch.setattr(pkgmanager, "TYPE", value=pkg_type) run_subprocess = mock.Mock(return_value=(subprocess_ret, "anything")) monkeypatch.setattr(utils, "run_subprocess", value=run_subprocess) assert YumConf.is_modified() == expected_result
def setUp(self): self._pika_engine = mock.Mock() self._poller_connection_mock = mock.Mock() self._poller_channel_mock = mock.Mock() self._poller_connection_mock.channel.return_value = ( self._poller_channel_mock) self._pika_engine.create_connection.return_value = ( self._poller_connection_mock) self._prefetch_count = 123 self._exchange = "rpc_reply_exchange" self._queue = "rpc_reply_queue" self._pika_engine.rpc_reply_retry_delay = 12132543456 self._pika_engine.rpc_queue_expiration = 12345 self._pika_engine.rpc_reply_retry_attempts = 3
def test_is_loaded_kernel_latest_eus_system( pretend_os, repoquery_version, uname_version, return_code, package_name, raise_system_exit, tmpdir, monkeypatch, caplog, ): fake_reposdir_path = str(tmpdir) monkeypatch.setattr(checks, "get_hardcoded_repofiles_dir", value=lambda: fake_reposdir_path) run_subprocess_mocked = mock.Mock( spec=run_subprocess, side_effect=run_subprocess_side_effect( ( ( "repoquery", "--quiet", "--qf", '"%{BUILDTIME}\\t%{VERSION}-%{RELEASE}\\t%{REPOID}"', "--setopt=reposdir=%s" % fake_reposdir_path, package_name, ), ( repoquery_version, return_code, ), ), (("uname", "-r"), (uname_version, return_code)), ), ) monkeypatch.setattr( checks, "run_subprocess", value=run_subprocess_mocked, ) if raise_system_exit: with pytest.raises(SystemExit): is_loaded_kernel_latest() repoquery_kernel_version = repoquery_version.split("\t")[1] uname_kernel_version = uname_version.rsplit(".", 1)[0] assert ( "The version of the loaded kernel is different from the latest version in repositories defined in the %s folder" % fake_reposdir_path) assert ("Latest kernel version available in baseos: %s\n" % repoquery_kernel_version in caplog.records[-1].message) assert "Loaded kernel version: %s\n" % uname_kernel_version in caplog.records[ -1].message else: is_loaded_kernel_latest() assert "The currently loaded kernel is at the latest version." in caplog.records[ -1].message
def test_pre_ponr_checks(monkeypatch): ensure_compatibility_of_kmods_mock = mock.Mock() monkeypatch.setattr( checks, "ensure_compatibility_of_kmods", value=ensure_compatibility_of_kmods_mock, ) checks.perform_pre_ponr_checks() ensure_compatibility_of_kmods_mock.assert_called_once()
def test_zmqincomingmessage(self): msg = impl_zmq.ZmqIncomingMessage(mock.Mock(), None, 'msg.foo') msg.reply("abc") self.assertIsInstance(msg.received, impl_zmq.ZmqIncomingMessage.ReceivedReply) self.assertIsInstance(msg.received, impl_zmq.ZmqIncomingMessage.ReceivedReply) self.assertEqual(msg.received.reply, "abc") msg.requeue()
def test_calling_registration_command_activation_key(self, monkeypatch): monkeypatch.setattr(utils, "run_subprocess", mock.Mock(return_value=("", 0))) monkeypatch.setattr(utils, "run_cmd_in_pty", mock.Mock(return_value=("", 0))) reg_cmd = subscription.RegistrationCommand(activation_key="0xDEADBEEF", org="Local Organization") assert reg_cmd() == ("", 0) utils.run_subprocess.assert_called_once_with( [ "subscription-manager", "register", "--force", "--activationkey=0xDEADBEEF", "--org=Local Organization" ], print_cmd=False, ) assert utils.run_cmd_in_pty.call_count == 0
def test_when_evetlet_is_unavailable_then_load_zmq(self): zmq_async.eventletutils.is_monkey_patched = lambda _: False mock_try_import = mock.Mock() zmq_async.importutils.try_import = mock_try_import zmq_async.import_zmq() mock_try_import.assert_called_with('zmq', default=None)
def data_elements(): """Mock data elements""" data_elements = [ mock.Mock(spec=smqtk.representation.DataElement) for i in range(NUM_BASE_ELEMENTS) ] for index, de in enumerate(data_elements): de.uuid.return_value = index return data_elements
def test_unregister_system_skipped(self, monkeypatch, caplog, tool_opts): tool_opts.keep_rhsm = True monkeypatch.setattr(pkghandler, "get_installed_pkg_objects", mock.Mock()) subscription.unregister_system() assert "Skipping due to the use of --keep-rhsm." in caplog.text pkghandler.get_installed_pkg_objects.assert_not_called()
def dummy_transform(data_element): """Transform function for testing augmented descriptor computation""" new_elements = [ mock.Mock(spec=smqtk.representation.DataElement) for i in range(data_element.uuid() + 1) ] for index, de in enumerate(new_elements): de.uuid.return_value = data_element.uuid()**2 + index return new_elements
def __init__(self, name='Virtual machine', runtime_state='OK', error_message=''): self.pk = 1 self.name = name self.runtime_state = runtime_state self.error_message = error_message self.save = mock.Mock()
def test_pytest_collection_finish(mocked_session): """Test collection_finish with the configured RP plugin. :param mocked_session: pytest fixture """ mocked_session.config.py_test_service = mock.Mock() pytest_collection_finish(mocked_session) mocked_session.config.py_test_service.collect_tests. \ assert_called_with(mocked_session)
def test_find_latest(self): mock_config = mock.Mock(instance_tag='spotr') fake_client, config = mock_client() latest_instance = instance.find_latest(fake_client, mock_config) self.assertEqual(latest_instance.id, config['instance_id']) self.assertEqual(latest_instance.volume_id, config['volume_id']) self.assertEqual(latest_instance.launch_time, config['launch_time']) self.assertEqual(latest_instance.ip_address, config['ip_address']) self.assertEqual(latest_instance.has_security_groups, True)
def testDelegateUploadFileToObjectZipped(self, mock_unlink): mock_stream = mock.Mock() mock_stream.close = mock.Mock() mock_upload_url = mock.Mock() mock_upload_url.object_name = 'Sample' def DelegateUpload(): return 'a', 'b' elapsed_time, uploaded_object = _DelegateUploadFileToObject( DelegateUpload, mock_upload_url, mock_stream, True, False, False, None) # Ensure results are passed through. self.assertEqual(elapsed_time, 'a') self.assertEqual(uploaded_object, 'b') # Ensure the file was unlinked. self.assertTrue(mock_unlink.called) # Ensure close was called. self.assertTrue(mock_stream.close.called)
def testRaisesErrorIfConflictingJsonAndMtlsHost(self, mock_get_context_config): mock_context_config = mock.Mock() mock_context_config.use_client_certificate = True mock_get_context_config.return_value = mock_context_config with SetBotoConfigForTest([('Credentials', 'gs_json_host', 'host')]): with self.assertRaises(cloud_api.ArgumentException): gcs_json_api.GcsJsonApi(None, None, None, None)
def test_zmqconnection_create_consumer_topic_exists(self, mock_reactor): mock_reactor.register = mock.Mock() conn = impl_zmq.Connection(self.driver.conf, self.driver) topic = 'topic.foo' context = mock.Mock() inaddr = ('ipc://%s/zmq_topic_topic.127.0.0.1' % (self.internal_ipc_dir)) conn.create_consumer(topic, context) conn.reactor.register.assert_called_with(context, inaddr, impl_zmq.zmq.PULL, subscribe=None, in_bind=False) conn.reactor.register.reset_mock() # Call again with same topic conn.create_consumer(topic, context) self.assertFalse(conn.reactor.register.called)
def testDelegateUploadFileToObjectGzipEncodedComposite(self, mock_lock): mock_stream = mock.Mock() mock_stream.close = mock.Mock() def DelegateUpload(): # Ensure the lock was not aquired before the delegate was called. self.assertFalse(mock_lock.__enter__.called) return 'a', 'b' elapsed_time, uploaded_object = _DelegateUploadFileToObject( DelegateUpload, 'url', mock_stream, False, True, True, None) # Ensure results are passed through. self.assertEqual(elapsed_time, 'a') self.assertEqual(uploaded_object, 'b') # Ensure close was called. self.assertTrue(mock_stream.close.called) # Ensure the lock was released. self.assertFalse(mock_lock.__exit__.called)
def test_zmqlistener_w_msg(self): listener = impl_zmq.ZmqListener(self.driver) kwargs = {'a': 1, 'b': 2} m = mock.Mock() ctxt = mock.Mock(autospec=impl_zmq.RpcContext) message = { 'namespace': 'name.space', 'method': m.fake_method, 'args': kwargs } eventlet.spawn_n(listener.dispatch, ctxt, message) resp = listener.poll(timeout=10) msg = { 'method': m.fake_method, 'namespace': 'name.space', 'args': kwargs } self.assertEqual(resp.message, msg)
def test_open_port_sg_without_from_or_to_ports(self): fake_client = mock.Mock(boto3.client('ec2')) attrs = { 'describe_security_groups.return_value': { 'SecurityGroups': [ { 'IpPermissions': [{ 'IpProtocol': 'TCP' }] } ] } } fake_client.configure_mock(**attrs) insta = mock.Mock(security_groups=[{'GroupId': 'sg-123'}]) result = instance.open_port(fake_client, insta, 8888) self.assertTrue(result)
def test_zmqdriver_multi_send_call_with_no_queues(self, mock_queues, mock_call): context = mock.Mock(autospec=impl_zmq.RpcContext) topic = 'testtopic' msg = 'jeronimo' mock_queues.return_value = None self.assertRaises(rpc_common.Timeout, impl_zmq._multi_send, self.driver, mock_call, context, topic, msg)