-
Notifications
You must be signed in to change notification settings - Fork 0
pytest
I personally do NOT recommend using pytest. I never enjoyed using it.
- Installation:
pip3 install pytest
- Note on testing via PyCharm: you need to set the test framework first
pytest
sees all functions starting with test_
as a test case.
import pytest
def test_blah(blub)
assert blub == 42
Fixtures are used in order to prepare identical and consistent test conditions for unit testing. That is initialisation, configuration, preparing preconditions, providing data (used pytest caching mechanisms automatically) etc.
Register a fixture by decorating an object:
import pytest
@pytest.fixture
def toolInit()
# Do some stuff
# Due to the fixture decorator toolInit is found by pytest
def test_myTest(toolInit)
# Do some stuff
a = ...
yield a # Provide a; end of normal init
# Teardown sequence begins
print("Teardown", a, "...")
Teardown actions can be set via yield
within a fixture. Use it instead of return to give back the generated object.
It is not called in case of previous exceptions. An alternative is the addfinalizer
function which is always called regardless of an exception event plus you can register multiple finaliser functions.
You can find available fixutres with pytest --fixtures test_myTests.py
. Private fixtures (having a leading underscore (_
) can be found using the verbose (-v
) option)
Accessing fixtures accross multiple files gets handier moving those fixtures to a file named conftest.py
without importing the file. Pytest discovers is automatically.
Fixtures are invoked by default per test function.
Defining the fixtures scope can save performance. @pytest.fixture(scope="module")
will invoke the fixture only once per module.
Available options are (and are instantiated in this order):
session
module
function
class
-
package
(runs when the last test was done)
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License *.
Code (snippets) are licensed under a MIT License *.
* Unless stated otherwise