### Install Mockito Python via pip Source: https://mockito-python.readthedocs.io/en/latest/index Install the Mockito Python package using pip package manager. Optionally install the pytest-mockito plugin if you are already using pytest for testing. ```bash pip install mockito ``` -------------------------------- ### Mocking with keyword arguments and argument matchers Source: https://mockito-python.readthedocs.io/en/latest/changes Shows how to use `when` and `verify` with keyword arguments and argument matchers. This example demonstrates matching the first URL argument exactly while ignoring other keyword arguments like headers. ```python when(requests).get('https://...', **kwargs).thenReturn(...) ``` -------------------------------- ### Mockito Context Manager with When and Verify Source: https://mockito-python.readthedocs.io/en/latest/walk-through This example shows another way to use mockito's context managers, combining `when` and `verify`. Within the `with when(...)` block, `os.path.exists('.flake8')` is stubbed, `cached_dir_lookup` is called, and then `os.path.exists` is verified to have been called zero times with any argument. ```python # Which is btw roughly the same as doing with when(os.path).exists('.flake8'): cached_dir_lookup('.flake8') verify(os.path, times=0).exists(...) ``` -------------------------------- ### Configuring magic methods on mocks Source: https://mockito-python.readthedocs.io/en/latest/changes Illustrates how to configure and verify the behavior of magic methods (dunder methods) on mock objects. This example shows setting up `__getitem__` to return a specific value when accessed with a key. ```python dummy = mock() when(dummy).__getitem__(1).thenReturn(2) assert dummy[1] == 2 ``` -------------------------------- ### Mocking Functions with Positional Arguments Source: https://mockito-python.readthedocs.io/en/latest/walk-through Illustrates mocking functions that take positional arguments and optional keyword arguments using Mockito's `args` matcher. It explains the behavior when `thenReturn` is omitted and shows examples of valid and invalid calls based on argument matching. ```python from mockito import args # Assuming 'main' is an imported module or object with an 'add_tasks' function # def add_tasks(*tasks, verbose=False): # pass # If you omit the `thenReturn` it will just return `None` when(main).add_tasks(*args) # Example of a call that would go: # add_tasks('task1', 'task2') ``` -------------------------------- ### Mocking Class Behavior with Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This example shows how to mock a class `Dog` using mockito. It first mocks the class itself, changing the behavior of the `bark` method for all instances. Then, it demonstrates mocking a specific instance (`rex`) of the `Dog` class. ```python 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() ``` -------------------------------- ### Combining stubs for os.path.exists Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This example shows how to combine multiple stub definitions for the same function. It first sets a default return value for `os.path.exists` for any path, and then overrides it for a specific file. This allows for precise control over function behavior in different scenarios within a test. ```python from mockito import when import os when(os.path).exists(...).thenReturn(False) when(os.path).exists('.flake8').thenReturn(True) ``` -------------------------------- ### Using context manager for expect and verification Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This example utilizes mockito's context manager capabilities, specifically `expect`, to patch a function within a block and assert call counts. Inside the `with` block, `os.path.exists` is patched to be called 0 times. After the block, the original behavior is restored automatically. ```python from mockito import expect import os def cached_dir_lookup(path): # Assume this function calls os.path.exists pass # 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 ``` -------------------------------- ### Verifying method calls on a specific instance Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This example demonstrates how to verify that a method on a specific object instance was called a certain number of times. After setting up a mock for the instance's method and calling it multiple times, `verify` is used with the instance and the desired `times` argument to assert the call count. ```python from mockito import when, verify, times 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() ``` -------------------------------- ### Stubbing with Wildcard Arguments in Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This example shows how to stub a function call using a wildcard argument with mockito. The `when(os.path).exists(...)` syntax ensures that `os.path.exists` will return `True` regardless of the arguments passed to it for the duration of the stub. ```python 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 ``` -------------------------------- ### Using thenCallOriginalImplementation in Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This example shows an alternative way to achieve spying behavior using `thenCallOriginalImplementation`. It first sets all `os.path.exists` calls to use the original implementation and then specifically stubs `.flake8` to return `False`. ```python when(os.path).exists(...).thenCallOriginalImplementation() when(os.path).exists('.flake8').thenReturn(False) ``` -------------------------------- ### Using thenCallOriginalImplementation with stubbing Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This example demonstrates an alternative way to achieve spying behavior using `thenCallOriginalImplementation`. It explicitly states that for any argument, the original implementation should be called, while a specific file (`'.flake8'`) is stubbed to return `False`. ```python from mockito import when import os when(os.path).exists(...).thenCallOriginalImplementation() when(os.path).exists('.flake8').thenReturn(False) ``` -------------------------------- ### Pytest Fixture for Unstubbing in Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This example demonstrates how to create a pytest fixture named `unstub` that automatically calls `mockito.unstub()` after each test. This ensures that any patches or stubs are cleaned up, preventing interference between tests. ```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") ``` -------------------------------- ### Mockito Strictness: Invalid Method or Arguments Source: https://mockito-python.readthedocs.io/en/latest/walk-through This example highlights mockito's strictness. It shows two scenarios that will cause errors: attempting to mock a method (`waggle`) that does not exist on the object, and attempting to provide arguments to a mocked method (`bark`) that is not defined to accept any. ```python # this will fail because `Dog` has no method named `waggle` when(rex).waggle().thenReturn('Nope') # this will fail because `bark` does not take any arguments when(rex).bark('Grrr').thenReturn('Nope') ``` -------------------------------- ### Strict mode method signature matching Source: https://mockito-python.readthedocs.io/en/latest/changes Highlights Mockito-Python's strict mode, which matches function signatures for mock calls. This example shows that calling `when(main).foo(12)` works if `foo` accepts a positional argument, but `when(main).foo(c=13)` fails if `foo` does not accept a keyword argument `c`. ```python def foo(a, b=1): ... when(main).foo(12) # will pass when(main).foo(c=13) # will raise immediately ``` -------------------------------- ### Creating and Verifying Mock Objects Source: https://mockito-python.readthedocs.io/en/latest/walk-through Demonstrates how to create a basic mock object using `mock()` and verify interactions with it. It covers setting return values with `when().thenReturn()` and initializing mocks with attributes or methods. ```python from mockito import mock, when, verify obj = mock() obj.say('Hi') verify(obj).say('Hi') when(obj).say('Hi').thenReturn('Ho') # Initializing mock with attributes obj_with_attr = mock({'hi': 'ho'}) assert obj_with_attr.hi == 'ho' # Initializing mock with methods obj_with_method = mock({'say': lambda _: 'Ho'}) assert obj_with_method.say('Anything') == 'Ho' verify(obj_with_method).say(...) ``` -------------------------------- ### Basic Mocking and Stubbing with Mockito Source: https://mockito-python.readthedocs.io/en/latest/index Import Mockito components (when, mock, unstub) and stub function calls to return predefined values. Demonstrates mocking os.path.exists and requests.get with mock objects, then cleaning up with unstub(). ```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() ``` -------------------------------- ### Mock Creation and Basic Stubbing in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Creates a basic mock object and configures method behavior using when().thenReturn(). Demonstrates default mock behavior (methods return None) and how to verify method interactions. ```python from mockito import mock, verify obj = mock() # pass it around, eventually it will be used obj.say('Hi') # back in the tests, verify the interactions verify(obj).say('Hi') # by default all invoked methods take any arguments and return None # you can configure your expected method calls with the usual `when` when(obj).say('Hi').thenReturn('Ho') ``` -------------------------------- ### Mock Initialization with Attributes and Lambda Methods Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Initializes mocks with predefined attributes and method behaviors using dictionaries. Demonstrates attribute assignment and lambda-based method stubbing, with a note that this approach lacks argument matching. ```python from mockito import mock # There is also a shortcut to set some attributes obj = mock({ 'hi': 'ho' }) assert obj.hi == 'ho' # This would work for methods as well; in this case obj = mock({ 'say': lambda _: 'Ho' }) # But you don't have any argument and signature matching assert obj.say('Anything') == 'Ho' # At least you can verify your calls verify(obj).say(...) ``` -------------------------------- ### Test Class Instantiation with Mockito Source: https://mockito-python.readthedocs.io/en/latest/recipes Demonstrates how to mock a class constructor to return a mocked instance. This is useful for testing code that relies on instantiating objects from specific classes, like `requests.Session`. ```python from mockito import when, mock, verifyStubbedInvocationsAreUsed import requests def fetch(url): session = requests.Session() return session.get(url) 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() ``` -------------------------------- ### Clear Invocation History with mockito.forget_invocations() Source: https://mockito-python.readthedocs.io/en/latest/the-functions Forgets all recorded invocations for specified objects without removing stubs. Useful for clearing setup code interactions before running test assertions, allowing clean interaction recording. ```python mockito.forget_invocations(obj1, obj2) ``` -------------------------------- ### Mocking Functions with Keyword Arguments Source: https://mockito-python.readthedocs.io/en/latest/walk-through Demonstrates how to use Mockito to mock a function that accepts keyword arguments. It shows successful stubbing with `kwargs` and `post` matching, and explains why certain calls would fail due to signature mismatches. ```python from mockito import kwargs # Assuming 'main' is an imported module or object with a 'bark' function # def bark(sound, post='!'): # return sound + post when(main).bark('Grrr', **kwargs).thenReturn('Nope') # Example of a call that would go: # bark('Grrr', post='?') ``` -------------------------------- ### Mocking Magic Methods (Context Managers) in Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/recipes This recipe demonstrates how to mock objects that implement the context manager protocol (using `with` statements). It covers faking `__enter__` and `__exit__` methods to control the behavior of the mocked session within a `with` block. This is essential for testing code that relies on context management for resources. ```python from mockito import when, mock, args import requests def fetch_2(url): with requests.Session() as session: return session.get(url) 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) # <= fakes entering context when(session).__exit__(*args) # <= fakes exiting context when(requests).Session().thenReturn(session) res = fetch_2(url) assert res.text == 'Ok' ``` -------------------------------- ### Basic Stubbing and Verification with Mockito-Python Source: https://mockito-python.readthedocs.io/en/latest/the-matchers Demonstrates fundamental stubbing and verification patterns in Mockito-Python using concrete values and the ellipsis matcher. This is the most common way to define expected behavior in tests. ```python from mockito import when, verify import os # Stubbing with a concrete value when(os.path).exists('/foo/bar.txt').thenReturn(True) # Verification using ellipsis for any argument verify(requests, times=1).get(...) ``` -------------------------------- ### Mock Context Managers with Mockito Source: https://mockito-python.readthedocs.io/en/latest/recipes Shows how to mock a class that acts as a context manager (using `__enter__` and `__exit__`). This recipe is for testing functions that use the `with` statement to manage resources, such as `requests.Session`. ```python from mockito import when, mock, args import requests def fetch_2(url): with requests.Session() as session: return session.get(url) 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' ``` -------------------------------- ### Create Mock Objects with mockito.mock() Source: https://mockito-python.readthedocs.io/en/latest/the-functions Creates empty mock objects that record all interactions and can be verified later. Supports strict mode, spec matching, and pre-configuration via dictionaries. All methods return None by default in non-strict mode. ```python response = mock({'text': 'ok', 'raise_for_status': lambda: None}) ``` ```python response = mock({'json': lambda: {'status': 'Ok'}}, spec=requests.Response) ``` ```python dummy = mock() when(dummy).__call__(1).thenReturn(2) ``` -------------------------------- ### Using when with context manager for verification Source: https://mockito-python.readthedocs.io/en/latest/changes Demonstrates how to use the `when` function as a context manager to temporarily set up mock behavior and verify interactions within a specific block of code. This requires calling `verify` within the `with` block. ```python with when(rex).waggle().thenReturn('Yup'): assert rex.waggle() == 'Yup' verify(rex).waggle() ``` -------------------------------- ### Mocking a specific instance's method Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This code shows how to mock a method (`bark`) on a specific instance (`rex`) of a class (`Dog`), rather than the class itself. This means only that particular instance will exhibit the mocked behavior, while other instances will retain the original behavior. This allows for targeted mocking of individual objects. ```python from mockito import when, unstub class Dog(object): def bark(self): return 'Wuff' rex = Dog() # or mock a concrete instance when(rex).bark().thenReturn('Grrrr') assert rex.bark() == 'Grrrr' # a different dog will still 'Miau!' (assuming class level mock was set and not unstubbed) # assert Dog().bark() == 'Miau!' unstub() ``` -------------------------------- ### Verify Method Calls with Arguments in Mockito-Python Source: https://mockito-python.readthedocs.io/en/latest/the-functions Demonstrates various ways to verify method calls on a mock object using different argument matching strategies, including positional arguments, argument unpacking, and ellipsis for Python 2 and 3 compatibility. ```python verify(manager).add_tasks(1, 2, 3) # duplicates `when`call ``` ```python verify(manager).add_tasks(*ARGS) ``` ```python verify(manager).add_tasks(...) # Py3 ``` ```python verify(manager).add_tasks(Ellipsis) # Py2 ``` -------------------------------- ### Spec-Based Mock with Method Stubs and Loose Mode Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Demonstrates preconfiguring stubbed methods in spec-based mocks and enabling loose mode to allow unconfigured calls. Shows signature matching enforcement and strict vs loose spec behavior. ```python from mockito import mock # preconfigure stubbed method rex = mock({'bark': lambda sound: 'Miau'}, spec=Dog) # as you specced the mock, you get at least function signature matching # `bark` does not take any arguments so rex.bark('sound') # will throw TypeError # Btw, you can make loose specced mocks:: rex = mock(Dog, strict=False) ``` -------------------------------- ### Verifying os.path.exists call with spy2 Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This code shows how to use `spy2` to keep the original implementation intact while enabling verification of method calls. After performing some actions, `verify` is used to assert that `os.path.exists` was called exactly once with a specific argument. ```python from mockito import spy2, verify, times import os def do_stuff(): # Assume this function exists and calls os.path.exists pass 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") ``` -------------------------------- ### Creating specced mocks with data Source: https://mockito-python.readthedocs.io/en/latest/changes Demonstrates creating a mock object with a specific specification and preconfigured data. This ensures the mock adheres to the interface of the specified class while returning predefined values. ```python mock({'text': 'OK'}, spec=requests.Response) ``` -------------------------------- ### Using mock with preconfigured data Source: https://mockito-python.readthedocs.io/en/latest/changes Illustrates creating a mock object preconfigured with specific data, such as a dictionary. This is useful for mocking objects that return simple data structures. ```python mock({'text': 'OK'}) ``` -------------------------------- ### Using context manager with when and verify Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This demonstrates another way to use mockito's context managers with `when` and `verify`. Inside the `with` block, `os.path.exists` is stubbed. After the block, the stub is automatically removed. This pattern is useful for temporary stubbing within a specific test scope. ```python from mockito import when, verify import os def cached_dir_lookup(path): # Assume this function calls os.path.exists pass with when(os.path).exists('.flake8'): cached_dir_lookup('.flake8') verify(os.path, times=0).exists(...) ``` -------------------------------- ### Stubbing with Concrete Arguments in Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This snippet demonstrates how to stub a specific function call with concrete arguments using mockito's `when` and `thenReturn` methods. It shows how to mock `os.path.exists` to return True for a specific path and how an unexpected invocation raises an error. ```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 ``` -------------------------------- ### Mocking Deepcopy Behavior with Mockito Source: https://mockito-python.readthedocs.io/en/latest/recipes Explains how to handle `__deepcopy__` when mocking objects. It covers configuring mocks to either fake `__deepcopy__` or allow the standard implementation, and discusses nuances with mutable objects and constructor configurations. ```python # Faking deepcopy # when(m).__deepcopy__(...).thenReturn(42) # Enabling standard implementation # mock({"__deepcopy__": None}, strict=True) # Example of setting attributes on instance vs class m = mock() m.foo = [1] # set on instance m = mock({"foo": [1]}) # set on class ``` -------------------------------- ### Mocking Global Modules with Requests in Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This Python code defines a function `get_text` that uses the `requests` library. It then shows how to mock the `requests.get` method using mockito to return a predefined response for a specific URL, enabling testing without making actual HTTP requests. ```python import requests def get_text(url): res = requests.get(url) if 200 <= res.status_code < 300: return res.text return None # How, dare, we did not inject our dependencies! Obviously we can get over that by patching at the module level like before: when(requests).get('https://example.com/api').thenReturn(...) # The return value needs to be defined. ``` -------------------------------- ### Keyword Arguments Matching with kwargs in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Uses the kwargs matcher to stub methods that accept keyword arguments. Demonstrates that kwargs matches any keyword arguments and fails if none are provided or signature doesn't match. ```python def bark(sound, post='!'): return sound + post from mockito import kwargs, when when(main).bark('Grrr', **kwargs).thenReturn('Nope') # now this one will fail bark('Grrr') # because there are no keyword arguments used # this one will fail because `then` does not match the function signature bark('Grrr', then='!!') # this one will go bark('Grrr', post='?') ``` -------------------------------- ### Verifying Function Usage with Mockito Spies Source: https://mockito-python.readthedocs.io/en/latest/walk-through This snippet demonstrates how to use `spy2` to keep the original implementation intact and then verify its usage. It spies on `os.path.exists`, performs some actions, and then verifies that `exists` was called exactly once with a specific argument. ```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") ``` -------------------------------- ### Setting Expectations for Specific Calls in Python Source: https://mockito-python.readthedocs.io/en/latest/changes Demonstrates how to set an expectation for a specific method call using `expect` with a string argument. This allows for more precise control over mock behavior. ```python expect(‘os.path’, times=2).exists(…).thenReturn(True) ``` -------------------------------- ### Mocking with Ellipsis Argument Matcher (Python 3) Source: https://mockito-python.readthedocs.io/en/latest/walk-through Shows how to use the ellipsis (`...`) as a flexible argument matcher in Mockito for Python 3. This allows any combination of arguments to match the mocked function call, simplifying mocking scenarios. ```python when(main).add_tasks(...) # Example of calls that would go: # add_tasks('task1', verbose=True) # add_tasks() ``` -------------------------------- ### Mocking Class Instances as Factories in Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/recipes This recipe shows how to mock a class constructor when it's used like a factory function, returning a mocked instance. It's useful for testing code that instantiates objects from classes, such as `requests.Session`. The mock replaces the actual class constructor with a mock object that returns a predefined mock session. ```python from mockito import when, mock, verifyStubbedInvocationsAreUsed import requests def fetch(url): session = requests.Session() return session.get(url) 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) # <= replaces the class constructor res = fetch(url) assert res.text == 'Ok' verifyStubbedInvocationsAreUsed() ``` -------------------------------- ### Advanced Argument Matching with Mockito Source: https://mockito-python.readthedocs.io/en/latest/index Use argument matchers like Ellipsis (...), ANY(), or_(), and not_() to match function arguments flexibly. Supports **kwargs for matching any keyword arguments, and matchers can be combined for 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')) ``` -------------------------------- ### Verifying Method Calls on Mockito Instances Source: https://mockito-python.readthedocs.io/en/latest/walk-through This snippet demonstrates how to verify method calls on a mocked object using mockito's `verify` function. It mocks a `Dog` instance, stubs its `bark` method, calls `bark` twice, and then verifies that `bark` was indeed called exactly two times. ```python from mockito import verify # once again rex = Dog() when(rex).bark().thenReturn('Grrrr') rex.bark() rex.bark() # `times` defaults to 1 verify(rex, times=2).bark() ``` -------------------------------- ### Speccing Mocks Against Concrete Classes Source: https://mockito-python.readthedocs.io/en/latest/walk-through Shows how to create a mock object that is 'specced' against a concrete class (e.g., `Dog`). This ensures the mock only allows access to methods and attributes defined in the specified class, catching signature errors. ```python # Assuming 'Dog' is a defined class # class Dog: # def bark(self): # pass # health = 0 rex = mock(Dog) when(rex).bark().thenReturn('Miau') # Accessing unconfigured attributes will fail by default # rex.health # This would fail # Preconfiguring attributes rex_preconfigured = mock({'health': 121}, spec=Dog) ``` -------------------------------- ### Using ANY matcher as a type Source: https://mockito-python.readthedocs.io/en/latest/changes Shows how to use the `ANY` matcher (aliased from `any_`) as a type hint for function arguments during verification. This allows for flexible matching of arguments, similar to using `any_()` but with a more concise syntax. ```python dummy = mock() verify(dummy).__call__(ANY) ``` -------------------------------- ### Loose Specced Mocks Source: https://mockito-python.readthedocs.io/en/latest/walk-through Demonstrates creating a mock object specced against a class but with `strict=False`. This allows for more flexibility, permitting calls to unconfigured methods or attributes while still benefiting from signature matching. ```python # Assuming 'Dog' is a defined class rex = mock(Dog, strict=False) # This mock will allow calls to unconfigured methods/attributes, # but will still enforce method signatures defined in Dog. ``` -------------------------------- ### Stubbing os.path.exists with any arguments Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This code illustrates how to stub `os.path.exists` to return a consistent value regardless of the arguments passed. This is achieved by using the ellipsis (...) as a wildcard for any argument. This is useful when the specific arguments to a function do not matter for the test outcome. ```python from mockito import when import os 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 ``` -------------------------------- ### String and Numerical Comparison Matchers in Mockito-Python Source: https://mockito-python.readthedocs.io/en/latest/the-matchers Explains the use of matchers for comparing strings using regular expressions and for numerical comparisons (greater than, less than, etc.). These are useful for precise argument validation. ```python from mockito import when, verify, contains, matches, gt, lt, gte, lte, eq, neq # Match strings containing a substring mock.foo([120, 121, 122, 123]) verify(mock).foo(contains(123)) # Match strings against a regex when(mock).process_data(matches(r'^\d{4}-\d{2}-\d{2}$')) # Numerical comparisons verify(mock).update_value(gt(10)) verify(mock).set_threshold(lt(5.5)) verify(mock).set_count(gte(0)) verify(mock).set_level(lte(100)) verify(mock).send_id(eq(12345)) verify(mock).ignore_id(neq(999)) ``` -------------------------------- ### Stubbing os.path.exists with specific arguments Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This snippet demonstrates how to stub the `os.path.exists` function to return a specific value when called with a concrete argument. It's useful for controlling the behavior of file system checks during tests. The `when` function from `mockito` is used, followed by `thenReturn` to specify the return value. ```python from mockito import when import os # stub `os.path.exists` when(os.path).exists('/foo').thenReturn(True) os.path.exists('/foo') # => True os.path.exists('/bar') # -> throws unexpected invocation ``` -------------------------------- ### Ellipsis Matcher for Any Arguments in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Uses ellipsis (...) as a wildcard matcher to match any arguments on Python 3. Allows configuration for methods called with any combination of positional or keyword arguments. ```python from mockito import when # On Python 3 you can also use `...` when(main).add_tasks(...) # when(main).add_tasks(Ellipsis) on Python 2 add_tasks('task1') # will go add_tasks(verbose=True) # will go add_tasks('task1', verbose=True) # will go add_tasks() # will go ``` -------------------------------- ### Using ANY Matcher in Mockito-Python Source: https://mockito-python.readthedocs.io/en/latest/the-matchers Shows how to use the ANY matcher to match any argument, or arguments of a specific type. This is useful when the exact value of an argument is not important for the test. ```python from mockito import when, verify, ANY import os # Match any argument when(os.path).exists(ANY).thenReturn(True) # Match argument of a specific type (string) when(os.path).exists(ANY(str)).thenReturn(True) # Match any string argument for a GET request when(requests).get(ANY(str), **kwargs) # Match specific URL, any other arguments with ellipsis when(requests).get('https://example.com', ...) # Example with ANY and type checking in stubbing when(mock).foo(any).thenReturn(1) verify(mock).foo(any(int)) ``` -------------------------------- ### Variable Arguments Matching with args in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Uses the args matcher to stub methods that accept variable positional arguments. Requires at least one argument to be passed and fails if only keyword arguments are provided. ```python def add_tasks(*tasks, verbose=False): pass from mockito import args, when # If you omit the `thenReturn` it will just return `None` when(main).add_tasks(*args) add_tasks('task1', 'task2') # will go add_tasks() # will fail add_tasks('task1', verbose=True) # will fail too ``` -------------------------------- ### Verify Method Interactions with mockito.verify() Source: https://mockito-python.readthedocs.io/en/latest/the-functions Central interface for verifying that methods were called with specific arguments, using a fluent API. Supports constraints like times, atleast, atmost, between, and inorder for flexible assertion patterns. ```python verify(, times=2).() ``` ```python from mockito import ANY, ARGS, KWARGS when(manager).add_tasks(1, 2, 3) ``` -------------------------------- ### Callable mock objects Source: https://mockito-python.readthedocs.io/en/latest/changes Shows how mock objects can be made callable, allowing them to be used like functions. This includes verifying calls made to the mock object using its `__call__` method. ```python m = mock() m(1, 2) verify(m).__call__(...) ``` -------------------------------- ### Mocking requests.get using mock and when Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This code shows how to mock the `requests.get` function to return a mock response object. It uses `mockito.mock` to create a fake response with specific attributes like `status_code` and `text`, and then `when` to define the return value for a specific URL. This is essential for testing functions that rely on external HTTP requests. ```python import requests from mockito import when, mock 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' ``` -------------------------------- ### Pytest fixture for automatic unstubbing Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This demonstrates how to create a pytest fixture named `unstub` that automatically calls `mockito.unstub()` after each test function yields. This ensures that mocks are cleaned up without manual intervention in each test. ```python # conftest.py import pytest @pytest.fixture def unstub(): from mockito import unstub yield unstub() ``` -------------------------------- ### Stubbing with Original Implementation in Python Source: https://mockito-python.readthedocs.io/en/latest/changes Demonstrates how to stub a method to call its original implementation while simultaneously providing a specific return value for a particular argument. This is useful for testing scenarios where a method needs its actual logic but a specific condition must be met. ```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) ``` -------------------------------- ### Mocking Deepcopy Behavior in Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/recipes This recipe addresses how Mockito handles `deepcopy` for mocks. It explains that by default, strict mocks will raise an error on unexpected `__deepcopy__` calls. It shows how to explicitly fake `__deepcopy__` or configure mocks to allow the standard implementation. It also touches upon the difference between setting attributes on mock instances versus classes. ```python # Faking __deepcopy__ # from mockito import when # when(m).__deepcopy__(...).thenReturn(42) # Allowing standard implementation # mock({"__deepcopy__": None}, strict=True) # Example of setting attributes on instance vs class # m = mock() # m.foo = [1] # <= instance attribute # m = mock({"foo": [1]}) # This sets "foo" on the class, not the instance directly in this context. ``` -------------------------------- ### Creating Strict Mock Objects Source: https://mockito-python.readthedocs.io/en/latest/walk-through Explains how to create a strict mock object using `mock(strict=True)`. Strict mocks will raise an error for any unconfigured or unexpected method calls or attribute accesses, enforcing stricter testing. ```python from mockito import mock obj = mock(strict=True) # Any unconfigured call like obj.some_method() will raise an error ``` -------------------------------- ### Using Context Managers for Mockito Stubbing Source: https://mockito-python.readthedocs.io/en/latest/walk-through This snippet illustrates the use of context managers (`with` statement) in mockito for temporary stubbing. The `expect` context manager is used here to assert that `os.path.exists` is never called within the block. Mockito automatically unstubs upon exiting the block. ```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 ``` -------------------------------- ### Mocking a class's method for all instances Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through This snippet demonstrates how to mock a method (`bark`) of a class (`Dog`) at the class level. When this is done, all instances of `Dog`, including existing and future ones, will exhibit the mocked behavior. This is useful for globally altering the behavior of a class for testing purposes. ```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!' # be sure to call unstub() once in while unstub() ``` -------------------------------- ### Unstubbing Modules with Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This code shows how to explicitly unstub a module using mockito to restore its original behavior. `unstub()` is called to restore the `os.path` module after it has been patched or stubbed. ```python from mockito import unstub unstub() # restore os.path module ``` -------------------------------- ### Combining Stubs in Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This snippet illustrates how to combine multiple stubs in mockito to define specific behaviors for different function calls. It sets a default return value of `False` for `os.path.exists` and then overrides it to return `True` for a specific file, `.flake8`. ```python when(os.path).exists(...).thenReturn(False) when(os.path).exists('.flake8').thenReturn(True) ``` -------------------------------- ### Stubbing Functions with when() in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/the-functions The `when()` function is the central interface for stubbing functions on a given object. It requires specifying concrete arguments for which the stub will return a defined value. Invocations not matching the signature are rejected. It supports fluent interface for configuration and can be used with a context manager for temporary stubbing. It also supports argument matchers like ANY, ARGS, and KWARGS. Unstubbing is required after use or via a 'with' statement. ```python from mockito import when # Example usage: when(dog).bark('Grrr').thenReturn('Wuff') when(dog).bark('Miau').thenRaise(TypeError()) # Using with context manager: with when(os.path).exists('/foo').thenReturn(True): pass # Using argument matchers: 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)) ``` -------------------------------- ### Capturing Multiple Arguments with Mockito in Python Source: https://mockito-python.readthedocs.io/en/latest/changes Shows how to use the `captor` to store all values passed to a mocked method across multiple calls. This is useful for verifying sequences of interactions or collecting data passed during a test. ```python arg = captor() mock.do_something(123) mock.do_something(456) verify(mock).do_something(arg) assert arg.all_values == [123, 456] ``` -------------------------------- ### Chaining Multiple Answers for Stubbed Calls in Mockito-Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/index This snippet illustrates how to define a sequence of different return values or exceptions for a single stubbed method call. Mockito will cycle through the defined answers on consecutive calls. ```python # Well, you know the internet when(requests).get(...).thenReturn(mock({'status': 501})) \ .thenRaise(Timeout("I'm flaky")) \ .thenReturn(mock({'status': 200, 'text': 'Ok'})) ``` -------------------------------- ### Advanced Matchers for Complex Conditions in Mockito-Python Source: https://mockito-python.readthedocs.io/en/latest/the-matchers Illustrates the use of advanced matchers like not_, or_, and arg_that for creating complex matching logic. These are powerful for verifying intricate argument patterns. ```python from mockito import when, verify, ANY, not_, or_, arg_that import math # Raise TypeError if sqrt receives non-numeric types when(math).sqrt(not_(_or(ANY(float), ANY(int)))).thenRaise(TypeError) # Match if argument is greater than 3 and less than 7 verify(mock).foo(arg_that(lambda arg: arg > 3 and arg < 7)) # Stubbing with a combination of matchers when(mock).foo(and_(ANY(str), contains('foo'))) # Stubbing to raise TypeError if argument is not a string when(mock).foo(not_(ANY(str))).thenRaise(TypeError) # Match if argument is an integer or a float when(mock).foo(or_(ANY(int), ANY(float))) ``` -------------------------------- ### Patching/Replacing Functions with patch() in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/the-functions The `patch()` function allows for patching or replacing functions, similar to monkeypatching, while still recording interactions for verification. It can be called with two arguments (strict mode) or three arguments (non-strict mode, allows adding methods). All interactions remain within the Mockito domain for verification. Unstubbing is required after use or via a 'with' statement. ```python from mockito import patch # Example usage (two arguments, strict mode): patch(os.path.exists, lambda str: True) # Example usage (three arguments, non-strict mode): patch(os.path, 'exists', lambda str: True) ``` -------------------------------- ### Spec-Based Mocking Against Concrete Classes Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Creates mocks specced against a concrete class to enforce method signature matching and limit available methods/attributes to those defined in the spec. Prevents AttributeError for undefined methods. ```python from mockito import mock, when # Given the above `Dog` rex = mock(Dog) # Now you can stub out any known method on `Dog` but other will throw when(rex).bark().thenReturn('Miau') # this one will fail when(rex).waggle() # These mocks are in general very strict, so even this will fail rex.health # unconfigured attribute # Of course you can just set it in a setup routine rex.health = 121 # Or again preconfigure rex = mock({'health': 121}, spec=Dog) ``` -------------------------------- ### Mocking with an answer callable Source: https://mockito-python.readthedocs.io/en/latest/changes Demonstrates the use of `thenAnswer` with a lambda function to compute the return value of a mocked method. The lambda receives the arguments passed to the mocked method and returns a computed result. ```python m = mock() when(m).do_times(any(), any()).thenAnswer(lambda one, two: one * two) self.assertEquals(20, m.do_times(5, 4)) ``` -------------------------------- ### Stubbing Functions with when2() in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/the-functions The `when2()` function provides a more Pythonic interface for stubbing function calls with given arguments compared to `when()`. It returns an `AnswerSelector` interface, similar to `when()`, allowing configuration with `thenReturn`, `thenRaise`, `thenAnswer`, and `thenCallOriginalImplementation`. This function is always strict and requires unstubbing or use with a context manager. ```python from mockito import when2 # Example usage: when2(dog.bark, 'Miau').thenReturn('Wuff') ``` -------------------------------- ### Method Signature Validation Failures in Mockito Python Source: https://mockito-python.readthedocs.io/en/latest/_sources/walk-through Demonstrates common failures when stubbing methods without proper argument matching. Shows errors for undefined methods, incorrect argument counts, and mismatched signatures. ```python from mockito import when # this will fail because `Dog` has no method named `waggle` when(rex).waggle().thenReturn('Nope') # this will fail because `bark` does not take any arguments when(rex).bark('Grrr').thenReturn('Nope') ``` -------------------------------- ### Spying on Functions with Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This code demonstrates using `spy2` in mockito to spy on a function, allowing the original implementation to be called while still enabling specific stubbing. Here, `spy2(os.path.exists)` is used, and then `os.path.exists('.flake8')` is stubbed to return `False`. ```python from mockito import spy2 spy2(os.path.exists) when(os.path).exists('.flake8').thenReturn(False) ``` -------------------------------- ### Mocking Properties with Mockito in Python Source: https://mockito-python.readthedocs.io/en/latest/changes Illustrates how to mock properties of an object using Mockito. This involves stubbing the `__get__` method of a mock object to control the behavior of a property. ```python prop = mock() when(prop).__get__(...).thenReturn(23) m = mock({'name': prop}) ``` -------------------------------- ### Faking Response Objects in Mockito Source: https://mockito-python.readthedocs.io/en/latest/walk-through This snippet demonstrates how to fake a `requests.Response` object using mockito's `mock()` function. It creates a mock object with specific `status_code` and `text` attributes, and a `spec` argument set to `requests.Response` for better type checking. This mock is then used to stub `requests.get`. ```python # 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' # done! ``` -------------------------------- ### Chained Stubbing with Multiple Return Values in Mockito Source: https://mockito-python.readthedocs.io/en/latest/index Chain multiple thenReturn() and thenRaise() calls to return different values or raise exceptions on successive invocations of the same mocked function. Useful for simulating flaky behavior or state changes. ```python # Well, you know the internet when(requests).get(...).thenReturn(mock({'status': 501})) \ .thenRaise(Timeout("I'm flaky")) \ .thenReturn(mock({'status': 200, 'text': 'Ok'})) ``` -------------------------------- ### Spy on Object Behavior with mockito.spy() Source: https://mockito-python.readthedocs.io/en/latest/the-functions Creates a proxy object that records interactions while preserving original function behavior and side effects. Returns a dummy proxy that must be injected into code under test; original object remains unpatched. ```python import time time = spy(time) do_work(..., time) verify(time).time() ```