Qiang Xu
Qiang Xu

Reputation: 4803

default arg with test class member variable

Have the simplified script snippet as follows:

#!pytest
import pytest

class TestDefaultArg():
    @pytest.fixture(scope="class", autouse=True)
    def setup_cleanup(self, request):
        request.cls.default_id = 100
        yield

    def test_basic(self):
        self.db_helper()

    def db_helper(self, id=self.default_id):
        pass

The intention is to pass the class memeber self.default_id to db_helper(). However, it gives me this error:

/u/qxu/test.py:4: in <module>
    class TestDefaultArg():
/u/qxu/test.py:13: in TestDefaultArg
    def db_helper(self, id=self.default_id):
E   NameError: name 'self' is not defined

So, the question is, how to use a test class data member to provide the default argument for a test class member function?

Upvotes: 0

Views: 48

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16815

This is not related to pytest, but just to normal Python functionality. You cannot reference self in a default argument, because the default argument is created at load time, not at run time. Also, you have been creating a class variable, not an instance variable, so you have to access it using self.__class__ instead of self.

The usual way to handle this is to use a None default value and only set the value in the function, e.g. something like:

    def db_helper(self, current_id=None):
        if current_id is None:
            current_id = self.__class__.default_id
        print(current_id)

Note that I have also changed the variable name, as id is a built-in name, and it is not good practice to shadow these.

EDIT: Use check for None as proposed by @chepner.

Upvotes: 1

Related Questions