Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark test to be run in independent process

Tags:

python

pytest

I'm using pytest. I have a test which involves checking that an import is not made when something happens. This is easy enough to make, but when the test is run in pytest it gets run in the same process as many other tests, which may import that thing beforehand.

Is there some way to mark a test to be run in its own process? Ideally there'd be some kind of decorator like

@pytest.mark.run_in_isolation
def test_import_not_made():
    ....

But I haven't found anything like that.

like image 676
Peter Avatar asked Aug 02 '17 13:08

Peter


People also ask

How does pytest know what to run?

Pytest automatically identifies those files as test files. We can make pytest run other filenames by explicitly mentioning them. Pytest requires the test function names to start with test. Function names which are not of format test* are not considered as test functions by pytest.

How do you run failed test cases in pytest?

The plugin provides two command line options to rerun failures from the last pytest invocation: --lf , --last-failed - to only re-run the failures. --ff , --failed-first - to run the failures first and then the rest of the tests.

What is pytest used for?

pytest is a software test framework, which means pytest is a command-line tool that automatically finds tests you've written, runs the tests, and reports the results.


1 Answers

I don't know of a pytest plugin that allows marking a test to run in its own process. The two I'd check are pytest-xdist and ptyest-xprocess (here's a list of pytest plugins), though they don't look like they'll do what you want.

I'd go with a different solution. I assume that the way you're checking whether a module is imported is whether it's in sys.modules. As such, I'd ensure sys.modules doesn't contain the module you're interested in before the test run.

Something like this will ensure sys.modules is in a clean state before your test run.

import sys

@pytest.fixture
def clean_sys_modules():
    try:
        del sys.modules['yourmodule']
    except KeyError:
        pass
    assert 'yourmodule' not in sys.modules # Sanity check.

@pytest.mark.usefixtures('clean_sys_modules')
def test_foo():
    # Do the thing you want NOT to do the import.
    assert 'yourmodule' not in sys.modules 
like image 107
Frank T Avatar answered Oct 09 '22 19:10

Frank T