为什么我无法在 pytest fixture 中设置 self.param 值?
class TestClass:
@pytest.fixture(scope='class', autouse=True)
def setup_class(self, test_env):
self.param = 2
def teardown_method(self):
remove_setting(self.param)
def test_one(self):
assert self.param == 2
def test_two(self):
assert len("hello") == 5
这导致scratch.py::TestClass::test_one FAILED
def test_one(self):
> assert self.param == 2
E AttributeError: 'TestClass' object has no attribute 'param'
def teardown_method(self):
> remove_setting(self.param)
E AttributeError: 'TestClass' object has no attribute 'param'
我想在设置期间设置此属性,因为我最终将使用该参数执行方法级拆卸(不是类级拆卸,所以我没有使用产量)。在这个例子中,我的测试看不到 self.param 值,我的拆卸函数也看不到。将 self.param = 2 移动到我所有的测试中很麻烦。有什么更好的方法来做到这一点?
最佳答案
如 docs说:
Something to be aware of when grouping tests inside classes is that each test has a unique instance of the class. Having each test share the same class instance would be very detrimental to test isolation and would promote poor test practices.
我建议使用这样的类范围 fixture :
import pytest
@pytest.fixture(scope='module')
def test_env():
pass
@pytest.fixture(scope='class')
def param(test_env):
return 2
class TestClass:
def test_one(self, param): # All tests methods share the same param
assert param == 2
def test_two(self, param):
assert param == 3
关于python - pytest:在测试用例不可见的 fixture 中分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63552491/