在Python中,我们经常用到@pytest.fixture装饰器去参数化case,如果你的@pytest.fixture装上函数需要在很多文件中使用,则可以把它写进conftest.py文件中。这个文件中的方法在运行pytest不需要被import,它会被pytest自动发现,发现顺序是:test classess, test modules, conftest.py,最后是内置和第三方插件。
举例:
# content of conftest.py
import pytest
import smtplib
@pytest.fixture(scope="module")
def smtp_connection():
return smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
content of test_module.py
def test_ehlo(smtp_connection):
response, msg = smtp_connection.ehlo()
assert response == 250
assert b"smtp.gmail.com" in msg
assert 0 # for demo purposes
def test_noop(smtp_connection):
response, msg = smtp_connection.noop()
assert response == 250
assert 0 # for demo purposes
其他:scope="session " 一个pytest session调用一次;scope="module" 一个模块调用一次;scope="class" 一个class调用一次;scope="function"一个方法调用一次
pytest.fixture scope范围回调
def determine_scope(fixture_name, config):
if config.getoption("--keep-containers", None):
return "session"
return "function"
@pytest.fixture(scope=determine_scope)
def docker_container():
yield spawn_container()
参考文档:pytest.pdf