Python unittest.mock() Examples
The following are 30
code examples of unittest.mock().
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
, or try the search function
.
Example #1
Source File: testmock.py From jawfish with MIT License | 8 votes |
def test_method_calls_compare_easily(self): mock = Mock() mock.something() self.assertEqual(mock.method_calls, [('something',)]) self.assertEqual(mock.method_calls, [('something', (), {})]) mock = Mock() mock.something('different') self.assertEqual(mock.method_calls, [('something', ('different',))]) self.assertEqual(mock.method_calls, [('something', ('different',), {})]) mock = Mock() mock.something(x=1) self.assertEqual(mock.method_calls, [('something', {'x': 1})]) self.assertEqual(mock.method_calls, [('something', (), {'x': 1})]) mock = Mock() mock.something('different', some='more') self.assertEqual(mock.method_calls, [ ('something', ('different',), {'some': 'more'}) ])
Example #2
Source File: testmock.py From jawfish with MIT License | 7 votes |
def test_configure_mock(self): mock = Mock(foo='bar') self.assertEqual(mock.foo, 'bar') mock = MagicMock(foo='bar') self.assertEqual(mock.foo, 'bar') kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 'foo': MagicMock()} mock = Mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) mock = Mock() mock.configure_mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock)
Example #3
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_enable_force_admins(self, enable): # Given options = DotDict({ 'retries': 1, 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = False toggle_enforce_admin(options) # Then enable.assert_called_once()
Example #4
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_disable_force_admins(self, disable): # Given options = DotDict({ 'retries': 1, 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = True toggle_enforce_admin(options) # Then disable.assert_called_once()
Example #5
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_always_disable_force_admins_when_disabled(self, disable): # Given options = DotDict({ 'retries': 1, 'enforce_admins': 'false', 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = False toggle_enforce_admin(options) # Then disable.assert_called_once()
Example #6
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_always_enable_force_admins_when_enabled(self, enable): # Given options = DotDict({ 'retries': 1, 'enforce_admins': 'true', 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = True toggle_enforce_admin(options) # Then enable.assert_called_once()
Example #7
Source File: testmock.py From jawfish with MIT License | 6 votes |
def test_assert_any_call(self): mock = Mock() mock(1, 2) mock(a=3) mock(1, b=6) mock.assert_any_call(1, 2) mock.assert_any_call(a=3) mock.assert_any_call(1, b=6) self.assertRaises( AssertionError, mock.assert_any_call ) self.assertRaises( AssertionError, mock.assert_any_call, 1, 3 ) self.assertRaises( AssertionError, mock.assert_any_call, a=4 )
Example #8
Source File: testmock.py From jawfish with MIT License | 6 votes |
def test_side_effect_setting_iterator(self): mock = Mock() mock.side_effect = iter([1, 2, 3]) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) mock.side_effect = ['a', 'b', 'c'] self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) this_iter = Iter() mock.side_effect = this_iter self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) self.assertIs(mock.side_effect, this_iter)
Example #9
Source File: testmock.py From jawfish with MIT License | 6 votes |
def test_adding_child_mock(self): for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock: mock = Klass() mock.foo = Mock() mock.foo() self.assertEqual(mock.method_calls, [call.foo()]) self.assertEqual(mock.mock_calls, [call.foo()]) mock = Klass() mock.bar = Mock(name='name') mock.bar() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) # mock with an existing _new_parent but no name mock = Klass() mock.baz = MagicMock()() mock.baz() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, [])
Example #10
Source File: testmock.py From jawfish with MIT License | 6 votes |
def test_assert_called_once_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises( AssertionError, lambda: mock.assert_called_once_with('bob', 'bar', baz=2) )
Example #11
Source File: test_cmd_unify.py From grimoirelab-sortinghat with GNU General Public License v3.0 | 6 votes |
def test_unify_no_success_no_recovery_file(self, mock_merge_unique_identities): """Test command when the recovery file does not exist, the recovery mode is active and the execution isn't ok""" mock_merge_unique_identities.side_effect = Exception with unittest.mock.patch('sortinghat.cmd.unify.RecoveryFile.location') as mock_location: mock_location.return_value = self.recovery_path self.assertFalse(os.path.exists(self.recovery_path)) with self.assertRaises(Exception): self.cmd.unify(matching='default', recovery=True) self.assertTrue(os.path.exists(self.recovery_path)) with open(self.recovery_path, 'r') as f: count_objs = 0 for line in f.readlines(): matches_obj = json.loads(line.strip("\n")) self.assertTrue(all([isinstance(m, str) for m in matches_obj['identities']])) self.assertFalse(matches_obj['processed']) count_objs += 1 self.assertEqual(count_objs, 1)
Example #12
Source File: testmock.py From jawfish with MIT License | 6 votes |
def test_from_spec(self): class Something(object): x = 3 __something__ = None def y(self): pass def test_attributes(mock): # should work mock.x mock.y mock.__something__ self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'z'", getattr, mock, 'z' ) self.assertRaisesRegex( AttributeError, "Mock object has no attribute '__foobar__'", getattr, mock, '__foobar__' ) test_attributes(Mock(spec=Something)) test_attributes(Mock(spec=Something()))
Example #13
Source File: test_cmd_unify.py From grimoirelab-sortinghat with GNU General Public License v3.0 | 6 votes |
def test_unify_no_success_no_recovery_file(self, mock_merge_unique_identities): """Test command when the recovery file does not exist, the recovery mode is active and the execution isn't ok""" mock_merge_unique_identities.side_effect = Exception with unittest.mock.patch('sortinghat.cmd.unify.RecoveryFile.location') as mock_location: mock_location.return_value = self.recovery_path self.assertFalse(os.path.exists(self.recovery_path)) with self.assertRaises(Exception): self.cmd.run('--recovery') self.assertTrue(os.path.exists(self.recovery_path)) with open(self.recovery_path, 'r') as f: count_objs = 0 for line in f.readlines(): matches_obj = json.loads(line.strip("\n")) self.assertTrue(all([isinstance(m, str) for m in matches_obj['identities']])) self.assertFalse(matches_obj['processed']) count_objs += 1 self.assertEqual(count_objs, 1)
Example #14
Source File: testmock.py From jawfish with MIT License | 6 votes |
def test_dir(self): mock = Mock() attrs = set(dir(mock)) type_attrs = set([m for m in dir(Mock) if not m.startswith('_')]) # all public attributes from the type are included self.assertEqual(set(), type_attrs - attrs) # creates these attributes mock.a, mock.b self.assertIn('a', dir(mock)) self.assertIn('b', dir(mock)) # instance attributes mock.c = mock.d = None self.assertIn('c', dir(mock)) self.assertIn('d', dir(mock)) # magic methods mock.__iter__ = lambda s: iter([]) self.assertIn('__iter__', dir(mock))
Example #15
Source File: testmock.py From jawfish with MIT License | 6 votes |
def test_spec_class(self): class X(object): pass mock = Mock(spec=X) self.assertTrue(isinstance(mock, X)) mock = Mock(spec=X()) self.assertTrue(isinstance(mock, X)) self.assertIs(mock.__class__, X) self.assertEqual(Mock().__class__.__name__, 'Mock') mock = Mock(spec_set=X) self.assertTrue(isinstance(mock, X)) mock = Mock(spec_set=X()) self.assertTrue(isinstance(mock, X))
Example #16
Source File: testpatch.py From jawfish with MIT License | 5 votes |
def test_patch_propogrates_exc_on_exit(self): class holder: exc_info = None, None, None class custom_patch(_patch): def __exit__(self, etype=None, val=None, tb=None): _patch.__exit__(self, etype, val, tb) holder.exc_info = etype, val, tb stop = __exit__ def with_custom_patch(target): getter, attribute = _get_target(target) return custom_patch( getter, attribute, DEFAULT, None, False, None, None, None, {} ) @with_custom_patch('squizz.squozz') def test(mock): raise RuntimeError self.assertRaises(RuntimeError, test) self.assertIs(holder.exc_info[0], RuntimeError) self.assertIsNotNone(holder.exc_info[1], 'exception value not propgated') self.assertIsNotNone(holder.exc_info[2], 'exception traceback not propgated')
Example #17
Source File: testpatch.py From jawfish with MIT License | 5 votes |
def test_new_callable_patch(self): patcher = patch(foo_name, new_callable=NonCallableMagicMock) m1 = patcher.start() patcher.stop() m2 = patcher.start() patcher.stop() self.assertIsNot(m1, m2) for mock in m1, m2: self.assertNotCallable(m1)
Example #18
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_adding_return_value_mock(self): for Klass in Mock, MagicMock: mock = Klass() mock.return_value = MagicMock() mock()() self.assertEqual(mock.mock_calls, [call(), call()()])
Example #19
Source File: testpatch.py From jawfish with MIT License | 5 votes |
def test_new_callable_patch_object(self): patcher = patch.object(Foo, 'f', new_callable=NonCallableMagicMock) m1 = patcher.start() patcher.stop() m2 = patcher.start() patcher.stop() self.assertIsNot(m1, m2) for mock in m1, m2: self.assertNotCallable(m1)
Example #20
Source File: testpatch.py From jawfish with MIT License | 5 votes |
def test_specs_false_instead_of_none(self): p = patch(MODNAME, spec=False, spec_set=False, autospec=False) mock = p.start() try: # no spec should have been set, so attribute access should not fail mock.does_not_exist mock.does_not_exist = 3 finally: p.stop()
Example #21
Source File: testpatch.py From jawfish with MIT License | 5 votes |
def test_autospec_name(self): patcher = patch(foo_name, autospec=True) mock = patcher.start() try: self.assertIn(" name='Foo'", repr(mock)) self.assertIn(" name='Foo.f'", repr(mock.f)) self.assertIn(" name='Foo()'", repr(mock(None))) self.assertIn(" name='Foo().f'", repr(mock(None).f)) finally: patcher.stop()
Example #22
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_side_effect_iterator(self): mock = Mock(side_effect=iter([1, 2, 3])) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) mock = MagicMock(side_effect=['a', 'b', 'c']) self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) mock = Mock(side_effect='ghi') self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i']) self.assertRaises(StopIteration, mock) class Foo(object): pass mock = MagicMock(side_effect=Foo) self.assertIsInstance(mock(), Foo) mock = Mock(side_effect=Iter()) self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock)
Example #23
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_mock_add_spec_magic_methods(self): for Klass in MagicMock, NonCallableMagicMock: mock = Klass() int(mock) mock.mock_add_spec(object) self.assertRaises(TypeError, int, mock) mock = Klass() mock['foo'] mock.__int__.return_value =4 mock.mock_add_spec(int) self.assertEqual(int(mock), 4) self.assertRaises(TypeError, lambda: mock['foo'])
Example #24
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_spec_list_subclass(self): class Sub(list): pass mock = Mock(spec=Sub(['foo'])) mock.append(3) mock.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock, 'foo')
Example #25
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_call_args_two_tuple(self): mock = Mock() mock(1, a=3) mock(2, b=4) self.assertEqual(len(mock.call_args), 2) args, kwargs = mock.call_args self.assertEqual(args, (2,)) self.assertEqual(kwargs, dict(b=4)) expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))] for expected, call_args in zip(expected_list, mock.call_args_list): self.assertEqual(len(call_args), 2) self.assertEqual(expected[0], call_args[0]) self.assertEqual(expected[1], call_args[1])
Example #26
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_arg_lists(self): mocks = [ Mock(), MagicMock(), NonCallableMock(), NonCallableMagicMock() ] def assert_attrs(mock): names = 'call_args_list', 'method_calls', 'mock_calls' for name in names: attr = getattr(mock, name) self.assertIsInstance(attr, _CallList) self.assertIsInstance(attr, list) self.assertEqual(attr, []) for mock in mocks: assert_attrs(mock) if callable(mock): mock() mock(1, 2) mock(a=3) mock.reset_mock() assert_attrs(mock) mock.foo() mock.foo.bar(1, a=3) mock.foo(1).bar().baz(3) mock.reset_mock() assert_attrs(mock)
Example #27
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_filter_dir(self): patcher = patch.object(mock, 'FILTER_DIR', False) patcher.start() try: attrs = set(dir(Mock())) type_attrs = set(dir(Mock)) # ALL attributes from the type are included self.assertEqual(set(), type_attrs - attrs) finally: patcher.stop()
Example #28
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_dir_from_spec(self): mock = Mock(spec=unittest.TestCase) testcase_attrs = set(dir(unittest.TestCase)) attrs = set(dir(mock)) # all attributes from the spec are included self.assertEqual(set(), testcase_attrs - attrs) # shadow a sys attribute mock.version = 3 self.assertEqual(dir(mock).count('version'), 1)
Example #29
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_setting_attribute_with_spec_set(self): class X(object): y = 3 mock = Mock(spec=X) mock.x = 'foo' mock = Mock(spec_set=X) def set_attr(): mock.x = 'foo' mock.y = 'foo' self.assertRaises(AttributeError, set_attr)
Example #30
Source File: testmock.py From jawfish with MIT License | 5 votes |
def test_wraps_attributes(self): class Real(object): attribute = Mock() real = Real() mock = Mock(wraps=real) self.assertEqual(mock.attribute(), real.attribute()) self.assertRaises(AttributeError, lambda: mock.fish) self.assertNotEqual(mock.attribute, real.attribute) result = mock.attribute.frog(1, 2, fish=3) Real.attribute.frog.assert_called_with(1, 2, fish=3) self.assertEqual(result, Real.attribute.frog())