Python unittest.mock.call() Examples
The following are 30
code examples of unittest.mock.call().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
unittest.mock
, or try the search function
.

Example #1
Source File: test_odbc_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_rpc_multiple_field_response(self): self._create_connector("odbc_rpc.json", override_rpc_params=True) row = self.db_cursor.execute("{CALL get_values}").fetchone() expected_values = {} for d in self.db_cursor.description: expected_values[d[0]] = getattr(row, d[0]) data = {"device": "someDevice", "data": { "id": 1, "method": "get_values", "params": { "result": True } }} self.connector.server_side_rpc_handler(data) sleep(1) self.gateway.send_rpc_reply.assert_has_calls([call(data["device"], data["data"]["id"], expected_values)])
Example #2
Source File: test_report.py From zun with Apache License 2.0 | 6 votes |
def test_ensure_resource_provider_refresh_fetch(self, mock_ref_assoc, mock_gpit): """Make sure refreshes are called with the appropriate UUIDs and flags when we fetch the provider tree from placement. """ tree_uuids = set([uuids.root, uuids.one, uuids.two]) mock_gpit.return_value = [{'uuid': u, 'name': u, 'generation': 42} for u in tree_uuids] self.assertEqual(uuids.root, self.client._ensure_resource_provider(self.context, uuids.root)) mock_gpit.assert_called_once_with(self.context, uuids.root) mock_ref_assoc.assert_has_calls( [mock.call(self.context, uuid, force=True) for uuid in tree_uuids]) self.assertEqual(tree_uuids, set(self.client._provider_tree.get_provider_uuids()))
Example #3
Source File: test_publish_cloudrun.py From datasette with Apache License 2.0 | 6 votes |
def test_publish_cloudrun(mock_call, mock_output, mock_which): mock_output.return_value = "myproject" mock_which.return_value = True runner = CliRunner() with runner.isolated_filesystem(): open("test.db", "w").write("data") result = runner.invoke( cli.cli, ["publish", "cloudrun", "test.db", "--service", "test"] ) assert 0 == result.exit_code tag = "gcr.io/{}/datasette".format(mock_output.return_value) mock_call.assert_has_calls( [ mock.call("gcloud builds submit --tag {}".format(tag), shell=True), mock.call( "gcloud run deploy --allow-unauthenticated --platform=managed --image {} test".format( tag ), shell=True, ), ] )
Example #4
Source File: test_volume_mapping.py From zun with Apache License 2.0 | 6 votes |
def test_refresh(self): uuid = self.fake_volume_mapping['uuid'] new_uuid = uuidutils.generate_uuid() returns = [dict(self.fake_volume_mapping, uuid=uuid), dict(self.fake_volume_mapping, uuid=new_uuid)] expected = [mock.call(self.context, uuid), mock.call(self.context, uuid)] with mock.patch.object(self.dbapi, 'get_volume_mapping_by_uuid', side_effect=returns, autospec=True) as mock_get_volume_mapping: volume_mapping = objects.VolumeMapping.get_by_uuid(self.context, uuid) self.assertEqual(uuid, volume_mapping.uuid) volume_mapping.refresh() self.assertEqual(new_uuid, volume_mapping.uuid) self.assertEqual(expected, mock_get_volume_mapping.call_args_list) self.assertEqual(self.context, volume_mapping._context)
Example #5
Source File: test_container.py From zun with Apache License 2.0 | 6 votes |
def test_refresh(self): uuid = self.fake_container['uuid'] container_type = self.fake_container['container_type'] new_uuid = uuidutils.generate_uuid() returns = [dict(self.fake_container, uuid=uuid), dict(self.fake_container, uuid=new_uuid)] expected = [mock.call(self.context, container_type, uuid), mock.call(self.context, container_type, uuid)] with mock.patch.object(self.dbapi, 'get_container_by_uuid', side_effect=returns, autospec=True) as mock_get_container: container = objects.Container.get_by_uuid(self.context, uuid) self.assertEqual(uuid, container.uuid) container.refresh() self.assertEqual(new_uuid, container.uuid) self.assertEqual(expected, mock_get_container.call_args_list) self.assertEqual(self.context, container._context)
Example #6
Source File: test_components_repository_repository.py From skelebot with MIT License | 6 votes |
def test_execute_push_artifactory_all(self, mock_artifactory, mock_remove, mock_copy): config = sb.objects.config.Config(version="1.0.0") args = argparse.Namespace(job="push", force=True, artifact='ALL', user='sean', token='abc123') self.artifactory.execute(config, args) mock_artifactory.assert_has_calls([ mock.call("artifactory.test.com/ml/test/test_v1.0.0.pkl", auth=('sean', 'abc123')), mock.call("artifactory.test.com/ml/test/test2_v1.0.0.pkl", auth=('sean', 'abc123')) ], any_order=True) mock_copy.assert_has_calls([ mock.call("test.pkl", "test_v1.0.0.pkl"), mock.call("test2.pkl", "test2_v1.0.0.pkl") ], any_order=True) mock_remove.assert_has_calls([ mock.call("test_v1.0.0.pkl"), mock.call("test2_v1.0.0.pkl") ], any_order=True)
Example #7
Source File: test_compute_node.py From zun with Apache License 2.0 | 6 votes |
def test_refresh(self): uuid = self.fake_compute_node['uuid'] hostname = self.fake_compute_node['hostname'] new_hostname = 'myhostname' returns = [dict(self.fake_compute_node, hostname=hostname), dict(self.fake_compute_node, hostname=new_hostname)] expected = [mock.call(self.context, uuid), mock.call(self.context, uuid)] with mock.patch.object(self.dbapi, 'get_compute_node', side_effect=returns, autospec=True) as mock_get: compute_node = objects.ComputeNode.get_by_uuid(self.context, uuid) self.assertEqual(hostname, compute_node.hostname) compute_node.refresh() self.assertEqual(new_hostname, compute_node.hostname) self.assertEqual(expected, mock_get.call_args_list) self.assertEqual(self.context, compute_node._context)
Example #8
Source File: test_resource_provider.py From zun with Apache License 2.0 | 6 votes |
def test_refresh(self): uuid = self.fake_provider['uuid'] new_uuid = uuidutils.generate_uuid() returns = [dict(self.fake_provider, uuid=uuid), dict(self.fake_provider, uuid=new_uuid)] expected = [mock.call(self.context, uuid), mock.call(self.context, uuid)] with mock.patch.object(self.dbapi, 'get_resource_provider', side_effect=returns, autospec=True) as mock_get_resource_provider: provider = objects.ResourceProvider.get_by_uuid(self.context, uuid) self.assertEqual(uuid, provider.uuid) provider.refresh() self.assertEqual(new_uuid, provider.uuid) self.assertEqual( expected, mock_get_resource_provider.call_args_list) self.assertEqual(self.context, provider._context)
Example #9
Source File: tests.py From trove-dashboard with Apache License 2.0 | 6 votes |
def test_master_list_pagination(self): request = http.HttpRequest() first_part = common.Paginated(items=self.databases.list()[:1], next_marker='marker') second_part = common.Paginated(items=self.databases.list()[1:]) self.mock_instance_list.side_effect = [ first_part, second_part, first_part] advanced_page = create_instance.AdvancedAction(request, None) choices = advanced_page.populate_master_choices(request, None) expected_calls = [ mock.call(request), mock.call(request, marker='marker'), mock.call(request)] self.assertEqual(expected_calls, self.mock_instance_list.call_args_list) self.assertTrue(len(choices) == len(self.databases.list()) + 1)
Example #10
Source File: tests.py From trove-dashboard with Apache License 2.0 | 6 votes |
def test_show_root(self): database = self.databases.first() database.id = u'id' user = self.database_user_roots.first() self.mock_instance_get.return_value = database self.mock_root_show.return_value = user url = reverse('horizon:project:databases:manage_root', args=['id']) res = self.client.get(url) self.mock_instance_get.assert_called_once_with( test.IsHttpRequest(), test.IsA(str)) self.assert_mock_multiple_calls_with_same_arguments( self.mock_root_show, 2, mock.call(test.IsHttpRequest(), database.id)) self.assertTemplateUsed( res, 'project/databases/manage_root.html')
Example #11
Source File: test_toplevel.py From arctic with GNU Lesser General Public License v2.1 | 6 votes |
def test_read(): self = create_autospec(TopLevelTickStore) tsl = TickStoreLibrary(create_autospec(TickStore), create_autospec(DateRange)) self._get_libraries.return_value = [tsl, tsl] dr = create_autospec(DateRange) with patch('pandas.concat') as concat: res = TopLevelTickStore.read(self, sentinel.symbol, dr, columns=sentinel.include_columns, include_images=sentinel.include_images) assert concat.call_args_list == [call([tsl.library.read.return_value, tsl.library.read.return_value])] assert res == concat.return_value assert tsl.library.read.call_args_list == [call(sentinel.symbol, tsl.date_range.intersection.return_value, sentinel.include_columns, include_images=sentinel.include_images), call(sentinel.symbol, tsl.date_range.intersection.return_value, sentinel.include_columns, include_images=sentinel.include_images)]
Example #12
Source File: test_report.py From zun with Apache License 2.0 | 6 votes |
def test_get_sharing_providers_error(self, logging_mock): # Ensure _get_sharing_providers() logs an error and raises if the # placement API call doesn't respond 200 resp_mock = mock.Mock(status_code=503) self.ks_adap_mock.get.return_value = resp_mock self.ks_adap_mock.get.return_value.headers = { 'x-openstack-request-id': uuids.request_id} uuid = uuids.agg self.assertRaises(exception.ResourceProviderRetrievalFailed, self.client._get_sharing_providers, self.context, [uuid]) expected_url = ('/resource_providers?member_of=in:' + uuid + '&required=MISC_SHARES_VIA_AGGREGATE') self.ks_adap_mock.get.assert_called_once_with( expected_url, microversion='1.18', endpoint_filter=mock.ANY, logger=mock.ANY, headers={'X-Openstack-Request-Id': self.context.global_id}) # A 503 Service Unavailable should trigger an error log that # includes the placement request id self.assertTrue(logging_mock.called) self.assertEqual(uuids.request_id, logging_mock.call_args[0][1]['placement_req_id'])
Example #13
Source File: test_odbc_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_iterator_persistence(self): self._create_connector("odbc_iterator.json") iterator_file_name = self.connector._OdbcConnector__iterator_file_name device_id = 1 # For eval data = {"deviceName": eval(self.config["mapping"]["device"]["name"]), "deviceType": self.connector._OdbcConnector__connector_type, "attributes": [], "telemetry": [{"value": 0}]} self.gateway.send_to_storage.assert_has_calls([call(self.connector.get_name(), data)]) self.connector.close() sleep(1) self.assertTrue(Path(self.CONFIG_PATH + "odbc" + path.sep + iterator_file_name).exists()) self.connector = OdbcConnector(self.gateway, self.config, "odbc") self.connector.open() sleep(1) data["telemetry"] = [{"value": 5}] self.gateway.send_to_storage.assert_has_calls([call(self.connector.get_name(), data)])
Example #14
Source File: test_odbc_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_restore_connection(self): self._create_connector("odbc_iterator.json") postgres_port = self.postgresql.dsn()["port"] device_id = 1 # For eval data = {"deviceName": eval(self.config["mapping"]["device"]["name"]), "deviceType": self.connector._OdbcConnector__connector_type, "attributes": [], "telemetry": [{"value": 0}]} self.gateway.send_to_storage.assert_has_calls([call(self.connector.get_name(), data)]) self.postgresql.stop() sleep(self.config["polling"]["period"]) self.assertFalse(self.connector.is_connected()) sleep(self.config["connection"]["reconnectPeriod"]) self.postgresql = testing.postgresql.Postgresql(port=postgres_port) self._init_test_db() sleep(self.config["connection"]["reconnectPeriod"]) self.assertTrue(self.connector.is_connected()) data["telemetry"] = [{"value": 5}] self.gateway.send_to_storage.assert_has_calls([call(self.connector.get_name(), data)])
Example #15
Source File: test_odbc_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_rpc_no_connection(self): self._create_connector("odbc_rpc.json", connection_str="fake_connection_string") self.assertFalse(self.connector.is_connected()) data = {"device": "someDevice", "data": { "id": 1, "method": "get_values", "params": { "result": True } }} self.connector.server_side_rpc_handler(data) sleep(1) self.gateway.send_rpc_reply.assert_has_calls([call(data["device"], data["data"]["id"], {"success": False})])
Example #16
Source File: tests.py From trove-dashboard with Apache License 2.0 | 6 votes |
def test_detail_backup_incr(self): incr_backup = self.database_backups.list()[2] parent_backup = self.database_backups.list()[1] self.mock_backup_get.side_effect = [incr_backup, parent_backup] self.mock_instance_get.return_value = self.databases.list()[1] url = reverse('horizon:project:database_backups:detail', args=[incr_backup.id]) res = self.client.get(url) self.assertEqual( [mock.call(test.IsHttpRequest(), test.IsA(str)), mock.call(test.IsHttpRequest(), incr_backup.parent_id)], self.mock_backup_get.call_args_list) self.mock_instance_get.assert_called_once_with( test.IsHttpRequest(), test.IsA(str)) self.assertTemplateUsed(res, 'project/database_backups/details.html')
Example #17
Source File: test_report.py From zun with Apache License 2.0 | 6 votes |
def test_aggregate_add_host_retry_success( self, mock_get_by_name, mock_get_aggs, mock_set_aggs): mock_get_by_name.return_value = { 'uuid': uuids.cn1, 'generation': 1, } gens = (42, 43, 44) mock_get_aggs.side_effect = ( report.AggInfo(aggregates=set([]), generation=gen) for gen in gens) mock_set_aggs.side_effect = ( exception.ResourceProviderUpdateConflict( uuid='uuid', generation=42, error='error'), exception.ResourceProviderUpdateConflict( uuid='uuid', generation=43, error='error'), None, ) self.client.aggregate_add_host(self.context, uuids.agg1, host_name='cn1') mock_set_aggs.assert_has_calls([mock.call( self.context, uuids.cn1, set([uuids.agg1]), use_cache=False, generation=gen) for gen in gens])
Example #18
Source File: test_report.py From zun with Apache License 2.0 | 6 votes |
def test_aggregate_add_host_retry_raises( self, mock_get_by_name, mock_get_aggs, mock_set_aggs): mock_get_by_name.return_value = { 'uuid': uuids.cn1, 'generation': 1, } gens = (42, 43, 44, 45) mock_get_aggs.side_effect = ( report.AggInfo(aggregates=set([]), generation=gen) for gen in gens) mock_set_aggs.side_effect = ( exception.ResourceProviderUpdateConflict( uuid='uuid', generation=gen, error='error') for gen in gens) self.assertRaises( exception.ResourceProviderUpdateConflict, self.client.aggregate_add_host, self.context, uuids.agg1, host_name='cn1') mock_set_aggs.assert_has_calls([mock.call( self.context, uuids.cn1, set([uuids.agg1]), use_cache=False, generation=gen) for gen in gens])
Example #19
Source File: test_report.py From zun with Apache License 2.0 | 6 votes |
def test_aggregate_remove_host_retry_success( self, mock_get_by_name, mock_get_aggs, mock_set_aggs): mock_get_by_name.return_value = { 'uuid': uuids.cn1, 'generation': 1, } gens = (42, 43, 44) mock_get_aggs.side_effect = ( report.AggInfo(aggregates=set([uuids.agg1]), generation=gen) for gen in gens) mock_set_aggs.side_effect = ( exception.ResourceProviderUpdateConflict( uuid='uuid', generation=42, error='error'), exception.ResourceProviderUpdateConflict( uuid='uuid', generation=43, error='error'), None, ) self.client.aggregate_remove_host(self.context, uuids.agg1, 'cn1') mock_set_aggs.assert_has_calls([mock.call( self.context, uuids.cn1, set([]), use_cache=False, generation=gen) for gen in gens])
Example #20
Source File: test_chance_scheduler.py From zun with Apache License 2.0 | 6 votes |
def test_select_destinations(self, mock_random_choice, mock_hosts_up): all_hosts = ['host1', 'host2', 'host3', 'host4'] def _return_hosts(*args, **kwargs): return all_hosts mock_random_choice.side_effect = ['host3'] mock_hosts_up.side_effect = _return_hosts test_container = utils.get_test_container() containers = [objects.Container(self.context, **test_container)] extra_spec = {} dests = self.driver_cls().select_destinations(self.context, containers, extra_spec) self.assertEqual(1, len(dests)) (host, node) = (dests[0]['host'], dests[0]['nodename']) self.assertEqual('host3', host) self.assertIsNone(node) calls = [mock.call(all_hosts)] self.assertEqual(calls, mock_random_choice.call_args_list)
Example #21
Source File: test_scheduler.py From zun with Apache License 2.0 | 6 votes |
def test_hosts_up(self, mock_service_is_up, mock_list_by_binary): service1 = objects.ZunService() service2 = objects.ZunService() service1.host = 'host1' service1.disabled = False service2.host = 'host2' service2.disabled = False services = [service1, service2] mock_list_by_binary.return_value = services mock_service_is_up.side_effect = [False, True] result = self.driver.hosts_up(self.context) self.assertEqual(['host2'], result) mock_list_by_binary.assert_called_once_with(self.context, 'zun-compute') calls = [mock.call(service1), mock.call(service2)] self.assertEqual(calls, mock_service_is_up.call_args_list)
Example #22
Source File: test_odbc_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_timeseries_send_on_change(self): self._create_connector("odbc_timeseries.json", True) rows = self.db_cursor.execute("SELECT DISTINCT long_v " "FROM timeseries " "ORDER BY long_v ASC").fetchall() self.assertEqual(self.gateway.send_to_storage.call_count, len(rows)) calls = [] device_id = 1 # for eval for row in rows: calls.append(call(self.connector.get_name(), {"deviceName": eval(self.config["mapping"]["device"]["name"]), "deviceType": self.config["mapping"]["device"]["type"], "attributes": [], "telemetry": [{"value": row.long_v}]})) self.gateway.send_to_storage.assert_has_calls(calls)
Example #23
Source File: test_shard.py From bloop with MIT License | 6 votes |
def test_get_records_after_head(shard, session): """Once the shard has reached head, get_stream_records is called once per get_records.""" shard.empty_responses = CALLS_TO_REACH_HEAD # Intentionally provide more than one page to ensure # the call isn't stopping because there is only one page. records = build_get_records_responses(1, 1) session.get_stream_records.side_effect = records returned_records = shard.get_records() assert len(returned_records) == 1 assert returned_records[0]["meta"]["sequence_number"] == "0" assert session.get_stream_records.called_once_with(shard.iterator_id) assert shard.iterator_type == "at_sequence" assert shard.sequence_number == "0"
Example #24
Source File: test_coordinator.py From bloop with MIT License | 6 votes |
def test_next_from_buffer(coordinator, shard, session): """next(coordinator) doesn't call GetRecords when the buffer has records""" shard.iterator_type = "latest" shard.sequence_number = None coordinator.active.append(shard) record = local_record(sequence_number="25") coordinator.buffer.push(record, shard) returned_record = next(coordinator) assert returned_record is record assert shard.iterator_type == "after_sequence" assert shard.sequence_number == "25" assert not coordinator.buffer # No outbound calls session.get_stream_records.assert_not_called() session.get_shard_iterator.assert_not_called() session.describe_stream.assert_not_called() assert shard in coordinator.active
Example #25
Source File: test_coordinator.py From bloop with MIT License | 6 votes |
def test_heartbeat_until_sequence_number(coordinator, session): """After heartbeat() finds records for a shard, the shard doesn't check during the next heartbeat.""" shard = Shard(stream_arn=coordinator.stream_arn, shard_id="shard-id", session=session, iterator_id="iterator-id", iterator_type="latest") coordinator.active.append(shard) session.get_stream_records.side_effect = build_get_records_responses(1, 0) # First call fetches records from DynamoDB coordinator.heartbeat() assert coordinator.buffer assert shard.sequence_number is not None session.get_stream_records.assert_called_once_with("iterator-id") # Second call skips the shard, since it now has a sequence_number. coordinator.heartbeat() assert session.get_stream_records.call_count == 1
Example #26
Source File: connection_test.py From aioredis with MIT License | 6 votes |
def test_connection_parser_argument(create_connection, server): klass = mock.MagicMock() klass.return_value = reader = mock.Mock() conn = await create_connection(server.tcp_address, parser=klass) assert klass.mock_calls == [ mock.call(protocolError=ProtocolError, replyError=ReplyError), ] response = [False] def feed_gets(data, **kwargs): response[0] = data reader.gets.side_effect = lambda *args, **kwargs: response[0] reader.feed.side_effect = feed_gets assert b'+PONG\r\n' == await conn.execute('ping')
Example #27
Source File: test_completiondelegate.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def test_highlighted(qtbot): """Make sure highlighting works. Note that with Qt 5.11.3 and > 5.12.1 we need to call setPlainText *after* creating the highlighter for highlighting to work. Ideally, we'd test whether CompletionItemDelegate._get_textdoc() works properly, but testing that is kind of hard, so we just test it in isolation here. """ doc = QTextDocument() completiondelegate._Highlighter(doc, 'Hello', Qt.red) doc.setPlainText('Hello World') # Needed so the highlighting actually works. edit = QTextEdit() qtbot.addWidget(edit) edit.setDocument(doc) colors = [f.foreground().color() for f in doc.allFormats()] assert QColor('red') in colors
Example #28
Source File: test_lineparser.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def test_binary(self, mocker): """Test if _open and _write correctly handle binary files.""" open_mock = mock.mock_open() mocker.patch('builtins.open', open_mock) testdata = b'\xf0\xff' lineparser = lineparsermod.BaseLineParser( self.CONFDIR, self.FILENAME, binary=True) with lineparser._open('r') as f: lineparser._write(f, [testdata]) open_mock.assert_called_once_with( str(pathlib.Path(self.CONFDIR) / self.FILENAME), 'rb') open_mock().write.assert_has_calls([ mock.call(testdata), mock.call(b'\n') ])
Example #29
Source File: test_snekbox.py From bot with MIT License | 6 votes |
def test_continue_eval_does_continue(self, partial_mock): """Test that the continue_eval function does continue if required conditions are met.""" ctx = MockContext(message=MockMessage(add_reaction=AsyncMock(), clear_reactions=AsyncMock())) response = MockMessage(delete=AsyncMock()) new_msg = MockMessage() self.bot.wait_for.side_effect = ((None, new_msg), None) expected = "NewCode" self.cog.get_code = create_autospec(self.cog.get_code, spec_set=True, return_value=expected) actual = await self.cog.continue_eval(ctx, response) self.cog.get_code.assert_awaited_once_with(new_msg) self.assertEqual(actual, expected) self.bot.wait_for.assert_has_awaits( ( call( 'message_edit', check=partial_mock(snekbox.predicate_eval_message_edit, ctx), timeout=snekbox.REEVAL_TIMEOUT, ), call('reaction_add', check=partial_mock(snekbox.predicate_eval_emoji_reaction, ctx), timeout=10) ) ) ctx.message.add_reaction.assert_called_once_with(snekbox.REEVAL_EMOJI) ctx.message.clear_reactions.assert_called_once() response.delete.assert_called_once()
Example #30
Source File: test_base.py From bot with MIT License | 6 votes |
def test_send_prompt_adds_reactions(self): """The message should have reactions for confirmation added.""" extant_message = helpers.MockMessage() subtests = ( (extant_message, lambda: (None, extant_message)), (None, self.mock_get_channel), (None, self.mock_fetch_channel), ) for message_arg, mock_ in subtests: subtest_msg = "Extant message" if mock_.__name__ == "<lambda>" else mock_.__name__ with self.subTest(msg=subtest_msg): _, mock_message = mock_() await self.syncer._send_prompt(message_arg) calls = [mock.call(emoji) for emoji in self.syncer._REACTION_EMOJIS] mock_message.add_reaction.assert_has_calls(calls)