对于 pytest 的 fixture
函数,它默认的作用域是函数级别的。如果你想将 fixture
应用于 class、module 或 session 级别,你可以使用 scope
参数或 autouse
参数来指定。这两个参数可以在 pytest.fixture
装饰器中进行配置。
-
scope
参数用于指定 fixture 的作用域。可选的作用域包括:"function"
(默认,适用于每个测试函数)、"class"
(适用于整个测试类)、"module"
(适用于整个测试模块)和"session"
(适用于整个测试会话)。你可以根据需要选择合适的作用域。 -
autouse
参数是一个布尔值,用于指定是否自动应用 fixture。如果将autouse=True
设置为True
,则将自动在每个测试函数或测试类中应用 fixture。默认值是False
,需要在测试函数或测试类中明确使用@pytest.mark.usefixtures
或传递 fixture 名称来应用 fixture。
除了使用 scope
和 autouse
自动应用 fixture 外,你也可以手动在测试函数或测试类中应用 fixture。在测试函数或测试类中使用 @pytest.mark.usefixtures
装饰器,并传递 fixture 名称来手动应用 fixture。示例如下:
import pytest
@pytest.fixture(scope="module")
def setup_module_fixture():
print("\nSetup module fixture")
@pytest.fixture(scope="class")
def setup_class_fixture():
print("\nSetup class fixture")
class TestExample:
@pytest.mark.usefixtures("setup_module_fixture", "setup_class_fixture")
def test_example(self):
print("\nRunning test_example")
assert True
在上述示例中,setup_module_fixture
使用了 module 级别的作用域,setup_class_fixture
使用了 class 级别的作用域。在 TestExample
类中的 test_example
方法上使用了 @pytest.mark.usefixtures
装饰器来手动应用这两个 fixture。
通过手动使用 @pytest.mark.usefixtures
,你可以有更多灵活的控制,以便在需要的地方应用 fixture。