12

假设我有下一个测试结构:

测试/
  模块1/   
    测试1.py
  模块2/
    测试2.py
  模块3/
    测试3.py

在所有这些测试之前,我如何设置某些方法只调用一次?

4

2 回答 2

25

您可以使用 autouse 固定装置:

# content of test/conftest.py 

import pytest
@pytest.fixture(scope="session", autouse=True)
def execute_before_any_test():
    # your setup code goes here, executed ahead of first test

有关更多信息,请参阅pytest 夹具文档

于 2013-11-18T20:26:44.157 回答
0

如果您的意思是在每次运行测试套装中只执行一次,那么您正在寻找设置和拆卸。

def setup_module(module):
    print ("This will at start of module")

def teardown_module(module):
    print ("This will run at end of module")

同样,您可以拥有setup_functionteardown_function,它们将在每个测试函数的开始和结束时重复运行。您还可以在测试类中添加setupteardown成员函数以在测试类运行的开始和结束时运行。

于 2019-10-04T13:27:20.027 回答