### Basic Mock Setup and Stubbing with Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/index.md Create mocks and stub return values using when().thenReturn() syntax. Demonstrates mocking os.path.exists and requests.get with custom response objects. Use unstub() to clean up after tests. ```python from mockito import when, mock, unstub when(os.path).exists('/foo').thenReturn(True) # or: import requests # the famous library # you actually want to return a Response-like obj, we'll fake it response = mock({'status_code': 200, 'text': 'Ok'}) when(requests).get(...).thenReturn(response) # use it requests.get('http://google.com/') # clean up unstub() ``` -------------------------------- ### Running tests with uv Source: https://github.com/kaste/mockito-python/blob/master/README.rst This snippet shows an example of how to run tests using `uv` for a Python project. It assumes the project has been cloned and dependencies synchronized with `uv sync`. ```bash uv run pytest ``` -------------------------------- ### Install Mockito Python Package Source: https://github.com/kaste/mockito-python/blob/master/docs/index.md Install the mockito package using pip package manager. For pytest users, consider installing the pytest-mockito plugin for enhanced integration. ```python pip install mockito ``` -------------------------------- ### Setup Mock Expectations with String Path in Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Use the `expect()` function with a string module path as the first argument to setup expectations for imported modules or objects. This example demonstrates expecting the `os.path.exists()` method to be called twice and return True. ```python expect('os.path', times=2).exists(...).thenReturn(True) ``` -------------------------------- ### Mocking Context Managers for Requests Session Source: https://github.com/kaste/mockito-python/blob/master/docs/recipes.md This example shows how to test a function `fetch_2` that uses `requests.Session` as a context manager. It mocks both the `__enter__` and `__exit__` magic methods of the session object, along with the `get` method, to control its behavior within the `with` statement. ```python import requests def fetch_2(url): with requests.Session() as session: return session.get(url) ``` ```python from mockito import when, mock, args def test_fetch_with(unstub): url = 'http://example.com/' response = mock({'text': 'Ok'}, spec=requests.Response) session = mock(requests.Session) when(session).get(url).thenReturn(response) when(session).__enter__().thenReturn(session) # <= when(session).__exit__(*args) # <= when(requests).Session().thenReturn(session) res = fetch_2(url) assert res.text == 'Ok' ``` -------------------------------- ### Preconfigure Mocks with Initial Values - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Demonstrates how to initialize mocks with preconfigured dictionary values, including specced mocks that verify isinstance checks. This allows setup of mock state at creation time, with optional spec parameter for type safety. ```python mock({'text': 'OK'}) mock({'text': 'OK'}, spec=requests.Response) ``` -------------------------------- ### Verifying Function Calls with spy2 Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This example shows how to use `mockito.spy2` in conjunction with `mockito.verify` to check if a function was called with specific arguments and a certain number of times. This is useful for testing interactions with the original implementation of a function. ```python from mockito import spy2, verify spy2(os.path.exists) # now do some stuff do_stuff() # then verify the we asked for the cache exactly once verify(os.path, times=1).exists("cache/.foo") ``` -------------------------------- ### Using Pytest Fixture for Unstubbing Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This example shows how to create a pytest fixture to automatically handle `mockito.unstub()` calls. The fixture yields control to the test and then calls `unstub()` in its teardown phase, ensuring patches are cleaned up after each test that uses the fixture. ```python # conftest.py import pytest @pytest.fixture def unstub(): from mockito import unstub yield unstub() # my_test.py import pytest pytestmark = pytest.mark.usefixtures("unstub") ``` -------------------------------- ### Verifying Mocked Instance Method Calls Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This example shows how to use `mockito.verify` to check if a method on a mocked instance was called a specific number of times. This is useful for asserting that interactions with a mocked object occurred as expected during test execution. ```python from mockito import mockito, when, verify class Dog(object): def bark(self): return 'Wuff' # once again rex = Dog() when(rex).bark().thenReturn('Grrrr') rex.bark() rex.bark() # `times` defaults to 1 verify(rex, times=2).bark() ``` -------------------------------- ### Using spy2 to Call Original Implementation Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This example demonstrates using `mockito.spy2` to wrap a function, allowing it to call the original implementation while still enabling stubbing for specific calls. This is useful when most of a function's behavior should be preserved, but specific cases need to be altered. ```python from mockito import spy2, when spy2(os.path.exists) when(os.path).exists('.flake8').thenReturn(False) ``` -------------------------------- ### Mocking External Library Requests Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This example shows how to mock the `requests.get` function from the `requests` library to test a function that makes HTTP requests. It creates a mock response object with specific `status_code` and `text` attributes, then uses `mockito.when` to control the return value of `requests.get`. ```python import requests from mockito import mock, when def get_text(url): res = requests.get(url) if 200 <= res.status_code < 300: return res.text return None # setup response = mock({ 'status_code': 200, 'text': 'Ok' }, spec=requests.Response) when(requests).get('https://example.com/api').thenReturn(response) # run assert get_text('https://example.com/api') == 'Ok' ``` -------------------------------- ### Mockito Strictness: Handling Non-existent Methods Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This snippet highlights mockito's strictness by showing how attempting to mock a method that does not exist on an object will raise an error. This helps catch potential typos or incorrect assumptions about the object's interface during test setup. ```python from mockito import when class Dog(object): def bark(self): return 'Wuff' rex = Dog() # this will fail because `Dog` has no method named `waggle` when(rex).waggle().thenReturn('Nope') ``` -------------------------------- ### Stubbing os.path.exists with Wildcard Arguments Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This example shows how to stub `os.path.exists` to return a value regardless of the arguments provided. It uses the wildcard `...` in the `when` call. This is helpful when the specific arguments to a function do not matter for the test's outcome. ```python from mockito import when when(os.path).exists(...).thenReturn(True) # now, obviously, you get the same answer, regardless of the arguments os.path.exists('FooBar') # => True os.path.exists('BarFoo') # => True ``` -------------------------------- ### Setup expected call counts with expect() in mockito-python Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md Stub function calls while defining expected invocation counts upfront. Accepts times, atleast, atmost, and between parameters. Throws at call time when actual invocations exceed expected count. Requires verifyExpectedInteractions() to ensure all expectations were met. ```python # Given dog is an instance of a Dog expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') # dog.bark('Wuff') # will throw: too many invocations # Verify all expectations were met verifyExpectedInteractions() ``` -------------------------------- ### Call Original Implementation with thenCallOriginalImplementation in Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Use `thenCallOriginalImplementation()` to invoke the real implementation of a stubbed method while maintaining the ability to mock other calls. This example shows mocking `os.path.exists()` to use the real filesystem but fake a specific file. ```python # Let `os.path.exists` use the real filesystem (often needed when # the testing framework needs itself a working `os.path.exists` # implementation) *but* fake a `.flake8` file. when(os.path).exists(...).thenCallOriginalImplementation() when(os.path).exists('.flake8').thenReturn(True) ``` -------------------------------- ### Value Comparison Matchers (eq, gt, gte, lt, lte, neq) Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Provides examples of matchers used for direct value comparison: `eq` for equality, `gt` for greater than, `gte` for greater than or equal to, `lt` for less than, `lte` for less than or equal to, and `neq` for not equal to. ```python when(mock).process(eq(10)) when(mock).process(gt(5)) when(mock).process(gte(5)) when(mock).process(lt(10)) when(mock).process(lte(10)) when(mock).process(neq(0)) ``` -------------------------------- ### Mock Return Value Computation with thenAnswer - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Demonstrates the thenAnswer method that accepts a callable to dynamically compute return values based on invocation arguments. The callable receives the same arguments as the original method call, enabling complex mock behavior like multiplication in this example. ```python m = mock() when(m).do_times(any(), any()).thenAnswer(lambda one, two: one * two) self.assertEquals(20, m.do_times(5, 4)) ``` -------------------------------- ### Mocking and Basic Verification with Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/docs/nutshell.md Demonstrates how to create a mock object, define return values for method calls, and verify that a method was called. It also shows how to simulate exceptions for method calls. ```python from mockito import * myMock = mock() when(myMock).getStuff().thenReturn('stuff') print(myMock.getStuff()) verify(myMock).getStuff() when(myMock).doSomething().thenRaise(Exception('Did a bad thing')) try: myMock.doSomething() except Exception as e: print(e) ``` -------------------------------- ### Creating and Using Mock Objects in Python Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md Shows how to create mock objects using `mock()` from Mockito. Covers creating empty stubs, configuring mock behavior with `when().thenReturn()`, setting attributes, and verifying method calls using `verify()`. ```python from mockito import mock, when, verify # Create an empty mock object obj = mock() # Invoke methods on the mock obj.say('Hi') # Verify the interactions verify(obj).say('Hi') # Configure expected method calls when(obj).say('Hi').thenReturn('Ho') # Create a mock with initial attributes obj_with_attrs = mock({ 'hi': 'ho' }) assert obj_with_attrs.hi == 'ho' # Create a mock with an initial method obj_with_method = mock({ 'say': lambda _: 'Ho' }) assert obj_with_method.say('Anything') == 'Ho' # Verify calls on a mock with a method verify(obj_with_method).say(...) # Create a screaming strict mock obj_strict = mock(strict=True) # Every unconfigured, unexpected call will raise an exception ``` -------------------------------- ### Mocking Classes and Instances with Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/docs/nutshell.md Illustrates how to mock static methods of a class and instance methods of an object. It also demonstrates how to unstub a mock to restore original behavior and how to stub an instance to have different return values on consecutive calls. ```python class Dog(object): def bark(self): return "Wau" # Mocking a class method when(Dog).bark().thenReturn('Miau!') rex = Dog() print(rex.bark()) # Unstubbing and mocking an instance unstub() print(rex.bark()) when(rex).bark().thenReturn('Grrrrr').thenReturn('Wuff') print(rex.bark()) print(rex.bark()) # Mocking an instance does not affect other instances bello = Dog() print(bello.bark()) ``` -------------------------------- ### Mockito-Python Mock Preconfiguration Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Shows how to preconfigure mocks in Mockito-Python, either with a dictionary for general mocks or with a dictionary and `spec` for specced mocks. This allows setting attributes and their values directly during mock creation. ```python from mockito import mock # General mock preconfiguration preconfigured_mock = mock({'text': 'OK'}) assert preconfigured_mock.text == 'OK' # Specced mock preconfiguration class Response: pass specced_preconfigured_mock = mock({'text': 'OK'}, spec=Response) assert specced_preconfigured_mock.text == 'OK' ``` -------------------------------- ### Basic Stubbing and Verification with Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Demonstrates basic stubbing of a function call with a concrete argument and verification using a wildcard. This sets up expected behavior and checks if calls are made as intended. ```python when(os.path).exists('/foo/bar.txt').thenReturn(True) verify(requests, times=1).get(...) ``` -------------------------------- ### Using Context Managers for Patching Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This snippet demonstrates using `mockito`'s context managers (e.g., `expect` or `when`) to temporarily patch modules. The patching is automatically reverted when exiting the `with` block, providing a clean way to manage patches without explicit `unstub()` calls. ```python # E.g. test that `exists` gets never called with expect(os.path, times=0).exists('.flake8'): # within the block `os.path.exists` is patched cached_dir_lookup('.flake8') # at the end of the block `os.path` gets unpatched # Which is btw roughly the same as doing with when(os.path).exists('.flake8'): cached_dir_lookup('.flake8') verify(os.path, times=0).exists(...) ``` -------------------------------- ### Specced Mocks with Classes in Python Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md Explains how to create mocks that are specced against a concrete Python class using `mock(Class)`. Demonstrates stubbing known methods, handling unconfigured attributes/methods, and configuring mocks with initial values or methods while maintaining the class's signature matching. ```python from mockito import mock, when, verify # Assume 'Dog' is a defined class # Create a mock specced against the Dog class rex = mock(Dog) # Stub a known method when(rex).bark().thenReturn('Miau') # This would fail as 'waggle' is not in the Dog spec or stubbed # when(rex).waggle() # Accessing unconfigured attributes will fail # rex.health # Setting an attribute directly rex.health = 121 # Preconfiguring with initial values and spec rex_preconfigured = mock({'health': 121}, spec=Dog) # Preconfiguring a stubbed method with spec rex_method_preconfigured = mock({'bark': lambda sound: 'Miau'}, spec=Dog) # Signature matching enforced by spec # rex_method_preconfigured.bark('sound') # will throw TypeError # Create a loose specced mock rex_loose = mock(Dog, strict=False) ``` -------------------------------- ### Stubbing Methods with Argument Matchers in Python Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md Demonstrates how to use Mockito's argument matchers (`args`, `kwargs`, `...`) to stub method calls with varying arguments. It shows how different argument combinations affect stubbing success and failure, and how omitting `thenReturn` defaults to `None`. ```python from mockito import kwargs, args from mockito import when, mock # Assume 'main' is an object with a 'bark' method # and 'rex' is an object with a 'bark' method # Example 1: Basic stubbing (will fail if bark takes no args) # when(rex).bark('Grrr').thenReturn('Nope') # Example 2: Using kwargs def bark(sound, post='!'): return sound + post when(main).bark('Grrr', **kwargs).thenReturn('Nope') # Example 3: Using args def add_tasks(*tasks, verbose=False): pass # If you omit the `thenReturn` it will just return `None` when(main).add_tasks(*args) # Example 4: Using Ellipsis (...) for any arguments (Python 3) when(main).add_tasks(...) # when(main).add_tasks(Ellipsis) on Python 2 ``` -------------------------------- ### Configuring Deepcopy Behavior for Mocks Source: https://github.com/kaste/mockito-python/blob/master/docs/recipes.md This snippet illustrates how to manage the `__deepcopy__` behavior for mocks in Mockito. It shows how to either completely fake the `__deepcopy__` method or enable the standard implementation by setting `__deepcopy__` to `None`. It also highlights the difference between setting attributes on the mock instance versus the mock class. ```python from mockito import when, mock # Example of faking __deepcopy__ # when(m).__deepcopy__(...).thenReturn(42) # Example of enabling standard implementation # mock_obj = mock({"__deepcopy__": None}, strict=True) # Difference between instance and class attributes m = mock() m.foo = [1] # <= this is set on the instance, not the class m = mock({"foo": [1]}) ``` -------------------------------- ### Create Mocks using mockito.mock() Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md Creates mock objects that can record interactions. Mocks can be unconfigured (returning None) or strict (raising errors on unexpected calls). They can also be configured with specs or dictionaries. ```python from mockito import mock, when # Create a plain mock plain_mock = mock() # Create a strict mock sctrict_mock = mock(strict=True) # Create a mock from a dictionary response = mock({'text': 'ok', 'raise_for_status': lambda: None}) # Create a specced mock response_specced = mock(spec=requests.Response) # Pre-configure a specced mock response_preconf = mock({'json': lambda: {'status': 'Ok'}}, spec=requests.Response) # Configure a callable mock dummy = mock() when(dummy).__call__(1).thenReturn(2) ``` -------------------------------- ### Context Manager Support for Mock Stubbing - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Demonstrates the context manager syntax for using 'when' with mockito-python. The stubbed behavior is only active within the with block, and verify must be called within the context. This provides cleaner, scoped mock configuration. ```python with when(rex).waggle().thenReturn('Yup'): assert rex.waggle() == 'Yup' verify(rex).waggle() ``` -------------------------------- ### Flexible Argument Matching in Mock Stubs - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Shows how mockito-python's simplified argument matchers work with 'when' and 'verify'. Using **kwargs matcher allows exact matching on specific arguments while ignoring others. This reduces boilerplate when you only care about certain parameters. ```python when(requests).get('https://...', **kwargs).thenReturn(...) ``` -------------------------------- ### Mocking Class Factories for Requests Session Source: https://github.com/kaste/mockito-python/blob/master/docs/recipes.md This snippet demonstrates how to mock the `requests.Session` class to test the `fetch` function. It replaces the globally available `requests.Session` with a mock factory that returns a mocked session object. This allows controlling the behavior of HTTP requests during testing. ```python import requests def fetch(url): session = requests.Session() return session.get(url) ``` ```python from mockito import when, mock, verifyStubbedInvocationsAreUsed def test_fetch(unstub): url = 'http://example.com/' response = mock({'text': 'Ok'}, spec=requests.Response) session = mock(requests.Session) when(session).get(url).thenReturn(response) when(requests).Session().thenReturn(session) # <= res = fetch(url) assert res.text == 'Ok' verifyStubbedInvocationsAreUsed() ``` -------------------------------- ### Mocking Module Functions in Python with Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/nutshell.md Shows how to mock functions within a module, such as 'exists' from 'os.path'. It covers defining return values for specific arguments and handling unexpected calls. The 'strict' mode can be adjusted to allow mocking methods not originally present on the object. ```python import os.path when(os.path).exists('somewhere/somewhat').thenReturn(True) when(os.path).exists('somewhere/something').thenReturn(False) print(os.path.exists('somewhere/somewhat')) print(os.path.exists('somewhere/something')) # Example of strict mode disabled when(os.path, strict=False).exist('another_place').thenReturn('well, nice here') print(os.path.exist('another_place')) ``` -------------------------------- ### Mock Callable Dummies - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Shows how to create callable mock objects in mockito-python and verify their invocations using the __call__ method. Callable mocks enable testing of objects that can be invoked as functions while maintaining full mock capabilities. ```python m = mock() m(1, 2) verify(m).__call__(...) ``` -------------------------------- ### Verifying Interactions with mockito.verify() Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md The central interface for verifying interactions with mocks. It supports specifying the number of times a method was called and allows for flexible argument matching using ANY, ARGS, KWARGS, or ellipsis. ```python from mockito import mock, verify, when, ANY, ARGS, KWARGS manager = mock() when(manager).add_tasks(1, 2, 3).thenReturn(True) # Verify exact call verify(manager).add_tasks(1, 2, 3) # Verify using ARGS verify(manager).add_tasks(*ARGS) # Verify using ellipsis (Py3) # verify(manager).add_tasks(...) # Verify using ellipsis (Py2) # verify(manager).add_tasks(Ellipsis) # Verify with times verify(manager, times=2).some_method(ANY) ``` -------------------------------- ### Use ANY Matcher for Type-like Arguments - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Shows the convenience syntax for using the ANY matcher (aliased from any_) as a type-like argument in verify statements. This allows verification without calling the matcher as a function, providing cleaner syntax. ```python dummy(1) verify(dummy).__call__(ANY) ``` -------------------------------- ### Using ANY Matcher in Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Illustrates how to use the `ANY` matcher to match any argument or arguments of a specific type during stubbing and verification. This is useful when the exact argument value is not important. ```python when(os.path).exists(ANY).thenReturn(True) when(os.path).exists(ANY(str)).thenReturn(True) when(mock).foo(any).thenReturn(1) verify(mock).foo(any(int)) ``` -------------------------------- ### Stubbing os.path.exists with Specific Arguments Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This snippet demonstrates how to stub the `os.path.exists` function to return a specific value when called with a concrete argument. It uses `mockito.when` to define the behavior and `thenReturn` to specify the return value. This is useful for controlling the outcome of file system checks during tests. ```python from mockito import when # stub `os.path.exists` when(os.path).exists('/foo').thenReturn(True) os.path.exists('/foo') # => True os.path.exists('/bar') # -> throws unexpected invocation ``` -------------------------------- ### Use Argument Matchers in Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/index.md Match arguments flexibly using Ellipsis (...), kwargs, or predefined matchers like ANY, or_, and not_. Enables stubbing methods with variable arguments and complex matching logic. ```python # Use the Ellipsis, if you don't care when(deferred).defer(...).thenRaise(Timeout) # Or **kwargs from mockito import kwargs # or KWARGS when(requests).get('http://my-api.com/user', **kwargs) # The usual matchers from mockito import ANY, or_, not_ number = or_(ANY(int), ANY(float)) when(math).sqrt(not_(number)).thenRaise( TypeError('argument must be a number')) ``` -------------------------------- ### Setting Expectations with String First Argument in Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Demonstrates the use of `expect` with a string as the first argument, allowing expectations to be set on module-level functions or methods accessed via strings. This enhances flexibility in defining mock behavior. It requires the `expect` function from the mockito library. ```python expect(‘os.path’, times=2).exists(…).thenReturn(True) ``` -------------------------------- ### Context Manager Support for 'when' in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Adds basic context manager support for `when` statements in Mockito-Python. This allows defining stubbed behavior within a `with` block, ensuring that `verify` is called within the same context. ```python from mockito import mock, when, verify rex = mock() with when(rex).waggle().thenReturn('Yup'): assert rex.waggle() == 'Yup' verify(rex).waggle() ``` -------------------------------- ### Stubbing a function with Mockito Python Source: https://github.com/kaste/mockito-python/blob/master/README.rst This snippet demonstrates how to stub a function's side effect using Mockito Python. It shows how to import necessary functions, define a stub for `os.path.exists`, and then how to stub a method of an imported library like `requests` to return a mock response object. Finally, it shows how to clean up stubs. ```python from mockito import when, mock, unstub import os import requests # Stubbing os.path.exists when(os.path).exists('/foo').thenReturn(True) # Stubbing a method of an imported library response = mock({'status_code': 200, 'text': 'Ok'}) when(requests).get(...).thenReturn(response) # Using the stubbed function requests.get('http://google.com/') # Cleaning up stubs unstub() ``` -------------------------------- ### Mockito-Python Argument Matchers Overview Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Lists a comprehensive set of argument matchers available in Mockito-Python as of release 0.7.0. These include logical operators (`and_`, `or_`, `not_`), comparison operators (`eq`, `neq`, `lt`, `lte`, `gt`, `gte`), and custom matching (`arg_that`, `matches`, `captor`). ```python from mockito import mock, when, arg_that, captor, eq, lt m = mock() # Example using arg_that and eq when(m).process(arg_that(eq(10))) # Example using captor to capture arguments input_captor = captor() when(m).receive(input_captor) m.receive('data') assert input_captor.value == 'data' # Example using lt when(m).check_value(lt(5)) ``` -------------------------------- ### Combining Stubs for os.path.exists Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This snippet illustrates how to combine multiple stubbing rules for the same function. It first sets a default return value for `os.path.exists` and then overrides it for a specific file path. This allows for nuanced control over function behavior based on different inputs. ```python from mockito import when when(os.path).exists(...).thenReturn(False) when(os.path).exists('.flake8').thenReturn(True) ``` -------------------------------- ### Mocking Magic Methods in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Demonstrates how to configure magic methods on mocks using Mockito-Python. This allows testing objects that rely on Python's special methods like `__getitem__`. ```python from mockito import mock, when, verify dummy = mock() when(dummy).__getitem__(1).thenReturn(2) assert dummy[1] == 2 verify(dummy).__getitem__(1) ``` -------------------------------- ### Callable Mock Dummies in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Illustrates that mock dummies created with `mock()` in Mockito-Python are now callable. This allows verification of the mock object being called as a function, including its arguments. ```python from mockito import mock, verify m = mock() m(1, 2) verify(m).__call__(1, 2) ``` -------------------------------- ### Verify Expected Interactions with Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md Verifies that specific expectations set using `expect()` have been met for the given mock objects. If no objects are provided, all registered objects are checked. This helps confirm that mocks were called as anticipated. ```python from mockito import expect, verifyExpectedInteractions import os # Set up an expectation for os.path.exists expect(os.path, times=1).exists(...).thenReturn(True) os.path('/foo') # Verify that the expectation was met verifyExpectedInteractions(os.path) # This will pass because os.path.exists was called once ``` -------------------------------- ### Mock Properties with __get__ in Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Mock properties by setting up expectations on the `__get__` method and including the property mock in a dictionary when creating the parent mock. This enables testing of property access behavior. ```python prop = mock() when(prop).__get__(...).thenReturn(23) m = mock({'name': prop}) ``` -------------------------------- ### Argument Capturing with Matcher Conditions Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Shows how to use `captor` in conjunction with other matchers like `any(str)` or `contains()` to capture arguments that meet specific criteria. This refines the capture process. ```python arg = captor(any(str)) arg = captor(contains("foo")) ``` -------------------------------- ### Define Different Responses for Different Arguments Source: https://github.com/kaste/mockito-python/blob/master/docs/index.md Stub the same method with different return values based on different arguments. Mockito throws immediately on unexpected invocations, ensuring type safety and preventing logic errors. ```python # Different arguments, different answers when(foo).bar(1).thenReturn(2) when(foo).bar(2).thenReturn(3) # but: foo.bar(3) # throws immediately: unexpected invocation # because of that you just know that when # you get a `2`, you called it with `1` ``` -------------------------------- ### Calling Original Implementation with Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Demonstrates how to use `thenCallOriginalImplementation` to allow a mocked method to execute its original code. This is useful when you need the real implementation for certain conditions or parts of your test, while still mocking other aspects. It requires the `when` function from the mockito library. ```python when(os.path).exists(...).thenCallOriginalImplementation() when(os.path).exists('.flake8').thenReturn(True) ``` -------------------------------- ### Argument Capturing with Mockito's captor Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Demonstrates how to use the `captor` to capture arguments passed to a mocked function during verification. It allows asserting on the captured values, including all captured values if multiple calls occur. ```python arg = captor() mock.do_something(123) mock.do_something(456) verify(mock).do_something(arg) assert arg.value == 456 assert arg.all_values == [123, 456] ``` -------------------------------- ### Combining Matchers with and_ and or_ Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Illustrates the use of `and_` and `or_` matchers to create complex matching conditions for arguments. `and_` requires all sub-matchers to pass, while `or_` requires at least one to pass. ```python when(mock).foo(and_(ANY(str), contains('foo'))) when(mock).foo(or_(ANY(int), ANY(float))) ``` -------------------------------- ### Patch and replace functions with patch() in mockito-python Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md Monkeypatch replacement functions while recording all interactions for verification within mockito's domain. Supports two calling conventions: direct function replacement or object with attribute name. Non-strict mode when called with three arguments allows adding new methods. ```python # Two-argument form (strict mode) patch(os.path.exists, lambda str: True) ``` ```python # Three-argument form (non-strict mode) patch(os.path, 'exists', lambda str: True) ``` -------------------------------- ### Mockito-Python Strict Mode and Signature Matching Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Enhances strict mode in Mockito-Python to generally match the signature of the target method with its usage. This aims to help developers spot bugs by making interface changes more apparent. It also mentions that `mock`, `when`, and `verify` now return mostly empty objects, reducing the likelihood of method name clashes. ```python from mockito import mock, when, verify def foo(a, b=1): pass main = mock() # This will pass because 'a' is provided when(main).foo(12) # This will raise an error because 'b' is expected by keyword # when(main).foo(c=13) # Example of simplified argument matching when(requests).get('https://example.com', **kwargs).thenReturn('OK') ``` -------------------------------- ### Chain Multiple Return Values and Exceptions with Mockito Source: https://github.com/kaste/mockito-python/blob/master/docs/index.md Chain multiple thenReturn() and thenRaise() calls to define sequential responses. Each invocation consumes the next stub in the chain, allowing simulation of flaky or state-dependent behavior. ```python when(requests).get(...).thenReturn(mock({'status': 501})) \ .thenRaise(Timeout("I'm flaky")) \ .thenReturn(mock({'status': 200, 'text': 'Ok'})) ``` -------------------------------- ### Stub function calls with when2() in mockito-python Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md Pythonic alternative to when() that accepts function references and arguments directly. Returns AnswerSelector interface supporting thenReturn, thenRaise, thenAnswer, and thenCallOriginalImplementation. Always operates in strict mode. ```python # Given dog is an instance of a Dog when2(dog.bark, 'Miau').thenReturn('Wuff') ``` -------------------------------- ### Argument Matchers in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/docs/nutshell.md Explains how to use argument matchers like 'any' and 'contains' to define flexible conditions for stubbing and verifying method calls. 'any(type)' matches any argument of the specified type, while 'contains(substring)' matches string arguments containing a specific substring. ```python from mockito import * myMock = mock() when(myMock).do(any(int)).thenReturn('A number') when(myMock).do(any(str)).thenReturn('A string') print(myMock.do(2)) print(myMock.do('times')) verify(myMock).do(any(int)) verify(myMock).do(any(str)) verify(myMock).do(contains('time')) ``` -------------------------------- ### Configure Magic Methods on Mocks - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Illustrates how to stub magic methods like __getitem__ on mock objects in mockito-python. This enables mocking of subscript operations and other special methods to test code that uses bracket notation or other magic method syntax. ```python dummy = mock() when(dummy).__getitem__(1).thenReturn(2) assert dummy[1] == 2 ``` -------------------------------- ### Using thenCallOriginalImplementation for Spying Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This snippet shows an alternative way to achieve spying behavior using `thenReturn(thenCallOriginalImplementation())`. It achieves the same result as `spy2` by allowing the original function to be called unless explicitly stubbed otherwise. ```python from mockito import when when(os.path).exists(...).thenCallOriginalImplementation() when(os.path).exists('.flake8').thenReturn(False) ``` -------------------------------- ### Custom Predicate Matching with arg_that Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Shows how to use `arg_that` with a custom predicate function (e.g., a lambda) to match arguments based on arbitrary conditions. This offers maximum flexibility for defining matching logic. ```python verify(mock).foo(arg_that(lambda arg: arg > 3 and arg < 7)) ``` -------------------------------- ### Conditional Stubbing with Matchers (ANY, not_, or_) Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Shows how to stub a function to raise an error if arguments do not meet specific criteria using `not_` and `or_` matchers combined with `ANY`. This allows for defining specific error conditions. ```python when(math).sqrt(not_(_or(ANY(float), ANY(int)))).thenRaise(TypeError) when(mock).foo(not_(ANY(str))).thenRaise(TypeError) ``` -------------------------------- ### Using ANY Matcher as a Type in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Provides a convenience feature in Mockito-Python where the `any_` matcher (aliased as `ANY`) can be used like a type instead of requiring explicit invocation like `any_()`. This simplifies verification calls. ```python from mockito import mock, verify, ANY dummy = mock() dummy(1) # Using ANY as if it were a type for verification verify(dummy).__call__(ANY) ``` -------------------------------- ### Capture All Mock Argument Values with captor in Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Use the `captor()` function to capture and store all values passed to mock method calls. The captured values are accessible via the `all_values` attribute, which returns a list of all captured arguments in order. ```python arg = captor() mock.do_something(123) mock.do_something(456) verify(mock).do_something(arg) assert arg.all_values == [123, 456] ``` -------------------------------- ### Configure Mock with Strict Signature Matching - Python Source: https://github.com/kaste/mockito-python/blob/master/docs/changes.md Demonstrates strict mode signature matching in mockito-python where function signatures are validated against mock invocations. The first call passes because argument 'a' is provided, while the second fails because 'c' is not in the original function signature. This helps catch interface changes and bugs in code. ```python def foo(a, b=1): ... when(main).foo(12) # will pass when(main).foo(c=13) # will raise immediately ``` -------------------------------- ### Stub function calls with when() in mockito-python Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md Central interface to stub functions on objects (modules, classes, instances, or mocks). Uses a fluent interface to configure stubs with specific argument signatures and return values. Supports context managers for automatic cleanup and handles side-effect-only functions. ```python when(dog).bark('Grrr').thenReturn('Wuff') when(dog).bark('Miau').thenRaise(TypeError()) assert dog.bark('Grrr') == 'Wuff' # dog.bark('Miau') will throw TypeError # dog.bark('Wuff') will throw unwanted interaction ``` ```python # Context manager usage for automatic unstubbing with when(os.path).exists('/foo').thenReturn(True): # Code under test here pass ``` ```python # Using ANY and KWARGS for flexible argument matching from mockito import ANY, ARGS, KWARGS when(requests).get('http://example.com/', **KWARGS).thenReturn(...) when(os.path).exists(ANY) when(os.path).exists(ANY(str)) ``` ```python # Side-effect only function (returns None) when(manager).do_work().thenReturn() ``` -------------------------------- ### Implement verifyZeroInteractions in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Introduces the `verifyZeroInteractions` function. This is a breaking change as it was previously an alias for `verifyNoMoreInteractions`. Users who relied on the alias should now call `verifyNoMoreInteractions` directly. ```python from mockito import verifyZeroInteractions, verifyNoMoreInteractions # Previously: # verifyZeroInteractions(mock_object) # Now: verifyNoMoreInteractions(mock_object) ``` -------------------------------- ### Mocking Class Behavior Source: https://github.com/kaste/mockito-python/blob/master/docs/walk-through.md This snippet demonstrates how to mock both a class itself and specific instances of a class. Mocking the class affects all future instances, while mocking an instance only affects that particular object. This provides granular control over object behavior in tests. ```python from mockito import when, unstub class Dog(object): def bark(self): return 'Wuff' # either mock the class when(Dog).bark().thenReturn('Miau!') # now all instances have a different behavior rex = Dog() assert rex.bark() == 'Miau!' # or mock a concrete instance when(rex).bark().thenReturn('Grrrr') assert rex.bark() == 'Grrrr' # a different dog will still 'Miau!' assert Dog().bark() == 'Miau!' # be sure to call unstub() once in while unstub() ``` -------------------------------- ### Spying on Objects with mockito.spy() and mockito.spy2() Source: https://github.com/kaste/mockito-python/blob/master/docs/the-functions.md Allows verification of interactions without patching the original object (spy) or by patching the module/class the function resides in (spy2). Both allow side effects to occur while recording interactions. ```python from mockito import spy, spy2, verify import time # Using spy: The returned object is a proxy time_spy = spy(time) # inject time_spy into the code under test # do_work(..., time_spy) # verify(time_spy).time() # Using spy2: Patches the original module/class # spy2(time.time) # do_work(...) # verify(time).time() ``` -------------------------------- ### String Matching with contains and matches Source: https://github.com/kaste/mockito-python/blob/master/docs/the-matchers.md Demonstrates using `contains` to match if a string argument includes a specific substring, and `matches` to check if a string argument conforms to a given regular expression. ```python mock.foo([120, 121, 122, 123]) verify(mock).foo(contains(123)) when(mock).bar(matches(r'^\d+$')) ``` -------------------------------- ### Specced Mocks and isinstance in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Demonstrates how specced mocks in Mockito-Python now correctly pass `isinstance` tests. When a mock is created with a specification (e.g., `mock(Class)`), it will behave like an instance of that class for type checking purposes. ```python from mockito import mock class MyClass: pass instance = mock(MyClass) assert isinstance(instance, MyClass) is True ``` -------------------------------- ### Implement thenAnswer Callable in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Introduces `thenAnswer(callable)`, which allows a stubbed method to return a value computed by a provided callable. The callable receives the arguments passed to the stubbed method, enabling dynamic return values based on input. ```python from mockito import mock, when, ANY m = mock() when(m).do_times(ANY, ANY).thenAnswer(lambda one, two: one * two) assert m.do_times(5, 4) == 20 ``` -------------------------------- ### Argument Matcher Aliases in Mockito-Python Source: https://github.com/kaste/mockito-python/blob/master/CHANGES.txt Aliases common argument matchers for convenience. `any_` is aliased to `ANY`, `args` to `ARGS`, and `kwargs` to `KWARGS`. It also notes that Python's built-in `any` can be used as a stand-in for `ANY`. ```python from mockito import mock, verify, ANY, ARGS, KWARGS dummy = mock() # Using ANY directly verify(dummy).__call__(ANY) # Using ARGS and KWARGS (example context) # when(some_obj).method(ARGS, KWARGS).thenReturn(...) # Using Python's built-in any as a stand-in for ANY import builtins verify(dummy).__call__(builtins.any) ```