mockito-0.5.2/0000755000076500001200000000000012231253716013756 5ustar justinhadmin00000000000000mockito-0.5.2/AUTHORS0000644000076500001200000000007212231116530015015 0ustar justinhadmin00000000000000Szczepan Faber Serhiy Oplakanets Herr Kaste Justin Hopper mockito-0.5.2/distribute_setup.py0000644000076500001200000003566512230723247017745 0ustar justinhadmin00000000000000#!python """Bootstrap distribute installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from distribute_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import os import sys import time import fnmatch import tempfile import tarfile from distutils import log try: from site import USER_SITE except ImportError: USER_SITE = None try: import subprocess def _python_cmd(*args): args = (sys.executable,) + args return subprocess.call(args) == 0 except ImportError: # will be used for python 2.3 def _python_cmd(*args): args = (sys.executable,) + args # quoting arguments if windows if sys.platform == 'win32': def quote(arg): if ' ' in arg: return '"%s"' % arg return arg args = [quote(arg) for arg in args] return os.spawnl(os.P_WAIT, sys.executable, *args) == 0 DEFAULT_VERSION = "0.6.10" DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/" SETUPTOOLS_FAKED_VERSION = "0.6c11" SETUPTOOLS_PKG_INFO = """\ Metadata-Version: 1.0 Name: setuptools Version: %s Summary: xxxx Home-page: xxx Author: xxx Author-email: xxx License: xxx Description: xxx """ % SETUPTOOLS_FAKED_VERSION def _install(tarball): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # installing log.warn('Installing Distribute') if not _python_cmd('setup.py', 'install'): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') finally: os.chdir(old_wd) def _build_egg(egg, tarball, to_dir): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # building an egg log.warn('Building a Distribute egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) finally: os.chdir(old_wd) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): tarball = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, tarball, to_dir) sys.path.insert(0, egg) import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15, no_fake=True): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try: try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): if not no_fake: _fake_setuptools() raise ImportError except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("distribute>="+version) return except pkg_resources.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of distribute (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U distribute'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) finally: if not no_fake: _create_fake_setuptools_pkg_info(to_dir) def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15): """Download distribute from a specified location and return its filename `version` should be a valid distribute version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen tgz_name = "distribute-%s.tar.gz" % version url = download_base + tgz_name saveto = os.path.join(to_dir, tgz_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: log.warn("Downloading %s", url) src = urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = src.read() dst = open(saveto, "wb") dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def _patch_file(path, content): """Will backup the file then patch it""" existing_content = open(path).read() if existing_content == content: # already patched log.warn('Already patched.') return False log.warn('Patching...') _rename_path(path) f = open(path, 'w') try: f.write(content) finally: f.close() return True def _same_content(path, content): return open(path).read() == content def _no_sandbox(function): def __no_sandbox(*args, **kw): try: from setuptools.sandbox import DirectorySandbox def violation(*args): pass DirectorySandbox._old = DirectorySandbox._violation DirectorySandbox._violation = violation patched = True except ImportError: patched = False try: return function(*args, **kw) finally: if patched: DirectorySandbox._violation = DirectorySandbox._old del DirectorySandbox._old return __no_sandbox @_no_sandbox def _rename_path(path): new_name = path + '.OLD.%s' % time.time() log.warn('Renaming %s into %s', path, new_name) os.rename(path, new_name) return new_name def _remove_flat_installation(placeholder): if not os.path.isdir(placeholder): log.warn('Unkown installation at %s', placeholder) return False found = False for file in os.listdir(placeholder): if fnmatch.fnmatch(file, 'setuptools*.egg-info'): found = True break if not found: log.warn('Could not locate setuptools*.egg-info') return log.warn('Removing elements out of the way...') pkg_info = os.path.join(placeholder, file) if os.path.isdir(pkg_info): patched = _patch_egg_dir(pkg_info) else: patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) if not patched: log.warn('%s already patched.', pkg_info) return False # now let's move the files out of the way for element in ('setuptools', 'pkg_resources.py', 'site.py'): element = os.path.join(placeholder, element) if os.path.exists(element): _rename_path(element) else: log.warn('Could not find the %s element of the ' 'Setuptools distribution', element) return True def _after_install(dist): log.warn('After install bootstrap.') placeholder = dist.get_command_obj('install').install_purelib _create_fake_setuptools_pkg_info(placeholder) @_no_sandbox def _create_fake_setuptools_pkg_info(placeholder): if not placeholder or not os.path.exists(placeholder): log.warn('Could not find the install location') return pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) setuptools_file = 'setuptools-%s-py%s.egg-info' % \ (SETUPTOOLS_FAKED_VERSION, pyver) pkg_info = os.path.join(placeholder, setuptools_file) if os.path.exists(pkg_info): log.warn('%s already exists', pkg_info) return log.warn('Creating %s', pkg_info) f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() pth_file = os.path.join(placeholder, 'setuptools.pth') log.warn('Creating %s', pth_file) f = open(pth_file, 'w') try: f.write(os.path.join(os.curdir, setuptools_file)) finally: f.close() def _patch_egg_dir(path): # let's check if it's already patched pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') if os.path.exists(pkg_info): if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): log.warn('%s already patched.', pkg_info) return False _rename_path(path) os.mkdir(path) os.mkdir(os.path.join(path, 'EGG-INFO')) pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() return True def _before_install(): log.warn('Before install bootstrap.') _fake_setuptools() def _under_prefix(location): if 'install' not in sys.argv: return True args = sys.argv[sys.argv.index('install')+1:] for index, arg in enumerate(args): for option in ('--root', '--prefix'): if arg.startswith('%s=' % option): top_dir = arg.split('root=')[-1] return location.startswith(top_dir) elif arg == option: if len(args) > index: top_dir = args[index+1] return location.startswith(top_dir) elif option == '--user' and USER_SITE is not None: return location.startswith(USER_SITE) return True def _fake_setuptools(): log.warn('Scanning installed packages') try: import pkg_resources except ImportError: # we're cool log.warn('Setuptools or Distribute does not seem to be installed.') return ws = pkg_resources.working_set try: setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools', replacement=False)) except TypeError: # old distribute API setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools')) if setuptools_dist is None: log.warn('No setuptools distribution found') return # detecting if it was already faked setuptools_location = setuptools_dist.location log.warn('Setuptools installation detected at %s', setuptools_location) # if --root or --preix was provided, and if # setuptools is not located in them, we don't patch it if not _under_prefix(setuptools_location): log.warn('Not patching, --root or --prefix is installing Distribute' ' in another location') return # let's see if its an egg if not setuptools_location.endswith('.egg'): log.warn('Non-egg installation') res = _remove_flat_installation(setuptools_location) if not res: return else: log.warn('Egg installation') pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') if (os.path.exists(pkg_info) and _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): log.warn('Already patched.') return log.warn('Patching...') # let's create a fake egg replacing setuptools one res = _patch_egg_dir(setuptools_location) if not res: return log.warn('Patched done.') _relaunch() def _relaunch(): log.warn('Relaunching...') # we have to relaunch the process args = [sys.executable] + sys.argv sys.exit(subprocess.call(args)) def _extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ import copy import operator from tarfile import ExtractError directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 448 # decimal for oct 0700 self.extract(tarinfo, path) # Reverse sort directories. if sys.version_info < (2, 4): def sorter(dir1, dir2): return cmp(dir1.name, dir2.name) directories.sort(sorter) directories.reverse() else: directories.sort(key=operator.attrgetter('name'), reverse=True) # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError: e = sys.exc_info()[1] if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball) if __name__ == '__main__': main(sys.argv[1:]) mockito-0.5.2/LICENSE0000644000076500001200000000212712231123464014761 0ustar justinhadmin00000000000000Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.mockito-0.5.2/MANIFEST.in0000644000076500001200000000013012231134651015502 0ustar justinhadmin00000000000000recursive-include mockito_test *.py include AUTHORS include LICENSE include README.rst mockito-0.5.2/mockito/0000755000076500001200000000000012231253716015423 5ustar justinhadmin00000000000000mockito-0.5.2/mockito/__init__.py0000644000076500001200000000370212231133437017533 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. '''Mockito is a Test Spy framework.''' from mockito import mock, verify, verifyNoMoreInteractions, verifyZeroInteractions, when, unstub, ArgumentError import inorder from spying import spy from verification import VerificationError # Imports for compatibility from mocking import Mock from matchers import any, contains, times # use package import (``from mockito.matchers import any, contains``) instead of ``from mockito import any, contains`` from verification import never __all__ = ['mock', 'spy', 'verify', 'verifyNoMoreInteractions', 'verifyZeroInteractions', 'inorder', 'when', 'unstub', 'VerificationError', 'ArgumentError', 'Mock', # deprecated 'any', # compatibility 'contains', # compatibility 'never', # compatibility 'times' # deprecated ] mockito-0.5.2/mockito/inorder.py0000644000076500001200000000253712231133437017443 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from mockito import verify as verify_main __author__ = "Serhiy Oplakanets " def verify(object, *args, **kwargs): kwargs['inorder'] = True return verify_main(object, *args, **kwargs) mockito-0.5.2/mockito/invocation.py0000644000076500001200000001363212231133437020150 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import matchers class InvocationError(AssertionError): pass class Invocation(object): def __init__(self, mock, method_name): self.method_name = method_name self.mock = mock self.verified = False self.verified_inorder = False self.params = () self.named_params = {} self.answers = [] self.strict = mock.strict def _remember_params(self, params, named_params): self.params = params self.named_params = named_params def __repr__(self): return self.method_name + "(" + ", ".join([repr(p) for p in self.params]) + ")" def answer_first(self): return self.answers[0].answer() class MatchingInvocation(Invocation): @staticmethod def compare(p1, p2): if isinstance(p1, matchers.Matcher): if not p1.matches(p2): return False elif p1 != p2: return False return True def matches(self, invocation): if self.method_name != invocation.method_name: return False if len(self.params) != len(invocation.params): return False if len(self.named_params) != len(invocation.named_params): return False if self.named_params.keys() != invocation.named_params.keys(): return False for x, p1 in enumerate(self.params): if not self.compare(p1, invocation.params[x]): return False for x, p1 in self.named_params.iteritems(): if not self.compare(p1, invocation.named_params[x]): return False return True class RememberedInvocation(Invocation): def __call__(self, *params, **named_params): self._remember_params(params, named_params) self.mock.remember(self) for matching_invocation in self.mock.stubbed_invocations: if matching_invocation.matches(self): return matching_invocation.answer_first() return None class RememberedProxyInvocation(Invocation): '''Remeber params and proxy to method of original object. Calls method on original object and returns it's return value. ''' def __call__(self, *params, **named_params): self._remember_params(params, named_params) self.mock.remember(self) obj = self.mock.original_object try: method = getattr(obj, self.method_name) except AttributeError: raise AttributeError("You tried to call method '%s' which '%s' instance does not have." % (self.method_name, obj.__class__.__name__)) return method(*params, **named_params) class VerifiableInvocation(MatchingInvocation): def __call__(self, *params, **named_params): self._remember_params(params, named_params) matched_invocations = [] for invocation in self.mock.invocations: if self.matches(invocation): matched_invocations.append(invocation) verification = self.mock.pull_verification() verification.verify(self, len(matched_invocations)) for invocation in matched_invocations: invocation.verified = True class StubbedInvocation(MatchingInvocation): def __init__(self, *params): super(StubbedInvocation, self).__init__(*params) if self.mock.strict: self.ensure_mocked_object_has_method(self.method_name) def ensure_mocked_object_has_method(self, method_name): if not self.mock.has_method(method_name): raise InvocationError("You tried to stub a method '%s' the object (%s) doesn't have." % (method_name, self.mock.mocked_obj)) def __call__(self, *params, **named_params): self._remember_params(params, named_params) return AnswerSelector(self) def stub_with(self, answer): self.answers.append(answer) self.mock.stub(self.method_name) self.mock.finish_stubbing(self) class AnswerSelector(object): def __init__(self, invocation): self.invocation = invocation self.answer = None def thenReturn(self, *return_values): for return_value in return_values: self.__then(Return(return_value)) return self def thenRaise(self, *exceptions): for exception in exceptions: self.__then(Raise(exception)) return self def __then(self, answer): if not self.answer: self.answer = CompositeAnswer(answer) self.invocation.stub_with(self.answer) else: self.answer.add(answer) return self class CompositeAnswer(object): def __init__(self, answer): self.answers = [answer] def add(self, answer): self.answers.insert(0, answer) def answer(self): if len(self.answers) > 1: a = self.answers.pop() else: a = self.answers[0] return a.answer() class Raise(object): def __init__(self, exception): self.exception = exception def answer(self): raise self.exception class Return(object): def __init__(self, return_value): self.return_value = return_value def answer(self): return self.return_value mockito-0.5.2/mockito/matchers.py0000644000076500001200000000432512231133437017604 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. '''Matchers for stubbing and verifications. Common matchers for use in stubbing and verifications. ''' __all__ = ['any', 'contains', 'times'] class Matcher: def matches(self, arg): pass class Any(Matcher): def __init__(self, wanted_type=None): self.wanted_type = wanted_type def matches(self, arg): if self.wanted_type: return isinstance(arg, self.wanted_type) else: return True def __repr__(self): return "" % self.wanted_type class Contains(Matcher): def __init__(self, sub): self.sub = sub def matches(self, arg): if not hasattr(arg, 'find'): return return self.sub and len(self.sub) > 0 and arg.find(self.sub) > -1 def __repr__(self): return "" % self.sub def any(wanted_type=None): """Matches any() argument OR any(SomeClass) argument Examples: when(mock).foo(any()).thenReturn(1) verify(mock).foo(any(int)) """ return Any(wanted_type) def contains(sub): return Contains(sub) def times(count): return count mockito-0.5.2/mockito/mock_registry.py0000644000076500001200000000317112231133437020655 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class MockRegistry: """Registers mock()s, ensures that we only have one mock() per mocked_obj, and iterates over them to unstub each stubbed method. """ def __init__(self): self.mocks = {} def register(self, mock): self.mocks[mock.mocked_obj] = mock def mock_for(self, cls): return self.mocks.get(cls, None) def unstub_all(self): for mock in self.mocks.itervalues(): mock.unstub() self.mocks.clear() mock_registry = MockRegistry()mockito-0.5.2/mockito/mocking.py0000644000076500001200000001043212231133437017421 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import inspect import invocation from mock_registry import mock_registry import warnings __all__ = ['mock', 'Mock'] class _Dummy(object): pass class TestDouble(object): pass class mock(TestDouble): def __init__(self, mocked_obj=None, strict=True): self.invocations = [] self.stubbed_invocations = [] self.original_methods = [] self.stubbing = None self.verification = None if mocked_obj is None: mocked_obj = _Dummy() strict = False self.mocked_obj = mocked_obj self.strict = strict self.stubbing_real_object = False mock_registry.register(self) def __getattr__(self, method_name): if self.stubbing is not None: return invocation.StubbedInvocation(self, method_name) if self.verification is not None: return invocation.VerifiableInvocation(self, method_name) return invocation.RememberedInvocation(self, method_name) def remember(self, invocation): self.invocations.insert(0, invocation) def finish_stubbing(self, stubbed_invocation): self.stubbed_invocations.insert(0, stubbed_invocation) self.stubbing = None def expect_stubbing(self): self.stubbing = True def pull_verification(self): v = self.verification self.verification = None return v def has_method(self, method_name): return hasattr(self.mocked_obj, method_name) def get_method(self, method_name): return self.mocked_obj.__dict__.get(method_name) def set_method(self, method_name, new_method): setattr(self.mocked_obj, method_name, new_method) def replace_method(self, method_name, original_method): def new_mocked_method(*args, **kwargs): # we throw away the first argument, if it's either self or cls if inspect.isclass(self.mocked_obj) and not isinstance(original_method, staticmethod): args = args[1:] call = self.__getattr__(method_name) # that is: invocation.RememberedInvocation(self, method_name) return call(*args, **kwargs) if isinstance(original_method, staticmethod): new_mocked_method = staticmethod(new_mocked_method) elif isinstance(original_method, classmethod): new_mocked_method = classmethod(new_mocked_method) self.set_method(method_name, new_mocked_method) def stub(self, method_name): original_method = self.get_method(method_name) original = (method_name, original_method) self.original_methods.append(original) # If we're trying to stub real object(not a generated mock), then we should patch object to use our mock method. # TODO: Polymorphism was invented long time ago. Refactor this. if self.stubbing_real_object: self.replace_method(method_name, original_method) def unstub(self): while self.original_methods: method_name, original_method = self.original_methods.pop() self.set_method(method_name, original_method) def Mock(*args, **kwargs): '''A ``mock``() alias. Alias for compatibility. To be removed in version 1.0. ''' warnings.warn("\n`Mock()` is deprecated, please use `mock()` (lower 'm') instead.", DeprecationWarning) return mock(*args, **kwargs) mockito-0.5.2/mockito/mockito.py0000644000076500001200000001023712231133437017442 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import verification from mocking import mock, TestDouble from mock_registry import mock_registry from verification import VerificationError class ArgumentError(Exception): pass def _multiple_arguments_in_use(*args): return len(filter(lambda x: x, args)) > 1 def _invalid_argument(value): return (value is not None and value < 1) or value == 0 def _invalid_between(between): if between is not None: start, end = between if start > end or start < 0: return True return False def verify(obj, times=1, atleast=None, atmost=None, between=None, inorder=False): if times < 0: raise ArgumentError("""'times' argument has invalid value. It should be at least 0. You wanted to set it to: %i""" % times) if _multiple_arguments_in_use(atleast, atmost, between): raise ArgumentError("""Sure you know what you are doing? You can set only one of the arguments: 'atleast', 'atmost' or 'between'.""") if _invalid_argument(atleast): raise ArgumentError("""'atleast' argument has invalid value. It should be at least 1. You wanted to set it to: %i""" % atleast) if _invalid_argument(atmost): raise ArgumentError("""'atmost' argument has invalid value. It should be at least 1. You wanted to set it to: %i""" % atmost) if _invalid_between(between): raise ArgumentError("""'between' argument has invalid value. It should consist of positive values with second number not greater than first e.g. [1, 4] or [0, 3] or [2, 2] You wanted to set it to: %s""" % between) if isinstance(obj, TestDouble): mocked_object = obj else: mocked_object = mock_registry.mock_for(obj) if atleast: mocked_object.verification = verification.AtLeast(atleast) elif atmost: mocked_object.verification = verification.AtMost(atmost) elif between: mocked_object.verification = verification.Between(*between) else: mocked_object.verification = verification.Times(times) if inorder: mocked_object.verification = verification.InOrder(mocked_object.verification) return mocked_object def when(obj, strict=True): if isinstance(obj, mock): theMock = obj else: theMock = mock_registry.mock_for(obj) if theMock is None: theMock = mock(obj, strict=strict) # If we call when on something that is not TestDouble that means we're trying to stub real object, # (class, module etc.). Not to be confused with generating stubs from real classes. theMock.stubbing_real_object = True theMock.expect_stubbing() return theMock def unstub(): """Unstubs all stubbed methods and functions""" mock_registry.unstub_all() def verifyNoMoreInteractions(*mocks): for mock in mocks: for i in mock.invocations: if not i.verified: raise VerificationError("\nUnwanted interaction: " + str(i)) def verifyZeroInteractions(*mocks): verifyNoMoreInteractions(*mocks) mockito-0.5.2/mockito/spying.py0000644000076500001200000000374412231133437017313 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. '''Spying on real objects.''' from invocation import RememberedProxyInvocation, VerifiableInvocation from mocking import TestDouble __author__ = "Serhiy Oplakanets " __all__ = ['spy'] def spy(original_object): return Spy(original_object) class Spy(TestDouble): strict = True # spies always have to check if method exists def __init__(self, original_object): self.original_object = original_object self.invocations = [] self.verification = None def __getattr__(self, name): if self.verification: return VerifiableInvocation(self, name) else: return RememberedProxyInvocation(self, name) def remember(self, invocation): self.invocations.insert(0, invocation) def pull_verification(self): v = self.verification self.verification = None return v mockito-0.5.2/mockito/verification.py0000644000076500001200000000745212231133437020464 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. __all__ = ['never', 'VerificationError'] class VerificationError(AssertionError): '''Indicates error during verification of invocations. Raised if verification fails. Error message contains the cause. ''' pass class AtLeast(object): def __init__(self, wanted_count): self.wanted_count = wanted_count def verify(self, invocation, actual_count): if actual_count < self.wanted_count: raise VerificationError("\nWanted at least: %i, actual times: %i" % (self.wanted_count, actual_count)) class AtMost(object): def __init__(self, wanted_count): self.wanted_count = wanted_count def verify(self, invocation, actual_count): if actual_count > self.wanted_count: raise VerificationError("\nWanted at most: %i, actual times: %i" % (self.wanted_count, actual_count)) class Between(object): def __init__(self, wanted_from, wanted_to): self.wanted_from = wanted_from self.wanted_to = wanted_to def verify(self, invocation, actual_count): if actual_count < self.wanted_from or actual_count > self.wanted_to: raise VerificationError("\nWanted between: [%i, %i], actual times: %i" % (self.wanted_from, self.wanted_to, actual_count)) class Times(object): def __init__(self, wanted_count): self.wanted_count = wanted_count def verify(self, invocation, actual_count): if actual_count == self.wanted_count: return if actual_count == 0: raise VerificationError("\nWanted but not invoked: %s" % (invocation)) else: if self.wanted_count == 0: raise VerificationError("\nUnwanted invocation of %s, times: %i" % (invocation, actual_count)) else: raise VerificationError("\nWanted times: %i, actual times: %i" % (self.wanted_count, actual_count)) class InOrder(object): ''' Verifies invocations in order. Verifies if invocation was in expected order, and if yes -- degrades to original Verifier (AtLeast, Times, Between, ...). ''' def __init__(self, original_verification): ''' @param original_verification: Original verifiaction to degrade to if order of invocation was ok. ''' self.original_verification = original_verification def verify(self, wanted_invocation, count): for invocation in reversed(wanted_invocation.mock.invocations): if not invocation.verified_inorder: if not wanted_invocation.matches(invocation): raise VerificationError("\nWanted %s to be invoked, got %s instead" % (wanted_invocation, invocation)) invocation.verified_inorder = True break # proceed with original verification self.original_verification.verify(wanted_invocation, count) never = 0 mockito-0.5.2/mockito.egg-info/0000755000076500001200000000000012231253716017115 5ustar justinhadmin00000000000000mockito-0.5.2/mockito.egg-info/dependency_links.txt0000644000076500001200000000000112231253716023163 0ustar justinhadmin00000000000000 mockito-0.5.2/mockito.egg-info/PKG-INFO0000644000076500001200000000115412231253716020213 0ustar justinhadmin00000000000000Metadata-Version: 1.0 Name: mockito Version: 0.5.2 Summary: Spying framework Home-page: http://code.google.com/p/mockito-python Author: Justin Hopper Author-email: mockito-python@googlegroups.com License: MIT Download-URL: http://code.google.com/p/mockito-python/downloads/list Description: Mockito is a spying framework based on Java library with the same name. Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Topic :: Software Development :: Testing Classifier: Programming Language :: Python :: 3 mockito-0.5.2/mockito.egg-info/SOURCES.txt0000644000076500001200000000156512231253716021010 0ustar justinhadmin00000000000000AUTHORS LICENSE MANIFEST.in README.rst distribute_setup.py setup.cfg setup.py mockito/__init__.py mockito/inorder.py mockito/invocation.py mockito/matchers.py mockito/mock_registry.py mockito/mocking.py mockito/mockito.py mockito/spying.py mockito/verification.py mockito.egg-info/PKG-INFO mockito.egg-info/SOURCES.txt mockito.egg-info/dependency_links.txt mockito.egg-info/top_level.txt mockito_test/__init__.py mockito_test/classmethods_test.py mockito_test/demo_test.py mockito_test/instancemethods_test.py mockito_test/matchers_test.py mockito_test/mockingexacttypes_test.py mockito_test/modulefunctions_test.py mockito_test/spying_test.py mockito_test/staticmethods_test.py mockito_test/stubbing_test.py mockito_test/test_base.py mockito_test/verification_errors_test.py mockito_test/verifications_test.py mockito_util/__init__.py mockito_util/test.py mockito_util/write_readme.pymockito-0.5.2/mockito.egg-info/top_level.txt0000644000076500001200000000006312231253716021646 0ustar justinhadmin00000000000000mockito_util distribute_setup mockito mockito_test mockito-0.5.2/mockito_test/0000755000076500001200000000000012231253716016462 5ustar justinhadmin00000000000000mockito-0.5.2/mockito_test/__init__.py0000644000076500001200000000221112231133437020564 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. mockito-0.5.2/mockito_test/classmethods_test.py0000644000076500001200000000607612231133013022560 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito import * class Dog: @classmethod def bark(cls): return "woof!" class Cat: @classmethod def meow(cls, m): return cls.__name__ + " " + str(m) class Lion(object): @classmethod def roar(cls): return "Rrrrr!" class ClassMethodsTest(TestBase): def tearDown(self): unstub() def testUnstubs(self): when(Dog).bark().thenReturn("miau!") unstub() self.assertEquals("woof!", Dog.bark()) #TODO decent test case please :) without testing irrelevant implementation details def testUnstubShouldPreserveMethodType(self): when(Dog).bark().thenReturn("miau!") unstub() self.assertTrue(isinstance(Dog.__dict__.get("bark"), classmethod)) def testStubs(self): self.assertEquals("woof!", Dog.bark()) when(Dog).bark().thenReturn("miau!") self.assertEquals("miau!", Dog.bark()) def testStubsClassesDerivedFromTheObjectClass(self): self.assertEquals("Rrrrr!", Lion.roar()) when(Lion).roar().thenReturn("miau!") self.assertEquals("miau!", Lion.roar()) def testVerifiesMultipleCallsOnClassmethod(self): when(Dog).bark().thenReturn("miau!") Dog.bark() Dog.bark() verify(Dog, times(2)).bark() def testFailsVerificationOfMultipleCallsOnClassmethod(self): when(Dog).bark().thenReturn("miau!") Dog.bark() self.assertRaises(VerificationError, verify(Dog, times(2)).bark) def testStubsAndVerifiesClassmethod(self): when(Dog).bark().thenReturn("miau!") self.assertEquals("miau!", Dog.bark()) verify(Dog).bark() def testPreservesClassArgumentAfterUnstub(self): self.assertEquals("Cat foo", Cat.meow("foo")) when(Cat).meow("foo").thenReturn("bar") self.assertEquals("bar", Cat.meow("foo")) unstub() self.assertEquals("Cat foo", Cat.meow("foo")) if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/demo_test.py0000644000076500001200000000402612231133437021016 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import mockito_util.write_readme #all below code will be merged with README #DELIMINATOR import unittest from mockito import mock, when, verify class DemoTest(unittest.TestCase): def testStubbing(self): # create a mock ourMock = mock() # stub it when(ourMock).getStuff("cool").thenReturn("cool stuff") # use the mock self.assertEqual("cool stuff", ourMock.getStuff("cool")) # what happens when you pass different argument? self.assertEqual(None, ourMock.getStuff("different argument")) def testVerification(self): # create a mock theMock = mock() # use the mock theMock.doStuff("cool") # verify the interactions. Method and parameters must match. Otherwise verification error. verify(theMock).doStuff("cool") #DELIMINATOR #all above code will be merged with README if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/instancemethods_test.py0000644000076500001200000000637212231133437023270 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito import * from mockito.invocation import InvocationError class Dog(object): def waggle(self): return "Wuff!" def bark(self, sound): return "%s!" % sound def do_default_bark(self): return self.bark('Wau') class InstanceMethodsTest(TestBase): def tearDown(self): unstub() def testUnstubAnInstanceMethod(self): original_method = Dog.waggle when(Dog).waggle().thenReturn('Nope!') unstub() rex = Dog() self.assertEquals('Wuff!', rex.waggle()) self.assertEquals(original_method, Dog.waggle) def testStubAnInstanceMethod(self): when(Dog).waggle().thenReturn('Boing!') rex = Dog() self.assertEquals('Boing!', rex.waggle()) def testStubsAnInstanceMethodWithAnArgument(self): when(Dog).bark('Miau').thenReturn('Wuff') rex = Dog() self.assertEquals('Wuff', rex.bark('Miau')) #self.assertEquals('Wuff', rex.bark('Wuff')) def testInvocateAStubbedMethodFromAnotherMethod(self): when(Dog).bark('Wau').thenReturn('Wuff') rex = Dog() self.assertEquals('Wuff', rex.do_default_bark()) verify(Dog).bark('Wau') def testYouCantStubAnUnknownMethodInStrictMode(self): try: when(Dog).barks('Wau').thenReturn('Wuff') self.fail('Stubbing an unknown method should have thrown a exception') except InvocationError: pass def testCallingAStubbedMethodWithUnexpectedArgumentsShouldReturnNone(self): when(Dog).bark('Miau').thenReturn('Wuff') rex = Dog() self.assertEquals(None, rex.bark('Shhh')) def testStubInstancesInsteadOfClasses(self): rex = Dog() when(rex).bark('Miau').thenReturn('Wuff') self.assertEquals('Wuff', rex.bark('Miau')) verify(rex, times=1).bark(any()) max = Dog() self.assertEquals('Miau!', max.bark('Miau')) if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/matchers_test.py0000644000076500001200000000405312231133437021700 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito import mock, verify, contains class MatchersTest(TestBase): def testVerifiesUsingContainsMatcher(self): ourMock = mock() ourMock.foo("foobar") verify(ourMock).foo(contains("foo")) verify(ourMock).foo(contains("bar")) class ContainsMatcherTest(TestBase): def testShouldSatisfiySubstringOfGivenString(self): self.assertTrue(contains("foo").matches("foobar")) def testShouldSatisfySameString(self): self.assertTrue(contains("foobar").matches("foobar")) def testShouldNotSatisfiyStringWhichIsNotSubstringOfGivenString(self): self.assertFalse(contains("barfoo").matches("foobar")) def testShouldNotSatisfiyEmptyString(self): self.assertFalse(contains("").matches("foobar")) def testShouldNotSatisfiyNone(self): self.assertFalse(contains(None).matches("foobar")) if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/mockingexacttypes_test.py0000644000076500001200000000341212231133437023631 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito.invocation import InvocationError from mockito import mock, when class Foo(object): def bar(self): pass class MockingExactTypesTest(TestBase): def testShouldScreamWhenUnknownMethodStubbed(self): ourMock = mock(Foo) when(ourMock).bar().thenReturn("grr"); try: when(ourMock).unknownMethod().thenReturn("grr"); self.fail() except InvocationError: pass def testShouldReturnNoneWhenCallingExistingButUnstubbedMethod(self): ourMock = mock(Foo) self.assertEquals(None, ourMock.bar()) if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/modulefunctions_test.py0000644000076500001200000000650512231133437023314 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito import * from mockito.invocation import InvocationError import os class ModuleFunctionsTest(TestBase): def tearDown(self): unstub() def testUnstubs(self): when(os.path).exists("test").thenReturn(True) unstub() self.assertEquals(False, os.path.exists("test")) def testStubs(self): when(os.path).exists("test").thenReturn(True) self.assertEquals(True, os.path.exists("test")) def testStubsConsecutiveCalls(self): when(os.path).exists("test").thenReturn(False).thenReturn(True) self.assertEquals(False, os.path.exists("test")) self.assertEquals(True, os.path.exists("test")) def testStubsMultipleClasses(self): when(os.path).exists("test").thenReturn(True) when(os.path).dirname(any(str)).thenReturn("mocked") self.assertEquals(True, os.path.exists("test")) self.assertEquals("mocked", os.path.dirname("whoah!")) def testVerifiesSuccesfully(self): when(os.path).exists("test").thenReturn(True) os.path.exists("test") verify(os.path).exists("test") def testFailsVerification(self): when(os.path).exists("test").thenReturn(True) self.assertRaises(VerificationError, verify(os.path).exists, "test") def testFailsOnNumberOfCalls(self): when(os.path).exists("test").thenReturn(True) os.path.exists("test") self.assertRaises(VerificationError, verify(os.path, times(2)).exists, "test") def testStubsTwiceAndUnstubs(self): when(os.path).exists("test").thenReturn(False) when(os.path).exists("test").thenReturn(True) self.assertEquals(True, os.path.exists("test")) unstub() self.assertEquals(False, os.path.exists("test")) def testStubsTwiceWithDifferentArguments(self): when(os.path).exists("Foo").thenReturn(False) when(os.path).exists("Bar").thenReturn(True) self.assertEquals(False, os.path.exists("Foo")) self.assertEquals(True, os.path.exists("Bar")) def testShouldThrowIfWeStubAFunctionNotDefinedInTheModule(self): self.assertRaises(InvocationError, lambda:when(os).walk_the_line().thenReturn(None)) if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/spying_test.py0000644000076500001200000000446712231133437021414 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #!/usr/bin/env python # coding: utf-8 from mockito_test.test_base import TestBase from mockito import spy, verify, VerificationError class Dummy: def foo(self): return "foo" def bar(self): raise TypeError def return_args(self, *args, **kwargs): return (args, kwargs) class SpyingTest(TestBase): def testPreservesReturnValues(self): dummy = Dummy() spiedDummy = spy(dummy) self.assertEquals(dummy.foo(), spiedDummy.foo()) def testPreservesSideEffects(self): dummy = spy(Dummy()) self.assertRaises(TypeError, dummy.bar) def testPassesArgumentsCorrectly(self): dummy = spy(Dummy()) self.assertEquals((('foo', 1), {'bar': 'baz'}), dummy.return_args('foo', 1, bar='baz')) def testIsVerifiable(self): dummy = spy(Dummy()) dummy.foo() verify(dummy).foo() self.assertRaises(VerificationError, verify(dummy).bar) def testRaisesAttributeErrorIfNoSuchMethod(self): dummy = spy(Dummy()) try: dummy.lol() self.fail("Should fail if no such method.") except AttributeError, e: self.assertEquals("You tried to call method 'lol' which 'Dummy' instance does not have.", str(e)) mockito-0.5.2/mockito_test/staticmethods_test.py0000644000076500001200000001052312231133437022744 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito import * class Dog: @staticmethod def bark(): return "woof" @staticmethod def barkHardly(*args): return "woof woof" class Cat: @staticmethod def meow(): return "miau" class StaticMethodsTest(TestBase): def tearDown(self): unstub() def testUnstubs(self): when(Dog).bark().thenReturn("miau") unstub() self.assertEquals("woof", Dog.bark()) #TODO decent test case please :) without testing irrelevant implementation details def testUnstubShouldPreserveMethodType(self): when(Dog).bark().thenReturn("miau!") unstub() self.assertTrue(isinstance(Dog.__dict__.get("bark"), staticmethod)) def testStubs(self): self.assertEquals("woof", Dog.bark()) when(Dog).bark().thenReturn("miau") self.assertEquals("miau", Dog.bark()) def testStubsConsecutiveCalls(self): when(Dog).bark().thenReturn(1).thenReturn(2) self.assertEquals(1, Dog.bark()) self.assertEquals(2, Dog.bark()) self.assertEquals(2, Dog.bark()) def testStubsWithArgs(self): self.assertEquals("woof woof", Dog.barkHardly(1, 2)) when(Dog).barkHardly(1, 2).thenReturn("miau") self.assertEquals("miau", Dog.barkHardly(1, 2)) def testStubsButDoesNotMachArguments(self): self.assertEquals("woof woof", Dog.barkHardly(1, "anything")) when(Dog, strict=False).barkHardly(1, 2).thenReturn("miau") self.assertEquals(None, Dog.barkHardly(1)) def testStubsMultipleClasses(self): when(Dog).barkHardly(1, 2).thenReturn(1) when(Dog).bark().thenReturn(2) when(Cat).meow().thenReturn(3) self.assertEquals(1, Dog.barkHardly(1, 2)) self.assertEquals(2, Dog.bark()) self.assertEquals(3, Cat.meow()) unstub() self.assertEquals("woof", Dog.bark()) self.assertEquals("miau", Cat.meow()) def testVerifiesSuccesfully(self): when(Dog).bark().thenReturn("boo") Dog.bark() verify(Dog).bark() def testVerifiesWithArguments(self): when(Dog).barkHardly(1, 2).thenReturn("boo") Dog.barkHardly(1, 2) verify(Dog).barkHardly(1, any()) def testFailsVerification(self): when(Dog).bark().thenReturn("boo") Dog.bark() self.assertRaises(VerificationError, verify(Dog).barkHardly, (1,2)) def testFailsOnInvalidArguments(self): when(Dog).bark().thenReturn("boo") Dog.barkHardly(1, 2) self.assertRaises(VerificationError, verify(Dog).barkHardly, (1,20)) def testFailsOnNumberOfCalls(self): when(Dog).bark().thenReturn("boo") Dog.bark() self.assertRaises(VerificationError, verify(Dog, times(2)).bark) def testStubsAndVerifies(self): when(Dog).bark().thenReturn("boo") self.assertEquals("boo", Dog.bark()) verify(Dog).bark() def testStubsTwiceAndUnstubs(self): when(Dog).bark().thenReturn(1) when(Dog).bark().thenReturn(2) self.assertEquals(2, Dog.bark()) unstub() self.assertEquals("woof", Dog.bark()) def testDoesNotVerifyStubbedCalls(self): when(Dog).bark().thenReturn(1) verify(Dog, times=0).bark() if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/stubbing_test.py0000644000076500001200000002203312231133437021705 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito import mock, when, verify, times, any class StubbingTest(TestBase): def testStubsWithReturnValue(self): theMock = mock() when(theMock).getStuff().thenReturn("foo") when(theMock).getMoreStuff(1, 2).thenReturn(10) self.assertEquals("foo", theMock.getStuff()) self.assertEquals(10, theMock.getMoreStuff(1, 2)) self.assertEquals(None, theMock.getMoreStuff(1, 3)) def testStubsWhenNoArgsGiven(self): theMock = mock() when(theMock).getStuff().thenReturn("foo") when(theMock).getWidget().thenReturn("bar") self.assertEquals("foo", theMock.getStuff()) self.assertEquals("bar", theMock.getWidget()) def testStubsConsecutivelyWhenNoArgsGiven(self): theMock = mock() when(theMock).getStuff().thenReturn("foo").thenReturn("bar") when(theMock).getWidget().thenReturn("baz").thenReturn("baz2") self.assertEquals("foo", theMock.getStuff()) self.assertEquals("bar", theMock.getStuff()) self.assertEquals("bar", theMock.getStuff()) self.assertEquals("baz", theMock.getWidget()) self.assertEquals("baz2", theMock.getWidget()) self.assertEquals("baz2", theMock.getWidget()) def testStubsWithException(self): theMock = mock() when(theMock).someMethod().thenRaise(Exception("foo")) self.assertRaisesMessage("foo", theMock.someMethod) def testStubsAndVerifies(self): theMock = mock() when(theMock).foo().thenReturn("foo") self.assertEquals("foo", theMock.foo()) verify(theMock).foo() def testStubsVerifiesAndStubsAgain(self): theMock = mock() when(theMock).foo().thenReturn("foo") self.assertEquals("foo", theMock.foo()) verify(theMock).foo() when(theMock).foo().thenReturn("next foo") self.assertEquals("next foo", theMock.foo()) verify(theMock, times(2)).foo() def testOverridesStubbing(self): theMock = mock() when(theMock).foo().thenReturn("foo") when(theMock).foo().thenReturn("bar") self.assertEquals("bar", theMock.foo()) def testStubsAndInvokesTwiceAndVerifies(self): theMock = mock() when(theMock).foo().thenReturn("foo") self.assertEquals("foo", theMock.foo()) self.assertEquals("foo", theMock.foo()) verify(theMock, times(2)).foo() def testStubsAndReturnValuesForMethodWithSameNameAndDifferentArguments(self): theMock = mock() when(theMock).getStuff(1).thenReturn("foo") when(theMock).getStuff(1, 2).thenReturn("bar") self.assertEquals("foo", theMock.getStuff(1)) self.assertEquals("bar", theMock.getStuff(1, 2)) def testStubsAndReturnValuesForMethodWithSameNameAndDifferentNamedArguments(self): repo = mock() when(repo).findby(id=6).thenReturn("John May") when(repo).findby(name="John").thenReturn(["John May", "John Smith"]) self.assertEquals("John May", repo.findby(id=6)) self.assertEquals(["John May", "John Smith"], repo.findby(name="John")) def testStubsForMethodWithSameNameAndNamedArgumentsInArbitraryOrder(self): theMock = mock() when(theMock).foo(first=1, second=2, third=3).thenReturn(True) self.assertEquals(True, theMock.foo(third=3, first=1, second=2)) def testStubsMethodWithSameNameAndMixedArguments(self): repo = mock() when(repo).findby(1).thenReturn("John May") when(repo).findby(1, active_only=True).thenReturn(None) when(repo).findby(name="Sarah").thenReturn(["Sarah Connor"]) when(repo).findby(name="Sarah", active_only=True).thenReturn([]) self.assertEquals("John May", repo.findby(1)) self.assertEquals(None, repo.findby(1, active_only=True)) self.assertEquals(["Sarah Connor"], repo.findby(name="Sarah")) self.assertEquals([], repo.findby(name="Sarah", active_only=True)) def testStubsWithChainedReturnValues(self): theMock = mock() when(theMock).getStuff().thenReturn("foo").thenReturn("bar").thenReturn("foobar") self.assertEquals("foo", theMock.getStuff()) self.assertEquals("bar", theMock.getStuff()) self.assertEquals("foobar", theMock.getStuff()) def testStubsWithChainedReturnValuesAndException(self): theMock = mock() when(theMock).getStuff().thenReturn("foo").thenReturn("bar").thenRaise(Exception("foobar")) self.assertEquals("foo", theMock.getStuff()) self.assertEquals("bar", theMock.getStuff()) self.assertRaisesMessage("foobar", theMock.getStuff) def testStubsWithChainedExceptionAndReturnValue(self): theMock = mock() when(theMock).getStuff().thenRaise(Exception("foo")).thenReturn("bar") self.assertRaisesMessage("foo", theMock.getStuff) self.assertEquals("bar", theMock.getStuff()) def testStubsWithChainedExceptions(self): theMock = mock() when(theMock).getStuff().thenRaise(Exception("foo")).thenRaise(Exception("bar")) self.assertRaisesMessage("foo", theMock.getStuff) self.assertRaisesMessage("bar", theMock.getStuff) def testStubsWithReturnValueBeingException(self): theMock = mock() exception = Exception("foo") when(theMock).getStuff().thenReturn(exception) self.assertEquals(exception, theMock.getStuff()) def testLastStubbingWins(self): theMock = mock() when(theMock).foo().thenReturn(1) when(theMock).foo().thenReturn(2) self.assertEquals(2, theMock.foo()) def testStubbingOverrides(self): theMock = mock() when(theMock).foo().thenReturn(1) when(theMock).foo().thenReturn(2).thenReturn(3) self.assertEquals(2, theMock.foo()) self.assertEquals(3, theMock.foo()) self.assertEquals(3, theMock.foo()) def testStubsWithMatchers(self): theMock = mock() when(theMock).foo(any()).thenReturn(1) self.assertEquals(1, theMock.foo(1)) self.assertEquals(1, theMock.foo(100)) def testStubbingOverrides2(self): theMock = mock() when(theMock).foo(any()).thenReturn(1) when(theMock).foo("oh").thenReturn(2) self.assertEquals(2, theMock.foo("oh")) self.assertEquals(1, theMock.foo("xxx")) def testDoesNotVerifyStubbedCalls(self): theMock = mock() when(theMock).foo().thenReturn(1) verify(theMock, times=0).foo() def testStubsWithMultipleReturnValues(self): theMock = mock() when(theMock).getStuff().thenReturn("foo", "bar", "foobar") self.assertEquals("foo", theMock.getStuff()) self.assertEquals("bar", theMock.getStuff()) self.assertEquals("foobar", theMock.getStuff()) def testStubsWithChainedMultipleReturnValues(self): theMock = mock() when(theMock).getStuff().thenReturn("foo", "bar").thenReturn("foobar") self.assertEquals("foo", theMock.getStuff()) self.assertEquals("bar", theMock.getStuff()) self.assertEquals("foobar", theMock.getStuff()) def testStubsWithMultipleExceptions(self): theMock = mock() when(theMock).getStuff().thenRaise(Exception("foo"), Exception("bar")) self.assertRaisesMessage("foo", theMock.getStuff) self.assertRaisesMessage("bar", theMock.getStuff) def testStubsWithMultipleChainedExceptions(self): theMock = mock() when(theMock).getStuff().thenRaise(Exception("foo"), Exception("bar")).thenRaise(Exception("foobar")) self.assertRaisesMessage("foo", theMock.getStuff) self.assertRaisesMessage("bar", theMock.getStuff) self.assertRaisesMessage("foobar", theMock.getStuff) def testLeavesOriginalMethodUntouchedWhenCreatingStubFromRealClass(self): class Person: def get_name(self): return "original name" # given person = Person() mockPerson = mock(Person) # when when(mockPerson).get_name().thenReturn("stubbed name") # then self.assertEquals("stubbed name", mockPerson.get_name()) self.assertEquals("original name", person.get_name(), 'Original method should not be replaced.') # TODO: verify after stubbing and vice versa if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/test_base.py0000644000076500001200000000334312231133437021005 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import unittest class TestBase(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) def assertRaisesMessage(self, message, callable, *params): try: if (params): callable(params) else: callable() self.fail('Exception with message "%s" expected, but never raised' % (message)) except Exception, e: # TODO: self.fail() raises AssertionError which is caught here and error message becomes hardly understadable self.assertEquals(message, str(e)) main = unittest.main mockito-0.5.2/mockito_test/verification_errors_test.py0000644000076500001200000000646512231133437024161 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import * from mockito import mock, when, verify, VerificationError, verifyNoMoreInteractions from mockito.verification import never class VerificationErrorsTest(TestBase): def testPrintsNicely(self): theMock = mock() try: verify(theMock).foo() except VerificationError, e: self.assertEquals("\nWanted but not invoked: foo()", str(e)) def testPrintsNicelyOneArgument(self): theMock = mock() try: verify(theMock).foo("bar") except VerificationError, e: self.assertEquals("\nWanted but not invoked: foo('bar')", str(e)) def testPrintsNicelyArguments(self): theMock = mock() try: verify(theMock).foo(1, 2) except VerificationError, e: self.assertEquals("\nWanted but not invoked: foo(1, 2)", str(e)) def testPrintsNicelyStringArguments(self): theMock = mock() try: verify(theMock).foo(1, 'foo') except VerificationError, e: self.assertEquals("\nWanted but not invoked: foo(1, 'foo')", str(e)) def testPrintsOutThatTheActualAndExpectedInvocationCountDiffers(self): theMock = mock() when(theMock).foo().thenReturn(0) theMock.foo() theMock.foo() try: verify(theMock).foo() except VerificationError, e: self.assertEquals("\nWanted times: 1, actual times: 2", str(e)) # TODO: implement def disabled_PrintsNicelyWhenArgumentsDifferent(self): theMock = mock() theMock.foo('foo', 1) try: verify(theMock).foo(1, 'foo') except VerificationError, e: self.assertEquals( """Arguments are different. Wanted: foo(1, 'foo') Actual: foo('foo', 1)""", str(e)) def testPrintsUnwantedInteraction(self): theMock = mock() theMock.foo(1, 'foo') try: verifyNoMoreInteractions(theMock) except VerificationError, e: self.assertEquals("\nUnwanted interaction: foo(1, 'foo')", str(e)) def testPrintsNeverWantedInteractionsNicely(self): theMock = mock() theMock.foo() self.assertRaisesMessage("\nUnwanted invocation of foo(), times: 1", verify(theMock, never).foo) if __name__ == '__main__': unittest.main() mockito-0.5.2/mockito_test/verifications_test.py0000644000076500001200000002272012231133437022740 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from test_base import TestBase, main from mockito import mock, verify, inorder, VerificationError , ArgumentError, verifyNoMoreInteractions, verifyZeroInteractions, any from mockito.verification import never class VerificationTestBase(TestBase): def __init__(self, verification_function, *args, **kwargs): self.verification_function = verification_function TestBase.__init__(self, *args, **kwargs) def setUp(self): self.mock = mock() def testVerifies(self): self.mock.foo() self.mock.someOtherMethod(1, "foo", "bar") self.verification_function(self.mock).foo() self.verification_function(self.mock).someOtherMethod(1, "foo", "bar") def testVerifiesWhenMethodIsUsingKeywordArguments(self): self.mock.foo() self.mock.someOtherMethod(1, fooarg="foo", bararg="bar") self.verification_function(self.mock).foo() self.verification_function(self.mock).someOtherMethod(1, bararg="bar", fooarg="foo") def testVerifiesDetectsNamedArguments(self): self.mock.foo(fooarg="foo", bararg="bar") self.verification_function(self.mock).foo(bararg="bar", fooarg="foo") try: self.verification_function(self.mock).foo(bararg="foo", fooarg="bar") self.fail(); except VerificationError: pass def testFailsVerification(self): self.mock.foo("boo") self.assertRaises(VerificationError, self.verification_function(self.mock).foo, "not boo") def testVerifiesAnyTimes(self): self.mock = mock() self.mock.foo() self.verification_function(self.mock).foo() self.verification_function(self.mock).foo() self.verification_function(self.mock).foo() def testVerifiesMultipleCalls(self): self.mock = mock() self.mock.foo() self.mock.foo() self.mock.foo() self.verification_function(self.mock, times=3).foo() def testFailsVerificationOfMultipleCalls(self): self.mock = mock() self.mock.foo() self.mock.foo() self.mock.foo() self.assertRaises(VerificationError, self.verification_function(self.mock, times=2).foo) def testVerifiesUsingAnyMatcher(self): self.mock.foo(1, "bar") self.verification_function(self.mock).foo(1, any()) self.verification_function(self.mock).foo(any(), "bar") self.verification_function(self.mock).foo(any(), any()) def testVerifiesUsingAnyIntMatcher(self): self.mock.foo(1, "bar") self.verification_function(self.mock).foo(any(int), "bar") def testFailsVerificationUsingAnyIntMatcher(self): self.mock.foo(1, "bar") self.assertRaises(VerificationError, self.verification_function(self.mock).foo, 1, any(int)) self.assertRaises(VerificationError, self.verification_function(self.mock).foo, any(int)) def testNumberOfTimesDefinedDirectlyInVerify(self): self.mock.foo("bar") self.verification_function(self.mock, times=1).foo("bar") def testFailsWhenTimesIsLessThanZero(self): self.assertRaises(ArgumentError, self.verification_function, None, -1) def testVerifiesAtLeastTwoWhenMethodInvokedTwice(self): self.mock.foo() self.mock.foo() self.verification_function(self.mock, atleast=2).foo() def testVerifiesAtLeastTwoWhenMethodInvokedFourTimes(self): self.mock.foo() self.mock.foo() self.mock.foo() self.mock.foo() self.verification_function(self.mock, atleast=2).foo() def testFailsWhenMethodInvokedOnceForAtLeastTwoVerification(self): self.mock.foo() self.assertRaises(VerificationError, self.verification_function(self.mock, atleast=2).foo) def testVerifiesAtMostTwoWhenMethodInvokedTwice(self): self.mock.foo() self.mock.foo() self.verification_function(self.mock, atmost=2).foo() def testVerifiesAtMostTwoWhenMethodInvokedOnce(self): self.mock.foo() self.verification_function(self.mock, atmost=2).foo() def testFailsWhenMethodInvokedFourTimesForAtMostTwoVerification(self): self.mock.foo() self.mock.foo() self.mock.foo() self.mock.foo() self.assertRaises(VerificationError, self.verification_function(self.mock, atmost=2).foo) def testVerifiesBetween(self): self.mock.foo() self.mock.foo() self.verification_function(self.mock, between=[1, 2]).foo() self.verification_function(self.mock, between=[2, 3]).foo() self.verification_function(self.mock, between=[1, 5]).foo() self.verification_function(self.mock, between=[2, 2]).foo() def testFailsVerificationWithBetween(self): self.mock.foo() self.mock.foo() self.mock.foo() self.assertRaises(VerificationError, self.verification_function(self.mock, between=[1, 2]).foo) self.assertRaises(VerificationError, self.verification_function(self.mock, between=[4, 9]).foo) def testFailsAtMostAtLeastAndBetweenVerificationWithWrongArguments(self): self.assertRaises(ArgumentError, self.verification_function, self.mock, atleast=0) self.assertRaises(ArgumentError, self.verification_function, self.mock, atleast=-5) self.assertRaises(ArgumentError, self.verification_function, self.mock, atmost=0) self.assertRaises(ArgumentError, self.verification_function, self.mock, atmost=-5) self.assertRaises(ArgumentError, self.verification_function, self.mock, between=[5, 1]) self.assertRaises(ArgumentError, self.verification_function, self.mock, between=[-1, 1]) self.assertRaises(ArgumentError, self.verification_function, self.mock, atleast=5, atmost=5) self.assertRaises(ArgumentError, self.verification_function, self.mock, atleast=5, between=[1, 2]) self.assertRaises(ArgumentError, self.verification_function, self.mock, atmost=5, between=[1, 2]) self.assertRaises(ArgumentError, self.verification_function, self.mock, atleast=5, atmost=5, between=[1, 2]) def runTest(self): pass class VerifyTest(VerificationTestBase): def __init__(self, *args, **kwargs): VerificationTestBase.__init__(self, verify, *args, **kwargs) def testVerifyNeverCalled(self): verify(self.mock, never).someMethod() def testVerifyNeverCalledRaisesError(self): self.mock.foo() self.assertRaises(VerificationError, verify(self.mock, never).foo) class InorderVerifyTest(VerificationTestBase): def __init__(self, *args, **kwargs): VerificationTestBase.__init__(self, inorder.verify, *args, **kwargs) def setUp(self): self.mock = mock() def testPassesIfOneIteraction(self): self.mock.first() inorder.verify(self.mock).first() def testPassesIfMultipleInteractions(self): self.mock.first() self.mock.second() self.mock.third() inorder.verify(self.mock).first() inorder.verify(self.mock).second() inorder.verify(self.mock).third() def testFailsIfNoInteractions(self): self.assertRaises(VerificationError, inorder.verify(self.mock).first) def testFailsIfWrongOrderOfInteractions(self): self.mock.first() self.mock.second() self.assertRaises(VerificationError, inorder.verify(self.mock).second) def testErrorMessage(self): self.mock.second() self.mock.first() self.assertRaisesMessage("\nWanted first() to be invoked, got second() instead", inorder.verify(self.mock).first) def testPassesMixedVerifications(self): self.mock.first() self.mock.second() verify(self.mock).first() verify(self.mock).second() inorder.verify(self.mock).first() inorder.verify(self.mock).second() def testFailsMixedVerifications(self): self.mock.second() self.mock.first() # first - normal verifications, they should pass verify(self.mock).first() verify(self.mock).second() # but, inorder verification should fail self.assertRaises(VerificationError, inorder.verify(self.mock).first) class VerifyNoMoreInteractionsTest(TestBase): def testVerifies(self): mockOne, mockTwo = mock(), mock() mockOne.foo() mockTwo.bar() verify(mockOne).foo() verify(mockTwo).bar() verifyNoMoreInteractions(mockOne, mockTwo) def testFails(self): theMock = mock() theMock.foo() self.assertRaises(VerificationError, verifyNoMoreInteractions, theMock) class VerifyZeroInteractionsTest(TestBase): def testVerifies(self): theMock = mock() verifyZeroInteractions(theMock) theMock.foo() self.assertRaises(VerificationError, verifyNoMoreInteractions, theMock) if __name__ == '__main__': main() mockito-0.5.2/mockito_util/0000755000076500001200000000000012231253716016460 5ustar justinhadmin00000000000000mockito-0.5.2/mockito_util/__init__.py0000644000076500001200000000221112231133437020562 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. mockito-0.5.2/mockito_util/test.py0000644000076500001200000000370312231133437020011 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from unittest import TestLoader as BaseTestLoader, TestSuite import sys class TestLoader(BaseTestLoader): def loadTestsFromName(self, name, module=None): suite = TestSuite() for test in findTests(name): sys.path.insert(0, name) # python3 compatibility suite.addTests(super(TestLoader, self).loadTestsFromName(test)) del sys.path[0] # python3 compatibility return suite def loadTestsFromNames(self, names, module=None): suite = TestSuite() for name in names: suite.addTests(self.loadTestsFromName(name)) return suite def findTests(dir): import os, re pattern = re.compile('([a-z]+_)+test\.py$') for fileName in os.listdir(dir): if pattern.match(fileName): yield os.path.join(dir, fileName).replace('.py', '').replace(os.sep, '.') __all__ = [TestLoader] mockito-0.5.2/mockito_util/write_readme.py0000644000076500001200000000336312231134541021500 0ustar justinhadmin00000000000000# Copyright (c) 2008-2013 Szczepan Faber, Serhiy Oplakanets, Herr Kaste # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import os import re def openFile(f, m='r'): if (os.path.exists(f)): return open(f, m) else: return open('../' + f, m) demo_test = ' '.join(openFile('mockito_test/demo_test.py').readlines()) demo_test = demo_test.split('#DELIMINATOR')[1] readme_before = ''.join(openFile('README.rst').readlines()) token = 'Basic usage:' readme_after = re.compile(token + '.*', re.S).sub(token + '\n' + demo_test, readme_before) if (readme_before != readme_after): readme_file = openFile('README.rst', 'w') readme_file.write(readme_after) print "README updated" else: print "README update not required" mockito-0.5.2/PKG-INFO0000644000076500001200000000115412231253716015054 0ustar justinhadmin00000000000000Metadata-Version: 1.0 Name: mockito Version: 0.5.2 Summary: Spying framework Home-page: http://code.google.com/p/mockito-python Author: Justin Hopper Author-email: mockito-python@googlegroups.com License: MIT Download-URL: http://code.google.com/p/mockito-python/downloads/list Description: Mockito is a spying framework based on Java library with the same name. Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Topic :: Software Development :: Testing Classifier: Programming Language :: Python :: 3 mockito-0.5.2/README.rst0000644000076500001200000000256412231124160015442 0ustar justinhadmin00000000000000Mockito is a spying framework based on Java library with the same name. 1. To install: $ python setup.py install 2. To run all tests: $ python setup.py test 3. For more info, see: __ http://code.google.com/p/mockito-python/ Feel free to contribute more documentation or feedback! 4. Our user and developer discussion group is: __ http://groups.google.com/group/mockito-python 5. Mockito is licensed under the MIT license 6. Library was tested with the following Python versions: Python 2.4.6 Python 2.5.4 Python 2.6.1 Python 2.7 Python 3.1.2 7. (Generated from mockito_demo_test.py) Basic usage: import unittest from mockito import mock, when, verify class DemoTest(unittest.TestCase): def testStubbing(self): # create a mock ourMock = mock() # stub it when(ourMock).getStuff("cool").thenReturn("cool stuff") # use the mock self.assertEqual("cool stuff", ourMock.getStuff("cool")) # what happens when you pass different argument? self.assertEqual(None, ourMock.getStuff("different argument")) def testVerification(self): # create a mock theMock = mock() # use the mock theMock.doStuff("cool") # verify the interactions. Method and parameters must match. Otherwise verification error. verify(theMock).doStuff("cool") mockito-0.5.2/setup.cfg0000644000076500001200000000016112231253716015575 0ustar justinhadmin00000000000000[nosetests] where = mockito_test detailed-errors = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 mockito-0.5.2/setup.py0000755000076500001200000000225012231124407015464 0ustar justinhadmin00000000000000#!/usr/bin/env python # coding: utf-8 from distribute_setup import use_setuptools use_setuptools() try: from setuptools import setup except ImportError: from distutils.core import setup import sys extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True setup(name='mockito', version='0.5.2', packages=['mockito', 'mockito_test', 'mockito_util'], url='http://code.google.com/p/mockito-python', download_url='http://code.google.com/p/mockito-python/downloads/list', maintainer='Justin Hopper', maintainer_email='mockito-python@googlegroups.com', license='MIT', description='Spying framework', long_description='Mockito is a spying framework based on Java library with the same name.', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Testing', 'Programming Language :: Python :: 3' ], test_suite='nose.collector', py_modules=['distribute_setup'], setup_requires=['nose'], **extra)