Skip to main content

Pytest plugin for automatical mocks creation

Project description

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
  • Black and white lists for attributes
  • 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.7+

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,
             allowed_methods: Optional[Sequence[str]] = None,
             forbidden_methods: Optional[Sequence[str]] = 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)
  • allowed_methods: sequence of allowed to mock attributes
  • forbidden_methods: sequnce of forbidden to mock attributes
  • 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,
             allowed_methods: Optional[Sequence[str]] = None,
             forbidden_methods: Optional[Sequence[str]] = None)
  • factory: object/function to wrap
  • memory: dicrionary to get/put mocks
  • locked: mode selector
  • allowed_methods: sequence of allowed to mock attributes
  • forbidden_methods: sequnce of forbidden to mock attributes

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest-automock-0.3.0.tar.gz (19.0 kB view details)

Uploaded Source

Built Distribution

pytest_automock-0.3.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file pytest-automock-0.3.0.tar.gz.

File metadata

  • Download URL: pytest-automock-0.3.0.tar.gz
  • Upload date:
  • Size: 19.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/3.6.9

File hashes

Hashes for pytest-automock-0.3.0.tar.gz
Algorithm Hash digest
SHA256 73c88ea8b15157c08e8c3040244d4830f7eb11af4d0fc051d1b365d776f68e40
MD5 a32a9c7050a5e8bd7344f731688e2cf5
BLAKE2b-256 3110750ef07f9a165672c8dc73b5670c22f3e8d0f43e0d96a8b19611efb9be70

See more details on using hashes here.

File details

Details for the file pytest_automock-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: pytest_automock-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 6.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/3.6.9

File hashes

Hashes for pytest_automock-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0f4fc11e7dcd2ca5ec47b66ec6a6bdb7c40fdb9459dd7879fc0b78b354e34a16
MD5 55eb8c69aeb9adba4322586d37890d9d
BLAKE2b-256 a3c23b6c9f6d5ba3f0e437fb95437c8c7ec87a756b8703dedbc90f21ea4091a8

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page