Search code examples
pythonpytestfixtures

Pytest fixture does not modify the variable


I am trying to use fixtures in my pytest code, but the variables I declare in the fixture do not seem to reflect in the test function.

Here is a snippet of my code for your reference (actual variables are different):

@pytest.fixture(autouse=True)
def setup():
    one = 1

# ....

@pytest.mark.usefixtures("setup")
class Test_class(object):
    @pytest.mark.usefixtures("setup")
    def test_print_one(self):
         print(one)

Here, python is complaining that the variable one is not defined. If I declare and assign it outside the fixture to, say, 2, it is now assigned but does not get updated by the fixture (ie the test will use the value 2 instead of 1 as specified in the fixture. My understanding is that a fixture like mine should "preceed" the test execution and set up everything for it. Please correct me if I am wrong.

I have tried passing it in as a parameter and even returning it from the fixture, but nothing seems to work. Also tried having both the fixture and the test method in the same class.

Thank you very much in advance for your kind help. Lorenzo


Solution

  • @pytest.mark.usefixtures doesn't make a variable that you declare inside the fixture to magically appear inside your test method. setup is already invoked automatically thanks to autouse but it still needs to return the values back unless it's supposed to modify some globally defined object (not recommended).

    Let the fixture return some config and declare the fixture in your test method:

    @pytest.fixture(autouse=True)
    def setup():
        return {"one": 1}
    
    class Test_class:
        def test_print_one(self, setup):
             print(setup["one"])
    

    Note: In this particular example you actually don't even need to set autouse=True. Pytest would invoke the fixture anyway because you declared it as an argument in the test method.