pytest fixture-模块化:从fixture函数中使用fixture
除了在测试函数中使用fixture外,fixture函数还可以使用其他fixture本身。这有助于fixture的模块化设计,并允许在许多项目中重用特定于框架的fixture。作为一个简单的例子,我们可以扩展前面的例子,实例化一个对象应用程序,我们将已经定义的smtp_connection资源插入其中:
# content of test_appsetup.py
import pytest
class App:
def __init__(self, smtp_connection):
self.smtp_connection = smtp_connection
@pytest.fixture(scope="module")
def app(smtp_connection):
return App(smtp_connection)
def test_smtp_connection_exists(app):
assert app.smtp_connection这里我们声明一个应用程序fixture,它接收前面定义的smtp_connection fixture,并使用它实例化一个app对象。让我们运行:
$ pytest -v test_appsetup.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 2 items
test_appsetup.py::test_smtp_connection_exists[smtp.gmail.com] PASSED [ 50%]
test_appsetup.py::test_smtp_connection_exists[mail.python.org] PASSED [100%]
============================ 2 passed in 0.12s =============================由于smtp_connection的参数化,测试将使用两个不同的App实例和各自的smtp服务器运行两次。应用程序fixture不需要知道smtp_connection参数化,因为pytest将全面分析fixture依赖关系图。
请注意,应用程序fixture有一个模块范围,并使用一个模块范围的smtp_connection fixture。如果smtp_connection被缓存在一个会话作用域上,这个例子仍然可以工作:对于fixture来说,使用更广泛作用域的fixture是可以的,但反过来不行:一个会话作用域的fixture不能以有意义的方式使用一个模块作用域的fixture。