Search code examples
pythonpytestfixtures

Can a pytest test change the value of a session fixture and affect subsequent tests?


Let's say that a pytest session fixture returns a dictionary and this dictionary is then manipulated within a test. Would this affect subsequent tests which use the same fixture?


Solution

  • Yes. And that is trivial to verify. Exactly one of these tests will fail:

    import pytest
    
    @pytest.fixture(scope="session")
    def d():
        return {}
    
    def test_one(d):
        assert not d
        d["k"] = "v"
    
    def test_two(d):
        assert not d
        d["k"] = "v"
    

    If the fixture scope is changed to "function" (the default scope) then both tests will pass, since the dict will be created anew each time.