Plex plugin to to play various online streams (mostly Latvian).

testmagicmethods.py 16KB

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