def test_DisplayMenu_draw(): mock_screen = MagicMock() mock_screen.getmaxyx.return_value = 100, 100 with patch(patch_NORMAL, 'NORMAL'),\ patch(patch_DIM, 'DIM'),\ patch(patch_REVERSE, 'REVERSE'),\ patch(PATCH_COLUMNS, DEFAULT_CONFIG): test_dm = DisplayMenu(mock_screen, FAKE_ITEMS['titles'], mock_model) # Display cursor on note 2. test_dm.update_pointers(0, 2) test_dm.draw() calls = [ call.getmaxyx(), call.getmaxyx(), call.addstr(1, 2, '(+)', 'NORMAL'), call.addstr(1, 6, '|', 'NORMAL'), call.addstr(1, 8, 'test_title ', 'NORMAL'), call.addstr(1, 30, '|', 'NORMAL'), call.addstr(1, 32, '- ', 'NORMAL'), call.addstr(1, 74, '|', 'NORMAL'), call.addstr(1, 76, ' - ', 'NORMAL'), call.addstr(1, 88, '|', 'NORMAL'), call.addstr(2, 2, '(+)', 'REVERSE'), call.addstr(2, 6, '|', 'REVERSE'), call.addstr(2, 8, 'another_title ', 'REVERSE'), call.addstr(2, 30, '|', 'REVERSE'), call.addstr(2, 32, '- ', 'REVERSE'), call.addstr(2, 74, '|', 'REVERSE'), call.addstr(2, 76, ' - ', 'REVERSE'), call.addstr(2, 88, '|', 'REVERSE')] mock_screen.assert_has_calls(calls)
def test_observable_register(self): notify_observers_mock = MagicMock() self.appmgr.notify_observers = notify_observers_mock self.my_app() app = self.appmgr.grab_apps()[0] calls = [call("register", app, IFakeInterface)] notify_observers_mock.assert_has_calls(calls)
def test_DisplayMenu_draw_item(display_data): """Test items are not drawn when they are off the screen.""" mock_screen = MagicMock() mock_screen.getmaxyx.return_value = 50, 50 test_dm = DisplayMenu(mock_screen, display_data['titles'], mock_model) with patch(patch_NORMAL, 'NORMAL'),\ patch(patch_DIM, 'DIM'),\ patch(patch_REVERSE, 'REVERSE'): test_dm.update_pointers(2, 3) test_dm.draw() calls = [ call.getmaxyx(), call.getmaxyx(), call.addstr(1, 2, '(+)', 'NORMAL'), call.addstr(1, 6, '|', 'NORMAL'), call.addstr(1, 8, 'C ', 'NORMAL'), call.addstr(1, 30, '|', 'NORMAL'), call.addstr(2, 2, '(+)', 'DIM'), call.addstr(2, 6, '|', 'DIM'), call.addstr(2, 8, 'D ', 'DIM'), call.addstr(2, 30, '|', 'DIM') ] mock_screen.assert_has_calls(calls)
def test_DisplayMenu_draw_small_height(): """ Test that note titles are not printed when the console height is smaller than the amount of notes. Params: screen max y: 4 display pointer: 1 """ mock_screen = MagicMock() mock_screen.getmaxyx.return_value = 4, 100 test_dm = DisplayMenu(mock_screen, FAKE_ITEMS['titles'], mock_model) test_dm.update_pointers(0, 1) with patch(patch_NORMAL, 'NORMAL'),\ patch(patch_DIM, 'DIM'),\ patch(patch_REVERSE, 'REVERSE'): test_dm.draw() calls = [ call.getmaxyx(), call.getmaxyx(), call.addstr(1, 2, '(+)', 'REVERSE'), call.addstr(1, 6, '|', 'REVERSE'), call.addstr(1, 8, 'test_title ', 'REVERSE'), call.addstr(1, 30, '|', 'REVERSE'), call.addstr(1, 32, '- ', 'REVERSE'), call.addstr(1, 74, '|', 'REVERSE'), call.addstr(1, 76, ' - ', 'REVERSE'), call.addstr(1, 88, '|', 'REVERSE')] mock_screen.assert_has_calls(calls)
def test_sequential_6byte_and_37byte_with_junk_in_front_and_between(): on_message = MagicMock() cp = SerialConnectionProtocol(on_message, None, None) payloads = [ b'\x01\x02\x03\x04\x05\x06\x07\x12', b'\x06\x00', b'\x00\x00\x18\x01', b'\x02\x03\x04\x05\x06\x07', b'\x01\x02\xe2\xff\xad\x06\x14', b'\x13\x01\x04\x0e\x10', b'\x00\x01\x05\x00\x00', b'\x00\x00\x00\x02Liv', b'ing room \x00\xcc' ] for p in payloads: cp.data_received(p) on_message.call_count = 2 on_message.assert_has_calls([ call( b'\x12\x06\x00\x00\x00\x18' ), call( b'\xe2\xff\xad\x06\x14\x13\x01\x04\x0e\x10\x00\x01\x05\x00\x00\x00\x00\x00\x02Living room \x00\xcc' ) ], )
def test_get_request_exception_and_retry_and_success(self, Session): self.count = 0 request_exception = RequestException('I raise RequestException!') def exception_raiser(method, url, data, params, headers=None, allow_redirects=None): if self.count < 4: self.count += 1 raise request_exception return MagicMock( status_code=200, json=MagicMock(return_value={'success': 'True'})) Session.return_value = MagicMock(request=exception_raiser) ex = HttpExecutor('http://api.stormpath.com/v1', ('user', 'pass')) ShouldRetry = MagicMock(return_value=True) with patch('stormpath.http.HttpExecutor.should_retry', ShouldRetry): with self.assertRaises(Error): ex.get('/test') should_retry_calls = [ call(0, request_exception), call(1, request_exception), call(2, request_exception), call(3, request_exception), ] ShouldRetry.assert_has_calls(should_retry_calls)
def test_get_request_exception_and_retry_and_success(self, Session): self.count = 0 request_exception = RequestException('mocked error') successful_response = MagicMock(status_code=200, json=MagicMock(return_value={'success': 'True'})) def faker(*args, **kwargs): if self.count < 3: self.count += 1 raise request_exception return successful_response Session.return_value = MagicMock(request=faker) ex = HttpExecutor('http://api.stormpath.com/v1', ('user', 'pass')) should_retry = MagicMock(return_value=True) with patch('stormpath.http.HttpExecutor.should_retry', should_retry): resp = ex.get('/test') self.assertEqual(resp['sp_http_status'], 200) should_retry.assert_has_calls([ call(0, request_exception), call(1, request_exception), call(2, request_exception), ])
def test_distributions(demo1_spec): provenance = Provenance.factory(demo1_spec) distributions = provenance.get_distributions() distributions = items_to_dict(distributions) assert set(distributions.keys()) == {'conda', 'debian'} # Test DebianDistribution class. debian_distribution = distributions['debian'] environment = MagicMock() with swallow_logs(new_level=logging.DEBUG) as log: debian_distribution.initiate(environment) debian_distribution.install_packages(environment) calls = [ call.execute_command(['apt-get', 'update']), call.execute_command([ 'apt-get', 'install', '-y', 'libc6-dev=2.19-18+deb8u4', 'afni=16.2.07~dfsg.1-2~nd90+1' ]), ] environment.assert_has_calls(calls, any_order=True) assert_in("Adding Debian update to environment command list.", log.lines) """
def test_mapper_args_value(self, db, bridge, mocker): """ Test checks: 1) that 'FeedItem' class is instantiated once with correct arguments 2) that 'self.mapper' method is called once with correct arguments, Actually, with the item yielded by 'get_tenders' function. 3) that 'self.mapper' was called AFTER 'FeedItem' class instantiated. """ mock_feed_item = mocker.patch.object(databridge_module, 'FeedItem', side_effect=FeedItem, autospec=True) manager = MagicMock() mock_mapper = MagicMock() bridge['bridge'].mapper = mock_mapper manager.attach_mock(mock_mapper, 'mock_mapper') manager.attach_mock(mock_feed_item, 'mock_feed_item') bridge['bridge_thread'].join(0.1) manager.assert_has_calls([ call.mock_feed_item(bridge['tenders'][0]), call.mock_mapper(mock_feed_item(bridge['tenders'][0])) ])
class TestDeleteDigests(unittest.TestCase): def setUp(self): self.registry = Registry() self.delete_digest_mock = MagicMock(return_value=(True, "Deleted")) self.registry.delete_digest = self.delete_digest_mock self.registry.http = MockRequests() self.registry.hostname = "http://testdomain.com" self.registry.http.reset_return_value(200, "MOCK_DIGEST") self.registry.http.return_value.headers = { 'Content-Length': '4935', 'Docker-Content-Digest': 'MOCK_DIGEST_HEADER', 'X-Content-Type-Options': 'nosniff' } def test_delete_digest(self): delete_digests(self.registry, "imagename", False, ["DIGEST_MOCK"]) self.delete_digest_mock.assert_called_once_with( "imagename", "DIGEST_MOCK", False) def test_delete_digests(self): delete_digests(self.registry, "imagename", False, ["DIGEST_MOCK1", "DIGEST_MOCK2"]) calls = [call("imagename", "DIGEST_MOCK1", False), call("imagename", "DIGEST_MOCK2", False)] self.delete_digest_mock.assert_has_calls(calls, any_order=True) self.assertEqual(len(self.delete_digest_mock.mock_calls), 2)
def test_get_request_exception_and_retry_four_times(self, Session): request_exception = RequestException('I raise RequestException!') def exception_raiser(method, url, data, params, headers=None, allow_redirects=None): raise request_exception Session.return_value = MagicMock(request=exception_raiser) ex = HttpExecutor('http://api.stormpath.com/v1', ('user', 'pass')) def try_four_times(retries, status): return retries <= 3 ShouldRetry = MagicMock() ShouldRetry.side_effect = try_four_times with patch('stormpath.http.HttpExecutor.should_retry', ShouldRetry): with self.assertRaises(Error): ex.get('/test') should_retry_calls = [ call(0, request_exception), call(1, request_exception), call(2, request_exception), call(3, request_exception), call(4, request_exception) ] ShouldRetry.assert_has_calls(should_retry_calls)
def test_plan( self, mock_action: MagicMock, cfngin_fixtures: Path, tmp_path: Path, patch_safehaven: MagicMock, ) -> None: """Test plan.""" mock_instance = self.configure_mock_action_instance(mock_action) copy_basic_fixtures(cfngin_fixtures, tmp_path) context = self.get_context() cfngin = CFNgin(ctx=context, sys_path=tmp_path) cfngin.plan() mock_action.assert_called_once() mock_instance.execute.assert_called_once_with() patch_safehaven.assert_has_calls( [ call(environ=context.env.vars), call.__enter__(), call(), call.__enter__(), call.__exit__(None, None, None), call.__exit__(None, None, None), ] )
def test_run(self, monkeypatch): """Test run method.""" # TODO test _process_deployments instead of mocking it out deployments = [{'modules': ['test'], 'regions': 'us-east-1'}] test_config = Config(deployments=deployments, tests=[]) get_env = MagicMock(return_value='test') monkeypatch.setattr(MODULE_PATH + '.select_modules_to_run', lambda a, b, c, d, e: a) monkeypatch.setattr(MODULE_PATH + '.get_env', get_env) monkeypatch.setattr(Config, 'find_config_file', MagicMock(return_value=os.getcwd() + 'runway.yml')) monkeypatch.setattr(ModulesCommand, 'runway_config', test_config) monkeypatch.setattr(ModulesCommand, '_process_deployments', lambda obj, y, x: None) obj = ModulesCommand(cli_arguments={}) with environ({}): os.environ.pop('CI', None) assert not obj.run(test_config.deployments, command='plan') os.environ['CI'] = '1' assert not obj.run(test_config.deployments, command='plan') get_env.assert_has_calls([ call(os.getcwd(), False, prompt_if_unexpected=True), call(os.getcwd(), False, prompt_if_unexpected=False) ])
def test_paginated_multiple_pages_empty_results(): mock_responder = MagicMock() mock_responder.side_effect = [ { "NextToken": "1", "Data": [] }, { "NextToken": "2", "Data": [] }, { "NextToken": "3", "Data": ["e", "f"] }, { "NextToken": None, "Data": [] }, ] @paginated("Data", request_pagination_marker="NextToken", response_pagination_marker="NextToken") def retrieve_letters(**kwargs): return mock_responder(**kwargs) result = retrieve_letters() assert result == ["e", "f"] assert mock_responder.call_count == 4 mock_responder.assert_has_calls([call(), call(NextToken="1"), call(NextToken="2"), call(NextToken="3")])
def test_DisplayMenu_draw_small_width(): """ Test that note descriptions are not printed when the width of the console is too small. Params: screen max x: 50 display pointer: 2 """ mock_screen = MagicMock() mock_screen.getmaxyx.return_value = 50, 50 test_dm = DisplayMenu(mock_screen, FAKE_ITEMS['titles'], mock_model) test_dm.update_pointers(0, 2) with patch(patch_NORMAL, 'NORMAL'),\ patch(patch_DIM, 'DIM'),\ patch(patch_REVERSE, 'REVERSE'): test_dm.draw() calls = [ call.getmaxyx(), call.getmaxyx(), call.addstr(1, 2, '(+)', 'NORMAL'), call.addstr(1, 6, '|', 'NORMAL'), call.addstr(1, 8, 'test_title ', 'NORMAL'), call.addstr(1, 30, '|', 'NORMAL'), call.addstr(2, 2, '(+)', 'REVERSE'), call.addstr(2, 6, '|', 'REVERSE'), call.addstr(2, 8, 'another_title ', 'REVERSE'), call.addstr(2, 30, '|', 'REVERSE')] mock_screen.assert_has_calls(calls)
def test_add_already_installed_channel(self): """Test adding an already added channel. Should only trigger the reposync for the channel""" channel = "sles11-sp3-pool-x86_64" options = get_options("add channel {0}".format(channel).split()) self.mgr_sync._fetch_remote_channels = MagicMock( return_value=parse_channels( read_data_from_fixture("list_channels.data"), self.mgr_sync.log)) stubbed_xmlrpm_call = MagicMock() self.mgr_sync._execute_xmlrpc_method = stubbed_xmlrpm_call with ConsoleRecorder() as recorder: self.assertEqual(0, self.mgr_sync.run(options)) expected_xmlrpc_calls = [ call._execute_xmlrpc_method(self.mgr_sync.conn.channel.software, "syncRepo", self.fake_auth_token, [channel]) ] stubbed_xmlrpm_call.assert_has_calls(expected_xmlrpc_calls) expected_output = [ "Channel '{0}' has already been added".format(channel), "Scheduling reposync for following channels:", "- {0}".format(channel) ] self.assertEqual(expected_output, recorder.stdout)
def test_retry_mechanism_no_sleep(pretty_api, monkeypatch): mocked_sleep = MagicMock() mocked_random = MagicMock(return_value=1) t.config.secure = False t.config.backoff_max_attempts = 5 monkeypatch.setattr(time, 'sleep', mocked_sleep) monkeypatch.setattr(random, 'uniform', mocked_random) with pytest.raises(HTTPError): t.retry() mocked_random.assert_has_calls([ call(0, 0.1 * 2 ** 0), call(0, 0.1 * 2 ** 1), call(0, 0.1 * 2 ** 2), call(0, 0.1 * 2 ** 3), call(0, 0.1 * 2 ** 4), ]) mocked_sleep.assert_has_calls([ call(1), call(1), call(1), call(1), call(1), ])
def test_add_available_base_channel(self): """ Test adding an available base channel""" channel = "rhel-i386-as-4" options = get_options("add channel {0}".format(channel).split()) self.mgr_sync._fetch_remote_channels = MagicMock( return_value=parse_channels( read_data_from_fixture("list_channels.data"), self.mgr_sync.log)) stubbed_xmlrpm_call = MagicMock() stubbed_xmlrpm_call.side_effect = xmlrpc_sideeffect self.mgr_sync._execute_xmlrpc_method = stubbed_xmlrpm_call with ConsoleRecorder() as recorder: self.assertEqual(0, self.mgr_sync.run(options)) expected_xmlrpc_calls = [ call._execute_xmlrpc_method(self.mgr_sync.conn.sync.content, "addChannels", self.fake_auth_token, channel, ''), call._execute_xmlrpc_method(self.mgr_sync.conn.channel.software, "syncRepo", self.fake_auth_token, [channel]) ] stubbed_xmlrpm_call.assert_has_calls(expected_xmlrpc_calls) expected_output = [ "Added '{0}' channel".format(channel), "Scheduling reposync for following channels:", "- {0}".format(channel) ] self.assertEqual(expected_output, recorder.stdout)
def test_create(self): credentials = Credentials("abc", "def") service = Service(credentials) response = { 'status': 'OK', 'ssh_key': { 'name': 'Name 1', 'id': 1, 'ssh_pub_key': "asr2354tegrh23425erfwerwerffghrgh3455" }, } mock = MagicMock(return_value=response) service.get = mock key = SSHKey.create( service, "Name 1", "asr2354tegrh23425erfwerwerffghrgh3455" ) self.assertEquals(key.id, 1) self.assertEquals(key.name, 'Name 1') self.assertEquals(key.public, "asr2354tegrh23425erfwerwerffghrgh3455") mock.assert_has_calls( [ call( 'ssh_keys/new', { "name": "Name 1", "ssh_pub_key": "asr2354tegrh23425erfwerwerffghrgh3455" }) ] )
def test_mapper_args_value(self, db, bridge, mocker): """ Test checks: 1) that 'FeedItem' class is instantiated once with correct arguments 2) that 'self.mapper' method is called once with correct arguments, Actually, with the item yielded by 'get_tenders' function. 3) that 'self.mapper' was called AFTER 'FeedItem' class instantiated. """ mock_feed_item = mocker.patch.object(databridge_module, 'FeedItem', side_effect=FeedItem, autospec=True) manager = MagicMock() mock_mapper = MagicMock() bridge['bridge'].mapper = mock_mapper manager.attach_mock(mock_mapper, 'mock_mapper') manager.attach_mock(mock_feed_item, 'mock_feed_item') bridge['bridge_thread'].join(0.1) manager.assert_has_calls( [call.mock_feed_item(bridge['tenders'][0]), call.mock_mapper(mock_feed_item(bridge['tenders'][0]))] )
def test_database_error(self): p = MagicMock(side_effect=Exception("Weird error")) with patch("djstatuspage.models.Status.objects.get_or_create", p): response = self._get_status(views.DefaultStatusPage) p.assert_has_calls([call(pk=1)]) self.assertEqual(response["database"], "error")
def test_get_request_exception_and_retry_and_success(self, Session): self.count = 0 request_exception = RequestException('I raise RequestException!') def exception_raiser(method, url, data, params, headers=None, allow_redirects=None): if self.count < 4: self.count += 1 raise request_exception return MagicMock(status_code=200, json=MagicMock(return_value={'success': 'True'})) Session.return_value = MagicMock(request=exception_raiser) ex = HttpExecutor('http://api.stormpath.com/v1', ('user', 'pass')) ShouldRetry = MagicMock(return_value=True) with patch('stormpath.http.HttpExecutor.should_retry', ShouldRetry): with self.assertRaises(Error): ex.get('/test') should_retry_calls = [ call(0, request_exception), call(1, request_exception), call(2, request_exception), call(3, request_exception), ] ShouldRetry.assert_has_calls(should_retry_calls)
def test_valid_hook(self, mock_load: MagicMock) -> None: """Test valid hook.""" mock_load.side_effect = [mock_hook, MockHook] hooks = [ CfnginHookDefinitionModel( **{ "path": "tests.unit.cfngin.hooks.test_utils.mock_hook", "required": True, }), CfnginHookDefinitionModel( **{ "path": "tests.unit.cfngin.hooks.test_utils.MockHook", "required": True, }), ] handle_hooks("pre_deploy", hooks, self.provider, self.context) assert mock_load.call_count == 2 mock_load.assert_has_calls([ call(hooks[0].path, try_reload=True), call(hooks[1].path, try_reload=True) ]) good = HOOK_QUEUE.get_nowait() self.assertEqual(good["provider"].region, "us-east-1") with self.assertRaises(queue.Empty): HOOK_QUEUE.get_nowait()
def test_args(self): mocked_os = MagicMock() mocked_log = MagicMock() mocked_grp = MagicMock() mocked_pass = MagicMock() mocked_file = MagicMock() mocked_args = MagicMock() mocked_parser = MagicMock() mocked_urlparse = MagicMock() mocked_parse_res1 = MagicMock() mocked_parse_res2 = MagicMock() mocked_log_handler = MagicMock() url = '[email protected]:owner/test.git' mocked_file.mkdtemp.return_value = "/tmp" mocked_pass.getuser.return_value = "test_user" mocked_os.getgid.return_value = 1 mocked_os.environ = {} mocked_os.path.abspath.return_value = "abs/tmp" mocked_grp.getgrgid().gr_name = "test_group" mocked_parser.parse_args.return_value = mocked_args mocked_args.remote_url = url mocked_parse_res1.scheme = None mocked_parse_res2.username = "******" mocked_urlparse.side_effect = [mocked_parse_res1, mocked_parse_res2] mocked_args.o = "magic=True,not_magic=False" mocked_args.group = None mocked_args.repo_path = None mocked_args.user = None mocked_args.branch = None mocked_args.ssh_user = None mocked_args.sentry_dsn = '' with patch.multiple('gitfs.utils.args', os=mocked_os, grp=mocked_grp, getpass=mocked_pass, tempfile=mocked_file, TimedRotatingFileHandler=mocked_log_handler, urlparse=mocked_urlparse, log=mocked_log): args = Args(mocked_parser) asserted_results = { "repo_path": "abs/tmp", "user": "******", "group": "test_group", "branch": "master", "not_magic": "False", "ssh_user": "******", } for name, value in iteritems(asserted_results): assert value == getattr(args, name) assert args.config == mocked_args assert mocked_pass.getuser.call_count == 1 assert mocked_file.mkdtemp.call_count == 1 mocked_log.setLevel.assert_called_once_with('DEBUG') mocked_urlparse.assert_has_calls([call(url), call('ssh://' + url)]) mocked_grp.getgrgid.has_calls([call(1)])
def test_check_attach_card(self): cl = ContollerClient() vm_original = self._get_vm() vm_get_mock = MagicMock(return_value=vm_original) with patch( "vsphere_plugin_common.VsphereClient._get_obj_by_id", vm_get_mock ): scsi_spec, controller_type = cl.generate_scsi_card( {'label': "Cloudify"}, 10) vm_get_mock.assert_called_once_with(vim.VirtualMachine, 10) self.assertEqual(scsi_spec.device.deviceInfo.label, "Cloudify") device = controller_type() device.key = 1001 vm_updated = self._get_vm() vm_updated.config.hardware.device.append(device) vm_get_mock = MagicMock(side_effect=[vm_original, vm_updated]) with patch( "vsphere_plugin_common.VsphereClient._get_obj_by_id", vm_get_mock ): self.assertEqual( cl.attach_controller(10, scsi_spec, controller_type), {'busKey': 1001, 'busNumber': 0}) vm_get_mock.assert_has_calls([ call(vim.VirtualMachine, 10), call(vim.VirtualMachine, 10, use_cache=False)])
def test_write_mutations_throttle_delay_retryable_error( self, unused_sleep): mock_batch = MagicMock() mock_batch.commit.side_effect = [ exceptions.DeadlineExceeded('retryable'), None ] mock_throttler = MagicMock() rpc_stats_callback = MagicMock() # First try: throttle once [True, False] # Second try: no throttle [False] mock_throttler.throttle_request.side_effect = [True, False, False] mutate = datastoreio._Mutate.DatastoreMutateFn(lambda: None) mutate._batch = mock_batch mutate._batch_elements = [] mutate._client = MagicMock() mutate.write_mutations(mock_throttler, rpc_stats_callback, throttle_delay=0) rpc_stats_callback.assert_has_calls([ call(successes=1), call(throttled_secs=ANY), call(errors=1), ], any_order=True) self.assertEqual(3, rpc_stats_callback.call_count)
def test_loop(self): timer = MagicMock() self.engine.loop(timer) self.engine.poll(0.01) self.engine.poll(0.01) self.engine.poll(0.01) timer.assert_has_calls([call() for _ in range(3)])
def test_remove_fact_no_paste(mock_requests): from cloudbot.util import database from plugins import factoids importlib.reload(database) importlib.reload(factoids) factoids.factoid_cache.clear() mock_requests.add(mock_requests.POST, 'https://hastebin.com/documents', status=404) mock_session = MagicMock() mock_notice = MagicMock() factoids.remove_fact('#example', ['foo'], mock_session, mock_notice) mock_notice.assert_called_once_with("Unknown factoids: 'foo'") mock_session.execute.assert_not_called() mock_notice.reset_mock() factoids.factoid_cache['#example']['foo'] = 'bar' factoids.remove_fact('#example', ['foo', 'bar'], mock_session, mock_notice) mock_notice.assert_has_calls([ call("Unknown factoids: 'bar'"), call('Unable to paste removed data, not removing facts'), ]) mock_session.execute.assert_not_called()
def test_get_request_exception_and_retry_and_success(self, Session): self.count = 0 request_exception = RequestException('mocked error') successful_response = MagicMock( status_code=200, json=MagicMock(return_value={'success': 'True'})) def faker(*args, **kwargs): if self.count < 3: self.count += 1 raise request_exception return successful_response Session.return_value = MagicMock(request=faker) ex = HttpExecutor('http://api.stormpath.com/v1', ('user', 'pass')) should_retry = MagicMock(return_value=True) with patch('stormpath.http.HttpExecutor.should_retry', should_retry): resp = ex.get('/test') self.assertEqual(resp['sp_http_status'], 200) should_retry.assert_has_calls([ call(0, request_exception), call(1, request_exception), call(2, request_exception), ])
def wraps_the_env_usage_with_creation_activation_and_deactivation(self): execute = MagicMock() @contextmanager def prefix(command): execute('called before prefix') execute('prefix: "%s"' % command) yield execute('called after prefix') with patch('provy.core.roles.Role.execute', execute), patch('fabric.api.prefix', prefix), self.env_exists('fancylib') as env_exists: venv = VirtualenvRole(prov=None, context={'user': '******',}) env_exists.return_value = False with venv('fancylib'): execute('some command') execute('some command 2') env_exists.assert_called_with('fancylib') env_creation_call = call('virtualenv %s/fancylib' % venv.base_directory, user='******') activation_prefix_call = call('prefix: "source %s/fancylib/bin/activate"' % venv.base_directory) expected_executes = [ env_creation_call, call('called before prefix'), activation_prefix_call, call('some command'), call('some command 2'), call('called after prefix'), ] execute.assert_has_calls(expected_executes)
def test_check_jobs(jobResetAgent): """Test for checkJobs function.""" jobIDs = [1, 2] dummy_treatJobWithNoReq = MagicMock() dummy_treatJobWithReq = MagicMock() # if the readRequestsForJobs func returns error than checkJobs should exit and return an error jobResetAgent.reqClient.readRequestsForJobs.return_value = S_ERROR() res = jobResetAgent.checkJobs(jobIDs, treatJobWithNoReq=dummy_treatJobWithNoReq, treatJobWithReq=dummy_treatJobWithReq) assert not res["OK"] # test if correct treatment functions are called jobResetAgent.reqClient.readRequestsForJobs.return_value = S_OK({'Successful': {}, 'Failed': {jobIDs[0]: 'Request not found'}}) jobResetAgent.checkJobs(jobIDs, treatJobWithNoReq=dummy_treatJobWithNoReq, treatJobWithReq=dummy_treatJobWithReq) dummy_treatJobWithNoReq.assert_has_calls([call(jobIDs[0]), call(jobIDs[1])]) dummy_treatJobWithReq.assert_not_called() dummy_treatJobWithNoReq.reset_mock() req1 = Request({"RequestID": 1}) req2 = Request({"RequestID": 2}) jobResetAgent.reqClient.readRequestsForJobs.return_value = S_OK({'Successful': {jobIDs[0]: req1, jobIDs[1]: req2}, 'Failed': {}}) jobResetAgent.checkJobs(jobIDs, treatJobWithNoReq=dummy_treatJobWithNoReq, treatJobWithReq=dummy_treatJobWithReq) dummy_treatJobWithNoReq.assert_not_called() dummy_treatJobWithReq.assert_has_calls([call(jobIDs[0], req1), call(jobIDs[1], req2)])
def test_construction( # pylint: disable=too-many-arguments self, mock_restoration, mock_notebook, mock_set_status, mock_status, mock_set_menu, mock_menu, ): mock_holder = MagicMock() mock_holder.attach_mock(mock_menu, 'ConfigFrameMenuBar') mock_holder.attach_mock(mock_set_menu, 'SetMenuBar') mock_holder.attach_mock(mock_status, 'ConfigFrameStatusBar') mock_holder.attach_mock(mock_set_status, 'SetStatusBar') mock_holder.attach_mock(mock_notebook, 'construct_notebook') mock_holder.attach_mock(mock_restoration, 'toggle_restoration') mock_holder.assert_not_called() self.frame.construct_gui() print(mock_holder.mock_calls) mock_holder.assert_has_calls( [ call.ConfigFrameMenuBar(), call.SetMenuBar(self.MENU_BAR), call.ConfigFrameStatusBar(self.frame), call.SetStatusBar(self.STATUS_BAR), call.construct_notebook(), call.toggle_restoration() ], True )
def test_add_available_base_channel_with_mirror(self): """ Test adding an available base channel""" mirror_url = "http://smt.suse.de" channel = "rhel-i386-as-4" options = get_options("add channel {0} --from-mirror {1}".format( channel, mirror_url).split()) self.mgr_sync._fetch_remote_channels = MagicMock( return_value=parse_channels( read_data_from_fixture("list_channels.data"), self.mgr_sync.log)) stubbed_xmlrpm_call = MagicMock() self.mgr_sync._execute_xmlrpc_method = stubbed_xmlrpm_call with ConsoleRecorder() as recorder: self.assertEqual(0, self.mgr_sync.run(options)) expected_xmlrpc_calls = [ call._execute_xmlrpc_method(self.mgr_sync.conn.sync.content, "addChannels", self.fake_auth_token, channel, mirror_url), self._mock_iterator(), call._execute_xmlrpc_method(self.mgr_sync.conn.channel.software, "syncRepo", self.fake_auth_token, [channel]) ] stubbed_xmlrpm_call.assert_has_calls(expected_xmlrpc_calls) expected_output = [ "Adding '{0}' channel".format(channel), "Scheduling reposync for '{0}' channel".format(channel) ]
def test_create_inventory_groups(self, m_inventory_manager): groups = {"cvms": ["1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"], "nodes": ["5.5.5.5", "6.6.6.6", "7.7.7.7", "8.8.8.8"]} m_inv_get_host = MagicMock() m_inventory_manager.return_value.attach_mock(m_inv_get_host, 'get_host') # `name` hack for breaking mock parent/child relationship m_host = MagicMock(name="not-a-child") m_inv_get_host.return_value = m_host inventory = anteater.main._create_inventory(sen.loader, groups=groups) # inventory = InventoryManager(loader=loader) m_inventory_manager.assert_called_once_with(loader=sen.loader) # inventory.add_group(group_name) expected_inv_add_group_calls = [call(key) for key in groups.keys()] m_inventory_manager.return_value.add_group.has_calls(expected_inv_add_group_calls) self.assertEqual(len(expected_inv_add_group_calls), m_inventory_manager.return_value.add_group.call_count) # inventory.add_host(host_name, group=group_name) expected_inv_add_host_calls = [call(host, group=group_name) for group_name, host_list in groups.iteritems() for host in host_list] m_inventory_manager.return_value.add_host.assert_has_calls( expected_inv_add_host_calls) self.assertEqual(len(expected_inv_add_host_calls), m_inventory_manager.return_value.add_host.call_count) # inventory.get_host(host_name) expected_inv_get_host_calls = [call(host) for group_name, host_list in groups.iteritems() for host in host_list] m_inv_get_host.assert_has_calls(expected_inv_get_host_calls) self.assertEqual(len(expected_inv_get_host_calls), m_inv_get_host.call_count) # host.add_group(group) expected_host_add_group_calls = [call(group_name) for group_name, host_list in groups.iteritems() for host in host_list] self.assertEqual(len(expected_host_add_group_calls), m_host.add_group.call_count) # group.add_host(host) expected_group_add_host_calls = [call(host) for group_name, host_list in groups.iteritems() for host in host_list] self.assertEqual(len(expected_group_add_host_calls), m_inventory_manager.return_value.groups.__getitem__.return_value.add_host.call_count) # inventory.reconcile_inventory() m_inventory_manager.return_value.reconcile_inventory\ .assert_called_once_with() # return inventory self.assertEqual(m_inventory_manager.return_value, inventory)
def test_unindex_objects(self, get_es_mock): mapping_type = MagicMock() unindex_objects(mapping_type, [1, 2, 3], 'foo') ok_(mapping_type.unindex.called) mapping_type.assert_has_calls([ call.unindex(1, es=get_es_mock(), public_index='foo'), call.unindex(2, es=get_es_mock(), public_index='foo'), call.unindex(3, es=get_es_mock(), public_index='foo')])
def test_unindex_objects(self, get_es_mock): model = MagicMock() unindex_objects(model, [1, 2, 3], 'foo') ok_(model.unindex.called) model.assert_has_calls([ call.unindex(es=get_es_mock(), public_index='foo', id=1), call.unindex(es=get_es_mock(), public_index='foo', id=2), call.unindex(es=get_es_mock(), public_index='foo', id=3)])
def test_existing_and_nonexistent(self): mock_intern = MagicMock() dummy_core = MagicMock(InternAtom=mock_intern) dummy_connection = MagicMock(core=dummy_core) self.prop_user.get_unknown_atom(dummy_connection, self.ATOM) mock_intern.assert_has_calls( [call(False, len(self.ATOM), self.ATOM), call().reply()])
def test_observable_unregister(self): notify_observers_mock = MagicMock() self.appmgr.notify_observers = notify_observers_mock self.my_app() app = self.appmgr.grab_apps()[0] self.appmgr.unregister(app) calls = [call("unregister", app, self.fake_interface)] notify_observers_mock.assert_has_calls(calls)
def test_retry_grpc_raises(self) -> None: fn = MagicMock() # Always a GOAWAY error fn.side_effect = GO_AWAY_ERROR with self.assertRaises(exceptions.InternalServerError): retry_grpc(3, fn, 1, b=2) fn.assert_has_calls([call(1, b=2)] * 4)
def testCompositeEvent(self): m = MagicMock() e1 = Event(m, "one") e2 = Event(m, "two") ce = CompositeEvent(e1, e2) self.performSequenceTest(ce) m.assert_has_calls([call("one"), call("two")])
def test_retry_grpc_raises_no_goaway(self) -> None: fn = MagicMock() # Always a different error fn.side_effect = OTHER_ERROR with self.assertRaises(exceptions.InternalServerError): retry_grpc(3, fn, 1, b=2) fn.assert_has_calls([call(1, b=2)])
def test_args(self): mocked_os = MagicMock() mocked_log = MagicMock() mocked_grp = MagicMock() mocked_pass = MagicMock() mocked_file = MagicMock() mocked_args = MagicMock() mocked_parser = MagicMock() mocked_urlparse = MagicMock() mocked_parse_res1 = MagicMock() mocked_parse_res2 = MagicMock() mocked_log_handler = MagicMock() url = '[email protected]:owner/test.git' mocked_file.mkdtemp.return_value = "/tmp" mocked_pass.getuser.return_value = "test_user" mocked_os.getgid.return_value = 1 mocked_os.environ = {} mocked_os.path.abspath.return_value = "abs/tmp" mocked_grp.getgrgid().gr_name = "test_group" mocked_parser.parse_args.return_value = mocked_args mocked_args.remote_url = url mocked_parse_res1.scheme = None mocked_parse_res2.username = "******" mocked_urlparse.side_effect = [mocked_parse_res1, mocked_parse_res2] mocked_args.o = "magic=True,not_magic=False" mocked_args.group = None mocked_args.repo_path = None mocked_args.user = None mocked_args.branch = None mocked_args.ssh_user = None mocked_args.sentry_dsn = '' with patch.multiple('gitfs.utils.args', os=mocked_os, grp=mocked_grp, getpass=mocked_pass, tempfile=mocked_file, TimedRotatingFileHandler=mocked_log_handler, urlparse=mocked_urlparse, log=mocked_log): args = Args(mocked_parser) asserted_results = { "repo_path": "abs/tmp", "user": "******", "group": "test_group", "branch": "master", "not_magic": "False", "ssh_user": "******", } for name, value in asserted_results.iteritems(): assert value == getattr(args, name) assert args.config == mocked_args assert mocked_pass.getuser.call_count == 1 assert mocked_file.mkdtemp.call_count == 1 mocked_log.setLevel.assert_called_once_with('DEBUG') mocked_urlparse.assert_has_calls([call(url), call('ssh://' + url)]) mocked_grp.getgrgid.has_calls([call(1)])
def test_prepere_after_filter(self): """ Django will reset related selects when a filter is added """ queryset = MagicMock() queryset_resource = ComplexUserResourceQuerySetResource(queryset) queryset_resource.get(mock_context(), EmptyParams()) calls = call.all().distinct().filter().select_related('manager').prefetch_related('reports').call_list() queryset.assert_has_calls(calls)
def test_write_blog_index_page_single(self): self.builder._per_page = 1 write_file = MagicMock() self.builder._write_file = write_file self.builder._write_blog_index_page(PAGE_POSTS, 1) write_file.assert_has_calls([ call(ANY, ''), call(ANY, 'blog'), call(ANY, 'blog/pages/1') ])
def test_with_progress_bar(): num_calls = 5 mocked_function = MagicMock() progress_func = with_progress_bar(mocked_function, num_calls) with patch.object(synapseutils.monitor, 'printTransferProgress') as mocked_progress_print: for i in range(num_calls): progress_func(i) mocked_progress_print.assert_has_calls([call(float(i+1), num_calls, '', '', False) for i in range(num_calls)]) mocked_function.assert_has_calls([call(i) for i in range(num_calls)])
def test_commit(): mock = MagicMock() with patch("subprocess.call", mock): scm = SourceControl() scm.commit("my message") mock.assert_has_calls( [ call(["git.exe", "add", "-u"], env=ANY, shell=True), call(["git.exe", "commit", "-m", "my message"], env=ANY, shell=True), ] )
def test_init_resources(self): mock_bbbDAQ=MagicMock() args=MagicMock(serialPort='2068', serialPortBar=None, database='hi') mock_bbbDAQ.init_port.return_value='The serial Port' mock_bbbDAQ.init_database.return_value='The database' bbbDAQ.init_port=mock_bbbDAQ.init_port bbbDAQ.init_database=mock_bbbDAQ.init_database my_port, my_port_bar, my_conn = bbbDAQ.init_resources(args) mock_bbbDAQ.assert_has_calls([call.init_port(args.serialPort, args_baudrate=921600), call.init_port(args.serialPortBar, args_baudrate=921600), call.init_database(args.database)], any_order=True)
def test_load_apps(self): load_app_mock = MagicMock() self.appmgr.path_apps = "/".join((__file__.split("/")[:-1])) + "/apps" old_load = self.appmgr.load_app self.appmgr.load_app = load_app_mock notify_observers_mock = MagicMock() self.appmgr.notify_observers = notify_observers_mock self.appmgr.load_apps() calls = [call("app1"), call("app2"), call("appIntegration")] load_app_mock.assert_has_calls(calls, any_order=True) calls = [call("load_apps")] notify_observers_mock.assert_has_calls(calls) self.appmgr.load_app = old_load
def test_trigger_job(self): check_call = MagicMock() trigger = {'name': 'foo-ci', 'branch': 'lp:foo', 'options': ['--trigger-ci']} plugin_path = '/iSCSI/jenkins/plugin' plugin = os.path.join(plugin_path, 'launchpadTrigger.py') calls = [ call([plugin, '--lock-name=lock', '--branch=lp:foo', '--job=foo-ci', '--trigger-ci'], cwd=plugin_path, stderr=subprocess.STDOUT)] with patch('subprocess.check_call', check_call): self.jt.trigger_job(plugin_path, trigger, 'lock') check_call.assert_has_calls(calls)
def test_cycle(self): self.engine.poll(0.01) timer = MagicMock(side_effect=self.timer) expected_times = [ self.engine.time + 0.01, self.engine.time + 0.02, self.engine.time + 0.03 ] self.engine.cycle(0.01, timer) self.engine.poll(0.2) self.engine.poll(0.2) self.engine.poll(0.2) timer.assert_has_calls([call() for _ in range(3)]) for i in range(3): self.assertLess(abs(expected_times[i] - self.times_called[i]), 0.01)
def test_cycle(self): self.engine.poll(0.01) timer = MagicMock(side_effect=self.timer) expected_times = [ self.engine.latest_poll_time + 0.01, self.engine.latest_poll_time + 0.02, self.engine.latest_poll_time + 0.03 ] self.engine.cycle(0.01, timer) self.engine.poll(0.2) self.engine.poll(0.2) self.engine.poll(0.2) if sys.platform == "win32": self.engine.poll(0.02) # See issue #40 timer.assert_has_calls([call() for _ in range(3)]) for i in range(3): self.assertLess(abs(expected_times[i] - self.times_called[i]), 0.01)
def testValueChange(self): ts = TouchSpinner() signal_receiver = MagicMock() ts.valueChanged.connect(signal_receiver) self.assertEqual(50, ts.value()) self.findButton(ts, '+').click() self.assertEqual(51, ts.value()) self.findButton(ts, '-').click() self.assertEqual(50, ts.value()) signal_receiver.assert_has_calls([ call(51), call(50) ]) ts.valueChanged.disconnect(signal_receiver)
class TestConsumerPool(TestCase): def setUp(self): self.channel = MagicMock(Channel) self.greenlet_maker = MagicMock(gevent.Greenlet) self.consumer_class = MagicMock('consumer_class') self.consumer_class.__name__ = 'Mock consumer class' def test_creates_consumer_specific_number_of_times(self): i = 3 ConsumerPool( self.channel, self.consumer_class, self.greenlet_maker, i, ) calls = [call() for _ in range(i)] self.consumer_class.assert_has_calls(calls)
def test_clear_repository_helper(): reserve_fn = MagicMock() reserve_fn.return_value = (0x1234) clear_fn = MagicMock() clear_fn.side_effect = [ ERASURE_COMPLETED, ERASURE_IN_PROGRESS, ERASURE_COMPLETED, ] clear_repository_helper(reserve_fn, clear_fn) clear_calls = [ call(INITIATE_ERASE, 0x1234), call(GET_ERASE_STATUS, 0x1234), call(GET_ERASE_STATUS, 0x1234), ] clear_fn.assert_has_calls(clear_calls) eq_(clear_fn.call_count, 3)
def test_access(self): mocked_access = MagicMock() mocked_access.side_effect = [True, True, False] with patch('gitfs.views.passthrough.os.access', mocked_access): view = PassthroughView(repo=self.repo, repo_path=self.repo_path) # normal, easy test view.access('good/relative/path', 777) # test if _full_path works view.access('/good/relative/path', 777) # test if proper exception is raised with raises(FuseOSError): view.access('/relative/path', 777) asserted_calls = [call('/the/root/path/good/relative/path', 777), call('/the/root/path/good/relative/path', 777), call('/the/root/path/relative/path', 777)] mocked_access.assert_has_calls(asserted_calls) assert mocked_access.call_count == 3