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

testpatch.py 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  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. import os
  5. import sys
  6. import six
  7. import unittest2 as unittest
  8. from mock.tests import support
  9. from mock.tests.support import SomeClass, is_instance, callable
  10. from mock import (
  11. NonCallableMock, CallableMixin, patch, sentinel,
  12. MagicMock, Mock, NonCallableMagicMock, patch,
  13. DEFAULT, call
  14. )
  15. from mock.mock import _patch, _get_target
  16. builtin_string = '__builtin__'
  17. if six.PY3:
  18. builtin_string = 'builtins'
  19. unicode = str
  20. PTModule = sys.modules[__name__]
  21. MODNAME = '%s.PTModule' % __name__
  22. def _get_proxy(obj, get_only=True):
  23. class Proxy(object):
  24. def __getattr__(self, name):
  25. return getattr(obj, name)
  26. if not get_only:
  27. def __setattr__(self, name, value):
  28. setattr(obj, name, value)
  29. def __delattr__(self, name):
  30. delattr(obj, name)
  31. Proxy.__setattr__ = __setattr__
  32. Proxy.__delattr__ = __delattr__
  33. return Proxy()
  34. # for use in the test
  35. something = sentinel.Something
  36. something_else = sentinel.SomethingElse
  37. class Foo(object):
  38. def __init__(self, a):
  39. pass
  40. def f(self, a):
  41. pass
  42. def g(self):
  43. pass
  44. foo = 'bar'
  45. class Bar(object):
  46. def a(self):
  47. pass
  48. foo_name = '%s.Foo' % __name__
  49. def function(a, b=Foo):
  50. pass
  51. class Container(object):
  52. def __init__(self):
  53. self.values = {}
  54. def __getitem__(self, name):
  55. return self.values[name]
  56. def __setitem__(self, name, value):
  57. self.values[name] = value
  58. def __delitem__(self, name):
  59. del self.values[name]
  60. def __iter__(self):
  61. return iter(self.values)
  62. class PatchTest(unittest.TestCase):
  63. def assertNotCallable(self, obj, magic=True):
  64. MockClass = NonCallableMagicMock
  65. if not magic:
  66. MockClass = NonCallableMock
  67. self.assertRaises(TypeError, obj)
  68. self.assertTrue(is_instance(obj, MockClass))
  69. self.assertFalse(is_instance(obj, CallableMixin))
  70. def test_single_patchobject(self):
  71. class Something(object):
  72. attribute = sentinel.Original
  73. @patch.object(Something, 'attribute', sentinel.Patched)
  74. def test():
  75. self.assertEqual(Something.attribute, sentinel.Patched, "unpatched")
  76. test()
  77. self.assertEqual(Something.attribute, sentinel.Original,
  78. "patch not restored")
  79. def test_patchobject_with_none(self):
  80. class Something(object):
  81. attribute = sentinel.Original
  82. @patch.object(Something, 'attribute', None)
  83. def test():
  84. self.assertIsNone(Something.attribute, "unpatched")
  85. test()
  86. self.assertEqual(Something.attribute, sentinel.Original,
  87. "patch not restored")
  88. def test_multiple_patchobject(self):
  89. class Something(object):
  90. attribute = sentinel.Original
  91. next_attribute = sentinel.Original2
  92. @patch.object(Something, 'attribute', sentinel.Patched)
  93. @patch.object(Something, 'next_attribute', sentinel.Patched2)
  94. def test():
  95. self.assertEqual(Something.attribute, sentinel.Patched,
  96. "unpatched")
  97. self.assertEqual(Something.next_attribute, sentinel.Patched2,
  98. "unpatched")
  99. test()
  100. self.assertEqual(Something.attribute, sentinel.Original,
  101. "patch not restored")
  102. self.assertEqual(Something.next_attribute, sentinel.Original2,
  103. "patch not restored")
  104. def test_object_lookup_is_quite_lazy(self):
  105. global something
  106. original = something
  107. @patch('%s.something' % __name__, sentinel.Something2)
  108. def test():
  109. pass
  110. try:
  111. something = sentinel.replacement_value
  112. test()
  113. self.assertEqual(something, sentinel.replacement_value)
  114. finally:
  115. something = original
  116. def test_patch(self):
  117. @patch('%s.something' % __name__, sentinel.Something2)
  118. def test():
  119. self.assertEqual(PTModule.something, sentinel.Something2,
  120. "unpatched")
  121. test()
  122. self.assertEqual(PTModule.something, sentinel.Something,
  123. "patch not restored")
  124. @patch('%s.something' % __name__, sentinel.Something2)
  125. @patch('%s.something_else' % __name__, sentinel.SomethingElse)
  126. def test():
  127. self.assertEqual(PTModule.something, sentinel.Something2,
  128. "unpatched")
  129. self.assertEqual(PTModule.something_else, sentinel.SomethingElse,
  130. "unpatched")
  131. self.assertEqual(PTModule.something, sentinel.Something,
  132. "patch not restored")
  133. self.assertEqual(PTModule.something_else, sentinel.SomethingElse,
  134. "patch not restored")
  135. # Test the patching and restoring works a second time
  136. test()
  137. self.assertEqual(PTModule.something, sentinel.Something,
  138. "patch not restored")
  139. self.assertEqual(PTModule.something_else, sentinel.SomethingElse,
  140. "patch not restored")
  141. mock = Mock()
  142. mock.return_value = sentinel.Handle
  143. @patch('%s.open' % builtin_string, mock)
  144. def test():
  145. self.assertEqual(open('filename', 'r'), sentinel.Handle,
  146. "open not patched")
  147. test()
  148. test()
  149. self.assertNotEqual(open, mock, "patch not restored")
  150. def test_patch_class_attribute(self):
  151. @patch('%s.SomeClass.class_attribute' % __name__,
  152. sentinel.ClassAttribute)
  153. def test():
  154. self.assertEqual(PTModule.SomeClass.class_attribute,
  155. sentinel.ClassAttribute, "unpatched")
  156. test()
  157. self.assertIsNone(PTModule.SomeClass.class_attribute,
  158. "patch not restored")
  159. def test_patchobject_with_default_mock(self):
  160. class Test(object):
  161. something = sentinel.Original
  162. something2 = sentinel.Original2
  163. @patch.object(Test, 'something')
  164. def test(mock):
  165. self.assertEqual(mock, Test.something,
  166. "Mock not passed into test function")
  167. self.assertIsInstance(mock, MagicMock,
  168. "patch with two arguments did not create a mock")
  169. test()
  170. @patch.object(Test, 'something')
  171. @patch.object(Test, 'something2')
  172. def test(this1, this2, mock1, mock2):
  173. self.assertEqual(this1, sentinel.this1,
  174. "Patched function didn't receive initial argument")
  175. self.assertEqual(this2, sentinel.this2,
  176. "Patched function didn't receive second argument")
  177. self.assertEqual(mock1, Test.something2,
  178. "Mock not passed into test function")
  179. self.assertEqual(mock2, Test.something,
  180. "Second Mock not passed into test function")
  181. self.assertIsInstance(mock2, MagicMock,
  182. "patch with two arguments did not create a mock")
  183. self.assertIsInstance(mock2, MagicMock,
  184. "patch with two arguments did not create a mock")
  185. # A hack to test that new mocks are passed the second time
  186. self.assertNotEqual(outerMock1, mock1, "unexpected value for mock1")
  187. self.assertNotEqual(outerMock2, mock2, "unexpected value for mock1")
  188. return mock1, mock2
  189. outerMock1 = outerMock2 = None
  190. outerMock1, outerMock2 = test(sentinel.this1, sentinel.this2)
  191. # Test that executing a second time creates new mocks
  192. test(sentinel.this1, sentinel.this2)
  193. def test_patch_with_spec(self):
  194. @patch('%s.SomeClass' % __name__, spec=SomeClass)
  195. def test(MockSomeClass):
  196. self.assertEqual(SomeClass, MockSomeClass)
  197. self.assertTrue(is_instance(SomeClass.wibble, MagicMock))
  198. self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)
  199. test()
  200. def test_patchobject_with_spec(self):
  201. @patch.object(SomeClass, 'class_attribute', spec=SomeClass)
  202. def test(MockAttribute):
  203. self.assertEqual(SomeClass.class_attribute, MockAttribute)
  204. self.assertTrue(is_instance(SomeClass.class_attribute.wibble,
  205. MagicMock))
  206. self.assertRaises(AttributeError,
  207. lambda: SomeClass.class_attribute.not_wibble)
  208. test()
  209. def test_patch_with_spec_as_list(self):
  210. @patch('%s.SomeClass' % __name__, spec=['wibble'])
  211. def test(MockSomeClass):
  212. self.assertEqual(SomeClass, MockSomeClass)
  213. self.assertTrue(is_instance(SomeClass.wibble, MagicMock))
  214. self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)
  215. test()
  216. def test_patchobject_with_spec_as_list(self):
  217. @patch.object(SomeClass, 'class_attribute', spec=['wibble'])
  218. def test(MockAttribute):
  219. self.assertEqual(SomeClass.class_attribute, MockAttribute)
  220. self.assertTrue(is_instance(SomeClass.class_attribute.wibble,
  221. MagicMock))
  222. self.assertRaises(AttributeError,
  223. lambda: SomeClass.class_attribute.not_wibble)
  224. test()
  225. def test_nested_patch_with_spec_as_list(self):
  226. # regression test for nested decorators
  227. @patch('%s.open' % builtin_string)
  228. @patch('%s.SomeClass' % __name__, spec=['wibble'])
  229. def test(MockSomeClass, MockOpen):
  230. self.assertEqual(SomeClass, MockSomeClass)
  231. self.assertTrue(is_instance(SomeClass.wibble, MagicMock))
  232. self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)
  233. test()
  234. def test_patch_with_spec_as_boolean(self):
  235. @patch('%s.SomeClass' % __name__, spec=True)
  236. def test(MockSomeClass):
  237. self.assertEqual(SomeClass, MockSomeClass)
  238. # Should not raise attribute error
  239. MockSomeClass.wibble
  240. self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble)
  241. test()
  242. def test_patch_object_with_spec_as_boolean(self):
  243. @patch.object(PTModule, 'SomeClass', spec=True)
  244. def test(MockSomeClass):
  245. self.assertEqual(SomeClass, MockSomeClass)
  246. # Should not raise attribute error
  247. MockSomeClass.wibble
  248. self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble)
  249. test()
  250. def test_patch_class_acts_with_spec_is_inherited(self):
  251. @patch('%s.SomeClass' % __name__, spec=True)
  252. def test(MockSomeClass):
  253. self.assertTrue(is_instance(MockSomeClass, MagicMock))
  254. instance = MockSomeClass()
  255. self.assertNotCallable(instance)
  256. # Should not raise attribute error
  257. instance.wibble
  258. self.assertRaises(AttributeError, lambda: instance.not_wibble)
  259. test()
  260. def test_patch_with_create_mocks_non_existent_attributes(self):
  261. @patch('%s.frooble' % builtin_string, sentinel.Frooble, create=True)
  262. def test():
  263. self.assertEqual(frooble, sentinel.Frooble)
  264. test()
  265. self.assertRaises(NameError, lambda: frooble)
  266. def test_patchobject_with_create_mocks_non_existent_attributes(self):
  267. @patch.object(SomeClass, 'frooble', sentinel.Frooble, create=True)
  268. def test():
  269. self.assertEqual(SomeClass.frooble, sentinel.Frooble)
  270. test()
  271. self.assertFalse(hasattr(SomeClass, 'frooble'))
  272. def test_patch_wont_create_by_default(self):
  273. try:
  274. @patch('%s.frooble' % builtin_string, sentinel.Frooble)
  275. def test():
  276. self.assertEqual(frooble, sentinel.Frooble)
  277. test()
  278. except AttributeError:
  279. pass
  280. else:
  281. self.fail('Patching non existent attributes should fail')
  282. self.assertRaises(NameError, lambda: frooble)
  283. def test_patchobject_wont_create_by_default(self):
  284. try:
  285. @patch.object(SomeClass, 'ord', sentinel.Frooble)
  286. def test():
  287. self.fail('Patching non existent attributes should fail')
  288. test()
  289. except AttributeError:
  290. pass
  291. else:
  292. self.fail('Patching non existent attributes should fail')
  293. self.assertFalse(hasattr(SomeClass, 'ord'))
  294. def test_patch_builtins_without_create(self):
  295. @patch(__name__+'.ord')
  296. def test_ord(mock_ord):
  297. mock_ord.return_value = 101
  298. return ord('c')
  299. @patch(__name__+'.open')
  300. def test_open(mock_open):
  301. m = mock_open.return_value
  302. m.read.return_value = 'abcd'
  303. fobj = open('doesnotexists.txt')
  304. data = fobj.read()
  305. fobj.close()
  306. return data
  307. self.assertEqual(test_ord(), 101)
  308. self.assertEqual(test_open(), 'abcd')
  309. def test_patch_with_static_methods(self):
  310. class Foo(object):
  311. @staticmethod
  312. def woot():
  313. return sentinel.Static
  314. @patch.object(Foo, 'woot', staticmethod(lambda: sentinel.Patched))
  315. def anonymous():
  316. self.assertEqual(Foo.woot(), sentinel.Patched)
  317. anonymous()
  318. self.assertEqual(Foo.woot(), sentinel.Static)
  319. def test_patch_local(self):
  320. foo = sentinel.Foo
  321. @patch.object(sentinel, 'Foo', 'Foo')
  322. def anonymous():
  323. self.assertEqual(sentinel.Foo, 'Foo')
  324. anonymous()
  325. self.assertEqual(sentinel.Foo, foo)
  326. def test_patch_slots(self):
  327. class Foo(object):
  328. __slots__ = ('Foo',)
  329. foo = Foo()
  330. foo.Foo = sentinel.Foo
  331. @patch.object(foo, 'Foo', 'Foo')
  332. def anonymous():
  333. self.assertEqual(foo.Foo, 'Foo')
  334. anonymous()
  335. self.assertEqual(foo.Foo, sentinel.Foo)
  336. def test_patchobject_class_decorator(self):
  337. class Something(object):
  338. attribute = sentinel.Original
  339. class Foo(object):
  340. def test_method(other_self):
  341. self.assertEqual(Something.attribute, sentinel.Patched,
  342. "unpatched")
  343. def not_test_method(other_self):
  344. self.assertEqual(Something.attribute, sentinel.Original,
  345. "non-test method patched")
  346. Foo = patch.object(Something, 'attribute', sentinel.Patched)(Foo)
  347. f = Foo()
  348. f.test_method()
  349. f.not_test_method()
  350. self.assertEqual(Something.attribute, sentinel.Original,
  351. "patch not restored")
  352. def test_patch_class_decorator(self):
  353. class Something(object):
  354. attribute = sentinel.Original
  355. class Foo(object):
  356. def test_method(other_self, mock_something):
  357. self.assertEqual(PTModule.something, mock_something,
  358. "unpatched")
  359. def not_test_method(other_self):
  360. self.assertEqual(PTModule.something, sentinel.Something,
  361. "non-test method patched")
  362. Foo = patch('%s.something' % __name__)(Foo)
  363. f = Foo()
  364. f.test_method()
  365. f.not_test_method()
  366. self.assertEqual(Something.attribute, sentinel.Original,
  367. "patch not restored")
  368. self.assertEqual(PTModule.something, sentinel.Something,
  369. "patch not restored")
  370. def test_patchobject_twice(self):
  371. class Something(object):
  372. attribute = sentinel.Original
  373. next_attribute = sentinel.Original2
  374. @patch.object(Something, 'attribute', sentinel.Patched)
  375. @patch.object(Something, 'attribute', sentinel.Patched)
  376. def test():
  377. self.assertEqual(Something.attribute, sentinel.Patched, "unpatched")
  378. test()
  379. self.assertEqual(Something.attribute, sentinel.Original,
  380. "patch not restored")
  381. def test_patch_dict(self):
  382. foo = {'initial': object(), 'other': 'something'}
  383. original = foo.copy()
  384. @patch.dict(foo)
  385. def test():
  386. foo['a'] = 3
  387. del foo['initial']
  388. foo['other'] = 'something else'
  389. test()
  390. self.assertEqual(foo, original)
  391. @patch.dict(foo, {'a': 'b'})
  392. def test():
  393. self.assertEqual(len(foo), 3)
  394. self.assertEqual(foo['a'], 'b')
  395. test()
  396. self.assertEqual(foo, original)
  397. @patch.dict(foo, [('a', 'b')])
  398. def test():
  399. self.assertEqual(len(foo), 3)
  400. self.assertEqual(foo['a'], 'b')
  401. test()
  402. self.assertEqual(foo, original)
  403. def test_patch_dict_with_container_object(self):
  404. foo = Container()
  405. foo['initial'] = object()
  406. foo['other'] = 'something'
  407. original = foo.values.copy()
  408. @patch.dict(foo)
  409. def test():
  410. foo['a'] = 3
  411. del foo['initial']
  412. foo['other'] = 'something else'
  413. test()
  414. self.assertEqual(foo.values, original)
  415. @patch.dict(foo, {'a': 'b'})
  416. def test():
  417. self.assertEqual(len(foo.values), 3)
  418. self.assertEqual(foo['a'], 'b')
  419. test()
  420. self.assertEqual(foo.values, original)
  421. def test_patch_dict_with_clear(self):
  422. foo = {'initial': object(), 'other': 'something'}
  423. original = foo.copy()
  424. @patch.dict(foo, clear=True)
  425. def test():
  426. self.assertEqual(foo, {})
  427. foo['a'] = 3
  428. foo['other'] = 'something else'
  429. test()
  430. self.assertEqual(foo, original)
  431. @patch.dict(foo, {'a': 'b'}, clear=True)
  432. def test():
  433. self.assertEqual(foo, {'a': 'b'})
  434. test()
  435. self.assertEqual(foo, original)
  436. @patch.dict(foo, [('a', 'b')], clear=True)
  437. def test():
  438. self.assertEqual(foo, {'a': 'b'})
  439. test()
  440. self.assertEqual(foo, original)
  441. def test_patch_dict_with_container_object_and_clear(self):
  442. foo = Container()
  443. foo['initial'] = object()
  444. foo['other'] = 'something'
  445. original = foo.values.copy()
  446. @patch.dict(foo, clear=True)
  447. def test():
  448. self.assertEqual(foo.values, {})
  449. foo['a'] = 3
  450. foo['other'] = 'something else'
  451. test()
  452. self.assertEqual(foo.values, original)
  453. @patch.dict(foo, {'a': 'b'}, clear=True)
  454. def test():
  455. self.assertEqual(foo.values, {'a': 'b'})
  456. test()
  457. self.assertEqual(foo.values, original)
  458. def test_name_preserved(self):
  459. foo = {}
  460. @patch('%s.SomeClass' % __name__, object())
  461. @patch('%s.SomeClass' % __name__, object(), autospec=True)
  462. @patch.object(SomeClass, object())
  463. @patch.dict(foo)
  464. def some_name():
  465. pass
  466. self.assertEqual(some_name.__name__, 'some_name')
  467. def test_patch_with_exception(self):
  468. foo = {}
  469. @patch.dict(foo, {'a': 'b'})
  470. def test():
  471. raise NameError('Konrad')
  472. try:
  473. test()
  474. except NameError:
  475. pass
  476. else:
  477. self.fail('NameError not raised by test')
  478. self.assertEqual(foo, {})
  479. def test_patch_dict_with_string(self):
  480. @patch.dict('os.environ', {'konrad_delong': 'some value'})
  481. def test():
  482. self.assertIn('konrad_delong', os.environ)
  483. test()
  484. @unittest.expectedFailure
  485. def test_patch_descriptor(self):
  486. # would be some effort to fix this - we could special case the
  487. # builtin descriptors: classmethod, property, staticmethod
  488. class Nothing(object):
  489. foo = None
  490. class Something(object):
  491. foo = {}
  492. @patch.object(Nothing, 'foo', 2)
  493. @classmethod
  494. def klass(cls):
  495. self.assertIs(cls, Something)
  496. @patch.object(Nothing, 'foo', 2)
  497. @staticmethod
  498. def static(arg):
  499. return arg
  500. @patch.dict(foo)
  501. @classmethod
  502. def klass_dict(cls):
  503. self.assertIs(cls, Something)
  504. @patch.dict(foo)
  505. @staticmethod
  506. def static_dict(arg):
  507. return arg
  508. # these will raise exceptions if patching descriptors is broken
  509. self.assertEqual(Something.static('f00'), 'f00')
  510. Something.klass()
  511. self.assertEqual(Something.static_dict('f00'), 'f00')
  512. Something.klass_dict()
  513. something = Something()
  514. self.assertEqual(something.static('f00'), 'f00')
  515. something.klass()
  516. self.assertEqual(something.static_dict('f00'), 'f00')
  517. something.klass_dict()
  518. def test_patch_spec_set(self):
  519. @patch('%s.SomeClass' % __name__, spec_set=SomeClass)
  520. def test(MockClass):
  521. MockClass.z = 'foo'
  522. self.assertRaises(AttributeError, test)
  523. @patch.object(support, 'SomeClass', spec_set=SomeClass)
  524. def test(MockClass):
  525. MockClass.z = 'foo'
  526. self.assertRaises(AttributeError, test)
  527. @patch('%s.SomeClass' % __name__, spec_set=True)
  528. def test(MockClass):
  529. MockClass.z = 'foo'
  530. self.assertRaises(AttributeError, test)
  531. @patch.object(support, 'SomeClass', spec_set=True)
  532. def test(MockClass):
  533. MockClass.z = 'foo'
  534. self.assertRaises(AttributeError, test)
  535. def test_spec_set_inherit(self):
  536. @patch('%s.SomeClass' % __name__, spec_set=True)
  537. def test(MockClass):
  538. instance = MockClass()
  539. instance.z = 'foo'
  540. self.assertRaises(AttributeError, test)
  541. def test_patch_start_stop(self):
  542. original = something
  543. patcher = patch('%s.something' % __name__)
  544. self.assertIs(something, original)
  545. mock = patcher.start()
  546. try:
  547. self.assertIsNot(mock, original)
  548. self.assertIs(something, mock)
  549. finally:
  550. patcher.stop()
  551. self.assertIs(something, original)
  552. def test_stop_without_start(self):
  553. patcher = patch(foo_name, 'bar', 3)
  554. # calling stop without start used to produce a very obscure error
  555. self.assertRaises(RuntimeError, patcher.stop)
  556. def test_patchobject_start_stop(self):
  557. original = something
  558. patcher = patch.object(PTModule, 'something', 'foo')
  559. self.assertIs(something, original)
  560. replaced = patcher.start()
  561. try:
  562. self.assertEqual(replaced, 'foo')
  563. self.assertIs(something, replaced)
  564. finally:
  565. patcher.stop()
  566. self.assertIs(something, original)
  567. def test_patch_dict_start_stop(self):
  568. d = {'foo': 'bar'}
  569. original = d.copy()
  570. patcher = patch.dict(d, [('spam', 'eggs')], clear=True)
  571. self.assertEqual(d, original)
  572. patcher.start()
  573. try:
  574. self.assertEqual(d, {'spam': 'eggs'})
  575. finally:
  576. patcher.stop()
  577. self.assertEqual(d, original)
  578. def test_patch_dict_class_decorator(self):
  579. this = self
  580. d = {'spam': 'eggs'}
  581. original = d.copy()
  582. class Test(object):
  583. def test_first(self):
  584. this.assertEqual(d, {'foo': 'bar'})
  585. def test_second(self):
  586. this.assertEqual(d, {'foo': 'bar'})
  587. Test = patch.dict(d, {'foo': 'bar'}, clear=True)(Test)
  588. self.assertEqual(d, original)
  589. test = Test()
  590. test.test_first()
  591. self.assertEqual(d, original)
  592. test.test_second()
  593. self.assertEqual(d, original)
  594. test = Test()
  595. test.test_first()
  596. self.assertEqual(d, original)
  597. test.test_second()
  598. self.assertEqual(d, original)
  599. def test_get_only_proxy(self):
  600. class Something(object):
  601. foo = 'foo'
  602. class SomethingElse:
  603. foo = 'foo'
  604. for thing in Something, SomethingElse, Something(), SomethingElse:
  605. proxy = _get_proxy(thing)
  606. @patch.object(proxy, 'foo', 'bar')
  607. def test():
  608. self.assertEqual(proxy.foo, 'bar')
  609. test()
  610. self.assertEqual(proxy.foo, 'foo')
  611. self.assertEqual(thing.foo, 'foo')
  612. self.assertNotIn('foo', proxy.__dict__)
  613. def test_get_set_delete_proxy(self):
  614. class Something(object):
  615. foo = 'foo'
  616. class SomethingElse:
  617. foo = 'foo'
  618. for thing in Something, SomethingElse, Something(), SomethingElse:
  619. proxy = _get_proxy(Something, get_only=False)
  620. @patch.object(proxy, 'foo', 'bar')
  621. def test():
  622. self.assertEqual(proxy.foo, 'bar')
  623. test()
  624. self.assertEqual(proxy.foo, 'foo')
  625. self.assertEqual(thing.foo, 'foo')
  626. self.assertNotIn('foo', proxy.__dict__)
  627. def test_patch_keyword_args(self):
  628. kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
  629. 'foo': MagicMock()}
  630. patcher = patch(foo_name, **kwargs)
  631. mock = patcher.start()
  632. patcher.stop()
  633. self.assertRaises(KeyError, mock)
  634. self.assertEqual(mock.foo.bar(), 33)
  635. self.assertIsInstance(mock.foo, MagicMock)
  636. def test_patch_object_keyword_args(self):
  637. kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
  638. 'foo': MagicMock()}
  639. patcher = patch.object(Foo, 'f', **kwargs)
  640. mock = patcher.start()
  641. patcher.stop()
  642. self.assertRaises(KeyError, mock)
  643. self.assertEqual(mock.foo.bar(), 33)
  644. self.assertIsInstance(mock.foo, MagicMock)
  645. def test_patch_dict_keyword_args(self):
  646. original = {'foo': 'bar'}
  647. copy = original.copy()
  648. patcher = patch.dict(original, foo=3, bar=4, baz=5)
  649. patcher.start()
  650. try:
  651. self.assertEqual(original, dict(foo=3, bar=4, baz=5))
  652. finally:
  653. patcher.stop()
  654. self.assertEqual(original, copy)
  655. def test_autospec(self):
  656. class Boo(object):
  657. def __init__(self, a):
  658. pass
  659. def f(self, a):
  660. pass
  661. def g(self):
  662. pass
  663. foo = 'bar'
  664. class Bar(object):
  665. def a(self):
  666. pass
  667. def _test(mock):
  668. mock(1)
  669. mock.assert_called_with(1)
  670. self.assertRaises(TypeError, mock)
  671. def _test2(mock):
  672. mock.f(1)
  673. mock.f.assert_called_with(1)
  674. self.assertRaises(TypeError, mock.f)
  675. mock.g()
  676. mock.g.assert_called_with()
  677. self.assertRaises(TypeError, mock.g, 1)
  678. self.assertRaises(AttributeError, getattr, mock, 'h')
  679. mock.foo.lower()
  680. mock.foo.lower.assert_called_with()
  681. self.assertRaises(AttributeError, getattr, mock.foo, 'bar')
  682. mock.Bar()
  683. mock.Bar.assert_called_with()
  684. mock.Bar.a()
  685. mock.Bar.a.assert_called_with()
  686. self.assertRaises(TypeError, mock.Bar.a, 1)
  687. mock.Bar().a()
  688. mock.Bar().a.assert_called_with()
  689. self.assertRaises(TypeError, mock.Bar().a, 1)
  690. self.assertRaises(AttributeError, getattr, mock.Bar, 'b')
  691. self.assertRaises(AttributeError, getattr, mock.Bar(), 'b')
  692. def function(mock):
  693. _test(mock)
  694. _test2(mock)
  695. _test2(mock(1))
  696. self.assertIs(mock, Foo)
  697. return mock
  698. test = patch(foo_name, autospec=True)(function)
  699. mock = test()
  700. self.assertIsNot(Foo, mock)
  701. # test patching a second time works
  702. test()
  703. module = sys.modules[__name__]
  704. test = patch.object(module, 'Foo', autospec=True)(function)
  705. mock = test()
  706. self.assertIsNot(Foo, mock)
  707. # test patching a second time works
  708. test()
  709. def test_autospec_function(self):
  710. @patch('%s.function' % __name__, autospec=True)
  711. def test(mock):
  712. function(1)
  713. function.assert_called_with(1)
  714. function(2, 3)
  715. function.assert_called_with(2, 3)
  716. self.assertRaises(TypeError, function)
  717. self.assertRaises(AttributeError, getattr, function, 'foo')
  718. test()
  719. def test_autospec_keywords(self):
  720. @patch('%s.function' % __name__, autospec=True,
  721. return_value=3)
  722. def test(mock_function):
  723. #self.assertEqual(function.abc, 'foo')
  724. return function(1, 2)
  725. result = test()
  726. self.assertEqual(result, 3)
  727. def test_autospec_with_new(self):
  728. patcher = patch('%s.function' % __name__, new=3, autospec=True)
  729. self.assertRaises(TypeError, patcher.start)
  730. module = sys.modules[__name__]
  731. patcher = patch.object(module, 'function', new=3, autospec=True)
  732. self.assertRaises(TypeError, patcher.start)
  733. def test_autospec_with_object(self):
  734. class Bar(Foo):
  735. extra = []
  736. patcher = patch(foo_name, autospec=Bar)
  737. mock = patcher.start()
  738. try:
  739. self.assertIsInstance(mock, Bar)
  740. self.assertIsInstance(mock.extra, list)
  741. finally:
  742. patcher.stop()
  743. def test_autospec_inherits(self):
  744. FooClass = Foo
  745. patcher = patch(foo_name, autospec=True)
  746. mock = patcher.start()
  747. try:
  748. self.assertIsInstance(mock, FooClass)
  749. self.assertIsInstance(mock(3), FooClass)
  750. finally:
  751. patcher.stop()
  752. def test_autospec_name(self):
  753. patcher = patch(foo_name, autospec=True)
  754. mock = patcher.start()
  755. try:
  756. self.assertIn(" name='Foo'", repr(mock))
  757. self.assertIn(" name='Foo.f'", repr(mock.f))
  758. self.assertIn(" name='Foo()'", repr(mock(None)))
  759. self.assertIn(" name='Foo().f'", repr(mock(None).f))
  760. finally:
  761. patcher.stop()
  762. def test_tracebacks(self):
  763. @patch.object(Foo, 'f', object())
  764. def test():
  765. raise AssertionError
  766. try:
  767. test()
  768. except:
  769. err = sys.exc_info()
  770. result = unittest.TextTestResult(None, None, 0)
  771. traceback = result._exc_info_to_string(err, self)
  772. self.assertIn('raise AssertionError', traceback)
  773. def test_new_callable_patch(self):
  774. patcher = patch(foo_name, new_callable=NonCallableMagicMock)
  775. m1 = patcher.start()
  776. patcher.stop()
  777. m2 = patcher.start()
  778. patcher.stop()
  779. self.assertIsNot(m1, m2)
  780. for mock in m1, m2:
  781. self.assertNotCallable(m1)
  782. def test_new_callable_patch_object(self):
  783. patcher = patch.object(Foo, 'f', new_callable=NonCallableMagicMock)
  784. m1 = patcher.start()
  785. patcher.stop()
  786. m2 = patcher.start()
  787. patcher.stop()
  788. self.assertIsNot(m1, m2)
  789. for mock in m1, m2:
  790. self.assertNotCallable(m1)
  791. def test_new_callable_keyword_arguments(self):
  792. class Bar(object):
  793. kwargs = None
  794. def __init__(self, **kwargs):
  795. Bar.kwargs = kwargs
  796. patcher = patch(foo_name, new_callable=Bar, arg1=1, arg2=2)
  797. m = patcher.start()
  798. try:
  799. self.assertIs(type(m), Bar)
  800. self.assertEqual(Bar.kwargs, dict(arg1=1, arg2=2))
  801. finally:
  802. patcher.stop()
  803. def test_new_callable_spec(self):
  804. class Bar(object):
  805. kwargs = None
  806. def __init__(self, **kwargs):
  807. Bar.kwargs = kwargs
  808. patcher = patch(foo_name, new_callable=Bar, spec=Bar)
  809. patcher.start()
  810. try:
  811. self.assertEqual(Bar.kwargs, dict(spec=Bar))
  812. finally:
  813. patcher.stop()
  814. patcher = patch(foo_name, new_callable=Bar, spec_set=Bar)
  815. patcher.start()
  816. try:
  817. self.assertEqual(Bar.kwargs, dict(spec_set=Bar))
  818. finally:
  819. patcher.stop()
  820. def test_new_callable_create(self):
  821. non_existent_attr = '%s.weeeee' % foo_name
  822. p = patch(non_existent_attr, new_callable=NonCallableMock)
  823. self.assertRaises(AttributeError, p.start)
  824. p = patch(non_existent_attr, new_callable=NonCallableMock,
  825. create=True)
  826. m = p.start()
  827. try:
  828. self.assertNotCallable(m, magic=False)
  829. finally:
  830. p.stop()
  831. def test_new_callable_incompatible_with_new(self):
  832. self.assertRaises(
  833. ValueError, patch, foo_name, new=object(), new_callable=MagicMock
  834. )
  835. self.assertRaises(
  836. ValueError, patch.object, Foo, 'f', new=object(),
  837. new_callable=MagicMock
  838. )
  839. def test_new_callable_incompatible_with_autospec(self):
  840. self.assertRaises(
  841. ValueError, patch, foo_name, new_callable=MagicMock,
  842. autospec=True
  843. )
  844. self.assertRaises(
  845. ValueError, patch.object, Foo, 'f', new_callable=MagicMock,
  846. autospec=True
  847. )
  848. def test_new_callable_inherit_for_mocks(self):
  849. class MockSub(Mock):
  850. pass
  851. MockClasses = (
  852. NonCallableMock, NonCallableMagicMock, MagicMock, Mock, MockSub
  853. )
  854. for Klass in MockClasses:
  855. for arg in 'spec', 'spec_set':
  856. kwargs = {arg: True}
  857. p = patch(foo_name, new_callable=Klass, **kwargs)
  858. m = p.start()
  859. try:
  860. instance = m.return_value
  861. self.assertRaises(AttributeError, getattr, instance, 'x')
  862. finally:
  863. p.stop()
  864. def test_new_callable_inherit_non_mock(self):
  865. class NotAMock(object):
  866. def __init__(self, spec):
  867. self.spec = spec
  868. p = patch(foo_name, new_callable=NotAMock, spec=True)
  869. m = p.start()
  870. try:
  871. self.assertTrue(is_instance(m, NotAMock))
  872. self.assertRaises(AttributeError, getattr, m, 'return_value')
  873. finally:
  874. p.stop()
  875. self.assertEqual(m.spec, Foo)
  876. def test_new_callable_class_decorating(self):
  877. test = self
  878. original = Foo
  879. class SomeTest(object):
  880. def _test(self, mock_foo):
  881. test.assertIsNot(Foo, original)
  882. test.assertIs(Foo, mock_foo)
  883. test.assertIsInstance(Foo, SomeClass)
  884. def test_two(self, mock_foo):
  885. self._test(mock_foo)
  886. def test_one(self, mock_foo):
  887. self._test(mock_foo)
  888. SomeTest = patch(foo_name, new_callable=SomeClass)(SomeTest)
  889. SomeTest().test_one()
  890. SomeTest().test_two()
  891. self.assertIs(Foo, original)
  892. def test_patch_multiple(self):
  893. original_foo = Foo
  894. original_f = Foo.f
  895. original_g = Foo.g
  896. patcher1 = patch.multiple(foo_name, f=1, g=2)
  897. patcher2 = patch.multiple(Foo, f=1, g=2)
  898. for patcher in patcher1, patcher2:
  899. patcher.start()
  900. try:
  901. self.assertIs(Foo, original_foo)
  902. self.assertEqual(Foo.f, 1)
  903. self.assertEqual(Foo.g, 2)
  904. finally:
  905. patcher.stop()
  906. self.assertIs(Foo, original_foo)
  907. self.assertEqual(Foo.f, original_f)
  908. self.assertEqual(Foo.g, original_g)
  909. @patch.multiple(foo_name, f=3, g=4)
  910. def test():
  911. self.assertIs(Foo, original_foo)
  912. self.assertEqual(Foo.f, 3)
  913. self.assertEqual(Foo.g, 4)
  914. test()
  915. def test_patch_multiple_no_kwargs(self):
  916. self.assertRaises(ValueError, patch.multiple, foo_name)
  917. self.assertRaises(ValueError, patch.multiple, Foo)
  918. def test_patch_multiple_create_mocks(self):
  919. original_foo = Foo
  920. original_f = Foo.f
  921. original_g = Foo.g
  922. @patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)
  923. def test(f, foo):
  924. self.assertIs(Foo, original_foo)
  925. self.assertIs(Foo.f, f)
  926. self.assertEqual(Foo.g, 3)
  927. self.assertIs(Foo.foo, foo)
  928. self.assertTrue(is_instance(f, MagicMock))
  929. self.assertTrue(is_instance(foo, MagicMock))
  930. test()
  931. self.assertEqual(Foo.f, original_f)
  932. self.assertEqual(Foo.g, original_g)
  933. def test_patch_multiple_create_mocks_different_order(self):
  934. # bug revealed by Jython!
  935. original_f = Foo.f
  936. original_g = Foo.g
  937. patcher = patch.object(Foo, 'f', 3)
  938. patcher.attribute_name = 'f'
  939. other = patch.object(Foo, 'g', DEFAULT)
  940. other.attribute_name = 'g'
  941. patcher.additional_patchers = [other]
  942. @patcher
  943. def test(g):
  944. self.assertIs(Foo.g, g)
  945. self.assertEqual(Foo.f, 3)
  946. test()
  947. self.assertEqual(Foo.f, original_f)
  948. self.assertEqual(Foo.g, original_g)
  949. def test_patch_multiple_stacked_decorators(self):
  950. original_foo = Foo
  951. original_f = Foo.f
  952. original_g = Foo.g
  953. @patch.multiple(foo_name, f=DEFAULT)
  954. @patch.multiple(foo_name, foo=DEFAULT)
  955. @patch(foo_name + '.g')
  956. def test1(g, **kwargs):
  957. _test(g, **kwargs)
  958. @patch.multiple(foo_name, f=DEFAULT)
  959. @patch(foo_name + '.g')
  960. @patch.multiple(foo_name, foo=DEFAULT)
  961. def test2(g, **kwargs):
  962. _test(g, **kwargs)
  963. @patch(foo_name + '.g')
  964. @patch.multiple(foo_name, f=DEFAULT)
  965. @patch.multiple(foo_name, foo=DEFAULT)
  966. def test3(g, **kwargs):
  967. _test(g, **kwargs)
  968. def _test(g, **kwargs):
  969. f = kwargs.pop('f')
  970. foo = kwargs.pop('foo')
  971. self.assertFalse(kwargs)
  972. self.assertIs(Foo, original_foo)
  973. self.assertIs(Foo.f, f)
  974. self.assertIs(Foo.g, g)
  975. self.assertIs(Foo.foo, foo)
  976. self.assertTrue(is_instance(f, MagicMock))
  977. self.assertTrue(is_instance(g, MagicMock))
  978. self.assertTrue(is_instance(foo, MagicMock))
  979. test1()
  980. test2()
  981. test3()
  982. self.assertEqual(Foo.f, original_f)
  983. self.assertEqual(Foo.g, original_g)
  984. def test_patch_multiple_create_mocks_patcher(self):
  985. original_foo = Foo
  986. original_f = Foo.f
  987. original_g = Foo.g
  988. patcher = patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)
  989. result = patcher.start()
  990. try:
  991. f = result['f']
  992. foo = result['foo']
  993. self.assertEqual(set(result), set(['f', 'foo']))
  994. self.assertIs(Foo, original_foo)
  995. self.assertIs(Foo.f, f)
  996. self.assertIs(Foo.foo, foo)
  997. self.assertTrue(is_instance(f, MagicMock))
  998. self.assertTrue(is_instance(foo, MagicMock))
  999. finally:
  1000. patcher.stop()
  1001. self.assertEqual(Foo.f, original_f)
  1002. self.assertEqual(Foo.g, original_g)
  1003. def test_patch_multiple_decorating_class(self):
  1004. test = self
  1005. original_foo = Foo
  1006. original_f = Foo.f
  1007. original_g = Foo.g
  1008. class SomeTest(object):
  1009. def _test(self, f, foo):
  1010. test.assertIs(Foo, original_foo)
  1011. test.assertIs(Foo.f, f)
  1012. test.assertEqual(Foo.g, 3)
  1013. test.assertIs(Foo.foo, foo)
  1014. test.assertTrue(is_instance(f, MagicMock))
  1015. test.assertTrue(is_instance(foo, MagicMock))
  1016. def test_two(self, f, foo):
  1017. self._test(f, foo)
  1018. def test_one(self, f, foo):
  1019. self._test(f, foo)
  1020. SomeTest = patch.multiple(
  1021. foo_name, f=DEFAULT, g=3, foo=DEFAULT
  1022. )(SomeTest)
  1023. thing = SomeTest()
  1024. thing.test_one()
  1025. thing.test_two()
  1026. self.assertEqual(Foo.f, original_f)
  1027. self.assertEqual(Foo.g, original_g)
  1028. def test_patch_multiple_create(self):
  1029. patcher = patch.multiple(Foo, blam='blam')
  1030. self.assertRaises(AttributeError, patcher.start)
  1031. patcher = patch.multiple(Foo, blam='blam', create=True)
  1032. patcher.start()
  1033. try:
  1034. self.assertEqual(Foo.blam, 'blam')
  1035. finally:
  1036. patcher.stop()
  1037. self.assertFalse(hasattr(Foo, 'blam'))
  1038. def test_patch_multiple_spec_set(self):
  1039. # if spec_set works then we can assume that spec and autospec also
  1040. # work as the underlying machinery is the same
  1041. patcher = patch.multiple(Foo, foo=DEFAULT, spec_set=['a', 'b'])
  1042. result = patcher.start()
  1043. try:
  1044. self.assertEqual(Foo.foo, result['foo'])
  1045. Foo.foo.a(1)
  1046. Foo.foo.b(2)
  1047. Foo.foo.a.assert_called_with(1)
  1048. Foo.foo.b.assert_called_with(2)
  1049. self.assertRaises(AttributeError, setattr, Foo.foo, 'c', None)
  1050. finally:
  1051. patcher.stop()
  1052. def test_patch_multiple_new_callable(self):
  1053. class Thing(object):
  1054. pass
  1055. patcher = patch.multiple(
  1056. Foo, f=DEFAULT, g=DEFAULT, new_callable=Thing
  1057. )
  1058. result = patcher.start()
  1059. try:
  1060. self.assertIs(Foo.f, result['f'])
  1061. self.assertIs(Foo.g, result['g'])
  1062. self.assertIsInstance(Foo.f, Thing)
  1063. self.assertIsInstance(Foo.g, Thing)
  1064. self.assertIsNot(Foo.f, Foo.g)
  1065. finally:
  1066. patcher.stop()
  1067. def test_nested_patch_failure(self):
  1068. original_f = Foo.f
  1069. original_g = Foo.g
  1070. @patch.object(Foo, 'g', 1)
  1071. @patch.object(Foo, 'missing', 1)
  1072. @patch.object(Foo, 'f', 1)
  1073. def thing1():
  1074. pass
  1075. @patch.object(Foo, 'missing', 1)
  1076. @patch.object(Foo, 'g', 1)
  1077. @patch.object(Foo, 'f', 1)
  1078. def thing2():
  1079. pass
  1080. @patch.object(Foo, 'g', 1)
  1081. @patch.object(Foo, 'f', 1)
  1082. @patch.object(Foo, 'missing', 1)
  1083. def thing3():
  1084. pass
  1085. for func in thing1, thing2, thing3:
  1086. self.assertRaises(AttributeError, func)
  1087. self.assertEqual(Foo.f, original_f)
  1088. self.assertEqual(Foo.g, original_g)
  1089. def test_new_callable_failure(self):
  1090. original_f = Foo.f
  1091. original_g = Foo.g
  1092. original_foo = Foo.foo
  1093. def crasher():
  1094. raise NameError('crasher')
  1095. @patch.object(Foo, 'g', 1)
  1096. @patch.object(Foo, 'foo', new_callable=crasher)
  1097. @patch.object(Foo, 'f', 1)
  1098. def thing1():
  1099. pass
  1100. @patch.object(Foo, 'foo', new_callable=crasher)
  1101. @patch.object(Foo, 'g', 1)
  1102. @patch.object(Foo, 'f', 1)
  1103. def thing2():
  1104. pass
  1105. @patch.object(Foo, 'g', 1)
  1106. @patch.object(Foo, 'f', 1)
  1107. @patch.object(Foo, 'foo', new_callable=crasher)
  1108. def thing3():
  1109. pass
  1110. for func in thing1, thing2, thing3:
  1111. self.assertRaises(NameError, func)
  1112. self.assertEqual(Foo.f, original_f)
  1113. self.assertEqual(Foo.g, original_g)
  1114. self.assertEqual(Foo.foo, original_foo)
  1115. def test_patch_multiple_failure(self):
  1116. original_f = Foo.f
  1117. original_g = Foo.g
  1118. patcher = patch.object(Foo, 'f', 1)
  1119. patcher.attribute_name = 'f'
  1120. good = patch.object(Foo, 'g', 1)
  1121. good.attribute_name = 'g'
  1122. bad = patch.object(Foo, 'missing', 1)
  1123. bad.attribute_name = 'missing'
  1124. for additionals in [good, bad], [bad, good]:
  1125. patcher.additional_patchers = additionals
  1126. @patcher
  1127. def func():
  1128. pass
  1129. self.assertRaises(AttributeError, func)
  1130. self.assertEqual(Foo.f, original_f)
  1131. self.assertEqual(Foo.g, original_g)
  1132. def test_patch_multiple_new_callable_failure(self):
  1133. original_f = Foo.f
  1134. original_g = Foo.g
  1135. original_foo = Foo.foo
  1136. def crasher():
  1137. raise NameError('crasher')
  1138. patcher = patch.object(Foo, 'f', 1)
  1139. patcher.attribute_name = 'f'
  1140. good = patch.object(Foo, 'g', 1)
  1141. good.attribute_name = 'g'
  1142. bad = patch.object(Foo, 'foo', new_callable=crasher)
  1143. bad.attribute_name = 'foo'
  1144. for additionals in [good, bad], [bad, good]:
  1145. patcher.additional_patchers = additionals
  1146. @patcher
  1147. def func():
  1148. pass
  1149. self.assertRaises(NameError, func)
  1150. self.assertEqual(Foo.f, original_f)
  1151. self.assertEqual(Foo.g, original_g)
  1152. self.assertEqual(Foo.foo, original_foo)
  1153. def test_patch_multiple_string_subclasses(self):
  1154. for base in (str, unicode):
  1155. Foo = type('Foo', (base,), {'fish': 'tasty'})
  1156. foo = Foo()
  1157. @patch.multiple(foo, fish='nearly gone')
  1158. def test():
  1159. self.assertEqual(foo.fish, 'nearly gone')
  1160. test()
  1161. self.assertEqual(foo.fish, 'tasty')
  1162. @patch('mock.patch.TEST_PREFIX', 'foo')
  1163. def test_patch_test_prefix(self):
  1164. class Foo(object):
  1165. thing = 'original'
  1166. def foo_one(self):
  1167. return self.thing
  1168. def foo_two(self):
  1169. return self.thing
  1170. def test_one(self):
  1171. return self.thing
  1172. def test_two(self):
  1173. return self.thing
  1174. Foo = patch.object(Foo, 'thing', 'changed')(Foo)
  1175. foo = Foo()
  1176. self.assertEqual(foo.foo_one(), 'changed')
  1177. self.assertEqual(foo.foo_two(), 'changed')
  1178. self.assertEqual(foo.test_one(), 'original')
  1179. self.assertEqual(foo.test_two(), 'original')
  1180. @patch('mock.patch.TEST_PREFIX', 'bar')
  1181. def test_patch_dict_test_prefix(self):
  1182. class Foo(object):
  1183. def bar_one(self):
  1184. return dict(the_dict)
  1185. def bar_two(self):
  1186. return dict(the_dict)
  1187. def test_one(self):
  1188. return dict(the_dict)
  1189. def test_two(self):
  1190. return dict(the_dict)
  1191. the_dict = {'key': 'original'}
  1192. Foo = patch.dict(the_dict, key='changed')(Foo)
  1193. foo =Foo()
  1194. self.assertEqual(foo.bar_one(), {'key': 'changed'})
  1195. self.assertEqual(foo.bar_two(), {'key': 'changed'})
  1196. self.assertEqual(foo.test_one(), {'key': 'original'})
  1197. self.assertEqual(foo.test_two(), {'key': 'original'})
  1198. def test_patch_with_spec_mock_repr(self):
  1199. for arg in ('spec', 'autospec', 'spec_set'):
  1200. p = patch('%s.SomeClass' % __name__, **{arg: True})
  1201. m = p.start()
  1202. try:
  1203. self.assertIn(" name='SomeClass'", repr(m))
  1204. self.assertIn(" name='SomeClass.class_attribute'",
  1205. repr(m.class_attribute))
  1206. self.assertIn(" name='SomeClass()'", repr(m()))
  1207. self.assertIn(" name='SomeClass().class_attribute'",
  1208. repr(m().class_attribute))
  1209. finally:
  1210. p.stop()
  1211. def test_patch_nested_autospec_repr(self):
  1212. p = patch('mock.tests.support', autospec=True)
  1213. m = p.start()
  1214. try:
  1215. self.assertIn(" name='support.SomeClass.wibble()'",
  1216. repr(m.SomeClass.wibble()))
  1217. self.assertIn(" name='support.SomeClass().wibble()'",
  1218. repr(m.SomeClass().wibble()))
  1219. finally:
  1220. p.stop()
  1221. def test_mock_calls_with_patch(self):
  1222. for arg in ('spec', 'autospec', 'spec_set'):
  1223. p = patch('%s.SomeClass' % __name__, **{arg: True})
  1224. m = p.start()
  1225. try:
  1226. m.wibble()
  1227. kalls = [call.wibble()]
  1228. self.assertEqual(m.mock_calls, kalls)
  1229. self.assertEqual(m.method_calls, kalls)
  1230. self.assertEqual(m.wibble.mock_calls, [call()])
  1231. result = m()
  1232. kalls.append(call())
  1233. self.assertEqual(m.mock_calls, kalls)
  1234. result.wibble()
  1235. kalls.append(call().wibble())
  1236. self.assertEqual(m.mock_calls, kalls)
  1237. self.assertEqual(result.mock_calls, [call.wibble()])
  1238. self.assertEqual(result.wibble.mock_calls, [call()])
  1239. self.assertEqual(result.method_calls, [call.wibble()])
  1240. finally:
  1241. p.stop()
  1242. def test_patch_imports_lazily(self):
  1243. sys.modules.pop('squizz', None)
  1244. p1 = patch('squizz.squozz')
  1245. self.assertRaises(ImportError, p1.start)
  1246. squizz = Mock()
  1247. squizz.squozz = 6
  1248. sys.modules['squizz'] = squizz
  1249. p1 = patch('squizz.squozz')
  1250. squizz.squozz = 3
  1251. p1.start()
  1252. p1.stop()
  1253. self.assertEqual(squizz.squozz, 3)
  1254. def test_patch_propogrates_exc_on_exit(self):
  1255. class holder:
  1256. exc_info = None, None, None
  1257. class custom_patch(_patch):
  1258. def __exit__(self, etype=None, val=None, tb=None):
  1259. _patch.__exit__(self, etype, val, tb)
  1260. holder.exc_info = etype, val, tb
  1261. stop = __exit__
  1262. def with_custom_patch(target):
  1263. getter, attribute = _get_target(target)
  1264. return custom_patch(
  1265. getter, attribute, DEFAULT, None, False, None,
  1266. None, None, {}
  1267. )
  1268. @with_custom_patch('squizz.squozz')
  1269. def test(mock):
  1270. raise RuntimeError
  1271. self.assertRaises(RuntimeError, test)
  1272. self.assertIs(holder.exc_info[0], RuntimeError)
  1273. self.assertIsNotNone(holder.exc_info[1],
  1274. 'exception value not propgated')
  1275. self.assertIsNotNone(holder.exc_info[2],
  1276. 'exception traceback not propgated')
  1277. def test_create_and_specs(self):
  1278. for kwarg in ('spec', 'spec_set', 'autospec'):
  1279. p = patch('%s.doesnotexist' % __name__, create=True,
  1280. **{kwarg: True})
  1281. self.assertRaises(TypeError, p.start)
  1282. self.assertRaises(NameError, lambda: doesnotexist)
  1283. # check that spec with create is innocuous if the original exists
  1284. p = patch(MODNAME, create=True, **{kwarg: True})
  1285. p.start()
  1286. p.stop()
  1287. def test_multiple_specs(self):
  1288. original = PTModule
  1289. for kwarg in ('spec', 'spec_set'):
  1290. p = patch(MODNAME, autospec=0, **{kwarg: 0})
  1291. self.assertRaises(TypeError, p.start)
  1292. self.assertIs(PTModule, original)
  1293. for kwarg in ('spec', 'autospec'):
  1294. p = patch(MODNAME, spec_set=0, **{kwarg: 0})
  1295. self.assertRaises(TypeError, p.start)
  1296. self.assertIs(PTModule, original)
  1297. for kwarg in ('spec_set', 'autospec'):
  1298. p = patch(MODNAME, spec=0, **{kwarg: 0})
  1299. self.assertRaises(TypeError, p.start)
  1300. self.assertIs(PTModule, original)
  1301. def test_specs_false_instead_of_none(self):
  1302. p = patch(MODNAME, spec=False, spec_set=False, autospec=False)
  1303. mock = p.start()
  1304. try:
  1305. # no spec should have been set, so attribute access should not fail
  1306. mock.does_not_exist
  1307. mock.does_not_exist = 3
  1308. finally:
  1309. p.stop()
  1310. def test_falsey_spec(self):
  1311. for kwarg in ('spec', 'autospec', 'spec_set'):
  1312. p = patch(MODNAME, **{kwarg: 0})
  1313. m = p.start()
  1314. try:
  1315. self.assertRaises(AttributeError, getattr, m, 'doesnotexit')
  1316. finally:
  1317. p.stop()
  1318. def test_spec_set_true(self):
  1319. for kwarg in ('spec', 'autospec'):
  1320. p = patch(MODNAME, spec_set=True, **{kwarg: True})
  1321. m = p.start()
  1322. try:
  1323. self.assertRaises(AttributeError, setattr, m,
  1324. 'doesnotexist', 'something')
  1325. self.assertRaises(AttributeError, getattr, m, 'doesnotexist')
  1326. finally:
  1327. p.stop()
  1328. def test_callable_spec_as_list(self):
  1329. spec = ('__call__',)
  1330. p = patch(MODNAME, spec=spec)
  1331. m = p.start()
  1332. try:
  1333. self.assertTrue(callable(m))
  1334. finally:
  1335. p.stop()
  1336. def test_not_callable_spec_as_list(self):
  1337. spec = ('foo', 'bar')
  1338. p = patch(MODNAME, spec=spec)
  1339. m = p.start()
  1340. try:
  1341. self.assertFalse(callable(m))
  1342. finally:
  1343. p.stop()
  1344. def test_patch_stopall(self):
  1345. unlink = os.unlink
  1346. chdir = os.chdir
  1347. path = os.path
  1348. patch('os.unlink', something).start()
  1349. patch('os.chdir', something_else).start()
  1350. @patch('os.path')
  1351. def patched(mock_path):
  1352. patch.stopall()
  1353. self.assertIs(os.path, mock_path)
  1354. self.assertIs(os.unlink, unlink)
  1355. self.assertIs(os.chdir, chdir)
  1356. patched()
  1357. self.assertIs(os.path, path)
  1358. def test_wrapped_patch(self):
  1359. decorated = patch('sys.modules')(function)
  1360. self.assertIs(decorated.__wrapped__, function)
  1361. def test_wrapped_several_times_patch(self):
  1362. decorated = patch('sys.modules')(function)
  1363. decorated = patch('sys.modules')(decorated)
  1364. self.assertIs(decorated.__wrapped__, function)
  1365. def test_wrapped_patch_object(self):
  1366. decorated = patch.object(sys, 'modules')(function)
  1367. self.assertIs(decorated.__wrapped__, function)
  1368. def test_wrapped_patch_dict(self):
  1369. decorated = patch.dict('sys.modules')(function)
  1370. self.assertIs(decorated.__wrapped__, function)
  1371. def test_wrapped_patch_multiple(self):
  1372. decorated = patch.multiple('sys', modules={})(function)
  1373. self.assertIs(decorated.__wrapped__, function)
  1374. def test_stopall_lifo(self):
  1375. stopped = []
  1376. class thing(object):
  1377. one = two = three = None
  1378. def get_patch(attribute):
  1379. class mypatch(_patch):
  1380. def stop(self):
  1381. stopped.append(attribute)
  1382. return super(mypatch, self).stop()
  1383. return mypatch(lambda: thing, attribute, None, None,
  1384. False, None, None, None, {})
  1385. [get_patch(val).start() for val in ("one", "two", "three")]
  1386. patch.stopall()
  1387. self.assertEqual(stopped, ["three", "two", "one"])
  1388. def test_special_attrs(self):
  1389. def foo(x=0):
  1390. """TEST"""
  1391. return x
  1392. with patch.object(foo, '__defaults__', (1, )):
  1393. self.assertEqual(foo(), 1)
  1394. self.assertEqual(foo(), 0)
  1395. with patch.object(foo, '__doc__', "FUN"):
  1396. self.assertEqual(foo.__doc__, "FUN")
  1397. self.assertEqual(foo.__doc__, "TEST")
  1398. with patch.object(foo, '__module__', "testpatch2"):
  1399. self.assertEqual(foo.__module__, "testpatch2")
  1400. self.assertEqual(foo.__module__, __name__)
  1401. if hasattr(self.test_special_attrs, '__annotations__'):
  1402. with patch.object(foo, '__annotations__', dict([('s', 1, )])):
  1403. self.assertEqual(foo.__annotations__, dict([('s', 1, )]))
  1404. self.assertEqual(foo.__annotations__, dict())
  1405. if hasattr(self.test_special_attrs, '__kwdefaults__'):
  1406. foo = eval("lambda *a, x=0: x")
  1407. with patch.object(foo, '__kwdefaults__', dict([('x', 1, )])):
  1408. self.assertEqual(foo(), 1)
  1409. self.assertEqual(foo(), 0)
  1410. if __name__ == '__main__':
  1411. unittest.main()