def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly") mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used") def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN)
def test_success(cli_paths): string_io = io.StringIO() pytest.helpers.create_cli_project(cli_paths.test_directory_path) material_path = pytest.helpers.create_cli_material( cli_paths.test_directory_path, "test_material") script = supriya.cli.ManageMaterialScript() command = ["--edit", "test_material"] mock_path = "supriya.cli.ProjectPackageScript._call_subprocess" with unittest.mock.patch(mock_path) as mock: mock.return_value = 0 with uqbar.io.RedirectedStreams( stdout=string_io), uqbar.io.DirectoryChange( cli_paths.inner_project_path): try: script(command) except SystemExit as e: raise RuntimeError("SystemExit: {}".format(e.code)) pytest.helpers.compare_strings( r""" Edit candidates: 'test_material' ... """, string_io.getvalue(), ) definition_path = material_path.joinpath("definition.py") command = "{} {!s}".format( supriya.config.get("core", "editor", fallback="vim"), definition_path) mock.assert_called_with(command)
def test_success(cli_paths): string_io = io.StringIO() pytest.helpers.create_cli_project(cli_paths.test_directory_path) material_path = pytest.helpers.create_cli_material( cli_paths.test_directory_path, "test_material" ) script = supriya.cli.ManageMaterialScript() command = ["--edit", "test_material"] mock_path = "supriya.cli.ProjectPackageScript._call_subprocess" with unittest.mock.patch(mock_path) as mock: mock.return_value = 0 with uqbar.io.RedirectedStreams(stdout=string_io), uqbar.io.DirectoryChange( cli_paths.inner_project_path ): try: script(command) except SystemExit as exception: if exception.args[0]: raise RuntimeError("SystemExit: {}".format(exception.code)) pytest.helpers.compare_strings( r""" Edit candidates: 'test_material' ... """, string_io.getvalue(), ) definition_path = material_path.joinpath("definition.py") command = "{} {!s}".format( supriya.config.get("core", "editor", fallback="vim"), definition_path ) mock.assert_called_with(command)
def test_init_and_close_loop_for_test(self): default_loop = self.create_default_loop() @asynctest.lenient class LoopTest(asynctest.TestCase): failing = False def runTest(self): try: self.assertIsNotNone(self.loop) self.assertFalse(self.loop.close.called) except Exception: self.failing = True raise def runFailingTest(self): self.runTest() raise SystemError() for method, test in itertools.product(self.run_methods, ('runTest', 'runFailingTest', )): with self.subTest(method=method, test=test), \ unittest.mock.patch('asyncio.new_event_loop') as mock: mock_loop = unittest.mock.Mock(asyncio.AbstractEventLoop) mock.return_value = mock_loop case = LoopTest(test) try: getattr(case, method)() except SystemError: pass mock.assert_called_with() mock_loop.close.assert_called_with() self.assertFalse(case.failing) self.assertIs(default_loop, asyncio.get_event_loop())
def test_received_cmd_is_invalid(self): inst = self.make_agent(core.BaseAgent, None) with unittest.mock.patch.object(inst.timer, 'wait', return_value=('invalid', None)): with unittest.mock.patch.object(inst.timer, 'response') as mock: inst.delayfunc(5) mock.assert_called_with(is_ok=False, detail='invalid cmd')
def test_init_slack_client(self, mock): """ Test __init__ method SlackClient call. """ proxies = {'http': {'vpprx': 0000}, 'https': {'vpprx': 0000}} token = 'TestToken' SlackHandler(token, '#channel', proxies) mock.assert_called_with(token, proxies=proxies)
def test_resolve_charm_type(config): """The config indicates the project is a charm.""" config.set(type="charm") cmd = PackCommand(config) with patch.object(cmd, "_pack_charm") as mock: cmd.run(noargs) mock.assert_called_with(noargs)
def test_init_url(self, mock): """ Test __init__ method correctly set url. """ flask_engine = FlaskEngine({'/test': {'cls': MethodView}}, {}) mock.assert_called_with( '/test', view_func=flask_engine._get_view(MethodView), methods=None )
def test_add_custom_constructors(self, mock): """ Test add_custom_constructors method return value and call yaml.add_constructor. """ custom_constructors = {'!test': YamlConstructor.simple_join} ret = self.yaml_parser.add_custom_constructors(custom_constructors) mock.assert_called_with('!test', custom_constructors['!test']) self.assertEqual(self.yaml_parser, ret)
def test_calculate_percentage_of_image_being_real_function_calls_convert_list_to_format_for_analysis_function( self): image_analysis = ImageAnalysis() with patch.object(DataUtils, 'convert_list_to_format_for_analysis') as mock: image_analysis.calculate_percentage_of_image_being_real("image") mock.assert_called_with("image")
def test_assert_called_with(self): mock = Mock() mock() mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a='fish', b='nothing') mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
def test_callbackConnect_non_gns3_server(http_client): params = { "virus": True, } mock = unittest.mock.MagicMock() http_client._callbackConnect("GET", "/version", mock, {}, {}, params) assert http_client._connected is False mock.assert_called_with({"message": "The remote server http://127.0.0.1:8000 is not a GNS3 server"}, error=True, server=http_client)
def test_add_getter_constructor(self, mock, mock_partial): """ Test add_getter_constructor method. """ name = '!test' data = {} ret = self.yaml_parser.add_getter_constructor(name, data) mock.assert_called_with(name, mock_partial()) self.assertEqual(self.yaml_parser, ret)
def _check(mock): mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2)
def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock('one') mock.assert_called_with('one') self.assertRaises(TypeError, mock, 'one', 'two')
def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException('Boom!')) try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass self.fail('java exception not raised') mock.assert_called_with(1, 2, fish=3)
def test_eval_without_handler(self, mocker): """Ensure that code is sent to octave for evaluation.""" mock = mocker.patch('matl_online.octave.OctaveEngine.eval') session = OctaveSession() code = '1 + 1' session.eval(code) mock.assert_called_with(code)
def test_fetch(self, mock, requests_mock): url = f'https://api.um.warszawa.pl/api/action/busestrams_get/' \ f'?resource_id=f2e5503e927d-4ad3-9500-4ab9e55deb59&apikey=foo' \ f'&type=1' requests_mock.get(url, text='{"result": "bar"}') fetcher = PositionFetcher(api_key='foo') fetcher.fetch() mock.assert_called_with('bar')
def test_fetch(self, mock, requests_mock): url = f'https://api.um.warszawa.pl/api/action/dbstore_get/' \ f'?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey=foo' requests_mock.get(url, text='{"result": "bar"}') fetcher = ScheduleFetcher(api_key='foo') fetcher.fetch() mock.assert_called_with('bar')
def assert_called_with(self, mock: mock.Mock, status: int, text_output: str, performance_data: str): mock.assert_called_with(url='1.2.3.4', user='******', password='******', status=status, host_name=cwatcher.HOSTNAME, service_name='my_service', text_output=text_output, performance_data=performance_data)
def test_emit_with_file(self, mock): """ Test emit method with fiel. """ file = '/file/path' record = self._record record.args = [file] self.handler.emit(record) mock.assert_called_with(record, file) self.assertIsNone(record.args)
def test_fetch_schedules(self, mock, requests_mock): url = f'https://api.um.warszawa.pl/api/action/dbtimetable_get/' \ f'?id=e923fa0e-d96c-43f9-ae6e-60518c9f3238&apikey=foo' \ f'&busstopId=420&busstopNr=0&line=100' requests_mock.get(url, text='{"result": "bar"}') fetcher = ScheduleFetcher(api_key='foo') fetcher.fetch_schedules(self.LINES[0], self.STOPS[0]) mock.assert_called_with('bar', self.LINES[0], self.STOPS[0])
def test_callbackConnect_version_non_local(http_client): params = { "local": False, "version": __version__ } mock = unittest.mock.MagicMock() http_client._callbackConnect("GET", "/version", mock, {}, {}, params) assert http_client._connected is False mock.assert_called_with({"message": "Running server is not a GNS3 local server (not started with --local)"}, error=True, server=http_client)
def test_callbackConnect_major_version_invalid(http_client): params = { "local": True, "version": "1.2.3" } mock = unittest.mock.MagicMock() http_client._callbackConnect("GET", "/version", mock, {}, {}, params) assert http_client._connected is False mock.assert_called_with({"message": "Client version {} differs with server version 1.2.3".format(__version__)}, error=True, server=http_client)
def test_fetch_lines(self, mock, requests_mock): url = f'https://api.um.warszawa.pl/api/action/dbtimetable_get/' \ f'?id=88cd555f-6f31-43ca-9de4-66c479ad5942&apikey=foo' \ f'&busstopId=420&busstopNr=0' requests_mock.get(url, text='{"result": "bar"}') fetcher = ScheduleFetcher(api_key='foo') fetcher.fetch_lines(self.STOPS[0]) mock.assert_called_with('bar', self.STOPS[0])
def test_tournament_start_success(self): # Test that RPP can successfully send a tournament start message and recieve ack rpp = RemotePlayerProxy('name', 1.0, self.dummy_socket) rpp._RemotePlayerProxy__socket = self.mock_socket self.mock_socket.recv.return_value = b'"void"' expected_client_request = f'["start", [true]]' with patch.object(rpp, '_RemotePlayerProxy__send_message') as mock: ack = rpp.tournament_has_started() mock.assert_called_with(expected_client_request) self.assertEqual(ack, True)
def test_playing_with_no_ack(self): # Test that RPP will return False if no ack received for set_color rpp = RemotePlayerProxy('name', 1.0, self.dummy_socket) rpp._RemotePlayerProxy__socket = self.mock_socket self.mock_socket.recv.return_value = b'whoops' expected_client_request = f'["playing-with", ["white", "black"]]' with patch.object(rpp, '_RemotePlayerProxy__send_message') as mock: ack = rpp.notify_opponent_colors([Color.WHITE, Color.BLACK]) mock.assert_called_with(expected_client_request) self.assertEqual(ack, False)
def test_playing_with_success(self): # Test that RPP can successfully send a color and receive ACK from client rpp = RemotePlayerProxy('name', 1.0, self.dummy_socket) rpp._RemotePlayerProxy__socket = self.mock_socket self.mock_socket.recv.return_value = b'"void"' expected_client_request = f'["playing-with", ["red", "brown"]]' with patch.object(rpp, '_RemotePlayerProxy__send_message') as mock: ack = rpp.notify_opponent_colors([Color.RED, Color.BROWN]) mock.assert_called_with(expected_client_request) self.assertEqual(ack, True)
def test_set_color_no_ack(self): # Test that RPP will return False if no ack received for set_color rpp = RemotePlayerProxy('name', 1.0, self.dummy_socket) rpp._RemotePlayerProxy__socket = self.mock_socket self.mock_socket.recv.return_value = b'[1, 2]' expected_client_request = f'["playing-as", ["white"]]' with patch.object(rpp, '_RemotePlayerProxy__send_message') as mock: ack = rpp.set_color(Color.WHITE) mock.assert_called_with(expected_client_request) self.assertEqual(ack, False)
def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock("one") mock.assert_called_with("one") self.assertRaises(TypeError, mock, "one", "two")
def test_send_cdi_email(self): with unittest.mock.patch('prog_code.util.mail_util.send_msg') as mock: form_url = parent_account_util.URL_TEMPLATE % 'url' msg = parent_account_util.get_cdi_email_template() % ('child', form_url) test_form = TEST_PARENT_FORM('child', 'url', 'test email') parent_account_util.send_cdi_email(test_form) mock.assert_called_with('test email', parent_account_util.CDI_EMAIL_SUBJECT, msg)
def test_callbackConnect_non_gns3_server(http_client): http_client.setMaxRetryConnection(0) params = { "virus": True, } mock = unittest.mock.MagicMock() http_client._query_waiting_connections.append((None, mock)) http_client._callbackConnect(params) assert http_client._connected is False mock.assert_called_with({"message": "The remote server http://127.0.0.1:3080 is not a GNS3 server"}, error=True, server=None)
def test_tournament_start_no_ack(self): # Test that RPP will return False if no ack received for tournament_start rpp = RemotePlayerProxy('name', 1.0, self.dummy_socket) rpp._RemotePlayerProxy__socket = self.mock_socket self.mock_socket.recv.return_value = b'[][]' expected_client_request = f'["start", [true]]' with patch.object(rpp, '_RemotePlayerProxy__send_message') as mock: ack = rpp.tournament_has_started() mock.assert_called_with(expected_client_request) self.assertEqual(ack, False)
def test_get_windows_symbols(self): ''' ensures that the windows symbol server endpoint is working ''' url = url_for_ish(self.WEBPAGES.Get_Windows_Symbols, path='test_path') with unittest.mock.patch('flask.send_file') as send_file_mock: with unittest.mock.patch( 'storage.Storage.getWindowsSymbolFilePath', return_value=None) as mock: self.app.get(url) mock.assert_called_with('test_path') send_file_mock.assert_called_once()
def test_callbackConnect_major_version_invalid(http_client): params = { "local": True, "version": "1.2.3" } mock = unittest.mock.MagicMock() http_client._query_waiting_connections.append((None, mock)) http_client._callbackConnect(params) assert http_client._connected is False mock.assert_called_with({"message": "Client version {} is not the same as server (controller) version 1.2.3".format(__version__)}, error=True, server=None)
def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1, 2, fish=3)
def test_resolve_no_config_packs_charm(config, tmp_path): """There is no config, so it's decided to pack a charm.""" config.set(project=Project( config_provided=False, dirpath=tmp_path, started_at=datetime.datetime.utcnow(), )) cmd = PackCommand(config) with patch.object(cmd, "_pack_charm") as mock: cmd.run(noargs) mock.assert_called_with(noargs)
def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1,2, fish=3)
def test_callbackConnect_version_non_local(http_client): params = {"local": False, "version": __version__} mock = unittest.mock.MagicMock() http_client._callbackConnect("GET", "/version", mock, {}, {}, params) assert http_client._connected is False mock.assert_called_with( { "message": "Running server is not a GNS3 local server (not started with --local)" }, error=True, server=http_client)
def test__request(): client = Client(domain='test', token='test') with unittest.mock.patch('requests.request') as mock: client.deals(1).update(title='test') mock.assert_called_with( 'PUT', 'https://test.pipedrive.com/api/v1/deals/1', json={'title': 'test'}, params={'api_token': 'test'}, headers={'Content-Type': 'application/json'}, )
def test_assert_called_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a="fish", b="nothing") mock.assert_called_with(1, 2, 3, a="fish", b="nothing")
def test_callbackConnect_minor_version_invalid(http_client): new_version = "{}.{}.{}".format(__version_info__[0], __version_info__[1], __version_info__[2] + 1) params = { "local": True, "version": new_version } mock = unittest.mock.MagicMock() # Stable release if __version_info__[3] == 0: http_client._callbackConnect("GET", "/version", mock, {}, {}, params) assert http_client._connected is False mock.assert_called_with({"message": "Client version {} differs with server version {}".format(__version__, new_version)}, error=True, server=http_client) else: http_client._callbackConnect("GET", "/version", mock, {}, {}, params) assert http_client._connected is True
def test_init_and_close_loop_for_test(self): default_loop = self.create_default_loop() @asynctest.lenient class LoopTest(asynctest.TestCase): failing = False def runTest(self): try: self.assertIsNotNone(self.loop) self.assertFalse(self.loop.close.called) except Exception: self.failing = True raise def runFailingTest(self): self.runTest() raise SystemError() for method, test in itertools.product(self.run_methods, ('runTest', 'runFailingTest', )): with self.subTest(method=method, test=test), \ unittest.mock.patch('asyncio.new_event_loop') as mock: mock_loop = unittest.mock.Mock(asyncio.AbstractEventLoop) mock_loop.run_until_complete.side_effect = default_loop.run_until_complete if sys.version_info >= (3, 6): mock_loop.shutdown_asyncgens = asynctest.CoroutineMock() mock.return_value = mock_loop case = LoopTest(test) try: getattr(case, method)() except SystemError: pass mock.assert_called_with() mock_loop.close.assert_called_with() if sys.version_info >= (3, 6): mock_loop.shutdown_asyncgens.assert_awaited() # If failing is True, one of the assertions in runTest failed self.assertFalse(case.failing) # Also, ensure we didn't override the original loop self.assertIs(default_loop, asyncio.get_event_loop())
def test_callbackConnect_minor_version_invalid(http_client): new_version = "{}.{}.{}".format(__version_info__[0], __version_info__[1], __version_info__[2] + 1) params = { "local": True, "version": new_version } mock = unittest.mock.MagicMock() http_client._query_waiting_connections.append((None, mock)) # Stable release if __version_info__[3] == 0: http_client._callbackConnect(params) assert http_client._connected is False mock.assert_called_with({"message": "Client version {} is not the same as server (controller) version {}".format(__version__, new_version)}, error=True, server=None) else: http_client._callbackConnect(params) assert http_client._connected is True
def assert_called(context): actual = json.loads(context.text or '{}') # Kinda hacky but tokens are time based mail = context.mocks['jam.plugins.user.sendgrid'].SendGridClient().send.call_args[0][0] mock = context.mocks['jam.plugins.user.sendgrid'].Mail mock.assert_called_with(to=actual['to']) if actual.get('from'): mail.set_from(actual.get('from')) token = mail.add_substitution.call_args_list[0][0][1] mail.add_substitution.assert_any_call(':token', token) user = mail.add_substitution.call_args_list[1][0][1] mail.add_substitution.assert_any_call(':user', user) mail.add_filter.assert_any_call('templates', 'enable', 1) mail.add_filter.assert_any_call('templates', 'template_id', actual['template'])
def test_before_test_called_before_user_setup(self): mock = unittest.mock.Mock() setattr(asynctest._fail_on._fail_on, "before_test_default", mock) self.addCleanup(delattr, asynctest._fail_on._fail_on, "before_test_default") class TestCase(asynctest.TestCase): def setUp(self): self.assertTrue(mock.called) def runTest(self): pass for method in self.run_methods: with self.subTest(method=method): case = Test.FooTestCase() getattr(case, method)() self.assert_checked("default") self.assertTrue(mock.called) mock.assert_called_with(case)
def test_setting_state_emits_on_state_change(self): mock = unittest.mock.Mock() mock.return_value = None self.tr.on_state_change.connect(mock) self.tr.state = tracking.MessageState.DELIVERED_TO_SERVER self.assertEqual( self.tr.state, tracking.MessageState.DELIVERED_TO_SERVER) mock.assert_called_with( tracking.MessageState.DELIVERED_TO_SERVER ) self.tr.state = tracking.MessageState.DELIVERED_TO_RECIPIENT self.assertEqual( self.tr.state, tracking.MessageState.DELIVERED_TO_RECIPIENT) mock.assert_called_with( tracking.MessageState.DELIVERED_TO_RECIPIENT ) self.tr.state = tracking.MessageState.SEEN_BY_RECIPIENT self.assertEqual( self.tr.state, tracking.MessageState.SEEN_BY_RECIPIENT) mock.assert_called_with( tracking.MessageState.SEEN_BY_RECIPIENT )
def test_assert_called_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError)
def test_reference_expansion(self): response = { 'manifests': [ { 'entry': 'a', 'annotations': { 'org.opencontainers.image.ref.name': '1.0', }, }, ], } for uri, base, expected in [ ( 'index.json', 'https://example.com/a', 'https://example.com/index.json', ), ( 'index.json', 'https://example.com/a/', 'https://example.com/a/index.json', ), ( 'https://{host}/{path}#{fragment}', 'https://a.example.com/b/', 'https://example.com/a#1.0' ), ( '//{host}/{path}#{fragment}', 'https://a.example.com/b/', 'https://example.com/a#1.0' ), ( '/{path}#{fragment}', 'https://b.example.com/c/', 'https://b.example.com/a#1.0', ), ( '{path}#{fragment}', 'https://b.example.com/c/', 'https://b.example.com/c/a#1.0', ), ( '#{fragment}', 'https://example.com/a', 'https://example.com/a#1.0', ), ( '#{fragment}', 'https://example.com/a/', 'https://example.com/a/#1.0', ), ]: with self.subTest(label='{} from {}'.format(uri, base)): engine = oci_index_template.Engine(uri=uri, base=base) with unittest.mock.patch( target='oci_discovery.ref_engine.oci_index_template._fetch_json.fetch', return_value={ 'uri': expected, 'json': response }) as mock: resolved = list(engine.resolve(name='example.com/a#1.0')) mock.assert_called_with( uri=expected, media_type='application/vnd.oci.image.index.v1+json') self.assertEqual( resolved, [ { 'mediaType': 'application/vnd.oci.descriptor.v1+json', 'root': root, 'uri': expected, } for root in response['manifests'] ])
def test_simple_setters(self, elem, code, method, args): code(elem) mock = getattr(elem._elem, method) mock.assert_called_with(*args)