在conftest中定义的类作用域fixture之后运行setup_class()类



所以,我在conftest.py文件中定义了fixture,scope="类";因为我想在调用每个测试类之前运行它们。conftest文件被放置在项目根目录中,以便每个测试模块都能看到它。

现在,在其中一个测试模块中,我有另一个设置函数,我只想为该模块运行一次。但问题是在运行conftest.py中定义的fixture之前调用了setup_class()方法。这是预期的吗?我希望它是相反的,因为我想使用在conftest中定义的fixture中完成的东西。如何做到这一点?

代码-

conftest.py:

@pytest.fixture(scope="class")
def fixture1(request):
#set a
@pytest.fixture(scope="class")
def fixture1(request):

test_1.py:

@pytest.mark.usefixtures("fixture_1", "fixture_2")
class Test1():
#need this to run AFTER the fixture_1 & fixture_2 
def setup_class():
#setup
#get a set in fixture_1

def test_1()
.....

我知道我可以简单地在测试文件中定义一个fixture,而不是setup_class,但我必须在每个测试方法的参数中指定它,以便pytest调用它。但建议是受欢迎的!

我也有同样的问题。直到现在我才意识到问题可能是在fixture之前调用setup_class&gt-/我认为这个问题与这个问题相似Pytest-如何将参数传递给setup_class?问题是混合了unittest和pytest方法。我有点像他们建议的那样——我提交了setup_class,并在特定的测试文件中创建了一个新的fixture,调用conftest.py中的fixture。到目前为止,它是有效的。M.

问题是,只能在pytest运行的测试函数(或方法(中使用fixture的结果。在这里,我可以建议一个变通方法。但我当然不确定它是否符合你的需求
解决方法是从测试方法调用函数:

conftest.py

@pytest.fixture(scope='class')
def fixture1():
yield 'MYTEXT'

test_1.py

class Test1:
def setup_class(self, some_var):
print(some_var)
def test_one(self, fixture1):
self.setup_class(fixture1)

Fixtures和setup_class是初始化测试函数(和类(的两种不同的范例。在这种情况下,将两者混合会产生一个问题:类范围的fixture在运行单个测试函数(方法(时运行。另一方面,setup_class之前运行。因此,不可能从setup_class访问fixture值(或fixture修改状态(。

其中一个解决方案是完全停止使用setup_class,并坚持使用仅限夹具的解决方案,这是目前pytest中的首选方式(请参阅开头的注释(。

# conftest.py or the test file:
@pytest.fixture(scope="class")
def fixture_1(request):
print('fixture_1')
# the test file:
class Test1():
@pytest.fixture(scope="class", autouse=True)
def setup(self, fixture_1, request):
print('Test1.setup')
def test_a(self):
print('Test1.test_a')
def test_b(self):
print('Test1.test_b')

请注意,setup固定装置依赖于fixture_1,因此可以访问它。

最新更新