ยปCore Development>Code coverage>Lib/unittest/test/testmock/testmock.py

Python code coverage for Lib/unittest/test/testmock/testmock.py

#countcontent
1n/aimport copy
2n/aimport sys
3n/aimport tempfile
4n/a
5n/aimport unittest
6n/afrom unittest.test.testmock.support import is_instance
7n/afrom unittest import mock
8n/afrom unittest.mock import (
9n/a call, DEFAULT, patch, sentinel,
10n/a MagicMock, Mock, NonCallableMock,
11n/a NonCallableMagicMock, _CallList,
12n/a create_autospec
13n/a)
14n/a
15n/a
16n/aclass Iter(object):
17n/a def __init__(self):
18n/a self.thing = iter(['this', 'is', 'an', 'iter'])
19n/a
20n/a def __iter__(self):
21n/a return self
22n/a
23n/a def next(self):
24n/a return next(self.thing)
25n/a
26n/a __next__ = next
27n/a
28n/a
29n/aclass Something(object):
30n/a def meth(self, a, b, c, d=None):
31n/a pass
32n/a
33n/a @classmethod
34n/a def cmeth(cls, a, b, c, d=None):
35n/a pass
36n/a
37n/a @staticmethod
38n/a def smeth(a, b, c, d=None):
39n/a pass
40n/a
41n/a
42n/aclass MockTest(unittest.TestCase):
43n/a
44n/a def test_all(self):
45n/a # if __all__ is badly defined then import * will raise an error
46n/a # We have to exec it because you can't import * inside a method
47n/a # in Python 3
48n/a exec("from unittest.mock import *")
49n/a
50n/a
51n/a def test_constructor(self):
52n/a mock = Mock()
53n/a
54n/a self.assertFalse(mock.called, "called not initialised correctly")
55n/a self.assertEqual(mock.call_count, 0,
56n/a "call_count not initialised correctly")
57n/a self.assertTrue(is_instance(mock.return_value, Mock),
58n/a "return_value not initialised correctly")
59n/a
60n/a self.assertEqual(mock.call_args, None,
61n/a "call_args not initialised correctly")
62n/a self.assertEqual(mock.call_args_list, [],
63n/a "call_args_list not initialised correctly")
64n/a self.assertEqual(mock.method_calls, [],
65n/a "method_calls not initialised correctly")
66n/a
67n/a # Can't use hasattr for this test as it always returns True on a mock
68n/a self.assertNotIn('_items', mock.__dict__,
69n/a "default mock should not have '_items' attribute")
70n/a
71n/a self.assertIsNone(mock._mock_parent,
72n/a "parent not initialised correctly")
73n/a self.assertIsNone(mock._mock_methods,
74n/a "methods not initialised correctly")
75n/a self.assertEqual(mock._mock_children, {},
76n/a "children not initialised incorrectly")
77n/a
78n/a
79n/a def test_return_value_in_constructor(self):
80n/a mock = Mock(return_value=None)
81n/a self.assertIsNone(mock.return_value,
82n/a "return value in constructor not honoured")
83n/a
84n/a
85n/a def test_repr(self):
86n/a mock = Mock(name='foo')
87n/a self.assertIn('foo', repr(mock))
88n/a self.assertIn("'%s'" % id(mock), repr(mock))
89n/a
90n/a mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
91n/a for mock, name in mocks:
92n/a self.assertIn('%s.bar' % name, repr(mock.bar))
93n/a self.assertIn('%s.foo()' % name, repr(mock.foo()))
94n/a self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
95n/a self.assertIn('%s()' % name, repr(mock()))
96n/a self.assertIn('%s()()' % name, repr(mock()()))
97n/a self.assertIn('%s()().foo.bar.baz().bing' % name,
98n/a repr(mock()().foo.bar.baz().bing))
99n/a
100n/a
101n/a def test_repr_with_spec(self):
102n/a class X(object):
103n/a pass
104n/a
105n/a mock = Mock(spec=X)
106n/a self.assertIn(" spec='X' ", repr(mock))
107n/a
108n/a mock = Mock(spec=X())
109n/a self.assertIn(" spec='X' ", repr(mock))
110n/a
111n/a mock = Mock(spec_set=X)
112n/a self.assertIn(" spec_set='X' ", repr(mock))
113n/a
114n/a mock = Mock(spec_set=X())
115n/a self.assertIn(" spec_set='X' ", repr(mock))
116n/a
117n/a mock = Mock(spec=X, name='foo')
118n/a self.assertIn(" spec='X' ", repr(mock))
119n/a self.assertIn(" name='foo' ", repr(mock))
120n/a
121n/a mock = Mock(name='foo')
122n/a self.assertNotIn("spec", repr(mock))
123n/a
124n/a mock = Mock()
125n/a self.assertNotIn("spec", repr(mock))
126n/a
127n/a mock = Mock(spec=['foo'])
128n/a self.assertNotIn("spec", repr(mock))
129n/a
130n/a
131n/a def test_side_effect(self):
132n/a mock = Mock()
133n/a
134n/a def effect(*args, **kwargs):
135n/a raise SystemError('kablooie')
136n/a
137n/a mock.side_effect = effect
138n/a self.assertRaises(SystemError, mock, 1, 2, fish=3)
139n/a mock.assert_called_with(1, 2, fish=3)
140n/a
141n/a results = [1, 2, 3]
142n/a def effect():
143n/a return results.pop()
144n/a mock.side_effect = effect
145n/a
146n/a self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
147n/a "side effect not used correctly")
148n/a
149n/a mock = Mock(side_effect=sentinel.SideEffect)
150n/a self.assertEqual(mock.side_effect, sentinel.SideEffect,
151n/a "side effect in constructor not used")
152n/a
153n/a def side_effect():
154n/a return DEFAULT
155n/a mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
156n/a self.assertEqual(mock(), sentinel.RETURN)
157n/a
158n/a def test_autospec_side_effect(self):
159n/a # Test for issue17826
160n/a results = [1, 2, 3]
161n/a def effect():
162n/a return results.pop()
163n/a def f():
164n/a pass
165n/a
166n/a mock = create_autospec(f)
167n/a mock.side_effect = [1, 2, 3]
168n/a self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
169n/a "side effect not used correctly in create_autospec")
170n/a # Test where side effect is a callable
171n/a results = [1, 2, 3]
172n/a mock = create_autospec(f)
173n/a mock.side_effect = effect
174n/a self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
175n/a "callable side effect not used correctly")
176n/a
177n/a def test_autospec_side_effect_exception(self):
178n/a # Test for issue 23661
179n/a def f():
180n/a pass
181n/a
182n/a mock = create_autospec(f)
183n/a mock.side_effect = ValueError('Bazinga!')
184n/a self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
185n/a
186n/a @unittest.skipUnless('java' in sys.platform,
187n/a 'This test only applies to Jython')
188n/a def test_java_exception_side_effect(self):
189n/a import java
190n/a mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
191n/a
192n/a # can't use assertRaises with java exceptions
193n/a try:
194n/a mock(1, 2, fish=3)
195n/a except java.lang.RuntimeException:
196n/a pass
197n/a else:
198n/a self.fail('java exception not raised')
199n/a mock.assert_called_with(1,2, fish=3)
200n/a
201n/a
202n/a def test_reset_mock(self):
203n/a parent = Mock()
204n/a spec = ["something"]
205n/a mock = Mock(name="child", parent=parent, spec=spec)
206n/a mock(sentinel.Something, something=sentinel.SomethingElse)
207n/a something = mock.something
208n/a mock.something()
209n/a mock.side_effect = sentinel.SideEffect
210n/a return_value = mock.return_value
211n/a return_value()
212n/a
213n/a mock.reset_mock()
214n/a
215n/a self.assertEqual(mock._mock_name, "child",
216n/a "name incorrectly reset")
217n/a self.assertEqual(mock._mock_parent, parent,
218n/a "parent incorrectly reset")
219n/a self.assertEqual(mock._mock_methods, spec,
220n/a "methods incorrectly reset")
221n/a
222n/a self.assertFalse(mock.called, "called not reset")
223n/a self.assertEqual(mock.call_count, 0, "call_count not reset")
224n/a self.assertEqual(mock.call_args, None, "call_args not reset")
225n/a self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
226n/a self.assertEqual(mock.method_calls, [],
227n/a "method_calls not initialised correctly: %r != %r" %
228n/a (mock.method_calls, []))
229n/a self.assertEqual(mock.mock_calls, [])
230n/a
231n/a self.assertEqual(mock.side_effect, sentinel.SideEffect,
232n/a "side_effect incorrectly reset")
233n/a self.assertEqual(mock.return_value, return_value,
234n/a "return_value incorrectly reset")
235n/a self.assertFalse(return_value.called, "return value mock not reset")
236n/a self.assertEqual(mock._mock_children, {'something': something},
237n/a "children reset incorrectly")
238n/a self.assertEqual(mock.something, something,
239n/a "children incorrectly cleared")
240n/a self.assertFalse(mock.something.called, "child not reset")
241n/a
242n/a
243n/a def test_reset_mock_recursion(self):
244n/a mock = Mock()
245n/a mock.return_value = mock
246n/a
247n/a # used to cause recursion
248n/a mock.reset_mock()
249n/a
250n/a def test_reset_mock_on_mock_open_issue_18622(self):
251n/a a = mock.mock_open()
252n/a a.reset_mock()
253n/a
254n/a def test_call(self):
255n/a mock = Mock()
256n/a self.assertTrue(is_instance(mock.return_value, Mock),
257n/a "Default return_value should be a Mock")
258n/a
259n/a result = mock()
260n/a self.assertEqual(mock(), result,
261n/a "different result from consecutive calls")
262n/a mock.reset_mock()
263n/a
264n/a ret_val = mock(sentinel.Arg)
265n/a self.assertTrue(mock.called, "called not set")
266n/a self.assertEqual(mock.call_count, 1, "call_count incoreect")
267n/a self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
268n/a "call_args not set")
269n/a self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
270n/a "call_args_list not initialised correctly")
271n/a
272n/a mock.return_value = sentinel.ReturnValue
273n/a ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
274n/a self.assertEqual(ret_val, sentinel.ReturnValue,
275n/a "incorrect return value")
276n/a
277n/a self.assertEqual(mock.call_count, 2, "call_count incorrect")
278n/a self.assertEqual(mock.call_args,
279n/a ((sentinel.Arg,), {'key': sentinel.KeyArg}),
280n/a "call_args not set")
281n/a self.assertEqual(mock.call_args_list, [
282n/a ((sentinel.Arg,), {}),
283n/a ((sentinel.Arg,), {'key': sentinel.KeyArg})
284n/a ],
285n/a "call_args_list not set")
286n/a
287n/a
288n/a def test_call_args_comparison(self):
289n/a mock = Mock()
290n/a mock()
291n/a mock(sentinel.Arg)
292n/a mock(kw=sentinel.Kwarg)
293n/a mock(sentinel.Arg, kw=sentinel.Kwarg)
294n/a self.assertEqual(mock.call_args_list, [
295n/a (),
296n/a ((sentinel.Arg,),),
297n/a ({"kw": sentinel.Kwarg},),
298n/a ((sentinel.Arg,), {"kw": sentinel.Kwarg})
299n/a ])
300n/a self.assertEqual(mock.call_args,
301n/a ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
302n/a
303n/a # Comparing call_args to a long sequence should not raise
304n/a # an exception. See issue 24857.
305n/a self.assertFalse(mock.call_args == "a long sequence")
306n/a
307n/a
308n/a def test_calls_equal_with_any(self):
309n/a # Check that equality and non-equality is consistent even when
310n/a # comparing with mock.ANY
311n/a mm = mock.MagicMock()
312n/a self.assertTrue(mm == mm)
313n/a self.assertFalse(mm != mm)
314n/a self.assertFalse(mm == mock.MagicMock())
315n/a self.assertTrue(mm != mock.MagicMock())
316n/a self.assertTrue(mm == mock.ANY)
317n/a self.assertFalse(mm != mock.ANY)
318n/a self.assertTrue(mock.ANY == mm)
319n/a self.assertFalse(mock.ANY != mm)
320n/a
321n/a call1 = mock.call(mock.MagicMock())
322n/a call2 = mock.call(mock.ANY)
323n/a self.assertTrue(call1 == call2)
324n/a self.assertFalse(call1 != call2)
325n/a self.assertTrue(call2 == call1)
326n/a self.assertFalse(call2 != call1)
327n/a
328n/a
329n/a def test_assert_called_with(self):
330n/a mock = Mock()
331n/a mock()
332n/a
333n/a # Will raise an exception if it fails
334n/a mock.assert_called_with()
335n/a self.assertRaises(AssertionError, mock.assert_called_with, 1)
336n/a
337n/a mock.reset_mock()
338n/a self.assertRaises(AssertionError, mock.assert_called_with)
339n/a
340n/a mock(1, 2, 3, a='fish', b='nothing')
341n/a mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
342n/a
343n/a
344n/a def test_assert_called_with_any(self):
345n/a m = MagicMock()
346n/a m(MagicMock())
347n/a m.assert_called_with(mock.ANY)
348n/a
349n/a
350n/a def test_assert_called_with_function_spec(self):
351n/a def f(a, b, c, d=None):
352n/a pass
353n/a
354n/a mock = Mock(spec=f)
355n/a
356n/a mock(1, b=2, c=3)
357n/a mock.assert_called_with(1, 2, 3)
358n/a mock.assert_called_with(a=1, b=2, c=3)
359n/a self.assertRaises(AssertionError, mock.assert_called_with,
360n/a 1, b=3, c=2)
361n/a # Expected call doesn't match the spec's signature
362n/a with self.assertRaises(AssertionError) as cm:
363n/a mock.assert_called_with(e=8)
364n/a self.assertIsInstance(cm.exception.__cause__, TypeError)
365n/a
366n/a
367n/a def test_assert_called_with_method_spec(self):
368n/a def _check(mock):
369n/a mock(1, b=2, c=3)
370n/a mock.assert_called_with(1, 2, 3)
371n/a mock.assert_called_with(a=1, b=2, c=3)
372n/a self.assertRaises(AssertionError, mock.assert_called_with,
373n/a 1, b=3, c=2)
374n/a
375n/a mock = Mock(spec=Something().meth)
376n/a _check(mock)
377n/a mock = Mock(spec=Something.cmeth)
378n/a _check(mock)
379n/a mock = Mock(spec=Something().cmeth)
380n/a _check(mock)
381n/a mock = Mock(spec=Something.smeth)
382n/a _check(mock)
383n/a mock = Mock(spec=Something().smeth)
384n/a _check(mock)
385n/a
386n/a
387n/a def test_assert_called_once_with(self):
388n/a mock = Mock()
389n/a mock()
390n/a
391n/a # Will raise an exception if it fails
392n/a mock.assert_called_once_with()
393n/a
394n/a mock()
395n/a self.assertRaises(AssertionError, mock.assert_called_once_with)
396n/a
397n/a mock.reset_mock()
398n/a self.assertRaises(AssertionError, mock.assert_called_once_with)
399n/a
400n/a mock('foo', 'bar', baz=2)
401n/a mock.assert_called_once_with('foo', 'bar', baz=2)
402n/a
403n/a mock.reset_mock()
404n/a mock('foo', 'bar', baz=2)
405n/a self.assertRaises(
406n/a AssertionError,
407n/a lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
408n/a )
409n/a
410n/a
411n/a def test_assert_called_once_with_function_spec(self):
412n/a def f(a, b, c, d=None):
413n/a pass
414n/a
415n/a mock = Mock(spec=f)
416n/a
417n/a mock(1, b=2, c=3)
418n/a mock.assert_called_once_with(1, 2, 3)
419n/a mock.assert_called_once_with(a=1, b=2, c=3)
420n/a self.assertRaises(AssertionError, mock.assert_called_once_with,
421n/a 1, b=3, c=2)
422n/a # Expected call doesn't match the spec's signature
423n/a with self.assertRaises(AssertionError) as cm:
424n/a mock.assert_called_once_with(e=8)
425n/a self.assertIsInstance(cm.exception.__cause__, TypeError)
426n/a # Mock called more than once => always fails
427n/a mock(4, 5, 6)
428n/a self.assertRaises(AssertionError, mock.assert_called_once_with,
429n/a 1, 2, 3)
430n/a self.assertRaises(AssertionError, mock.assert_called_once_with,
431n/a 4, 5, 6)
432n/a
433n/a
434n/a def test_attribute_access_returns_mocks(self):
435n/a mock = Mock()
436n/a something = mock.something
437n/a self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
438n/a self.assertEqual(mock.something, something,
439n/a "different attributes returned for same name")
440n/a
441n/a # Usage example
442n/a mock = Mock()
443n/a mock.something.return_value = 3
444n/a
445n/a self.assertEqual(mock.something(), 3, "method returned wrong value")
446n/a self.assertTrue(mock.something.called,
447n/a "method didn't record being called")
448n/a
449n/a
450n/a def test_attributes_have_name_and_parent_set(self):
451n/a mock = Mock()
452n/a something = mock.something
453n/a
454n/a self.assertEqual(something._mock_name, "something",
455n/a "attribute name not set correctly")
456n/a self.assertEqual(something._mock_parent, mock,
457n/a "attribute parent not set correctly")
458n/a
459n/a
460n/a def test_method_calls_recorded(self):
461n/a mock = Mock()
462n/a mock.something(3, fish=None)
463n/a mock.something_else.something(6, cake=sentinel.Cake)
464n/a
465n/a self.assertEqual(mock.something_else.method_calls,
466n/a [("something", (6,), {'cake': sentinel.Cake})],
467n/a "method calls not recorded correctly")
468n/a self.assertEqual(mock.method_calls, [
469n/a ("something", (3,), {'fish': None}),
470n/a ("something_else.something", (6,), {'cake': sentinel.Cake})
471n/a ],
472n/a "method calls not recorded correctly")
473n/a
474n/a
475n/a def test_method_calls_compare_easily(self):
476n/a mock = Mock()
477n/a mock.something()
478n/a self.assertEqual(mock.method_calls, [('something',)])
479n/a self.assertEqual(mock.method_calls, [('something', (), {})])
480n/a
481n/a mock = Mock()
482n/a mock.something('different')
483n/a self.assertEqual(mock.method_calls, [('something', ('different',))])
484n/a self.assertEqual(mock.method_calls,
485n/a [('something', ('different',), {})])
486n/a
487n/a mock = Mock()
488n/a mock.something(x=1)
489n/a self.assertEqual(mock.method_calls, [('something', {'x': 1})])
490n/a self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
491n/a
492n/a mock = Mock()
493n/a mock.something('different', some='more')
494n/a self.assertEqual(mock.method_calls, [
495n/a ('something', ('different',), {'some': 'more'})
496n/a ])
497n/a
498n/a
499n/a def test_only_allowed_methods_exist(self):
500n/a for spec in ['something'], ('something',):
501n/a for arg in 'spec', 'spec_set':
502n/a mock = Mock(**{arg: spec})
503n/a
504n/a # this should be allowed
505n/a mock.something
506n/a self.assertRaisesRegex(
507n/a AttributeError,
508n/a "Mock object has no attribute 'something_else'",
509n/a getattr, mock, 'something_else'
510n/a )
511n/a
512n/a
513n/a def test_from_spec(self):
514n/a class Something(object):
515n/a x = 3
516n/a __something__ = None
517n/a def y(self):
518n/a pass
519n/a
520n/a def test_attributes(mock):
521n/a # should work
522n/a mock.x
523n/a mock.y
524n/a mock.__something__
525n/a self.assertRaisesRegex(
526n/a AttributeError,
527n/a "Mock object has no attribute 'z'",
528n/a getattr, mock, 'z'
529n/a )
530n/a self.assertRaisesRegex(
531n/a AttributeError,
532n/a "Mock object has no attribute '__foobar__'",
533n/a getattr, mock, '__foobar__'
534n/a )
535n/a
536n/a test_attributes(Mock(spec=Something))
537n/a test_attributes(Mock(spec=Something()))
538n/a
539n/a
540n/a def test_wraps_calls(self):
541n/a real = Mock()
542n/a
543n/a mock = Mock(wraps=real)
544n/a self.assertEqual(mock(), real())
545n/a
546n/a real.reset_mock()
547n/a
548n/a mock(1, 2, fish=3)
549n/a real.assert_called_with(1, 2, fish=3)
550n/a
551n/a
552n/a def test_wraps_call_with_nondefault_return_value(self):
553n/a real = Mock()
554n/a
555n/a mock = Mock(wraps=real)
556n/a mock.return_value = 3
557n/a
558n/a self.assertEqual(mock(), 3)
559n/a self.assertFalse(real.called)
560n/a
561n/a
562n/a def test_wraps_attributes(self):
563n/a class Real(object):
564n/a attribute = Mock()
565n/a
566n/a real = Real()
567n/a
568n/a mock = Mock(wraps=real)
569n/a self.assertEqual(mock.attribute(), real.attribute())
570n/a self.assertRaises(AttributeError, lambda: mock.fish)
571n/a
572n/a self.assertNotEqual(mock.attribute, real.attribute)
573n/a result = mock.attribute.frog(1, 2, fish=3)
574n/a Real.attribute.frog.assert_called_with(1, 2, fish=3)
575n/a self.assertEqual(result, Real.attribute.frog())
576n/a
577n/a
578n/a def test_exceptional_side_effect(self):
579n/a mock = Mock(side_effect=AttributeError)
580n/a self.assertRaises(AttributeError, mock)
581n/a
582n/a mock = Mock(side_effect=AttributeError('foo'))
583n/a self.assertRaises(AttributeError, mock)
584n/a
585n/a
586n/a def test_baseexceptional_side_effect(self):
587n/a mock = Mock(side_effect=KeyboardInterrupt)
588n/a self.assertRaises(KeyboardInterrupt, mock)
589n/a
590n/a mock = Mock(side_effect=KeyboardInterrupt('foo'))
591n/a self.assertRaises(KeyboardInterrupt, mock)
592n/a
593n/a
594n/a def test_assert_called_with_message(self):
595n/a mock = Mock()
596n/a self.assertRaisesRegex(AssertionError, 'Not called',
597n/a mock.assert_called_with)
598n/a
599n/a
600n/a def test_assert_called_once_with_message(self):
601n/a mock = Mock(name='geoffrey')
602n/a self.assertRaisesRegex(AssertionError,
603n/a r"Expected 'geoffrey' to be called once\.",
604n/a mock.assert_called_once_with)
605n/a
606n/a
607n/a def test__name__(self):
608n/a mock = Mock()
609n/a self.assertRaises(AttributeError, lambda: mock.__name__)
610n/a
611n/a mock.__name__ = 'foo'
612n/a self.assertEqual(mock.__name__, 'foo')
613n/a
614n/a
615n/a def test_spec_list_subclass(self):
616n/a class Sub(list):
617n/a pass
618n/a mock = Mock(spec=Sub(['foo']))
619n/a
620n/a mock.append(3)
621n/a mock.append.assert_called_with(3)
622n/a self.assertRaises(AttributeError, getattr, mock, 'foo')
623n/a
624n/a
625n/a def test_spec_class(self):
626n/a class X(object):
627n/a pass
628n/a
629n/a mock = Mock(spec=X)
630n/a self.assertIsInstance(mock, X)
631n/a
632n/a mock = Mock(spec=X())
633n/a self.assertIsInstance(mock, X)
634n/a
635n/a self.assertIs(mock.__class__, X)
636n/a self.assertEqual(Mock().__class__.__name__, 'Mock')
637n/a
638n/a mock = Mock(spec_set=X)
639n/a self.assertIsInstance(mock, X)
640n/a
641n/a mock = Mock(spec_set=X())
642n/a self.assertIsInstance(mock, X)
643n/a
644n/a
645n/a def test_setting_attribute_with_spec_set(self):
646n/a class X(object):
647n/a y = 3
648n/a
649n/a mock = Mock(spec=X)
650n/a mock.x = 'foo'
651n/a
652n/a mock = Mock(spec_set=X)
653n/a def set_attr():
654n/a mock.x = 'foo'
655n/a
656n/a mock.y = 'foo'
657n/a self.assertRaises(AttributeError, set_attr)
658n/a
659n/a
660n/a def test_copy(self):
661n/a current = sys.getrecursionlimit()
662n/a self.addCleanup(sys.setrecursionlimit, current)
663n/a
664n/a # can't use sys.maxint as this doesn't exist in Python 3
665n/a sys.setrecursionlimit(int(10e8))
666n/a # this segfaults without the fix in place
667n/a copy.copy(Mock())
668n/a
669n/a
670n/a def test_subclass_with_properties(self):
671n/a class SubClass(Mock):
672n/a def _get(self):
673n/a return 3
674n/a def _set(self, value):
675n/a raise NameError('strange error')
676n/a some_attribute = property(_get, _set)
677n/a
678n/a s = SubClass(spec_set=SubClass)
679n/a self.assertEqual(s.some_attribute, 3)
680n/a
681n/a def test():
682n/a s.some_attribute = 3
683n/a self.assertRaises(NameError, test)
684n/a
685n/a def test():
686n/a s.foo = 'bar'
687n/a self.assertRaises(AttributeError, test)
688n/a
689n/a
690n/a def test_setting_call(self):
691n/a mock = Mock()
692n/a def __call__(self, a):
693n/a return self._mock_call(a)
694n/a
695n/a type(mock).__call__ = __call__
696n/a mock('one')
697n/a mock.assert_called_with('one')
698n/a
699n/a self.assertRaises(TypeError, mock, 'one', 'two')
700n/a
701n/a
702n/a def test_dir(self):
703n/a mock = Mock()
704n/a attrs = set(dir(mock))
705n/a type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
706n/a
707n/a # all public attributes from the type are included
708n/a self.assertEqual(set(), type_attrs - attrs)
709n/a
710n/a # creates these attributes
711n/a mock.a, mock.b
712n/a self.assertIn('a', dir(mock))
713n/a self.assertIn('b', dir(mock))
714n/a
715n/a # instance attributes
716n/a mock.c = mock.d = None
717n/a self.assertIn('c', dir(mock))
718n/a self.assertIn('d', dir(mock))
719n/a
720n/a # magic methods
721n/a mock.__iter__ = lambda s: iter([])
722n/a self.assertIn('__iter__', dir(mock))
723n/a
724n/a
725n/a def test_dir_from_spec(self):
726n/a mock = Mock(spec=unittest.TestCase)
727n/a testcase_attrs = set(dir(unittest.TestCase))
728n/a attrs = set(dir(mock))
729n/a
730n/a # all attributes from the spec are included
731n/a self.assertEqual(set(), testcase_attrs - attrs)
732n/a
733n/a # shadow a sys attribute
734n/a mock.version = 3
735n/a self.assertEqual(dir(mock).count('version'), 1)
736n/a
737n/a
738n/a def test_filter_dir(self):
739n/a patcher = patch.object(mock, 'FILTER_DIR', False)
740n/a patcher.start()
741n/a try:
742n/a attrs = set(dir(Mock()))
743n/a type_attrs = set(dir(Mock))
744n/a
745n/a # ALL attributes from the type are included
746n/a self.assertEqual(set(), type_attrs - attrs)
747n/a finally:
748n/a patcher.stop()
749n/a
750n/a
751n/a def test_configure_mock(self):
752n/a mock = Mock(foo='bar')
753n/a self.assertEqual(mock.foo, 'bar')
754n/a
755n/a mock = MagicMock(foo='bar')
756n/a self.assertEqual(mock.foo, 'bar')
757n/a
758n/a kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
759n/a 'foo': MagicMock()}
760n/a mock = Mock(**kwargs)
761n/a self.assertRaises(KeyError, mock)
762n/a self.assertEqual(mock.foo.bar(), 33)
763n/a self.assertIsInstance(mock.foo, MagicMock)
764n/a
765n/a mock = Mock()
766n/a mock.configure_mock(**kwargs)
767n/a self.assertRaises(KeyError, mock)
768n/a self.assertEqual(mock.foo.bar(), 33)
769n/a self.assertIsInstance(mock.foo, MagicMock)
770n/a
771n/a
772n/a def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
773n/a # needed because assertRaisesRegex doesn't work easily with newlines
774n/a try:
775n/a func(*args, **kwargs)
776n/a except:
777n/a instance = sys.exc_info()[1]
778n/a self.assertIsInstance(instance, exception)
779n/a else:
780n/a self.fail('Exception %r not raised' % (exception,))
781n/a
782n/a msg = str(instance)
783n/a self.assertEqual(msg, message)
784n/a
785n/a
786n/a def test_assert_called_with_failure_message(self):
787n/a mock = NonCallableMock()
788n/a
789n/a expected = "mock(1, '2', 3, bar='foo')"
790n/a message = 'Expected call: %s\nNot called'
791n/a self.assertRaisesWithMsg(
792n/a AssertionError, message % (expected,),
793n/a mock.assert_called_with, 1, '2', 3, bar='foo'
794n/a )
795n/a
796n/a mock.foo(1, '2', 3, foo='foo')
797n/a
798n/a
799n/a asserters = [
800n/a mock.foo.assert_called_with, mock.foo.assert_called_once_with
801n/a ]
802n/a for meth in asserters:
803n/a actual = "foo(1, '2', 3, foo='foo')"
804n/a expected = "foo(1, '2', 3, bar='foo')"
805n/a message = 'Expected call: %s\nActual call: %s'
806n/a self.assertRaisesWithMsg(
807n/a AssertionError, message % (expected, actual),
808n/a meth, 1, '2', 3, bar='foo'
809n/a )
810n/a
811n/a # just kwargs
812n/a for meth in asserters:
813n/a actual = "foo(1, '2', 3, foo='foo')"
814n/a expected = "foo(bar='foo')"
815n/a message = 'Expected call: %s\nActual call: %s'
816n/a self.assertRaisesWithMsg(
817n/a AssertionError, message % (expected, actual),
818n/a meth, bar='foo'
819n/a )
820n/a
821n/a # just args
822n/a for meth in asserters:
823n/a actual = "foo(1, '2', 3, foo='foo')"
824n/a expected = "foo(1, 2, 3)"
825n/a message = 'Expected call: %s\nActual call: %s'
826n/a self.assertRaisesWithMsg(
827n/a AssertionError, message % (expected, actual),
828n/a meth, 1, 2, 3
829n/a )
830n/a
831n/a # empty
832n/a for meth in asserters:
833n/a actual = "foo(1, '2', 3, foo='foo')"
834n/a expected = "foo()"
835n/a message = 'Expected call: %s\nActual call: %s'
836n/a self.assertRaisesWithMsg(
837n/a AssertionError, message % (expected, actual), meth
838n/a )
839n/a
840n/a
841n/a def test_mock_calls(self):
842n/a mock = MagicMock()
843n/a
844n/a # need to do this because MagicMock.mock_calls used to just return
845n/a # a MagicMock which also returned a MagicMock when __eq__ was called
846n/a self.assertIs(mock.mock_calls == [], True)
847n/a
848n/a mock = MagicMock()
849n/a mock()
850n/a expected = [('', (), {})]
851n/a self.assertEqual(mock.mock_calls, expected)
852n/a
853n/a mock.foo()
854n/a expected.append(call.foo())
855n/a self.assertEqual(mock.mock_calls, expected)
856n/a # intermediate mock_calls work too
857n/a self.assertEqual(mock.foo.mock_calls, [('', (), {})])
858n/a
859n/a mock = MagicMock()
860n/a mock().foo(1, 2, 3, a=4, b=5)
861n/a expected = [
862n/a ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
863n/a ]
864n/a self.assertEqual(mock.mock_calls, expected)
865n/a self.assertEqual(mock.return_value.foo.mock_calls,
866n/a [('', (1, 2, 3), dict(a=4, b=5))])
867n/a self.assertEqual(mock.return_value.mock_calls,
868n/a [('foo', (1, 2, 3), dict(a=4, b=5))])
869n/a
870n/a mock = MagicMock()
871n/a mock().foo.bar().baz()
872n/a expected = [
873n/a ('', (), {}), ('().foo.bar', (), {}),
874n/a ('().foo.bar().baz', (), {})
875n/a ]
876n/a self.assertEqual(mock.mock_calls, expected)
877n/a self.assertEqual(mock().mock_calls,
878n/a call.foo.bar().baz().call_list())
879n/a
880n/a for kwargs in dict(), dict(name='bar'):
881n/a mock = MagicMock(**kwargs)
882n/a int(mock.foo)
883n/a expected = [('foo.__int__', (), {})]
884n/a self.assertEqual(mock.mock_calls, expected)
885n/a
886n/a mock = MagicMock(**kwargs)
887n/a mock.a()()
888n/a expected = [('a', (), {}), ('a()', (), {})]
889n/a self.assertEqual(mock.mock_calls, expected)
890n/a self.assertEqual(mock.a().mock_calls, [call()])
891n/a
892n/a mock = MagicMock(**kwargs)
893n/a mock(1)(2)(3)
894n/a self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
895n/a self.assertEqual(mock().mock_calls, call(2)(3).call_list())
896n/a self.assertEqual(mock()().mock_calls, call(3).call_list())
897n/a
898n/a mock = MagicMock(**kwargs)
899n/a mock(1)(2)(3).a.b.c(4)
900n/a self.assertEqual(mock.mock_calls,
901n/a call(1)(2)(3).a.b.c(4).call_list())
902n/a self.assertEqual(mock().mock_calls,
903n/a call(2)(3).a.b.c(4).call_list())
904n/a self.assertEqual(mock()().mock_calls,
905n/a call(3).a.b.c(4).call_list())
906n/a
907n/a mock = MagicMock(**kwargs)
908n/a int(mock().foo.bar().baz())
909n/a last_call = ('().foo.bar().baz().__int__', (), {})
910n/a self.assertEqual(mock.mock_calls[-1], last_call)
911n/a self.assertEqual(mock().mock_calls,
912n/a call.foo.bar().baz().__int__().call_list())
913n/a self.assertEqual(mock().foo.bar().mock_calls,
914n/a call.baz().__int__().call_list())
915n/a self.assertEqual(mock().foo.bar().baz.mock_calls,
916n/a call().__int__().call_list())
917n/a
918n/a
919n/a def test_subclassing(self):
920n/a class Subclass(Mock):
921n/a pass
922n/a
923n/a mock = Subclass()
924n/a self.assertIsInstance(mock.foo, Subclass)
925n/a self.assertIsInstance(mock(), Subclass)
926n/a
927n/a class Subclass(Mock):
928n/a def _get_child_mock(self, **kwargs):
929n/a return Mock(**kwargs)
930n/a
931n/a mock = Subclass()
932n/a self.assertNotIsInstance(mock.foo, Subclass)
933n/a self.assertNotIsInstance(mock(), Subclass)
934n/a
935n/a
936n/a def test_arg_lists(self):
937n/a mocks = [
938n/a Mock(),
939n/a MagicMock(),
940n/a NonCallableMock(),
941n/a NonCallableMagicMock()
942n/a ]
943n/a
944n/a def assert_attrs(mock):
945n/a names = 'call_args_list', 'method_calls', 'mock_calls'
946n/a for name in names:
947n/a attr = getattr(mock, name)
948n/a self.assertIsInstance(attr, _CallList)
949n/a self.assertIsInstance(attr, list)
950n/a self.assertEqual(attr, [])
951n/a
952n/a for mock in mocks:
953n/a assert_attrs(mock)
954n/a
955n/a if callable(mock):
956n/a mock()
957n/a mock(1, 2)
958n/a mock(a=3)
959n/a
960n/a mock.reset_mock()
961n/a assert_attrs(mock)
962n/a
963n/a mock.foo()
964n/a mock.foo.bar(1, a=3)
965n/a mock.foo(1).bar().baz(3)
966n/a
967n/a mock.reset_mock()
968n/a assert_attrs(mock)
969n/a
970n/a
971n/a def test_call_args_two_tuple(self):
972n/a mock = Mock()
973n/a mock(1, a=3)
974n/a mock(2, b=4)
975n/a
976n/a self.assertEqual(len(mock.call_args), 2)
977n/a args, kwargs = mock.call_args
978n/a self.assertEqual(args, (2,))
979n/a self.assertEqual(kwargs, dict(b=4))
980n/a
981n/a expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
982n/a for expected, call_args in zip(expected_list, mock.call_args_list):
983n/a self.assertEqual(len(call_args), 2)
984n/a self.assertEqual(expected[0], call_args[0])
985n/a self.assertEqual(expected[1], call_args[1])
986n/a
987n/a
988n/a def test_side_effect_iterator(self):
989n/a mock = Mock(side_effect=iter([1, 2, 3]))
990n/a self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
991n/a self.assertRaises(StopIteration, mock)
992n/a
993n/a mock = MagicMock(side_effect=['a', 'b', 'c'])
994n/a self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
995n/a self.assertRaises(StopIteration, mock)
996n/a
997n/a mock = Mock(side_effect='ghi')
998n/a self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
999n/a self.assertRaises(StopIteration, mock)
1000n/a
1001n/a class Foo(object):
1002n/a pass
1003n/a mock = MagicMock(side_effect=Foo)
1004n/a self.assertIsInstance(mock(), Foo)
1005n/a
1006n/a mock = Mock(side_effect=Iter())
1007n/a self.assertEqual([mock(), mock(), mock(), mock()],
1008n/a ['this', 'is', 'an', 'iter'])
1009n/a self.assertRaises(StopIteration, mock)
1010n/a
1011n/a
1012n/a def test_side_effect_iterator_exceptions(self):
1013n/a for Klass in Mock, MagicMock:
1014n/a iterable = (ValueError, 3, KeyError, 6)
1015n/a m = Klass(side_effect=iterable)
1016n/a self.assertRaises(ValueError, m)
1017n/a self.assertEqual(m(), 3)
1018n/a self.assertRaises(KeyError, m)
1019n/a self.assertEqual(m(), 6)
1020n/a
1021n/a
1022n/a def test_side_effect_setting_iterator(self):
1023n/a mock = Mock()
1024n/a mock.side_effect = iter([1, 2, 3])
1025n/a self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1026n/a self.assertRaises(StopIteration, mock)
1027n/a side_effect = mock.side_effect
1028n/a self.assertIsInstance(side_effect, type(iter([])))
1029n/a
1030n/a mock.side_effect = ['a', 'b', 'c']
1031n/a self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1032n/a self.assertRaises(StopIteration, mock)
1033n/a side_effect = mock.side_effect
1034n/a self.assertIsInstance(side_effect, type(iter([])))
1035n/a
1036n/a this_iter = Iter()
1037n/a mock.side_effect = this_iter
1038n/a self.assertEqual([mock(), mock(), mock(), mock()],
1039n/a ['this', 'is', 'an', 'iter'])
1040n/a self.assertRaises(StopIteration, mock)
1041n/a self.assertIs(mock.side_effect, this_iter)
1042n/a
1043n/a def test_side_effect_iterator_default(self):
1044n/a mock = Mock(return_value=2)
1045n/a mock.side_effect = iter([1, DEFAULT])
1046n/a self.assertEqual([mock(), mock()], [1, 2])
1047n/a
1048n/a def test_assert_has_calls_any_order(self):
1049n/a mock = Mock()
1050n/a mock(1, 2)
1051n/a mock(a=3)
1052n/a mock(3, 4)
1053n/a mock(b=6)
1054n/a mock(b=6)
1055n/a
1056n/a kalls = [
1057n/a call(1, 2), ({'a': 3},),
1058n/a ((3, 4),), ((), {'a': 3}),
1059n/a ('', (1, 2)), ('', {'a': 3}),
1060n/a ('', (1, 2), {}), ('', (), {'a': 3})
1061n/a ]
1062n/a for kall in kalls:
1063n/a mock.assert_has_calls([kall], any_order=True)
1064n/a
1065n/a for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1066n/a self.assertRaises(
1067n/a AssertionError, mock.assert_has_calls,
1068n/a [kall], any_order=True
1069n/a )
1070n/a
1071n/a kall_lists = [
1072n/a [call(1, 2), call(b=6)],
1073n/a [call(3, 4), call(1, 2)],
1074n/a [call(b=6), call(b=6)],
1075n/a ]
1076n/a
1077n/a for kall_list in kall_lists:
1078n/a mock.assert_has_calls(kall_list, any_order=True)
1079n/a
1080n/a kall_lists = [
1081n/a [call(b=6), call(b=6), call(b=6)],
1082n/a [call(1, 2), call(1, 2)],
1083n/a [call(3, 4), call(1, 2), call(5, 7)],
1084n/a [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1085n/a ]
1086n/a for kall_list in kall_lists:
1087n/a self.assertRaises(
1088n/a AssertionError, mock.assert_has_calls,
1089n/a kall_list, any_order=True
1090n/a )
1091n/a
1092n/a def test_assert_has_calls(self):
1093n/a kalls1 = [
1094n/a call(1, 2), ({'a': 3},),
1095n/a ((3, 4),), call(b=6),
1096n/a ('', (1,), {'b': 6}),
1097n/a ]
1098n/a kalls2 = [call.foo(), call.bar(1)]
1099n/a kalls2.extend(call.spam().baz(a=3).call_list())
1100n/a kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1101n/a
1102n/a mocks = []
1103n/a for mock in Mock(), MagicMock():
1104n/a mock(1, 2)
1105n/a mock(a=3)
1106n/a mock(3, 4)
1107n/a mock(b=6)
1108n/a mock(1, b=6)
1109n/a mocks.append((mock, kalls1))
1110n/a
1111n/a mock = Mock()
1112n/a mock.foo()
1113n/a mock.bar(1)
1114n/a mock.spam().baz(a=3)
1115n/a mock.bam(set(), foo={}).fish([1])
1116n/a mocks.append((mock, kalls2))
1117n/a
1118n/a for mock, kalls in mocks:
1119n/a for i in range(len(kalls)):
1120n/a for step in 1, 2, 3:
1121n/a these = kalls[i:i+step]
1122n/a mock.assert_has_calls(these)
1123n/a
1124n/a if len(these) > 1:
1125n/a self.assertRaises(
1126n/a AssertionError,
1127n/a mock.assert_has_calls,
1128n/a list(reversed(these))
1129n/a )
1130n/a
1131n/a
1132n/a def test_assert_has_calls_with_function_spec(self):
1133n/a def f(a, b, c, d=None):
1134n/a pass
1135n/a
1136n/a mock = Mock(spec=f)
1137n/a
1138n/a mock(1, b=2, c=3)
1139n/a mock(4, 5, c=6, d=7)
1140n/a mock(10, 11, c=12)
1141n/a calls = [
1142n/a ('', (1, 2, 3), {}),
1143n/a ('', (4, 5, 6), {'d': 7}),
1144n/a ((10, 11, 12), {}),
1145n/a ]
1146n/a mock.assert_has_calls(calls)
1147n/a mock.assert_has_calls(calls, any_order=True)
1148n/a mock.assert_has_calls(calls[1:])
1149n/a mock.assert_has_calls(calls[1:], any_order=True)
1150n/a mock.assert_has_calls(calls[:-1])
1151n/a mock.assert_has_calls(calls[:-1], any_order=True)
1152n/a # Reversed order
1153n/a calls = list(reversed(calls))
1154n/a with self.assertRaises(AssertionError):
1155n/a mock.assert_has_calls(calls)
1156n/a mock.assert_has_calls(calls, any_order=True)
1157n/a with self.assertRaises(AssertionError):
1158n/a mock.assert_has_calls(calls[1:])
1159n/a mock.assert_has_calls(calls[1:], any_order=True)
1160n/a with self.assertRaises(AssertionError):
1161n/a mock.assert_has_calls(calls[:-1])
1162n/a mock.assert_has_calls(calls[:-1], any_order=True)
1163n/a
1164n/a
1165n/a def test_assert_any_call(self):
1166n/a mock = Mock()
1167n/a mock(1, 2)
1168n/a mock(a=3)
1169n/a mock(1, b=6)
1170n/a
1171n/a mock.assert_any_call(1, 2)
1172n/a mock.assert_any_call(a=3)
1173n/a mock.assert_any_call(1, b=6)
1174n/a
1175n/a self.assertRaises(
1176n/a AssertionError,
1177n/a mock.assert_any_call
1178n/a )
1179n/a self.assertRaises(
1180n/a AssertionError,
1181n/a mock.assert_any_call,
1182n/a 1, 3
1183n/a )
1184n/a self.assertRaises(
1185n/a AssertionError,
1186n/a mock.assert_any_call,
1187n/a a=4
1188n/a )
1189n/a
1190n/a
1191n/a def test_assert_any_call_with_function_spec(self):
1192n/a def f(a, b, c, d=None):
1193n/a pass
1194n/a
1195n/a mock = Mock(spec=f)
1196n/a
1197n/a mock(1, b=2, c=3)
1198n/a mock(4, 5, c=6, d=7)
1199n/a mock.assert_any_call(1, 2, 3)
1200n/a mock.assert_any_call(a=1, b=2, c=3)
1201n/a mock.assert_any_call(4, 5, 6, 7)
1202n/a mock.assert_any_call(a=4, b=5, c=6, d=7)
1203n/a self.assertRaises(AssertionError, mock.assert_any_call,
1204n/a 1, b=3, c=2)
1205n/a # Expected call doesn't match the spec's signature
1206n/a with self.assertRaises(AssertionError) as cm:
1207n/a mock.assert_any_call(e=8)
1208n/a self.assertIsInstance(cm.exception.__cause__, TypeError)
1209n/a
1210n/a
1211n/a def test_mock_calls_create_autospec(self):
1212n/a def f(a, b):
1213n/a pass
1214n/a obj = Iter()
1215n/a obj.f = f
1216n/a
1217n/a funcs = [
1218n/a create_autospec(f),
1219n/a create_autospec(obj).f
1220n/a ]
1221n/a for func in funcs:
1222n/a func(1, 2)
1223n/a func(3, 4)
1224n/a
1225n/a self.assertEqual(
1226n/a func.mock_calls, [call(1, 2), call(3, 4)]
1227n/a )
1228n/a
1229n/a #Issue21222
1230n/a def test_create_autospec_with_name(self):
1231n/a m = mock.create_autospec(object(), name='sweet_func')
1232n/a self.assertIn('sweet_func', repr(m))
1233n/a
1234n/a #Issue21238
1235n/a def test_mock_unsafe(self):
1236n/a m = Mock()
1237n/a with self.assertRaises(AttributeError):
1238n/a m.assert_foo_call()
1239n/a with self.assertRaises(AttributeError):
1240n/a m.assret_foo_call()
1241n/a m = Mock(unsafe=True)
1242n/a m.assert_foo_call()
1243n/a m.assret_foo_call()
1244n/a
1245n/a #Issue21262
1246n/a def test_assert_not_called(self):
1247n/a m = Mock()
1248n/a m.hello.assert_not_called()
1249n/a m.hello()
1250n/a with self.assertRaises(AssertionError):
1251n/a m.hello.assert_not_called()
1252n/a
1253n/a def test_assert_called(self):
1254n/a m = Mock()
1255n/a with self.assertRaises(AssertionError):
1256n/a m.hello.assert_called()
1257n/a m.hello()
1258n/a m.hello.assert_called()
1259n/a
1260n/a m.hello()
1261n/a m.hello.assert_called()
1262n/a
1263n/a def test_assert_called_once(self):
1264n/a m = Mock()
1265n/a with self.assertRaises(AssertionError):
1266n/a m.hello.assert_called_once()
1267n/a m.hello()
1268n/a m.hello.assert_called_once()
1269n/a
1270n/a m.hello()
1271n/a with self.assertRaises(AssertionError):
1272n/a m.hello.assert_called_once()
1273n/a
1274n/a #Issue21256 printout of keyword args should be in deterministic order
1275n/a def test_sorted_call_signature(self):
1276n/a m = Mock()
1277n/a m.hello(name='hello', daddy='hero')
1278n/a text = "call(daddy='hero', name='hello')"
1279n/a self.assertEqual(repr(m.hello.call_args), text)
1280n/a
1281n/a #Issue21270 overrides tuple methods for mock.call objects
1282n/a def test_override_tuple_methods(self):
1283n/a c = call.count()
1284n/a i = call.index(132,'hello')
1285n/a m = Mock()
1286n/a m.count()
1287n/a m.index(132,"hello")
1288n/a self.assertEqual(m.method_calls[0], c)
1289n/a self.assertEqual(m.method_calls[1], i)
1290n/a
1291n/a def test_reset_return_sideeffect(self):
1292n/a m = Mock(return_value=10, side_effect=[2,3])
1293n/a m.reset_mock(return_value=True, side_effect=True)
1294n/a self.assertIsInstance(m.return_value, Mock)
1295n/a self.assertEqual(m.side_effect, None)
1296n/a
1297n/a def test_reset_return(self):
1298n/a m = Mock(return_value=10, side_effect=[2,3])
1299n/a m.reset_mock(return_value=True)
1300n/a self.assertIsInstance(m.return_value, Mock)
1301n/a self.assertNotEqual(m.side_effect, None)
1302n/a
1303n/a def test_reset_sideeffect(self):
1304n/a m = Mock(return_value=10, side_effect=[2,3])
1305n/a m.reset_mock(side_effect=True)
1306n/a self.assertEqual(m.return_value, 10)
1307n/a self.assertEqual(m.side_effect, None)
1308n/a
1309n/a def test_mock_add_spec(self):
1310n/a class _One(object):
1311n/a one = 1
1312n/a class _Two(object):
1313n/a two = 2
1314n/a class Anything(object):
1315n/a one = two = three = 'four'
1316n/a
1317n/a klasses = [
1318n/a Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1319n/a ]
1320n/a for Klass in list(klasses):
1321n/a klasses.append(lambda K=Klass: K(spec=Anything))
1322n/a klasses.append(lambda K=Klass: K(spec_set=Anything))
1323n/a
1324n/a for Klass in klasses:
1325n/a for kwargs in dict(), dict(spec_set=True):
1326n/a mock = Klass()
1327n/a #no error
1328n/a mock.one, mock.two, mock.three
1329n/a
1330n/a for One, Two in [(_One, _Two), (['one'], ['two'])]:
1331n/a for kwargs in dict(), dict(spec_set=True):
1332n/a mock.mock_add_spec(One, **kwargs)
1333n/a
1334n/a mock.one
1335n/a self.assertRaises(
1336n/a AttributeError, getattr, mock, 'two'
1337n/a )
1338n/a self.assertRaises(
1339n/a AttributeError, getattr, mock, 'three'
1340n/a )
1341n/a if 'spec_set' in kwargs:
1342n/a self.assertRaises(
1343n/a AttributeError, setattr, mock, 'three', None
1344n/a )
1345n/a
1346n/a mock.mock_add_spec(Two, **kwargs)
1347n/a self.assertRaises(
1348n/a AttributeError, getattr, mock, 'one'
1349n/a )
1350n/a mock.two
1351n/a self.assertRaises(
1352n/a AttributeError, getattr, mock, 'three'
1353n/a )
1354n/a if 'spec_set' in kwargs:
1355n/a self.assertRaises(
1356n/a AttributeError, setattr, mock, 'three', None
1357n/a )
1358n/a # note that creating a mock, setting an instance attribute, and
1359n/a # *then* setting a spec doesn't work. Not the intended use case
1360n/a
1361n/a
1362n/a def test_mock_add_spec_magic_methods(self):
1363n/a for Klass in MagicMock, NonCallableMagicMock:
1364n/a mock = Klass()
1365n/a int(mock)
1366n/a
1367n/a mock.mock_add_spec(object)
1368n/a self.assertRaises(TypeError, int, mock)
1369n/a
1370n/a mock = Klass()
1371n/a mock['foo']
1372n/a mock.__int__.return_value =4
1373n/a
1374n/a mock.mock_add_spec(int)
1375n/a self.assertEqual(int(mock), 4)
1376n/a self.assertRaises(TypeError, lambda: mock['foo'])
1377n/a
1378n/a
1379n/a def test_adding_child_mock(self):
1380n/a for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1381n/a mock = Klass()
1382n/a
1383n/a mock.foo = Mock()
1384n/a mock.foo()
1385n/a
1386n/a self.assertEqual(mock.method_calls, [call.foo()])
1387n/a self.assertEqual(mock.mock_calls, [call.foo()])
1388n/a
1389n/a mock = Klass()
1390n/a mock.bar = Mock(name='name')
1391n/a mock.bar()
1392n/a self.assertEqual(mock.method_calls, [])
1393n/a self.assertEqual(mock.mock_calls, [])
1394n/a
1395n/a # mock with an existing _new_parent but no name
1396n/a mock = Klass()
1397n/a mock.baz = MagicMock()()
1398n/a mock.baz()
1399n/a self.assertEqual(mock.method_calls, [])
1400n/a self.assertEqual(mock.mock_calls, [])
1401n/a
1402n/a
1403n/a def test_adding_return_value_mock(self):
1404n/a for Klass in Mock, MagicMock:
1405n/a mock = Klass()
1406n/a mock.return_value = MagicMock()
1407n/a
1408n/a mock()()
1409n/a self.assertEqual(mock.mock_calls, [call(), call()()])
1410n/a
1411n/a
1412n/a def test_manager_mock(self):
1413n/a class Foo(object):
1414n/a one = 'one'
1415n/a two = 'two'
1416n/a manager = Mock()
1417n/a p1 = patch.object(Foo, 'one')
1418n/a p2 = patch.object(Foo, 'two')
1419n/a
1420n/a mock_one = p1.start()
1421n/a self.addCleanup(p1.stop)
1422n/a mock_two = p2.start()
1423n/a self.addCleanup(p2.stop)
1424n/a
1425n/a manager.attach_mock(mock_one, 'one')
1426n/a manager.attach_mock(mock_two, 'two')
1427n/a
1428n/a Foo.two()
1429n/a Foo.one()
1430n/a
1431n/a self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1432n/a
1433n/a
1434n/a def test_magic_methods_mock_calls(self):
1435n/a for Klass in Mock, MagicMock:
1436n/a m = Klass()
1437n/a m.__int__ = Mock(return_value=3)
1438n/a m.__float__ = MagicMock(return_value=3.0)
1439n/a int(m)
1440n/a float(m)
1441n/a
1442n/a self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1443n/a self.assertEqual(m.method_calls, [])
1444n/a
1445n/a def test_mock_open_reuse_issue_21750(self):
1446n/a mocked_open = mock.mock_open(read_data='data')
1447n/a f1 = mocked_open('a-name')
1448n/a f1_data = f1.read()
1449n/a f2 = mocked_open('another-name')
1450n/a f2_data = f2.read()
1451n/a self.assertEqual(f1_data, f2_data)
1452n/a
1453n/a def test_mock_open_write(self):
1454n/a # Test exception in file writing write()
1455n/a mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1456n/a with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1457n/a mock_filehandle = mock_namedtemp.return_value
1458n/a mock_write = mock_filehandle.write
1459n/a mock_write.side_effect = OSError('Test 2 Error')
1460n/a def attempt():
1461n/a tempfile.NamedTemporaryFile().write('asd')
1462n/a self.assertRaises(OSError, attempt)
1463n/a
1464n/a def test_mock_open_alter_readline(self):
1465n/a mopen = mock.mock_open(read_data='foo\nbarn')
1466n/a mopen.return_value.readline.side_effect = lambda *args:'abc'
1467n/a first = mopen().readline()
1468n/a second = mopen().readline()
1469n/a self.assertEqual('abc', first)
1470n/a self.assertEqual('abc', second)
1471n/a
1472n/a def test_mock_open_after_eof(self):
1473n/a # read, readline and readlines should work after end of file.
1474n/a _open = mock.mock_open(read_data='foo')
1475n/a h = _open('bar')
1476n/a h.read()
1477n/a self.assertEqual('', h.read())
1478n/a self.assertEqual('', h.read())
1479n/a self.assertEqual('', h.readline())
1480n/a self.assertEqual('', h.readline())
1481n/a self.assertEqual([], h.readlines())
1482n/a self.assertEqual([], h.readlines())
1483n/a
1484n/a def test_mock_parents(self):
1485n/a for Klass in Mock, MagicMock:
1486n/a m = Klass()
1487n/a original_repr = repr(m)
1488n/a m.return_value = m
1489n/a self.assertIs(m(), m)
1490n/a self.assertEqual(repr(m), original_repr)
1491n/a
1492n/a m.reset_mock()
1493n/a self.assertIs(m(), m)
1494n/a self.assertEqual(repr(m), original_repr)
1495n/a
1496n/a m = Klass()
1497n/a m.b = m.a
1498n/a self.assertIn("name='mock.a'", repr(m.b))
1499n/a self.assertIn("name='mock.a'", repr(m.a))
1500n/a m.reset_mock()
1501n/a self.assertIn("name='mock.a'", repr(m.b))
1502n/a self.assertIn("name='mock.a'", repr(m.a))
1503n/a
1504n/a m = Klass()
1505n/a original_repr = repr(m)
1506n/a m.a = m()
1507n/a m.a.return_value = m
1508n/a
1509n/a self.assertEqual(repr(m), original_repr)
1510n/a self.assertEqual(repr(m.a()), original_repr)
1511n/a
1512n/a
1513n/a def test_attach_mock(self):
1514n/a classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1515n/a for Klass in classes:
1516n/a for Klass2 in classes:
1517n/a m = Klass()
1518n/a
1519n/a m2 = Klass2(name='foo')
1520n/a m.attach_mock(m2, 'bar')
1521n/a
1522n/a self.assertIs(m.bar, m2)
1523n/a self.assertIn("name='mock.bar'", repr(m2))
1524n/a
1525n/a m.bar.baz(1)
1526n/a self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1527n/a self.assertEqual(m.method_calls, [call.bar.baz(1)])
1528n/a
1529n/a
1530n/a def test_attach_mock_return_value(self):
1531n/a classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1532n/a for Klass in Mock, MagicMock:
1533n/a for Klass2 in classes:
1534n/a m = Klass()
1535n/a
1536n/a m2 = Klass2(name='foo')
1537n/a m.attach_mock(m2, 'return_value')
1538n/a
1539n/a self.assertIs(m(), m2)
1540n/a self.assertIn("name='mock()'", repr(m2))
1541n/a
1542n/a m2.foo()
1543n/a self.assertEqual(m.mock_calls, call().foo().call_list())
1544n/a
1545n/a
1546n/a def test_attribute_deletion(self):
1547n/a for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1548n/a NonCallableMock()):
1549n/a self.assertTrue(hasattr(mock, 'm'))
1550n/a
1551n/a del mock.m
1552n/a self.assertFalse(hasattr(mock, 'm'))
1553n/a
1554n/a del mock.f
1555n/a self.assertFalse(hasattr(mock, 'f'))
1556n/a self.assertRaises(AttributeError, getattr, mock, 'f')
1557n/a
1558n/a
1559n/a def test_class_assignable(self):
1560n/a for mock in Mock(), MagicMock():
1561n/a self.assertNotIsInstance(mock, int)
1562n/a
1563n/a mock.__class__ = int
1564n/a self.assertIsInstance(mock, int)
1565n/a mock.foo
1566n/a
1567n/a
1568n/aif __name__ == '__main__':
1569n/a unittest.main()