mox.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. #!/usr/bin/python2.4
  2. #
  3. # Copyright 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # This file is used for testing. The original is at:
  17. # http://code.google.com/p/pymox/
  18. """Mox, an object-mocking framework for Python.
  19. Mox works in the record-replay-verify paradigm. When you first create
  20. a mock object, it is in record mode. You then programmatically set
  21. the expected behavior of the mock object (what methods are to be
  22. called on it, with what parameters, what they should return, and in
  23. what order).
  24. Once you have set up the expected mock behavior, you put it in replay
  25. mode. Now the mock responds to method calls just as you told it to.
  26. If an unexpected method (or an expected method with unexpected
  27. parameters) is called, then an exception will be raised.
  28. Once you are done interacting with the mock, you need to verify that
  29. all the expected interactions occurred. (Maybe your code exited
  30. prematurely without calling some cleanup method!) The verify phase
  31. ensures that every expected method was called; otherwise, an exception
  32. will be raised.
  33. Suggested usage / workflow:
  34. # Create Mox factory
  35. my_mox = Mox()
  36. # Create a mock data access object
  37. mock_dao = my_mox.CreateMock(DAOClass)
  38. # Set up expected behavior
  39. mock_dao.RetrievePersonWithIdentifier('1').AndReturn(person)
  40. mock_dao.DeletePerson(person)
  41. # Put mocks in replay mode
  42. my_mox.ReplayAll()
  43. # Inject mock object and run test
  44. controller.SetDao(mock_dao)
  45. controller.DeletePersonById('1')
  46. # Verify all methods were called as expected
  47. my_mox.VerifyAll()
  48. """
  49. from collections import deque
  50. import re
  51. import types
  52. import unittest
  53. import stubout
  54. class Error(AssertionError):
  55. """Base exception for this module."""
  56. pass
  57. class ExpectedMethodCallsError(Error):
  58. """Raised when Verify() is called before all expected methods have been called
  59. """
  60. def __init__(self, expected_methods):
  61. """Init exception.
  62. Args:
  63. # expected_methods: A sequence of MockMethod objects that should have been
  64. # called.
  65. expected_methods: [MockMethod]
  66. Raises:
  67. ValueError: if expected_methods contains no methods.
  68. """
  69. if not expected_methods:
  70. raise ValueError("There must be at least one expected method")
  71. Error.__init__(self)
  72. self._expected_methods = expected_methods
  73. def __str__(self):
  74. calls = "\n".join(["%3d. %s" % (i, m)
  75. for i, m in enumerate(self._expected_methods)])
  76. return "Verify: Expected methods never called:\n%s" % (calls,)
  77. class UnexpectedMethodCallError(Error):
  78. """Raised when an unexpected method is called.
  79. This can occur if a method is called with incorrect parameters, or out of the
  80. specified order.
  81. """
  82. def __init__(self, unexpected_method, expected):
  83. """Init exception.
  84. Args:
  85. # unexpected_method: MockMethod that was called but was not at the head of
  86. # the expected_method queue.
  87. # expected: MockMethod or UnorderedGroup the method should have
  88. # been in.
  89. unexpected_method: MockMethod
  90. expected: MockMethod or UnorderedGroup
  91. """
  92. Error.__init__(self)
  93. self._unexpected_method = unexpected_method
  94. self._expected = expected
  95. def __str__(self):
  96. return "Unexpected method call: %s. Expecting: %s" % \
  97. (self._unexpected_method, self._expected)
  98. class UnknownMethodCallError(Error):
  99. """Raised if an unknown method is requested of the mock object."""
  100. def __init__(self, unknown_method_name):
  101. """Init exception.
  102. Args:
  103. # unknown_method_name: Method call that is not part of the mocked class's
  104. # public interface.
  105. unknown_method_name: str
  106. """
  107. Error.__init__(self)
  108. self._unknown_method_name = unknown_method_name
  109. def __str__(self):
  110. return "Method called is not a member of the object: %s" % \
  111. self._unknown_method_name
  112. class Mox(object):
  113. """Mox: a factory for creating mock objects."""
  114. # A list of types that should be stubbed out with MockObjects (as
  115. # opposed to MockAnythings).
  116. _USE_MOCK_OBJECT = [types.ClassType, types.InstanceType, types.ModuleType,
  117. types.ObjectType, types.TypeType]
  118. def __init__(self):
  119. """Initialize a new Mox."""
  120. self._mock_objects = []
  121. self.stubs = stubout.StubOutForTesting()
  122. def CreateMock(self, class_to_mock):
  123. """Create a new mock object.
  124. Args:
  125. # class_to_mock: the class to be mocked
  126. class_to_mock: class
  127. Returns:
  128. MockObject that can be used as the class_to_mock would be.
  129. """
  130. new_mock = MockObject(class_to_mock)
  131. self._mock_objects.append(new_mock)
  132. return new_mock
  133. def CreateMockAnything(self):
  134. """Create a mock that will accept any method calls.
  135. This does not enforce an interface.
  136. """
  137. new_mock = MockAnything()
  138. self._mock_objects.append(new_mock)
  139. return new_mock
  140. def ReplayAll(self):
  141. """Set all mock objects to replay mode."""
  142. for mock_obj in self._mock_objects:
  143. mock_obj._Replay()
  144. def VerifyAll(self):
  145. """Call verify on all mock objects created."""
  146. for mock_obj in self._mock_objects:
  147. mock_obj._Verify()
  148. def ResetAll(self):
  149. """Call reset on all mock objects. This does not unset stubs."""
  150. for mock_obj in self._mock_objects:
  151. mock_obj._Reset()
  152. def StubOutWithMock(self, obj, attr_name, use_mock_anything=False):
  153. """Replace a method, attribute, etc. with a Mock.
  154. This will replace a class or module with a MockObject, and everything else
  155. (method, function, etc) with a MockAnything. This can be overridden to
  156. always use a MockAnything by setting use_mock_anything to True.
  157. Args:
  158. obj: A Python object (class, module, instance, callable).
  159. attr_name: str. The name of the attribute to replace with a mock.
  160. use_mock_anything: bool. True if a MockAnything should be used regardless
  161. of the type of attribute.
  162. """
  163. attr_to_replace = getattr(obj, attr_name)
  164. if type(attr_to_replace) in self._USE_MOCK_OBJECT and not use_mock_anything:
  165. stub = self.CreateMock(attr_to_replace)
  166. else:
  167. stub = self.CreateMockAnything()
  168. self.stubs.Set(obj, attr_name, stub)
  169. def UnsetStubs(self):
  170. """Restore stubs to their original state."""
  171. self.stubs.UnsetAll()
  172. def Replay(*args):
  173. """Put mocks into Replay mode.
  174. Args:
  175. # args is any number of mocks to put into replay mode.
  176. """
  177. for mock in args:
  178. mock._Replay()
  179. def Verify(*args):
  180. """Verify mocks.
  181. Args:
  182. # args is any number of mocks to be verified.
  183. """
  184. for mock in args:
  185. mock._Verify()
  186. def Reset(*args):
  187. """Reset mocks.
  188. Args:
  189. # args is any number of mocks to be reset.
  190. """
  191. for mock in args:
  192. mock._Reset()
  193. class MockAnything:
  194. """A mock that can be used to mock anything.
  195. This is helpful for mocking classes that do not provide a public interface.
  196. """
  197. def __init__(self):
  198. """ """
  199. self._Reset()
  200. def __getattr__(self, method_name):
  201. """Intercept method calls on this object.
  202. A new MockMethod is returned that is aware of the MockAnything's
  203. state (record or replay). The call will be recorded or replayed
  204. by the MockMethod's __call__.
  205. Args:
  206. # method name: the name of the method being called.
  207. method_name: str
  208. Returns:
  209. A new MockMethod aware of MockAnything's state (record or replay).
  210. """
  211. return self._CreateMockMethod(method_name)
  212. def _CreateMockMethod(self, method_name):
  213. """Create a new mock method call and return it.
  214. Args:
  215. # method name: the name of the method being called.
  216. method_name: str
  217. Returns:
  218. A new MockMethod aware of MockAnything's state (record or replay).
  219. """
  220. return MockMethod(method_name, self._expected_calls_queue,
  221. self._replay_mode)
  222. def __nonzero__(self):
  223. """Return 1 for nonzero so the mock can be used as a conditional."""
  224. return 1
  225. def __eq__(self, rhs):
  226. """Provide custom logic to compare objects."""
  227. return (isinstance(rhs, MockAnything) and
  228. self._replay_mode == rhs._replay_mode and
  229. self._expected_calls_queue == rhs._expected_calls_queue)
  230. def __ne__(self, rhs):
  231. """Provide custom logic to compare objects."""
  232. return not self == rhs
  233. def _Replay(self):
  234. """Start replaying expected method calls."""
  235. self._replay_mode = True
  236. def _Verify(self):
  237. """Verify that all of the expected calls have been made.
  238. Raises:
  239. ExpectedMethodCallsError: if there are still more method calls in the
  240. expected queue.
  241. """
  242. # If the list of expected calls is not empty, raise an exception
  243. if self._expected_calls_queue:
  244. # The last MultipleTimesGroup is not popped from the queue.
  245. if (len(self._expected_calls_queue) == 1 and
  246. isinstance(self._expected_calls_queue[0], MultipleTimesGroup) and
  247. self._expected_calls_queue[0].IsSatisfied()):
  248. pass
  249. else:
  250. raise ExpectedMethodCallsError(self._expected_calls_queue)
  251. def _Reset(self):
  252. """Reset the state of this mock to record mode with an empty queue."""
  253. # Maintain a list of method calls we are expecting
  254. self._expected_calls_queue = deque()
  255. # Make sure we are in setup mode, not replay mode
  256. self._replay_mode = False
  257. class MockObject(MockAnything, object):
  258. """A mock object that simulates the public/protected interface of a class."""
  259. def __init__(self, class_to_mock):
  260. """Initialize a mock object.
  261. This determines the methods and properties of the class and stores them.
  262. Args:
  263. # class_to_mock: class to be mocked
  264. class_to_mock: class
  265. """
  266. # This is used to hack around the mixin/inheritance of MockAnything, which
  267. # is not a proper object (it can be anything. :-)
  268. MockAnything.__dict__['__init__'](self)
  269. # Get a list of all the public and special methods we should mock.
  270. self._known_methods = set()
  271. self._known_vars = set()
  272. self._class_to_mock = class_to_mock
  273. for method in dir(class_to_mock):
  274. if callable(getattr(class_to_mock, method)):
  275. self._known_methods.add(method)
  276. else:
  277. self._known_vars.add(method)
  278. def __getattr__(self, name):
  279. """Intercept attribute request on this object.
  280. If the attribute is a public class variable, it will be returned and not
  281. recorded as a call.
  282. If the attribute is not a variable, it is handled like a method
  283. call. The method name is checked against the set of mockable
  284. methods, and a new MockMethod is returned that is aware of the
  285. MockObject's state (record or replay). The call will be recorded
  286. or replayed by the MockMethod's __call__.
  287. Args:
  288. # name: the name of the attribute being requested.
  289. name: str
  290. Returns:
  291. Either a class variable or a new MockMethod that is aware of the state
  292. of the mock (record or replay).
  293. Raises:
  294. UnknownMethodCallError if the MockObject does not mock the requested
  295. method.
  296. """
  297. if name in self._known_vars:
  298. return getattr(self._class_to_mock, name)
  299. if name in self._known_methods:
  300. return self._CreateMockMethod(name)
  301. raise UnknownMethodCallError(name)
  302. def __eq__(self, rhs):
  303. """Provide custom logic to compare objects."""
  304. return (isinstance(rhs, MockObject) and
  305. self._class_to_mock == rhs._class_to_mock and
  306. self._replay_mode == rhs._replay_mode and
  307. self._expected_calls_queue == rhs._expected_calls_queue)
  308. def __setitem__(self, key, value):
  309. """Provide custom logic for mocking classes that support item assignment.
  310. Args:
  311. key: Key to set the value for.
  312. value: Value to set.
  313. Returns:
  314. Expected return value in replay mode. A MockMethod object for the
  315. __setitem__ method that has already been called if not in replay mode.
  316. Raises:
  317. TypeError if the underlying class does not support item assignment.
  318. UnexpectedMethodCallError if the object does not expect the call to
  319. __setitem__.
  320. """
  321. setitem = self._class_to_mock.__dict__.get('__setitem__', None)
  322. # Verify the class supports item assignment.
  323. if setitem is None:
  324. raise TypeError('object does not support item assignment')
  325. # If we are in replay mode then simply call the mock __setitem__ method.
  326. if self._replay_mode:
  327. return MockMethod('__setitem__', self._expected_calls_queue,
  328. self._replay_mode)(key, value)
  329. # Otherwise, create a mock method __setitem__.
  330. return self._CreateMockMethod('__setitem__')(key, value)
  331. def __getitem__(self, key):
  332. """Provide custom logic for mocking classes that are subscriptable.
  333. Args:
  334. key: Key to return the value for.
  335. Returns:
  336. Expected return value in replay mode. A MockMethod object for the
  337. __getitem__ method that has already been called if not in replay mode.
  338. Raises:
  339. TypeError if the underlying class is not subscriptable.
  340. UnexpectedMethodCallError if the object does not expect the call to
  341. __setitem__.
  342. """
  343. getitem = self._class_to_mock.__dict__.get('__getitem__', None)
  344. # Verify the class supports item assignment.
  345. if getitem is None:
  346. raise TypeError('unsubscriptable object')
  347. # If we are in replay mode then simply call the mock __getitem__ method.
  348. if self._replay_mode:
  349. return MockMethod('__getitem__', self._expected_calls_queue,
  350. self._replay_mode)(key)
  351. # Otherwise, create a mock method __getitem__.
  352. return self._CreateMockMethod('__getitem__')(key)
  353. def __call__(self, *params, **named_params):
  354. """Provide custom logic for mocking classes that are callable."""
  355. # Verify the class we are mocking is callable
  356. callable = self._class_to_mock.__dict__.get('__call__', None)
  357. if callable is None:
  358. raise TypeError('Not callable')
  359. # Because the call is happening directly on this object instead of a method,
  360. # the call on the mock method is made right here
  361. mock_method = self._CreateMockMethod('__call__')
  362. return mock_method(*params, **named_params)
  363. @property
  364. def __class__(self):
  365. """Return the class that is being mocked."""
  366. return self._class_to_mock
  367. class MockMethod(object):
  368. """Callable mock method.
  369. A MockMethod should act exactly like the method it mocks, accepting parameters
  370. and returning a value, or throwing an exception (as specified). When this
  371. method is called, it can optionally verify whether the called method (name and
  372. signature) matches the expected method.
  373. """
  374. def __init__(self, method_name, call_queue, replay_mode):
  375. """Construct a new mock method.
  376. Args:
  377. # method_name: the name of the method
  378. # call_queue: deque of calls, verify this call against the head, or add
  379. # this call to the queue.
  380. # replay_mode: False if we are recording, True if we are verifying calls
  381. # against the call queue.
  382. method_name: str
  383. call_queue: list or deque
  384. replay_mode: bool
  385. """
  386. self._name = method_name
  387. self._call_queue = call_queue
  388. if not isinstance(call_queue, deque):
  389. self._call_queue = deque(self._call_queue)
  390. self._replay_mode = replay_mode
  391. self._params = None
  392. self._named_params = None
  393. self._return_value = None
  394. self._exception = None
  395. self._side_effects = None
  396. def __call__(self, *params, **named_params):
  397. """Log parameters and return the specified return value.
  398. If the Mock(Anything/Object) associated with this call is in record mode,
  399. this MockMethod will be pushed onto the expected call queue. If the mock
  400. is in replay mode, this will pop a MockMethod off the top of the queue and
  401. verify this call is equal to the expected call.
  402. Raises:
  403. UnexpectedMethodCall if this call is supposed to match an expected method
  404. call and it does not.
  405. """
  406. self._params = params
  407. self._named_params = named_params
  408. if not self._replay_mode:
  409. self._call_queue.append(self)
  410. return self
  411. expected_method = self._VerifyMethodCall()
  412. if expected_method._side_effects:
  413. expected_method._side_effects(*params, **named_params)
  414. if expected_method._exception:
  415. raise expected_method._exception
  416. return expected_method._return_value
  417. def __getattr__(self, name):
  418. """Raise an AttributeError with a helpful message."""
  419. raise AttributeError('MockMethod has no attribute "%s". '
  420. 'Did you remember to put your mocks in replay mode?' % name)
  421. def _PopNextMethod(self):
  422. """Pop the next method from our call queue."""
  423. try:
  424. return self._call_queue.popleft()
  425. except IndexError:
  426. raise UnexpectedMethodCallError(self, None)
  427. def _VerifyMethodCall(self):
  428. """Verify the called method is expected.
  429. This can be an ordered method, or part of an unordered set.
  430. Returns:
  431. The expected mock method.
  432. Raises:
  433. UnexpectedMethodCall if the method called was not expected.
  434. """
  435. expected = self._PopNextMethod()
  436. # Loop here, because we might have a MethodGroup followed by another
  437. # group.
  438. while isinstance(expected, MethodGroup):
  439. expected, method = expected.MethodCalled(self)
  440. if method is not None:
  441. return method
  442. # This is a mock method, so just check equality.
  443. if expected != self:
  444. raise UnexpectedMethodCallError(self, expected)
  445. return expected
  446. def __str__(self):
  447. params = ', '.join(
  448. [repr(p) for p in self._params or []] +
  449. ['%s=%r' % x for x in sorted((self._named_params or {}).items())])
  450. desc = "%s(%s) -> %r" % (self._name, params, self._return_value)
  451. return desc
  452. def __eq__(self, rhs):
  453. """Test whether this MockMethod is equivalent to another MockMethod.
  454. Args:
  455. # rhs: the right hand side of the test
  456. rhs: MockMethod
  457. """
  458. return (isinstance(rhs, MockMethod) and
  459. self._name == rhs._name and
  460. self._params == rhs._params and
  461. self._named_params == rhs._named_params)
  462. def __ne__(self, rhs):
  463. """Test whether this MockMethod is not equivalent to another MockMethod.
  464. Args:
  465. # rhs: the right hand side of the test
  466. rhs: MockMethod
  467. """
  468. return not self == rhs
  469. def GetPossibleGroup(self):
  470. """Returns a possible group from the end of the call queue or None if no
  471. other methods are on the stack.
  472. """
  473. # Remove this method from the tail of the queue so we can add it to a group.
  474. this_method = self._call_queue.pop()
  475. assert this_method == self
  476. # Determine if the tail of the queue is a group, or just a regular ordered
  477. # mock method.
  478. group = None
  479. try:
  480. group = self._call_queue[-1]
  481. except IndexError:
  482. pass
  483. return group
  484. def _CheckAndCreateNewGroup(self, group_name, group_class):
  485. """Checks if the last method (a possible group) is an instance of our
  486. group_class. Adds the current method to this group or creates a new one.
  487. Args:
  488. group_name: the name of the group.
  489. group_class: the class used to create instance of this new group
  490. """
  491. group = self.GetPossibleGroup()
  492. # If this is a group, and it is the correct group, add the method.
  493. if isinstance(group, group_class) and group.group_name() == group_name:
  494. group.AddMethod(self)
  495. return self
  496. # Create a new group and add the method.
  497. new_group = group_class(group_name)
  498. new_group.AddMethod(self)
  499. self._call_queue.append(new_group)
  500. return self
  501. def InAnyOrder(self, group_name="default"):
  502. """Move this method into a group of unordered calls.
  503. A group of unordered calls must be defined together, and must be executed
  504. in full before the next expected method can be called. There can be
  505. multiple groups that are expected serially, if they are given
  506. different group names. The same group name can be reused if there is a
  507. standard method call, or a group with a different name, spliced between
  508. usages.
  509. Args:
  510. group_name: the name of the unordered group.
  511. Returns:
  512. self
  513. """
  514. return self._CheckAndCreateNewGroup(group_name, UnorderedGroup)
  515. def MultipleTimes(self, group_name="default"):
  516. """Move this method into group of calls which may be called multiple times.
  517. A group of repeating calls must be defined together, and must be executed in
  518. full before the next expected method can be called.
  519. Args:
  520. group_name: the name of the unordered group.
  521. Returns:
  522. self
  523. """
  524. return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup)
  525. def AndReturn(self, return_value):
  526. """Set the value to return when this method is called.
  527. Args:
  528. # return_value can be anything.
  529. """
  530. self._return_value = return_value
  531. return return_value
  532. def AndRaise(self, exception):
  533. """Set the exception to raise when this method is called.
  534. Args:
  535. # exception: the exception to raise when this method is called.
  536. exception: Exception
  537. """
  538. self._exception = exception
  539. def WithSideEffects(self, side_effects):
  540. """Set the side effects that are simulated when this method is called.
  541. Args:
  542. side_effects: A callable which modifies the parameters or other relevant
  543. state which a given test case depends on.
  544. Returns:
  545. Self for chaining with AndReturn and AndRaise.
  546. """
  547. self._side_effects = side_effects
  548. return self
  549. class Comparator:
  550. """Base class for all Mox comparators.
  551. A Comparator can be used as a parameter to a mocked method when the exact
  552. value is not known. For example, the code you are testing might build up a
  553. long SQL string that is passed to your mock DAO. You're only interested that
  554. the IN clause contains the proper primary keys, so you can set your mock
  555. up as follows:
  556. mock_dao.RunQuery(StrContains('IN (1, 2, 4, 5)')).AndReturn(mock_result)
  557. Now whatever query is passed in must contain the string 'IN (1, 2, 4, 5)'.
  558. A Comparator may replace one or more parameters, for example:
  559. # return at most 10 rows
  560. mock_dao.RunQuery(StrContains('SELECT'), 10)
  561. or
  562. # Return some non-deterministic number of rows
  563. mock_dao.RunQuery(StrContains('SELECT'), IsA(int))
  564. """
  565. def equals(self, rhs):
  566. """Special equals method that all comparators must implement.
  567. Args:
  568. rhs: any python object
  569. """
  570. raise NotImplementedError('method must be implemented by a subclass.')
  571. def __eq__(self, rhs):
  572. return self.equals(rhs)
  573. def __ne__(self, rhs):
  574. return not self.equals(rhs)
  575. class IsA(Comparator):
  576. """This class wraps a basic Python type or class. It is used to verify
  577. that a parameter is of the given type or class.
  578. Example:
  579. mock_dao.Connect(IsA(DbConnectInfo))
  580. """
  581. def __init__(self, class_name):
  582. """Initialize IsA
  583. Args:
  584. class_name: basic python type or a class
  585. """
  586. self._class_name = class_name
  587. def equals(self, rhs):
  588. """Check to see if the RHS is an instance of class_name.
  589. Args:
  590. # rhs: the right hand side of the test
  591. rhs: object
  592. Returns:
  593. bool
  594. """
  595. try:
  596. return isinstance(rhs, self._class_name)
  597. except TypeError:
  598. # Check raw types if there was a type error. This is helpful for
  599. # things like cStringIO.StringIO.
  600. return type(rhs) == type(self._class_name)
  601. def __repr__(self):
  602. return str(self._class_name)
  603. class IsAlmost(Comparator):
  604. """Comparison class used to check whether a parameter is nearly equal
  605. to a given value. Generally useful for floating point numbers.
  606. Example mock_dao.SetTimeout((IsAlmost(3.9)))
  607. """
  608. def __init__(self, float_value, places=7):
  609. """Initialize IsAlmost.
  610. Args:
  611. float_value: The value for making the comparison.
  612. places: The number of decimal places to round to.
  613. """
  614. self._float_value = float_value
  615. self._places = places
  616. def equals(self, rhs):
  617. """Check to see if RHS is almost equal to float_value
  618. Args:
  619. rhs: the value to compare to float_value
  620. Returns:
  621. bool
  622. """
  623. try:
  624. return round(rhs-self._float_value, self._places) == 0
  625. except TypeError:
  626. # This is probably because either float_value or rhs is not a number.
  627. return False
  628. def __repr__(self):
  629. return str(self._float_value)
  630. class StrContains(Comparator):
  631. """Comparison class used to check whether a substring exists in a
  632. string parameter. This can be useful in mocking a database with SQL
  633. passed in as a string parameter, for example.
  634. Example:
  635. mock_dao.RunQuery(StrContains('IN (1, 2, 4, 5)')).AndReturn(mock_result)
  636. """
  637. def __init__(self, search_string):
  638. """Initialize.
  639. Args:
  640. # search_string: the string you are searching for
  641. search_string: str
  642. """
  643. self._search_string = search_string
  644. def equals(self, rhs):
  645. """Check to see if the search_string is contained in the rhs string.
  646. Args:
  647. # rhs: the right hand side of the test
  648. rhs: object
  649. Returns:
  650. bool
  651. """
  652. try:
  653. return rhs.find(self._search_string) > -1
  654. except Exception:
  655. return False
  656. def __repr__(self):
  657. return '<str containing \'%s\'>' % self._search_string
  658. class Regex(Comparator):
  659. """Checks if a string matches a regular expression.
  660. This uses a given regular expression to determine equality.
  661. """
  662. def __init__(self, pattern, flags=0):
  663. """Initialize.
  664. Args:
  665. # pattern is the regular expression to search for
  666. pattern: str
  667. # flags passed to re.compile function as the second argument
  668. flags: int
  669. """
  670. self.regex = re.compile(pattern, flags=flags)
  671. def equals(self, rhs):
  672. """Check to see if rhs matches regular expression pattern.
  673. Returns:
  674. bool
  675. """
  676. return self.regex.search(rhs) is not None
  677. def __repr__(self):
  678. s = '<regular expression \'%s\'' % self.regex.pattern
  679. if self.regex.flags:
  680. s += ', flags=%d' % self.regex.flags
  681. s += '>'
  682. return s
  683. class In(Comparator):
  684. """Checks whether an item (or key) is in a list (or dict) parameter.
  685. Example:
  686. mock_dao.GetUsersInfo(In('expectedUserName')).AndReturn(mock_result)
  687. """
  688. def __init__(self, key):
  689. """Initialize.
  690. Args:
  691. # key is any thing that could be in a list or a key in a dict
  692. """
  693. self._key = key
  694. def equals(self, rhs):
  695. """Check to see whether key is in rhs.
  696. Args:
  697. rhs: dict
  698. Returns:
  699. bool
  700. """
  701. return self._key in rhs
  702. def __repr__(self):
  703. return '<sequence or map containing \'%s\'>' % self._key
  704. class ContainsKeyValue(Comparator):
  705. """Checks whether a key/value pair is in a dict parameter.
  706. Example:
  707. mock_dao.UpdateUsers(ContainsKeyValue('stevepm', stevepm_user_info))
  708. """
  709. def __init__(self, key, value):
  710. """Initialize.
  711. Args:
  712. # key: a key in a dict
  713. # value: the corresponding value
  714. """
  715. self._key = key
  716. self._value = value
  717. def equals(self, rhs):
  718. """Check whether the given key/value pair is in the rhs dict.
  719. Returns:
  720. bool
  721. """
  722. try:
  723. return rhs[self._key] == self._value
  724. except Exception:
  725. return False
  726. def __repr__(self):
  727. return '<map containing the entry \'%s: %s\'>' % (self._key, self._value)
  728. class SameElementsAs(Comparator):
  729. """Checks whether iterables contain the same elements (ignoring order).
  730. Example:
  731. mock_dao.ProcessUsers(SameElementsAs('stevepm', 'salomaki'))
  732. """
  733. def __init__(self, expected_seq):
  734. """Initialize.
  735. Args:
  736. expected_seq: a sequence
  737. """
  738. self._expected_seq = expected_seq
  739. def equals(self, actual_seq):
  740. """Check to see whether actual_seq has same elements as expected_seq.
  741. Args:
  742. actual_seq: sequence
  743. Returns:
  744. bool
  745. """
  746. try:
  747. expected = dict([(element, None) for element in self._expected_seq])
  748. actual = dict([(element, None) for element in actual_seq])
  749. except TypeError:
  750. # Fall back to slower list-compare if any of the objects are unhashable.
  751. expected = list(self._expected_seq)
  752. actual = list(actual_seq)
  753. expected.sort()
  754. actual.sort()
  755. return expected == actual
  756. def __repr__(self):
  757. return '<sequence with same elements as \'%s\'>' % self._expected_seq
  758. class And(Comparator):
  759. """Evaluates one or more Comparators on RHS and returns an AND of the results.
  760. """
  761. def __init__(self, *args):
  762. """Initialize.
  763. Args:
  764. *args: One or more Comparator
  765. """
  766. self._comparators = args
  767. def equals(self, rhs):
  768. """Checks whether all Comparators are equal to rhs.
  769. Args:
  770. # rhs: can be anything
  771. Returns:
  772. bool
  773. """
  774. for comparator in self._comparators:
  775. if not comparator.equals(rhs):
  776. return False
  777. return True
  778. def __repr__(self):
  779. return '<AND %s>' % str(self._comparators)
  780. class Or(Comparator):
  781. """Evaluates one or more Comparators on RHS and returns an OR of the results.
  782. """
  783. def __init__(self, *args):
  784. """Initialize.
  785. Args:
  786. *args: One or more Mox comparators
  787. """
  788. self._comparators = args
  789. def equals(self, rhs):
  790. """Checks whether any Comparator is equal to rhs.
  791. Args:
  792. # rhs: can be anything
  793. Returns:
  794. bool
  795. """
  796. for comparator in self._comparators:
  797. if comparator.equals(rhs):
  798. return True
  799. return False
  800. def __repr__(self):
  801. return '<OR %s>' % str(self._comparators)
  802. class Func(Comparator):
  803. """Call a function that should verify the parameter passed in is correct.
  804. You may need the ability to perform more advanced operations on the parameter
  805. in order to validate it. You can use this to have a callable validate any
  806. parameter. The callable should return either True or False.
  807. Example:
  808. def myParamValidator(param):
  809. # Advanced logic here
  810. return True
  811. mock_dao.DoSomething(Func(myParamValidator), true)
  812. """
  813. def __init__(self, func):
  814. """Initialize.
  815. Args:
  816. func: callable that takes one parameter and returns a bool
  817. """
  818. self._func = func
  819. def equals(self, rhs):
  820. """Test whether rhs passes the function test.
  821. rhs is passed into func.
  822. Args:
  823. rhs: any python object
  824. Returns:
  825. the result of func(rhs)
  826. """
  827. return self._func(rhs)
  828. def __repr__(self):
  829. return str(self._func)
  830. class IgnoreArg(Comparator):
  831. """Ignore an argument.
  832. This can be used when we don't care about an argument of a method call.
  833. Example:
  834. # Check if CastMagic is called with 3 as first arg and 'disappear' as third.
  835. mymock.CastMagic(3, IgnoreArg(), 'disappear')
  836. """
  837. def equals(self, unused_rhs):
  838. """Ignores arguments and returns True.
  839. Args:
  840. unused_rhs: any python object
  841. Returns:
  842. always returns True
  843. """
  844. return True
  845. def __repr__(self):
  846. return '<IgnoreArg>'
  847. class MethodGroup(object):
  848. """Base class containing common behaviour for MethodGroups."""
  849. def __init__(self, group_name):
  850. self._group_name = group_name
  851. def group_name(self):
  852. return self._group_name
  853. def __str__(self):
  854. return '<%s "%s">' % (self.__class__.__name__, self._group_name)
  855. def AddMethod(self, mock_method):
  856. raise NotImplementedError
  857. def MethodCalled(self, mock_method):
  858. raise NotImplementedError
  859. def IsSatisfied(self):
  860. raise NotImplementedError
  861. class UnorderedGroup(MethodGroup):
  862. """UnorderedGroup holds a set of method calls that may occur in any order.
  863. This construct is helpful for non-deterministic events, such as iterating
  864. over the keys of a dict.
  865. """
  866. def __init__(self, group_name):
  867. super(UnorderedGroup, self).__init__(group_name)
  868. self._methods = []
  869. def AddMethod(self, mock_method):
  870. """Add a method to this group.
  871. Args:
  872. mock_method: A mock method to be added to this group.
  873. """
  874. self._methods.append(mock_method)
  875. def MethodCalled(self, mock_method):
  876. """Remove a method call from the group.
  877. If the method is not in the set, an UnexpectedMethodCallError will be
  878. raised.
  879. Args:
  880. mock_method: a mock method that should be equal to a method in the group.
  881. Returns:
  882. The mock method from the group
  883. Raises:
  884. UnexpectedMethodCallError if the mock_method was not in the group.
  885. """
  886. # Check to see if this method exists, and if so, remove it from the set
  887. # and return it.
  888. for method in self._methods:
  889. if method == mock_method:
  890. # Remove the called mock_method instead of the method in the group.
  891. # The called method will match any comparators when equality is checked
  892. # during removal. The method in the group could pass a comparator to
  893. # another comparator during the equality check.
  894. self._methods.remove(mock_method)
  895. # If this group is not empty, put it back at the head of the queue.
  896. if not self.IsSatisfied():
  897. mock_method._call_queue.appendleft(self)
  898. return self, method
  899. raise UnexpectedMethodCallError(mock_method, self)
  900. def IsSatisfied(self):
  901. """Return True if there are not any methods in this group."""
  902. return len(self._methods) == 0
  903. class MultipleTimesGroup(MethodGroup):
  904. """MultipleTimesGroup holds methods that may be called any number of times.
  905. Note: Each method must be called at least once.
  906. This is helpful, if you don't know or care how many times a method is called.
  907. """
  908. def __init__(self, group_name):
  909. super(MultipleTimesGroup, self).__init__(group_name)
  910. self._methods = set()
  911. self._methods_called = set()
  912. def AddMethod(self, mock_method):
  913. """Add a method to this group.
  914. Args:
  915. mock_method: A mock method to be added to this group.
  916. """
  917. self._methods.add(mock_method)
  918. def MethodCalled(self, mock_method):
  919. """Remove a method call from the group.
  920. If the method is not in the set, an UnexpectedMethodCallError will be
  921. raised.
  922. Args:
  923. mock_method: a mock method that should be equal to a method in the group.
  924. Returns:
  925. The mock method from the group
  926. Raises:
  927. UnexpectedMethodCallError if the mock_method was not in the group.
  928. """
  929. # Check to see if this method exists, and if so add it to the set of
  930. # called methods.
  931. for method in self._methods:
  932. if method == mock_method:
  933. self._methods_called.add(mock_method)
  934. # Always put this group back on top of the queue, because we don't know
  935. # when we are done.
  936. mock_method._call_queue.appendleft(self)
  937. return self, method
  938. if self.IsSatisfied():
  939. next_method = mock_method._PopNextMethod();
  940. return next_method, None
  941. else:
  942. raise UnexpectedMethodCallError(mock_method, self)
  943. def IsSatisfied(self):
  944. """Return True if all methods in this group are called at least once."""
  945. # NOTE(psycho): We can't use the simple set difference here because we want
  946. # to match different parameters which are considered the same e.g. IsA(str)
  947. # and some string. This solution is O(n^2) but n should be small.
  948. tmp = self._methods.copy()
  949. for called in self._methods_called:
  950. for expected in tmp:
  951. if called == expected:
  952. tmp.remove(expected)
  953. if not tmp:
  954. return True
  955. break
  956. return False
  957. class MoxMetaTestBase(type):
  958. """Metaclass to add mox cleanup and verification to every test.
  959. As the mox unit testing class is being constructed (MoxTestBase or a
  960. subclass), this metaclass will modify all test functions to call the
  961. CleanUpMox method of the test class after they finish. This means that
  962. unstubbing and verifying will happen for every test with no additional code,
  963. and any failures will result in test failures as opposed to errors.
  964. """
  965. def __init__(cls, name, bases, d):
  966. type.__init__(cls, name, bases, d)
  967. # also get all the attributes from the base classes to account
  968. # for a case when test class is not the immediate child of MoxTestBase
  969. for base in bases:
  970. for attr_name in dir(base):
  971. d[attr_name] = getattr(base, attr_name)
  972. for func_name, func in d.items():
  973. if func_name.startswith('test') and callable(func):
  974. setattr(cls, func_name, MoxMetaTestBase.CleanUpTest(cls, func))
  975. @staticmethod
  976. def CleanUpTest(cls, func):
  977. """Adds Mox cleanup code to any MoxTestBase method.
  978. Always unsets stubs after a test. Will verify all mocks for tests that
  979. otherwise pass.
  980. Args:
  981. cls: MoxTestBase or subclass; the class whose test method we are altering.
  982. func: method; the method of the MoxTestBase test class we wish to alter.
  983. Returns:
  984. The modified method.
  985. """
  986. def new_method(self, *args, **kwargs):
  987. mox_obj = getattr(self, 'mox', None)
  988. cleanup_mox = False
  989. if mox_obj and isinstance(mox_obj, Mox):
  990. cleanup_mox = True
  991. try:
  992. func(self, *args, **kwargs)
  993. finally:
  994. if cleanup_mox:
  995. mox_obj.UnsetStubs()
  996. if cleanup_mox:
  997. mox_obj.VerifyAll()
  998. new_method.__name__ = func.__name__
  999. new_method.__doc__ = func.__doc__
  1000. new_method.__module__ = func.__module__
  1001. return new_method
  1002. class MoxTestBase(unittest.TestCase):
  1003. """Convenience test class to make stubbing easier.
  1004. Sets up a "mox" attribute which is an instance of Mox - any mox tests will
  1005. want this. Also automatically unsets any stubs and verifies that all mock
  1006. methods have been called at the end of each test, eliminating boilerplate
  1007. code.
  1008. """
  1009. __metaclass__ = MoxMetaTestBase
  1010. def setUp(self):
  1011. self.mox = Mox()