def test_client_start_by_call_order(self, *mocks): watson_office_addr = ('localhost', 11111) num_nodes = 10 master = MagicMock() with patch('umatobi.simulator.client.Client', autospec=True, spec_set=True): client = Client(watson_office_addr, num_nodes) self.assertEqual(client.watson_office_addr, ('localhost', 11111)) self.assertEqual(client.num_nodes, num_nodes) for mock in mocks: m = re.search('function (.+) at', str(mock)) func_name = m[1] # print('func_name =', func_name) master.attach_mock(mock.mock, func_name) try: mock.assert_called_once_with(client) except AssertionError as err: err_msg = f"Expected '{func_name}' to be called once. Called 0 times." self.assertEqual(err.args[0], err_msg) self.assertEqual(0, mock.call_count) client.start() # print('mocks[0] == master.method_calls[0] is', mocks[0] == master.method_calls[0]) # print('mocks[0] == master.method_calls[0] is', master.method_calls[0] == mocks[0]) # print('mocks =', mocks) # print('master.method_calls =', master.method_calls) for i, mock in enumerate(reversed(mocks)): # self.assertEqual(master.mock_calls[i], mock.mock_calls[0]) # FALSE! self.assertEqual(mock.mock_calls[0], master.mock_calls[i]) # TRUE!! # ??? different __eq__() ??? self.assertEqual(len(mocks), len(master.mock_calls))
def test_no_source(self, commands, mocker): mock = mocker.patch( 'qutebrowser.config.configcommands.editor.' 'ExternalEditor._start_editor', autospec=True) commands.config_edit(no_source=True) mock.assert_called_once_with(unittest.mock.ANY)
def test_configure_logging_file(mocker): mock = mocker.patch('logging.config.fileConfig') # anything that is not a boolean is treated like a file autosuspend.configure_logging(42) mock.assert_called_once_with(42)
def test_approve_ignores_approved_price_lists(self, mock): self.price_list.approve(self.user) admin.approve(None, self.request_mock, SubmittedPriceList.objects.all()) mock.assert_called_once_with( self.request_mock, messages.INFO, '0 price list(s) have been approved and added to CALC.')
def test_existing_cache_with_unrelated_data(self): section = Section('test-section') filedict = {} # Start with some unrelated cache values. Those are ignored as they are # never hit during a cache lookup. cache = {CustomTasksBear: {b'123456': [100, 101, 102]}} task_args = -1, -2, -3 bear = CustomTasksBear(section, filedict, tasks=[task_args]) with unittest.mock.patch.object(bear, 'analyze', wraps=bear.analyze) as mock: # First time we have a cache miss. results = self.execute_run({bear}, cache) mock.assert_called_once_with(*task_args) self.assertEqual(results, list(task_args)) self.assertEqual(len(cache), 1) self.assertIn(CustomTasksBear, cache) cache_values = next(iter(cache.values())) self.assertEqual(len(cache_values), 2) # The unrelated data is left untouched. self.assertIn(b'123456', cache_values) self.assertEqual(cache_values[b'123456'], [100, 101, 102])
def test_require_authentication_unknown_user( mocked_authenticator, configure_model, sudo_client_v1, sudo_user_with_external_id, app): now, expired = make_now_expired() endpoint = "/" + pytest.faux.gen_alphanumeric() mock = mocked_authenticator.client.tokens.get_token_data mock.return_value = { "token": make_token_data(sudo_user_with_external_id, now, expired) } mock.return_value["token"]["user"]["id"] += "FAKE" @app.route(endpoint) @mocked_authenticator.require_authentication def testing_endpoint(): assert int(flask.g.token.expires_at.timestamp()) == int( calendar.timegm(expired.timetuple())) assert flask.g.token.user_id == sudo_user_with_external_id.model_id return flask.jsonify(value=1) response = sudo_client_v1.get(endpoint) assert response.status_code == 401 mock = mocked_authenticator.client.tokens.get_token_data mock.assert_called_once_with(sudo_client_v1.auth_token)
def test_two_overlays(self): container2 = QWidget() overlay2 = NotificationOverlay(container2) self.server.newNotification.connect(overlay2.addNotification) self.server.nextNotification.connect(overlay2.nextWidget) mock = unittest.mock.MagicMock() self.notif.accepted.connect(mock) self.server.registerNotification(self.notif) self.container.show() container2.show() w1 = self.overlay.currentWidget() w2 = overlay2.currentWidget() self.assertTrue(w1.isVisible()) self.assertTrue(w2.isVisible()) button = w2.button(NotificationWidget.Ok) QTest.mouseClick(button, Qt.LeftButton) mock.assert_called_once_with() self.assertFalse(w1.isVisible()) self.assertFalse(w2.isVisible())
def test_overlay_message(self): container = QWidget() overlay = MessageOverlayWidget(parent=container) overlay.setWidget(container) overlay.setIcon(QStyle.SP_MessageBoxInformation) container.show() QTest.qWaitForWindowExposed(container) self.assertTrue(overlay.isVisible()) overlay.setText("Hello world! It's so nice here") QApplication.sendPostedEvents(overlay, QEvent.LayoutRequest) self.assertTrue(overlay.geometry().isValid()) button_ok = overlay.addButton(MessageOverlayWidget.Ok) button_close = overlay.addButton(MessageOverlayWidget.Close) button_help = overlay.addButton(MessageOverlayWidget.Help) self.assertTrue(all([button_ok, button_close, button_help])) self.assertIs(overlay.button(MessageOverlayWidget.Ok), button_ok) self.assertIs(overlay.button(MessageOverlayWidget.Close), button_close) self.assertIs(overlay.button(MessageOverlayWidget.Help), button_help) button = overlay.addButton("Click Me!", MessageOverlayWidget.AcceptRole) self.assertIsNot(button, None) self.assertTrue(overlay.buttonRole(button), MessageOverlayWidget.AcceptRole) mock = unittest.mock.MagicMock() overlay.accepted.connect(mock) QTest.mouseClick(button, Qt.LeftButton) self.assertFalse(overlay.isVisible()) mock.assert_called_once_with()
def test_draw_para_content_with_header_that_does_not_fit(self, mock): self.img.content.fits = False self.img._draw_para() header_with_padding_height = 2 * \ self.img.content.padding + self.img.header.height current_h = header_with_padding_height mock.assert_called_once_with(current_h, self.img.para)
def test_client_start(self, *mocks): watson_office_addr = ('localhost', 0) num_nodes = 10 client = Client(watson_office_addr, num_nodes) # battle of log # print('mocks[0] =', mocks[0]) # print('type(mocks[0]) =', type(mocks[0])) # print('str(mocks[0]) =', str(mocks[0])) # print('mocks[0].__dict__ =', mocks[0].__dict__) # print('dir(mocks[0]) =', dir(mocks[0])) # print('mocks[0].mock._extract_mock_name() =', mocks[0].mock._extract_mock_name()) for mock in reversed(mocks): m = re.search('function (.+) at', str(mock)) func_name = m[1] try: mock.assert_called_once_with(client) except AssertionError as err: # err_msg = f"Expected '{mock.mock._extract_mock_name()}' to be called once. Called 0 times." err_msg = f"Expected '{func_name}' to be called once. Called 0 times." self.assertEqual(err.args[0], err_msg) self.assertEqual(0, mock.call_count) client.start() for mock in reversed(mocks): mock.assert_called_once_with(client)
def test_specifics(self, mock) -> None: VowpalSoftmaxLearner(softmax=5, interactions=["ax"], ignore_linear=[], seed=None) mock.assert_called_once_with( "--cb_explore_adf --softmax --lambda 5 --interactions ax")
def test_custom_flag(self, mock) -> None: VowpalEpsilonLearner(epsilon=0.1, features=['a', 'x', 'ax'], seed=None, b=20) mock.assert_called_once_with( "--cb_explore_adf --epsilon 0.1 --interactions ax -b 20 --quiet")
def test_config_py_with_sourcing(self, commands, config_stub, patch_editor, config_py_arg): assert config_stub.val.content.javascript.enabled conf = 'c.content.javascript.enabled = False' mock = patch_editor(conf) commands.config_edit() mock.assert_called_once_with(unittest.mock.ANY) assert not config_stub.val.content.javascript.enabled assert config_py_arg.read_text('utf-8').splitlines() == [conf]
def test_reject_ignores_rejected_price_lists(self, mock): self.price_list.reject(self.user) admin.reject(None, self.request_mock, SubmittedPriceList.objects.all()) mock.assert_called_once_with( self.request_mock, messages.INFO, '0 price list(s) have been rejected.' )
def test_retire_ignores_retired_price_lists(self, mock): admin.retire(None, self.request_mock, SubmittedPriceList.objects.all()) mock.assert_called_once_with( self.request_mock, messages.INFO, '0 price list(s) have been retired and removed from CALC.' )
def test_check(self, mocker): mock = mocker.patch('subprocess.check_call') parser = configparser.ConfigParser() parser.read_string('''[section] command = foo bar''') assert autosuspend.ExternalCommand.create( 'name', parser['section']).check() is not None mock.assert_called_once_with('foo bar', shell=True)
def test_specifics(self, mock) -> None: VowpalSquarecbLearner(mode="elimination", gamma_scale=5, features=['a', 'x', 'ax'], seed=None) mock.assert_called_once_with( "--cb_explore_adf --squarecb --gamma_scale 5 --elim --interactions ax --quiet" )
def test_with_sourcing(self, commands, config_stub, patch_editor): assert config_stub.val.content.javascript.enabled mock = patch_editor('c.content.javascript.enabled = False') commands.config_edit() mock.assert_called_once_with(unittest.mock.ANY) assert not config_stub.val.content.javascript.enabled
def test_date_invalid(self): to_pass_in = ['22/13/14', '12/13/14'] with patch('builtins.input', side_effect=to_pass_in): with patch('builtins.print', side_effect=print) as mock: result = worklog.get_date() mock.assert_called_once_with("Opps! Wrong date format. Please post in MM/DD/YY format ")
def test_notification_dismiss(self): mock = unittest.mock.MagicMock() self.notif.clicked.connect(mock) self.server.registerNotification(self.notif) notifw = self.overlay.currentWidget() QTest.mouseClick(notifw.dismissButton, Qt.LeftButton) mock.assert_called_once_with(self.notif.DismissRole)
def test_abort_display_aborts_message(): "abort message is displayed when `settings.display_aborts` is `True`" result = {"foo": "bar"} with state.settings(display_aborts=True): with patch("threadbare.operations.LOG.error") as mock: with pytest.raises(RuntimeError): operations.abort(result, "failed to succeed") mock.assert_called_once_with("Fatal error: failed to succeed")
def test_approve_ignores_approved_price_lists(self, mock): self.price_list.approve(self.user) admin.approve(None, self.request_mock, SubmittedPriceList.objects.all()) mock.assert_called_once_with( self.request_mock, messages.INFO, '0 price list(s) have been approved and added to CALC.' )
def test_output_is_sourceable(mock, releases_dictionary): bash_script = '/foo/bar.sh' assert write_releases_dictionary_to_bash(releases_dictionary, bash_script) mock.assert_called_once_with(bash_script, 'w') handle = mock() args, _ = handle.write.call_args written_content = args[0] # TODO(Llorente): check environment variables assert 0 == os.system(written_content)
def test_notification_accept(self): mock = unittest.mock.MagicMock() self.notif.clicked.connect(mock) self.server.registerNotification(self.notif) notifw = self.overlay.currentWidget() b = notifw._msgWidget.button(NotificationWidget.Ok) QTest.mouseClick(b, Qt.LeftButton) mock.assert_called_once_with(self.notif.AcceptRole)
def test_with_sourcing(self, commands, config_stub, patch_editor): assert config_stub.val.content.javascript.enabled mock = patch_editor('\n'.join(['config.load_autoconfig(False)', 'c.content.javascript.enabled = False'])) commands.config_edit() mock.assert_called_once_with(unittest.mock.ANY) assert not config_stub.val.content.javascript.enabled
def test_configure_logging_file_fallback(mocker): mock = mocker.patch('logging.config.fileConfig', side_effect=RuntimeError()) mock_basic = mocker.patch('logging.basicConfig') # anything that is not a boolean is treated like a file autosuspend.configure_logging(42) mock.assert_called_once_with(42) mock_basic.assert_called_once_with(level=logging.WARNING)
def _test_with_settings(mock, settings): create_instance(mock, settings, None, *args, **kwargs) if hasattr(mock, 'from_crawler'): self.assertEqual(mock.from_crawler.call_count, 0) if hasattr(mock, 'from_settings'): mock.from_settings.assert_called_once_with( settings, *args, **kwargs) self.assertEqual(mock.call_count, 0) else: mock.assert_called_once_with(*args, **kwargs)
def test_download_url_dispatch_download_from_google_drive(self, mock): url = "https://drive.google.com/file/d/1hbzc_P1FuxMkcabkgn9ZKinBwW683j45/view" id = "1hbzc_P1FuxMkcabkgn9ZKinBwW683j45" filename = "filename" md5 = "md5" with get_tmp_dir() as root: utils.download_url(url, root, filename, md5) mock.assert_called_once_with(id, root, filename, md5)
def test_execute_suspend_call_exception(mocker): mock = mocker.patch('subprocess.check_call') command = ['foo', 'bar'] mock.side_effect = subprocess.CalledProcessError(2, command) spy = mocker.spy(autosuspend._logger, 'warning') autosuspend.execute_suspend(command) mock.assert_called_once_with(command, shell=True) assert spy.call_count == 1
def test_forward_data_changed_signal(self): mock = unittest.mock.Mock() self.m.dataChanged.connect(mock) self.accounts.set_account_enabled(self.accounts[0], False) mock.assert_called_once_with( self.m.index(0, 0), self.m.index(0, self.m.COLUMN_COUNT - 1), [], )
def test_unicast_removes_for_true_result(self): mock = unittest.mock.Mock() mock.return_value = True obj = object() nh = TagDispatcher() nh.add_callback("tag", mock) nh.unicast("tag", obj) with self.assertRaises(KeyError): nh.unicast("tag", obj) mock.assert_called_once_with(obj)
def test_octaverc(self, mocker): """Ensure that the octaverc file is sourced.""" octaverc = os.path.join('path', 'to', 'my', '.octaverc') mock = mocker.patch('matl_online.octave.OctaveSession.eval') session = OctaveSession(octaverc=octaverc) assert session.octaverc == octaverc assert session.paths == [] mock.assert_called_once_with('source("' '%s' '")' % octaverc)
def test_cache(self): section = Section('test-section') filedict = {} cache = {} task_args = 10, 11, 12 bear = CustomTasksBear(section, filedict, tasks=[task_args]) with unittest.mock.patch.object(bear, 'analyze', wraps=bear.analyze) as mock: # First time we have a cache miss. results = self.execute_run({bear}, cache) mock.assert_called_once_with(*task_args) self.assertEqual(results, list(task_args)) self.assertEqual(len(cache), 1) self.assertEqual(next(iter(cache.keys())), CustomTasksBear) self.assertEqual(len(next(iter(cache.values()))), 1) # All following times we have a cache hit (we don't modify the # cache in between). for i in range(3): mock.reset_mock() results = self.execute_run({bear}, cache) self.assertFalse(mock.called) self.assertEqual(results, list(task_args)) self.assertEqual(len(cache), 1) self.assertIn(CustomTasksBear, cache) self.assertEqual(len(next(iter(cache.values()))), 1) task_args = 500, 11, 12 bear = CustomTasksBear(section, filedict, tasks=[task_args]) with unittest.mock.patch.object(bear, 'analyze', wraps=bear.analyze) as mock: # Invocation with different args should add another cache entry, # and invoke analyze() again because those weren't cached before. results = self.execute_run({bear}, cache) mock.assert_called_once_with(*task_args) self.assertEqual(results, list(task_args)) self.assertEqual(len(cache), 1) self.assertIn(CustomTasksBear, cache) self.assertEqual(len(next(iter(cache.values()))), 2) mock.reset_mock() results = self.execute_run({bear}, cache) self.assertFalse(mock.called) self.assertEqual(results, list(task_args)) self.assertEqual(len(cache), 1) self.assertIn(CustomTasksBear, cache) self.assertEqual(len(next(iter(cache.values()))), 2)
def test_assert_called_once_with(self): mock = Mock() mock() mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises(AssertionError, lambda : mock.assert_called_once_with('bob', 'bar', baz=2))
def test_connect_async(self): signal = AdHocSignal() mock = unittest.mock.MagicMock() fun = functools.partial(mock) signal.connect(fun, AdHocSignal.ASYNC_WITH_LOOP(None)) signal.fire() mock.assert_not_called() run_coroutine(asyncio.sleep(0)) mock.assert_called_once_with()
def test_assert_called_once_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock("foo", "bar", baz=2) mock.assert_called_once_with("foo", "bar", baz=2) mock.reset_mock() mock("foo", "bar", baz=2) self.assertRaises(AssertionError, lambda: mock.assert_called_once_with("bob", "bar", baz=2))
def test_no_cache(self): # Two runs without using the cache shall always run analyze() again. section = Section('test-section') filedict = {} task_args = 3, 4, 5 bear = CustomTasksBear(section, filedict, tasks=[task_args]) with unittest.mock.patch.object(bear, 'analyze', wraps=bear.analyze) as mock: # By default, omitting the cache parameter shall mean "no cache". results = self.execute_run({bear}) mock.assert_called_once_with(*task_args) self.assertEqual(results, list(task_args)) mock.reset_mock() results = self.execute_run({bear}) mock.assert_called_once_with(*task_args) self.assertEqual(results, list(task_args)) mock.reset_mock() # Passing None for cache shall disable it too explicitly. results = self.execute_run({bear}, None) mock.assert_called_once_with(*task_args) self.assertEqual(results, list(task_args))
def test_assert_called_once_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_once_with(1, 2, 3) mock.assert_called_once_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_once_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) # Mock called more than once => always fails mock(4, 5, 6) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, 2, 3) self.assertRaises(AssertionError, mock.assert_called_once_with, 4, 5, 6)
oo.func1 = MagicMock() print(oo.func1("POKEMON !!").split() + 33) print(oo.func2()) # Il est possible d'avoir un historique de ce qui a été utilisé avec les mocks. print(oo.func1.mock_calls) # Il est possible de vérifier si un appel a bien été fait : oo.func1.assert_called_with("POKEMON !!") # oo.func1.assert_called_with("Mario !") Provoquera une erreur. # Patch # permet de modifier le comportement de ce qui existe pour les tests. from unittest.mock import patch """ with patch.object(builtins, "open", mock_open(read_data="wololo") as mock: #with patch('__main__.open', mock_open(read_data='wololo'), create=True) as mock: with open('zefile') as h: result = h.read() mock.assert_called_once_with('zefile') assert result == 'wololo' """ ### Ne fonctionne pas # Il est possible de patcher un bout de module : @patch('os.listdir') def ah(mock): import os print(os.listdir('.')) # l'objet mock initial est aussi passé en param automatiquement
def test_perform_system_call(self, mock): cmd = 'universal' perform_system_command(cmd) mock.assert_called_once_with(cmd)
def test_no_source(self, commands, mocker): mock = mocker.patch('qutebrowser.config.configcommands.editor.' 'ExternalEditor._start_editor', autospec=True) commands.config_edit(no_source=True) mock.assert_called_once_with(unittest.mock.ANY)