def test_update_step(self): task = self.do_configure(axes_to_scan=["x", "y"]) positionsA = task.put_many.call_args_list[3][0][1]["positionsA"] self.assertEqual(len(positionsA), 11) self.assertEqual(positionsA[-1], 0.375) self.assertEqual(self.o.end_index, 4) self.assertEqual(len(self.o.completed_steps_lookup), 11) update_completed_steps = MagicMock() task = MagicMock() self.o.update_step(3, update_completed_steps, task) update_completed_steps.assert_called_once_with(1, self.o) self.assertEqual(self.o.loading, False) self.assertEqual(task.put_many.call_count, 2) self.assertEqual(task.post.call_count, 1) self.check_resolutions_and_use(task.put_many.call_args_list[0][0][1]) self.assertEqual(task.post.call_args_list[0], call(self.child["appendProfile"])) self.assertEqual(task.put_many.call_args_list[1][0][1], dict( timeArray=[ 500000, 500000, 500000, 500000, 100000], velocityMode=[ 0, 0, 0, 1, 3], userPrograms=[ 4, 3, 4, 2, 8], pointsToBuild=5, positionsA=[ 0.25, 0.125, 0.0, -0.125, -0.1375], positionsB=[ 0.1, 0.1, 0.1, 0.1, 0.1]))
def test_rename(self): mocked_re = MagicMock() mocked_index = MagicMock() mocked_os = MagicMock() mocked_result = MagicMock() mocked_result.rename.return_value = True mocked_re.sub.return_value = "new" mocked_os.path.split.return_value = [1, 1] with patch.multiple('gitfs.views.current', re=mocked_re, os=mocked_os): from gitfs.views import current as current_view old_rename = current_view.PassthroughView.rename current_view.PassthroughView.rename = lambda self, old, new: True current = CurrentView(regex="regex", repo="repo", repo_path="repo_path", ignore=CachedIgnore()) current._stage = mocked_index result = current.rename("old", "new") assert result is True mocked_index.assert_called_once_with(**{ 'remove': 1, 'add': "new", "message": "Rename old to new" }) mocked_os.path.split.assert_called_once_with("old") current_view.PassthroughView.rename = old_rename
def test_get_view(self): mocked_index = MagicMock() mocked_current = MagicMock() mocked_view = MagicMock(return_value=mocked_current) router, mocks = self.get_new_router() router.register([ ("/history", mocked_view), ("/current", mocked_view), ("/", MagicMock(return_value=mocked_index)), ]) with patch('gitfs.router.lru_cache') as mocked_cache: mocked_cache.get_if_exists.return_value = None view, path = router.get_view("/current") assert view == mocked_current assert path == "/" asserted_call = { 'repo': mocks['repo'], 'ignore': mocks['repo'].ignore, 'repo_path': mocks['repo_path'], 'mount_path': mocks['mount_path'], 'regex': "/current", 'relative_path': "/", 'uid': 1, 'gid': 1, 'branch': mocks['branch'], 'mount_time': 0, 'queue': mocks['queue'], 'max_size': mocks['max_size'], 'max_offset': mocks['max_offset'], } mocked_view.assert_called_once_with(**asserted_call) mocked_cache.get_if_exists.assert_called_once_with("/current")
def test_load_data_auto_assigns_label(): factory = MagicMock() result = Data(x=[1, 2, 3], label='') factory.return_value = result d = df.load_data('test.fits', factory) factory.assert_called_once_with('test.fits') assert d.label == 'test'
def test_getattr(self): mocked_full = MagicMock() mocked_os = MagicMock() mocked_stat = MagicMock() mocked_repo = MagicMock() mocked_stat.simple = "stat" mocked_os.lstat.return_value = mocked_stat mocked_full.return_value = "full_path" mocked_repo._full_path = mocked_full with patch.multiple('gitfs.views.current', os=mocked_os, STATS=['simple']): current = CurrentView(repo=mocked_repo, uid=1, gid=1, repo_path="repo_path", ignore=CachedIgnore()) current._full_path = mocked_full result = current.getattr("path") asserted_result = { 'st_uid': 1, 'st_gid': 1, 'simple': "stat" } assert result == asserted_result mocked_os.lstat.assert_called_once_with("full_path") mocked_full.assert_called_once_with("path")
def run_contents_pillar(self, pillar_value, expected): def returner(contents, *args, **kwargs): returner.returned = (contents, args, kwargs) returner.returned = None filestate.__salt__ = {"file.manage_file": returner} path = "/tmp/foo" pillar_path = "foo:bar" # the values don't matter here filestate.__salt__["config.manage_mode"] = MagicMock() filestate.__salt__["file.source_list"] = MagicMock(return_value=[None, None]) filestate.__salt__["file.get_managed"] = MagicMock(return_value=[None, None, None]) # pillar.get should return the pillar_value pillar_mock = MagicMock(return_value=pillar_value) filestate.__salt__["pillar.get"] = pillar_mock ret = filestate.managed(path, contents_pillar=pillar_path) # make sure the pillar_mock is called with the given path pillar_mock.assert_called_once_with(pillar_path) # make sure no errors are returned self.assertEquals(None, ret) # make sure the value is correct self.assertEquals(expected, returner.returned[1][-1])
def test_solve_conflicts_both_update_a_file(self): mocked_theirs = MagicMock() mocked_ours = MagicMock(id="id", path="path") mocked_full = MagicMock(return_value="full_path") mocked_repo = MagicMock(_full_path=mocked_full) mocked_repo.get().data = "data" def conflicts(): yield None, mocked_theirs, mocked_ours mock_path = 'gitfs.merges.accept_mine.open' with patch(mock_path, create=True) as mocked_open: mocked_file = MagicMock(spec=file) mocked_open.return_value = mocked_file mine = AcceptMine(mocked_repo) mine.solve_conflicts(conflicts()) mocked_full.assert_called_once_with("path") mocked_open.assert_called_once_with("full_path", "w") mocked_repo.get.has_calls([call("id")]) mocked_open().__enter__().write.assert_called_once_with("data") mocked_repo.index.add.assert_called_once_with("path")
def test_with_method_name(self, TestSuiteMock): case = MagicMock() result = self.obj.prepere_suite(case, 'method') TestSuiteMock.assert_called_once_with() case.assert_called_once_with('method') TestSuiteMock().addTest.assert_called_once_with(case()) self.assertEqual(TestSuiteMock(), result)
def test_add_correlation_info_to_message(self): route_message_func = MagicMock() with patch('meniscus.correlation.correlator.sinks.route_message', route_message_func): correlator._add_correlation_info_to_message( self.tenant, self.cee_msg) route_message_func.assert_called_once_with(self.cee_msg)
def test_list_command_with_prefix(self): eggs = [ 'M2Crypto==0.21.1', '-e [email protected]:s0undt3ch/salt-testing.git@9ed81aa2f918d59d3706e56b18f0782d1ea43bf8#egg=SaltTesting-dev', 'bbfreeze==1.1.0', 'bbfreeze-loader==1.1.0', 'pycrypto==2.6' ] mock = MagicMock( return_value={ 'retcode': 0, 'stdout': '\n'.join(eggs) } ) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): ret = pip.list_(prefix='bb') mock.assert_called_once_with( 'pip freeze', runas=None, cwd=None ) self.assertEqual( ret, { 'bbfreeze-loader': '1.1.0', 'bbfreeze': '1.1.0', } )
def test_assess_status(self): with patch.object(nutils, 'assess_status_func') as asf: callee = MagicMock() asf.return_value = callee nutils.assess_status('test-config') asf.assert_called_once_with('test-config') callee.assert_called_once_with()
def test_uninstall_timeout_argument_in_resulting_command(self): # Passing an int mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): pip.uninstall('pep8', timeout=10) mock.assert_called_once_with( 'pip uninstall -y --timeout=10 pep8', runas=None, cwd=None ) # Passing an int as a string mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): pip.uninstall('pep8', timeout='10') mock.assert_called_once_with( 'pip uninstall -y --timeout=10 pep8', runas=None, cwd=None ) # Passing a non-int to timeout mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): self.assertRaises( ValueError, pip.uninstall, 'pep8', timeout='a' )
def test_freeze_command(self): eggs = [ 'M2Crypto==0.21.1', '-e [email protected]:s0undt3ch/salt-testing.git@9ed81aa2f918d59d3706e56b18f0782d1ea43bf8#egg=SaltTesting-dev', 'bbfreeze==1.1.0', 'bbfreeze-loader==1.1.0', 'pycrypto==2.6' ] mock = MagicMock( return_value={ 'retcode': 0, 'stdout': '\n'.join(eggs) } ) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): ret = pip.freeze() mock.assert_called_once_with( 'pip freeze', runas=None, cwd=None ) self.assertEqual(ret, eggs) # Non zero returncode raises exception? mock = MagicMock(return_value={'retcode': 1, 'stderr': 'CABOOOOMMM!'}) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): self.assertRaises( CommandExecutionError, pip.freeze, )
def test_install_cached_requirements_used(self, get_cached_requirements): get_cached_requirements.return_value = 'my_cached_reqs' mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): pip.install(requirements='salt://requirements.txt') expected_cmd = 'pip install --requirement=\'my_cached_reqs\'' mock.assert_called_once_with(expected_cmd, runas=None, cwd=None)
def test_install_multiple_editable(self): editables = [ 'git+https://github.com/jek/blinker.git#egg=Blinker', 'git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting' ] # Passing editables as a list mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): pip.install(editable=editables) mock.assert_called_once_with( 'pip install ' '--editable=git+https://github.com/jek/blinker.git#egg=Blinker ' '--editable=git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting', runas=None, cwd=None ) # Passing editables as a comma separated list mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) with patch.dict(pip.__salt__, {'cmd.run_all': mock}): pip.install(editable=','.join(editables)) mock.assert_called_once_with( 'pip install ' '--editable=git+https://github.com/jek/blinker.git#egg=Blinker ' '--editable=git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting', runas=None, cwd=None )
def test_prepare_docset(monkeypatch): with tempfile.TemporaryDirectory() as td: monkeypatch.chdir(td) m_ct = MagicMock() monkeypatch.setattr(shutil, 'copytree', m_ct) os.mkdir('bar') args.configure_mock(source='some/path/foo', name='foo') main.prepare_docset(args, 'bar') m_ct.assert_called_once_with( 'some/path/foo', 'bar/Contents/Resources/Documents', ) assert os.path.isfile('bar/Contents/Resources/docSet.dsidx') p = plistlib.readPlist('bar/Contents/Info.plist') assert p == { 'CFBundleIdentifier': 'foo', 'CFBundleName': 'foo', 'DocSetPlatformFamily': 'foo', 'DashDocSetFamily': 'python', 'isDashDocset': True, } with sqlite3.connect('bar/Contents/Resources/docSet.dsidx') as db_conn: cur = db_conn.cursor() # ensure table exists and is empty cur.execute('select count(1) from searchIndex') assert cur.fetchone()[0] == 0
def test_update_acquire_url(self, private, acquire_url, resource_provider, resource_name, resource_version, should_update): c = store_connector.plugins.toolkit.c c.user = resource_provider package_update = MagicMock() store_connector.plugins.toolkit.get_action = MagicMock(return_value=package_update) # Call the method dataset = { 'private': private, 'acquire_url': acquire_url } resource = { 'name': resource_name, 'version': resource_version, 'provider': resource_provider, 'id': 'example_id' } expected_dataset = dataset.copy() # new_name = resource['name'].replace(' ', '%20') expected_dataset['acquire_url'] = '%s/#/offering?productSpecId=%s' % (BASE_STORE_URL, resource['id']) # Update Acquire URL self.instance._update_acquire_url(dataset, resource) # Check that the acquire URL has been updated if should_update: context = {'model': store_connector.model, 'session': store_connector.model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, } package_update.assert_called_once_with(context, expected_dataset) else: self.assertEquals(0, package_update.call_count)
def test_component_id_combo_helper_add(): # Make sure that when adding a component, and if a data collection is not # present, the choices still get updated callback = MagicMock() state = ExampleState() state.add_callback('combo', callback) dc = DataCollection([]) helper = ComponentIDComboHelper(state, 'combo') assert selection_choices(state, 'combo') == "" data1 = Data(x=[1, 2, 3], y=[2, 3, 4], label='data1') callback.reset_mock() dc.append(data1) helper.append_data(data1) callback.assert_called_once_with(0) callback.reset_mock() assert selection_choices(state, 'combo') == "x:y" data1.add_component([7, 8, 9], 'z') # Should get notification since choices have changed callback.assert_called_once_with(0) callback.reset_mock() assert selection_choices(state, 'combo') == "x:y:z"
def test_update_with_no_args(self): mock = MagicMock(name='update') timeline = Timeline(update_function=mock,) timeline.update() mock.assert_called_once_with()
def test_logs_subcommand(): get_logs_method = MagicMock() result_value = "" get_logs_method.return_value = (True, result_value) spark_controller.get_logs = get_logs_method command = "logs -s" name = "sessions_name" line = " ".join([command, name]) cell = "cell code" # Could get results result = magic.spark(line, cell) get_logs_method.assert_called_once_with(name) assert result is None ipython_display.write.assert_called_once_with(result_value) # Could not get results get_logs_method.reset_mock() get_logs_method.return_value = (False, result_value) result = magic.spark(line, cell) get_logs_method.assert_called_once_with(name) assert result is None ipython_display.send_error.assert_called_once_with(result_value)
def test_add_sessions_command_parses(): # Do not skip and python add_sessions_mock = MagicMock() spark_controller.add_session = add_sessions_mock command = "add" name = "-s name" language = "-l python" connection_string = "-u http://url.com -a sdf -p w" line = " ".join([command, name, language, connection_string]) magic.spark(line) add_sessions_mock.assert_called_once_with("name", Endpoint("http://url.com", "sdf", "w"), False, {"kind": "pyspark"}) # Skip and scala - upper case add_sessions_mock = MagicMock() spark_controller.add_session = add_sessions_mock command = "add" name = "-s name" language = "-l scala" connection_string = "--url http://location:port" line = " ".join([command, name, language, connection_string, "-k"]) magic.spark(line) add_sessions_mock.assert_called_once_with("name", Endpoint("http://location:port"), True, {"kind": "spark"})
def test_delete_sequence(self): self.mongo_handler.status = mongodb.STATUS_CONNECTED sequence = 'sequence01' delete_sequence = MagicMock() self.mongo_handler.delete = delete_sequence self.mongo_handler.delete_sequence(sequence) delete_sequence.assert_called_once_with('counters', {'name': sequence})
def test_diverge(self): mocked_repo = MagicMock() mocked_lookup = MagicMock() mocked_find = MagicMock() mocked_commits = MagicMock() mocked_branch_remote = MagicMock(target=1) mocked_branch_local = MagicMock(target=2) def lookup(reference, opt): if "origin/master" == reference: return mocked_branch_remote return mocked_branch_local mocked_commits.second_commits = [] mocked_commits.first_commits = [] mocked_find.return_value = mocked_commits mocked_lookup = lookup repo = Repository(mocked_repo) repo.lookup_branch = mocked_lookup repo.find_diverge_commits = mocked_find assert repo.diverge("origin", "master") == (False, False) mocked_find.assert_called_once_with(mocked_branch_local, mocked_branch_remote)
def test_connection(self): connection = MagicMock(return_value=MagicMock()) with patch('meniscus.data.adapters.mongodb.MongoClient', connection): self.mongo_handler.connect() connection.assert_called_once_with(self.mongo_handler.mongo_servers, slave_okay=True) self.assertEquals(self.mongo_handler.status, mongodb.STATUS_CONNECTED)
def test_create_sequence_existing_sequence(self): self.mongo_handler.status = mongodb.STATUS_CONNECTED sequence = 'sequence01' create_sequence = MagicMock() self.mongo_handler.find_one = create_sequence self.mongo_handler.create_sequence(sequence) create_sequence.assert_called_once_with('counters', {'name': sequence})
def test_add_endpoint_command_parses(): # Do not skip add_endpoint_mock = MagicMock() spark_controller.add_endpoint = add_endpoint_mock command = "add" name = "name" language = "python" connection_string = "url=http://location:port;username=name;password=word" line = " ".join([command, name, language, connection_string]) magic.spark(line) add_endpoint_mock.assert_called_once_with(name, language, connection_string, False) # Skip add_endpoint_mock = MagicMock() spark_controller.add_endpoint = add_endpoint_mock command = "add" name = "name" language = "python" connection_string = "url=http://location:port;username=name;password=word" line = " ".join([command, name, language, connection_string, "skip"]) magic.spark(line) add_endpoint_mock.assert_called_once_with(name, language, connection_string, True)
def test_propagate_tle(self): """ Tests the _propagate_tle() method which is responsible for performing one round of propagation and sending the new position data to the registered position data handlers. """ # Mock time to return a known time old_time = time.time time.time = lambda : 1385438844 # Create a service to test with test_service = sgp4_tracker.SGP4PropagationService('direct_downlink_aprs_service', 'tracker', self.standard_device_config) test_service.set_tle("1 37853U 11061D 13328.80218348 .00012426 00000-0 90147-3 0 6532", "2 37853 101.7000 256.9348 0228543 286.4751 136.0421 14.85566785112276") # Register a mock position receiver results = None def test_receiver(targetting_info): results = targetting_info test_receiver2 = MagicMock() test_service.register_position_receiver(test_receiver) test_service.register_position_receiver(test_receiver2) # Run the propagator and verify the results results = test_service._propagate_tle() test_receiver2.assert_called_once_with(results) self.assertEqual(results['timestamp'], 1385438844) self.assertEqual(results['altitude'], 643468.9375) self.assertEqual(results['elevation'], -41.31524396861143) self.assertEqual(results['azimuth'], 111.91629687167571) self.assertEqual(results['latitude'], -0.9842437063337659) self.assertEqual(results['longitude'], -48.365802362005475) # Restore the time module time.time = old_time
def test_remove_broken_public_id(self, remove_owner, HTTPCallbackGroup, get_associated_privates): # Setup HTTPCallbackGroup.return_value = MagicMock() on_success_handler = MagicMock() on_failure_handler = MagicMock() self.handler.forward_error = MagicMock() sip_uri = SIP_URI2 # Test numbers.remove_public_id(self.db_sess, sip_uri, on_success_handler, on_failure_handler, False) # Fail the Priv->Pub lookup get_associated_privates.assert_called_once_with(sip_uri, ANY) HTTPCallbackGroup.assert_called_once_with(ANY, ANY) failure_callback = HTTPCallbackGroup.call_args[0][1] error = MagicMock() error.code = 404 failure_callback(error) # Asserts remove_owner.assert_called_once_with(self.db_sess, sip_uri) self.db_sess.commit.assert_called_once() on_success_handler.assert_called_once_with({})
def test__rvm(self): mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) with patch.dict(rvm.__salt__, {'cmd.run_all': mock}): rvm._rvm("install", "1.9.3") mock.assert_called_once_with( "/usr/local/rvm/bin/rvm install 1.9.3", runas=None )
def test_default_no(self): get_input = MagicMock(return_value="") self.assertEqual( ui.ask_interactively("OHAI?", False, get_input=get_input), False, ) get_input.assert_called_once_with("OHAI? [y/N] ")
def test_create_tasks_Several_tasks(self): self.te.create_issue = MagicMock() self.te.create_issue.return_value = 'DRYRUN-XXXX' self.te.update_issue_desc = MagicMock() input_list = [{'assignee': 'assignee', 'markup': 'h4.', 'description': 'h4 task description', 'summary': 'h4 task'}, \ {'assignee': 'assignee', 'markup': 'h5.', 'summary': 'h5 task', 'description': 'h5 task description'}, \ {'assignee': 'assignee', 'markup': '#', 'description': 'line1 description\nline2 description', 'summary': 'sub-task'}] expected_result = [call({'issuetype': 'User Story', 'assignee': 'assignee', 'markup': 'h4.', \ 'description': 'h4 task description', 'summary': 'h4 task'}), \ call({'issuetype': 'Task', 'assignee': 'assignee', 'markup': 'h5.', 'description': \ 'h5 task description', 'summary': 'h5 task'}), \ call({'description': 'line1 description\nline2 description', 'parent': 'DRYRUN-XXXX', \ 'markup': '#', 'summary': 'sub-task', 'assignee': 'assignee', 'issuetype': 'Sub-task'})] self.te.create_tasks(input_list) self.assertEquals(self.te.create_issue.call_args_list, expected_result) MagicMock.assert_called_once_with(self.te.update_issue_desc, 'DRYRUN-XXXX', 'h5 task description\n# sub-task (DRYRUN-XXXX)')
def test_build_master_key_provider_known_provider( patch_load_master_key_provider): mock_provider_callable = MagicMock() patch_load_master_key_provider.return_value = mock_provider_callable test = master_key_parsing._build_master_key_provider( discovery=sentinel.discovery, provider=sentinel.known_provider_id, key=[], a=sentinel.a, b=sentinel.b) patch_load_master_key_provider.assert_called_once_with( sentinel.known_provider_id) mock_provider_callable.assert_called_once_with( a=sentinel.a, b=sentinel.b, discovery=sentinel.discovery) assert not mock_provider_callable.return_value.add_master_key.called assert test is mock_provider_callable.return_value
def test_set_is_developer_mode(self, value): settings_manager = SettingsManager() set_is_developer_mode_mock = MagicMock() settings_manager.set_is_developer_mode = set_is_developer_mode_mock settings_developer_resource = SettingsDeveloper(settings_manager) self.api.add_route('/api/settings/developer', settings_developer_resource) request = {'is_developer_mode': value} self.simulate_request("/api/settings/developer", method="PUT", body=json.dumps(request)) self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT) set_is_developer_mode_mock.assert_called_once_with(value)
def test_logs_subcommand(): get_logs_method = MagicMock() result_value = "" get_logs_method.return_value = result_value spark_controller.get_logs = get_logs_method command = "logs -s" name = "sessions_name" line = " ".join([command, name]) cell = "cell code" result = magic.spark(line, cell) get_logs_method.assert_called_once_with(name) assert result is None ipython_display.write.assert_called_once_with(result_value)
def test_run_cell_command_exception(): run_cell_method = MagicMock() run_cell_method.side_effect = HttpClientException('meh') spark_controller.run_command = run_cell_method command = "-s" name = "sessions_name" line = " ".join([command, name]) cell = "cell code" result = magic.spark(line, cell) run_cell_method.assert_called_once_with(Command(cell), name) assert result is None ipython_display.send_error.assert_called_once_with( EXPECTED_ERROR_MSG.format(run_cell_method.side_effect))
def test_run_cell_command_writes_to_err(): run_cell_method = MagicMock() result_value = "" run_cell_method.return_value = (False, result_value) spark_controller.run_command = run_cell_method command = "-s" name = "sessions_name" line = " ".join([command, name]) cell = "cell code" result = magic.spark(line, cell) run_cell_method.assert_called_once_with(Command(cell), name) assert result is None ipython_display.send_error.assert_called_once_with(result_value)
def test__check_and_install_ruby(self): mock_check_rvm = MagicMock(return_value={ 'changes': {}, 'result': True }) mock_check_ruby = MagicMock(return_value={ 'changes': {}, 'result': False }) mock_install_ruby = MagicMock(return_value="") with patch.object(rvm, '_check_rvm', new=mock_check_rvm): with patch.object(rvm, '_check_ruby', new=mock_check_ruby): with patch.dict(rvm.__salt__, {'rvm.install_ruby': mock_install_ruby}): rvm._check_and_install_ruby({'changes': {}}, '1.9.3') mock_install_ruby.assert_called_once_with('1.9.3', runas=None)
def test_after_delete(self): dataset = MagicMock() action = MagicMock(return_value=dataset) plugin.plugins.toolkit.get_action = MagicMock(return_value=action) # Call the function context = {'user': MagicMock()} dataset_info = {'pkg_id': 'example-pkg-id'} self.storePublisher.after_delete(context, dataset_info) # Verifications self._store_connector_instance.delete_attached_resources.assert_called_once_with( dataset) action.assert_called_once_with(context, dataset_info) plugin.plugins.toolkit.get_action.assert_called_once_with( 'package_show')
def test_sync(self): _path = '/path' _safe_dump = MagicMock(name='safe_dump') with patch('teuthology.timer.yaml.safe_dump', _safe_dump): with patch('teuthology.timer.open', mock_open(), create=True) as _open: self.timer = timer.Timer(path=_path, sync=True) assert self.timer.path == _path assert self.timer.sync is True self.timer.mark() _open.assert_called_once_with(_path, 'w') _safe_dump.assert_called_once_with( self.timer.data, _open.return_value.__enter__.return_value, default_flow_style=False, )
def test_add_sessions_command_exception(): # Do not skip and python add_sessions_mock = MagicMock(side_effect=BadUserDataException('hehe')) spark_controller.add_session = add_sessions_mock command = "add" name = "-s name" language = "-l python" connection_string = "-u http://url.com -a sdf -p w" line = " ".join([command, name, language, connection_string]) magic.spark(line) add_sessions_mock.assert_called_once_with("name", Endpoint("http://url.com", "sdf", "w"), False, {"kind": "pyspark"}) ipython_display.send_error.assert_called_once_with(EXPECTED_ERROR_MSG .format(add_sessions_mock.side_effect))
def test_wait_for_negative_path(self): from ImageHorizonLibrary import InvalidImageException run_on_failure = MagicMock() with self.assertRaises(InvalidImageException), \ patch(self.locate, side_effect=InvalidImageException('')), \ patch.object(self.lib, '_run_on_failure', run_on_failure): start = time.time() self.lib.wait_for('notfound', timeout='1') stop = time.time() run_on_failure.assert_called_once_with() # check that timeout given as string works and it does not use # default timeout self.assertLess(stop - start, 10)
def test_export_shadow_vm(self): self.http_transferer._get_disk_url_from_lease = MagicMock() self.http_transferer._wait_for_lease = MagicMock() mock_get_vm = MagicMock() mock_lease = MagicMock() self.vim_client.get_vm_obj_in_cache = mock_get_vm mock_get_vm.return_value.ExportVm.return_value = mock_lease lease, url = self.http_transferer._export_shadow_vm() mock_get_vm.assert_called_once_with(self.http_transferer._shadow_vm_id) mock_get_vm.return_value.ExportVm.assert_called_once_with() self.http_transferer._wait_for_lease.assert_called_once_with( mock_lease) self.http_transferer._get_disk_url_from_lease.assert_called_once_with( mock_lease)
def test_emitterFor(self): """ You can get a function that takes a single argument and emits events for a particular object. """ ev1 = MagicMock() world = World(ev1) ev2 = MagicMock() world.subscribeTo('1234', ev2) emitter = world.emitterFor('1234') emitter('foo') ev1.assert_called_once_with('foo') ev2.assert_called_once_with('foo')
def test_sync(self): _path = '/path' _safe_dump = MagicMock(name='safe_dump') with patch('teuthology.timer.yaml.safe_dump', _safe_dump): with patch('teuthology.timer.file') as _file: _file.return_value = MagicMock(spec=file) self.timer = timer.Timer(path=_path, sync=True) assert self.timer.path == _path assert self.timer.sync is True self.timer.mark() _file.assert_called_once_with(_path, 'w') _safe_dump.assert_called_once_with( self.timer.data, _file.return_value.__enter__.return_value, default_flow_style=False, )
def test_run_cell_command_parses(): run_cell_method = MagicMock() result_value = "" run_cell_method.return_value = (True, result_value, MIMETYPE_TEXT_PLAIN) spark_controller.run_command = run_cell_method command = "-s" name = "sessions_name" line = " ".join([command, name]) cell = "cell code" result = magic.spark(line, cell) run_cell_method.assert_called_once_with(Command(cell), name) assert result is None ipython_display.write.assert_called_once_with(result_value)
def test_calcSIFsForSigmaAndSIF(self): an = AnalysisNodeData('node', ['K1'], 'areas') an.anSolParams = {'a': 20, 'b': 10, 'v': 0.3, 'gamma': 45, 'omega': 60} an.angles = [30, 45] aMock = MagicMock(return_value=123) with patch('anSol.calcAnSolWrapper', aMock): res = an.calcSIFsForSigmaAndSIF(100, 'K2') self.assertEqual(123, res) aMock.assert_called_once_with(sifKey='K2', majorAxis=20, minorAxis=10, v=0.3, betas=[30, 45], gamma=45, omega=60, tensileStress=100)
def test_mqtt_client_callback_triggers_provider_callback( MockMqttClient, client_callback_name, client_callback_args, provider_callback_name, provider_callback_args, ): mock_mqtt_client = MockMqttClient.return_value mqtt_provider = MQTTProvider(fake_device_id, fake_hostname, fake_username) stub_provider_callback = MagicMock() setattr(mqtt_provider, provider_callback_name, stub_provider_callback) getattr(mock_mqtt_client, client_callback_name)(*client_callback_args) stub_provider_callback.assert_called_once_with(*provider_callback_args)
def test_cache_init_creates_store_and_stats(self, CacheStats): store = MagicMock() c = Cache(store=store, ttl=100, tti=10, store_opts={ 'foo': 1, 'bar': 2, 'baz': 3 }) CacheStats.assert_called_once_with() store.assert_called_once_with(foo=1, bar=2, baz=3) self.assertEqual(c.store, store.return_value) self.assertEqual(c.stats, CacheStats.return_value)
def test_make_api_call(self): namespace = MagicMock() namespace.method = 'mock_method' tags = MagicMock() client = MagicMock() kwargs = dict(mock_key='mock_value') mock_extractor = MagicMock(return_value=kwargs) parameter_extractor_mapping = {'mock_method': mock_extractor} make_api_call(namespace, tags, client, parameter_extractor_mapping=parameter_extractor_mapping) mock_extractor.assert_called_once_with(namespace, tags) client.mock_method.assert_called_once_with(**kwargs)
def test_install_commit(self, ios_xr_cmd_templates_mock, cte_mock): # Setup exec_cmd_mock = MagicMock() cte_mock.return_value.execute_command = exec_cmd_mock # Act self._system_admin_actions.INSTALL_COMMIT_TIMEOUT = 0.1 self._system_admin_actions.install_commit() # Assert cte_mock.assert_called_once_with( self._cli_service, ios_xr_cmd_templates_mock.INSTALL_COMMIT, action_map=None, error_map=None) exec_cmd_mock.assert_called_once_with(admin=None)
def test_set_is_proxy_enabled(self, value): settings_manager = SettingsManager() set_is_proxy_enabled_mock = MagicMock() settings_manager.set_is_proxy_enabled = set_is_proxy_enabled_mock settings_proxy_enabled_resource = SettingsProxyEnabled( settings_manager) self.api.add_route(self.api_url, settings_proxy_enabled_resource) request = {'enabled': value} self.simulate_request(self.api_url, method="PUT", body=json.dumps(request)) self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT) set_is_proxy_enabled_mock.assert_called_once_with(value)
def test_redshift_connector_creation( self, mock_keyring_get_password: MagicMock, mock_user_config_dir: MagicMock) -> None: redshift_connector = RedshiftConnector() mock_user_config_dir.assert_called_once_with('pypandasql') mock_keyring_get_password.assert_called_once_with( 'pypandasql-redshift', 'test') self.assertEqual(redshift_connector.engine_name, 'redshift+psycopg2') connection_att = redshift_connector.connection_attr self.assertEqual(connection_att['host'], 'test-host') self.assertEqual(connection_att['port'], '1234') self.assertEqual(connection_att['user_name'], 'test') credentials = connection_att['credentials'] self.assertEqual(credentials.service_name, 'pypandasql-redshift') self.assertEqual(credentials.user, 'test') self.assertEqual(credentials.password, 'random-password')
def test__do_right(self, mocked_rospy): mocked_rospy.get_param.return_value = utils.get_params() receiver = CommandReceiver() mocked_forward = MagicMock() receiver._forward = mocked_forward mocked_rotate = MagicMock() receiver._rotate = mocked_rotate odom = Odometry receiver._CommandReceiver__current_odometry = odom receiver._do_right() mocked_forward.assert_not_called() mocked_rotate.assert_called_once_with(odom, -1 * 0.01, reverse=True)
def test_delay_multiple(): tc = TestClass() test = MagicMock() test2 = MagicMock() add_callback(tc, 'prop1', test) add_callback(tc, 'prop2', test2) with delay_callback(tc, 'prop1', 'prop2'): tc.prop1 = 100 tc.prop2 = 200 assert test.call_count == 0 assert test2.call_count == 0 test.assert_called_once_with(100) test2.assert_called_once_with(200)
def test_get_response_no_parameters(self): m = Method("test_description") m.set_logger_name("mname") call_func_mock = MagicMock() m.call_function = call_func_mock func = Mock(return_value={"first_out": "test"}) m.set_function(func) args_meta = Mock(spec=MapMeta) args_meta.elements = {"first": Mock()} m.set_takes(args_meta) request = MagicMock() del request.parameters # Make sure mock doesn't have `parameters` m.get_response(request) call_func_mock.assert_called_once_with(dict())
def test_validate_all_called_on_value(self): ''' When passed a scalar, passthrough validator should call validate_all on the scalar. ''' v = validators.PassthroughValidator() mock = MagicMock() # mocks are iterable .. we don't want that here mock.attach_mock(MagicMock(side_effect=TypeError), '__iter__') validate_mock = MagicMock() mock.attach_mock(validate_mock, 'validate_all') v.validate(mock) validate_mock.assert_called_once_with()
def test_live_migrate_with_recover(self): os_instance = FakeOSInstance() pvc_instance = FakePVCInstance() service = self._driver._service service.get_instance = MagicMock(return_value=pvc_instance) dest_compute_info = FakeHostStat().stat os_instance.os_instance['metadata']['powervm:defer_placement'] = \ 'false' recover_method = MagicMock() post_method = MagicMock() service.live_migrate = MagicMock(side_effect=Exception("Error")) self.assertRaises(Exception, self._driver.live_migration, None, os_instance, dest_compute_info, post_method, recover_method) recover_method.assert_called_once_with(None, os_instance, dest_compute_info, False, None)
def test_decrypt_data_key_from_list_first_try(self): mock_decrypt_data_key = MagicMock() mock_decrypt_data_key.return_value = sentinel.data_key mock_master_key_provider = MockMasterKeyProvider( provider_id=sentinel.provider_id, mock_new_master_key=sentinel.new_master_key ) mock_master_key_provider.decrypt_data_key = mock_decrypt_data_key test = mock_master_key_provider.decrypt_data_key_from_list( encrypted_data_keys=[sentinel.encrypted_data_key_a, sentinel.encrypted_data_key_b], algorithm=sentinel.algorithm, encryption_context=sentinel.encryption_context, ) mock_decrypt_data_key.assert_called_once_with( sentinel.encrypted_data_key_a, sentinel.algorithm, sentinel.encryption_context ) assert test is sentinel.data_key
def test_handle_http_request_with_string_content_and_action_set_status_content_type( ): request = mock_http_request() response = Mock(HTTPResponse) action = MagicMock() action.return_value = content = '<book>resource created</book>' response.status = 201 response.content_type = 'text/xml' resp = handle_action(action, request, response) action.assert_called_once_with(request, response) assert resp == response assert resp.status == 201 assert resp.content_type == 'text/xml' assert resp.content == content
def test_that_can_delete_file_from_bucket_and_parse_to_gcp_response( self, mock_request: mock.MagicMock ): mock_file_object = self.__mock_deleted_file_object() mock_request.return_value = mock_file_object self.provider.set_bucket(self.bucket) response = self.provider.request_delete(self.remote_file_path) mock_request.assert_called_once_with(self.remote_file_path) self.assertEqual(None, response.get("id")) self.assertEqual("bucket-testing", response.get("bucket")) self.assertEqual("gs://bucket-testing/ex1/test.txt", response.get("uri")) self.assertFalse(response.get("exists"))