Python unittest.mock.create_autospec() Examples
The following are 30
code examples of unittest.mock.create_autospec().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
unittest.mock
, or try the search function
.
Example #1
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_dsc_resolve_identifiers_none_sessionreturns( subject_context, monkeypatch, mock_session): """ unit tested: resolve_identifiers test case: - the dsc doesn't have an identifiers attribute set - neither account nor subject has identifiers - resolve_session is called to obtain a session and the session's identifiers obtained """ dsc = subject_context mock_subject = mock.create_autospec(DelegatingSubject) mock_subject.identifiers = None monkeypatch.setattr(dsc, 'identifiers', None) monkeypatch.setattr(dsc, 'subject', mock_subject) monkeypatch.setattr(mock_session, 'get_internal_attribute', lambda x: 'identifiers') result = dsc.resolve_identifiers(mock_session) assert result == 'identifiers'
Example #2
Source File: test_session.py From yosai with Apache License 2.0 | 6 votes |
def test_ds_stop(patched_delegating_session, monkeypatch): """ unit tested: stop test case: delegates the request to the MockSessionManager """ pds = patched_delegating_session mock_sm = mock.create_autospec(NativeSessionManager) monkeypatch.setattr(pds, 'session_manager', mock_sm) mock_callback = mock.MagicMock() monkeypatch.setattr(pds, 'stop_session_callback', mock_callback) pds.stop('identifiers') mock_sm.stop.assert_called_once_with(pds.session_key, 'identifiers') mock_callback.assert_called_once_with()
Example #3
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_web_subject_context_resolve_webregistry_no_reg_returns_subject_wr( web_subject_context, monkeypatch): """ - no self.web_registry exists - returns subject.web_registry attribute """ mock_subject = mock.create_autospec(WebDelegatingSubject) mock_subject.web_registry = 'mockwebregistry' monkeypatch.setattr(web_subject_context, 'subject', mock_subject) monkeypatch.setattr(web_subject_context, 'web_registry', None) result = web_subject_context.resolve_web_registry() assert result == 'mockwebregistry' # ------------------------------------------------------------------------------ # WebDelegatingSubject # ------------------------------------------------------------------------------
Example #4
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_web_yosai_get_subject_returns_subject( mock_wsc, web_yosai, monkeypatch, mock_web_registry): @staticmethod def mock_cwr(): return mock_web_registry monkeypatch.setattr(WebYosai, 'get_current_webregistry', mock_cwr) with mock.patch.object(web_yosai.security_manager, 'create_subject') as mock_cs: mock_ws = mock.create_autospec(WebDelegatingSubject) mock_ws.web_registry = 'wr' mock_cs.return_value = mock_ws result = web_yosai._get_subject() mock_wsc.assert_called_once_with(yosai=web_yosai, security_manager=web_yosai.security_manager, web_registry=mock_web_registry) mock_cs.assert_called_once_with(subject_context='wsc') assert result == mock_ws
Example #5
Source File: test_batch_job.py From marge-bot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_batch_merge_job(self, api, mocklab, **batch_merge_kwargs): project_id = mocklab.project_info['id'] merge_request_iid = mocklab.merge_request_info['iid'] merge_request = MergeRequest.fetch_by_iid(project_id, merge_request_iid, api) params = { 'api': api, 'user': marge.user.User.myself(api), 'project': marge.project.Project.fetch_by_id(project_id, api), 'repo': create_autospec(marge.git.Repo, spec_set=True), 'options': MergeJobOptions.default(), 'merge_requests': [merge_request] } params.update(batch_merge_kwargs) return BatchMergeJob(**params)
Example #6
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_requires_permission_succeeds(monkeypatch): """ This test verifies that the decorator works as expected. """ mock_wds = mock.create_autospec(WebDelegatingSubject) @staticmethod def mock_gcs(): return mock_wds monkeypatch.setattr(WebYosai, 'get_current_subject', mock_gcs) @WebYosai.requires_permission(['something:anything']) def do_this(): return 'dothis' result = do_this() assert result == 'dothis' mock_wds.check_permission.assert_called_once_with(['something:anything'], all)
Example #7
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_requires_permission_raises_one(monkeypatch): @staticmethod def mock_gcs(): m = mock.create_autospec(WebDelegatingSubject) m.check_permission.side_effect = ValueError @staticmethod def mock_cwr(): m = mock.MagicMock() m.raise_unauthorized.return_value = Exception m.raise_forbidden.return_value = Exception return m monkeypatch.setattr(WebYosai, 'get_current_subject', mock_gcs) monkeypatch.setattr(WebYosai, 'get_current_webregistry', mock_cwr) @WebYosai.requires_permission(['something_anything']) def do_this(): return 'dothis' with pytest.raises(Exception): do_this()
Example #8
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_requires_permission_raises_two(monkeypatch): mock_wds = mock.create_autospec(WebDelegatingSubject) mock_wds.check_permission.side_effect = AuthorizationException @staticmethod def mock_gcs(): return mock_wds @staticmethod def mock_cwr(): m = mock.MagicMock() m.raise_unauthorized.return_value = Exception m.raise_forbidden.return_value = Exception return m monkeypatch.setattr(WebYosai, 'get_current_subject', mock_gcs) monkeypatch.setattr(WebYosai, 'get_current_webregistry', mock_cwr) @WebYosai.requires_permission(['something_anything']) def do_this(): return 'dothis' with pytest.raises(Exception): do_this()
Example #9
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_requires_role_succeeds(monkeypatch): """ This test verifies that the decorator works as expected. """ mock_wds = mock.create_autospec(WebDelegatingSubject) @staticmethod def mock_gcs(): return mock_wds monkeypatch.setattr(WebYosai, 'get_current_subject', mock_gcs) @WebYosai.requires_role(['role1']) def do_this(): return 'dothis' result = do_this() assert result == 'dothis' mock_wds.check_role.assert_called_once_with(['role1'], all)
Example #10
Source File: base.py From ec2-api with Apache License 2.0 | 6 votes |
def mock_nova(self): # NOTE(ft): create an extra mock for Nova calls with an admin account. # Also make sure that the admin account is used only for this calls. # The special mock is needed to validate tested function to retrieve # appropriate data, as long as only calls with admin account return # some specific data. novaclient_spec = novaclient.Client('2') nova = mock.create_autospec(novaclient_spec) nova_admin = mock.create_autospec(novaclient_spec) nova_patcher = mock.patch('novaclient.client.Client') novaclient_getter = nova_patcher.start() self.addCleanup(nova_patcher.stop) novaclient_getter.side_effect = ( lambda *args, **kwargs: ( nova_admin if (kwargs.get('session') == mock.sentinel.admin_session) else nova if (kwargs.get('session') == mock.sentinel.session) else None)) return nova, nova_admin
Example #11
Source File: test_toplevel.py From arctic with GNU Lesser General Public License v2.1 | 6 votes |
def test_read(): self = create_autospec(TopLevelTickStore) tsl = TickStoreLibrary(create_autospec(TickStore), create_autospec(DateRange)) self._get_libraries.return_value = [tsl, tsl] dr = create_autospec(DateRange) with patch('pandas.concat') as concat: res = TopLevelTickStore.read(self, sentinel.symbol, dr, columns=sentinel.include_columns, include_images=sentinel.include_images) assert concat.call_args_list == [call([tsl.library.read.return_value, tsl.library.read.return_value])] assert res == concat.return_value assert tsl.library.read.call_args_list == [call(sentinel.symbol, tsl.date_range.intersection.return_value, sentinel.include_columns, include_images=sentinel.include_images), call(sentinel.symbol, tsl.date_range.intersection.return_value, sentinel.include_columns, include_images=sentinel.include_images)]
Example #12
Source File: test_toplevel.py From arctic with GNU Lesser General Public License v2.1 | 6 votes |
def test_write_pandas_data_to_right_libraries(): self = create_autospec(TopLevelTickStore, _arctic_lib=MagicMock(), _collection=MagicMock()) self._collection.find.return_value = [{'library_name': sentinel.libname1, 'start': sentinel.st1, 'end': sentinel.end1}, {'library_name': sentinel.libname2, 'start': sentinel.st2, 'end': sentinel.end2}] slice1 = range(2) slice2 = range(4) when(self._slice).called_with(sentinel.data, sentinel.st1, sentinel.end1).then(slice1) when(self._slice).called_with(sentinel.data, sentinel.st2, sentinel.end2).then(slice2) mock_lib1 = Mock() mock_lib2 = Mock() when(self._arctic_lib.arctic.__getitem__).called_with(sentinel.libname1).then(mock_lib1) when(self._arctic_lib.arctic.__getitem__).called_with(sentinel.libname2).then(mock_lib2) with patch("arctic.tickstore.toplevel.to_dt") as patch_to_dt: patch_to_dt.side_effect = [sentinel.st1, sentinel.end1, sentinel.st2, sentinel.end2] TopLevelTickStore.write(self, 'blah', sentinel.data) mock_lib1.write.assert_called_once_with('blah', slice1) mock_lib2.write.assert_called_once_with('blah', slice2)
Example #13
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_dss_merge_identity_with_session_case3( default_subject_store, monkeypatch, delegating_subject, mock_session): """ unit tested: merge_authentication_state test case: - no current_identifiers, existing_identifiers added to to_remove - subject not authenticated - existing_authc is None """ dss = default_subject_store ds = delegating_subject attrs = {'identifiers_session_key' : 'identifiers', 'authenticated_session_key': True} mock_session = mock.create_autospec(DelegatingSession) mock_session.get_internal_attributes.return_value = attrs monkeypatch.setattr(ds, 'authenticated', False) dss.merge_identity_with_session(None, ds, mock_session) to_remove = ['identifiers_session_key', 'authenticated_session_key'] mock_session.remove_internal_attributes.assert_called_once_with(to_remove) assert not mock_session.set_internal_attributes.called
Example #14
Source File: test_mgt.py From yosai with Apache License 2.0 | 6 votes |
def test_nsm_login_raises_then_succeeds(native_security_manager, monkeypatch, mock_subject): """ unit tested: login test case: authenticate_account raises an AuthenticationException, on_failed_login succeeds, and an AuthenticationException is raised up the stack """ nsm = native_security_manager mock_authc = mock.create_autospec(DefaultAuthenticator) mock_authc.authenticate_account.side_effect = AuthenticationException monkeypatch.setattr(nsm, 'authenticator', mock_authc) mock_subject.identifiers = 'identifiers' with mock.patch.object(NativeSecurityManager, 'on_failed_login') as nsm_ofl: nsm_ofl.return_value = None with pytest.raises(AuthenticationException): nsm.login(mock_subject, 'authc_token') nsm_ofl.assert_called_once_with( 'authc_token', AuthenticationException, 'subject')
Example #15
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_dss_merge_identity_with_session_case1( default_subject_store, monkeypatch, delegating_subject): """ unit tested: merge_authentication_state test case: - current_identifiers != existing_identifiers - subject authenticated - existing_authc is None """ dss = default_subject_store ds = delegating_subject attrs = {'identifiers_session_key' : 'isk', 'authenticated_session_key': None} mock_session = mock.create_autospec(DelegatingSession) mock_session.get_internal_attributes.return_value = attrs monkeypatch.setattr(ds, 'authenticated', True) dss.merge_identity_with_session('current_identifiers', ds, mock_session) to_set = [['identifiers_session_key', 'current_identifiers'], ['authenticated_session_key', True]] mock_session.set_internal_attributes.assert_called_once_with(to_set) assert not mock_session.remove_internal_attributes.called
Example #16
Source File: test_mgt.py From yosai with Apache License 2.0 | 6 votes |
def test_nsm_do_create_subject(mock_ds, native_security_manager, monkeypatch): """ unit tested: do_create_subject """ nsm = native_security_manager mock_sc = mock.create_autospec(SubjectContext) mock_sc.resolve_security_manager.return_value = 'security_manager' mock_sc.resolve_session.return_value = 'session' mock_sc.session_creation_enabled = 'session_creation_enabled' mock_sc.resolve_identifiers.return_value = 'identifiers' mock_sc.remembered = True mock_sc.resolve_authenticated.return_value = True mock_sc.resolve_host.return_value = 'host' nsm.do_create_subject(mock_sc) mock_ds.assert_called_once_with(identifiers='identifiers', remembered=True, authenticated=True, host='host', session='session', session_creation_enabled='session_creation_enabled', security_manager='security_manager')
Example #17
Source File: test_token_remover.py From bot with MIT License | 6 votes |
def test_find_token_valid_match(self, token_re, token_cls, is_valid_id, is_valid_timestamp): """The first match with a valid user ID and timestamp should be returned as a `Token`.""" matches = [ mock.create_autospec(Match, spec_set=True, instance=True), mock.create_autospec(Match, spec_set=True, instance=True), ] tokens = [ mock.create_autospec(Token, spec_set=True, instance=True), mock.create_autospec(Token, spec_set=True, instance=True), ] token_re.finditer.return_value = matches token_cls.side_effect = tokens is_valid_id.side_effect = (False, True) # The 1st match will be invalid, 2nd one valid. is_valid_timestamp.return_value = True return_value = TokenRemover.find_token_in_message(self.msg) self.assertEqual(tokens[1], return_value) token_re.finditer.assert_called_once_with(self.msg.content)
Example #18
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_dss_merge_identity_with_session_case2( default_subject_store, monkeypatch, delegating_subject, mock_session): """ unit tested: merge_authentication_state test case: - current_identifiers == existing_identifiers - subject authenticated - existing_authc is None """ dss = default_subject_store ds = delegating_subject attrs = {'identifiers_session_key' : 'current_identifiers', 'authenticated_session_key': None} mock_session = mock.create_autospec(DelegatingSession) mock_session.get_internal_attributes.return_value = attrs monkeypatch.setattr(ds, 'authenticated', True) dss.merge_identity_with_session('current_identifiers', ds, mock_session) to_set = [['authenticated_session_key', True]] mock_session.set_internal_attributes.assert_called_once_with(to_set) assert not mock_session.remove_internal_attributes.called
Example #19
Source File: test_sql_validator.py From spectacles with MIT License | 6 votes |
def test_create_and_run_keyboard_interrupt_cancels_queries(validator): validator._running_queries = [ Query( query_id="12345", lookml_ref=None, query_task_id="abc", explore_url="https://example.looker.com/x/12345", ) ] mock_create_queries = create_autospec(validator._create_queries) mock_create_queries.side_effect = KeyboardInterrupt() validator._create_queries = mock_create_queries mock_cancel_queries = create_autospec(validator._cancel_queries) validator._cancel_queries = mock_cancel_queries try: validator._create_and_run(mode="batch") except SpectaclesException: mock_cancel_queries.assert_called_once_with(query_task_ids=["abc"])
Example #20
Source File: test_mgt.py From yosai with Apache License 2.0 | 6 votes |
def test_armm_on_successful_login_isnotrememberme( mock_remember_me_manager, monkeypatch, caplog): """ unit tested: on_successful_login test case: the subject identity is forgotten and then debug output is printed """ mrmm = mock_remember_me_manager mock_token = mock.create_autospec(UsernamePasswordToken) mock_token.is_remember_me = False with mock.patch.object(MockRememberMeManager, 'forget_identity') as mrmm_fi: mrmm_fi.return_value = None mrmm.on_successful_login('subject', mock_token, 'accountid') out = caplog.text mrmm_fi.assert_called_once_with('subject') assert "AuthenticationToken did not indicate" in out
Example #21
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_get_session_withoutsessionattribute_createsnew( delegating_subject, monkeypatch, mock_session): """ unit tested: get_session test case: no session attribute, creation enabled, results in creation of a new session attribute """ ds = delegating_subject monkeypatch.setattr(ds, 'session', None) monkeypatch.setattr(ds, 'create_session_context', lambda: 'sessioncontext') mock_sm = mock.create_autospec(NativeSecurityManager) mock_sm.start.return_value = mock_session monkeypatch.setattr(ds, 'security_manager', mock_sm) result = ds.get_session() mock_sm.start.assert_called_once_with('sessioncontext') assert result == mock_session assert mock_session.stop_session_callback == ds.session_stopped
Example #22
Source File: test_subject.py From yosai with Apache License 2.0 | 6 votes |
def test_dsc_resolve_host_notexists_token(subject_context, monkeypatch): """ unit tested: resolve_host test case: no host attribute exists, so token's host is returned """ dsc = subject_context mock_token = mock.create_autospec(UsernamePasswordToken) mock_token.host = 'token_host' monkeypatch.setattr(dsc, 'host', None) monkeypatch.setattr(dsc, 'authentication_token', mock_token) result = dsc.resolve_host('session') assert result == 'token_host'
Example #23
Source File: test_subject.py From yosai with Apache License 2.0 | 5 votes |
def test_dss_merge_identity_notrunas_withoutsession( mock_dss_miws, default_subject_store, delegating_subject, monkeypatch, mock_session): """ unit tested: merge_identity test case: - current_identifiers obtained from subject.identifiers - get_session returns None """ dss = default_subject_store mock_session = mock.create_autospec(DelegatingSession) def get_session(create=True): if create: return mock_session return None mock_subject = mock.MagicMock(is_run_as=False, identifiers='subject_identifiers', get_session=get_session) dss.merge_identity(mock_subject) to_set = [['identifiers_session_key', 'subject_identifiers'], ['authenticated_session_key', True]] mock_session.set_internal_attributes.assert_called_once_with(to_set) assert not mock_dss_miws.called
Example #24
Source File: test_mgt.py From yosai with Apache License 2.0 | 5 votes |
def test_nsm_login_raises_additional(native_security_manager, monkeypatch, mock_subject): nsm = native_security_manager mock_subject.identifiers = 'identifiers' mock_authc = mock.create_autospec(DefaultAuthenticator) mock_authc.authenticate_account.side_effect = AdditionalAuthenticationRequired monkeypatch.setattr(nsm, 'authenticator', mock_authc) mock_usi = mock.MagicMock() monkeypatch.setattr(nsm, 'update_subject_identity', mock_usi) with pytest.raises(AdditionalAuthenticationRequired): nsm.login(mock_subject, 'authc_token') assert mock_usi.called
Example #25
Source File: test_session.py From yosai with Apache License 2.0 | 5 votes |
def test_ds_internal_attribute_keys(patched_delegating_session, monkeypatch): """ unit tested: internal_attribute_keys test case: delegates the request to the MockSessionManager """ pds = patched_delegating_session mock_sm = mock.create_autospec(NativeSessionManager) monkeypatch.setattr(pds, 'session_manager', mock_sm) pds.internal_attribute_keys mock_sm.get_internal_attribute_keys.assert_called_once_with(pds.session_key)
Example #26
Source File: test_session.py From yosai with Apache License 2.0 | 5 votes |
def test_ds_touch(patched_delegating_session, monkeypatch): """ unit tested: touch test case: delegates the request to the MockSessionManager """ pds = patched_delegating_session mock_sm = mock.create_autospec(NativeSessionManager) monkeypatch.setattr(pds, 'session_manager', mock_sm) pds.touch() mock_sm.touch.assert_called_once_with(pds.session_key)
Example #27
Source File: test_subject.py From yosai with Apache License 2.0 | 5 votes |
def test_ds_check_permission(mock_aacp, delegating_subject, monkeypatch): """ unit tested: check_permission test case: delegates call to security_manager """ ds = delegating_subject monkeypatch.setattr(ds, 'authenticated', True) mock_cp = mock.create_autospec(NativeSecurityManager) monkeypatch.setattr(ds.security_manager, 'check_permission', mock_cp) ds.check_permission(['arbitrary'], all) mock_aacp.assert_called_once_with() assert mock_cp.called
Example #28
Source File: test_session.py From yosai with Apache License 2.0 | 5 votes |
def test_ds_setabsolute_timeout(patched_delegating_session, monkeypatch): """ unit tested: absolute_timeout test case: delegates the request to the MockSessionManager """ pds = patched_delegating_session mock_sm = mock.create_autospec(NativeSessionManager) monkeypatch.setattr(pds, 'session_manager', mock_sm) pds.absolute_timeout = 1234 mock_sm.set_absolute_timeout.assert_called_once_with(pds.session_key, 1234)
Example #29
Source File: test_session.py From yosai with Apache License 2.0 | 5 votes |
def test_ds_setidle_timeout(patched_delegating_session, monkeypatch): """ unit tested: idle_timeout test case: delegates the request to the MockSessionManager """ pds = patched_delegating_session mock_sm = mock.create_autospec(NativeSessionManager) monkeypatch.setattr(pds, 'session_manager', mock_sm) pds.idle_timeout = 1234 mock_sm.set_idle_timeout.assert_called_once_with(pds.session_key, 1234)
Example #30
Source File: test_session_manager.py From yosai with Apache License 2.0 | 5 votes |
def test_sh_create_session(session_handler, monkeypatch): sh = session_handler session_store = mock.create_autospec(CachingSessionStore) monkeypatch.setattr(sh, 'session_store', session_store) sh.create_session('session') session_store.create.assert_called_once_with('session')