python (3.12.0)

(root)/
lib/
python3.12/
test/
test_unittest/
testmock/
testhelpers.py
       1  import inspect
       2  import time
       3  import types
       4  import unittest
       5  
       6  from unittest.mock import (
       7      call, _Call, create_autospec, MagicMock,
       8      Mock, ANY, _CallList, patch, PropertyMock, _callable
       9  )
      10  
      11  from datetime import datetime
      12  from functools import partial
      13  
      14  class ESC[4;38;5;81mSomeClass(ESC[4;38;5;149mobject):
      15      def one(self, a, b): pass
      16      def two(self): pass
      17      def three(self, a=None): pass
      18  
      19  
      20  
      21  class ESC[4;38;5;81mAnyTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
      22  
      23      def test_any(self):
      24          self.assertEqual(ANY, object())
      25  
      26          mock = Mock()
      27          mock(ANY)
      28          mock.assert_called_with(ANY)
      29  
      30          mock = Mock()
      31          mock(foo=ANY)
      32          mock.assert_called_with(foo=ANY)
      33  
      34      def test_repr(self):
      35          self.assertEqual(repr(ANY), '<ANY>')
      36          self.assertEqual(str(ANY), '<ANY>')
      37  
      38  
      39      def test_any_and_datetime(self):
      40          mock = Mock()
      41          mock(datetime.now(), foo=datetime.now())
      42  
      43          mock.assert_called_with(ANY, foo=ANY)
      44  
      45  
      46      def test_any_mock_calls_comparison_order(self):
      47          mock = Mock()
      48          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
      49              def __eq__(self, other): pass
      50              def __ne__(self, other): pass
      51  
      52          for d in datetime.now(), Foo():
      53              mock.reset_mock()
      54  
      55              mock(d, foo=d, bar=d)
      56              mock.method(d, zinga=d, alpha=d)
      57              mock().method(a1=d, z99=d)
      58  
      59              expected = [
      60                  call(ANY, foo=ANY, bar=ANY),
      61                  call.method(ANY, zinga=ANY, alpha=ANY),
      62                  call(), call().method(a1=ANY, z99=ANY)
      63              ]
      64              self.assertEqual(expected, mock.mock_calls)
      65              self.assertEqual(mock.mock_calls, expected)
      66  
      67      def test_any_no_spec(self):
      68          # This is a regression test for bpo-37555
      69          class ESC[4;38;5;81mFoo:
      70              def __eq__(self, other): pass
      71  
      72          mock = Mock()
      73          mock(Foo(), 1)
      74          mock.assert_has_calls([call(ANY, 1)])
      75          mock.assert_called_with(ANY, 1)
      76          mock.assert_any_call(ANY, 1)
      77  
      78      def test_any_and_spec_set(self):
      79          # This is a regression test for bpo-37555
      80          class ESC[4;38;5;81mFoo:
      81              def __eq__(self, other): pass
      82  
      83          mock = Mock(spec=Foo)
      84  
      85          mock(Foo(), 1)
      86          mock.assert_has_calls([call(ANY, 1)])
      87          mock.assert_called_with(ANY, 1)
      88          mock.assert_any_call(ANY, 1)
      89  
      90  class ESC[4;38;5;81mCallTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
      91  
      92      def test_call_with_call(self):
      93          kall = _Call()
      94          self.assertEqual(kall, _Call())
      95          self.assertEqual(kall, _Call(('',)))
      96          self.assertEqual(kall, _Call(((),)))
      97          self.assertEqual(kall, _Call(({},)))
      98          self.assertEqual(kall, _Call(('', ())))
      99          self.assertEqual(kall, _Call(('', {})))
     100          self.assertEqual(kall, _Call(('', (), {})))
     101          self.assertEqual(kall, _Call(('foo',)))
     102          self.assertEqual(kall, _Call(('bar', ())))
     103          self.assertEqual(kall, _Call(('baz', {})))
     104          self.assertEqual(kall, _Call(('spam', (), {})))
     105  
     106          kall = _Call(((1, 2, 3),))
     107          self.assertEqual(kall, _Call(((1, 2, 3),)))
     108          self.assertEqual(kall, _Call(('', (1, 2, 3))))
     109          self.assertEqual(kall, _Call(((1, 2, 3), {})))
     110          self.assertEqual(kall, _Call(('', (1, 2, 3), {})))
     111  
     112          kall = _Call(((1, 2, 4),))
     113          self.assertNotEqual(kall, _Call(('', (1, 2, 3))))
     114          self.assertNotEqual(kall, _Call(('', (1, 2, 3), {})))
     115  
     116          kall = _Call(('foo', (1, 2, 4),))
     117          self.assertNotEqual(kall, _Call(('', (1, 2, 4))))
     118          self.assertNotEqual(kall, _Call(('', (1, 2, 4), {})))
     119          self.assertNotEqual(kall, _Call(('bar', (1, 2, 4))))
     120          self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {})))
     121  
     122          kall = _Call(({'a': 3},))
     123          self.assertEqual(kall, _Call(('', (), {'a': 3})))
     124          self.assertEqual(kall, _Call(('', {'a': 3})))
     125          self.assertEqual(kall, _Call(((), {'a': 3})))
     126          self.assertEqual(kall, _Call(({'a': 3},)))
     127  
     128  
     129      def test_empty__Call(self):
     130          args = _Call()
     131  
     132          self.assertEqual(args, ())
     133          self.assertEqual(args, ('foo',))
     134          self.assertEqual(args, ((),))
     135          self.assertEqual(args, ('foo', ()))
     136          self.assertEqual(args, ('foo',(), {}))
     137          self.assertEqual(args, ('foo', {}))
     138          self.assertEqual(args, ({},))
     139  
     140  
     141      def test_named_empty_call(self):
     142          args = _Call(('foo', (), {}))
     143  
     144          self.assertEqual(args, ('foo',))
     145          self.assertEqual(args, ('foo', ()))
     146          self.assertEqual(args, ('foo',(), {}))
     147          self.assertEqual(args, ('foo', {}))
     148  
     149          self.assertNotEqual(args, ((),))
     150          self.assertNotEqual(args, ())
     151          self.assertNotEqual(args, ({},))
     152          self.assertNotEqual(args, ('bar',))
     153          self.assertNotEqual(args, ('bar', ()))
     154          self.assertNotEqual(args, ('bar', {}))
     155  
     156  
     157      def test_call_with_args(self):
     158          args = _Call(((1, 2, 3), {}))
     159  
     160          self.assertEqual(args, ((1, 2, 3),))
     161          self.assertEqual(args, ('foo', (1, 2, 3)))
     162          self.assertEqual(args, ('foo', (1, 2, 3), {}))
     163          self.assertEqual(args, ((1, 2, 3), {}))
     164          self.assertEqual(args.args, (1, 2, 3))
     165          self.assertEqual(args.kwargs, {})
     166  
     167  
     168      def test_named_call_with_args(self):
     169          args = _Call(('foo', (1, 2, 3), {}))
     170  
     171          self.assertEqual(args, ('foo', (1, 2, 3)))
     172          self.assertEqual(args, ('foo', (1, 2, 3), {}))
     173          self.assertEqual(args.args, (1, 2, 3))
     174          self.assertEqual(args.kwargs, {})
     175  
     176          self.assertNotEqual(args, ((1, 2, 3),))
     177          self.assertNotEqual(args, ((1, 2, 3), {}))
     178  
     179  
     180      def test_call_with_kwargs(self):
     181          args = _Call(((), dict(a=3, b=4)))
     182  
     183          self.assertEqual(args, (dict(a=3, b=4),))
     184          self.assertEqual(args, ('foo', dict(a=3, b=4)))
     185          self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
     186          self.assertEqual(args, ((), dict(a=3, b=4)))
     187          self.assertEqual(args.args, ())
     188          self.assertEqual(args.kwargs, dict(a=3, b=4))
     189  
     190  
     191      def test_named_call_with_kwargs(self):
     192          args = _Call(('foo', (), dict(a=3, b=4)))
     193  
     194          self.assertEqual(args, ('foo', dict(a=3, b=4)))
     195          self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
     196          self.assertEqual(args.args, ())
     197          self.assertEqual(args.kwargs, dict(a=3, b=4))
     198  
     199          self.assertNotEqual(args, (dict(a=3, b=4),))
     200          self.assertNotEqual(args, ((), dict(a=3, b=4)))
     201  
     202  
     203      def test_call_with_args_call_empty_name(self):
     204          args = _Call(((1, 2, 3), {}))
     205  
     206          self.assertEqual(args, call(1, 2, 3))
     207          self.assertEqual(call(1, 2, 3), args)
     208          self.assertIn(call(1, 2, 3), [args])
     209  
     210  
     211      def test_call_ne(self):
     212          self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2))
     213          self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3))
     214          self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3))
     215  
     216  
     217      def test_call_non_tuples(self):
     218          kall = _Call(((1, 2, 3),))
     219          for value in 1, None, self, int:
     220              self.assertNotEqual(kall, value)
     221              self.assertFalse(kall == value)
     222  
     223  
     224      def test_repr(self):
     225          self.assertEqual(repr(_Call()), 'call()')
     226          self.assertEqual(repr(_Call(('foo',))), 'call.foo()')
     227  
     228          self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))),
     229                           "call(1, 2, 3, a='b')")
     230          self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))),
     231                           "call.bar(1, 2, 3, a='b')")
     232  
     233          self.assertEqual(repr(call), 'call')
     234          self.assertEqual(str(call), 'call')
     235  
     236          self.assertEqual(repr(call()), 'call()')
     237          self.assertEqual(repr(call(1)), 'call(1)')
     238          self.assertEqual(repr(call(zz='thing')), "call(zz='thing')")
     239  
     240          self.assertEqual(repr(call().foo), 'call().foo')
     241          self.assertEqual(repr(call(1).foo.bar(a=3).bing),
     242                           'call().foo.bar().bing')
     243          self.assertEqual(
     244              repr(call().foo(1, 2, a=3)),
     245              "call().foo(1, 2, a=3)"
     246          )
     247          self.assertEqual(repr(call()()), "call()()")
     248          self.assertEqual(repr(call(1)(2)), "call()(2)")
     249          self.assertEqual(
     250              repr(call()().bar().baz.beep(1)),
     251              "call()().bar().baz.beep(1)"
     252          )
     253  
     254  
     255      def test_call(self):
     256          self.assertEqual(call(), ('', (), {}))
     257          self.assertEqual(call('foo', 'bar', one=3, two=4),
     258                           ('', ('foo', 'bar'), {'one': 3, 'two': 4}))
     259  
     260          mock = Mock()
     261          mock(1, 2, 3)
     262          mock(a=3, b=6)
     263          self.assertEqual(mock.call_args_list,
     264                           [call(1, 2, 3), call(a=3, b=6)])
     265  
     266      def test_attribute_call(self):
     267          self.assertEqual(call.foo(1), ('foo', (1,), {}))
     268          self.assertEqual(call.bar.baz(fish='eggs'),
     269                           ('bar.baz', (), {'fish': 'eggs'}))
     270  
     271          mock = Mock()
     272          mock.foo(1, 2 ,3)
     273          mock.bar.baz(a=3, b=6)
     274          self.assertEqual(mock.method_calls,
     275                           [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)])
     276  
     277  
     278      def test_extended_call(self):
     279          result = call(1).foo(2).bar(3, a=4)
     280          self.assertEqual(result, ('().foo().bar', (3,), dict(a=4)))
     281  
     282          mock = MagicMock()
     283          mock(1, 2, a=3, b=4)
     284          self.assertEqual(mock.call_args, call(1, 2, a=3, b=4))
     285          self.assertNotEqual(mock.call_args, call(1, 2, 3))
     286  
     287          self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)])
     288          self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)])
     289  
     290          mock = MagicMock()
     291          mock.foo(1).bar()().baz.beep(a=6)
     292  
     293          last_call = call.foo(1).bar()().baz.beep(a=6)
     294          self.assertEqual(mock.mock_calls[-1], last_call)
     295          self.assertEqual(mock.mock_calls, last_call.call_list())
     296  
     297  
     298      def test_extended_not_equal(self):
     299          a = call(x=1).foo
     300          b = call(x=2).foo
     301          self.assertEqual(a, a)
     302          self.assertEqual(b, b)
     303          self.assertNotEqual(a, b)
     304  
     305  
     306      def test_nested_calls_not_equal(self):
     307          a = call(x=1).foo().bar
     308          b = call(x=2).foo().bar
     309          self.assertEqual(a, a)
     310          self.assertEqual(b, b)
     311          self.assertNotEqual(a, b)
     312  
     313  
     314      def test_call_list(self):
     315          mock = MagicMock()
     316          mock(1)
     317          self.assertEqual(call(1).call_list(), mock.mock_calls)
     318  
     319          mock = MagicMock()
     320          mock(1).method(2)
     321          self.assertEqual(call(1).method(2).call_list(),
     322                           mock.mock_calls)
     323  
     324          mock = MagicMock()
     325          mock(1).method(2)(3)
     326          self.assertEqual(call(1).method(2)(3).call_list(),
     327                           mock.mock_calls)
     328  
     329          mock = MagicMock()
     330          int(mock(1).method(2)(3).foo.bar.baz(4)(5))
     331          kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__()
     332          self.assertEqual(kall.call_list(), mock.mock_calls)
     333  
     334  
     335      def test_call_any(self):
     336          self.assertEqual(call, ANY)
     337  
     338          m = MagicMock()
     339          int(m)
     340          self.assertEqual(m.mock_calls, [ANY])
     341          self.assertEqual([ANY], m.mock_calls)
     342  
     343  
     344      def test_two_args_call(self):
     345          args = _Call(((1, 2), {'a': 3}), two=True)
     346          self.assertEqual(len(args), 2)
     347          self.assertEqual(args[0], (1, 2))
     348          self.assertEqual(args[1], {'a': 3})
     349  
     350          other_args = _Call(((1, 2), {'a': 3}))
     351          self.assertEqual(args, other_args)
     352  
     353      def test_call_with_name(self):
     354          self.assertEqual(_Call((), 'foo')[0], 'foo')
     355          self.assertEqual(_Call((('bar', 'barz'),),)[0], '')
     356          self.assertEqual(_Call((('bar', 'barz'), {'hello': 'world'}),)[0], '')
     357  
     358      def test_dunder_call(self):
     359          m = MagicMock()
     360          m().foo()['bar']()
     361          self.assertEqual(
     362              m.mock_calls,
     363              [call(), call().foo(), call().foo().__getitem__('bar'), call().foo().__getitem__()()]
     364          )
     365          m = MagicMock()
     366          m().foo()['bar'] = 1
     367          self.assertEqual(
     368              m.mock_calls,
     369              [call(), call().foo(), call().foo().__setitem__('bar', 1)]
     370          )
     371          m = MagicMock()
     372          iter(m().foo())
     373          self.assertEqual(
     374              m.mock_calls,
     375              [call(), call().foo(), call().foo().__iter__()]
     376          )
     377  
     378  
     379  class ESC[4;38;5;81mSpecSignatureTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
     380  
     381      def _check_someclass_mock(self, mock):
     382          self.assertRaises(AttributeError, getattr, mock, 'foo')
     383          mock.one(1, 2)
     384          mock.one.assert_called_with(1, 2)
     385          self.assertRaises(AssertionError,
     386                            mock.one.assert_called_with, 3, 4)
     387          self.assertRaises(TypeError, mock.one, 1)
     388  
     389          mock.two()
     390          mock.two.assert_called_with()
     391          self.assertRaises(AssertionError,
     392                            mock.two.assert_called_with, 3)
     393          self.assertRaises(TypeError, mock.two, 1)
     394  
     395          mock.three()
     396          mock.three.assert_called_with()
     397          self.assertRaises(AssertionError,
     398                            mock.three.assert_called_with, 3)
     399          self.assertRaises(TypeError, mock.three, 3, 2)
     400  
     401          mock.three(1)
     402          mock.three.assert_called_with(1)
     403  
     404          mock.three(a=1)
     405          mock.three.assert_called_with(a=1)
     406  
     407  
     408      def test_basic(self):
     409          mock = create_autospec(SomeClass)
     410          self._check_someclass_mock(mock)
     411          mock = create_autospec(SomeClass())
     412          self._check_someclass_mock(mock)
     413  
     414  
     415      def test_create_autospec_return_value(self):
     416          def f(): pass
     417          mock = create_autospec(f, return_value='foo')
     418          self.assertEqual(mock(), 'foo')
     419  
     420          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     421              pass
     422  
     423          mock = create_autospec(Foo, return_value='foo')
     424          self.assertEqual(mock(), 'foo')
     425  
     426  
     427      def test_autospec_reset_mock(self):
     428          m = create_autospec(int)
     429          int(m)
     430          m.reset_mock()
     431          self.assertEqual(m.__int__.call_count, 0)
     432  
     433  
     434      def test_mocking_unbound_methods(self):
     435          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     436              def foo(self, foo): pass
     437          p = patch.object(Foo, 'foo')
     438          mock_foo = p.start()
     439          Foo().foo(1)
     440  
     441          mock_foo.assert_called_with(1)
     442  
     443  
     444      def test_create_autospec_keyword_arguments(self):
     445          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     446              a = 3
     447          m = create_autospec(Foo, a='3')
     448          self.assertEqual(m.a, '3')
     449  
     450  
     451      def test_create_autospec_keyword_only_arguments(self):
     452          def foo(a, *, b=None): pass
     453  
     454          m = create_autospec(foo)
     455          m(1)
     456          m.assert_called_with(1)
     457          self.assertRaises(TypeError, m, 1, 2)
     458  
     459          m(2, b=3)
     460          m.assert_called_with(2, b=3)
     461  
     462  
     463      def test_function_as_instance_attribute(self):
     464          obj = SomeClass()
     465          def f(a): pass
     466          obj.f = f
     467  
     468          mock = create_autospec(obj)
     469          mock.f('bing')
     470          mock.f.assert_called_with('bing')
     471  
     472  
     473      def test_spec_as_list(self):
     474          # because spec as a list of strings in the mock constructor means
     475          # something very different we treat a list instance as the type.
     476          mock = create_autospec([])
     477          mock.append('foo')
     478          mock.append.assert_called_with('foo')
     479  
     480          self.assertRaises(AttributeError, getattr, mock, 'foo')
     481  
     482          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     483              foo = []
     484  
     485          mock = create_autospec(Foo)
     486          mock.foo.append(3)
     487          mock.foo.append.assert_called_with(3)
     488          self.assertRaises(AttributeError, getattr, mock.foo, 'foo')
     489  
     490  
     491      def test_attributes(self):
     492          class ESC[4;38;5;81mSub(ESC[4;38;5;149mSomeClass):
     493              attr = SomeClass()
     494  
     495          sub_mock = create_autospec(Sub)
     496  
     497          for mock in (sub_mock, sub_mock.attr):
     498              self._check_someclass_mock(mock)
     499  
     500  
     501      def test_spec_has_descriptor_returning_function(self):
     502  
     503          class ESC[4;38;5;81mCrazyDescriptor(ESC[4;38;5;149mobject):
     504  
     505              def __get__(self, obj, type_):
     506                  if obj is None:
     507                      return lambda x: None
     508  
     509          class ESC[4;38;5;81mMyClass(ESC[4;38;5;149mobject):
     510  
     511              some_attr = CrazyDescriptor()
     512  
     513          mock = create_autospec(MyClass)
     514          mock.some_attr(1)
     515          with self.assertRaises(TypeError):
     516              mock.some_attr()
     517          with self.assertRaises(TypeError):
     518              mock.some_attr(1, 2)
     519  
     520  
     521      def test_spec_has_function_not_in_bases(self):
     522  
     523          class ESC[4;38;5;81mCrazyClass(ESC[4;38;5;149mobject):
     524  
     525              def __dir__(self):
     526                  return super(CrazyClass, self).__dir__()+['crazy']
     527  
     528              def __getattr__(self, item):
     529                  if item == 'crazy':
     530                      return lambda x: x
     531                  raise AttributeError(item)
     532  
     533          inst = CrazyClass()
     534          with self.assertRaises(AttributeError):
     535              inst.other
     536          self.assertEqual(inst.crazy(42), 42)
     537  
     538          mock = create_autospec(inst)
     539          mock.crazy(42)
     540          with self.assertRaises(TypeError):
     541              mock.crazy()
     542          with self.assertRaises(TypeError):
     543              mock.crazy(1, 2)
     544  
     545  
     546      def test_builtin_functions_types(self):
     547          # we could replace builtin functions / methods with a function
     548          # with *args / **kwargs signature. Using the builtin method type
     549          # as a spec seems to work fairly well though.
     550          class ESC[4;38;5;81mBuiltinSubclass(ESC[4;38;5;149mlist):
     551              def bar(self, arg): pass
     552              sorted = sorted
     553              attr = {}
     554  
     555          mock = create_autospec(BuiltinSubclass)
     556          mock.append(3)
     557          mock.append.assert_called_with(3)
     558          self.assertRaises(AttributeError, getattr, mock.append, 'foo')
     559  
     560          mock.bar('foo')
     561          mock.bar.assert_called_with('foo')
     562          self.assertRaises(TypeError, mock.bar, 'foo', 'bar')
     563          self.assertRaises(AttributeError, getattr, mock.bar, 'foo')
     564  
     565          mock.sorted([1, 2])
     566          mock.sorted.assert_called_with([1, 2])
     567          self.assertRaises(AttributeError, getattr, mock.sorted, 'foo')
     568  
     569          mock.attr.pop(3)
     570          mock.attr.pop.assert_called_with(3)
     571          self.assertRaises(AttributeError, getattr, mock.attr, 'foo')
     572  
     573  
     574      def test_method_calls(self):
     575          class ESC[4;38;5;81mSub(ESC[4;38;5;149mSomeClass):
     576              attr = SomeClass()
     577  
     578          mock = create_autospec(Sub)
     579          mock.one(1, 2)
     580          mock.two()
     581          mock.three(3)
     582  
     583          expected = [call.one(1, 2), call.two(), call.three(3)]
     584          self.assertEqual(mock.method_calls, expected)
     585  
     586          mock.attr.one(1, 2)
     587          mock.attr.two()
     588          mock.attr.three(3)
     589  
     590          expected.extend(
     591              [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)]
     592          )
     593          self.assertEqual(mock.method_calls, expected)
     594  
     595  
     596      def test_magic_methods(self):
     597          class ESC[4;38;5;81mBuiltinSubclass(ESC[4;38;5;149mlist):
     598              attr = {}
     599  
     600          mock = create_autospec(BuiltinSubclass)
     601          self.assertEqual(list(mock), [])
     602          self.assertRaises(TypeError, int, mock)
     603          self.assertRaises(TypeError, int, mock.attr)
     604          self.assertEqual(list(mock), [])
     605  
     606          self.assertIsInstance(mock['foo'], MagicMock)
     607          self.assertIsInstance(mock.attr['foo'], MagicMock)
     608  
     609  
     610      def test_spec_set(self):
     611          class ESC[4;38;5;81mSub(ESC[4;38;5;149mSomeClass):
     612              attr = SomeClass()
     613  
     614          for spec in (Sub, Sub()):
     615              mock = create_autospec(spec, spec_set=True)
     616              self._check_someclass_mock(mock)
     617  
     618              self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar')
     619              self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar')
     620  
     621  
     622      def test_descriptors(self):
     623          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     624              @classmethod
     625              def f(cls, a, b): pass
     626              @staticmethod
     627              def g(a, b): pass
     628  
     629          class ESC[4;38;5;81mBar(ESC[4;38;5;149mFoo): pass
     630  
     631          class ESC[4;38;5;81mBaz(ESC[4;38;5;149mSomeClass, ESC[4;38;5;149mBar): pass
     632  
     633          for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()):
     634              mock = create_autospec(spec)
     635              mock.f(1, 2)
     636              mock.f.assert_called_once_with(1, 2)
     637  
     638              mock.g(3, 4)
     639              mock.g.assert_called_once_with(3, 4)
     640  
     641  
     642      def test_recursive(self):
     643          class ESC[4;38;5;81mA(ESC[4;38;5;149mobject):
     644              def a(self): pass
     645              foo = 'foo bar baz'
     646              bar = foo
     647  
     648          A.B = A
     649          mock = create_autospec(A)
     650  
     651          mock()
     652          self.assertFalse(mock.B.called)
     653  
     654          mock.a()
     655          mock.B.a()
     656          self.assertEqual(mock.method_calls, [call.a(), call.B.a()])
     657  
     658          self.assertIs(A.foo, A.bar)
     659          self.assertIsNot(mock.foo, mock.bar)
     660          mock.foo.lower()
     661          self.assertRaises(AssertionError, mock.bar.lower.assert_called_with)
     662  
     663  
     664      def test_spec_inheritance_for_classes(self):
     665          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     666              def a(self, x): pass
     667              class ESC[4;38;5;81mBar(ESC[4;38;5;149mobject):
     668                  def f(self, y): pass
     669  
     670          class_mock = create_autospec(Foo)
     671  
     672          self.assertIsNot(class_mock, class_mock())
     673  
     674          for this_mock in class_mock, class_mock():
     675              this_mock.a(x=5)
     676              this_mock.a.assert_called_with(x=5)
     677              this_mock.a.assert_called_with(5)
     678              self.assertRaises(TypeError, this_mock.a, 'foo', 'bar')
     679              self.assertRaises(AttributeError, getattr, this_mock, 'b')
     680  
     681          instance_mock = create_autospec(Foo())
     682          instance_mock.a(5)
     683          instance_mock.a.assert_called_with(5)
     684          instance_mock.a.assert_called_with(x=5)
     685          self.assertRaises(TypeError, instance_mock.a, 'foo', 'bar')
     686          self.assertRaises(AttributeError, getattr, instance_mock, 'b')
     687  
     688          # The return value isn't isn't callable
     689          self.assertRaises(TypeError, instance_mock)
     690  
     691          instance_mock.Bar.f(6)
     692          instance_mock.Bar.f.assert_called_with(6)
     693          instance_mock.Bar.f.assert_called_with(y=6)
     694          self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
     695  
     696          instance_mock.Bar().f(6)
     697          instance_mock.Bar().f.assert_called_with(6)
     698          instance_mock.Bar().f.assert_called_with(y=6)
     699          self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
     700  
     701  
     702      def test_inherit(self):
     703          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     704              a = 3
     705  
     706          Foo.Foo = Foo
     707  
     708          # class
     709          mock = create_autospec(Foo)
     710          instance = mock()
     711          self.assertRaises(AttributeError, getattr, instance, 'b')
     712  
     713          attr_instance = mock.Foo()
     714          self.assertRaises(AttributeError, getattr, attr_instance, 'b')
     715  
     716          # instance
     717          mock = create_autospec(Foo())
     718          self.assertRaises(AttributeError, getattr, mock, 'b')
     719          self.assertRaises(TypeError, mock)
     720  
     721          # attribute instance
     722          call_result = mock.Foo()
     723          self.assertRaises(AttributeError, getattr, call_result, 'b')
     724  
     725  
     726      def test_builtins(self):
     727          # used to fail with infinite recursion
     728          create_autospec(1)
     729  
     730          create_autospec(int)
     731          create_autospec('foo')
     732          create_autospec(str)
     733          create_autospec({})
     734          create_autospec(dict)
     735          create_autospec([])
     736          create_autospec(list)
     737          create_autospec(set())
     738          create_autospec(set)
     739          create_autospec(1.0)
     740          create_autospec(float)
     741          create_autospec(1j)
     742          create_autospec(complex)
     743          create_autospec(False)
     744          create_autospec(True)
     745  
     746  
     747      def test_function(self):
     748          def f(a, b): pass
     749  
     750          mock = create_autospec(f)
     751          self.assertRaises(TypeError, mock)
     752          mock(1, 2)
     753          mock.assert_called_with(1, 2)
     754          mock.assert_called_with(1, b=2)
     755          mock.assert_called_with(a=1, b=2)
     756  
     757          f.f = f
     758          mock = create_autospec(f)
     759          self.assertRaises(TypeError, mock.f)
     760          mock.f(3, 4)
     761          mock.f.assert_called_with(3, 4)
     762          mock.f.assert_called_with(a=3, b=4)
     763  
     764  
     765      def test_skip_attributeerrors(self):
     766          class ESC[4;38;5;81mRaiser(ESC[4;38;5;149mobject):
     767              def __get__(self, obj, type=None):
     768                  if obj is None:
     769                      raise AttributeError('Can only be accessed via an instance')
     770  
     771          class ESC[4;38;5;81mRaiserClass(ESC[4;38;5;149mobject):
     772              raiser = Raiser()
     773  
     774              @staticmethod
     775              def existing(a, b):
     776                  return a + b
     777  
     778          self.assertEqual(RaiserClass.existing(1, 2), 3)
     779          s = create_autospec(RaiserClass)
     780          self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
     781          self.assertEqual(s.existing(1, 2), s.existing.return_value)
     782          self.assertRaises(AttributeError, lambda: s.nonexisting)
     783  
     784          # check we can fetch the raiser attribute and it has no spec
     785          obj = s.raiser
     786          obj.foo, obj.bar
     787  
     788  
     789      def test_signature_class(self):
     790          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     791              def __init__(self, a, b=3): pass
     792  
     793          mock = create_autospec(Foo)
     794  
     795          self.assertRaises(TypeError, mock)
     796          mock(1)
     797          mock.assert_called_once_with(1)
     798          mock.assert_called_once_with(a=1)
     799          self.assertRaises(AssertionError, mock.assert_called_once_with, 2)
     800  
     801          mock(4, 5)
     802          mock.assert_called_with(4, 5)
     803          mock.assert_called_with(a=4, b=5)
     804          self.assertRaises(AssertionError, mock.assert_called_with, a=5, b=4)
     805  
     806  
     807      def test_class_with_no_init(self):
     808          # this used to raise an exception
     809          # due to trying to get a signature from object.__init__
     810          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     811              pass
     812          create_autospec(Foo)
     813  
     814  
     815      def test_signature_callable(self):
     816          class ESC[4;38;5;81mCallable(ESC[4;38;5;149mobject):
     817              def __init__(self, x, y): pass
     818              def __call__(self, a): pass
     819  
     820          mock = create_autospec(Callable)
     821          mock(1, 2)
     822          mock.assert_called_once_with(1, 2)
     823          mock.assert_called_once_with(x=1, y=2)
     824          self.assertRaises(TypeError, mock, 'a')
     825  
     826          instance = mock(1, 2)
     827          self.assertRaises(TypeError, instance)
     828          instance(a='a')
     829          instance.assert_called_once_with('a')
     830          instance.assert_called_once_with(a='a')
     831          instance('a')
     832          instance.assert_called_with('a')
     833          instance.assert_called_with(a='a')
     834  
     835          mock = create_autospec(Callable(1, 2))
     836          mock(a='a')
     837          mock.assert_called_once_with(a='a')
     838          self.assertRaises(TypeError, mock)
     839          mock('a')
     840          mock.assert_called_with('a')
     841  
     842  
     843      def test_signature_noncallable(self):
     844          class ESC[4;38;5;81mNonCallable(ESC[4;38;5;149mobject):
     845              def __init__(self):
     846                  pass
     847  
     848          mock = create_autospec(NonCallable)
     849          instance = mock()
     850          mock.assert_called_once_with()
     851          self.assertRaises(TypeError, mock, 'a')
     852          self.assertRaises(TypeError, instance)
     853          self.assertRaises(TypeError, instance, 'a')
     854  
     855          mock = create_autospec(NonCallable())
     856          self.assertRaises(TypeError, mock)
     857          self.assertRaises(TypeError, mock, 'a')
     858  
     859  
     860      def test_create_autospec_none(self):
     861          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     862              bar = None
     863  
     864          mock = create_autospec(Foo)
     865          none = mock.bar
     866          self.assertNotIsInstance(none, type(None))
     867  
     868          none.foo()
     869          none.foo.assert_called_once_with()
     870  
     871  
     872      def test_autospec_functions_with_self_in_odd_place(self):
     873          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     874              def f(a, self): pass
     875  
     876          a = create_autospec(Foo)
     877          a.f(10)
     878          a.f.assert_called_with(10)
     879          a.f.assert_called_with(self=10)
     880          a.f(self=10)
     881          a.f.assert_called_with(10)
     882          a.f.assert_called_with(self=10)
     883  
     884  
     885      def test_autospec_data_descriptor(self):
     886          class ESC[4;38;5;81mDescriptor(ESC[4;38;5;149mobject):
     887              def __init__(self, value):
     888                  self.value = value
     889  
     890              def __get__(self, obj, cls=None):
     891                  return self
     892  
     893              def __set__(self, obj, value): pass
     894  
     895          class ESC[4;38;5;81mMyProperty(ESC[4;38;5;149mproperty):
     896              pass
     897  
     898          class ESC[4;38;5;81mFoo(ESC[4;38;5;149mobject):
     899              __slots__ = ['slot']
     900  
     901              @property
     902              def prop(self): pass
     903  
     904              @MyProperty
     905              def subprop(self): pass
     906  
     907              desc = Descriptor(42)
     908  
     909          foo = create_autospec(Foo)
     910  
     911          def check_data_descriptor(mock_attr):
     912              # Data descriptors don't have a spec.
     913              self.assertIsInstance(mock_attr, MagicMock)
     914              mock_attr(1, 2, 3)
     915              mock_attr.abc(4, 5, 6)
     916              mock_attr.assert_called_once_with(1, 2, 3)
     917              mock_attr.abc.assert_called_once_with(4, 5, 6)
     918  
     919          # property
     920          check_data_descriptor(foo.prop)
     921          # property subclass
     922          check_data_descriptor(foo.subprop)
     923          # class __slot__
     924          check_data_descriptor(foo.slot)
     925          # plain data descriptor
     926          check_data_descriptor(foo.desc)
     927  
     928  
     929      def test_autospec_on_bound_builtin_function(self):
     930          meth = types.MethodType(time.ctime, time.time())
     931          self.assertIsInstance(meth(), str)
     932          mocked = create_autospec(meth)
     933  
     934          # no signature, so no spec to check against
     935          mocked()
     936          mocked.assert_called_once_with()
     937          mocked.reset_mock()
     938          mocked(4, 5, 6)
     939          mocked.assert_called_once_with(4, 5, 6)
     940  
     941  
     942      def test_autospec_getattr_partial_function(self):
     943          # bpo-32153 : getattr returning partial functions without
     944          # __name__ should not create AttributeError in create_autospec
     945          class ESC[4;38;5;81mFoo:
     946  
     947              def __getattr__(self, attribute):
     948                  return partial(lambda name: name, attribute)
     949  
     950          proxy = Foo()
     951          autospec = create_autospec(proxy)
     952          self.assertFalse(hasattr(autospec, '__name__'))
     953  
     954  
     955      def test_autospec_signature_staticmethod(self):
     956          class ESC[4;38;5;81mFoo:
     957              @staticmethod
     958              def static_method(a, b=10, *, c): pass
     959  
     960          mock = create_autospec(Foo.__dict__['static_method'])
     961          self.assertEqual(inspect.signature(Foo.static_method), inspect.signature(mock))
     962  
     963  
     964      def test_autospec_signature_classmethod(self):
     965          class ESC[4;38;5;81mFoo:
     966              @classmethod
     967              def class_method(cls, a, b=10, *, c): pass
     968  
     969          mock = create_autospec(Foo.__dict__['class_method'])
     970          self.assertEqual(inspect.signature(Foo.class_method), inspect.signature(mock))
     971  
     972  
     973      def test_spec_inspect_signature(self):
     974  
     975          def myfunc(x, y): pass
     976  
     977          mock = create_autospec(myfunc)
     978          mock(1, 2)
     979          mock(x=1, y=2)
     980  
     981          self.assertEqual(inspect.signature(mock), inspect.signature(myfunc))
     982          self.assertEqual(mock.mock_calls, [call(1, 2), call(x=1, y=2)])
     983          self.assertRaises(TypeError, mock, 1)
     984  
     985  
     986      def test_spec_inspect_signature_annotations(self):
     987  
     988          def foo(a: int, b: int=10, *, c:int) -> int:
     989              return a + b + c
     990  
     991          self.assertEqual(foo(1, 2 , c=3), 6)
     992          mock = create_autospec(foo)
     993          mock(1, 2, c=3)
     994          mock(1, c=3)
     995  
     996          self.assertEqual(inspect.signature(mock), inspect.signature(foo))
     997          self.assertEqual(mock.mock_calls, [call(1, 2, c=3), call(1, c=3)])
     998          self.assertRaises(TypeError, mock, 1)
     999          self.assertRaises(TypeError, mock, 1, 2, 3, c=4)
    1000  
    1001  
    1002      def test_spec_function_no_name(self):
    1003          func = lambda: 'nope'
    1004          mock = create_autospec(func)
    1005          self.assertEqual(mock.__name__, 'funcopy')
    1006  
    1007  
    1008      def test_spec_function_assert_has_calls(self):
    1009          def f(a): pass
    1010          mock = create_autospec(f)
    1011          mock(1)
    1012          mock.assert_has_calls([call(1)])
    1013          with self.assertRaises(AssertionError):
    1014              mock.assert_has_calls([call(2)])
    1015  
    1016  
    1017      def test_spec_function_assert_any_call(self):
    1018          def f(a): pass
    1019          mock = create_autospec(f)
    1020          mock(1)
    1021          mock.assert_any_call(1)
    1022          with self.assertRaises(AssertionError):
    1023              mock.assert_any_call(2)
    1024  
    1025  
    1026      def test_spec_function_reset_mock(self):
    1027          def f(a): pass
    1028          rv = Mock()
    1029          mock = create_autospec(f, return_value=rv)
    1030          mock(1)(2)
    1031          self.assertEqual(mock.mock_calls, [call(1)])
    1032          self.assertEqual(rv.mock_calls, [call(2)])
    1033          mock.reset_mock()
    1034          self.assertEqual(mock.mock_calls, [])
    1035          self.assertEqual(rv.mock_calls, [])
    1036  
    1037  
    1038  class ESC[4;38;5;81mTestCallList(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
    1039  
    1040      def test_args_list_contains_call_list(self):
    1041          mock = Mock()
    1042          self.assertIsInstance(mock.call_args_list, _CallList)
    1043  
    1044          mock(1, 2)
    1045          mock(a=3)
    1046          mock(3, 4)
    1047          mock(b=6)
    1048  
    1049          for kall in call(1, 2), call(a=3), call(3, 4), call(b=6):
    1050              self.assertIn(kall, mock.call_args_list)
    1051  
    1052          calls = [call(a=3), call(3, 4)]
    1053          self.assertIn(calls, mock.call_args_list)
    1054          calls = [call(1, 2), call(a=3)]
    1055          self.assertIn(calls, mock.call_args_list)
    1056          calls = [call(3, 4), call(b=6)]
    1057          self.assertIn(calls, mock.call_args_list)
    1058          calls = [call(3, 4)]
    1059          self.assertIn(calls, mock.call_args_list)
    1060  
    1061          self.assertNotIn(call('fish'), mock.call_args_list)
    1062          self.assertNotIn([call('fish')], mock.call_args_list)
    1063  
    1064  
    1065      def test_call_list_str(self):
    1066          mock = Mock()
    1067          mock(1, 2)
    1068          mock.foo(a=3)
    1069          mock.foo.bar().baz('fish', cat='dog')
    1070  
    1071          expected = (
    1072              "[call(1, 2),\n"
    1073              " call.foo(a=3),\n"
    1074              " call.foo.bar(),\n"
    1075              " call.foo.bar().baz('fish', cat='dog')]"
    1076          )
    1077          self.assertEqual(str(mock.mock_calls), expected)
    1078  
    1079  
    1080      def test_propertymock(self):
    1081          p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock)
    1082          mock = p.start()
    1083          try:
    1084              SomeClass.one
    1085              mock.assert_called_once_with()
    1086  
    1087              s = SomeClass()
    1088              s.one
    1089              mock.assert_called_with()
    1090              self.assertEqual(mock.mock_calls, [call(), call()])
    1091  
    1092              s.one = 3
    1093              self.assertEqual(mock.mock_calls, [call(), call(), call(3)])
    1094          finally:
    1095              p.stop()
    1096  
    1097  
    1098      def test_propertymock_bare(self):
    1099          m = MagicMock()
    1100          p = PropertyMock()
    1101          type(m).foo = p
    1102  
    1103          returned = m.foo
    1104          p.assert_called_once_with()
    1105          self.assertIsInstance(returned, MagicMock)
    1106          self.assertNotIsInstance(returned, PropertyMock)
    1107  
    1108  
    1109      def test_propertymock_returnvalue(self):
    1110          m = MagicMock()
    1111          p = PropertyMock(return_value=42)
    1112          type(m).foo = p
    1113  
    1114          returned = m.foo
    1115          p.assert_called_once_with()
    1116          self.assertEqual(returned, 42)
    1117          self.assertNotIsInstance(returned, PropertyMock)
    1118  
    1119  
    1120      def test_propertymock_side_effect(self):
    1121          m = MagicMock()
    1122          p = PropertyMock(side_effect=ValueError)
    1123          type(m).foo = p
    1124  
    1125          with self.assertRaises(ValueError):
    1126              m.foo
    1127          p.assert_called_once_with()
    1128  
    1129  
    1130  class ESC[4;38;5;81mTestCallablePredicate(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
    1131  
    1132      def test_type(self):
    1133          for obj in [str, bytes, int, list, tuple, SomeClass]:
    1134              self.assertTrue(_callable(obj))
    1135  
    1136      def test_call_magic_method(self):
    1137          class ESC[4;38;5;81mCallable:
    1138              def __call__(self): pass
    1139          instance = Callable()
    1140          self.assertTrue(_callable(instance))
    1141  
    1142      def test_staticmethod(self):
    1143          class ESC[4;38;5;81mWithStaticMethod:
    1144              @staticmethod
    1145              def staticfunc(): pass
    1146          self.assertTrue(_callable(WithStaticMethod.staticfunc))
    1147  
    1148      def test_non_callable_staticmethod(self):
    1149          class ESC[4;38;5;81mBadStaticMethod:
    1150              not_callable = staticmethod(None)
    1151          self.assertFalse(_callable(BadStaticMethod.not_callable))
    1152  
    1153      def test_classmethod(self):
    1154          class ESC[4;38;5;81mWithClassMethod:
    1155              @classmethod
    1156              def classfunc(cls): pass
    1157          self.assertTrue(_callable(WithClassMethod.classfunc))
    1158  
    1159      def test_non_callable_classmethod(self):
    1160          class ESC[4;38;5;81mBadClassMethod:
    1161              not_callable = classmethod(None)
    1162          self.assertFalse(_callable(BadClassMethod.not_callable))
    1163  
    1164  
    1165  if __name__ == '__main__':
    1166      unittest.main()