def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly") mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used") def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN)
async def async_gen_fixture(mock): try: yield mock(START) except Exception as e: mock(e) else: mock(END)
def test_main_with_shortener(): """Test usage with url shortener.""" from katcr import main, get_from_short from unittest.mock import patch, call opts = {'<SEARCH_TERM>': "foo", '--search-engines': ['Katcr'], '--interactive': False, '--open': False, '-d': False, '--shortener': ['bar'], '--disable-shortener': False, '--pages': [1]} with patch('katcr.Katcr') as mock: with patch('katcr.get_from_short') as short_mock: with patch('katcr.docopt', side_effect=(opts,)): main() mock().search.assert_called_with(opts['<SEARCH_TERM>'], 1) short_mock.assert_called_with('bar', None) class Foo: # pylint: disable=too-few-public-methods, missing-docstring text = "foo" with patch('katcr.requests.post', return_value=Foo) as mock: with patch('katcr.docopt', side_effect=(opts,)): result = list(get_from_short( "foo.com", [("1", "2"), ("3", "4")])) assert [result == [('1', '2', 'foo.com/foo'), ('3', '4', 'foo.com/foo')]] mock.assert_has_calls([call('foo.com', data={'magnet': '2'}), call('foo.com', data={'magnet': '4'})])
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()()])
def test_call(self): mock = Mock() self.assertTrue(is_instance(mock.return_value, Mock), "Default return_value should be a Mock") result = mock() self.assertEqual(mock(), result, "different result from consecutive calls") mock.reset_mock() ret_val = mock(sentinel.Arg) self.assertTrue(mock.called, "called not set") self.assertEqual(mock.call_count, 1, "call_count incoreect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), "call_args not set") self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], "call_args_list not initialised correctly") mock.return_value = sentinel.ReturnValue ret_val = mock(sentinel.Arg, key=sentinel.KeyArg) self.assertEqual(ret_val, sentinel.ReturnValue, "incorrect return value") self.assertEqual(mock.call_count, 2, "call_count incorrect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {'key': sentinel.KeyArg}), "call_args not set") self.assertEqual(mock.call_args_list, [ ((sentinel.Arg,), {}), ((sentinel.Arg,), {'key': sentinel.KeyArg}) ], "call_args_list not set")
def test_assert_has_calls(self): kalls1 = [call(1, 2), ({"a": 3},), ((3, 4),), call(b=6), ("", (1,), {"b": 6})] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in Mock(), MagicMock(): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in 1, 2, 3: these = kalls[i : i + step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises(AssertionError, mock.assert_has_calls, list(reversed(these)))
def test_wraps_calls(self): real = Mock() mock = Mock(wraps=real) self.assertEqual(mock(), real()) real.reset_mock() mock(1, 2, fish=3) real.assert_called_with(1, 2, fish=3)
def test_reset_mock(self): parent = Mock() spec = ['something'] mock = Mock(name='child', parent=parent, spec=spec) mock(sentinel.Something, something=sentinel.SomethingElse) something = mock.something mock.something() mock.side_effect = sentinel.SideEffect return_value = mock.return_value return_value() mock.reset_mock() self.assertEqual(mock._mock_name, 'child', 'name incorrectly reset') self.assertEqual(mock._mock_parent, parent, 'parent incorrectly reset') self.assertEqual(mock._mock_methods, spec, 'methods incorrectly reset') self.assertFalse(mock.called, 'called not reset') self.assertEqual(mock.call_count, 0, 'call_count not reset') self.assertEqual(mock.call_args, None, 'call_args not reset') self.assertEqual(mock.call_args_list, [], 'call_args_list not reset') self.assertEqual(mock.method_calls, [], 'method_calls not initialised correctly: %r != %r' % (mock.method_calls, [])) self.assertEqual(mock.mock_calls, []) self.assertEqual(mock.side_effect, sentinel.SideEffect, 'side_effect incorrectly reset') self.assertEqual(mock.return_value, return_value, 'return_value incorrectly reset') self.assertFalse(return_value.called, 'return value mock not reset') self.assertEqual(mock._mock_children, {'something': something}, 'children reset incorrectly') self.assertEqual(mock.something, something, 'children incorrectly cleared') self.assertFalse(mock.something.called, 'child not reset')
def test_reset_mock(self): parent = Mock() spec = ["something"] mock = Mock(name="child", parent=parent, spec=spec) mock(sentinel.Something, something=sentinel.SomethingElse) something = mock.something mock.something() mock.side_effect = sentinel.SideEffect return_value = mock.return_value return_value() mock.reset_mock() self.assertEqual(mock._mock_name, "child", "name incorrectly reset") self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset") self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset") self.assertFalse(mock.called, "called not reset") self.assertEqual(mock.call_count, 0, "call_count not reset") self.assertEqual(mock.call_args, None, "call_args not reset") self.assertEqual(mock.call_args_list, [], "call_args_list not reset") self.assertEqual( mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, []) ) self.assertEqual(mock.mock_calls, []) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset") self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset") self.assertFalse(return_value.called, "return value mock not reset") self.assertEqual(mock._mock_children, {"something": something}, "children reset incorrectly") self.assertEqual(mock.something, something, "children incorrectly cleared") self.assertFalse(mock.something.called, "child not reset")
def test_assert_called_with(self): mock = Mock() mock() mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a='fish', b='nothing') mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException('Boom!')) try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass self.fail('java exception not raised') mock.assert_called_with(1, 2, fish=3)
def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock('one') mock.assert_called_with('one') self.assertRaises(TypeError, mock, 'one', 'two')
def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock("one") mock.assert_called_with("one") self.assertRaises(TypeError, mock, "one", "two")
def test_main(): """Test argument parsing and calling.""" from katcr import main from unittest.mock import patch opts = {'<SEARCH_TERM>': "foo", '--search-engines': ['Katcr'], '--interactive': False, '--open': False, '-d': False, '--disable-shortener': True, '--pages': [1]} with patch('katcr.Katcr') as mock: with patch('katcr.docopt', side_effect=(opts,)): main() mock().search.assert_called_with(opts['<SEARCH_TERM>'], 1)
def test_repr(self): mock = Mock(name='foo') self.assertIn('foo', repr(mock)) self.assertIn("'%s'" % id(mock), repr(mock)) mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')] for (mock, name) in mocks: self.assertIn('%s.bar' % name, repr(mock.bar)) self.assertIn('%s.foo()' % name, repr(mock.foo())) self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing)) self.assertIn('%s()' % name, repr(mock())) self.assertIn('%s()()' % name, repr(mock()())) self.assertIn('%s()().foo.bar.baz().bing' % name, repr(mock()().foo.bar.baz().bing))
def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1,2, fish=3)
def test_assert_called_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a="fish", b="nothing") mock.assert_called_with(1, 2, 3, a="fish", b="nothing")
def test_repr(self): mock = Mock(name="foo") self.assertIn("foo", repr(mock)) self.assertIn("'%s'" % id(mock), repr(mock)) mocks = [(Mock(), "mock"), (Mock(name="bar"), "bar")] for mock, name in mocks: self.assertIn("%s.bar" % name, repr(mock.bar)) self.assertIn("%s.foo()" % name, repr(mock.foo())) self.assertIn("%s.foo().bing" % name, repr(mock.foo().bing)) self.assertIn("%s()" % name, repr(mock())) self.assertIn("%s()()" % name, repr(mock()())) self.assertIn("%s()().foo.bar.baz().bing" % name, repr(mock()().foo.bar.baz().bing))
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])
def test_assert_called_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError)
def test_call_args_comparison(self): mock = Mock() mock() mock(sentinel.Arg) mock(kw=sentinel.Kwarg) mock(sentinel.Arg, kw=sentinel.Kwarg) self.assertEqual(mock.call_args_list, [(), ((sentinel.Arg,),), ({'kw': sentinel.Kwarg},), ((sentinel.Arg,), {'kw': sentinel.Kwarg})]) self.assertEqual(mock.call_args, ((sentinel.Arg,), {'kw': sentinel.Kwarg}))
def test_subclassing(self): class Subclass(Mock): pass mock = Subclass() self.assertIsInstance(mock.foo, Subclass) self.assertIsInstance(mock(), Subclass) class Subclass(Mock): def _get_child_mock(self, **kwargs): return Mock(**kwargs) mock = Subclass() self.assertNotIsInstance(mock.foo, Subclass) self.assertNotIsInstance(mock(), Subclass)
def test_wraps_call_with_nondefault_return_value(self): real = Mock() mock = Mock(wraps=real) mock.return_value = 3 self.assertEqual(mock(), 3) self.assertFalse(real.called)
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)
def setUp(self): """ Function that runs before each test. The main role of this function is to prepare all mocks that are used in main, setup fake file and devices etc. """ mock = lambda m: patch(m).start() self.open = mock('builtins.open') self.print = mock('builtins.print') self.open_conn = mock('cvra_bootloader.utils.open_connection') self.conn = Mock() self.open_conn.return_value = self.conn self.flash = mock('cvra_bootloader.bootloader_flash.flash_binary') self.check = mock('cvra_bootloader.bootloader_flash.check_binary') self.run = mock('cvra_bootloader.bootloader_flash.run_application') self.check_online_boards = mock('cvra_bootloader.bootloader_flash.check_online_boards') self.check_online_boards.side_effect = lambda f, b: set([1, 2, 3]) # Prepare binary file argument self.binary_data = bytes([0] * 10) self.open.return_value = BytesIO(self.binary_data) # Flash checking results self.check.return_value = [1, 2, 3] # all boards are ok # Populate command line arguments sys.argv = "test.py -b test.bin -a 0x1000 -p /dev/ttyUSB0 -c dummy 1 2 3".split()
def test_subclassing(self): class Subclass(Mock): __qualname__ = 'MockTest.test_subclassing.<locals>.Subclass' mock = Subclass() self.assertIsInstance(mock.foo, Subclass) self.assertIsInstance(mock(), Subclass) class Subclass(Mock): __qualname__ = 'MockTest.test_subclassing.<locals>.Subclass' def _get_child_mock(self, **kwargs): return Mock(**kwargs) mock = Subclass() self.assertNotIsInstance(mock.foo, Subclass) self.assertNotIsInstance(mock(), Subclass)
def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [call(1, 2), ({'a': 3},), ((3, 4),), ((), {'a': 3}), ('', (1, 2)), ('', {'a': 3}), ('', (1, 2), {}), ('', (), {'a': 3})] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in (call(1, '2'), call(b=3), call(), 3, None, 'foo'): self.assertRaises(AssertionError, mock.assert_has_calls, [kall], any_order=True) kall_lists = [[call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)]] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [[call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)]] for kall_list in kall_lists: self.assertRaises(AssertionError, mock.assert_has_calls, kall_list, any_order=True)
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)
def test_search_call(): """Test main search call.""" from katcr import main from unittest.mock import patch opts = {'<SEARCH_TERM>': "foo", '--search-engines': ['Katcr'], '--interactive': False, '--open': False, '--disable-shortener': True, "--shortener": "http://foo.com", '--pages': [1]} args = opts['<SEARCH_TERM>'], 1 with patch('katcr.Terminal') as tmock: with patch('katcr.Katcr') as mock: tmock().width = 50 mock().search.side_effect = ((('foo', 'bar', "baz"),),) with patch('katcr.docopt', side_effect=(opts,)): main() mock().search.assert_called_with(*args)
def test_assert_called_once_with(self): mock = Mock() mock() mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises(AssertionError, lambda : mock.assert_called_once_with('bob', 'bar', baz=2))
def test_docket_parsing(self, mock): paths = mock() for path in paths: with open(path) as f: data = json.loads(f.read()) for case in data: answer = re.sub("–", "-", case["answer"]) answer = re.sub("—", "-", answer) answer = re.sub("–", "-", answer) print(answer) self.assertEqual(get_tax_docket_numbers(case["text"]), answer) print("Success ✓")
def test_assert_called_once_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_once_with(1, 2, 3) mock.assert_called_once_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_once_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) # Mock called more than once => always fails mock(4, 5, 6) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, 2, 3) self.assertRaises(AssertionError, mock.assert_called_once_with, 4, 5, 6)
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)
def test_assert_called_once_with(self): mock = Mock() mock() mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises(AssertionError, lambda : mock. assert_called_once_with('bob', 'bar', baz=2))
def test_call_args_comparison(self): mock = Mock() mock() mock(sentinel.Arg) mock(kw=sentinel.Kwarg) mock(sentinel.Arg, kw=sentinel.Kwarg) self.assertEqual(mock.call_args_list, [ (), ((sentinel.Arg,),), ({"kw": sentinel.Kwarg},), ((sentinel.Arg,), {"kw": sentinel.Kwarg}) ]) self.assertEqual(mock.call_args, ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
def test_assert_has_calls_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock(10, 11, c=12) calls = [ ('', (1, 2, 3), {}), ('', (4, 5, 6), { 'd': 7 }), ((10, 11, 12), {}), ] mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) # Reversed order calls = list(reversed(calls)) with self.assertRaises(AssertionError): mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True)
def test_reset_mock(self): parent = Mock() spec = ["something"] mock = Mock(name="child", parent=parent, spec=spec) mock(sentinel.Something, something=sentinel.SomethingElse) something = mock.something mock.something() mock.side_effect = sentinel.SideEffect return_value = mock.return_value return_value() mock.reset_mock() self.assertEqual(mock._mock_name, "child", "name incorrectly reset") self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset") self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset") self.assertFalse(mock.called, "called not reset") self.assertEqual(mock.call_count, 0, "call_count not reset") self.assertEqual(mock.call_args, None, "call_args not reset") self.assertEqual(mock.call_args_list, [], "call_args_list not reset") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])) self.assertEqual(mock.mock_calls, []) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset") self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset") self.assertFalse(return_value.called, "return value mock not reset") self.assertEqual(mock._mock_children, {'something': something}, "children reset incorrectly") self.assertEqual(mock.something, something, "children incorrectly cleared") self.assertFalse(mock.something.called, "child not reset")
def test_assert_has_calls(self): kalls1 = [ call(1, 2), ({'a': 3},), ((3, 4),), call(b=6), ('', (1,), {'b': 6}), ] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in Mock(), MagicMock(): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in 1, 2, 3: these = kalls[i:i+step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises( AssertionError, mock.assert_has_calls, list(reversed(these)) )
def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], 'side effect not used correctly') mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, 'side effect in constructor not used') def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN)
def test_method_call(self): #case1: mock method, specify return value real = ProductionClass() real.method_sub = unittest.mock.Mock() real.method_sub.return_value = 3 self.assertEqual(real.method(), 3) self.assertTrue(real.method_sub.called) #case2: trace all calls real.method_sub.assert_called_once_with(1, 2, 3) self.assertEqual(real.method_sub.mock_calls, [unittest.mock.call.method_sub(1, 2, 3)]) self.assertEqual(real.method_sub.call_args_list, [unittest.mock.call(1, 2, 3)]) self.assertEqual(real.method_sub.call_args, unittest.mock.call(1, 2, 3)) self.assertEqual(real.method_sub.call_args[0], (1, 2, 3)) #case3: trace different args mock = unittest.mock.Mock() mock(1, 2, 3, k="4") self.assertEqual(mock.call_args[0], (1, 2, 3)) self.assertEqual(mock.call_args[1], {"k": "4"}) #case4: mock method, by another func vals = {(1, 2, 3): 1, (2, 3, 4): 2} def side_effect(*args): return vals[args] real.method_sub = unittest.mock.Mock(side_effect=side_effect) self.assertEqual(real.method(), 1) #case5: mock for Method Calls on an Object mock = unittest.mock.Mock() real.closer(mock) mock.close.assert_called_with()
def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [call(1, 2), ({'a': 3},), ((3, 4),), ((), {'a': 3}), ('', ( 1, 2)), ('', {'a': 3}), ('', (1, 2), {}), ('', (), {'a': 3})] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in (call(1, '2'), call(b=3), call(), 3, None, 'foo'): self.assertRaises(AssertionError, mock.assert_has_calls, [kall], any_order=True) kall_lists = [[call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [ call(b=6), call(b=6)]] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [[call(b=6), call(b=6), call(b=6)], [call(1, 2), call( 1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call( 3, 4), call(b=6), call(1, 2), call(b=6)]] for kall_list in kall_lists: self.assertRaises(AssertionError, mock.assert_has_calls, kall_list, any_order=True)
def test_call_args_comparison(self): mock = Mock() mock() mock(sentinel.Arg) mock(kw=sentinel.Kwarg) mock(sentinel.Arg, kw=sentinel.Kwarg) self.assertEqual(mock.call_args_list, [ (), ((sentinel.Arg,),), ({"kw": sentinel.Kwarg},), ((sentinel.Arg,), {"kw": sentinel.Kwarg}) ]) self.assertEqual(mock.call_args, ((sentinel.Arg,), {"kw": sentinel.Kwarg})) # Comparing call_args to a long sequence should not raise # an exception. See issue 24857. self.assertFalse(mock.call_args == "a long sequence")
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)
def test_broadcast_block_retry( fx_session: scoped_session, fx_user: User, limit: int, blocks: int, expected: int ): for i in range(blocks): block = Block.create(fx_user, []) url = 'http://test.neko' now = datetime.datetime.utcnow() node = Node(url=url, last_connected_at=now) fx_session.add(node) fx_session.flush() patch = unittest.mock.patch('nekoyume.broadcast.BROADCAST_LIMIT', limit) with mock() as m, patch: m.register_uri('POST', 'http://test.neko/blocks', [ { 'json': { 'result': 'failed', 'block_id': 0, 'mesage': "new block isn't our next block." }, 'status_code': 403 }, { 'json': { 'result': 'success', }, 'status_code': 200 } ]) multicast( serialized=block.serialize( use_bencode=False, include_suffix=True, include_moves=True, include_hash=True ), broadcast=broadcast_block, ) assert m.call_count == expected assert node.last_connected_at > now
def test_autospec_side_effect(self): results = [1, 2, 3] def effect(): return results.pop() def f(): pass mock = create_autospec(f) mock.side_effect = [1, 2, 3] self.assertEqual([mock(), mock(), mock()], [1, 2, 3], 'side effect not used correctly in create_autospec') results = [1, 2, 3] mock = create_autospec(f) mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], 'callable side effect not used correctly')
def test_autospec_side_effect(self): # Test for issue17826 results = [1, 2, 3] def effect(): return results.pop() def f(): pass mock = create_autospec(f) mock.side_effect = [1, 2, 3] self.assertEqual([mock(), mock(), mock()], [1, 2, 3], "side effect not used correctly in create_autospec") # Test where side effect is a callable results = [1, 2, 3] mock = create_autospec(f) mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "callable side effect not used correctly")
def test_cons_iterator(self): #case1: use 'side_effect' construct iterator mock = unittest.mock.Mock(side_effect=[4, 5, 6]) self.assertEqual(mock(), 4) self.assertEqual(mock(), 5) self.assertEqual(mock(), 6)
self.left = self.left.remove(data) elif data > self.data: if self.right: self.right = self.right.remove(data) if data == self.data: if self.right is None and self.left is None: return None elif self.right is None: return self.left elif self.left is None: return self.right else: remplaso = self.left.maximo(data) self.data = remplaso self.right = self.right.remove(remplaso) return self N = int(mock()) data = int(mock().split()[1]) tree = Node(data, 1) for i in range(1, N): info = mock().split() if info[0] == "i": tree.add(int(info[1])) if info[0] == 'd': tree.remove(int(info[1]))
def test_path_row_column(self): if not hasattr(unittest, 'mock'): return # Shortcuts. originalIsFile = test_buffer_file.os.path.isfile decode = test_buffer_file.pathRowColumn Mock = unittest.mock.MagicMock mock = Mock(side_effect=[False, True]) self.assertEqual(False, mock("a")) self.assertEqual(True, mock("a")) with self.assertRaises(StopIteration): self.assertEqual(True, mock("a")) os.path.isfile = Mock(side_effect=[False, True]) self.assertEqual(False, os.path.isfile("a")) self.assertEqual(True, os.path.isfile("a")) with self.assertRaises(StopIteration): self.assertEqual(True, os.path.isfile("a")) os.path.isfile = Mock(side_effect=[False, True]) self.assertEqual(decode(u"", u""), (u"", None, None)) self.assertEqual(decode(u"/", u""), (u"/", None, None)) os.path.isfile = Mock(side_effect=[False, False]) self.assertEqual(decode(u"//apple", u"/stuff"), (u"/stuff/apple", None, None)) os.path.isfile = Mock(side_effect=[False, False]) self.assertEqual(decode(u"//apple", None), (u"//apple", None, None)) os.path.isfile = Mock(side_effect=[False, False, False]) self.assertEqual(decode(u":5", u""), (u"", 4, None)) os.path.isfile = Mock(side_effect=[False, False, False]) self.assertEqual(decode(u"/:5", u""), (u"/", 4, None)) os.path.isfile = Mock(side_effect=[False, False, False]) self.assertEqual(decode(u"//apple:5", u"/stuff"), (u"/stuff/apple", 4, None)) os.path.isfile = Mock(side_effect=[False, False, False]) self.assertEqual(decode(u"//apple:5", None), (u"//apple", 4, None)) os.path.isfile = Mock(side_effect=[False, True]) self.assertEqual(decode(u"//apple", u"/stuff"), (u"/stuff/apple", None, None)) os.path.isfile = Mock(side_effect=[False, True]) self.assertEqual(decode(u"//apple", None), (u"apple", None, None)) os.path.isfile = Mock(side_effect=[False, True]) self.assertEqual(decode(u":5", u""), (u"", 4, None)) os.path.isfile = Mock(side_effect=[False, True]) self.assertEqual(decode(u"/:5", u""), (u"/", 4, None)) os.path.isfile = Mock(side_effect=[False, True]) self.assertEqual(decode(u"//apple:5", u"/stuff"), (u"/stuff/apple", 4, None)) os.path.isfile = Mock(side_effect=[False, True, True]) self.assertEqual(decode(u"//apple:5", None), (u"apple", 4, None)) os.path.isfile = Mock(side_effect=[False, True, True]) self.assertEqual(decode(u"//apple:5:", None), (u"apple", 4, None)) os.path.isfile = Mock(side_effect=[False, True, True]) self.assertEqual(decode(u"//apple:5:9", None), (u"apple", 4, 8)) os.path.isfile = Mock(side_effect=[False, True, True]) self.assertEqual(decode(u"//apple:5:9:", None), (u"apple", 4, 8)) os.path.isfile = Mock(side_effect=[False, True, True]) self.assertEqual(decode(u"apple:banana", None), (u"apple:banana", None, None)) os.path.isfile = Mock(side_effect=[False, True, True]) self.assertEqual(decode(u"//apple:banana:cat:", None), (u"apple:banana:cat:", None, None)) os.path.isfile = originalIsFile
def sub(): mock()
def sub(): # pragma: no cover mock()
def setUp(self): mock = lambda m: patch(m).start() self.progressbar = mock('progressbar.ProgressBar') self.print = mock('builtins.print')
def call_request(url): mock(url) return mock
def fake_request_getter(mock): return mock()
def coroutine_mock(self, mock, *args, **kwargs): return mock(*args, **kwargs)
def wrapper(self, *args, **kwargs): mock(*args, **kwargs) return method(self, *args, **kwargs)
def mock_coroutine(self, mock, *args, **kwargs): return mock(*args, **kwargs)
def test_side_effect_iterator_default(self): mock = Mock(return_value=2) mock.side_effect = iter([1, DEFAULT]) self.assertEqual([mock(), mock()], [1, 2])
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)
def test_mock_calls(self): mock = MagicMock() # need to do this because MagicMock.mock_calls used to just return # a MagicMock which also returned a MagicMock when __eq__ was called self.assertIs(mock.mock_calls == [], True) mock = MagicMock() mock() expected = [('', (), {})] self.assertEqual(mock.mock_calls, expected) mock.foo() expected.append(call.foo()) self.assertEqual(mock.mock_calls, expected) # intermediate mock_calls work too self.assertEqual(mock.foo.mock_calls, [('', (), {})]) mock = MagicMock() mock().foo(1, 2, 3, a=4, b=5) expected = [('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.return_value.foo.mock_calls, [('', (1, 2, 3), dict(a=4, b=5))]) self.assertEqual(mock.return_value.mock_calls, [('foo', (1, 2, 3), dict(a=4, b=5))]) mock = MagicMock() mock().foo.bar().baz() expected = [('', (), {}), ('().foo.bar', (), {}), ('().foo.bar().baz', (), {})] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock().mock_calls, call.foo.bar().baz().call_list()) for kwargs in dict(), dict(name='bar'): mock = MagicMock(**kwargs) int(mock.foo) expected = [('foo.__int__', (), {})] self.assertEqual(mock.mock_calls, expected) mock = MagicMock(**kwargs) mock.a()() expected = [('a', (), {}), ('a()', (), {})] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.a().mock_calls, [call()]) mock = MagicMock(**kwargs) mock(1)(2)(3) self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).call_list()) self.assertEqual(mock()().mock_calls, call(3).call_list()) mock = MagicMock(**kwargs) mock(1)(2)(3).a.b.c(4) self.assertEqual(mock.mock_calls, call(1)(2)(3).a.b.c(4).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).a.b.c(4).call_list()) self.assertEqual(mock()().mock_calls, call(3).a.b.c(4).call_list()) mock = MagicMock(**kwargs) int(mock().foo.bar().baz()) last_call = ('().foo.bar().baz().__int__', (), {}) self.assertEqual(mock.mock_calls[-1], last_call) self.assertEqual(mock().mock_calls, call.foo.bar().baz().__int__().call_list()) self.assertEqual(mock().foo.bar().mock_calls, call.baz().__int__().call_list()) self.assertEqual(mock().foo.bar().baz.mock_calls, call().__int__().call_list())