Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial and final check when running pytest test suite

Tags:

python

pytest

I have productive code which creates config files in my $HOME folder and to run my tests in an isolated environment I patch $HOME in conftest.py. Still I'm not sure if this works in general and maybe unthoughtful written test functions might break out.

To ensure the validity of my test suite I'd like to run a preliminary check of the respective files in $HOME and I'd like to run a final check after running the test suite.

How can I achieve this with the "official" means of pytest ? I have a dirty hack which works but messes up reporting.

My test suite is correct now and this question is out of curiosity because I'd like to learn more about pytest.


Addition: Same question, but different use case: I'd like to check if a 3rd-party plugin fullfills a version requierement. If this is not the case I'd like to show a message and stop py.test.

like image 520
rocksportrocker Avatar asked Aug 31 '16 20:08

rocksportrocker


People also ask

How does pytest know what tests to run?

With no arguments, pytest looks at the current working directory (or some other preconfigured directory) and all subdirectories for test files and runs the test code it finds.

What is used to run tests before and after in pytest?

You can use Module level setup/teardown Fixtures of Pytest. It will call setup_module before this test and teardown_module after test completes. You can include this fixture in each test-script to run it for each test.

Which fixture is instantiated first in pytest?

Higher-scoped fixtures are instantiated first¶ Within a function request for features, fixture of higher-scopes (such as session ) are instantiated first than lower-scoped fixtures (such as function or class ).


1 Answers

Have you considered writing a session-scoped pytest fixture? Something like:

@pytest.fixture(scope="session")
def global_check(request):
    assert initial_condition

    def final_check(request):
        assert final_condition

    request.addfinalizer(final_check)

    return request

If all of your other fixtures inherit from global_check, then initial_condition will be asserted at the beginning of all of your test runs and final_condition will be asserted at the end of your test runs.

like image 171
Max Gasner Avatar answered Oct 27 '22 07:10

Max Gasner