mox_test.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. #!/usr/bin/python2.4
  2. #
  3. # Unit tests for Mox.
  4. #
  5. # Copyright 2008 Google Inc.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import cStringIO
  19. import unittest
  20. import re
  21. import mox
  22. import mox_test_helper
  23. class ExpectedMethodCallsErrorTest(unittest.TestCase):
  24. """Test creation and string conversion of ExpectedMethodCallsError."""
  25. def testAtLeastOneMethod(self):
  26. self.assertRaises(ValueError, mox.ExpectedMethodCallsError, [])
  27. def testOneError(self):
  28. method = mox.MockMethod("testMethod", [], False)
  29. method(1, 2).AndReturn('output')
  30. e = mox.ExpectedMethodCallsError([method])
  31. self.assertEqual(
  32. "Verify: Expected methods never called:\n"
  33. " 0. testMethod(1, 2) -> 'output'",
  34. str(e))
  35. def testManyErrors(self):
  36. method1 = mox.MockMethod("testMethod", [], False)
  37. method1(1, 2).AndReturn('output')
  38. method2 = mox.MockMethod("testMethod", [], False)
  39. method2(a=1, b=2, c="only named")
  40. method3 = mox.MockMethod("testMethod2", [], False)
  41. method3().AndReturn(44)
  42. method4 = mox.MockMethod("testMethod", [], False)
  43. method4(1, 2).AndReturn('output')
  44. e = mox.ExpectedMethodCallsError([method1, method2, method3, method4])
  45. self.assertEqual(
  46. "Verify: Expected methods never called:\n"
  47. " 0. testMethod(1, 2) -> 'output'\n"
  48. " 1. testMethod(a=1, b=2, c='only named') -> None\n"
  49. " 2. testMethod2() -> 44\n"
  50. " 3. testMethod(1, 2) -> 'output'",
  51. str(e))
  52. class OrTest(unittest.TestCase):
  53. """Test Or correctly chains Comparators."""
  54. def testValidOr(self):
  55. """Or should be True if either Comparator returns True."""
  56. self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == {})
  57. self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test')
  58. self.assert_(mox.Or(mox.IsA(str), mox.IsA(str)) == 'test')
  59. def testInvalidOr(self):
  60. """Or should be False if both Comparators return False."""
  61. self.failIf(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0)
  62. class AndTest(unittest.TestCase):
  63. """Test And correctly chains Comparators."""
  64. def testValidAnd(self):
  65. """And should be True if both Comparators return True."""
  66. self.assert_(mox.And(mox.IsA(str), mox.IsA(str)) == '1')
  67. def testClauseOneFails(self):
  68. """And should be False if the first Comparator returns False."""
  69. self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1')
  70. def testAdvancedUsage(self):
  71. """And should work with other Comparators.
  72. Note: this test is reliant on In and ContainsKeyValue.
  73. """
  74. test_dict = {"mock" : "obj", "testing" : "isCOOL"}
  75. self.assert_(mox.And(mox.In("testing"),
  76. mox.ContainsKeyValue("mock", "obj")) == test_dict)
  77. def testAdvancedUsageFails(self):
  78. """Note: this test is reliant on In and ContainsKeyValue."""
  79. test_dict = {"mock" : "obj", "testing" : "isCOOL"}
  80. self.failIf(mox.And(mox.In("NOTFOUND"),
  81. mox.ContainsKeyValue("mock", "obj")) == test_dict)
  82. class SameElementsAsTest(unittest.TestCase):
  83. """Test SameElementsAs correctly identifies sequences with same elements."""
  84. def testSortedLists(self):
  85. """Should return True if two lists are exactly equal."""
  86. self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c'])
  87. def testUnsortedLists(self):
  88. """Should return True if two lists are unequal but have same elements."""
  89. self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1])
  90. def testUnhashableLists(self):
  91. """Should return True if two lists have the same unhashable elements."""
  92. self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) ==
  93. [{2: 'b'}, {'a': 1}])
  94. def testEmptyLists(self):
  95. """Should return True for two empty lists."""
  96. self.assert_(mox.SameElementsAs([]) == [])
  97. def testUnequalLists(self):
  98. """Should return False if the lists are not equal."""
  99. self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c'])
  100. def testUnequalUnhashableLists(self):
  101. """Should return False if two lists with unhashable elements are unequal."""
  102. self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])
  103. class ContainsKeyValueTest(unittest.TestCase):
  104. """Test ContainsKeyValue correctly identifies key/value pairs in a dict.
  105. """
  106. def testValidPair(self):
  107. """Should return True if the key value is in the dict."""
  108. self.assert_(mox.ContainsKeyValue("key", 1) == {"key": 1})
  109. def testInvalidValue(self):
  110. """Should return False if the value is not correct."""
  111. self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2})
  112. def testInvalidKey(self):
  113. """Should return False if they key is not in the dict."""
  114. self.failIf(mox.ContainsKeyValue("qux", 1) == {"key": 2})
  115. class InTest(unittest.TestCase):
  116. """Test In correctly identifies a key in a list/dict"""
  117. def testItemInList(self):
  118. """Should return True if the item is in the list."""
  119. self.assert_(mox.In(1) == [1, 2, 3])
  120. def testKeyInDict(self):
  121. """Should return True if the item is a key in a dict."""
  122. self.assert_(mox.In("test") == {"test" : "module"})
  123. class NotTest(unittest.TestCase):
  124. """Test Not correctly identifies False predicates."""
  125. def testItemInList(self):
  126. """Should return True if the item is NOT in the list."""
  127. self.assert_(mox.Not(mox.In(42)) == [1, 2, 3])
  128. def testKeyInDict(self):
  129. """Should return True if the item is NOT a key in a dict."""
  130. self.assert_(mox.Not(mox.In("foo")) == {"key" : 42})
  131. def testInvalidKeyWithNot(self):
  132. """Should return False if they key is NOT in the dict."""
  133. self.assert_(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2})
  134. class StrContainsTest(unittest.TestCase):
  135. """Test StrContains correctly checks for substring occurrence of a parameter.
  136. """
  137. def testValidSubstringAtStart(self):
  138. """Should return True if the substring is at the start of the string."""
  139. self.assert_(mox.StrContains("hello") == "hello world")
  140. def testValidSubstringInMiddle(self):
  141. """Should return True if the substring is in the middle of the string."""
  142. self.assert_(mox.StrContains("lo wo") == "hello world")
  143. def testValidSubstringAtEnd(self):
  144. """Should return True if the substring is at the end of the string."""
  145. self.assert_(mox.StrContains("ld") == "hello world")
  146. def testInvaildSubstring(self):
  147. """Should return False if the substring is not in the string."""
  148. self.failIf(mox.StrContains("AAA") == "hello world")
  149. def testMultipleMatches(self):
  150. """Should return True if there are multiple occurances of substring."""
  151. self.assert_(mox.StrContains("abc") == "ababcabcabcababc")
  152. class RegexTest(unittest.TestCase):
  153. """Test Regex correctly matches regular expressions."""
  154. def testIdentifyBadSyntaxDuringInit(self):
  155. """The user should know immediately if a regex has bad syntax."""
  156. self.assertRaises(re.error, mox.Regex, '(a|b')
  157. def testPatternInMiddle(self):
  158. """Should return True if the pattern matches at the middle of the string.
  159. This ensures that re.search is used (instead of re.find).
  160. """
  161. self.assert_(mox.Regex(r"a\s+b") == "x y z a b c")
  162. def testNonMatchPattern(self):
  163. """Should return False if the pattern does not match the string."""
  164. self.failIf(mox.Regex(r"a\s+b") == "x y z")
  165. def testFlagsPassedCorrectly(self):
  166. """Should return True as we pass IGNORECASE flag."""
  167. self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a")
  168. def testReprWithoutFlags(self):
  169. """repr should return the regular expression pattern."""
  170. self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>")
  171. def testReprWithFlags(self):
  172. """repr should return the regular expression pattern and flags."""
  173. self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) ==
  174. "<regular expression 'a\s+b', flags=4>")
  175. class IsATest(unittest.TestCase):
  176. """Verify IsA correctly checks equality based upon class type, not value."""
  177. def testEqualityValid(self):
  178. """Verify that == correctly identifies objects of the same type."""
  179. self.assert_(mox.IsA(str) == 'test')
  180. def testEqualityInvalid(self):
  181. """Verify that == correctly identifies objects of different types."""
  182. self.failIf(mox.IsA(str) == 10)
  183. def testInequalityValid(self):
  184. """Verify that != identifies objects of different type."""
  185. self.assert_(mox.IsA(str) != 10)
  186. def testInequalityInvalid(self):
  187. """Verify that != correctly identifies objects of the same type."""
  188. self.failIf(mox.IsA(str) != "test")
  189. def testEqualityInListValid(self):
  190. """Verify list contents are properly compared."""
  191. isa_list = [mox.IsA(str), mox.IsA(str)]
  192. str_list = ["abc", "def"]
  193. self.assert_(isa_list == str_list)
  194. def testEquailtyInListInvalid(self):
  195. """Verify list contents are properly compared."""
  196. isa_list = [mox.IsA(str),mox.IsA(str)]
  197. mixed_list = ["abc", 123]
  198. self.failIf(isa_list == mixed_list)
  199. def testSpecialTypes(self):
  200. """Verify that IsA can handle objects like cStringIO.StringIO."""
  201. isA = mox.IsA(cStringIO.StringIO())
  202. stringIO = cStringIO.StringIO()
  203. self.assert_(isA == stringIO)
  204. class IsAlmostTest(unittest.TestCase):
  205. """Verify IsAlmost correctly checks equality of floating point numbers."""
  206. def testEqualityValid(self):
  207. """Verify that == correctly identifies nearly equivalent floats."""
  208. self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
  209. def testEqualityInvalid(self):
  210. """Verify that == correctly identifies non-equivalent floats."""
  211. self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
  212. def testEqualityWithPlaces(self):
  213. """Verify that specifying places has the desired effect."""
  214. self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
  215. self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
  216. def testNonNumericTypes(self):
  217. """Verify that IsAlmost handles non-numeric types properly."""
  218. self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9')
  219. self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9)
  220. self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
  221. class MockMethodTest(unittest.TestCase):
  222. """Test class to verify that the MockMethod class is working correctly."""
  223. def setUp(self):
  224. self.expected_method = mox.MockMethod("testMethod", [], False)(['original'])
  225. self.mock_method = mox.MockMethod("testMethod", [self.expected_method],
  226. True)
  227. def testAndReturnNoneByDefault(self):
  228. """Should return None by default."""
  229. return_value = self.mock_method(['original'])
  230. self.assert_(return_value == None)
  231. def testAndReturnValue(self):
  232. """Should return a specificed return value."""
  233. expected_return_value = "test"
  234. self.expected_method.AndReturn(expected_return_value)
  235. return_value = self.mock_method(['original'])
  236. self.assert_(return_value == expected_return_value)
  237. def testAndRaiseException(self):
  238. """Should raise a specified exception."""
  239. expected_exception = Exception('test exception')
  240. self.expected_method.AndRaise(expected_exception)
  241. self.assertRaises(Exception, self.mock_method)
  242. def testWithSideEffects(self):
  243. """Should call state modifier."""
  244. local_list = ['original']
  245. def modifier(mutable_list):
  246. self.assertTrue(local_list is mutable_list)
  247. mutable_list[0] = 'mutation'
  248. self.expected_method.WithSideEffects(modifier).AndReturn(1)
  249. self.mock_method(local_list)
  250. self.assertEquals('mutation', local_list[0])
  251. def testEqualityNoParamsEqual(self):
  252. """Methods with the same name and without params should be equal."""
  253. expected_method = mox.MockMethod("testMethod", [], False)
  254. self.assertEqual(self.mock_method, expected_method)
  255. def testEqualityNoParamsNotEqual(self):
  256. """Methods with different names and without params should not be equal."""
  257. expected_method = mox.MockMethod("otherMethod", [], False)
  258. self.failIfEqual(self.mock_method, expected_method)
  259. def testEqualityParamsEqual(self):
  260. """Methods with the same name and parameters should be equal."""
  261. params = [1, 2, 3]
  262. expected_method = mox.MockMethod("testMethod", [], False)
  263. expected_method._params = params
  264. self.mock_method._params = params
  265. self.assertEqual(self.mock_method, expected_method)
  266. def testEqualityParamsNotEqual(self):
  267. """Methods with the same name and different params should not be equal."""
  268. expected_method = mox.MockMethod("testMethod", [], False)
  269. expected_method._params = [1, 2, 3]
  270. self.mock_method._params = ['a', 'b', 'c']
  271. self.failIfEqual(self.mock_method, expected_method)
  272. def testEqualityNamedParamsEqual(self):
  273. """Methods with the same name and same named params should be equal."""
  274. named_params = {"input1": "test", "input2": "params"}
  275. expected_method = mox.MockMethod("testMethod", [], False)
  276. expected_method._named_params = named_params
  277. self.mock_method._named_params = named_params
  278. self.assertEqual(self.mock_method, expected_method)
  279. def testEqualityNamedParamsNotEqual(self):
  280. """Methods with the same name and diffnamed params should not be equal."""
  281. expected_method = mox.MockMethod("testMethod", [], False)
  282. expected_method._named_params = {"input1": "test", "input2": "params"}
  283. self.mock_method._named_params = {"input1": "test2", "input2": "params2"}
  284. self.failIfEqual(self.mock_method, expected_method)
  285. def testEqualityWrongType(self):
  286. """Method should not be equal to an object of a different type."""
  287. self.failIfEqual(self.mock_method, "string?")
  288. def testObjectEquality(self):
  289. """Equality of objects should work without a Comparator"""
  290. instA = TestClass();
  291. instB = TestClass();
  292. params = [instA, ]
  293. expected_method = mox.MockMethod("testMethod", [], False)
  294. expected_method._params = params
  295. self.mock_method._params = [instB, ]
  296. self.assertEqual(self.mock_method, expected_method)
  297. def testStrConversion(self):
  298. method = mox.MockMethod("f", [], False)
  299. method(1, 2, "st", n1=8, n2="st2")
  300. self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None"))
  301. method = mox.MockMethod("testMethod", [], False)
  302. method(1, 2, "only positional")
  303. self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None")
  304. method = mox.MockMethod("testMethod", [], False)
  305. method(a=1, b=2, c="only named")
  306. self.assertEqual(str(method),
  307. "testMethod(a=1, b=2, c='only named') -> None")
  308. method = mox.MockMethod("testMethod", [], False)
  309. method()
  310. self.assertEqual(str(method), "testMethod() -> None")
  311. method = mox.MockMethod("testMethod", [], False)
  312. method(x="only 1 parameter")
  313. self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None")
  314. method = mox.MockMethod("testMethod", [], False)
  315. method().AndReturn('return_value')
  316. self.assertEqual(str(method), "testMethod() -> 'return_value'")
  317. method = mox.MockMethod("testMethod", [], False)
  318. method().AndReturn(('a', {1: 2}))
  319. self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})")
  320. class MockAnythingTest(unittest.TestCase):
  321. """Verify that the MockAnything class works as expected."""
  322. def setUp(self):
  323. self.mock_object = mox.MockAnything()
  324. def testRepr(self):
  325. """Calling repr on a MockAnything instance must work."""
  326. self.assertEqual('<MockAnything instance>', repr(self.mock_object))
  327. def testSetupMode(self):
  328. """Verify the mock will accept any call."""
  329. self.mock_object.NonsenseCall()
  330. self.assert_(len(self.mock_object._expected_calls_queue) == 1)
  331. def testReplayWithExpectedCall(self):
  332. """Verify the mock replays method calls as expected."""
  333. self.mock_object.ValidCall() # setup method call
  334. self.mock_object._Replay() # start replay mode
  335. self.mock_object.ValidCall() # make method call
  336. def testReplayWithUnexpectedCall(self):
  337. """Unexpected method calls should raise UnexpectedMethodCallError."""
  338. self.mock_object.ValidCall() # setup method call
  339. self.mock_object._Replay() # start replay mode
  340. self.assertRaises(mox.UnexpectedMethodCallError,
  341. self.mock_object.OtherValidCall)
  342. def testVerifyWithCompleteReplay(self):
  343. """Verify should not raise an exception for a valid replay."""
  344. self.mock_object.ValidCall() # setup method call
  345. self.mock_object._Replay() # start replay mode
  346. self.mock_object.ValidCall() # make method call
  347. self.mock_object._Verify()
  348. def testVerifyWithIncompleteReplay(self):
  349. """Verify should raise an exception if the replay was not complete."""
  350. self.mock_object.ValidCall() # setup method call
  351. self.mock_object._Replay() # start replay mode
  352. # ValidCall() is never made
  353. self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify)
  354. def testSpecialClassMethod(self):
  355. """Verify should not raise an exception when special methods are used."""
  356. self.mock_object[1].AndReturn(True)
  357. self.mock_object._Replay()
  358. returned_val = self.mock_object[1]
  359. self.assert_(returned_val)
  360. self.mock_object._Verify()
  361. def testNonzero(self):
  362. """You should be able to use the mock object in an if."""
  363. self.mock_object._Replay()
  364. if self.mock_object:
  365. pass
  366. def testNotNone(self):
  367. """Mock should be comparable to None."""
  368. self.mock_object._Replay()
  369. if self.mock_object is not None:
  370. pass
  371. if self.mock_object is None:
  372. pass
  373. def testEquals(self):
  374. """A mock should be able to compare itself to another object."""
  375. self.mock_object._Replay()
  376. self.assertEquals(self.mock_object, self.mock_object)
  377. def testEqualsMockFailure(self):
  378. """Verify equals identifies unequal objects."""
  379. self.mock_object.SillyCall()
  380. self.mock_object._Replay()
  381. self.assertNotEquals(self.mock_object, mox.MockAnything())
  382. def testEqualsInstanceFailure(self):
  383. """Verify equals identifies that objects are different instances."""
  384. self.mock_object._Replay()
  385. self.assertNotEquals(self.mock_object, TestClass())
  386. def testNotEquals(self):
  387. """Verify not equals works."""
  388. self.mock_object._Replay()
  389. self.assertFalse(self.mock_object != self.mock_object)
  390. def testNestedMockCallsRecordedSerially(self):
  391. """Test that nested calls work when recorded serially."""
  392. self.mock_object.CallInner().AndReturn(1)
  393. self.mock_object.CallOuter(1)
  394. self.mock_object._Replay()
  395. self.mock_object.CallOuter(self.mock_object.CallInner())
  396. self.mock_object._Verify()
  397. def testNestedMockCallsRecordedNested(self):
  398. """Test that nested cals work when recorded in a nested fashion."""
  399. self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1))
  400. self.mock_object._Replay()
  401. self.mock_object.CallOuter(self.mock_object.CallInner())
  402. self.mock_object._Verify()
  403. def testIsCallable(self):
  404. """Test that MockAnything can even mock a simple callable.
  405. This is handy for "stubbing out" a method in a module with a mock, and
  406. verifying that it was called.
  407. """
  408. self.mock_object().AndReturn('mox0rd')
  409. self.mock_object._Replay()
  410. self.assertEquals('mox0rd', self.mock_object())
  411. self.mock_object._Verify()
  412. def testIsReprable(self):
  413. """Test that MockAnythings can be repr'd without causing a failure."""
  414. self.failUnless('MockAnything' in repr(self.mock_object))
  415. class MethodCheckerTest(unittest.TestCase):
  416. """Tests MockMethod's use of MethodChecker method."""
  417. def testNoParameters(self):
  418. method = mox.MockMethod('NoParameters', [], False,
  419. CheckCallTestClass.NoParameters)
  420. method()
  421. self.assertRaises(AttributeError, method, 1)
  422. self.assertRaises(AttributeError, method, 1, 2)
  423. self.assertRaises(AttributeError, method, a=1)
  424. self.assertRaises(AttributeError, method, 1, b=2)
  425. def testOneParameter(self):
  426. method = mox.MockMethod('OneParameter', [], False,
  427. CheckCallTestClass.OneParameter)
  428. self.assertRaises(AttributeError, method)
  429. method(1)
  430. method(a=1)
  431. self.assertRaises(AttributeError, method, b=1)
  432. self.assertRaises(AttributeError, method, 1, 2)
  433. self.assertRaises(AttributeError, method, 1, a=2)
  434. self.assertRaises(AttributeError, method, 1, b=2)
  435. def testTwoParameters(self):
  436. method = mox.MockMethod('TwoParameters', [], False,
  437. CheckCallTestClass.TwoParameters)
  438. self.assertRaises(AttributeError, method)
  439. self.assertRaises(AttributeError, method, 1)
  440. self.assertRaises(AttributeError, method, a=1)
  441. self.assertRaises(AttributeError, method, b=1)
  442. method(1, 2)
  443. method(1, b=2)
  444. method(a=1, b=2)
  445. method(b=2, a=1)
  446. self.assertRaises(AttributeError, method, b=2, c=3)
  447. self.assertRaises(AttributeError, method, a=1, b=2, c=3)
  448. self.assertRaises(AttributeError, method, 1, 2, 3)
  449. self.assertRaises(AttributeError, method, 1, 2, 3, 4)
  450. self.assertRaises(AttributeError, method, 3, a=1, b=2)
  451. def testOneDefaultValue(self):
  452. method = mox.MockMethod('OneDefaultValue', [], False,
  453. CheckCallTestClass.OneDefaultValue)
  454. method()
  455. method(1)
  456. method(a=1)
  457. self.assertRaises(AttributeError, method, b=1)
  458. self.assertRaises(AttributeError, method, 1, 2)
  459. self.assertRaises(AttributeError, method, 1, a=2)
  460. self.assertRaises(AttributeError, method, 1, b=2)
  461. def testTwoDefaultValues(self):
  462. method = mox.MockMethod('TwoDefaultValues', [], False,
  463. CheckCallTestClass.TwoDefaultValues)
  464. self.assertRaises(AttributeError, method)
  465. self.assertRaises(AttributeError, method, c=3)
  466. self.assertRaises(AttributeError, method, 1)
  467. self.assertRaises(AttributeError, method, 1, d=4)
  468. self.assertRaises(AttributeError, method, 1, d=4, c=3)
  469. method(1, 2)
  470. method(a=1, b=2)
  471. method(1, 2, 3)
  472. method(1, 2, 3, 4)
  473. method(1, 2, c=3)
  474. method(1, 2, c=3, d=4)
  475. method(1, 2, d=4, c=3)
  476. method(d=4, c=3, a=1, b=2)
  477. self.assertRaises(AttributeError, method, 1, 2, 3, 4, 5)
  478. self.assertRaises(AttributeError, method, 1, 2, e=9)
  479. self.assertRaises(AttributeError, method, a=1, b=2, e=9)
  480. def testArgs(self):
  481. method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args)
  482. self.assertRaises(AttributeError, method)
  483. self.assertRaises(AttributeError, method, 1)
  484. method(1, 2)
  485. method(a=1, b=2)
  486. method(1, 2, 3)
  487. method(1, 2, 3, 4)
  488. self.assertRaises(AttributeError, method, 1, 2, a=3)
  489. self.assertRaises(AttributeError, method, 1, 2, c=3)
  490. def testKwargs(self):
  491. method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs)
  492. self.assertRaises(AttributeError, method)
  493. method(1)
  494. method(1, 2)
  495. method(a=1, b=2)
  496. method(b=2, a=1)
  497. self.assertRaises(AttributeError, method, 1, 2, 3)
  498. self.assertRaises(AttributeError, method, 1, 2, a=3)
  499. method(1, 2, c=3)
  500. method(a=1, b=2, c=3)
  501. method(c=3, a=1, b=2)
  502. method(a=1, b=2, c=3, d=4)
  503. self.assertRaises(AttributeError, method, 1, 2, 3, 4)
  504. def testArgsAndKwargs(self):
  505. method = mox.MockMethod('ArgsAndKwargs', [], False,
  506. CheckCallTestClass.ArgsAndKwargs)
  507. self.assertRaises(AttributeError, method)
  508. method(1)
  509. method(1, 2)
  510. method(1, 2, 3)
  511. method(a=1)
  512. method(1, b=2)
  513. self.assertRaises(AttributeError, method, 1, a=2)
  514. method(b=2, a=1)
  515. method(c=3, b=2, a=1)
  516. method(1, 2, c=3)
  517. class CheckCallTestClass(object):
  518. def NoParameters(self):
  519. pass
  520. def OneParameter(self, a):
  521. pass
  522. def TwoParameters(self, a, b):
  523. pass
  524. def OneDefaultValue(self, a=1):
  525. pass
  526. def TwoDefaultValues(self, a, b, c=1, d=2):
  527. pass
  528. def Args(self, a, b, *args):
  529. pass
  530. def Kwargs(self, a, b=2, **kwargs):
  531. pass
  532. def ArgsAndKwargs(self, a, *args, **kwargs):
  533. pass
  534. class MockObjectTest(unittest.TestCase):
  535. """Verify that the MockObject class works as exepcted."""
  536. def setUp(self):
  537. self.mock_object = mox.MockObject(TestClass)
  538. def testSetupModeWithValidCall(self):
  539. """Verify the mock object properly mocks a basic method call."""
  540. self.mock_object.ValidCall()
  541. self.assert_(len(self.mock_object._expected_calls_queue) == 1)
  542. def testSetupModeWithInvalidCall(self):
  543. """UnknownMethodCallError should be raised if a non-member method is called.
  544. """
  545. # Note: assertRaises does not catch exceptions thrown by MockObject's
  546. # __getattr__
  547. try:
  548. self.mock_object.InvalidCall()
  549. self.fail("No exception thrown, expected UnknownMethodCallError")
  550. except mox.UnknownMethodCallError:
  551. pass
  552. except Exception:
  553. self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
  554. def testReplayWithInvalidCall(self):
  555. """UnknownMethodCallError should be raised if a non-member method is called.
  556. """
  557. self.mock_object.ValidCall() # setup method call
  558. self.mock_object._Replay() # start replay mode
  559. # Note: assertRaises does not catch exceptions thrown by MockObject's
  560. # __getattr__
  561. try:
  562. self.mock_object.InvalidCall()
  563. self.fail("No exception thrown, expected UnknownMethodCallError")
  564. except mox.UnknownMethodCallError:
  565. pass
  566. except Exception:
  567. self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
  568. def testIsInstance(self):
  569. """Mock should be able to pass as an instance of the mocked class."""
  570. self.assert_(isinstance(self.mock_object, TestClass))
  571. def testFindValidMethods(self):
  572. """Mock should be able to mock all public methods."""
  573. self.assert_('ValidCall' in self.mock_object._known_methods)
  574. self.assert_('OtherValidCall' in self.mock_object._known_methods)
  575. self.assert_('MyClassMethod' in self.mock_object._known_methods)
  576. self.assert_('MyStaticMethod' in self.mock_object._known_methods)
  577. self.assert_('_ProtectedCall' in self.mock_object._known_methods)
  578. self.assert_('__PrivateCall' not in self.mock_object._known_methods)
  579. self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods)
  580. def testFindsSuperclassMethods(self):
  581. """Mock should be able to mock superclasses methods."""
  582. self.mock_object = mox.MockObject(ChildClass)
  583. self.assert_('ValidCall' in self.mock_object._known_methods)
  584. self.assert_('OtherValidCall' in self.mock_object._known_methods)
  585. self.assert_('MyClassMethod' in self.mock_object._known_methods)
  586. self.assert_('ChildValidCall' in self.mock_object._known_methods)
  587. def testAccessClassVariables(self):
  588. """Class variables should be accessible through the mock."""
  589. self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars)
  590. self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)
  591. self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR)
  592. def testEquals(self):
  593. """A mock should be able to compare itself to another object."""
  594. self.mock_object._Replay()
  595. self.assertEquals(self.mock_object, self.mock_object)
  596. def testEqualsMockFailure(self):
  597. """Verify equals identifies unequal objects."""
  598. self.mock_object.ValidCall()
  599. self.mock_object._Replay()
  600. self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
  601. def testEqualsInstanceFailure(self):
  602. """Verify equals identifies that objects are different instances."""
  603. self.mock_object._Replay()
  604. self.assertNotEquals(self.mock_object, TestClass())
  605. def testNotEquals(self):
  606. """Verify not equals works."""
  607. self.mock_object._Replay()
  608. self.assertFalse(self.mock_object != self.mock_object)
  609. def testMockSetItem_ExpectedSetItem_Success(self):
  610. """Test that __setitem__() gets mocked in Dummy.
  611. In this test, _Verify() succeeds.
  612. """
  613. dummy = mox.MockObject(TestClass)
  614. dummy['X'] = 'Y'
  615. dummy._Replay()
  616. dummy['X'] = 'Y'
  617. dummy._Verify()
  618. def testMockSetItem_ExpectedSetItem_NoSuccess(self):
  619. """Test that __setitem__() gets mocked in Dummy.
  620. In this test, _Verify() fails.
  621. """
  622. dummy = mox.MockObject(TestClass)
  623. dummy['X'] = 'Y'
  624. dummy._Replay()
  625. # NOT doing dummy['X'] = 'Y'
  626. self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
  627. def testMockSetItem_ExpectedNoSetItem_Success(self):
  628. """Test that __setitem__() gets mocked in Dummy."""
  629. dummy = mox.MockObject(TestClass)
  630. # NOT doing dummy['X'] = 'Y'
  631. dummy._Replay()
  632. def call(): dummy['X'] = 'Y'
  633. self.assertRaises(mox.UnexpectedMethodCallError, call)
  634. def testMockSetItem_ExpectedNoSetItem_NoSuccess(self):
  635. """Test that __setitem__() gets mocked in Dummy.
  636. In this test, _Verify() fails.
  637. """
  638. dummy = mox.MockObject(TestClass)
  639. # NOT doing dummy['X'] = 'Y'
  640. dummy._Replay()
  641. # NOT doing dummy['X'] = 'Y'
  642. dummy._Verify()
  643. def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self):
  644. """Test that __setitem__() fails if other parameters are expected."""
  645. dummy = mox.MockObject(TestClass)
  646. dummy['X'] = 'Y'
  647. dummy._Replay()
  648. def call(): dummy['wrong'] = 'Y'
  649. self.assertRaises(mox.UnexpectedMethodCallError, call)
  650. dummy._Verify()
  651. def testMockSetItem_WithSubClassOfNewStyleClass(self):
  652. class NewStyleTestClass(object):
  653. def __init__(self):
  654. self.my_dict = {}
  655. def __setitem__(self, key, value):
  656. self.my_dict[key], value
  657. class TestSubClass(NewStyleTestClass):
  658. pass
  659. dummy = mox.MockObject(TestSubClass)
  660. dummy[1] = 2
  661. dummy._Replay()
  662. dummy[1] = 2
  663. dummy._Verify()
  664. def testMockGetItem_ExpectedGetItem_Success(self):
  665. """Test that __getitem__() gets mocked in Dummy.
  666. In this test, _Verify() succeeds.
  667. """
  668. dummy = mox.MockObject(TestClass)
  669. dummy['X'].AndReturn('value')
  670. dummy._Replay()
  671. self.assertEqual(dummy['X'], 'value')
  672. dummy._Verify()
  673. def testMockGetItem_ExpectedGetItem_NoSuccess(self):
  674. """Test that __getitem__() gets mocked in Dummy.
  675. In this test, _Verify() fails.
  676. """
  677. dummy = mox.MockObject(TestClass)
  678. dummy['X'].AndReturn('value')
  679. dummy._Replay()
  680. # NOT doing dummy['X']
  681. self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
  682. def testMockGetItem_ExpectedNoGetItem_NoSuccess(self):
  683. """Test that __getitem__() gets mocked in Dummy."""
  684. dummy = mox.MockObject(TestClass)
  685. # NOT doing dummy['X']
  686. dummy._Replay()
  687. def call(): return dummy['X']
  688. self.assertRaises(mox.UnexpectedMethodCallError, call)
  689. def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self):
  690. """Test that __getitem__() fails if other parameters are expected."""
  691. dummy = mox.MockObject(TestClass)
  692. dummy['X'].AndReturn('value')
  693. dummy._Replay()
  694. def call(): return dummy['wrong']
  695. self.assertRaises(mox.UnexpectedMethodCallError, call)
  696. dummy._Verify()
  697. def testMockGetItem_WithSubClassOfNewStyleClass(self):
  698. class NewStyleTestClass(object):
  699. def __getitem__(self, key):
  700. return {1: '1', 2: '2'}[key]
  701. class TestSubClass(NewStyleTestClass):
  702. pass
  703. dummy = mox.MockObject(TestSubClass)
  704. dummy[1].AndReturn('3')
  705. dummy._Replay()
  706. self.assertEquals('3', dummy.__getitem__(1))
  707. dummy._Verify()
  708. def testMockIter_ExpectedIter_Success(self):
  709. """Test that __iter__() gets mocked in Dummy.
  710. In this test, _Verify() succeeds.
  711. """
  712. dummy = mox.MockObject(TestClass)
  713. iter(dummy).AndReturn(iter(['X', 'Y']))
  714. dummy._Replay()
  715. self.assertEqual([x for x in dummy], ['X', 'Y'])
  716. dummy._Verify()
  717. def testMockContains_ExpectedContains_Success(self):
  718. """Test that __contains__ gets mocked in Dummy.
  719. In this test, _Verify() succeeds.
  720. """
  721. dummy = mox.MockObject(TestClass)
  722. dummy.__contains__('X').AndReturn(True)
  723. dummy._Replay()
  724. self.failUnless('X' in dummy)
  725. dummy._Verify()
  726. def testMockContains_ExpectedContains_NoSuccess(self):
  727. """Test that __contains__() gets mocked in Dummy.
  728. In this test, _Verify() fails.
  729. """
  730. dummy = mox.MockObject(TestClass)
  731. dummy.__contains__('X').AndReturn('True')
  732. dummy._Replay()
  733. # NOT doing 'X' in dummy
  734. self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
  735. def testMockContains_ExpectedContains_NonmatchingParameter(self):
  736. """Test that __contains__ fails if other parameters are expected."""
  737. dummy = mox.MockObject(TestClass)
  738. dummy.__contains__('X').AndReturn(True)
  739. dummy._Replay()
  740. def call(): return 'Y' in dummy
  741. self.assertRaises(mox.UnexpectedMethodCallError, call)
  742. dummy._Verify()
  743. def testMockIter_ExpectedIter_NoSuccess(self):
  744. """Test that __iter__() gets mocked in Dummy.
  745. In this test, _Verify() fails.
  746. """
  747. dummy = mox.MockObject(TestClass)
  748. iter(dummy).AndReturn(iter(['X', 'Y']))
  749. dummy._Replay()
  750. # NOT doing self.assertEqual([x for x in dummy], ['X', 'Y'])
  751. self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
  752. def testMockIter_ExpectedNoIter_NoSuccess(self):
  753. """Test that __iter__() gets mocked in Dummy."""
  754. dummy = mox.MockObject(TestClass)
  755. # NOT doing iter(dummy)
  756. dummy._Replay()
  757. def call(): return [x for x in dummy]
  758. self.assertRaises(mox.UnexpectedMethodCallError, call)
  759. def testMockIter_ExpectedGetItem_Success(self):
  760. """Test that __iter__() gets mocked in Dummy using getitem."""
  761. dummy = mox.MockObject(SubscribtableNonIterableClass)
  762. dummy[0].AndReturn('a')
  763. dummy[1].AndReturn('b')
  764. dummy[2].AndRaise(IndexError)
  765. dummy._Replay()
  766. self.assertEquals(['a', 'b'], [x for x in dummy])
  767. dummy._Verify()
  768. def testMockIter_ExpectedNoGetItem_NoSuccess(self):
  769. """Test that __iter__() gets mocked in Dummy using getitem."""
  770. dummy = mox.MockObject(SubscribtableNonIterableClass)
  771. # NOT doing dummy[index]
  772. dummy._Replay()
  773. function = lambda: [x for x in dummy]
  774. self.assertRaises(mox.UnexpectedMethodCallError, function)
  775. def testMockGetIter_WithSubClassOfNewStyleClass(self):
  776. class NewStyleTestClass(object):
  777. def __iter__(self):
  778. return iter([1, 2, 3])
  779. class TestSubClass(NewStyleTestClass):
  780. pass
  781. dummy = mox.MockObject(TestSubClass)
  782. iter(dummy).AndReturn(iter(['a', 'b']))
  783. dummy._Replay()
  784. self.assertEquals(['a', 'b'], [x for x in dummy])
  785. dummy._Verify()
  786. class MoxTest(unittest.TestCase):
  787. """Verify Mox works correctly."""
  788. def setUp(self):
  789. self.mox = mox.Mox()
  790. def testCreateObject(self):
  791. """Mox should create a mock object."""
  792. mock_obj = self.mox.CreateMock(TestClass)
  793. def testVerifyObjectWithCompleteReplay(self):
  794. """Mox should replay and verify all objects it created."""
  795. mock_obj = self.mox.CreateMock(TestClass)
  796. mock_obj.ValidCall()
  797. mock_obj.ValidCallWithArgs(mox.IsA(TestClass))
  798. self.mox.ReplayAll()
  799. mock_obj.ValidCall()
  800. mock_obj.ValidCallWithArgs(TestClass("some_value"))
  801. self.mox.VerifyAll()
  802. def testVerifyObjectWithIncompleteReplay(self):
  803. """Mox should raise an exception if a mock didn't replay completely."""
  804. mock_obj = self.mox.CreateMock(TestClass)
  805. mock_obj.ValidCall()
  806. self.mox.ReplayAll()
  807. # ValidCall() is never made
  808. self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll)
  809. def testEntireWorkflow(self):
  810. """Test the whole work flow."""
  811. mock_obj = self.mox.CreateMock(TestClass)
  812. mock_obj.ValidCall().AndReturn("yes")
  813. self.mox.ReplayAll()
  814. ret_val = mock_obj.ValidCall()
  815. self.assertEquals("yes", ret_val)
  816. self.mox.VerifyAll()
  817. def testCallableObject(self):
  818. """Test recording calls to a callable object works."""
  819. mock_obj = self.mox.CreateMock(CallableClass)
  820. mock_obj("foo").AndReturn("qux")
  821. self.mox.ReplayAll()
  822. ret_val = mock_obj("foo")
  823. self.assertEquals("qux", ret_val)
  824. self.mox.VerifyAll()
  825. def testInheritedCallableObject(self):
  826. """Test recording calls to an object inheriting from a callable object."""
  827. mock_obj = self.mox.CreateMock(InheritsFromCallable)
  828. mock_obj("foo").AndReturn("qux")
  829. self.mox.ReplayAll()
  830. ret_val = mock_obj("foo")
  831. self.assertEquals("qux", ret_val)
  832. self.mox.VerifyAll()
  833. def testCallOnNonCallableObject(self):
  834. """Test that you cannot call a non-callable object."""
  835. mock_obj = self.mox.CreateMock(TestClass)
  836. self.assertRaises(TypeError, mock_obj)
  837. def testCallableObjectWithBadCall(self):
  838. """Test verifying calls to a callable object works."""
  839. mock_obj = self.mox.CreateMock(CallableClass)
  840. mock_obj("foo").AndReturn("qux")
  841. self.mox.ReplayAll()
  842. self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, "ZOOBAZ")
  843. def testUnorderedGroup(self):
  844. """Test that using one unordered group works."""
  845. mock_obj = self.mox.CreateMockAnything()
  846. mock_obj.Method(1).InAnyOrder()
  847. mock_obj.Method(2).InAnyOrder()
  848. self.mox.ReplayAll()
  849. mock_obj.Method(2)
  850. mock_obj.Method(1)
  851. self.mox.VerifyAll()
  852. def testUnorderedGroupsInline(self):
  853. """Unordered groups should work in the context of ordered calls."""
  854. mock_obj = self.mox.CreateMockAnything()
  855. mock_obj.Open()
  856. mock_obj.Method(1).InAnyOrder()
  857. mock_obj.Method(2).InAnyOrder()
  858. mock_obj.Close()
  859. self.mox.ReplayAll()
  860. mock_obj.Open()
  861. mock_obj.Method(2)
  862. mock_obj.Method(1)
  863. mock_obj.Close()
  864. self.mox.VerifyAll()
  865. def testMultipleUnorderdGroups(self):
  866. """Multiple unoreded groups should work."""
  867. mock_obj = self.mox.CreateMockAnything()
  868. mock_obj.Method(1).InAnyOrder()
  869. mock_obj.Method(2).InAnyOrder()
  870. mock_obj.Foo().InAnyOrder('group2')
  871. mock_obj.Bar().InAnyOrder('group2')
  872. self.mox.ReplayAll()
  873. mock_obj.Method(2)
  874. mock_obj.Method(1)
  875. mock_obj.Bar()
  876. mock_obj.Foo()
  877. self.mox.VerifyAll()
  878. def testMultipleUnorderdGroupsOutOfOrder(self):
  879. """Multiple unordered groups should maintain external order"""
  880. mock_obj = self.mox.CreateMockAnything()
  881. mock_obj.Method(1).InAnyOrder()
  882. mock_obj.Method(2).InAnyOrder()
  883. mock_obj.Foo().InAnyOrder('group2')
  884. mock_obj.Bar().InAnyOrder('group2')
  885. self.mox.ReplayAll()
  886. mock_obj.Method(2)
  887. self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar)
  888. def testUnorderedGroupWithReturnValue(self):
  889. """Unordered groups should work with return values."""
  890. mock_obj = self.mox.CreateMockAnything()
  891. mock_obj.Open()
  892. mock_obj.Method(1).InAnyOrder().AndReturn(9)
  893. mock_obj.Method(2).InAnyOrder().AndReturn(10)
  894. mock_obj.Close()
  895. self.mox.ReplayAll()
  896. mock_obj.Open()
  897. actual_two = mock_obj.Method(2)
  898. actual_one = mock_obj.Method(1)
  899. mock_obj.Close()
  900. self.assertEquals(9, actual_one)
  901. self.assertEquals(10, actual_two)
  902. self.mox.VerifyAll()
  903. def testUnorderedGroupWithComparator(self):
  904. """Unordered groups should work with comparators"""
  905. def VerifyOne(cmd):
  906. if not isinstance(cmd, str):
  907. self.fail('Unexpected type passed to comparator: ' + str(cmd))
  908. return cmd == 'test'
  909. def VerifyTwo(cmd):
  910. return True
  911. mock_obj = self.mox.CreateMockAnything()
  912. mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\
  913. AndReturn('yes test')
  914. mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\
  915. AndReturn('anything')
  916. self.mox.ReplayAll()
  917. mock_obj.Foo(['test'], 'anything', bar=1)
  918. mock_obj.Foo(['test'], 'test', bar=1)
  919. self.mox.VerifyAll()
  920. def testMultipleTimes(self):
  921. """Test if MultipleTimesGroup works."""
  922. mock_obj = self.mox.CreateMockAnything()
  923. mock_obj.Method(1).MultipleTimes().AndReturn(9)
  924. mock_obj.Method(2).AndReturn(10)
  925. mock_obj.Method(3).MultipleTimes().AndReturn(42)
  926. self.mox.ReplayAll()
  927. actual_one = mock_obj.Method(1)
  928. second_one = mock_obj.Method(1) # This tests MultipleTimes.
  929. actual_two = mock_obj.Method(2)
  930. actual_three = mock_obj.Method(3)
  931. mock_obj.Method(3)
  932. mock_obj.Method(3)
  933. self.mox.VerifyAll()
  934. self.assertEquals(9, actual_one)
  935. self.assertEquals(9, second_one) # Repeated calls should return same number.
  936. self.assertEquals(10, actual_two)
  937. self.assertEquals(42, actual_three)
  938. def testMultipleTimesUsingIsAParameter(self):
  939. """Test if MultipleTimesGroup works with a IsA parameter."""
  940. mock_obj = self.mox.CreateMockAnything()
  941. mock_obj.Open()
  942. mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9)
  943. mock_obj.Close()
  944. self.mox.ReplayAll()
  945. mock_obj.Open()
  946. actual_one = mock_obj.Method("1")
  947. second_one = mock_obj.Method("2") # This tests MultipleTimes.
  948. mock_obj.Close()
  949. self.mox.VerifyAll()
  950. self.assertEquals(9, actual_one)
  951. self.assertEquals(9, second_one) # Repeated calls should return same number.
  952. def testMutlipleTimesUsingFunc(self):
  953. """Test that the Func is not evaluated more times than necessary.
  954. If a Func() has side effects, it can cause a passing test to fail.
  955. """
  956. self.counter = 0
  957. def MyFunc(actual_str):
  958. """Increment the counter if actual_str == 'foo'."""
  959. if actual_str == 'foo':
  960. self.counter += 1
  961. return True
  962. mock_obj = self.mox.CreateMockAnything()
  963. mock_obj.Open()
  964. mock_obj.Method(mox.Func(MyFunc)).MultipleTimes()
  965. mock_obj.Close()
  966. self.mox.ReplayAll()
  967. mock_obj.Open()
  968. mock_obj.Method('foo')
  969. mock_obj.Method('foo')
  970. mock_obj.Method('not-foo')
  971. mock_obj.Close()
  972. self.mox.VerifyAll()
  973. self.assertEquals(2, self.counter)
  974. def testMultipleTimesThreeMethods(self):
  975. """Test if MultipleTimesGroup works with three or more methods."""
  976. mock_obj = self.mox.CreateMockAnything()
  977. mock_obj.Open()
  978. mock_obj.Method(1).MultipleTimes().AndReturn(9)
  979. mock_obj.Method(2).MultipleTimes().AndReturn(8)
  980. mock_obj.Method(3).MultipleTimes().AndReturn(7)
  981. mock_obj.Method(4).AndReturn(10)
  982. mock_obj.Close()
  983. self.mox.ReplayAll()
  984. mock_obj.Open()
  985. actual_three = mock_obj.Method(3)
  986. mock_obj.Method(1)
  987. actual_two = mock_obj.Method(2)
  988. mock_obj.Method(3)
  989. actual_one = mock_obj.Method(1)
  990. actual_four = mock_obj.Method(4)
  991. mock_obj.Close()
  992. self.assertEquals(9, actual_one)
  993. self.assertEquals(8, actual_two)
  994. self.assertEquals(7, actual_three)
  995. self.assertEquals(10, actual_four)
  996. self.mox.VerifyAll()
  997. def testMultipleTimesMissingOne(self):
  998. """Test if MultipleTimesGroup fails if one method is missing."""
  999. mock_obj = self.mox.CreateMockAnything()
  1000. mock_obj.Open()
  1001. mock_obj.Method(1).MultipleTimes().AndReturn(9)
  1002. mock_obj.Method(2).MultipleTimes().AndReturn(8)
  1003. mock_obj.Method(3).MultipleTimes().AndReturn(7)
  1004. mock_obj.Method(4).AndReturn(10)
  1005. mock_obj.Close()
  1006. self.mox.ReplayAll()
  1007. mock_obj.Open()
  1008. mock_obj.Method(3)
  1009. mock_obj.Method(2)
  1010. mock_obj.Method(3)
  1011. mock_obj.Method(3)
  1012. mock_obj.Method(2)
  1013. self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4)
  1014. def testMultipleTimesTwoGroups(self):
  1015. """Test if MultipleTimesGroup works with a group after a
  1016. MultipleTimesGroup.
  1017. """
  1018. mock_obj = self.mox.CreateMockAnything()
  1019. mock_obj.Open()
  1020. mock_obj.Method(1).MultipleTimes().AndReturn(9)
  1021. mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
  1022. mock_obj.Close()
  1023. self.mox.ReplayAll()
  1024. mock_obj.Open()
  1025. actual_one = mock_obj.Method(1)
  1026. mock_obj.Method(1)
  1027. actual_three = mock_obj.Method(3)
  1028. mock_obj.Method(3)
  1029. mock_obj.Close()
  1030. self.assertEquals(9, actual_one)
  1031. self.assertEquals(42, actual_three)
  1032. self.mox.VerifyAll()
  1033. def testMultipleTimesTwoGroupsFailure(self):
  1034. """Test if MultipleTimesGroup fails with a group after a
  1035. MultipleTimesGroup.
  1036. """
  1037. mock_obj = self.mox.CreateMockAnything()
  1038. mock_obj.Open()
  1039. mock_obj.Method(1).MultipleTimes().AndReturn(9)
  1040. mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
  1041. mock_obj.Close()
  1042. self.mox.ReplayAll()
  1043. mock_obj.Open()
  1044. actual_one = mock_obj.Method(1)
  1045. mock_obj.Method(1)
  1046. actual_three = mock_obj.Method(3)
  1047. self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1)
  1048. def testWithSideEffects(self):
  1049. """Test side effect operations actually modify their target objects."""
  1050. def modifier(mutable_list):
  1051. mutable_list[0] = 'mutated'
  1052. mock_obj = self.mox.CreateMockAnything()
  1053. mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier)
  1054. mock_obj.WorkWithParameter(['mutated'])
  1055. self.mox.ReplayAll()
  1056. local_list = ['original']
  1057. mock_obj.ConfigureInOutParameter(local_list)
  1058. mock_obj.WorkWithParameter(local_list)
  1059. self.mox.VerifyAll()
  1060. def testWithSideEffectsException(self):
  1061. """Test side effect operations actually modify their target objects."""
  1062. def modifier(mutable_list):
  1063. mutable_list[0] = 'mutated'
  1064. mock_obj = self.mox.CreateMockAnything()
  1065. method = mock_obj.ConfigureInOutParameter(['original'])
  1066. method.WithSideEffects(modifier).AndRaise(Exception('exception'))
  1067. mock_obj.WorkWithParameter(['mutated'])
  1068. self.mox.ReplayAll()
  1069. local_list = ['original']
  1070. self.failUnlessRaises(Exception,
  1071. mock_obj.ConfigureInOutParameter,
  1072. local_list)
  1073. mock_obj.WorkWithParameter(local_list)
  1074. self.mox.VerifyAll()
  1075. def testStubOutMethod(self):
  1076. """Test that a method is replaced with a MockAnything."""
  1077. test_obj = TestClass()
  1078. # Replace OtherValidCall with a mock.
  1079. self.mox.StubOutWithMock(test_obj, 'OtherValidCall')
  1080. self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything))
  1081. test_obj.OtherValidCall().AndReturn('foo')
  1082. self.mox.ReplayAll()
  1083. actual = test_obj.OtherValidCall()
  1084. self.mox.VerifyAll()
  1085. self.mox.UnsetStubs()
  1086. self.assertEquals('foo', actual)
  1087. self.failIf(isinstance(test_obj.OtherValidCall, mox.MockAnything))
  1088. def testWarnsUserIfMockingMock(self):
  1089. """Test that user is warned if they try to stub out a MockAnything."""
  1090. self.mox.StubOutWithMock(TestClass, 'MyStaticMethod')
  1091. self.assertRaises(TypeError, self.mox.StubOutWithMock, TestClass,
  1092. 'MyStaticMethod')
  1093. def testStubOutObject(self):
  1094. """Test than object is replaced with a Mock."""
  1095. class Foo(object):
  1096. def __init__(self):
  1097. self.obj = TestClass()
  1098. foo = Foo()
  1099. self.mox.StubOutWithMock(foo, "obj")
  1100. self.assert_(isinstance(foo.obj, mox.MockObject))
  1101. foo.obj.ValidCall()
  1102. self.mox.ReplayAll()
  1103. foo.obj.ValidCall()
  1104. self.mox.VerifyAll()
  1105. self.mox.UnsetStubs()
  1106. self.failIf(isinstance(foo.obj, mox.MockObject))
  1107. def testForgotReplayHelpfulMessage(self):
  1108. """If there is an AttributeError on a MockMethod, give users a helpful msg.
  1109. """
  1110. foo = self.mox.CreateMockAnything()
  1111. bar = self.mox.CreateMockAnything()
  1112. foo.GetBar().AndReturn(bar)
  1113. bar.ShowMeTheMoney()
  1114. # Forgot to replay!
  1115. try:
  1116. foo.GetBar().ShowMeTheMoney()
  1117. except AttributeError, e:
  1118. self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". '
  1119. 'Did you remember to put your mocks in replay mode?', str(e))
  1120. class ReplayTest(unittest.TestCase):
  1121. """Verify Replay works properly."""
  1122. def testReplay(self):
  1123. """Replay should put objects into replay mode."""
  1124. mock_obj = mox.MockObject(TestClass)
  1125. self.assertFalse(mock_obj._replay_mode)
  1126. mox.Replay(mock_obj)
  1127. self.assertTrue(mock_obj._replay_mode)
  1128. class MoxTestBaseTest(unittest.TestCase):
  1129. """Verify that all tests in a class derived from MoxTestBase are wrapped."""
  1130. def setUp(self):
  1131. self.mox = mox.Mox()
  1132. self.test_mox = mox.Mox()
  1133. self.result = unittest.TestResult()
  1134. def tearDown(self):
  1135. # In case one of our tests fail before UnsetStubs is called.
  1136. self.mox.UnsetStubs()
  1137. self.test_mox.UnsetStubs()
  1138. def _setUpTestClass(self):
  1139. """Replacement for setUp in the test class instance.
  1140. Assigns a mox.Mox instance as the mox attribute of the test class instance.
  1141. This replacement Mox instance is under our control before setUp is called
  1142. in the test class instance.
  1143. """
  1144. self.test.mox = self.test_mox
  1145. def _CreateTest(self, test_name):
  1146. """Create a test from our example mox class.
  1147. The created test instance is assigned to this instances test attribute.
  1148. """
  1149. self.test = mox_test_helper.ExampleMoxTest(test_name)
  1150. self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass)
  1151. def _VerifySuccess(self):
  1152. """Run the checks to confirm test method completed successfully."""
  1153. self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
  1154. self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
  1155. self.test_mox.UnsetStubs()
  1156. self.test_mox.VerifyAll()
  1157. self.mox.ReplayAll()
  1158. self.test.run(result=self.result)
  1159. self.assertTrue(self.result.wasSuccessful())
  1160. self.mox.UnsetStubs()
  1161. self.mox.VerifyAll()
  1162. self.test_mox.UnsetStubs()
  1163. self.test_mox.VerifyAll()
  1164. def testSuccess(self):
  1165. """Successful test method execution test."""
  1166. self._CreateTest('testSuccess')
  1167. self._VerifySuccess()
  1168. def testExpectedNotCalled(self):
  1169. """Stubbed out method is not called."""
  1170. self._CreateTest('testExpectedNotCalled')
  1171. self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
  1172. # Dont stub out VerifyAll - that's what causes the test to fail
  1173. self.test_mox.UnsetStubs()
  1174. self.test_mox.VerifyAll()
  1175. self.mox.ReplayAll()
  1176. self.test.run(result=self.result)
  1177. self.failIf(self.result.wasSuccessful())
  1178. self.mox.UnsetStubs()
  1179. self.mox.VerifyAll()
  1180. self.test_mox.UnsetStubs()
  1181. def testUnexpectedCall(self):
  1182. """Stubbed out method is called with unexpected arguments."""
  1183. self._CreateTest('testUnexpectedCall')
  1184. self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
  1185. # Ensure no calls are made to VerifyAll()
  1186. self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
  1187. self.test_mox.UnsetStubs()
  1188. self.mox.ReplayAll()
  1189. self.test.run(result=self.result)
  1190. self.failIf(self.result.wasSuccessful())
  1191. self.mox.UnsetStubs()
  1192. self.mox.VerifyAll()
  1193. self.test_mox.UnsetStubs()
  1194. def testFailure(self):
  1195. """Failing assertion in test method."""
  1196. self._CreateTest('testFailure')
  1197. self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
  1198. # Ensure no calls are made to VerifyAll()
  1199. self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
  1200. self.test_mox.UnsetStubs()
  1201. self.mox.ReplayAll()
  1202. self.test.run(result=self.result)
  1203. self.failIf(self.result.wasSuccessful())
  1204. self.mox.UnsetStubs()
  1205. self.mox.VerifyAll()
  1206. self.test_mox.UnsetStubs()
  1207. def testMixin(self):
  1208. """Run test from mix-in test class, ensure it passes."""
  1209. self._CreateTest('testStat')
  1210. self._VerifySuccess()
  1211. def testMixinAgain(self):
  1212. """Run same test as above but from the current test class.
  1213. This ensures metaclass properly wrapped test methods from all base classes.
  1214. If unsetting of stubs doesn't happen, this will fail.
  1215. """
  1216. self._CreateTest('testStatOther')
  1217. self._VerifySuccess()
  1218. class VerifyTest(unittest.TestCase):
  1219. """Verify Verify works properly."""
  1220. def testVerify(self):
  1221. """Verify should be called for all objects.
  1222. This should throw an exception because the expected behavior did not occur.
  1223. """
  1224. mock_obj = mox.MockObject(TestClass)
  1225. mock_obj.ValidCall()
  1226. mock_obj._Replay()
  1227. self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
  1228. class ResetTest(unittest.TestCase):
  1229. """Verify Reset works properly."""
  1230. def testReset(self):
  1231. """Should empty all queues and put mocks in record mode."""
  1232. mock_obj = mox.MockObject(TestClass)
  1233. mock_obj.ValidCall()
  1234. self.assertFalse(mock_obj._replay_mode)
  1235. mock_obj._Replay()
  1236. self.assertTrue(mock_obj._replay_mode)
  1237. self.assertEquals(1, len(mock_obj._expected_calls_queue))
  1238. mox.Reset(mock_obj)
  1239. self.assertFalse(mock_obj._replay_mode)
  1240. self.assertEquals(0, len(mock_obj._expected_calls_queue))
  1241. class MyTestCase(unittest.TestCase):
  1242. """Simulate the use of a fake wrapper around Python's unittest library."""
  1243. def setUp(self):
  1244. super(MyTestCase, self).setUp()
  1245. self.critical_variable = 42
  1246. class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase):
  1247. """Test that multiple inheritance can be used with MoxTestBase."""
  1248. def setUp(self):
  1249. super(MoxTestBaseMultipleInheritanceTest, self).setUp()
  1250. def testMultipleInheritance(self):
  1251. """Should be able to access members created by all parent setUp()."""
  1252. self.assert_(isinstance(self.mox, mox.Mox))
  1253. self.assertEquals(42, self.critical_variable)
  1254. class TestClass:
  1255. """This class is used only for testing the mock framework"""
  1256. SOME_CLASS_VAR = "test_value"
  1257. _PROTECTED_CLASS_VAR = "protected value"
  1258. def __init__(self, ivar=None):
  1259. self.__ivar = ivar
  1260. def __eq__(self, rhs):
  1261. return self.__ivar == rhs
  1262. def __ne__(self, rhs):
  1263. return not self.__eq__(rhs)
  1264. def ValidCall(self):
  1265. pass
  1266. def OtherValidCall(self):
  1267. pass
  1268. def ValidCallWithArgs(self, *args, **kwargs):
  1269. pass
  1270. @classmethod
  1271. def MyClassMethod(cls):
  1272. pass
  1273. @staticmethod
  1274. def MyStaticMethod():
  1275. pass
  1276. def _ProtectedCall(self):
  1277. pass
  1278. def __PrivateCall(self):
  1279. pass
  1280. def __getitem__(self, key):
  1281. pass
  1282. def __DoNotMock(self):
  1283. pass
  1284. def __getitem__(self, key):
  1285. """Return the value for key."""
  1286. return self.d[key]
  1287. def __setitem__(self, key, value):
  1288. """Set the value for key to value."""
  1289. self.d[key] = value
  1290. def __contains__(self, key):
  1291. """Returns True if d contains the key."""
  1292. return key in self.d
  1293. def __iter__(self):
  1294. pass
  1295. class ChildClass(TestClass):
  1296. """This inherits from TestClass."""
  1297. def __init__(self):
  1298. TestClass.__init__(self)
  1299. def ChildValidCall(self):
  1300. pass
  1301. class CallableClass(object):
  1302. """This class is callable, and that should be mockable!"""
  1303. def __init__(self):
  1304. pass
  1305. def __call__(self, param):
  1306. return param
  1307. class SubscribtableNonIterableClass(object):
  1308. def __getitem__(self, index):
  1309. raise IndexError
  1310. class InheritsFromCallable(CallableClass):
  1311. """This class should also be mockable; it inherits from a callable class."""
  1312. pass
  1313. if __name__ == '__main__':
  1314. unittest.main()