什么是 Fixture?
Fixture 是 Pytest 中用于提供测试环境的一种机制。它可以被用来模拟资源,例如数据库连接、临时文件、网络连接等,以及执行一系列的设置和清理操作,从而使测试用例能够在可控的环境下运行。
Fixture 的基本用法
在 Pytest 中,我们可以通过 @pytest.fixture
装饰器定义 fixture。fixture 可以在测试函数中作为参数传递,并在需要时自动执行。以下是一个简单的例子:
import pytest
@pytest.fixture
def setup():
print("Performing setup")
yield
print("Performing cleanup")
def test_example(setup):
print("Executing test")
assert 1 + 1 == 2
在上面的例子中,setup
函数是一个 fixture。在 test_example
测试用例执行前,setup
函数会被调用。当测试用例执行完成后,setup
函数会执行清理操作。
Fixture 的作用域
Fixture 可以具有不同的作用域,以控制其生命周期和共享程度。Pytest 支持四种作用域:function
、class
、module
和 session
。
- function:默认的作用域