expectise


Nameexpectise JSON
Version 1.3.0 PyPI version JSON
download
home_pagehttps://github.com/tcassou/expectise
SummaryMocking API and function calls in Python - inspired by Ruby's RSpec-Mocks.
upload_time2023-11-03 20:51:17
maintainer
docs_urlNone
authortcassou
requires_python>=3.8,<4.0
license
keywords python testing mocking unit tests
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Expectise
![Lint, Test and Release](https://github.com/tcassou/expectise/workflows/Lint,%20Test%20and%20Release/badge.svg?branch=master)

Mocking function calls in Python - inspired by Ruby's RSpec-Mocks.

## Description
Test environments are usually isolated from external services, and meant to check the execution logic of the code exclusively. However it is quite common for projects to deal with external APIs (to receive or post data for example) or systems (such as databases).
In that scenario, there are (at least) 2 options:
1. not testing such modules or objects to avoid performing external calls (that would fail anyway - ideally),
2. mocking external calls in order to test their surrounding logic, and increase the coverage of tests as much as possible.

This package is here to help with 2).

## Contents
This repo contains:
* the `expectise` module itself, under `/expectise`;
* a dummy example of small module and its tests under `/example` with unit tests showcasing what the `expectise` package can do.

## Install
Install from [Pypi](https://pypi.org/project/expectise/):
```bash
pip install expectise
```

## Running Tests with Expectise

### Lifecycle
There are 2 steps in the lifecycle of decoration:
1. Set up: marking a method, so that it can be replaced by a surrogate method, and its calls intercepted;
2. Tear down: resetting the mocking behaviour so that all unit tests are fully independent and don't interfere with each other. During that step, some infractions can be caught too, such as not having called a method that was supposed to be called.

### Set Up
Methods can be marked as mocked in 2 different ways, that are described below.

1. Method 1: using the `mock_if` decorator, along with the name and value of the environment variable you use to identify your test environment.
This environment variable, say `ENV` will be checked at interpretation time: if its value matches the input, say `ENV=test`, the mocking logic will be implemented; if not, nothing in your code will be modified, and performance will stay the same since nothing will happen passed interpretation.

Example of decoration:
```python
from expectise import mock_if


class MyObject:
    ...

    @mock_if("ENV", "test")
    def my_function(self, ...)
        ...

    ...
```

This method is concise, explicit and transparent: you can identify mocked candidates at a glance, and your tests can remain light without any heavy setup logic. However, it means patching production code, and carrying a dependency on this package in your production environment, which may be seen as a deal breaker from an isolation of concerns perspective.

2. Method 2: using explicit `mock` statements when setting up your tests.
Before running individual tests, mocks can be injected explicitly as part of any piece of custom logic, typically through fixtures if you're familiar with `pytest` (you'll find examples in `examples/tests/`).

Example of statement:
```python
import pytest
from expectise import mock


@pytest.fixture(autouse=True)
def run_around_tests():
    mock(SomeObject, SomeObject.some_method, "ENV", "test")
    yield
    # see next section for more details on tear down actions
```

This method is a little bit heavier, and may require more maintenance when mocked objects are modified. However, it keeps a clear separation of concerns with production code that is not patched and does not have to depend on this package.

### Tear Down
Once a test has run, underlying `expectise` objects have to be reset so that 1) some final checks can happen, and 2) new tests can be run with no undesirable side effects from previous tests. Again, there are 2 ways of performing the necessary tear down actions, described below.

1. Method 1: using the `Expectations` context manager provided in this package. We recommend using this approach if only a few of your tests deal with functions that you want to mock. Toy example:

```python
from expectise import Expect


def test_instance_method():
    with Expectations():
        Expect("SomeAPI").to_receive("update_attribute").and_return("sshhhh")
        ...
        assert SomeAPI().update_attribute("secret_value") == "sshhhh"
```

2. Method 2: by performing a teardown method for all your tests. We recommend using this approach if most of your tests manipulate objects that you want to mock. Reusing the `pytest` fixtures example from the previous section:

```python
import pytest
from expectise import mock
from expectise import tear_down


@pytest.fixture(autouse=True)
def run_around_tests():
    mock(SomeObject, SomeObject.some_method, "ENV", "test")
    yield
    tear_down()
```
### Manually Disabling a Mock

Sometimes it can be useful to manually disable a mock - for example, to write a test for a method decorated with `mock_if`.
To achieve this, simply call `Expect.disable_mock("<class name>", "<method name>")`

## Mocking Examples
The following use cases are covered:
* asserting that a method is called (the right number of times),
* checking the arguments passed to a method,
* overriding a method so that it returns a given output when called,
* overriding a method so that it raises an exception when called.

The above features can be combined too, with the following 4 possible patterns:
```python
Expect('MyObject').to_receive('my_method').and_return(my_object)
Expect('MyObject').to_receive('my_method').and_raise(my_error)
Expect('MyObject').to_receive('my_method').with_args(*my_args, **my_kwargs).and_return(my_object)
Expect('MyObject').to_receive('my_method').with_args(*my_args, **my_kwargs).and_raise(my_error)
```

A given method of a class can be decorated several times, with different arguments to check and ouputs to be returned.
You just have to specify it with several `Expect` statements. In this case, the order of the statements matters.

The following is valid and assumes `my_method` is going to be called three times exactly:
```python
Expect('MyObject').to_receive('my_method').with_args(*my_args_1, **my_kwargs_1).and_return(my_object_1)
Expect('MyObject').to_receive('my_method').with_args(*my_args_2, **my_kwargs_2).and_raise(my_error)
Expect('MyObject').to_receive('my_method').with_args(*my_args_3, **my_kwargs_3).and_return(my_object_2)
```

Note that if a method decorated at least once with an `Expect` statement is called more or less times than the number
of Expect statements, the unit test will fail.

# Contributing
## Local Setup
We recommend [using `asdf` for managing high level dependencies](https://asdf-vm.com/).
With `asdf` installed,
1. simply run `asdf install` at the root of the repository,
2. run `poetry install` to install python dependencies.

## Running Tests
```python
poetry shell
ENV=test python -m pytest -v examples/tests/
```


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/tcassou/expectise",
    "name": "expectise",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "python,testing,mocking,unit,tests",
    "author": "tcassou",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/e3/0e/fcbe7a9b3f410e57e2d9fe4061ee4454080571b4046b25f67a4a9c470ca6/expectise-1.3.0.tar.gz",
    "platform": null,
    "description": "# Expectise\n![Lint, Test and Release](https://github.com/tcassou/expectise/workflows/Lint,%20Test%20and%20Release/badge.svg?branch=master)\n\nMocking function calls in Python - inspired by Ruby's RSpec-Mocks.\n\n## Description\nTest environments are usually isolated from external services, and meant to check the execution logic of the code exclusively. However it is quite common for projects to deal with external APIs (to receive or post data for example) or systems (such as databases).\nIn that scenario, there are (at least) 2 options:\n1. not testing such modules or objects to avoid performing external calls (that would fail anyway - ideally),\n2. mocking external calls in order to test their surrounding logic, and increase the coverage of tests as much as possible.\n\nThis package is here to help with 2).\n\n## Contents\nThis repo contains:\n* the `expectise` module itself, under `/expectise`;\n* a dummy example of small module and its tests under `/example` with unit tests showcasing what the `expectise` package can do.\n\n## Install\nInstall from [Pypi](https://pypi.org/project/expectise/):\n```bash\npip install expectise\n```\n\n## Running Tests with Expectise\n\n### Lifecycle\nThere are 2 steps in the lifecycle of decoration:\n1. Set up: marking a method, so that it can be replaced by a surrogate method, and its calls intercepted;\n2. Tear down: resetting the mocking behaviour so that all unit tests are fully independent and don't interfere with each other. During that step, some infractions can be caught too, such as not having called a method that was supposed to be called.\n\n### Set Up\nMethods can be marked as mocked in 2 different ways, that are described below.\n\n1. Method 1: using the `mock_if` decorator, along with the name and value of the environment variable you use to identify your test environment.\nThis environment variable, say `ENV` will be checked at interpretation time: if its value matches the input, say `ENV=test`, the mocking logic will be implemented; if not, nothing in your code will be modified, and performance will stay the same since nothing will happen passed interpretation.\n\nExample of decoration:\n```python\nfrom expectise import mock_if\n\n\nclass MyObject:\n    ...\n\n    @mock_if(\"ENV\", \"test\")\n    def my_function(self, ...)\n        ...\n\n    ...\n```\n\nThis method is concise, explicit and transparent: you can identify mocked candidates at a glance, and your tests can remain light without any heavy setup logic. However, it means patching production code, and carrying a dependency on this package in your production environment, which may be seen as a deal breaker from an isolation of concerns perspective.\n\n2. Method 2: using explicit `mock` statements when setting up your tests.\nBefore running individual tests, mocks can be injected explicitly as part of any piece of custom logic, typically through fixtures if you're familiar with `pytest` (you'll find examples in `examples/tests/`).\n\nExample of statement:\n```python\nimport pytest\nfrom expectise import mock\n\n\n@pytest.fixture(autouse=True)\ndef run_around_tests():\n    mock(SomeObject, SomeObject.some_method, \"ENV\", \"test\")\n    yield\n    # see next section for more details on tear down actions\n```\n\nThis method is a little bit heavier, and may require more maintenance when mocked objects are modified. However, it keeps a clear separation of concerns with production code that is not patched and does not have to depend on this package.\n\n### Tear Down\nOnce a test has run, underlying `expectise` objects have to be reset so that 1) some final checks can happen, and 2) new tests can be run with no undesirable side effects from previous tests. Again, there are 2 ways of performing the necessary tear down actions, described below.\n\n1. Method 1: using the `Expectations` context manager provided in this package. We recommend using this approach if only a few of your tests deal with functions that you want to mock. Toy example:\n\n```python\nfrom expectise import Expect\n\n\ndef test_instance_method():\n    with Expectations():\n        Expect(\"SomeAPI\").to_receive(\"update_attribute\").and_return(\"sshhhh\")\n        ...\n        assert SomeAPI().update_attribute(\"secret_value\") == \"sshhhh\"\n```\n\n2. Method 2: by performing a teardown method for all your tests. We recommend using this approach if most of your tests manipulate objects that you want to mock. Reusing the `pytest` fixtures example from the previous section:\n\n```python\nimport pytest\nfrom expectise import mock\nfrom expectise import tear_down\n\n\n@pytest.fixture(autouse=True)\ndef run_around_tests():\n    mock(SomeObject, SomeObject.some_method, \"ENV\", \"test\")\n    yield\n    tear_down()\n```\n### Manually Disabling a Mock\n\nSometimes it can be useful to manually disable a mock - for example, to write a test for a method decorated with `mock_if`.\nTo achieve this, simply call `Expect.disable_mock(\"<class name>\", \"<method name>\")`\n\n## Mocking Examples\nThe following use cases are covered:\n* asserting that a method is called (the right number of times),\n* checking the arguments passed to a method,\n* overriding a method so that it returns a given output when called,\n* overriding a method so that it raises an exception when called.\n\nThe above features can be combined too, with the following 4 possible patterns:\n```python\nExpect('MyObject').to_receive('my_method').and_return(my_object)\nExpect('MyObject').to_receive('my_method').and_raise(my_error)\nExpect('MyObject').to_receive('my_method').with_args(*my_args, **my_kwargs).and_return(my_object)\nExpect('MyObject').to_receive('my_method').with_args(*my_args, **my_kwargs).and_raise(my_error)\n```\n\nA given method of a class can be decorated several times, with different arguments to check and ouputs to be returned.\nYou just have to specify it with several `Expect` statements. In this case, the order of the statements matters.\n\nThe following is valid and assumes `my_method` is going to be called three times exactly:\n```python\nExpect('MyObject').to_receive('my_method').with_args(*my_args_1, **my_kwargs_1).and_return(my_object_1)\nExpect('MyObject').to_receive('my_method').with_args(*my_args_2, **my_kwargs_2).and_raise(my_error)\nExpect('MyObject').to_receive('my_method').with_args(*my_args_3, **my_kwargs_3).and_return(my_object_2)\n```\n\nNote that if a method decorated at least once with an `Expect` statement is called more or less times than the number\nof Expect statements, the unit test will fail.\n\n# Contributing\n## Local Setup\nWe recommend [using `asdf` for managing high level dependencies](https://asdf-vm.com/).\nWith `asdf` installed,\n1. simply run `asdf install` at the root of the repository,\n2. run `poetry install` to install python dependencies.\n\n## Running Tests\n```python\npoetry shell\nENV=test python -m pytest -v examples/tests/\n```\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Mocking API and function calls in Python - inspired by Ruby's RSpec-Mocks.",
    "version": "1.3.0",
    "project_urls": {
        "Homepage": "https://github.com/tcassou/expectise",
        "Repository": "https://github.com/tcassou/expectise"
    },
    "split_keywords": [
        "python",
        "testing",
        "mocking",
        "unit",
        "tests"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6b2ca8811864d0968930d107e6359f8e83689d6bb4614479683a4eb6b0b938c3",
                "md5": "4e7883317c9b6e63587549e22b6cb8b9",
                "sha256": "d70235410e74e440427514bd24a6d77da29570a8504c8c5625b394664ab8d821"
            },
            "downloads": -1,
            "filename": "expectise-1.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4e7883317c9b6e63587549e22b6cb8b9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 10466,
            "upload_time": "2023-11-03T20:51:15",
            "upload_time_iso_8601": "2023-11-03T20:51:15.671897Z",
            "url": "https://files.pythonhosted.org/packages/6b/2c/a8811864d0968930d107e6359f8e83689d6bb4614479683a4eb6b0b938c3/expectise-1.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e30efcbe7a9b3f410e57e2d9fe4061ee4454080571b4046b25f67a4a9c470ca6",
                "md5": "4ac0e931daccde47602ab5944cf922ad",
                "sha256": "3c1d0acfeeeb9bc06f10dbfab1e7a0a120a48e0b82300691d3ab12643c8b7504"
            },
            "downloads": -1,
            "filename": "expectise-1.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "4ac0e931daccde47602ab5944cf922ad",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 12023,
            "upload_time": "2023-11-03T20:51:17",
            "upload_time_iso_8601": "2023-11-03T20:51:17.071265Z",
            "url": "https://files.pythonhosted.org/packages/e3/0e/fcbe7a9b3f410e57e2d9fe4061ee4454080571b4046b25f67a4a9c470ca6/expectise-1.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-03 20:51:17",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "tcassou",
    "github_project": "expectise",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "expectise"
}
        
Elapsed time: 0.13143s