我正在为 pytest 制作一个测试类,我想设置一个a将用于多种测试方法的类属性。为此,我使用了一个固定装置set_a,它会自动启动autouse=True,并且只为类 ( scope='class') 调用一次,因为设置a成本很高。这是我的代码:
import pytest
import time
class Test:
@pytest.fixture(scope='class', autouse=True)
def set_a(self):
print('Setting a...')
time.sleep(5)
self.a = 1
def test_1(self):
print('TEST 1')
assert self.a == 1
Run Code Online (Sandbox Code Playgroud)
但测试失败并出现以下错误:
========================================================================= FAILURES ==========================================================================
________________________________________________________________________ Test.test_1 ________________________________________________________________________
self = <tests.test_file.Test object at 0x116d953a0>
def test_1(self):
print('TEST 1')
> assert self.a == 1
E AttributeError: 'Test' object has no attribute 'a'
tests/test_file.py:15: AttributeError
------------------------------------------------------------------- Captured stdout setup -------------------------------------------------------------------
Setting a...
------------------------------------------------------------------- Captured …Run Code Online (Sandbox Code Playgroud)