Builtin
Karva provides a few built-in fixtures that can be used in your tests.
We will try to add more built-in fixtures from pytest in the future.
Temporary Directory
This fixture provides the user with a pathlib.Path object that points to a temporary directory.
You can use any of the following fixture names:
tmp_path(from pytest)tmpdir(from pytest)temp_path(from karva)temp_dir(from karva)
| test.py | |
|---|---|
1 2 | |
Mock Environment
This fixture allows you to safely modify environment variables, and the system path during tests. All changes are automatically undone after the test completes.
You can use any of the following fixture names:
monkeypatch(from pytest)
This fixture is compatible with pytest's monkeypatch fixture.
| test.py | |
|---|---|
1 2 3 4 5 6 7 8 9 | |
The fixture provides all of these helper methods:
| Python | |
|---|---|
1 2 3 4 5 6 7 8 | |
The raising parameter determines whether or not a KeyError or AttributeError is raised when the attribute or item does not exist when trying to set / delete it.
Simple Example
Consider a scenario where you are working with user configuration and you need to mock their cache directory.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 | |
Reusing Mocks
we can share mocks across multiple functions without having to rerun the mocking functions by using fixture.
See this example where instead of requesting the monkeypatch fixture, we can reuse the mock_response fixture.
This lets us move the patching logic to another function and reuse the mock_response fixture across multiple tests.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
Mocking Environment Variables
If you are working with environment variables, you often need to modify them when testing.
See the example on how this could be useful.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
See the pytest documentation for more information.