pythonpytest

Mark test to be run in independent process


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.


Solution

  • 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 pytest-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