python/mock-1.0.0/tests/testhelpers.py

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

     1 # Copyright (C) 2007-2012 Michael Foord & the mock team
     2 # E-mail: fuzzyman AT voidspace DOT org DOT uk
     3 # http://www.voidspace.org.uk/python/mock/
     5 from tests.support import unittest2, inPy3k
     7 from mock import (
     8     call, _Call, create_autospec, MagicMock,
     9     Mock, ANY, _CallList, patch, PropertyMock
    10 )
    12 from datetime import datetime
    14 class SomeClass(object):
    15     def one(self, a, b):
    16         pass
    17     def two(self):
    18         pass
    19     def three(self, a=None):
    20         pass
    24 class AnyTest(unittest2.TestCase):
    26     def test_any(self):
    27         self.assertEqual(ANY, object())
    29         mock = Mock()
    30         mock(ANY)
    31         mock.assert_called_with(ANY)
    33         mock = Mock()
    34         mock(foo=ANY)
    35         mock.assert_called_with(foo=ANY)
    37     def test_repr(self):
    38         self.assertEqual(repr(ANY), '<ANY>')
    39         self.assertEqual(str(ANY), '<ANY>')
    42     def test_any_and_datetime(self):
    43         mock = Mock()
    44         mock(datetime.now(), foo=datetime.now())
    46         mock.assert_called_with(ANY, foo=ANY)
    49     def test_any_mock_calls_comparison_order(self):
    50         mock = Mock()
    51         d = datetime.now()
    52         class Foo(object):
    53             def __eq__(self, other):
    54                 return False
    55             def __ne__(self, other):
    56                 return True
    58         for d in datetime.now(), Foo():
    59             mock.reset_mock()
    61             mock(d, foo=d, bar=d)
    62             mock.method(d, zinga=d, alpha=d)
    63             mock().method(a1=d, z99=d)
    65             expected = [
    66                 call(ANY, foo=ANY, bar=ANY),
    67                 call.method(ANY, zinga=ANY, alpha=ANY),
    68                 call(), call().method(a1=ANY, z99=ANY)
    69             ]
    70             self.assertEqual(expected, mock.mock_calls)
    71             self.assertEqual(mock.mock_calls, expected)
    75 class CallTest(unittest2.TestCase):
    77     def test_call_with_call(self):
    78         kall = _Call()
    79         self.assertEqual(kall, _Call())
    80         self.assertEqual(kall, _Call(('',)))
    81         self.assertEqual(kall, _Call(((),)))
    82         self.assertEqual(kall, _Call(({},)))
    83         self.assertEqual(kall, _Call(('', ())))
    84         self.assertEqual(kall, _Call(('', {})))
    85         self.assertEqual(kall, _Call(('', (), {})))
    86         self.assertEqual(kall, _Call(('foo',)))
    87         self.assertEqual(kall, _Call(('bar', ())))
    88         self.assertEqual(kall, _Call(('baz', {})))
    89         self.assertEqual(kall, _Call(('spam', (), {})))
    91         kall = _Call(((1, 2, 3),))
    92         self.assertEqual(kall, _Call(((1, 2, 3),)))
    93         self.assertEqual(kall, _Call(('', (1, 2, 3))))
    94         self.assertEqual(kall, _Call(((1, 2, 3), {})))
    95         self.assertEqual(kall, _Call(('', (1, 2, 3), {})))
    97         kall = _Call(((1, 2, 4),))
    98         self.assertNotEqual(kall, _Call(('', (1, 2, 3))))
    99         self.assertNotEqual(kall, _Call(('', (1, 2, 3), {})))
   101         kall = _Call(('foo', (1, 2, 4),))
   102         self.assertNotEqual(kall, _Call(('', (1, 2, 4))))
   103         self.assertNotEqual(kall, _Call(('', (1, 2, 4), {})))
   104         self.assertNotEqual(kall, _Call(('bar', (1, 2, 4))))
   105         self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {})))
   107         kall = _Call(({'a': 3},))
   108         self.assertEqual(kall, _Call(('', (), {'a': 3})))
   109         self.assertEqual(kall, _Call(('', {'a': 3})))
   110         self.assertEqual(kall, _Call(((), {'a': 3})))
   111         self.assertEqual(kall, _Call(({'a': 3},)))
   114     def test_empty__Call(self):
   115         args = _Call()
   117         self.assertEqual(args, ())
   118         self.assertEqual(args, ('foo',))
   119         self.assertEqual(args, ((),))
   120         self.assertEqual(args, ('foo', ()))
   121         self.assertEqual(args, ('foo',(), {}))
   122         self.assertEqual(args, ('foo', {}))
   123         self.assertEqual(args, ({},))
   126     def test_named_empty_call(self):
   127         args = _Call(('foo', (), {}))
   129         self.assertEqual(args, ('foo',))
   130         self.assertEqual(args, ('foo', ()))
   131         self.assertEqual(args, ('foo',(), {}))
   132         self.assertEqual(args, ('foo', {}))
   134         self.assertNotEqual(args, ((),))
   135         self.assertNotEqual(args, ())
   136         self.assertNotEqual(args, ({},))
   137         self.assertNotEqual(args, ('bar',))
   138         self.assertNotEqual(args, ('bar', ()))
   139         self.assertNotEqual(args, ('bar', {}))
   142     def test_call_with_args(self):
   143         args = _Call(((1, 2, 3), {}))
   145         self.assertEqual(args, ((1, 2, 3),))
   146         self.assertEqual(args, ('foo', (1, 2, 3)))
   147         self.assertEqual(args, ('foo', (1, 2, 3), {}))
   148         self.assertEqual(args, ((1, 2, 3), {}))
   151     def test_named_call_with_args(self):
   152         args = _Call(('foo', (1, 2, 3), {}))
   154         self.assertEqual(args, ('foo', (1, 2, 3)))
   155         self.assertEqual(args, ('foo', (1, 2, 3), {}))
   157         self.assertNotEqual(args, ((1, 2, 3),))
   158         self.assertNotEqual(args, ((1, 2, 3), {}))
   161     def test_call_with_kwargs(self):
   162         args = _Call(((), dict(a=3, b=4)))
   164         self.assertEqual(args, (dict(a=3, b=4),))
   165         self.assertEqual(args, ('foo', dict(a=3, b=4)))
   166         self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
   167         self.assertEqual(args, ((), dict(a=3, b=4)))
   170     def test_named_call_with_kwargs(self):
   171         args = _Call(('foo', (), dict(a=3, b=4)))
   173         self.assertEqual(args, ('foo', dict(a=3, b=4)))
   174         self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
   176         self.assertNotEqual(args, (dict(a=3, b=4),))
   177         self.assertNotEqual(args, ((), dict(a=3, b=4)))
   180     def test_call_with_args_call_empty_name(self):
   181         args = _Call(((1, 2, 3), {}))
   182         self.assertEqual(args, call(1, 2, 3))
   183         self.assertEqual(call(1, 2, 3), args)
   184         self.assertTrue(call(1, 2, 3) in [args])
   187     def test_call_ne(self):
   188         self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2))
   189         self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3))
   190         self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3))
   193     def test_call_non_tuples(self):
   194         kall = _Call(((1, 2, 3),))
   195         for value in 1, None, self, int:
   196             self.assertNotEqual(kall, value)
   197             self.assertFalse(kall == value)
   200     def test_repr(self):
   201         self.assertEqual(repr(_Call()), 'call()')
   202         self.assertEqual(repr(_Call(('foo',))), 'call.foo()')
   204         self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))),
   205                          "call(1, 2, 3, a='b')")
   206         self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))),
   207                          "call.bar(1, 2, 3, a='b')")
   209         self.assertEqual(repr(call), 'call')
   210         self.assertEqual(str(call), 'call')
   212         self.assertEqual(repr(call()), 'call()')
   213         self.assertEqual(repr(call(1)), 'call(1)')
   214         self.assertEqual(repr(call(zz='thing')), "call(zz='thing')")
   216         self.assertEqual(repr(call().foo), 'call().foo')
   217         self.assertEqual(repr(call(1).foo.bar(a=3).bing),
   218                          'call().foo.bar().bing')
   219         self.assertEqual(
   220             repr(call().foo(1, 2, a=3)),
   221             "call().foo(1, 2, a=3)"
   222         )
   223         self.assertEqual(repr(call()()), "call()()")
   224         self.assertEqual(repr(call(1)(2)), "call()(2)")
   225         self.assertEqual(
   226             repr(call()().bar().baz.beep(1)),
   227             "call()().bar().baz.beep(1)"
   228         )
   231     def test_call(self):
   232         self.assertEqual(call(), ('', (), {}))
   233         self.assertEqual(call('foo', 'bar', one=3, two=4),
   234                          ('', ('foo', 'bar'), {'one': 3, 'two': 4}))
   236         mock = Mock()
   237         mock(1, 2, 3)
   238         mock(a=3, b=6)
   239         self.assertEqual(mock.call_args_list,
   240                          [call(1, 2, 3), call(a=3, b=6)])
   242     def test_attribute_call(self):
   243         self.assertEqual(call.foo(1), ('foo', (1,), {}))
   244         self.assertEqual(call.bar.baz(fish='eggs'),
   245                          ('bar.baz', (), {'fish': 'eggs'}))
   247         mock = Mock()
   248         mock.foo(1, 2 ,3)
   249         mock.bar.baz(a=3, b=6)
   250         self.assertEqual(mock.method_calls,
   251                          [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)])
   254     def test_extended_call(self):
   255         result = call(1).foo(2).bar(3, a=4)
   256         self.assertEqual(result, ('().foo().bar', (3,), dict(a=4)))
   258         mock = MagicMock()
   259         mock(1, 2, a=3, b=4)
   260         self.assertEqual(mock.call_args, call(1, 2, a=3, b=4))
   261         self.assertNotEqual(mock.call_args, call(1, 2, 3))
   263         self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)])
   264         self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)])
   266         mock = MagicMock()
   267         mock.foo(1).bar()().baz.beep(a=6)
   269         last_call = call.foo(1).bar()().baz.beep(a=6)
   270         self.assertEqual(mock.mock_calls[-1], last_call)
   271         self.assertEqual(mock.mock_calls, last_call.call_list())
   274     def test_call_list(self):
   275         mock = MagicMock()
   276         mock(1)
   277         self.assertEqual(call(1).call_list(), mock.mock_calls)
   279         mock = MagicMock()
   280         mock(1).method(2)
   281         self.assertEqual(call(1).method(2).call_list(),
   282                          mock.mock_calls)
   284         mock = MagicMock()
   285         mock(1).method(2)(3)
   286         self.assertEqual(call(1).method(2)(3).call_list(),
   287                          mock.mock_calls)
   289         mock = MagicMock()
   290         int(mock(1).method(2)(3).foo.bar.baz(4)(5))
   291         kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__()
   292         self.assertEqual(kall.call_list(), mock.mock_calls)
   295     def test_call_any(self):
   296         self.assertEqual(call, ANY)
   298         m = MagicMock()
   299         int(m)
   300         self.assertEqual(m.mock_calls, [ANY])
   301         self.assertEqual([ANY], m.mock_calls)
   304     def test_two_args_call(self):
   305         args = _Call(((1, 2), {'a': 3}), two=True)
   306         self.assertEqual(len(args), 2)
   307         self.assertEqual(args[0], (1, 2))
   308         self.assertEqual(args[1], {'a': 3})
   310         other_args = _Call(((1, 2), {'a': 3}))
   311         self.assertEqual(args, other_args)
   314 class SpecSignatureTest(unittest2.TestCase):
   316     def _check_someclass_mock(self, mock):
   317         self.assertRaises(AttributeError, getattr, mock, 'foo')
   318         mock.one(1, 2)
   319         mock.one.assert_called_with(1, 2)
   320         self.assertRaises(AssertionError,
   321                           mock.one.assert_called_with, 3, 4)
   322         self.assertRaises(TypeError, mock.one, 1)
   324         mock.two()
   325         mock.two.assert_called_with()
   326         self.assertRaises(AssertionError,
   327                           mock.two.assert_called_with, 3)
   328         self.assertRaises(TypeError, mock.two, 1)
   330         mock.three()
   331         mock.three.assert_called_with()
   332         self.assertRaises(AssertionError,
   333                           mock.three.assert_called_with, 3)
   334         self.assertRaises(TypeError, mock.three, 3, 2)
   336         mock.three(1)
   337         mock.three.assert_called_with(1)
   339         mock.three(a=1)
   340         mock.three.assert_called_with(a=1)
   343     def test_basic(self):
   344         for spec in (SomeClass, SomeClass()):
   345             mock = create_autospec(spec)
   346             self._check_someclass_mock(mock)
   349     def test_create_autospec_return_value(self):
   350         def f():
   351             pass
   352         mock = create_autospec(f, return_value='foo')
   353         self.assertEqual(mock(), 'foo')
   355         class Foo(object):
   356             pass
   358         mock = create_autospec(Foo, return_value='foo')
   359         self.assertEqual(mock(), 'foo')
   362     def test_autospec_reset_mock(self):
   363         m = create_autospec(int)
   364         int(m)
   365         m.reset_mock()
   366         self.assertEqual(m.__int__.call_count, 0)
   369     def test_mocking_unbound_methods(self):
   370         class Foo(object):
   371             def foo(self, foo):
   372                 pass
   373         p = patch.object(Foo, 'foo')
   374         mock_foo = p.start()
   375         Foo().foo(1)
   377         mock_foo.assert_called_with(1)
   380     @unittest2.expectedFailure
   381     def test_create_autospec_unbound_methods(self):
   382         # see issue 128
   383         class Foo(object):
   384             def foo(self):
   385                 pass
   387         klass = create_autospec(Foo)
   388         instance = klass()
   389         self.assertRaises(TypeError, instance.foo, 1)
   391         # Note: no type checking on the "self" parameter
   392         klass.foo(1)
   393         klass.foo.assert_called_with(1)
   394         self.assertRaises(TypeError, klass.foo)
   397     def test_create_autospec_keyword_arguments(self):
   398         class Foo(object):
   399             a = 3
   400         m = create_autospec(Foo, a='3')
   401         self.assertEqual(m.a, '3')
   403     @unittest2.skipUnless(inPy3k, "Keyword only arguments Python 3 specific")
   404     def test_create_autospec_keyword_only_arguments(self):
   405         func_def = "def foo(a, *, b=None):\n    pass\n"
   406         namespace = {}
   407         exec (func_def, namespace)
   408         foo = namespace['foo']
   410         m = create_autospec(foo)
   411         m(1)
   412         m.assert_called_with(1)
   413         self.assertRaises(TypeError, m, 1, 2)
   415         m(2, b=3)
   416         m.assert_called_with(2, b=3)
   418     def test_function_as_instance_attribute(self):
   419         obj = SomeClass()
   420         def f(a):
   421             pass
   422         obj.f = f
   424         mock = create_autospec(obj)
   425         mock.f('bing')
   426         mock.f.assert_called_with('bing')
   429     def test_spec_as_list(self):
   430         # because spec as a list of strings in the mock constructor means
   431         # something very different we treat a list instance as the type.
   432         mock = create_autospec([])
   433         mock.append('foo')
   434         mock.append.assert_called_with('foo')
   436         self.assertRaises(AttributeError, getattr, mock, 'foo')
   438         class Foo(object):
   439             foo = []
   441         mock = create_autospec(Foo)
   442         mock.foo.append(3)
   443         mock.foo.append.assert_called_with(3)
   444         self.assertRaises(AttributeError, getattr, mock.foo, 'foo')
   447     def test_attributes(self):
   448         class Sub(SomeClass):
   449             attr = SomeClass()
   451         sub_mock = create_autospec(Sub)
   453         for mock in (sub_mock, sub_mock.attr):
   454             self._check_someclass_mock(mock)
   457     def test_builtin_functions_types(self):
   458         # we could replace builtin functions / methods with a function
   459         # with *args / **kwargs signature. Using the builtin method type
   460         # as a spec seems to work fairly well though.
   461         class BuiltinSubclass(list):
   462             def bar(self, arg):
   463                 pass
   464             sorted = sorted
   465             attr = {}
   467         mock = create_autospec(BuiltinSubclass)
   468         mock.append(3)
   469         mock.append.assert_called_with(3)
   470         self.assertRaises(AttributeError, getattr, mock.append, 'foo')
   472         mock.bar('foo')
   473         mock.bar.assert_called_with('foo')
   474         self.assertRaises(TypeError, mock.bar, 'foo', 'bar')
   475         self.assertRaises(AttributeError, getattr, mock.bar, 'foo')
   477         mock.sorted([1, 2])
   478         mock.sorted.assert_called_with([1, 2])
   479         self.assertRaises(AttributeError, getattr, mock.sorted, 'foo')
   481         mock.attr.pop(3)
   482         mock.attr.pop.assert_called_with(3)
   483         self.assertRaises(AttributeError, getattr, mock.attr, 'foo')
   486     def test_method_calls(self):
   487         class Sub(SomeClass):
   488             attr = SomeClass()
   490         mock = create_autospec(Sub)
   491         mock.one(1, 2)
   492         mock.two()
   493         mock.three(3)
   495         expected = [call.one(1, 2), call.two(), call.three(3)]
   496         self.assertEqual(mock.method_calls, expected)
   498         mock.attr.one(1, 2)
   499         mock.attr.two()
   500         mock.attr.three(3)
   502         expected.extend(
   503             [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)]
   504         )
   505         self.assertEqual(mock.method_calls, expected)
   508     def test_magic_methods(self):
   509         class BuiltinSubclass(list):
   510             attr = {}
   512         mock = create_autospec(BuiltinSubclass)
   513         self.assertEqual(list(mock), [])
   514         self.assertRaises(TypeError, int, mock)
   515         self.assertRaises(TypeError, int, mock.attr)
   516         self.assertEqual(list(mock), [])
   518         self.assertIsInstance(mock['foo'], MagicMock)
   519         self.assertIsInstance(mock.attr['foo'], MagicMock)
   522     def test_spec_set(self):
   523         class Sub(SomeClass):
   524             attr = SomeClass()
   526         for spec in (Sub, Sub()):
   527             mock = create_autospec(spec, spec_set=True)
   528             self._check_someclass_mock(mock)
   530             self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar')
   531             self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar')
   534     def test_descriptors(self):
   535         class Foo(object):
   536             @classmethod
   537             def f(cls, a, b):
   538                 pass
   539             @staticmethod
   540             def g(a, b):
   541                 pass
   543         class Bar(Foo):
   544             pass
   546         class Baz(SomeClass, Bar):
   547             pass
   549         for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()):
   550             mock = create_autospec(spec)
   551             mock.f(1, 2)
   552             mock.f.assert_called_once_with(1, 2)
   554             mock.g(3, 4)
   555             mock.g.assert_called_once_with(3, 4)
   558     @unittest2.skipIf(inPy3k, "No old style classes in Python 3")
   559     def test_old_style_classes(self):
   560         class Foo:
   561             def f(self, a, b):
   562                 pass
   564         class Bar(Foo):
   565             g = Foo()
   567         for spec in (Foo, Foo(), Bar, Bar()):
   568             mock = create_autospec(spec)
   569             mock.f(1, 2)
   570             mock.f.assert_called_once_with(1, 2)
   572             self.assertRaises(AttributeError, getattr, mock, 'foo')
   573             self.assertRaises(AttributeError, getattr, mock.f, 'foo')
   575         mock.g.f(1, 2)
   576         mock.g.f.assert_called_once_with(1, 2)
   577         self.assertRaises(AttributeError, getattr, mock.g, 'foo')
   580     def test_recursive(self):
   581         class A(object):
   582             def a(self):
   583                 pass
   584             foo = 'foo bar baz'
   585             bar = foo
   587         A.B = A
   588         mock = create_autospec(A)
   590         mock()
   591         self.assertFalse(mock.B.called)
   593         mock.a()
   594         mock.B.a()
   595         self.assertEqual(mock.method_calls, [call.a(), call.B.a()])
   597         self.assertIs(A.foo, A.bar)
   598         self.assertIsNot(mock.foo, mock.bar)
   599         mock.foo.lower()
   600         self.assertRaises(AssertionError, mock.bar.lower.assert_called_with)
   603     def test_spec_inheritance_for_classes(self):
   604         class Foo(object):
   605             def a(self):
   606                 pass
   607             class Bar(object):
   608                 def f(self):
   609                     pass
   611         class_mock = create_autospec(Foo)
   613         self.assertIsNot(class_mock, class_mock())
   615         for this_mock in class_mock, class_mock():
   616             this_mock.a()
   617             this_mock.a.assert_called_with()
   618             self.assertRaises(TypeError, this_mock.a, 'foo')
   619             self.assertRaises(AttributeError, getattr, this_mock, 'b')
   621         instance_mock = create_autospec(Foo())
   622         instance_mock.a()
   623         instance_mock.a.assert_called_with()
   624         self.assertRaises(TypeError, instance_mock.a, 'foo')
   625         self.assertRaises(AttributeError, getattr, instance_mock, 'b')
   627         # The return value isn't isn't callable
   628         self.assertRaises(TypeError, instance_mock)
   630         instance_mock.Bar.f()
   631         instance_mock.Bar.f.assert_called_with()
   632         self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
   634         instance_mock.Bar().f()
   635         instance_mock.Bar().f.assert_called_with()
   636         self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
   639     def test_inherit(self):
   640         class Foo(object):
   641             a = 3
   643         Foo.Foo = Foo
   645         # class
   646         mock = create_autospec(Foo)
   647         instance = mock()
   648         self.assertRaises(AttributeError, getattr, instance, 'b')
   650         attr_instance = mock.Foo()
   651         self.assertRaises(AttributeError, getattr, attr_instance, 'b')
   653         # instance
   654         mock = create_autospec(Foo())
   655         self.assertRaises(AttributeError, getattr, mock, 'b')
   656         self.assertRaises(TypeError, mock)
   658         # attribute instance
   659         call_result = mock.Foo()
   660         self.assertRaises(AttributeError, getattr, call_result, 'b')
   663     def test_builtins(self):
   664         # used to fail with infinite recursion
   665         create_autospec(1)
   667         create_autospec(int)
   668         create_autospec('foo')
   669         create_autospec(str)
   670         create_autospec({})
   671         create_autospec(dict)
   672         create_autospec([])
   673         create_autospec(list)
   674         create_autospec(set())
   675         create_autospec(set)
   676         create_autospec(1.0)
   677         create_autospec(float)
   678         create_autospec(1j)
   679         create_autospec(complex)
   680         create_autospec(False)
   681         create_autospec(True)
   684     def test_function(self):
   685         def f(a, b):
   686             pass
   688         mock = create_autospec(f)
   689         self.assertRaises(TypeError, mock)
   690         mock(1, 2)
   691         mock.assert_called_with(1, 2)
   693         f.f = f
   694         mock = create_autospec(f)
   695         self.assertRaises(TypeError, mock.f)
   696         mock.f(3, 4)
   697         mock.f.assert_called_with(3, 4)
   700     def test_skip_attributeerrors(self):
   701         class Raiser(object):
   702             def __get__(self, obj, type=None):
   703                 if obj is None:
   704                     raise AttributeError('Can only be accessed via an instance')
   706         class RaiserClass(object):
   707             raiser = Raiser()
   709             @staticmethod
   710             def existing(a, b):
   711                 return a + b
   713         s = create_autospec(RaiserClass)
   714         self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
   715         s.existing(1, 2)
   716         self.assertRaises(AttributeError, lambda: s.nonexisting)
   718         # check we can fetch the raiser attribute and it has no spec
   719         obj = s.raiser
   720         obj.foo, obj.bar
   723     def test_signature_class(self):
   724         class Foo(object):
   725             def __init__(self, a, b=3):
   726                 pass
   728         mock = create_autospec(Foo)
   730         self.assertRaises(TypeError, mock)
   731         mock(1)
   732         mock.assert_called_once_with(1)
   734         mock(4, 5)
   735         mock.assert_called_with(4, 5)
   738     @unittest2.skipIf(inPy3k, 'no old style classes in Python 3')
   739     def test_signature_old_style_class(self):
   740         class Foo:
   741             def __init__(self, a, b=3):
   742                 pass
   744         mock = create_autospec(Foo)
   746         self.assertRaises(TypeError, mock)
   747         mock(1)
   748         mock.assert_called_once_with(1)
   750         mock(4, 5)
   751         mock.assert_called_with(4, 5)
   754     def test_class_with_no_init(self):
   755         # this used to raise an exception
   756         # due to trying to get a signature from object.__init__
   757         class Foo(object):
   758             pass
   759         create_autospec(Foo)
   762     @unittest2.skipIf(inPy3k, 'no old style classes in Python 3')
   763     def test_old_style_class_with_no_init(self):
   764         # this used to raise an exception
   765         # due to Foo.__init__ raising an AttributeError
   766         class Foo:
   767             pass
   768         create_autospec(Foo)
   771     def test_signature_callable(self):
   772         class Callable(object):
   773             def __init__(self):
   774                 pass
   775             def __call__(self, a):
   776                 pass
   778         mock = create_autospec(Callable)
   779         mock()
   780         mock.assert_called_once_with()
   781         self.assertRaises(TypeError, mock, 'a')
   783         instance = mock()
   784         self.assertRaises(TypeError, instance)
   785         instance(a='a')
   786         instance.assert_called_once_with(a='a')
   787         instance('a')
   788         instance.assert_called_with('a')
   790         mock = create_autospec(Callable())
   791         mock(a='a')
   792         mock.assert_called_once_with(a='a')
   793         self.assertRaises(TypeError, mock)
   794         mock('a')
   795         mock.assert_called_with('a')
   798     def test_signature_noncallable(self):
   799         class NonCallable(object):
   800             def __init__(self):
   801                 pass
   803         mock = create_autospec(NonCallable)
   804         instance = mock()
   805         mock.assert_called_once_with()
   806         self.assertRaises(TypeError, mock, 'a')
   807         self.assertRaises(TypeError, instance)
   808         self.assertRaises(TypeError, instance, 'a')
   810         mock = create_autospec(NonCallable())
   811         self.assertRaises(TypeError, mock)
   812         self.assertRaises(TypeError, mock, 'a')
   815     def test_create_autospec_none(self):
   816         class Foo(object):
   817             bar = None
   819         mock = create_autospec(Foo)
   820         none = mock.bar
   821         self.assertNotIsInstance(none, type(None))
   823         none.foo()
   824         none.foo.assert_called_once_with()
   827     def test_autospec_functions_with_self_in_odd_place(self):
   828         class Foo(object):
   829             def f(a, self):
   830                 pass
   832         a = create_autospec(Foo)
   833         a.f(self=10)
   834         a.f.assert_called_with(self=10)
   837     def test_autospec_property(self):
   838         class Foo(object):
   839             @property
   840             def foo(self):
   841                 return 3
   843         foo = create_autospec(Foo)
   844         mock_property = foo.foo
   846         # no spec on properties
   847         self.assertTrue(isinstance(mock_property, MagicMock))
   848         mock_property(1, 2, 3)
   849         mock_property.abc(4, 5, 6)
   850         mock_property.assert_called_once_with(1, 2, 3)
   851         mock_property.abc.assert_called_once_with(4, 5, 6)
   854     def test_autospec_slots(self):
   855         class Foo(object):
   856             __slots__ = ['a']
   858         foo = create_autospec(Foo)
   859         mock_slot = foo.a
   861         # no spec on slots
   862         mock_slot(1, 2, 3)
   863         mock_slot.abc(4, 5, 6)
   864         mock_slot.assert_called_once_with(1, 2, 3)
   865         mock_slot.abc.assert_called_once_with(4, 5, 6)
   868 class TestCallList(unittest2.TestCase):
   870     def test_args_list_contains_call_list(self):
   871         mock = Mock()
   872         self.assertIsInstance(mock.call_args_list, _CallList)
   874         mock(1, 2)
   875         mock(a=3)
   876         mock(3, 4)
   877         mock(b=6)
   879         for kall in call(1, 2), call(a=3), call(3, 4), call(b=6):
   880             self.assertTrue(kall in mock.call_args_list)
   882         calls = [call(a=3), call(3, 4)]
   883         self.assertTrue(calls in mock.call_args_list)
   884         calls = [call(1, 2), call(a=3)]
   885         self.assertTrue(calls in mock.call_args_list)
   886         calls = [call(3, 4), call(b=6)]
   887         self.assertTrue(calls in mock.call_args_list)
   888         calls = [call(3, 4)]
   889         self.assertTrue(calls in mock.call_args_list)
   891         self.assertFalse(call('fish') in mock.call_args_list)
   892         self.assertFalse([call('fish')] in mock.call_args_list)
   895     def test_call_list_str(self):
   896         mock = Mock()
   897         mock(1, 2)
   898         mock.foo(a=3)
   899         mock.foo.bar().baz('fish', cat='dog')
   901         expected = (
   902             "[call(1, 2),\n"
   903             " call.foo(a=3),\n"
   904             " call.foo.bar(),\n"
   905             " call.foo.bar().baz('fish', cat='dog')]"
   906         )
   907         self.assertEqual(str(mock.mock_calls), expected)
   910     def test_propertymock(self):
   911         p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock)
   912         mock = p.start()
   913         try:
   914             SomeClass.one
   915             mock.assert_called_once_with()
   917             s = SomeClass()
   918             s.one
   919             mock.assert_called_with()
   920             self.assertEqual(mock.mock_calls, [call(), call()])
   922             s.one = 3
   923             self.assertEqual(mock.mock_calls, [call(), call(), call(3)])
   924         finally:
   925             p.stop()
   928     def test_propertymock_returnvalue(self):
   929         m = MagicMock()
   930         p = PropertyMock()
   931         type(m).foo = p
   933         returned = m.foo
   934         p.assert_called_once_with()
   935         self.assertIsInstance(returned, MagicMock)
   936         self.assertNotIsInstance(returned, PropertyMock)
   939 if __name__ == '__main__':
   940     unittest2.main()

mercurial