默认 arg with test class 成员变量
default arg with test class member variable
简化后的脚本片段如下:
#!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
目的是将 class 成员 self.default_id 传递给 db_helper()。但是,它给了我这个错误:
/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
那么,问题来了,如何使用testclass数据成员为testclass成员函数提供默认参数?
这与 pytest
无关,仅与正常的 Python 功能相关。
您不能在默认参数中引用 self
,因为默认参数是在加载时创建的,而不是在 运行 时创建的。此外,您一直在创建 class 变量,而不是实例变量,因此您必须使用 self.__class__
而不是 self
.
来访问它
通常的处理方法是使用 None
默认值并仅在函数中设置值,例如类似于:
def db_helper(self, current_id=None):
if current_id is None:
current_id = self.__class__.default_id
print(current_id)
请注意,我还更改了变量名称,因为 id
是一个内置名称,隐藏这些不是一个好习惯。
编辑:按照@chepner 的建议使用 None
检查。
简化后的脚本片段如下:
#!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
目的是将 class 成员 self.default_id 传递给 db_helper()。但是,它给了我这个错误:
/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
那么,问题来了,如何使用testclass数据成员为testclass成员函数提供默认参数?
这与 pytest
无关,仅与正常的 Python 功能相关。
您不能在默认参数中引用 self
,因为默认参数是在加载时创建的,而不是在 运行 时创建的。此外,您一直在创建 class 变量,而不是实例变量,因此您必须使用 self.__class__
而不是 self
.
通常的处理方法是使用 None
默认值并仅在函数中设置值,例如类似于:
def db_helper(self, current_id=None):
if current_id is None:
current_id = self.__class__.default_id
print(current_id)
请注意,我还更改了变量名称,因为 id
是一个内置名称,隐藏这些不是一个好习惯。
编辑:按照@chepner 的建议使用 None
检查。