Argument matchers for unittest.mock

Overview

callee

Argument matchers for unittest.mock

Version Development Status Python versions License Build Status

More robust tests

Python's mocking library (or its backport for Python <3.3) is simple, reliable, and easy to use. But it is also a little lacking when it comes to asserting what calls a mock has received.

You can be either very specific:

my_mock.assert_called_once_with(42, some_foo_object, 'certain string')

or extremely general:

my_mock.assert_called_with(ANY, ANY, ANY)
# passes as long as argument count is the same
The former can make your tests over-specified, and thus fragile.
The latter could make them too broad, missing some erroneous cases and possibly letting your code fail in production.

callee provides argument matchers that allow you to be exactly as precise as you want:

my_mock.assert_called_with(GreaterThan(0), InstanceOf(Foo), String())

without tedious, handcrafted, and poorly readable code that checks call_args or call_args_list:

self.assertGreater(mock.call_args[0][0], 0)
self.assertIsInstance(mock.call_args[0][1], Foo)
self.assertIsInstance(mock.call_args[0][2], str)

It has plenty of matcher types to fit all common and uncommon needs, and you can easily write your own if necessary.

Installation

Installing callee is easy with pip:

$ pip install callee
callee support goes all the way back to Python 2.6.
It also works both with the unittest.mock module from Python 3.3+ or its backport.

API reference

See the documentation for complete reference on the library usage and all available matchers.

Contributing

Contributions are welcome! If you need ideas, head to the issue tracker or search for the various TODOs scattered around the codebase. Or just think what matchers you'd like to add :)

After cloning the repository, this should get you up and running:

# ... create virtualenv as necessary ...
pip install -r requirements-dev.txt
tox

To regenerate documentation and display it in the browser, simply run:

inv docs

Happy hacking!

Comments
  • Add support for python 3.7

    Add support for python 3.7

    Hi!

    Python 3.7 raises the following warning:

    DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
    

    We're running our tests with all warnings turned to errors, so they fail on that. This PR fixes that (and adds python 3.7 to tox.ini).

    opened by ndparker 4
  • leveraging the existing functionality for configuring mocks

    leveraging the existing functionality for configuring mocks

    Is there a way to use the functionality for configuring a mock to return specific values (using side_effect as it seems from how mock works) when called with specific parameters?

    opened by nirwall 2
  • Importing ABCs directly from collections deprecated in Python 3.7, stopped working in 3.8

    Importing ABCs directly from collections deprecated in Python 3.7, stopped working in 3.8

    When I run some tests with pytest and callee 0.3, this is printed at the end:

    ============================== warnings summary ===============================
    c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:74
      c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:74: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
        CLASS = collections.Iterable
    
    c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:116
      c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:116: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
        CLASS = collections.Sequence
    
    c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:128
      c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:128: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
        CLASS = collections.Set
    
    c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:246
      c:\users\rnd10\appdata\local\programs\python\python37-32\lib\site-packages\callee\collections.py:246: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
        CLASS = collections.Mapping
    
    -- Docs: https://docs.pytest.org/en/latest/warnings.html
    ======================= 78 passed, 4 warnings in 1.38s ========================
    

    Pytest version info:

    platform win32 -- Python 3.7.3, pytest-5.1.0, py-1.8.0, pluggy-0.12.0
    plugins: cov-2.7.1, ordering-0.6, pycharm-0.6.0
    

    Solution suggestions: https://stackoverflow.com/questions/53978542/how-to-use-collections-abc-from-both-python-3-8-and-python-2-7

    opened by danielschenk 2
  • Fix __repr__ for And and Or matchers

    Fix __repr__ for And and Or matchers

    I cannot use the And matcher in my tests, since the test crashes if mock decides to print out the matcher using __repr__. It looks like the __repr__ functions for And and Or incorrectly have the value argument?

    I assume these haven't actually been used previously, since these two methods also reference self.matchers instead of the correct self._matchers (which would have been caught earlier if they were actually called).

    Let me know if the value arg is intended behaviour. It seems that the value arg is not used though, and it's highly unusual for __repr__() to have more args than just self.

    opened by DonaldWhyte 2
  • Are maintainers missing in this project?

    Are maintainers missing in this project?

    Hi @Xion or other people who maintains this project,

    What is the status of this project? This is a great tool for testing, I would like to keep using but looks like it hasn't been maintained for a while.

    If there are any alternatives we could use, that information would be appreciated, too.

    Thanks!

    opened by untidy-hair 3
  • asyncio.coroutine has been deprecated since Python 3.8 over async def syntax

    asyncio.coroutine has been deprecated since Python 3.8 over async def syntax

    Following tests emit deprecation warning regarding this as below :

    tests/test_objects.py
    80:        @asyncio.coroutine
    103:        @asyncio.coroutine
    
    tests/test_functions.py
    176:        @asyncio.coroutine
    199:        @asyncio.coroutine
    
    tests/test_functions.py::CoroutineFunction::test_coroutine__decorator
      /root/checked_repos/callee/tests/test_functions.py:177: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
        def coro_func(loop):
    
    tests/test_functions.py::CoroutineFunction::test_coroutine_function__decorator
      /root/checked_repos/callee/tests/test_functions.py:200: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
        def coro_func(loop):
    
    tests/test_objects.py::Coroutine::test_coroutine__decorator
      /root/checked_repos/callee/tests/test_objects.py:81: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
        def coro_func(loop):
    
    tests/test_objects.py::Coroutine::test_coroutine_function__decorator
      /root/checked_repos/callee/tests/test_objects.py:104: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
        def coro_func(loop):
    
    opened by tirkarthi 0
  • Dict(keys=String()) example fails

    Dict(keys=String()) example fails

    Docs give the example:

    dict with string keys (no restriction on values)

    Dict(keys=String())

    But this will fail because the code expects both keys and value to be defined. Also there is not test case for this example. Is this docs error or code error?

    opened by talamandas 1
  • Deprecation warning due to invalid escape sequences.

    Deprecation warning due to invalid escape sequences.

    Deprecation warning due to invalid escape sequences. Using raw strings or escaping them again helps in resolving this. Check https://github.com/asottile/pyupgrade/ for automatic fix of this.

    find . -iname '*.py' | grep -Ev 'rdf4|tool' | xargs -P4 -I{} python3.8 -Wall -m py_compile {}
    ./callee/collections.py:98: DeprecationWarning: invalid escape sequence \ 
      """Matches an iterable that's a generator.
    ./callee/types.py:19: DeprecationWarning: invalid escape sequence \ 
      """:param type\ _: Type to match against"""
    ./callee/types.py:35: DeprecationWarning: invalid escape sequence \ 
      """
    ./callee/types.py:61: DeprecationWarning: invalid escape sequence \ 
      """
    ./callee/operators.py:188: DeprecationWarning: invalid escape sequence \ 
      """Matches values that are shorter than,
    ./callee/operators.py:206: DeprecationWarning: invalid escape sequence \ 
      """Matches values that are longer than,
    ./callee/numbers.py:46: DeprecationWarning: invalid escape sequence \ 
      """Matches any complex number.
    ./callee/numbers.py:60: DeprecationWarning: invalid escape sequence \ 
      """Matches any real number.
    ./callee/numbers.py:75: DeprecationWarning: invalid escape sequence \ 
      """Matches a rational number.
    ./callee/base.py:150: DeprecationWarning: invalid escape sequence \ 
      """Provides a default ``repr``\ esentation for custom matchers.
    
    opened by tirkarthi 1
  • Allow `Captor` to capture multiple arguments

    Allow `Captor` to capture multiple arguments

    Currently the following will fail

    from callee.general import Captor
    from mock import Mock
    
    mock = Mock()
    mock(1)
    
    captor = Captor()
    mock.assert_called_with(captor)
    assert 1 == captor.value  # This is ok!
    
    mock(2)
    mock.assert_called_with(captor)  # Fails with ValueError: a value has already been captured
    

    This is somewhat inconsistent with how Mock::assert_called_with works. For example:

    mock = Mock()
    
    mock(1)
    mock(2)
    mock(3)
    
    mock.assert_called_with(3)  # This is ok!
    

    There are multiple ways to deal with this.

    • Allow Captor to be created with an allow_multiple_captures parameter and set the value to the last captured argument
    captor = Captor(allow_multiple_captures=True)  # False by default?
    mock = Mock()
    mock(1)
    mock(2)
    mock.assert_called_with(captor)
    assert 2 == captor.value
    
    • Allow Captor to match multiple arguments and save them in a list
    captor = Captor(matcher=lambda x: x < 2, allow_multiple_captures=True)
    mock = Mock()
    mock(1)
    mock(2)
    
    mock.assert_called_with(captor)
    assert [1, 2] == captor.values
    assert [Match(1, True), Match(2, False)] == captor.matches
    
    
    • Create a MultiCaptor Captor that will collect all matches for a given argument
    opened by NazarioJL 0
Implement unittest, removing all global variable and returning values

Implement unittest, removing all global variable and returning values

Placide 1 Nov 1, 2021
a socket mock framework - for all kinds of socket animals, web-clients included

mocket /mɔˈkɛt/ A socket mock framework for all kinds of socket animals, web-clients included - with gevent/asyncio/SSL support ...and then MicroPytho

Giorgio Salluzzo 249 Dec 14, 2022
Automatically mock your HTTP interactions to simplify and speed up testing

VCR.py ?? This is a Python version of Ruby's VCR library. Source code https://github.com/kevin1024/vcrpy Documentation https://vcrpy.readthedocs.io/ R

Kevin McCarthy 2.3k Jan 1, 2023
Automatically mock your HTTP interactions to simplify and speed up testing

VCR.py ?? This is a Python version of Ruby's VCR library. Source code https://github.com/kevin1024/vcrpy Documentation https://vcrpy.readthedocs.io/ R

Kevin McCarthy 1.8k Feb 7, 2021
Aioresponses is a helper for mock/fake web requests in python aiohttp package.

aioresponses Aioresponses is a helper to mock/fake web requests in python aiohttp package. For requests module there are a lot of packages that help u

null 402 Jan 6, 2023
a socket mock framework - for all kinds of socket animals, web-clients included

mocket /mɔˈkɛt/ A socket mock framework for all kinds of socket animals, web-clients included - with gevent/asyncio/SSL support ...and then MicroPytho

Giorgio Salluzzo 208 Jan 31, 2021
Mockoon is the easiest and quickest way to run mock APIs locally. No remote deployment, no account required, open source.

Mockoon Mockoon is the easiest and quickest way to run mock APIs locally. No remote deployment, no account required, open source. It has been built wi

mockoon 4.4k Dec 30, 2022
Thin-wrapper around the mock package for easier use with pytest

pytest-mock This plugin provides a mocker fixture which is a thin-wrapper around the patching API provided by the mock package: import os class UnixF

pytest-dev 1.5k Jan 5, 2023
Cornell record & replay mock server

Cornell: record & replay mock server Cornell makes it dead simple, via its record and replay features to perform end-to-end testing in a fast and isol

HiredScoreLabs 134 Sep 15, 2022
Mock smart contracts for writing Ethereum test suites

Mock smart contracts for writing Ethereum test suites This package contains comm

Trading Strategy 222 Jan 4, 2023
User-interest mock backend server implemnted using flask restful, and SQLAlchemy ORM confiugred with sqlite

Flask_Restful_SQLAlchemy_server User-interest mock backend server implemnted using flask restful, and SQLAlchemy ORM confiugred with sqlite. Backend b

Austin Weigel 1 Nov 17, 2022
Data-Driven Tests for Python Unittest

DDT (Data-Driven Tests) allows you to multiply one test case by running it with different test data, and make it appear as multiple test cases. Instal

null 424 Nov 28, 2022
Implement unittest, removing all global variable and returning values

Implement unittest, removing all global variable and returning values

Placide 1 Nov 1, 2021
Code for paper "Document-Level Argument Extraction by Conditional Generation". NAACL 21'

Argument Extraction by Generation Code for paper "Document-Level Argument Extraction by Conditional Generation". NAACL 21' Dependencies pytorch=1.6 tr

Zoey Li 87 Dec 26, 2022
Argument Injection in Dragonfly Ruby Gem

CVE-2021-33564 PoC Exploit script for CVE-2021-33564 (Argument Injection in Dragonfly Ruby Gem). Usage Arbitrary File Read python3 poc.py -u https://<

Michael Tsai 12 Nov 9, 2022
This is a python based command line Network Scanner utility, which input as an argument for the exact IP address or the relative IP Address range you wish to do the Network Scan for and returns all the available IP addresses with their MAC addresses on your current Network.

This is a python based command line Network Scanner utility, which input as an argument for the exact IP address or the relative IP Address range you wish to do the Network Scan for and returns all the available IP addresses with their MAC addresses on your current Network.

Abhinandan Khurana 1 Feb 9, 2022
Source code for "A Two-Stream AMR-enhanced Model for Document-level Event Argument Extraction" @ NAACL 2022

TSAR Source code for NAACL 2022 paper: A Two-Stream AMR-enhanced Model for Document-level Event Argument Extraction. ?? Introduction We focus on extra

null 21 Sep 24, 2022
a socket mock framework - for all kinds of socket animals, web-clients included

mocket /mɔˈkɛt/ A socket mock framework for all kinds of socket animals, web-clients included - with gevent/asyncio/SSL support ...and then MicroPytho

Giorgio Salluzzo 249 Dec 14, 2022
Automatically mock your HTTP interactions to simplify and speed up testing

VCR.py ?? This is a Python version of Ruby's VCR library. Source code https://github.com/kevin1024/vcrpy Documentation https://vcrpy.readthedocs.io/ R

Kevin McCarthy 2.3k Jan 1, 2023
a socket mock framework - for all kinds of socket animals, web-clients included

mocket /mɔˈkɛt/ A socket mock framework for all kinds of socket animals, web-clients included - with gevent/asyncio/SSL support ...and then MicroPytho

Giorgio Salluzzo 249 Dec 14, 2022