summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordglasser <dglasser@b1010a0a-674b-0410-b734-77272b80c875>2008-06-13 23:00:27 +0000
committerdglasser <dglasser@b1010a0a-674b-0410-b734-77272b80c875>2008-06-13 23:00:27 +0000
commit8689cfa340245a0ac04e5b04f2eca94303f01ee2 (patch)
tree50d272351c5fcec38d4fda8c3022c3186f27329c
parent2f8a16fe0037bf288bca6934680cd0eeb12172b6 (diff)
downloadmox-8689cfa340245a0ac04e5b04f2eca94303f01ee2.tar.gz
Initial import of mox (originally an internal Google project).
It's not quite ready for release yet, but it's been appropriately scrubbed and relicensed. git-svn-id: http://pymox.googlecode.com/svn/trunk@7 b1010a0a-674b-0410-b734-77272b80c875
-rw-r--r--COPYING202
-rw-r--r--MANIFEST.in2
-rw-r--r--README1
-rwxr-xr-xmox.py1398
-rwxr-xr-xmox_test.py1326
-rwxr-xr-xmox_test_helper.py76
-rwxr-xr-xsetup.py15
-rw-r--r--stubout.py137
8 files changed, 3157 insertions, 0 deletions
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..6b4c552
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,2 @@
+include COPYING
+include mox_test.py
diff --git a/README b/README
new file mode 100644
index 0000000..9cf8aeb
--- /dev/null
+++ b/README
@@ -0,0 +1 @@
+TODO(glasser): README!
diff --git a/mox.py b/mox.py
new file mode 100755
index 0000000..a155aa0
--- /dev/null
+++ b/mox.py
@@ -0,0 +1,1398 @@
+#!/usr/bin/python2.4
+#
+# Copyright 2008 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Mox, an object-mocking framework for Python.
+
+Mox works in the record-replay-verify paradigm. When you first create
+a mock object, it is in record mode. You then programmatically set
+the expected behavior of the mock object (what methods are to be
+called on it, with what parameters, what they should return, and in
+what order).
+
+Once you have set up the expected mock behavior, you put it in replay
+mode. Now the mock responds to method calls just as you told it to.
+If an unexpected method (or an expected method with unexpected
+parameters) is called, then an exception will be raised.
+
+Once you are done interacting with the mock, you need to verify that
+all the expected interactions occured. (Maybe your code exited
+prematurely without calling some cleanup method!) The verify phase
+ensures that every expected method was called; otherwise, an exception
+will be raised.
+
+Suggested usage / workflow:
+
+ # Create Mox factory
+ my_mox = Mox()
+
+ # Create a mock data access object
+ mock_dao = my_mox.CreateMock(DAOClass)
+
+ # Set up expected behavior
+ mock_dao.RetrievePersonWithIdentifier('1').AndReturn(person)
+ mock_dao.DeletePerson(person)
+
+ # Put mocks in replay mode
+ my_mox.ReplayAll()
+
+ # Inject mock object and run test
+ controller.SetDao(mock_dao)
+ controller.DeletePersonById('1')
+
+ # Verify all methods were called as expected
+ my_mox.VerifyAll()
+"""
+
+from collections import deque
+import re
+import types
+import unittest
+
+import stubout
+
+class Error(AssertionError):
+ """Base exception for this module."""
+
+ pass
+
+
+class ExpectedMethodCallsError(Error):
+ """Raised when Verify() is called before all expected methods have been called
+ """
+
+ def __init__(self, expected_methods):
+ """Init exception.
+
+ Args:
+ # expected_methods: A sequence of MockMethod objects that should have been
+ # called.
+ expected_methods: [MockMethod]
+
+ Raises:
+ ValueError: if expected_methods contains no methods.
+ """
+
+ if not expected_methods:
+ raise ValueError("There must be at least one expected method")
+ Error.__init__(self)
+ self._expected_methods = expected_methods
+
+ def __str__(self):
+ calls = "\n".join(["%3d. %s" % (i, m)
+ for i, m in enumerate(self._expected_methods)])
+ return "Verify: Expected methods never called:\n%s" % (calls,)
+
+
+class UnexpectedMethodCallError(Error):
+ """Raised when an unexpected method is called.
+
+ This can occur if a method is called with incorrect parameters, or out of the
+ specified order.
+ """
+
+ def __init__(self, unexpected_method, expected):
+ """Init exception.
+
+ Args:
+ # unexpected_method: MockMethod that was called but was not at the head of
+ # the expected_method queue.
+ # expected: MockMethod or UnorderedGroup the method should have
+ # been in.
+ unexpected_method: MockMethod
+ expected: MockMethod or UnorderedGroup
+ """
+
+ Error.__init__(self)
+ self._unexpected_method = unexpected_method
+ self._expected = expected
+
+ def __str__(self):
+ return "Unexpected method call: %s. Expecting: %s" % \
+ (self._unexpected_method, self._expected)
+
+
+class UnknownMethodCallError(Error):
+ """Raised if an unknown method is requested of the mock object."""
+
+ def __init__(self, unknown_method_name):
+ """Init exception.
+
+ Args:
+ # unknown_method_name: Method call that is not part of the mocked class's
+ # public interface.
+ unknown_method_name: str
+ """
+
+ Error.__init__(self)
+ self._unknown_method_name = unknown_method_name
+
+ def __str__(self):
+ return "Method called is not a member of the object: %s" % \
+ self._unknown_method_name
+
+
+class Mox(object):
+ """Mox: a factory for creating mock objects."""
+
+ # A list of types that should be stubbed out with MockObjects (as
+ # opposed to MockAnythings).
+ _USE_MOCK_OBJECT = [types.ClassType, types.InstanceType, types.ModuleType,
+ types.ObjectType, types.TypeType]
+
+ def __init__(self):
+ """Initialize a new Mox."""
+
+ self._mock_objects = []
+ self.stubs = stubout.StubOutForTesting()
+
+ def CreateMock(self, class_to_mock):
+ """Create a new mock object.
+
+ Args:
+ # class_to_mock: the class to be mocked
+ class_to_mock: class
+
+ Returns:
+ MockObject that can be used as the class_to_mock would be.
+ """
+
+ new_mock = MockObject(class_to_mock)
+ self._mock_objects.append(new_mock)
+ return new_mock
+
+ def CreateMockAnything(self):
+ """Create a mock that will accept any method calls.
+
+ This does not enforce an interface.
+ """
+
+ new_mock = MockAnything()
+ self._mock_objects.append(new_mock)
+ return new_mock
+
+ def ReplayAll(self):
+ """Set all mock objects to replay mode."""
+
+ for mock_obj in self._mock_objects:
+ mock_obj._Replay()
+
+
+ def VerifyAll(self):
+ """Call verify on all mock objects created."""
+
+ for mock_obj in self._mock_objects:
+ mock_obj._Verify()
+
+ def ResetAll(self):
+ """Call reset on all mock objects. This does not unset stubs."""
+
+ for mock_obj in self._mock_objects:
+ mock_obj._Reset()
+
+ def StubOutWithMock(self, obj, attr_name, use_mock_anything=False):
+ """Replace a method, attribute, etc. with a Mock.
+
+ This will replace a class or module with a MockObject, and everything else
+ (method, function, etc) with a MockAnything. This can be overridden to
+ always use a MockAnything by setting use_mock_anything to True.
+
+ Args:
+ obj: A Python object (class, module, instance, callable).
+ attr_name: str. The name of the attribute to replace with a mock.
+ use_mock_anything: bool. True if a MockAnything should be used regardless
+ of the type of attribute.
+ """
+
+ attr_to_replace = getattr(obj, attr_name)
+ if type(attr_to_replace) in self._USE_MOCK_OBJECT and not use_mock_anything:
+ stub = self.CreateMock(attr_to_replace)
+ else:
+ stub = self.CreateMockAnything()
+
+ self.stubs.Set(obj, attr_name, stub)
+
+ def UnsetStubs(self):
+ """Restore stubs to their original state."""
+
+ self.stubs.UnsetAll()
+
+def Replay(*args):
+ """Put mocks into Replay mode.
+
+ Args:
+ # args is any number of mocks to put into replay mode.
+ """
+
+ for mock in args:
+ mock._Replay()
+
+
+def Verify(*args):
+ """Verify mocks.
+
+ Args:
+ # args is any number of mocks to be verified.
+ """
+
+ for mock in args:
+ mock._Verify()
+
+
+def Reset(*args):
+ """Reset mocks.
+
+ Args:
+ # args is any number of mocks to be reset.
+ """
+
+ for mock in args:
+ mock._Reset()
+
+
+class MockAnything:
+ """A mock that can be used to mock anything.
+
+ This is helpful for mocking classes that do not provide a public interface.
+ """
+
+ def __init__(self):
+ """ """
+ self._Reset()
+
+ def __getattr__(self, method_name):
+ """Intercept method calls on this object.
+
+ A new MockMethod is returned that is aware of the MockAnything's
+ state (record or replay). The call will be recorded or replayed
+ by the MockMethod's __call__.
+
+ Args:
+ # method name: the name of the method being called.
+ method_name: str
+
+ Returns:
+ A new MockMethod aware of MockAnything's state (record or replay).
+ """
+
+ return self._CreateMockMethod(method_name)
+
+ def _CreateMockMethod(self, method_name):
+ """Create a new mock method call and return it.
+
+ Args:
+ # method name: the name of the method being called.
+ method_name: str
+
+ Returns:
+ A new MockMethod aware of MockAnything's state (record or replay).
+ """
+
+ return MockMethod(method_name, self._expected_calls_queue,
+ self._replay_mode)
+
+ def __nonzero__(self):
+ """Return 1 for nonzero so the mock can be used as a conditional."""
+
+ return 1
+
+ def __eq__(self, rhs):
+ """Provide custom logic to compare objects."""
+
+ return (isinstance(rhs, MockAnything) and
+ self._replay_mode == rhs._replay_mode and
+ self._expected_calls_queue == rhs._expected_calls_queue)
+
+ def __ne__(self, rhs):
+ """Provide custom logic to compare objects."""
+
+ return not self == rhs
+
+ def _Replay(self):
+ """Start replaying expected method calls."""
+
+ self._replay_mode = True
+
+ def _Verify(self):
+ """Verify that all of the expected calls have been made.
+
+ Raises:
+ ExpectedMethodCallsError: if there are still more method calls in the
+ expected queue.
+ """
+
+ # If the list of expected calls is not empty, raise an exception
+ if self._expected_calls_queue:
+ # The last MultipleTimesGroup is not popped from the queue.
+ if (len(self._expected_calls_queue) == 1 and
+ isinstance(self._expected_calls_queue[0], MultipleTimesGroup) and
+ self._expected_calls_queue[0].IsSatisfied()):
+ pass
+ else:
+ raise ExpectedMethodCallsError(self._expected_calls_queue)
+
+ def _Reset(self):
+ """Reset the state of this mock to record mode with an empty queue."""
+
+ # Maintain a list of method calls we are expecting
+ self._expected_calls_queue = deque()
+
+ # Make sure we are in setup mode, not replay mode
+ self._replay_mode = False
+
+
+class MockObject(MockAnything, object):
+ """A mock object that simulates the public/protected interface of a class."""
+
+ def __init__(self, class_to_mock):
+ """Initialize a mock object.
+
+ This determines the methods and properties of the class and stores them.
+
+ Args:
+ # class_to_mock: class to be mocked
+ class_to_mock: class
+ """
+
+ # This is used to hack around the mixin/inheritance of MockAnything, which
+ # is not a proper object (it can be anything. :-)
+ MockAnything.__dict__['__init__'](self)
+
+ # Get a list of all the public and special methods we should mock.
+ self._known_methods = set()
+ self._known_vars = set()
+ self._class_to_mock = class_to_mock
+ for method in dir(class_to_mock):
+ if callable(getattr(class_to_mock, method)):
+ self._known_methods.add(method)
+ else:
+ self._known_vars.add(method)
+
+ def __getattr__(self, name):
+ """Intercept attribute request on this object.
+
+ If the attribute is a public class variable, it will be returned and not
+ recorded as a call.
+
+ If the attribute is not a variable, it is handled like a method
+ call. The method name is checked against the set of mockable
+ methods, and a new MockMethod is returned that is aware of the
+ MockObject's state (record or replay). The call will be recorded
+ or replayed by the MockMethod's __call__.
+
+ Args:
+ # name: the name of the attribute being requested.
+ name: str
+
+ Returns:
+ Either a class variable or a new MockMethod that is aware of the state
+ of the mock (record or replay).
+
+ Raises:
+ UnknownMethodCallError if the MockObject does not mock the requested
+ method.
+ """
+
+ if name in self._known_vars:
+ return getattr(self._class_to_mock, name)
+
+ if name in self._known_methods:
+ return self._CreateMockMethod(name)
+
+ raise UnknownMethodCallError(name)
+
+ def __eq__(self, rhs):
+ """Provide custom logic to compare objects."""
+
+ return (isinstance(rhs, MockObject) and
+ self._class_to_mock == rhs._class_to_mock and
+ self._replay_mode == rhs._replay_mode and
+ self._expected_calls_queue == rhs._expected_calls_queue)
+
+ def __setitem__(self, key, value):
+ """Provide custom logic for mocking classes that support item assignment.
+
+ Args:
+ key: Key to set the value for.
+ value: Value to set.
+
+ Returns:
+ Expected return value in replay mode. A MockMethod object for the
+ __setitem__ method that has already been called if not in replay mode.
+
+ Raises:
+ TypeError if the underlying class does not support item assignment.
+ UnexpectedMethodCallError if the object does not expect the call to
+ __setitem__.
+
+ """
+ setitem = self._class_to_mock.__dict__.get('__setitem__', None)
+
+ # Verify the class supports item assignment.
+ if setitem is None:
+ raise TypeError('object does not support item assignment')
+
+ # If we are in replay mode then simply call the mock __setitem__ method.
+ if self._replay_mode:
+ return MockMethod('__setitem__', self._expected_calls_queue,
+ self._replay_mode)(key, value)
+
+
+ # Otherwise, create a mock method __setitem__.
+ return self._CreateMockMethod('__setitem__')(key, value)
+
+ def __getitem__(self, key):
+ """Provide custom logic for mocking classes that are subscriptable.
+
+ Args:
+ key: Key to return the value for.
+
+ Returns:
+ Expected return value in replay mode. A MockMethod object for the
+ __getitem__ method that has already been called if not in replay mode.
+
+ Raises:
+ TypeError if the underlying class is not subscriptable.
+ UnexpectedMethodCallError if the object does not expect the call to
+ __setitem__.
+
+ """
+ getitem = self._class_to_mock.__dict__.get('__getitem__', None)
+
+ # Verify the class supports item assignment.
+ if getitem is None:
+ raise TypeError('unsubscriptable object')
+
+ # If we are in replay mode then simply call the mock __getitem__ method.
+ if self._replay_mode:
+ return MockMethod('__getitem__', self._expected_calls_queue,
+ self._replay_mode)(key)
+
+
+ # Otherwise, create a mock method __getitem__.
+ return self._CreateMockMethod('__getitem__')(key)
+
+ def __call__(self, *params, **named_params):
+ """Provide custom logic for mocking classes that are callable."""
+
+ # Verify the class we are mocking is callable
+ callable = self._class_to_mock.__dict__.get('__call__', None)
+ if callable is None:
+ raise TypeError('Not callable')
+
+ # Because the call is happening directly on this object instead of a method,
+ # the call on the mock method is made right here
+ mock_method = self._CreateMockMethod('__call__')
+ return mock_method(*params, **named_params)
+
+ @property
+ def __class__(self):
+ """Return the class that is being mocked."""
+
+ return self._class_to_mock
+
+
+class MockMethod(object):
+ """Callable mock method.
+
+ A MockMethod should act exactly like the method it mocks, accepting parameters
+ and returning a value, or throwing an exception (as specified). When this
+ method is called, it can optionally verify whether the called method (name and
+ signature) matches the expected method.
+ """
+
+ def __init__(self, method_name, call_queue, replay_mode):
+ """Construct a new mock method.
+
+ Args:
+ # method_name: the name of the method
+ # call_queue: deque of calls, verify this call against the head, or add
+ # this call to the queue.
+ # replay_mode: False if we are recording, True if we are verifying calls
+ # against the call queue.
+ method_name: str
+ call_queue: list or deque
+ replay_mode: bool
+ """
+
+ self._name = method_name
+ self._call_queue = call_queue
+ if not isinstance(call_queue, deque):
+ self._call_queue = deque(self._call_queue)
+ self._replay_mode = replay_mode
+
+ self._params = None
+ self._named_params = None
+ self._return_value = None
+ self._exception = None
+ self._side_effects = None
+
+ def __call__(self, *params, **named_params):
+ """Log parameters and return the specified return value.
+
+ If the Mock(Anything/Object) associated with this call is in record mode,
+ this MockMethod will be pushed onto the expected call queue. If the mock
+ is in replay mode, this will pop a MockMethod off the top of the queue and
+ verify this call is equal to the expected call.
+
+ Raises:
+ UnexpectedMethodCall if this call is supposed to match an expected method
+ call and it does not.
+ """
+
+ self._params = params
+ self._named_params = named_params
+
+ if not self._replay_mode:
+ self._call_queue.append(self)
+ return self
+
+ expected_method = self._VerifyMethodCall()
+
+ if expected_method._side_effects:
+ expected_method._side_effects(*params, **named_params)
+
+ if expected_method._exception:
+ raise expected_method._exception
+
+ return expected_method._return_value
+
+ def __getattr__(self, name):
+ """Raise an AttributeError with a helpful message."""
+
+ raise AttributeError('MockMethod has no attribute "%s". '
+ 'Did you remember to put your mocks in replay mode?' % name)
+
+ def _PopNextMethod(self):
+ """Pop the next method from our call queue."""
+ try:
+ return self._call_queue.popleft()
+ except IndexError:
+ raise UnexpectedMethodCallError(self, None)
+
+ def _VerifyMethodCall(self):
+ """Verify the called method is expected.
+
+ This can be an ordered method, or part of an unordered set.
+
+ Returns:
+ The expected mock method.
+
+ Raises:
+ UnexpectedMethodCall if the method called was not expected.
+ """
+
+ expected = self._PopNextMethod()
+
+ # Loop here, because we might have a MethodGroup followed by another
+ # group.
+ while isinstance(expected, MethodGroup):
+ expected, method = expected.MethodCalled(self)
+ if method is not None:
+ return method
+
+ # This is a mock method, so just check equality.
+ if expected != self:
+ raise UnexpectedMethodCallError(self, expected)
+
+ return expected
+
+ def __str__(self):
+ params = ', '.join(
+ [repr(p) for p in self._params or []] +
+ ['%s=%r' % x for x in sorted((self._named_params or {}).items())])
+ desc = "%s(%s) -> %r" % (self._name, params, self._return_value)
+ return desc
+
+ def __eq__(self, rhs):
+ """Test whether this MockMethod is equivalent to another MockMethod.
+
+ Args:
+ # rhs: the right hand side of the test
+ rhs: MockMethod
+ """
+
+ return (isinstance(rhs, MockMethod) and
+ self._name == rhs._name and
+ self._params == rhs._params and
+ self._named_params == rhs._named_params)
+
+ def __ne__(self, rhs):
+ """Test whether this MockMethod is not equivalent to another MockMethod.
+
+ Args:
+ # rhs: the right hand side of the test
+ rhs: MockMethod
+ """
+
+ return not self == rhs
+
+ def GetPossibleGroup(self):
+ """Returns a possible group from the end of the call queue or None if no
+ other methods are on the stack.
+ """
+
+ # Remove this method from the tail of the queue so we can add it to a group.
+ this_method = self._call_queue.pop()
+ assert this_method == self
+
+ # Determine if the tail of the queue is a group, or just a regular ordered
+ # mock method.
+ group = None
+ try:
+ group = self._call_queue[-1]
+ except IndexError:
+ pass
+
+ return group
+
+ def _CheckAndCreateNewGroup(self, group_name, group_class):
+ """Checks if the last method (a possible group) is an instance of our
+ group_class. Adds the current method to this group or creates a new one.
+
+ Args:
+
+ group_name: the name of the group.
+ group_class: the class used to create instance of this new group
+ """
+ group = self.GetPossibleGroup()
+
+ # If this is a group, and it is the correct group, add the method.
+ if isinstance(group, group_class) and group.group_name() == group_name:
+ group.AddMethod(self)
+ return self
+
+ # Create a new group and add the method.
+ new_group = group_class(group_name)
+ new_group.AddMethod(self)
+ self._call_queue.append(new_group)
+ return self
+
+ def InAnyOrder(self, group_name="default"):
+ """Move this method into a group of unordered calls.
+
+ A group of unordered calls must be defined together, and must be executed
+ in full before the next expected method can be called. There can be
+ multiple groups that are expected serially, if they are given
+ different group names. The same group name can be reused if there is a
+ standard method call, or a group with a different name, spliced between
+ usages.
+
+ Args:
+ group_name: the name of the unordered group.
+
+ Returns:
+ self
+ """
+ return self._CheckAndCreateNewGroup(group_name, UnorderedGroup)
+
+ def MultipleTimes(self, group_name="default"):
+ """Move this method into group of calls which may be called multiple times.
+
+ A group of repeating calls must be defined together, and must be executed in
+ full before the next expected mehtod can be called.
+
+ Args:
+ group_name: the name of the unordered group.
+
+ Returns:
+ self
+ """
+ return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup)
+
+ def AndReturn(self, return_value):
+ """Set the value to return when this method is called.
+
+ Args:
+ # return_value can be anything.
+ """
+
+ self._return_value = return_value
+ return return_value
+
+ def AndRaise(self, exception):
+ """Set the exception to raise when this method is called.
+
+ Args:
+ # exception: the exception to raise when this method is called.
+ exception: Exception
+ """
+
+ self._exception = exception
+
+ def WithSideEffects(self, side_effects):
+ """Set the side effects that are simulated when this method is called.
+
+ Args:
+ side_effects: A callable which modifies the parameters or other relevant
+ state which a given test case depends on.
+
+ Returns:
+ Self for chaining with AndReturn and AndRaise.
+ """
+ self._side_effects = side_effects
+ return self
+
+class Comparator:
+ """Base class for all Mox comparators.
+
+ A Comparator can be used as a parameter to a mocked method when the exact
+ value is not known. For example, the code you are testing might build up a
+ long SQL string that is passed to your mock DAO. You're only interested that
+ the IN clause contains the proper primary keys, so you can set your mock
+ up as follows:
+
+ mock_dao.RunQuery(StrContains('IN (1, 2, 4, 5)')).AndReturn(mock_result)
+
+ Now whatever query is passed in must contain the string 'IN (1, 2, 4, 5)'.
+
+ A Comparator may replace one or more parameters, for example:
+ # return at most 10 rows
+ mock_dao.RunQuery(StrContains('SELECT'), 10)
+
+ or
+
+ # Return some non-deterministic number of rows
+ mock_dao.RunQuery(StrContains('SELECT'), IsA(int))
+ """
+
+ def equals(self, rhs):
+ """Special equals method that all comparators must implement.
+
+ Args:
+ rhs: any python object
+ """
+
+ raise NotImplementedError, 'method must be implemented by a subclass.'
+
+ def __eq__(self, rhs):
+ return self.equals(rhs)
+
+ def __ne__(self, rhs):
+ return not self.equals(rhs)
+
+
+class IsA(Comparator):
+ """This class wraps a basic Python type or class. It is used to verify
+ that a parameter is of the given type or class.
+
+ Example:
+ mock_dao.Connect(IsA(DbConnectInfo))
+ """
+
+ def __init__(self, class_name):
+ """Initialize IsA
+
+ Args:
+ class_name: basic python type or a class
+ """
+
+ self._class_name = class_name
+
+ def equals(self, rhs):
+ """Check to see if the RHS is an instance of class_name.
+
+ Args:
+ # rhs: the right hand side of the test
+ rhs: object
+
+ Returns:
+ bool
+ """
+
+ try:
+ return isinstance(rhs, self._class_name)
+ except TypeError:
+ # Check raw types if there was a type error. This is helpful for
+ # things like cStringIO.StringIO.
+ return type(rhs) == type(self._class_name)
+
+ def __repr__(self):
+ return str(self._class_name)
+
+class IsAlmost(Comparator):
+ """Comparison class used to check whether a parameter is nearly equal
+ to a given value. Generally useful for floating point numbers.
+
+ Example mock_dao.SetTimeout((IsAlmost(3.9)))
+ """
+
+ def __init__(self, float_value, places=7):
+ """Initialize IsAlmost.
+
+ Args:
+ float_value: The value for making the comparison.
+ places: The number of decimal places to round to.
+ """
+
+ self._float_value = float_value
+ self._places = places
+
+ def equals(self, rhs):
+ """Check to see if RHS is almost equal to float_value
+
+ Args:
+ rhs: the value to compare to float_value
+
+ Returns:
+ bool
+ """
+
+ try:
+ return round(rhs-self._float_value, self._places) == 0
+ except TypeError:
+ # This is probably because either float_value or rhs is not a number.
+ return False
+
+ def __repr__(self):
+ return str(self._float_value)
+
+class StrContains(Comparator):
+ """Comparison class used to check whether a substring exists in a
+ string parameter. This can be useful in mocking a database with SQL
+ passed in as a string parameter, for example.
+
+ Example:
+ mock_dao.RunQuery(StrContains('IN (1, 2, 4, 5)')).AndReturn(mock_result)
+ """
+
+ def __init__(self, search_string):
+ """Initialize.
+
+ Args:
+ # search_string: the string you are searching for
+ search_string: str
+ """
+
+ self._search_string = search_string
+
+ def equals(self, rhs):
+ """Check to see if the search_string is contained in the rhs string.
+
+ Args:
+ # rhs: the right hand side of the test
+ rhs: object
+
+ Returns:
+ bool
+ """
+
+ try:
+ return rhs.find(self._search_string) > -1
+ except Exception:
+ return False
+
+ def __repr__(self):
+ return '<str containing \'%s\'>' % self._search_string
+
+
+class Regex(Comparator):
+ """Checks if a string matches a regular expression.
+
+ This uses a given regular expression to determine equality.
+ """
+
+ def __init__(self, pattern, flags=0):
+ """Initialize.
+
+ Args:
+ # pattern is the regular expression to search for
+ pattern: str
+ # flags passed to re.compile function as the second argument
+ flags: int
+ """
+
+ self.regex = re.compile(pattern, flags=flags)
+
+ def equals(self, rhs):
+ """Check to see if rhs matches regular expression pattern.
+
+ Returns:
+ bool
+ """
+
+ return self.regex.search(rhs) is not None
+
+ def __repr__(self):
+ s = '<regular expression \'%s\'' % self.regex.pattern
+ if self.regex.flags:
+ s += ', flags=%d' % self.regex.flags
+ s += '>'
+ return s
+
+
+class In(Comparator):
+ """Checks whether an item (or key) is in a list (or dict) parameter.
+
+ Example:
+ mock_dao.GetUsersInfo(In('expectedUserName')).AndReturn(mock_result)
+ """
+
+ def __init__(self, key):
+ """Initialize.
+
+ Args:
+ # key is any thing that could be in a list or a key in a dict
+ """
+
+ self._key = key
+
+ def equals(self, rhs):
+ """Check to see whether key is in rhs.
+
+ Args:
+ rhs: dict
+
+ Returns:
+ bool
+ """
+
+ return self._key in rhs
+
+ def __repr__(self):
+ return '<sequence or map containing \'%s\'>' % self._key
+
+
+class ContainsKeyValue(Comparator):
+ """Checks whether a key/value pair is in a dict parameter.
+
+ Example:
+ mock_dao.UpdateUsers(ContainsKeyValue('stevepm', stevepm_user_info))
+ """
+
+ def __init__(self, key, value):
+ """Initialize.
+
+ Args:
+ # key: a key in a dict
+ # value: the corresponding value
+ """
+
+ self._key = key
+ self._value = value
+
+ def equals(self, rhs):
+ """Check whether the given key/value pair is in the rhs dict.
+
+ Returns:
+ bool
+ """
+
+ try:
+ return rhs[self._key] == self._value
+ except Exception:
+ return False
+
+ def __repr__(self):
+ return '<map containing the entry \'%s: %s\'>' % (self._key, self._value)
+
+
+class SameElementsAs(Comparator):
+ """Checks whether iterables contain the same elements (ignoring order).
+
+ Example:
+ mock_dao.ProcessUsers(SameElementsAs('stevepm', 'salomaki'))
+ """
+
+ def __init__(self, expected_seq):
+ """Initialize.
+
+ Args:
+ expected_seq: a sequence
+ """
+
+ self._expected_seq = expected_seq
+
+ def equals(self, actual_seq):
+ """Check to see whether actual_seq has same elements as expected_seq.
+
+ Args:
+ actual_seq: sequence
+
+ Returns:
+ bool
+ """
+
+ try:
+ expected = dict([(element, None) for element in self._expected_seq])
+ actual = dict([(element, None) for element in actual_seq])
+ except TypeError:
+ # Fall back to slower list-compare if any of the objects are unhashable.
+ expected = list(self._expected_seq)
+ actual = list(actual_seq)
+ expected.sort()
+ actual.sort()
+ return expected == actual
+
+ def __repr__(self):
+ return '<sequence with same elements as \'%s\'>' % self._expected_seq
+
+
+class And(Comparator):
+ """Evaluates one or more Comparators on RHS and returns an AND of the results.
+ """
+
+ def __init__(self, *args):
+ """Initialize.
+
+ Args:
+ *args: One or more Comparator
+ """
+
+ self._comparators = args
+
+ def equals(self, rhs):
+ """Checks whether all Comparators are equal to rhs.
+
+ Args:
+ # rhs: can be anything
+
+ Returns:
+ bool
+ """
+
+ for comparator in self._comparators:
+ if not comparator.equals(rhs):
+ return False
+
+ return True
+
+ def __repr__(self):
+ return '<AND %s>' % str(self._comparators)
+
+
+class Or(Comparator):
+ """Evaluates one or more Comparators on RHS and returns an OR of the results.
+ """
+
+ def __init__(self, *args):
+ """Initialize.
+
+ Args:
+ *args: One or more Mox comparators
+ """
+
+ self._comparators = args
+
+ def equals(self, rhs):
+ """Checks whether any Comparator is equal to rhs.
+
+ Args:
+ # rhs: can be anything
+
+ Returns:
+ bool
+ """
+
+ for comparator in self._comparators:
+ if comparator.equals(rhs):
+ return True
+
+ return False
+
+ def __repr__(self):
+ return '<OR %s>' % str(self._comparators)
+
+
+class Func(Comparator):
+ """Call a function that should verify the parameter passed in is correct.
+
+ You may need the ability to perform more advanced operations on the parameter
+ in order to validate it. You can use this to have a callable validate any
+ parameter. The callable should return either True or False.
+
+
+ Example:
+
+ def myParamValidator(param):
+ # Advanced logic here
+ return True
+
+ mock_dao.DoSomething(Func(myParamValidator), true)
+ """
+
+ def __init__(self, func):
+ """Initialize.
+
+ Args:
+ func: callable that takes one parameter and returns a bool
+ """
+
+ self._func = func
+
+ def equals(self, rhs):
+ """Test whether rhs passes the function test.
+
+ rhs is passed into func.
+
+ Args:
+ rhs: any python object
+
+ Returns:
+ the result of func(rhs)
+ """
+
+ return self._func(rhs)
+
+ def __repr__(self):
+ return str(self._func)
+
+
+class IgnoreArg(Comparator):
+ """Ignore an argument.
+
+ This can be used when we don't care about an argument of a method call.
+
+ Example:
+ # Check if CastMagic is called with 3 as first arg and 'disappear' as third.
+ mymock.CastMagic(3, IgnoreArg(), 'disappear')
+ """
+
+ def equals(self, unused_rhs):
+ """Ignores arguments and returns True.
+
+ Args:
+ unused_rhs: any python object
+
+ Returns:
+ always returns True
+ """
+
+ return True
+
+ def __repr__(self):
+ return '<IgnoreArg>'
+
+
+class MethodGroup(object):
+ """Base class containing common behaviour for MethodGroups."""
+
+ def __init__(self, group_name):
+ self._group_name = group_name
+
+ def group_name(self):
+ return self._group_name
+
+ def __str__(self):
+ return '<%s "%s">' % (self.__class__.__name__, self._group_name)
+
+ def AddMethod(self, mock_method):
+ raise NotImplementedError
+
+ def MethodCalled(self, mock_method):
+ raise NotImplementedError
+
+ def IsSatisfied(self):
+ raise NotImplementedError
+
+class UnorderedGroup(MethodGroup):
+ """UnorderedGroup holds a set of method calls that may occur in any order.
+
+ This construct is helpful for non-deterministic events, such as iterating
+ over the keys of a dict.
+ """
+
+ def __init__(self, group_name):
+ super(UnorderedGroup, self).__init__(group_name)
+ self._methods = []
+
+ def AddMethod(self, mock_method):
+ """Add a method to this group.
+
+ Args:
+ mock_method: A mock method to be added to this group.
+ """
+
+ self._methods.append(mock_method)
+
+ def MethodCalled(self, mock_method):
+ """Remove a method call from the group.
+
+ If the method is not in the set, an UnexpectedMethodCallError will be
+ raised.
+
+ Args:
+ mock_method: a mock method that should be equal to a method in the group.
+
+ Returns:
+ The mock method from the group
+
+ Raises:
+ UnexpectedMethodCallError if the mock_method was not in the group.
+ """
+
+ # Check to see if this method exists, and if so, remove it from the set
+ # and return it.
+ for method in self._methods:
+ if method == mock_method:
+ # Remove the called mock_method instead of the method in the group.
+ # The called method will match any comparators when equality is checked
+ # during removal. The method in the group could pass a comparator to
+ # another comparator during the equality check.
+ self._methods.remove(mock_method)
+
+ # If this group is not empty, put it back at the head of the queue.
+ if not self.IsSatisfied():
+ mock_method._call_queue.appendleft(self)
+
+ return self, method
+
+ raise UnexpectedMethodCallError(mock_method, self)
+
+ def IsSatisfied(self):
+ """Return True if there are not any methods in this group."""
+
+ return len(self._methods) == 0
+
+
+class MultipleTimesGroup(MethodGroup):
+ """MultipleTimesGroup holds methods that may be called any number of times.
+
+ Note: Each method must be called at least once.
+
+ This is helpful, if you don't know or care how many times a method is called.
+ """
+
+ def __init__(self, group_name):
+ super(MultipleTimesGroup, self).__init__(group_name)
+ self._methods = set()
+ self._methods_called = set()
+
+ def AddMethod(self, mock_method):
+ """Add a method to this group.
+
+ Args:
+ mock_method: A mock method to be added to this group.
+ """
+
+ self._methods.add(mock_method)
+
+ def MethodCalled(self, mock_method):
+ """Remove a method call from the group.
+
+ If the method is not in the set, an UnexpectedMethodCallError will be
+ raised.
+
+ Args:
+ mock_method: a mock method that should be equal to a method in the group.
+
+ Returns:
+ The mock method from the group
+
+ Raises:
+ UnexpectedMethodCallError if the mock_method was not in the group.
+ """
+
+ # Check to see if this method exists, and if so add it to the set of
+ # called methods.
+
+ for method in self._methods:
+ if method == mock_method:
+ self._methods_called.add(mock_method)
+ # Always put this group back on top of the queue, because we don't know
+ # when we are done.
+ mock_method._call_queue.appendleft(self)
+ return self, method
+
+ if self.IsSatisfied():
+ next_method = mock_method._PopNextMethod();
+ return next_method, None
+ else:
+ raise UnexpectedMethodCallError(mock_method, self)
+
+ def IsSatisfied(self):
+ """Return True if all methods in this group are called at least once."""
+ # NOTE(psycho): We can't use the simple set difference here because we want
+ # to match different parameters which are considered the same e.g. IsA(str)
+ # and some string. This solution is O(n^2) but n should be small.
+ tmp = self._methods.copy()
+ for called in self._methods_called:
+ for expected in tmp:
+ if called == expected:
+ tmp.remove(expected)
+ if not tmp:
+ return True
+ break
+ return False
+
+
+class MoxMetaTestBase(type):
+ """Metaclass to add mox cleanup and verification to every test.
+
+ As the mox unit testing class is being constructed (MoxTestBase or a
+ subclass), this metaclass will modify all test functions to call the
+ CleanUpMox method of the test class after they finish. This means that
+ unstubbing and verifying will happen for every test with no additional code,
+ and any failures will result in test failures as opposed to errors.
+ """
+
+ def __init__(cls, name, bases, d):
+ type.__init__(cls, name, bases, d)
+
+ # also get all the attributes from the base classes to account
+ # for a case when test class is not the immediate child of MoxTestBase
+ for base in bases:
+ for attr_name in dir(base):
+ d[attr_name] = getattr(base, attr_name)
+
+ for func_name, func in d.items():
+ if func_name.startswith('test') and callable(func):
+ setattr(cls, func_name, MoxMetaTestBase.CleanUpTest(cls, func))
+
+ @staticmethod
+ def CleanUpTest(cls, func):
+ """Adds Mox cleanup code to any MoxTestBase method.
+
+ Always unsets stubs after a test. Will verify all mocks for tests that
+ otherwise pass.
+
+ Args:
+ cls: MoxTestBase or subclass; the class whose test method we are altering.
+ func: method; the method of the MoxTestBase test class we wish to alter.
+
+ Returns:
+ The modified method.
+ """
+ def new_method(self, *args, **kwargs):
+ mox_obj = getattr(self, 'mox', None)
+ cleanup_mox = False
+ if mox_obj and isinstance(mox_obj, Mox):
+ cleanup_mox = True
+ try:
+ func(self, *args, **kwargs)
+ finally:
+ if cleanup_mox:
+ mox_obj.UnsetStubs()
+ if cleanup_mox:
+ mox_obj.VerifyAll()
+ new_method.__name__ = func.__name__
+ new_method.__doc__ = func.__doc__
+ new_method.__module__ = func.__module__
+ return new_method
+
+
+class MoxTestBase(unittest.TestCase):
+ """Convenience test class to make stubbing easier.
+
+ Sets up a "mox" attribute which is an instance of Mox - any mox tests will
+ want this. Also automatically unsets any stubs and verifies that all mock
+ methods have been called at the end of each test, eliminating boilerplate
+ code.
+ """
+
+ __metaclass__ = MoxMetaTestBase
+
+ def setUp(self):
+ self.mox = Mox()
diff --git a/mox_test.py b/mox_test.py
new file mode 100755
index 0000000..df83c45
--- /dev/null
+++ b/mox_test.py
@@ -0,0 +1,1326 @@
+#!/usr/bin/python2.4
+#
+# Unit tests for Mox.
+#
+# Copyright 2008 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import cStringIO
+import unittest
+import re
+
+import mox
+
+import mox_test_helper
+
+
+class ExpectedMethodCallsErrorTest(unittest.TestCase):
+ """Test creation and string conversion of ExpectedMethodCallsError."""
+
+ def testAtLeastOneMethod(self):
+ self.assertRaises(ValueError, mox.ExpectedMethodCallsError, [])
+
+ def testOneError(self):
+ method = mox.MockMethod("testMethod", [], False)
+ method(1, 2).AndReturn('output')
+ e = mox.ExpectedMethodCallsError([method])
+ self.assertEqual(
+ "Verify: Expected methods never called:\n"
+ " 0. testMethod(1, 2) -> 'output'",
+ str(e))
+
+ def testManyErrors(self):
+ method1 = mox.MockMethod("testMethod", [], False)
+ method1(1, 2).AndReturn('output')
+ method2 = mox.MockMethod("testMethod", [], False)
+ method2(a=1, b=2, c="only named")
+ method3 = mox.MockMethod("testMethod2", [], False)
+ method3().AndReturn(44)
+ method4 = mox.MockMethod("testMethod", [], False)
+ method4(1, 2).AndReturn('output')
+ e = mox.ExpectedMethodCallsError([method1, method2, method3, method4])
+ self.assertEqual(
+ "Verify: Expected methods never called:\n"
+ " 0. testMethod(1, 2) -> 'output'\n"
+ " 1. testMethod(a=1, b=2, c='only named') -> None\n"
+ " 2. testMethod2() -> 44\n"
+ " 3. testMethod(1, 2) -> 'output'",
+ str(e))
+
+
+class OrTest(unittest.TestCase):
+ """Test Or correctly chains Comparators."""
+
+ def testValidOr(self):
+ """Or should be True if either Comparator returns True."""
+ self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == {})
+ self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test')
+ self.assert_(mox.Or(mox.IsA(str), mox.IsA(str)) == 'test')
+
+ def testInvalidOr(self):
+ """Or should be False if both Comparators return False."""
+ self.failIf(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0)
+
+
+class AndTest(unittest.TestCase):
+ """Test And correctly chains Comparators."""
+
+ def testValidAnd(self):
+ """And should be True if both Comparators return True."""
+ self.assert_(mox.And(mox.IsA(str), mox.IsA(str)) == '1')
+
+ def testClauseOneFails(self):
+ """And should be False if the first Comparator returns False."""
+
+ self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1')
+
+ def testAdvancedUsage(self):
+ """And should work with other Comparators.
+
+ Note: this test is reliant on In and ContainsKeyValue.
+ """
+ test_dict = {"mock" : "obj", "testing" : "isCOOL"}
+ self.assert_(mox.And(mox.In("testing"),
+ mox.ContainsKeyValue("mock", "obj")) == test_dict)
+
+ def testAdvancedUsageFails(self):
+ """Note: this test is reliant on In and ContainsKeyValue."""
+ test_dict = {"mock" : "obj", "testing" : "isCOOL"}
+ self.failIf(mox.And(mox.In("NOTFOUND"),
+ mox.ContainsKeyValue("mock", "obj")) == test_dict)
+
+
+class SameElementsAsTest(unittest.TestCase):
+ """Test SameElementsAs correctly identifies sequences with same elements."""
+
+ def testSortedLists(self):
+ """Should return True if two lists are exactly equal."""
+ self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c'])
+
+ def testUnsortedLists(self):
+ """Should return True if two lists are unequal but have same elements."""
+ self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1])
+
+ def testUnhashableLists(self):
+ """Should return True if two lists have the same unhashable elements."""
+ self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) ==
+ [{2: 'b'}, {'a': 1}])
+
+ def testEmptyLists(self):
+ """Should return True for two empty lists."""
+ self.assert_(mox.SameElementsAs([]) == [])
+
+ def testUnequalLists(self):
+ """Should return False if the lists are not equal."""
+ self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c'])
+
+ def testUnequalUnhashableLists(self):
+ """Should return False if two lists with unhashable elements are unequal."""
+ self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])
+
+
+class ContainsKeyValueTest(unittest.TestCase):
+ """Test ContainsKeyValue correctly identifies key/value pairs in a dict.
+ """
+
+ def testValidPair(self):
+ """Should return True if the key value is in the dict."""
+ self.assert_(mox.ContainsKeyValue("key", 1) == {"key": 1})
+
+ def testInvalidValue(self):
+ """Should return False if the value is not correct."""
+ self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2})
+
+ def testInvalidKey(self):
+ """Should return False if they key is not in the dict."""
+ self.failIf(mox.ContainsKeyValue("qux", 1) == {"key": 2})
+
+
+class InTest(unittest.TestCase):
+ """Test In correctly identifies a key in a list/dict"""
+
+ def testItemInList(self):
+ """Should return True if the item is in the list."""
+ self.assert_(mox.In(1) == [1, 2, 3])
+
+ def testKeyInDict(self):
+ """Should return True if the item is a key in a dict."""
+ self.assert_(mox.In("test") == {"test" : "module"})
+
+
+class StrContainsTest(unittest.TestCase):
+ """Test StrContains correctly checks for substring occurrence of a parameter.
+ """
+
+ def testValidSubstringAtStart(self):
+ """Should return True if the substring is at the start of the string."""
+ self.assert_(mox.StrContains("hello") == "hello world")
+
+ def testValidSubstringInMiddle(self):
+ """Should return True if the substring is in the middle of the string."""
+ self.assert_(mox.StrContains("lo wo") == "hello world")
+
+ def testValidSubstringAtEnd(self):
+ """Should return True if the substring is at the end of the string."""
+ self.assert_(mox.StrContains("ld") == "hello world")
+
+ def testInvaildSubstring(self):
+ """Should return False if the substring is not in the string."""
+ self.failIf(mox.StrContains("AAA") == "hello world")
+
+ def testMultipleMatches(self):
+ """Should return True if there are multiple occurances of substring."""
+ self.assert_(mox.StrContains("abc") == "ababcabcabcababc")
+
+
+class RegexTest(unittest.TestCase):
+ """Test Regex correctly matches regular expressions."""
+
+ def testIdentifyBadSyntaxDuringInit(self):
+ """The user should know immediately if a regex has bad syntax."""
+ self.assertRaises(re.error, mox.Regex, '(a|b')
+
+ def testPatternInMiddle(self):
+ """Should return True if the pattern matches at the middle of the string.
+
+ This ensures that re.search is used (instead of re.find).
+ """
+ self.assert_(mox.Regex(r"a\s+b") == "x y z a b c")
+
+ def testNonMatchPattern(self):
+ """Should return False if the pattern does not match the string."""
+ self.failIf(mox.Regex(r"a\s+b") == "x y z")
+
+ def testFlagsPassedCorrectly(self):
+ """Should return True as we pass IGNORECASE flag."""
+ self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a")
+
+ def testReprWithoutFlags(self):
+ """repr should return the regular expression pattern."""
+ self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>")
+
+ def testReprWithFlags(self):
+ """repr should return the regular expression pattern and flags."""
+ self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) ==
+ "<regular expression 'a\s+b', flags=4>")
+
+
+class IsATest(unittest.TestCase):
+ """Verify IsA correctly checks equality based upon class type, not value."""
+
+ def testEqualityValid(self):
+ """Verify that == correctly identifies objects of the same type."""
+ self.assert_(mox.IsA(str) == 'test')
+
+ def testEqualityInvalid(self):
+ """Verify that == correctly identifies objects of different types."""
+ self.failIf(mox.IsA(str) == 10)
+
+ def testInequalityValid(self):
+ """Verify that != identifies objects of different type."""
+ self.assert_(mox.IsA(str) != 10)
+
+ def testInequalityInvalid(self):
+ """Verify that != correctly identifies objects of the same type."""
+ self.failIf(mox.IsA(str) != "test")
+
+ def testEqualityInListValid(self):
+ """Verify list contents are properly compared."""
+ isa_list = [mox.IsA(str), mox.IsA(str)]
+ str_list = ["abc", "def"]
+ self.assert_(isa_list == str_list)
+
+ def testEquailtyInListInvalid(self):
+ """Verify list contents are properly compared."""
+ isa_list = [mox.IsA(str),mox.IsA(str)]
+ mixed_list = ["abc", 123]
+ self.failIf(isa_list == mixed_list)
+
+ def testSpecialTypes(self):
+ """Verify that IsA can handle objects like cStringIO.StringIO."""
+ isA = mox.IsA(cStringIO.StringIO())
+ stringIO = cStringIO.StringIO()
+ self.assert_(isA == stringIO)
+
+class IsAlmostTest(unittest.TestCase):
+ """Verify IsAlmost correctly checks equality of floating point numbers."""
+
+ def testEqualityValid(self):
+ """Verify that == correctly identifies nearly equivalent floats."""
+ self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
+
+ def testEqualityInvalid(self):
+ """Verify that == correctly identifies non-equivalent floats."""
+ self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
+
+ def testEqualityWithPlaces(self):
+ """Verify that specifying places has the desired effect."""
+ self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
+ self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
+
+ def testNonNumericTypes(self):
+ """Verify that IsAlmost handles non-numeric types properly."""
+
+ self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9')
+ self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9)
+ self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
+
+class MockMethodTest(unittest.TestCase):
+ """Test class to verify that the MockMethod class is working correctly."""
+
+ def setUp(self):
+ self.expected_method = mox.MockMethod("testMethod", [], False)(['original'])
+ self.mock_method = mox.MockMethod("testMethod", [self.expected_method],
+ True)
+
+ def testAndReturnNoneByDefault(self):
+ """Should return None by default."""
+ return_value = self.mock_method(['original'])
+ self.assert_(return_value == None)
+
+ def testAndReturnValue(self):
+ """Should return a specificed return value."""
+ expected_return_value = "test"
+ self.expected_method.AndReturn(expected_return_value)
+ return_value = self.mock_method(['original'])
+ self.assert_(return_value == expected_return_value)
+
+ def testAndRaiseException(self):
+ """Should raise a specified exception."""
+ expected_exception = Exception('test exception')
+ self.expected_method.AndRaise(expected_exception)
+ self.assertRaises(Exception, self.mock_method)
+
+ def testWithSideEffects(self):
+ """Should call state modifier."""
+ local_list = ['original']
+ def modifier(mutable_list):
+ self.assertTrue(local_list is mutable_list)
+ mutable_list[0] = 'mutation'
+ self.expected_method.WithSideEffects(modifier).AndReturn(1)
+ self.mock_method(local_list)
+ self.assertEquals('mutation', local_list[0])
+
+ def testEqualityNoParamsEqual(self):
+ """Methods with the same name and without params should be equal."""
+ expected_method = mox.MockMethod("testMethod", [], False)
+ self.assertEqual(self.mock_method, expected_method)
+
+ def testEqualityNoParamsNotEqual(self):
+ """Methods with different names and without params should not be equal."""
+ expected_method = mox.MockMethod("otherMethod", [], False)
+ self.failIfEqual(self.mock_method, expected_method)
+
+ def testEqualityParamsEqual(self):
+ """Methods with the same name and parameters should be equal."""
+ params = [1, 2, 3]
+ expected_method = mox.MockMethod("testMethod", [], False)
+ expected_method._params = params
+
+ self.mock_method._params = params
+ self.assertEqual(self.mock_method, expected_method)
+
+ def testEqualityParamsNotEqual(self):
+ """Methods with the same name and different params should not be equal."""
+ expected_method = mox.MockMethod("testMethod", [], False)
+ expected_method._params = [1, 2, 3]
+
+ self.mock_method._params = ['a', 'b', 'c']
+ self.failIfEqual(self.mock_method, expected_method)
+
+ def testEqualityNamedParamsEqual(self):
+ """Methods with the same name and same named params should be equal."""
+ named_params = {"input1": "test", "input2": "params"}
+ expected_method = mox.MockMethod("testMethod", [], False)
+ expected_method._named_params = named_params
+
+ self.mock_method._named_params = named_params
+ self.assertEqual(self.mock_method, expected_method)
+
+ def testEqualityNamedParamsNotEqual(self):
+ """Methods with the same name and diffnamed params should not be equal."""
+ expected_method = mox.MockMethod("testMethod", [], False)
+ expected_method._named_params = {"input1": "test", "input2": "params"}
+
+ self.mock_method._named_params = {"input1": "test2", "input2": "params2"}
+ self.failIfEqual(self.mock_method, expected_method)
+
+ def testEqualityWrongType(self):
+ """Method should not be equal to an object of a different type."""
+ self.failIfEqual(self.mock_method, "string?")
+
+ def testObjectEquality(self):
+ """Equality of objects should work without a Comparator"""
+ instA = TestClass();
+ instB = TestClass();
+
+ params = [instA, ]
+ expected_method = mox.MockMethod("testMethod", [], False)
+ expected_method._params = params
+
+ self.mock_method._params = [instB, ]
+ self.assertEqual(self.mock_method, expected_method)
+
+ def testStrConversion(self):
+ method = mox.MockMethod("f", [], False)
+ method(1, 2, "st", n1=8, n2="st2")
+ self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None"))
+
+ method = mox.MockMethod("testMethod", [], False)
+ method(1, 2, "only positional")
+ self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None")
+
+ method = mox.MockMethod("testMethod", [], False)
+ method(a=1, b=2, c="only named")
+ self.assertEqual(str(method),
+ "testMethod(a=1, b=2, c='only named') -> None")
+
+ method = mox.MockMethod("testMethod", [], False)
+ method()
+ self.assertEqual(str(method), "testMethod() -> None")
+
+ method = mox.MockMethod("testMethod", [], False)
+ method(x="only 1 parameter")
+ self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None")
+
+ method = mox.MockMethod("testMethod", [], False)
+ method().AndReturn('return_value')
+ self.assertEqual(str(method), "testMethod() -> 'return_value'")
+
+ method = mox.MockMethod("testMethod", [], False)
+ method().AndReturn(('a', {1: 2}))
+ self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})")
+
+
+class MockAnythingTest(unittest.TestCase):
+ """Verify that the MockAnything class works as expected."""
+
+ def setUp(self):
+ self.mock_object = mox.MockAnything()
+
+ def testSetupMode(self):
+ """Verify the mock will accept any call."""
+ self.mock_object.NonsenseCall()
+ self.assert_(len(self.mock_object._expected_calls_queue) == 1)
+
+ def testReplayWithExpectedCall(self):
+ """Verify the mock replays method calls as expected."""
+ self.mock_object.ValidCall() # setup method call
+ self.mock_object._Replay() # start replay mode
+ self.mock_object.ValidCall() # make method call
+
+ def testReplayWithUnexpectedCall(self):
+ """Unexpected method calls should raise UnexpectedMethodCallError."""
+ self.mock_object.ValidCall() # setup method call
+ self.mock_object._Replay() # start replay mode
+ self.assertRaises(mox.UnexpectedMethodCallError,
+ self.mock_object.OtherValidCall)
+
+ def testVerifyWithCompleteReplay(self):
+ """Verify should not raise an exception for a valid replay."""
+ self.mock_object.ValidCall() # setup method call
+ self.mock_object._Replay() # start replay mode
+ self.mock_object.ValidCall() # make method call
+ self.mock_object._Verify()
+
+ def testVerifyWithIncompleteReplay(self):
+ """Verify should raise an exception if the replay was not complete."""
+ self.mock_object.ValidCall() # setup method call
+ self.mock_object._Replay() # start replay mode
+ # ValidCall() is never made
+ self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify)
+
+ def testSpecialClassMethod(self):
+ """Verify should not raise an exception when special methods are used."""
+ self.mock_object[1].AndReturn(True)
+ self.mock_object._Replay()
+ returned_val = self.mock_object[1]
+ self.assert_(returned_val)
+ self.mock_object._Verify()
+
+ def testNonzero(self):
+ """You should be able to use the mock object in an if."""
+ self.mock_object._Replay()
+ if self.mock_object:
+ pass
+
+ def testNotNone(self):
+ """Mock should be comparable to None."""
+ self.mock_object._Replay()
+ if self.mock_object is not None:
+ pass
+
+ if self.mock_object is None:
+ pass
+
+ def testEquals(self):
+ """A mock should be able to compare itself to another object."""
+ self.mock_object._Replay()
+ self.assertEquals(self.mock_object, self.mock_object)
+
+ def testEqualsMockFailure(self):
+ """Verify equals identifies unequal objects."""
+ self.mock_object.SillyCall()
+ self.mock_object._Replay()
+ self.assertNotEquals(self.mock_object, mox.MockAnything())
+
+ def testEqualsInstanceFailure(self):
+ """Verify equals identifies that objects are different instances."""
+ self.mock_object._Replay()
+ self.assertNotEquals(self.mock_object, TestClass())
+
+ def testNotEquals(self):
+ """Verify not equals works."""
+ self.mock_object._Replay()
+ self.assertFalse(self.mock_object != self.mock_object)
+
+ def testNestedMockCallsRecordedSerially(self):
+ """Test that nested calls work when recorded serially."""
+ self.mock_object.CallInner().AndReturn(1)
+ self.mock_object.CallOuter(1)
+ self.mock_object._Replay()
+
+ self.mock_object.CallOuter(self.mock_object.CallInner())
+
+ self.mock_object._Verify()
+
+ def testNestedMockCallsRecordedNested(self):
+ """Test that nested cals work when recorded in a nested fashion."""
+ self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1))
+ self.mock_object._Replay()
+
+ self.mock_object.CallOuter(self.mock_object.CallInner())
+
+ self.mock_object._Verify()
+
+ def testIsCallable(self):
+ """Test that MockAnything can even mock a simple callable.
+
+ This is handy for "stubbing out" a method in a module with a mock, and
+ verifying that it was called.
+ """
+ self.mock_object().AndReturn('mox0rd')
+ self.mock_object._Replay()
+
+ self.assertEquals('mox0rd', self.mock_object())
+
+ self.mock_object._Verify()
+
+
+class MockObjectTest(unittest.TestCase):
+ """Verify that the MockObject class works as exepcted."""
+
+ def setUp(self):
+ self.mock_object = mox.MockObject(TestClass)
+
+ def testSetupModeWithValidCall(self):
+ """Verify the mock object properly mocks a basic method call."""
+ self.mock_object.ValidCall()
+ self.assert_(len(self.mock_object._expected_calls_queue) == 1)
+
+ def testSetupModeWithInvalidCall(self):
+ """UnknownMethodCallError should be raised if a non-member method is called.
+ """
+ # Note: assertRaises does not catch exceptions thrown by MockObject's
+ # __getattr__
+ try:
+ self.mock_object.InvalidCall()
+ self.fail("No exception thrown, expected UnknownMethodCallError")
+ except mox.UnknownMethodCallError:
+ pass
+ except Exception:
+ self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
+
+ def testReplayWithInvalidCall(self):
+ """UnknownMethodCallError should be raised if a non-member method is called.
+ """
+ self.mock_object.ValidCall() # setup method call
+ self.mock_object._Replay() # start replay mode
+ # Note: assertRaises does not catch exceptions thrown by MockObject's
+ # __getattr__
+ try:
+ self.mock_object.InvalidCall()
+ self.fail("No exception thrown, expected UnknownMethodCallError")
+ except mox.UnknownMethodCallError:
+ pass
+ except Exception:
+ self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
+
+ def testIsInstance(self):
+ """Mock should be able to pass as an instance of the mocked class."""
+ self.assert_(isinstance(self.mock_object, TestClass))
+
+ def testFindValidMethods(self):
+ """Mock should be able to mock all public methods."""
+ self.assert_('ValidCall' in self.mock_object._known_methods)
+ self.assert_('OtherValidCall' in self.mock_object._known_methods)
+ self.assert_('MyClassMethod' in self.mock_object._known_methods)
+ self.assert_('MyStaticMethod' in self.mock_object._known_methods)
+ self.assert_('_ProtectedCall' in self.mock_object._known_methods)
+ self.assert_('__PrivateCall' not in self.mock_object._known_methods)
+ self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods)
+
+ def testFindsSuperclassMethods(self):
+ """Mock should be able to mock superclasses methods."""
+ self.mock_object = mox.MockObject(ChildClass)
+ self.assert_('ValidCall' in self.mock_object._known_methods)
+ self.assert_('OtherValidCall' in self.mock_object._known_methods)
+ self.assert_('MyClassMethod' in self.mock_object._known_methods)
+ self.assert_('ChildValidCall' in self.mock_object._known_methods)
+
+ def testAccessClassVariables(self):
+ """Class variables should be accessible through the mock."""
+ self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars)
+ self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)
+ self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR)
+
+ def testEquals(self):
+ """A mock should be able to compare itself to another object."""
+ self.mock_object._Replay()
+ self.assertEquals(self.mock_object, self.mock_object)
+
+ def testEqualsMockFailure(self):
+ """Verify equals identifies unequal objects."""
+ self.mock_object.ValidCall()
+ self.mock_object._Replay()
+ self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
+
+ def testEqualsInstanceFailure(self):
+ """Verify equals identifies that objects are different instances."""
+ self.mock_object._Replay()
+ self.assertNotEquals(self.mock_object, TestClass())
+
+ def testNotEquals(self):
+ """Verify not equals works."""
+ self.mock_object._Replay()
+ self.assertFalse(self.mock_object != self.mock_object)
+
+ def testMockSetItem_ExpectedSetItem_Success(self):
+ """Test that __setitem__() gets mocked in Dummy.
+
+ In this test, _Verify() succeeds.
+ """
+ dummy = mox.MockObject(TestClass)
+ dummy['X'] = 'Y'
+
+ dummy._Replay()
+
+ dummy['X'] = 'Y'
+
+ dummy._Verify()
+
+ def testMockSetItem_ExpectedSetItem_NoSuccess(self):
+ """Test that __setitem__() gets mocked in Dummy.
+
+ In this test, _Verify() fails.
+ """
+ dummy = mox.MockObject(TestClass)
+ dummy['X'] = 'Y'
+
+ dummy._Replay()
+
+ # NOT doing dummy['X'] = 'Y'
+
+ self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
+
+ def testMockSetItem_ExpectedNoSetItem_Success(self):
+ """Test that __setitem__() gets mocked in Dummy.
+
+ In this test, _Verify() succeeds.
+ """
+ dummy = mox.MockObject(TestClass)
+ # NOT doing dummy['X'] = 'Y'
+
+ dummy._Replay()
+
+ def call(): dummy['X'] = 'Y'
+ self.assertRaises(mox.UnexpectedMethodCallError, call)
+
+ dummy._Verify()
+
+ def testMockSetItem_ExpectedNoSetItem_NoSuccess(self):
+ """Test that __setitem__() gets mocked in Dummy.
+
+ In this test, _Verify() fails.
+ """
+ dummy = mox.MockObject(TestClass)
+ # NOT doing dummy['X'] = 'Y'
+
+ dummy._Replay()
+
+ # NOT doing dummy['X'] = 'Y'
+
+ dummy._Verify()
+
+ def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self):
+ """Test that __setitem__() fails if other parameters are expected."""
+ dummy = mox.MockObject(TestClass)
+ dummy['X'] = 'Y'
+
+ dummy._Replay()
+
+ def call(): dummy['wrong'] = 'Y'
+
+ self.assertRaises(mox.UnexpectedMethodCallError, call)
+
+ dummy._Verify()
+
+ def testMockGetItem_ExpectedGetItem_Success(self):
+ """Test that __setitem__() gets mocked in Dummy.
+
+ In this test, _Verify() succeeds.
+ """
+ dummy = mox.MockObject(TestClass)
+ dummy['X'].AndReturn('value')
+
+ dummy._Replay()
+
+ self.assertEqual(dummy['X'], 'value')
+
+ dummy._Verify()
+
+ def testMockGetItem_ExpectedGetItem_NoSuccess(self):
+ """Test that __setitem__() gets mocked in Dummy.
+
+ In this test, _Verify() fails.
+ """
+ dummy = mox.MockObject(TestClass)
+ dummy['X'].AndReturn('value')
+
+ dummy._Replay()
+
+ # NOT doing dummy['X']
+
+ self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
+
+ def testMockGetItem_ExpectedNoGetItem_NoSuccess(self):
+ """Test that __setitem__() gets mocked in Dummy.
+
+ In this test, _Verify() succeeds.
+ """
+ dummy = mox.MockObject(TestClass)
+ # NOT doing dummy['X']
+
+ dummy._Replay()
+
+ def call(): return dummy['X']
+ self.assertRaises(mox.UnexpectedMethodCallError, call)
+
+ dummy._Verify()
+
+ def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self):
+ """Test that __setitem__() fails if other parameters are expected."""
+ dummy = mox.MockObject(TestClass)
+ dummy['X'].AndReturn('value')
+
+ dummy._Replay()
+
+ def call(): return dummy['wrong']
+
+ self.assertRaises(mox.UnexpectedMethodCallError, call)
+
+ dummy._Verify()
+
+
+class MoxTest(unittest.TestCase):
+ """Verify Mox works correctly."""
+
+ def setUp(self):
+ self.mox = mox.Mox()
+
+ def testCreateObject(self):
+ """Mox should create a mock object."""
+ mock_obj = self.mox.CreateMock(TestClass)
+
+ def testVerifyObjectWithCompleteReplay(self):
+ """Mox should replay and verify all objects it created."""
+ mock_obj = self.mox.CreateMock(TestClass)
+ mock_obj.ValidCall()
+ mock_obj.ValidCallWithArgs(mox.IsA(TestClass))
+ self.mox.ReplayAll()
+ mock_obj.ValidCall()
+ mock_obj.ValidCallWithArgs(TestClass("some_value"))
+ self.mox.VerifyAll()
+
+ def testVerifyObjectWithIncompleteReplay(self):
+ """Mox should raise an exception if a mock didn't replay completely."""
+ mock_obj = self.mox.CreateMock(TestClass)
+ mock_obj.ValidCall()
+ self.mox.ReplayAll()
+ # ValidCall() is never made
+ self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll)
+
+ def testEntireWorkflow(self):
+ """Test the whole work flow."""
+ mock_obj = self.mox.CreateMock(TestClass)
+ mock_obj.ValidCall().AndReturn("yes")
+ self.mox.ReplayAll()
+
+ ret_val = mock_obj.ValidCall()
+ self.assertEquals("yes", ret_val)
+ self.mox.VerifyAll()
+
+ def testCallableObject(self):
+ """Test recording calls to a callable object works."""
+ mock_obj = self.mox.CreateMock(CallableClass)
+ mock_obj("foo").AndReturn("qux")
+ self.mox.ReplayAll()
+
+ ret_val = mock_obj("foo")
+ self.assertEquals("qux", ret_val)
+ self.mox.VerifyAll()
+
+ def testCallOnNonCallableObject(self):
+ """Test that you cannot call a non-callable object."""
+ mock_obj = self.mox.CreateMock(TestClass)
+ self.assertRaises(TypeError, mock_obj)
+
+ def testCallableObjectWithBadCall(self):
+ """Test verifying calls to a callable object works."""
+ mock_obj = self.mox.CreateMock(CallableClass)
+ mock_obj("foo").AndReturn("qux")
+ self.mox.ReplayAll()
+
+ self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, "ZOOBAZ")
+
+ def testUnorderedGroup(self):
+ """Test that using one unordered group works."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Method(1).InAnyOrder()
+ mock_obj.Method(2).InAnyOrder()
+ self.mox.ReplayAll()
+
+ mock_obj.Method(2)
+ mock_obj.Method(1)
+
+ self.mox.VerifyAll()
+
+ def testUnorderedGroupsInline(self):
+ """Unordered groups should work in the context of ordered calls."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Open()
+ mock_obj.Method(1).InAnyOrder()
+ mock_obj.Method(2).InAnyOrder()
+ mock_obj.Close()
+ self.mox.ReplayAll()
+
+ mock_obj.Open()
+ mock_obj.Method(2)
+ mock_obj.Method(1)
+ mock_obj.Close()
+
+ self.mox.VerifyAll()
+
+ def testMultipleUnorderdGroups(self):
+ """Multiple unoreded groups should work."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Method(1).InAnyOrder()
+ mock_obj.Method(2).InAnyOrder()
+ mock_obj.Foo().InAnyOrder('group2')
+ mock_obj.Bar().InAnyOrder('group2')
+ self.mox.ReplayAll()
+
+ mock_obj.Method(2)
+ mock_obj.Method(1)
+ mock_obj.Bar()
+ mock_obj.Foo()
+
+ self.mox.VerifyAll()
+
+ def testMultipleUnorderdGroupsOutOfOrder(self):
+ """Multiple unordered groups should maintain external order"""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Method(1).InAnyOrder()
+ mock_obj.Method(2).InAnyOrder()
+ mock_obj.Foo().InAnyOrder('group2')
+ mock_obj.Bar().InAnyOrder('group2')
+ self.mox.ReplayAll()
+
+ mock_obj.Method(2)
+ self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar)
+
+ def testUnorderedGroupWithReturnValue(self):
+ """Unordered groups should work with return values."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Open()
+ mock_obj.Method(1).InAnyOrder().AndReturn(9)
+ mock_obj.Method(2).InAnyOrder().AndReturn(10)
+ mock_obj.Close()
+ self.mox.ReplayAll()
+
+ mock_obj.Open()
+ actual_two = mock_obj.Method(2)
+ actual_one = mock_obj.Method(1)
+ mock_obj.Close()
+
+ self.assertEquals(9, actual_one)
+ self.assertEquals(10, actual_two)
+
+ self.mox.VerifyAll()
+
+ def testUnorderedGroupWithComparator(self):
+ """Unordered groups should work with comparators"""
+
+ def VerifyOne(cmd):
+ if not isinstance(cmd, str):
+ self.fail('Unexpected type passed to comparator: ' + str(cmd))
+ return cmd == 'test'
+
+ def VerifyTwo(cmd):
+ return True
+
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\
+ AndReturn('yes test')
+ mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\
+ AndReturn('anything')
+
+ self.mox.ReplayAll()
+
+ mock_obj.Foo(['test'], 'anything', bar=1)
+ mock_obj.Foo(['test'], 'test', bar=1)
+
+ self.mox.VerifyAll()
+
+ def testMultipleTimes(self):
+ """Test if MultipleTimesGroup works."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Method(1).MultipleTimes().AndReturn(9)
+ mock_obj.Method(2).AndReturn(10)
+ mock_obj.Method(3).MultipleTimes().AndReturn(42)
+ self.mox.ReplayAll()
+
+ actual_one = mock_obj.Method(1)
+ second_one = mock_obj.Method(1) # This tests MultipleTimes.
+ actual_two = mock_obj.Method(2)
+ actual_three = mock_obj.Method(3)
+ mock_obj.Method(3)
+ mock_obj.Method(3)
+
+ self.assertEquals(9, actual_one)
+ self.assertEquals(9, second_one) # Repeated calls should return same number.
+ self.assertEquals(10, actual_two)
+ self.assertEquals(42, actual_three)
+
+ self.mox.VerifyAll()
+
+ def testMultipleTimesUsingIsAParameter(self):
+ """Test if MultipleTimesGroup works with a IsA parameter."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Open()
+ mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9)
+ mock_obj.Close()
+ self.mox.ReplayAll()
+
+ mock_obj.Open()
+ actual_one = mock_obj.Method("1")
+ second_one = mock_obj.Method("2") # This tests MultipleTimes.
+ mock_obj.Close()
+
+ self.assertEquals(9, actual_one)
+ self.assertEquals(9, second_one) # Repeated calls should return same number.
+
+ self.mox.VerifyAll()
+
+ def testMultipleTimesThreeMethods(self):
+ """Test if MultipleTimesGroup works with three or more methods."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Open()
+ mock_obj.Method(1).MultipleTimes().AndReturn(9)
+ mock_obj.Method(2).MultipleTimes().AndReturn(8)
+ mock_obj.Method(3).MultipleTimes().AndReturn(7)
+ mock_obj.Method(4).AndReturn(10)
+ mock_obj.Close()
+ self.mox.ReplayAll()
+
+ mock_obj.Open()
+ actual_three = mock_obj.Method(3)
+ mock_obj.Method(1)
+ actual_two = mock_obj.Method(2)
+ mock_obj.Method(3)
+ actual_one = mock_obj.Method(1)
+ actual_four = mock_obj.Method(4)
+ mock_obj.Close()
+
+ self.assertEquals(9, actual_one)
+ self.assertEquals(8, actual_two)
+ self.assertEquals(7, actual_three)
+ self.assertEquals(10, actual_four)
+
+ self.mox.VerifyAll()
+
+ def testMultipleTimesMissingOne(self):
+ """Test if MultipleTimesGroup fails if one method is missing."""
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Open()
+ mock_obj.Method(1).MultipleTimes().AndReturn(9)
+ mock_obj.Method(2).MultipleTimes().AndReturn(8)
+ mock_obj.Method(3).MultipleTimes().AndReturn(7)
+ mock_obj.Method(4).AndReturn(10)
+ mock_obj.Close()
+ self.mox.ReplayAll()
+
+ mock_obj.Open()
+ mock_obj.Method(3)
+ mock_obj.Method(2)
+ mock_obj.Method(3)
+ mock_obj.Method(3)
+ mock_obj.Method(2)
+
+ self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4)
+
+ def testMultipleTimesTwoGroups(self):
+ """Test if MultipleTimesGroup works with a group after a
+ MultipleTimesGroup.
+ """
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Open()
+ mock_obj.Method(1).MultipleTimes().AndReturn(9)
+ mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
+ mock_obj.Close()
+ self.mox.ReplayAll()
+
+ mock_obj.Open()
+ actual_one = mock_obj.Method(1)
+ mock_obj.Method(1)
+ actual_three = mock_obj.Method(3)
+ mock_obj.Method(3)
+ mock_obj.Close()
+
+ self.assertEquals(9, actual_one)
+ self.assertEquals(42, actual_three)
+
+ self.mox.VerifyAll()
+
+ def testMultipleTimesTwoGroupsFailure(self):
+ """Test if MultipleTimesGroup fails with a group after a
+ MultipleTimesGroup.
+ """
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.Open()
+ mock_obj.Method(1).MultipleTimes().AndReturn(9)
+ mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
+ mock_obj.Close()
+ self.mox.ReplayAll()
+
+ mock_obj.Open()
+ actual_one = mock_obj.Method(1)
+ mock_obj.Method(1)
+ actual_three = mock_obj.Method(3)
+
+ self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1)
+
+ def testWithSideEffects(self):
+ """Test side effect operations actually modify their target objects."""
+ def modifier(mutable_list):
+ mutable_list[0] = 'mutated'
+ mock_obj = self.mox.CreateMockAnything()
+ mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier)
+ mock_obj.WorkWithParameter(['mutated'])
+ self.mox.ReplayAll()
+
+ local_list = ['original']
+ mock_obj.ConfigureInOutParameter(local_list)
+ mock_obj.WorkWithParameter(local_list)
+
+ self.mox.VerifyAll()
+
+ def testWithSideEffectsException(self):
+ """Test side effect operations actually modify their target objects."""
+ def modifier(mutable_list):
+ mutable_list[0] = 'mutated'
+ mock_obj = self.mox.CreateMockAnything()
+ method = mock_obj.ConfigureInOutParameter(['original'])
+ method.WithSideEffects(modifier).AndRaise(Exception('exception'))
+ mock_obj.WorkWithParameter(['mutated'])
+ self.mox.ReplayAll()
+
+ local_list = ['original']
+ self.failUnlessRaises(Exception,
+ mock_obj.ConfigureInOutParameter,
+ local_list)
+ mock_obj.WorkWithParameter(local_list)
+
+ self.mox.VerifyAll()
+
+ def testStubOutMethod(self):
+ """Test that a method is replaced with a MockAnything."""
+ test_obj = TestClass()
+ # Replace OtherValidCall with a mock.
+ self.mox.StubOutWithMock(test_obj, 'OtherValidCall')
+ self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything))
+ test_obj.OtherValidCall().AndReturn('foo')
+ self.mox.ReplayAll()
+
+ actual = test_obj.OtherValidCall()
+
+ self.mox.VerifyAll()
+ self.mox.UnsetStubs()
+ self.assertEquals('foo', actual)
+ self.failIf(isinstance(test_obj.OtherValidCall, mox.MockAnything))
+
+ def testStubOutObject(self):
+ """Test than object is replaced with a Mock."""
+
+ class Foo(object):
+ def __init__(self):
+ self.obj = TestClass()
+
+ foo = Foo()
+ self.mox.StubOutWithMock(foo, "obj")
+ self.assert_(isinstance(foo.obj, mox.MockObject))
+ foo.obj.ValidCall()
+ self.mox.ReplayAll()
+
+ foo.obj.ValidCall()
+
+ self.mox.VerifyAll()
+ self.mox.UnsetStubs()
+ self.failIf(isinstance(foo.obj, mox.MockObject))
+
+ def testForgotReplayHelpfulMessage(self):
+ """If there is an AttributeError on a MockMethod, give users a helpful msg.
+ """
+ foo = self.mox.CreateMockAnything()
+ bar = self.mox.CreateMockAnything()
+ foo.GetBar().AndReturn(bar)
+ bar.ShowMeTheMoney()
+ # Forgot to replay!
+ try:
+ foo.GetBar().ShowMeTheMoney()
+ except AttributeError, e:
+ self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". '
+ 'Did you remember to put your mocks in replay mode?', str(e))
+
+class ReplayTest(unittest.TestCase):
+ """Verify Replay works properly."""
+
+ def testReplay(self):
+ """Replay should put objects into replay mode."""
+ mock_obj = mox.MockObject(TestClass)
+ self.assertFalse(mock_obj._replay_mode)
+ mox.Replay(mock_obj)
+ self.assertTrue(mock_obj._replay_mode)
+
+class MoxTestBaseTest(unittest.TestCase):
+ """Verify that all tests in a class derived from MoxTestBase are wrapped."""
+
+ def setUp(self):
+ self.mox = mox.Mox()
+ self.test_mox = mox.Mox()
+ self.result = unittest.TestResult()
+
+ def tearDown(self):
+ # In case one of our tests fail before UnsetStubs is called.
+ self.mox.UnsetStubs()
+ self.test_mox.UnsetStubs()
+
+ def _setUpTestClass(self):
+ """Replacement for setUp in the test class instance.
+
+ Assigns a mox.Mox instance as the mox attribute of the test class instance.
+ This replacement Mox instance is under our control before setUp is called
+ in the test class instance.
+ """
+ self.test.mox = self.test_mox
+
+ def _CreateTest(self, test_name):
+ """Create a test from our example mox class.
+
+ The created test instance is assigned to this instances test attribute.
+ """
+ self.test = mox_test_helper.ExampleMoxTest(test_name)
+ self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass)
+
+ def _VerifySuccess(self):
+ """Run the checks to confirm test method completed successfully."""
+ self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
+ self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
+ self.test_mox.UnsetStubs()
+ self.test_mox.VerifyAll()
+ self.mox.ReplayAll()
+ self.test.run(result=self.result)
+ self.assertTrue(self.result.wasSuccessful())
+ self.mox.UnsetStubs()
+ self.mox.VerifyAll()
+ self.test_mox.UnsetStubs()
+ self.test_mox.VerifyAll()
+
+ def testSuccess(self):
+ """Successful test method execution test."""
+ self._CreateTest('testSuccess')
+ self._VerifySuccess()
+
+ def testExpectedNotCalled(self):
+ """Stubbed out method is not called."""
+ self._CreateTest('testExpectedNotCalled')
+ self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
+ # Dont stub out VerifyAll - that's what causes the test to fail
+ self.test_mox.UnsetStubs()
+ self.test_mox.VerifyAll()
+ self.mox.ReplayAll()
+ self.test.run(result=self.result)
+ self.failIf(self.result.wasSuccessful())
+ self.mox.UnsetStubs()
+ self.mox.VerifyAll()
+ self.test_mox.UnsetStubs()
+
+ def testUnexpectedCall(self):
+ """Stubbed out method is called with unexpected arguments."""
+ self._CreateTest('testUnexpectedCall')
+ self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
+ # Ensure no calls are made to VerifyAll()
+ self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
+ self.test_mox.UnsetStubs()
+ self.mox.ReplayAll()
+ self.test.run(result=self.result)
+ self.failIf(self.result.wasSuccessful())
+ self.mox.UnsetStubs()
+ self.mox.VerifyAll()
+ self.test_mox.UnsetStubs()
+
+ def testFailure(self):
+ """Failing assertion in test method."""
+ self._CreateTest('testFailure')
+ self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
+ # Ensure no calls are made to VerifyAll()
+ self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
+ self.test_mox.UnsetStubs()
+ self.mox.ReplayAll()
+ self.test.run(result=self.result)
+ self.failIf(self.result.wasSuccessful())
+ self.mox.UnsetStubs()
+ self.mox.VerifyAll()
+ self.test_mox.UnsetStubs()
+
+ def testMixin(self):
+ """Run test from mix-in test class, ensure it passes."""
+ self._CreateTest('testStat')
+ self._VerifySuccess()
+
+ def testMixinAgain(self):
+ """Run same test as above but from the current test class.
+
+ This ensures metaclass properly wrapped test methods from all base classes.
+ If unsetting of stubs doesn't happen, this will fail.
+ """
+ self._CreateTest('testStatOther')
+ self._VerifySuccess()
+
+
+class VerifyTest(unittest.TestCase):
+ """Verify Verify works properly."""
+
+ def testVerify(self):
+ """Verify should be called for all objects.
+
+ This should throw an exception because the expected behavior did not occur.
+ """
+ mock_obj = mox.MockObject(TestClass)
+ mock_obj.ValidCall()
+ mock_obj._Replay()
+ self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
+
+
+class ResetTest(unittest.TestCase):
+ """Verify Reset works properly."""
+
+ def testReset(self):
+ """Should empty all queues and put mocks in record mode."""
+ mock_obj = mox.MockObject(TestClass)
+ mock_obj.ValidCall()
+ self.assertFalse(mock_obj._replay_mode)
+ mock_obj._Replay()
+ self.assertTrue(mock_obj._replay_mode)
+ self.assertEquals(1, len(mock_obj._expected_calls_queue))
+
+ mox.Reset(mock_obj)
+ self.assertFalse(mock_obj._replay_mode)
+ self.assertEquals(0, len(mock_obj._expected_calls_queue))
+
+
+class TestClass:
+ """This class is used only for testing the mock framework"""
+
+ SOME_CLASS_VAR = "test_value"
+ _PROTECTED_CLASS_VAR = "protected value"
+
+ def __init__(self, ivar=None):
+ self.__ivar = ivar
+
+ def __eq__(self, rhs):
+ return self.__ivar == rhs
+
+ def __ne__(self, rhs):
+ return not self.__eq__(rhs)
+
+ def ValidCall(self):
+ pass
+
+ def OtherValidCall(self):
+ pass
+
+ def ValidCallWithArgs(self, *args, **kwargs):
+ pass
+
+ @classmethod
+ def MyClassMethod(cls):
+ pass
+
+ @staticmethod
+ def MyStaticMethod():
+ pass
+
+ def _ProtectedCall(self):
+ pass
+
+ def __PrivateCall(self):
+ pass
+
+ def __getitem__(self, key):
+ pass
+
+ def __DoNotMock(self):
+ pass
+
+ def __getitem__(self, key):
+ """Return the value for key."""
+ return self.d[key]
+
+ def __setitem__(self, key, value):
+ """Set the value for key to value."""
+ self.d[key] = value
+
+
+class ChildClass(TestClass):
+ """This inherits from TestClass."""
+ def __init__(self):
+ TestClass.__init__(self)
+
+ def ChildValidCall(self):
+ pass
+
+
+class CallableClass(object):
+ """This class is callable, and that should be mockable!"""
+
+ def __init__(self):
+ pass
+
+ def __call__(self, param):
+ return param
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/mox_test_helper.py b/mox_test_helper.py
new file mode 100755
index 0000000..164c0ec
--- /dev/null
+++ b/mox_test_helper.py
@@ -0,0 +1,76 @@
+#!/usr/bin/python2.4
+#
+# Copyright 2008 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""A very basic test class derived from mox.MoxTestBase, used by mox_test.py.
+
+The class defined in this module is used to test the features of
+MoxTestBase and is not intended to be a standalone test. It needs to
+be in a separate module, because otherwise the tests in this class
+(which should not all pass) would be executed as part of the
+mox_test.py test suite.
+
+See mox_test.MoxTestBaseTest for how this class is actually used.
+"""
+
+import os
+
+import mox
+
+class ExampleMoxTestMixin(object):
+ """Mix-in class for mox test case class.
+
+ It stubs out the same function as one of the test methods in
+ the example test case. Both tests must pass as meta class wraps
+ test methods in all base classes.
+ """
+
+ def testStat(self):
+ self.mox.StubOutWithMock(os, 'stat')
+ os.stat(self.DIR_PATH)
+ self.mox.ReplayAll()
+ os.stat(self.DIR_PATH)
+
+
+class ExampleMoxTest(mox.MoxTestBase, ExampleMoxTestMixin):
+
+ DIR_PATH = '/path/to/some/directory'
+
+ def testSuccess(self):
+ self.mox.StubOutWithMock(os, 'listdir')
+ os.listdir(self.DIR_PATH)
+ self.mox.ReplayAll()
+ os.listdir(self.DIR_PATH)
+
+ def testExpectedNotCalled(self):
+ self.mox.StubOutWithMock(os, 'listdir')
+ os.listdir(self.DIR_PATH)
+ self.mox.ReplayAll()
+
+ def testUnexpectedCall(self):
+ self.mox.StubOutWithMock(os, 'listdir')
+ os.listdir(self.DIR_PATH)
+ self.mox.ReplayAll()
+ os.listdir('/path/to/some/other/directory')
+ os.listdir(self.DIR_PATH)
+
+ def testFailure(self):
+ self.assertTrue(False)
+
+ def testStatOther(self):
+ self.mox.StubOutWithMock(os, 'stat')
+ os.stat(self.DIR_PATH)
+ self.mox.ReplayAll()
+ os.stat(self.DIR_PATH)
diff --git a/setup.py b/setup.py
new file mode 100755
index 0000000..8eaa6b2
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,15 @@
+#!/usr/bin/python2.4
+from distutils.core import setup
+# TODO(glasser): Make sure that test stuff is included/documented.
+setup(name='mox',
+ version='1.0.0',
+ py_modules=['mox', 'stubout'],
+ url='http://code.google.com/p/pymox/',
+ maintainer='pymox maintainers',
+ # TODO(glasser): Make pymox-devel list.
+ maintainer_email='pymox-devel@googlegroups.com',
+ license='Apache License, Version 2.0',
+ description='Mock object framework',
+ long_description='''Mox is a mock object framework for Python based on the
+Java mock object framework EasyMock.''',
+ )
diff --git a/stubout.py b/stubout.py
new file mode 100644
index 0000000..d253de1
--- /dev/null
+++ b/stubout.py
@@ -0,0 +1,137 @@
+#!/usr/bin/python2.4
+#
+# Copyright 2008 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+class StubOutForTesting:
+ """Sample Usage:
+ You want os.path.exists() to always return true during testing.
+
+ stubs = StubOutForTesting()
+ stubs.Set(os.path, 'exists', lambda x: 1)
+ ...
+ stubs.UnsetAll()
+
+ The above changes os.path.exists into a lambda that returns 1. Once
+ the ... part of the code finishes, the UnsetAll() looks up the old value
+ of os.path.exists and restores it.
+
+ """
+ def __init__(self):
+ self.cache = []
+ self.stubs = []
+
+ def __del__(self):
+ self.SmartUnsetAll()
+ self.UnsetAll()
+
+ def SmartSet(self, obj, attr_name, new_attr):
+ """Replace obj.attr_name with new_attr. This method is smart and works
+ at the module, class, and instance level while preserving proper
+ inheritance. It will not stub out C types however unless that has been
+ explicitly allowed by the type.
+
+ This method supports the case where attr_name is a staticmethod or a
+ classmethod of obj.
+
+ Notes:
+ - If obj is an instance, then it is its class that will actually be
+ stubbed. Note that the method Set() does not do that: if obj is
+ an instance, it (and not its class) will be stubbed.
+ - The stubbing is using the builtin getattr and setattr. So, the __get__
+ and __set__ will be called when stubbing (TODO: A better idea would
+ probably be to manipulate obj.__dict__ instead of getattr() and
+ setattr()).
+
+ Raises AttributeError if the attribute cannot be found.
+ """
+ if (inspect.ismodule(obj) or
+ (not inspect.isclass(obj) and obj.__dict__.has_key(attr_name))):
+ orig_obj = obj
+ orig_attr = getattr(obj, attr_name)
+
+ else:
+ if not inspect.isclass(obj):
+ mro = list(inspect.getmro(obj.__class__))
+ else:
+ mro = list(inspect.getmro(obj))
+
+ mro.reverse()
+
+ orig_attr = None
+
+ for cls in mro:
+ try:
+ orig_obj = cls
+ orig_attr = getattr(obj, attr_name)
+ except AttributeError:
+ continue
+
+ if orig_attr is None:
+ raise AttributeError("Attribute not found.")
+
+ # Calling getattr() on a staticmethod transforms it to a 'normal' function.
+ # We need to ensure that we put it back as a staticmethod.
+ old_attribute = obj.__dict__.get(attr_name)
+ if old_attribute is not None and isinstance(old_attribute, staticmethod):
+ orig_attr = staticmethod(orig_attr)
+
+ self.stubs.append((orig_obj, attr_name, orig_attr))
+ setattr(orig_obj, attr_name, new_attr)
+
+ def SmartUnsetAll(self):
+ """Reverses all the SmartSet() calls, restoring things to their original
+ definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
+ have no effect if no SmartSet() calls have been made.
+
+ """
+ self.stubs.reverse()
+
+ for args in self.stubs:
+ setattr(*args)
+
+ self.stubs = []
+
+ def Set(self, parent, child_name, new_child):
+ """Replace child_name's old definition with new_child, in the context
+ of the given parent. The parent could be a module when the child is a
+ function at module scope. Or the parent could be a class when a class'
+ method is being replaced. The named child is set to new_child, while
+ the prior definition is saved away for later, when UnsetAll() is called.
+
+ This method supports the case where child_name is a staticmethod or a
+ classmethod of parent.
+ """
+ old_child = getattr(parent, child_name)
+
+ old_attribute = parent.__dict__.get(child_name)
+ if old_attribute is not None and isinstance(old_attribute, staticmethod):
+ old_child = staticmethod(old_child)
+
+ self.cache.append((parent, old_child, child_name))
+ setattr(parent, child_name, new_child)
+
+ def UnsetAll(self):
+ """Reverses all the Set() calls, restoring things to their original
+ definition. Its okay to call UnsetAll() repeatedly, as later calls have
+ no effect if no Set() calls have been made.
+
+ """
+ # Undo calls to Set() in reverse order, in case Set() was called on the
+ # same arguments repeatedly (want the original call to be last one undone)
+ self.cache.reverse()
+
+ for (parent, old_child, child_name) in self.cache:
+ setattr(parent, child_name, old_child)
+ self.cache = []