Skip to main content

pytest-automock

Travis status for master branch Codecov coverage for master branch Pypi version Pypi downloads count

Reason

  • No generic automock solution

Features

  • Pytest plugin
  • Autogenerate/autouse mocks for functions and objects
  • Sync and async support
  • Locked mode to be sure mocked objects stay untouched
  • Customizable serialization

Limitaions

  • No support for dunder methods (can be partly solved in future)
  • No support for sync/async generators/contexts
  • Races will break tests, since order counts

License

pytest-automock is offered under MIT license.

Requirements

  • python 3.6+

Usage

Lets say you have some module mymod.py:

import time

class Network:
    def get_data_from_network(self, x, y):
        time.sleep(1)
        return x + y

    def send_data_to_network(self, value):
        time.sleep(1)

def logic(x):
    n = Network()
    a, b = 0, 1
    while b < x:
        c = n.get_data_from_network(a, b)
        a, b = b, c
        n.send_data_to_network("ok")
    return b

And you want to create mocks for your Network class (since testing time and sane counts), but you are too lazy to write them... conftest.py:

import pytest
import mymod

@pytest.fixture(autouse=True)
def _mocks(automock):
    with automock((mymod, "Network")):
        yield

test_logic.py:

from mymod import logic

def test_logic():
    assert logic(7) == 8
    assert logic(10) == 13

If you run pytest on this setup, then you will see fail:

$ pytest -x
...
E           RuntimeError: Mock is locked, but '__init__' wanted

automock can work in two modes: locked and unlocked. Locked mode is default, real methods calls of mocked objects are not allowed in this mode. So, above error says that we can't call __init__ of our Network. In locked mode there is no mock-files update also.

To allow real calls and mocks generation automock provides extra cli argument to pytest: --automock-unlocked

$ pytest -x --automock-unlocked
...
test_logic.py .
...
1 passed in 22.09s

After that you can see that tests/mocks/test_logic/mymod/Network file was created. This is mock for your test sequence. Now you can rerun tests and see what happens (you can omit --automock-unlocked key for ensurance, that real object will not be touched (actually even created)).

$ pytest -x
...
test_logic.py .
...
1 passed in 0.04s

API

automock (fixture)

automock fixture is a context manager

def automock(*pairs,
             storage: Union[str, Path] = "tests/mocks",
             override_name: Optional[str] = None,
             unlocked: Optional[bool] = None,
             encode: Callable[[Any], bytes] = pickle.dumps,
             decode: Callable[[bytes], Any] = pickle.loads)
  • *pairs: pair/tuple of object/module and attribute name (str)
  • storage: root path for storing mocks
  • override_name: forced mock-file name
  • unlocked: mode selector (if omited, selected by --automock-unlocked)
  • encode: encode routine
  • decode: decode routine

automock_unlocked (fixture)

Fixture with default mode from cli parameter (bool).

automock (function)

automock function is not supposed to be used by anyone but automock fixture

def automock(factory: Callable, *,
             memory: Dict,
             locked: bool = True,
             encode: Callable[[Any], bytes] = pickle.dumps,
             decode: Callable[[bytes], Any] = pickle.loads):
  • factory: object/function to wrap
  • memory: dicrionary to get/put mocks
  • locked: mode selector
  • encode: encode routine
  • decode: decode routine

Development

Run tests

Since coverage issue/feature, plugins coverage is broken by default. Workaround:

COV_CORE_SOURCE=pytest_automock COV_CORE_CONFIG=.coveragerc COV_CORE_DATAFILE=.coverage.eager pytest

Release files for pytest-automock 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-automock 0.4.0
File Size Uploaded
pytest-automock-0.4.0.tar.gz 11.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pytest-automock 0.4.0
File Interpreter ABI Platform
pytest_automock-0.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 17.0 kB

Release files / pytest-automock-0.4.0.tar.gz

Download URL pytest-automock-0.4.0.tar.gz
Size 11.3 kB
Tags Source
SHA-256 checksum
How to use checksums
38960a806c464ac38a666699b6459bc88362755ba6e7fce87705eb1f2d615bcf
BLAKE2b-256 checksum
How to use checksums
cb6641ee760055f8b8bed2d8f31f5866d03f0f788de0511a635746419ff7f21b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/2.0.0 pkginfo/1.5.0.1 requests/2.20.1 setuptools/40.6.3 requests-toolbelt/0.8.0 tqdm/4.36.1 CPython/3.7.2

Release files / pytest_automock-0.4.0-py3-none-any.whl

Download URL pytest_automock-0.4.0-py3-none-any.whl
Size 5.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
79bc828cc1ce32c675cf2fcc981c57e2d48f2dd0d9cb00a42948b493f1c163a0
BLAKE2b-256 checksum
How to use checksums
8146498ed8799b03f5e0f6b6a58748c2107200ec011bac80ab1f70008a6f728a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/2.0.0 pkginfo/1.5.0.1 requests/2.20.1 setuptools/40.6.3 requests-toolbelt/0.8.0 tqdm/4.36.1 CPython/3.7.2

Release history Release notifications | RSS feed

0.9.1

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.0

2 release files

0.6.3

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.0

2 release files

This release

0.4.0 This release

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page