# 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": null,
"docs_url": null,
"requires_python": "<4.0,>=3.8",
"maintainer_email": null,
"keywords": "python, testing, mocking, unit, tests",
"author": "tcassou",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/d9/d2/94ba3006216d125807c2912d5016ce3593a69697ae341692d48f47fa1264/expectise-1.3.1.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": null,
"summary": "Mocking API and function calls in Python - inspired by Ruby's RSpec-Mocks.",
"version": "1.3.1",
"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": "6f3d4c52d48b70b548d35ffe6b0446be1f28a59a5f802bea68a397ee57e927ed",
"md5": "3c62a7ca224f30625f8fe29b86f5dd3a",
"sha256": "cfa84bee321574543c4e30940c65be19ad8a77d2866791d7dbe31e32bd0db217"
},
"downloads": -1,
"filename": "expectise-1.3.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "3c62a7ca224f30625f8fe29b86f5dd3a",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.8",
"size": 10465,
"upload_time": "2024-08-19T19:21:58",
"upload_time_iso_8601": "2024-08-19T19:21:58.263976Z",
"url": "https://files.pythonhosted.org/packages/6f/3d/4c52d48b70b548d35ffe6b0446be1f28a59a5f802bea68a397ee57e927ed/expectise-1.3.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "d9d294ba3006216d125807c2912d5016ce3593a69697ae341692d48f47fa1264",
"md5": "8fd8f365c4b46097d12a51c67bc192fa",
"sha256": "c9e3592a41fa841de7a841977ccf7d5936749ba0aa39cee42143ff5e2bd308de"
},
"downloads": -1,
"filename": "expectise-1.3.1.tar.gz",
"has_sig": false,
"md5_digest": "8fd8f365c4b46097d12a51c67bc192fa",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.8",
"size": 11400,
"upload_time": "2024-08-19T19:21:59",
"upload_time_iso_8601": "2024-08-19T19:21:59.493802Z",
"url": "https://files.pythonhosted.org/packages/d9/d2/94ba3006216d125807c2912d5016ce3593a69697ae341692d48f47fa1264/expectise-1.3.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-08-19 19:21:59",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "tcassou",
"github_project": "expectise",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "expectise"
}