阅读(844) (1)

pytest fixture-模块化:从fixture函数中使用fixture

2022-03-18 13:56:49 更新

除了在测试函数中使用​​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​​。