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

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

#countcontent
1n/aimport unittest
2n/aimport sys
3n/afrom unittest.mock import Mock, MagicMock, _magics
4n/a
5n/a
6n/a
7n/aclass TestMockingMagicMethods(unittest.TestCase):
8n/a
9n/a def test_deleting_magic_methods(self):
10n/a mock = Mock()
11n/a self.assertFalse(hasattr(mock, '__getitem__'))
12n/a
13n/a mock.__getitem__ = Mock()
14n/a self.assertTrue(hasattr(mock, '__getitem__'))
15n/a
16n/a del mock.__getitem__
17n/a self.assertFalse(hasattr(mock, '__getitem__'))
18n/a
19n/a
20n/a def test_magicmock_del(self):
21n/a mock = MagicMock()
22n/a # before using getitem
23n/a del mock.__getitem__
24n/a self.assertRaises(TypeError, lambda: mock['foo'])
25n/a
26n/a mock = MagicMock()
27n/a # this time use it first
28n/a mock['foo']
29n/a del mock.__getitem__
30n/a self.assertRaises(TypeError, lambda: mock['foo'])
31n/a
32n/a
33n/a def test_magic_method_wrapping(self):
34n/a mock = Mock()
35n/a def f(self, name):
36n/a return self, 'fish'
37n/a
38n/a mock.__getitem__ = f
39n/a self.assertIsNot(mock.__getitem__, f)
40n/a self.assertEqual(mock['foo'], (mock, 'fish'))
41n/a self.assertEqual(mock.__getitem__('foo'), (mock, 'fish'))
42n/a
43n/a mock.__getitem__ = mock
44n/a self.assertIs(mock.__getitem__, mock)
45n/a
46n/a
47n/a def test_magic_methods_isolated_between_mocks(self):
48n/a mock1 = Mock()
49n/a mock2 = Mock()
50n/a
51n/a mock1.__iter__ = Mock(return_value=iter([]))
52n/a self.assertEqual(list(mock1), [])
53n/a self.assertRaises(TypeError, lambda: list(mock2))
54n/a
55n/a
56n/a def test_repr(self):
57n/a mock = Mock()
58n/a self.assertEqual(repr(mock), "<Mock id='%s'>" % id(mock))
59n/a mock.__repr__ = lambda s: 'foo'
60n/a self.assertEqual(repr(mock), 'foo')
61n/a
62n/a
63n/a def test_str(self):
64n/a mock = Mock()
65n/a self.assertEqual(str(mock), object.__str__(mock))
66n/a mock.__str__ = lambda s: 'foo'
67n/a self.assertEqual(str(mock), 'foo')
68n/a
69n/a
70n/a def test_dict_methods(self):
71n/a mock = Mock()
72n/a
73n/a self.assertRaises(TypeError, lambda: mock['foo'])
74n/a def _del():
75n/a del mock['foo']
76n/a def _set():
77n/a mock['foo'] = 3
78n/a self.assertRaises(TypeError, _del)
79n/a self.assertRaises(TypeError, _set)
80n/a
81n/a _dict = {}
82n/a def getitem(s, name):
83n/a return _dict[name]
84n/a def setitem(s, name, value):
85n/a _dict[name] = value
86n/a def delitem(s, name):
87n/a del _dict[name]
88n/a
89n/a mock.__setitem__ = setitem
90n/a mock.__getitem__ = getitem
91n/a mock.__delitem__ = delitem
92n/a
93n/a self.assertRaises(KeyError, lambda: mock['foo'])
94n/a mock['foo'] = 'bar'
95n/a self.assertEqual(_dict, {'foo': 'bar'})
96n/a self.assertEqual(mock['foo'], 'bar')
97n/a del mock['foo']
98n/a self.assertEqual(_dict, {})
99n/a
100n/a
101n/a def test_numeric(self):
102n/a original = mock = Mock()
103n/a mock.value = 0
104n/a
105n/a self.assertRaises(TypeError, lambda: mock + 3)
106n/a
107n/a def add(self, other):
108n/a mock.value += other
109n/a return self
110n/a mock.__add__ = add
111n/a self.assertEqual(mock + 3, mock)
112n/a self.assertEqual(mock.value, 3)
113n/a
114n/a del mock.__add__
115n/a def iadd(mock):
116n/a mock += 3
117n/a self.assertRaises(TypeError, iadd, mock)
118n/a mock.__iadd__ = add
119n/a mock += 6
120n/a self.assertEqual(mock, original)
121n/a self.assertEqual(mock.value, 9)
122n/a
123n/a self.assertRaises(TypeError, lambda: 3 + mock)
124n/a mock.__radd__ = add
125n/a self.assertEqual(7 + mock, mock)
126n/a self.assertEqual(mock.value, 16)
127n/a
128n/a def test_division(self):
129n/a original = mock = Mock()
130n/a mock.value = 32
131n/a self.assertRaises(TypeError, lambda: mock / 2)
132n/a
133n/a def truediv(self, other):
134n/a mock.value /= other
135n/a return self
136n/a mock.__truediv__ = truediv
137n/a self.assertEqual(mock / 2, mock)
138n/a self.assertEqual(mock.value, 16)
139n/a
140n/a del mock.__truediv__
141n/a def itruediv(mock):
142n/a mock /= 4
143n/a self.assertRaises(TypeError, itruediv, mock)
144n/a mock.__itruediv__ = truediv
145n/a mock /= 8
146n/a self.assertEqual(mock, original)
147n/a self.assertEqual(mock.value, 2)
148n/a
149n/a self.assertRaises(TypeError, lambda: 8 / mock)
150n/a mock.__rtruediv__ = truediv
151n/a self.assertEqual(0.5 / mock, mock)
152n/a self.assertEqual(mock.value, 4)
153n/a
154n/a def test_hash(self):
155n/a mock = Mock()
156n/a # test delegation
157n/a self.assertEqual(hash(mock), Mock.__hash__(mock))
158n/a
159n/a def _hash(s):
160n/a return 3
161n/a mock.__hash__ = _hash
162n/a self.assertEqual(hash(mock), 3)
163n/a
164n/a
165n/a def test_nonzero(self):
166n/a m = Mock()
167n/a self.assertTrue(bool(m))
168n/a
169n/a m.__bool__ = lambda s: False
170n/a self.assertFalse(bool(m))
171n/a
172n/a
173n/a def test_comparison(self):
174n/a mock = Mock()
175n/a def comp(s, o):
176n/a return True
177n/a mock.__lt__ = mock.__gt__ = mock.__le__ = mock.__ge__ = comp
178n/a self. assertTrue(mock < 3)
179n/a self. assertTrue(mock > 3)
180n/a self. assertTrue(mock <= 3)
181n/a self. assertTrue(mock >= 3)
182n/a
183n/a self.assertRaises(TypeError, lambda: MagicMock() < object())
184n/a self.assertRaises(TypeError, lambda: object() < MagicMock())
185n/a self.assertRaises(TypeError, lambda: MagicMock() < MagicMock())
186n/a self.assertRaises(TypeError, lambda: MagicMock() > object())
187n/a self.assertRaises(TypeError, lambda: object() > MagicMock())
188n/a self.assertRaises(TypeError, lambda: MagicMock() > MagicMock())
189n/a self.assertRaises(TypeError, lambda: MagicMock() <= object())
190n/a self.assertRaises(TypeError, lambda: object() <= MagicMock())
191n/a self.assertRaises(TypeError, lambda: MagicMock() <= MagicMock())
192n/a self.assertRaises(TypeError, lambda: MagicMock() >= object())
193n/a self.assertRaises(TypeError, lambda: object() >= MagicMock())
194n/a self.assertRaises(TypeError, lambda: MagicMock() >= MagicMock())
195n/a
196n/a
197n/a def test_equality(self):
198n/a for mock in Mock(), MagicMock():
199n/a self.assertEqual(mock == mock, True)
200n/a self.assertIsInstance(mock == mock, bool)
201n/a self.assertEqual(mock != mock, False)
202n/a self.assertIsInstance(mock != mock, bool)
203n/a self.assertEqual(mock == object(), False)
204n/a self.assertEqual(mock != object(), True)
205n/a
206n/a def eq(self, other):
207n/a return other == 3
208n/a mock.__eq__ = eq
209n/a self.assertTrue(mock == 3)
210n/a self.assertFalse(mock == 4)
211n/a
212n/a def ne(self, other):
213n/a return other == 3
214n/a mock.__ne__ = ne
215n/a self.assertTrue(mock != 3)
216n/a self.assertFalse(mock != 4)
217n/a
218n/a mock = MagicMock()
219n/a mock.__eq__.return_value = True
220n/a self.assertIsInstance(mock == 3, bool)
221n/a self.assertEqual(mock == 3, True)
222n/a
223n/a mock.__ne__.return_value = False
224n/a self.assertIsInstance(mock != 3, bool)
225n/a self.assertEqual(mock != 3, False)
226n/a
227n/a
228n/a def test_len_contains_iter(self):
229n/a mock = Mock()
230n/a
231n/a self.assertRaises(TypeError, len, mock)
232n/a self.assertRaises(TypeError, iter, mock)
233n/a self.assertRaises(TypeError, lambda: 'foo' in mock)
234n/a
235n/a mock.__len__ = lambda s: 6
236n/a self.assertEqual(len(mock), 6)
237n/a
238n/a mock.__contains__ = lambda s, o: o == 3
239n/a self.assertIn(3, mock)
240n/a self.assertNotIn(6, mock)
241n/a
242n/a mock.__iter__ = lambda s: iter('foobarbaz')
243n/a self.assertEqual(list(mock), list('foobarbaz'))
244n/a
245n/a
246n/a def test_magicmock(self):
247n/a mock = MagicMock()
248n/a
249n/a mock.__iter__.return_value = iter([1, 2, 3])
250n/a self.assertEqual(list(mock), [1, 2, 3])
251n/a
252n/a getattr(mock, '__bool__').return_value = False
253n/a self.assertFalse(hasattr(mock, '__nonzero__'))
254n/a self.assertFalse(bool(mock))
255n/a
256n/a for entry in _magics:
257n/a self.assertTrue(hasattr(mock, entry))
258n/a self.assertFalse(hasattr(mock, '__imaginery__'))
259n/a
260n/a
261n/a def test_magic_mock_equality(self):
262n/a mock = MagicMock()
263n/a self.assertIsInstance(mock == object(), bool)
264n/a self.assertIsInstance(mock != object(), bool)
265n/a
266n/a self.assertEqual(mock == object(), False)
267n/a self.assertEqual(mock != object(), True)
268n/a self.assertEqual(mock == mock, True)
269n/a self.assertEqual(mock != mock, False)
270n/a
271n/a
272n/a def test_magicmock_defaults(self):
273n/a mock = MagicMock()
274n/a self.assertEqual(int(mock), 1)
275n/a self.assertEqual(complex(mock), 1j)
276n/a self.assertEqual(float(mock), 1.0)
277n/a self.assertNotIn(object(), mock)
278n/a self.assertEqual(len(mock), 0)
279n/a self.assertEqual(list(mock), [])
280n/a self.assertEqual(hash(mock), object.__hash__(mock))
281n/a self.assertEqual(str(mock), object.__str__(mock))
282n/a self.assertTrue(bool(mock))
283n/a
284n/a # in Python 3 oct and hex use __index__
285n/a # so these tests are for __index__ in py3k
286n/a self.assertEqual(oct(mock), '0o1')
287n/a self.assertEqual(hex(mock), '0x1')
288n/a # how to test __sizeof__ ?
289n/a
290n/a
291n/a def test_magic_methods_and_spec(self):
292n/a class Iterable(object):
293n/a def __iter__(self):
294n/a pass
295n/a
296n/a mock = Mock(spec=Iterable)
297n/a self.assertRaises(AttributeError, lambda: mock.__iter__)
298n/a
299n/a mock.__iter__ = Mock(return_value=iter([]))
300n/a self.assertEqual(list(mock), [])
301n/a
302n/a class NonIterable(object):
303n/a pass
304n/a mock = Mock(spec=NonIterable)
305n/a self.assertRaises(AttributeError, lambda: mock.__iter__)
306n/a
307n/a def set_int():
308n/a mock.__int__ = Mock(return_value=iter([]))
309n/a self.assertRaises(AttributeError, set_int)
310n/a
311n/a mock = MagicMock(spec=Iterable)
312n/a self.assertEqual(list(mock), [])
313n/a self.assertRaises(AttributeError, set_int)
314n/a
315n/a
316n/a def test_magic_methods_and_spec_set(self):
317n/a class Iterable(object):
318n/a def __iter__(self):
319n/a pass
320n/a
321n/a mock = Mock(spec_set=Iterable)
322n/a self.assertRaises(AttributeError, lambda: mock.__iter__)
323n/a
324n/a mock.__iter__ = Mock(return_value=iter([]))
325n/a self.assertEqual(list(mock), [])
326n/a
327n/a class NonIterable(object):
328n/a pass
329n/a mock = Mock(spec_set=NonIterable)
330n/a self.assertRaises(AttributeError, lambda: mock.__iter__)
331n/a
332n/a def set_int():
333n/a mock.__int__ = Mock(return_value=iter([]))
334n/a self.assertRaises(AttributeError, set_int)
335n/a
336n/a mock = MagicMock(spec_set=Iterable)
337n/a self.assertEqual(list(mock), [])
338n/a self.assertRaises(AttributeError, set_int)
339n/a
340n/a
341n/a def test_setting_unsupported_magic_method(self):
342n/a mock = MagicMock()
343n/a def set_setattr():
344n/a mock.__setattr__ = lambda self, name: None
345n/a self.assertRaisesRegex(AttributeError,
346n/a "Attempting to set unsupported magic method '__setattr__'.",
347n/a set_setattr
348n/a )
349n/a
350n/a
351n/a def test_attributes_and_return_value(self):
352n/a mock = MagicMock()
353n/a attr = mock.foo
354n/a def _get_type(obj):
355n/a # the type of every mock (or magicmock) is a custom subclass
356n/a # so the real type is the second in the mro
357n/a return type(obj).__mro__[1]
358n/a self.assertEqual(_get_type(attr), MagicMock)
359n/a
360n/a returned = mock()
361n/a self.assertEqual(_get_type(returned), MagicMock)
362n/a
363n/a
364n/a def test_magic_methods_are_magic_mocks(self):
365n/a mock = MagicMock()
366n/a self.assertIsInstance(mock.__getitem__, MagicMock)
367n/a
368n/a mock[1][2].__getitem__.return_value = 3
369n/a self.assertEqual(mock[1][2][3], 3)
370n/a
371n/a
372n/a def test_magic_method_reset_mock(self):
373n/a mock = MagicMock()
374n/a str(mock)
375n/a self.assertTrue(mock.__str__.called)
376n/a mock.reset_mock()
377n/a self.assertFalse(mock.__str__.called)
378n/a
379n/a
380n/a def test_dir(self):
381n/a # overriding the default implementation
382n/a for mock in Mock(), MagicMock():
383n/a def _dir(self):
384n/a return ['foo']
385n/a mock.__dir__ = _dir
386n/a self.assertEqual(dir(mock), ['foo'])
387n/a
388n/a
389n/a @unittest.skipIf('PyPy' in sys.version, "This fails differently on pypy")
390n/a def test_bound_methods(self):
391n/a m = Mock()
392n/a
393n/a # XXXX should this be an expected failure instead?
394n/a
395n/a # this seems like it should work, but is hard to do without introducing
396n/a # other api inconsistencies. Failure message could be better though.
397n/a m.__iter__ = [3].__iter__
398n/a self.assertRaises(TypeError, iter, m)
399n/a
400n/a
401n/a def test_magic_method_type(self):
402n/a class Foo(MagicMock):
403n/a pass
404n/a
405n/a foo = Foo()
406n/a self.assertIsInstance(foo.__int__, Foo)
407n/a
408n/a
409n/a def test_descriptor_from_class(self):
410n/a m = MagicMock()
411n/a type(m).__str__.return_value = 'foo'
412n/a self.assertEqual(str(m), 'foo')
413n/a
414n/a
415n/a def test_iterable_as_iter_return_value(self):
416n/a m = MagicMock()
417n/a m.__iter__.return_value = [1, 2, 3]
418n/a self.assertEqual(list(m), [1, 2, 3])
419n/a self.assertEqual(list(m), [1, 2, 3])
420n/a
421n/a m.__iter__.return_value = iter([4, 5, 6])
422n/a self.assertEqual(list(m), [4, 5, 6])
423n/a self.assertEqual(list(m), [])
424n/a
425n/a
426n/a def test_matmul(self):
427n/a m = MagicMock()
428n/a self.assertIsInstance(m @ 1, MagicMock)
429n/a m.__matmul__.return_value = 42
430n/a m.__rmatmul__.return_value = 666
431n/a m.__imatmul__.return_value = 24
432n/a self.assertEqual(m @ 1, 42)
433n/a self.assertEqual(1 @ m, 666)
434n/a m @= 24
435n/a self.assertEqual(m, 24)
436n/a
437n/a def test_divmod_and_rdivmod(self):
438n/a m = MagicMock()
439n/a self.assertIsInstance(divmod(5, m), MagicMock)
440n/a m.__divmod__.return_value = (2, 1)
441n/a self.assertEqual(divmod(m, 2), (2, 1))
442n/a m = MagicMock()
443n/a foo = divmod(2, m)
444n/a self.assertIsInstance(foo, MagicMock)
445n/a foo_direct = m.__divmod__(2)
446n/a self.assertIsInstance(foo_direct, MagicMock)
447n/a bar = divmod(m, 2)
448n/a self.assertIsInstance(bar, MagicMock)
449n/a bar_direct = m.__rdivmod__(2)
450n/a self.assertIsInstance(bar_direct, MagicMock)
451n/a
452n/a # http://bugs.python.org/issue23310
453n/a # Check if you can change behaviour of magic methds in MagicMock init
454n/a def test_magic_in_initialization(self):
455n/a m = MagicMock(**{'__str__.return_value': "12"})
456n/a self.assertEqual(str(m), "12")
457n/a
458n/a def test_changing_magic_set_in_initialization(self):
459n/a m = MagicMock(**{'__str__.return_value': "12"})
460n/a m.__str__.return_value = "13"
461n/a self.assertEqual(str(m), "13")
462n/a m = MagicMock(**{'__str__.return_value': "12"})
463n/a m.configure_mock(**{'__str__.return_value': "14"})
464n/a self.assertEqual(str(m), "14")
465n/a
466n/a
467n/aif __name__ == '__main__':
468n/a unittest.main()