柚子快报激活码778899分享:pytest fixture - pytest --setup-show pytest01_study_notes
柚子快报激活码778899分享:pytest fixture
Fixture
基本语法
使用 @pytest.fixture 装饰器定义 fixture:
import pytest
@pytest.fixture
def my_fixture():
# 初始化资源(setup)
data = "Hello, pytest!"
yield data # 返回数据给测试用例
# 清理资源(teardown)
print("资源清理完成")
def test_example(my_fixture):
assert my_fixture == "Hello, pytest!"
fixture 可以依赖其他 fixture,测试用例可以传递多个 fixture。
常用参数
scope
作用:定义 fixture 的生命周期作用域,控制其初始化和清理的频率。
可选值:
“function”(默认):每个测试函数执行一次。“class”:每个测试类执行一次。“module”:每个模块(文件)执行一次。“session”:整个测试会话(所有测试)执行一次。
params
作用:参数化 fixture,生成多组测试数据。
使用场景:为依赖该 fixture 的测试函数生成多组参数化用例。autouse
作用:自动应用 fixture,无需在测试函数中显式声明。
使用场景:全局配置(如日志初始化、临时目录创建)。ids
作用:为参数化 fixture 的每组参数生成可读的标识符。
使用场景:提升测试报告的可读性。name
作用:重命名 fixture,解决命名冲突或简化调用名称。
使用场景:当 fixture 函数名与测试参数名冲突时。
生命周期管理
作用域默认function(作用域优先级:session > module > class > function)Setup/Teardown 逻辑:使用 yield 分离初始化与清理 或者 通过 request.addfinalizer() 注册清理函数
查看 Fixture 执行顺序
可以通过 pytest --setup-show <测试文件> 命令查看 详细的 SETUP/TEARDOWN 顺序,如:
pytest --setup-show pytest01_study_notes.py
SETUP S _session_faker
SETUP F mail_admin
SETUP F receiving_user (fixtures used: mail_admin)
SETUP F sending_user (fixtures used: mail_admin)
SETUP F email (fixtures used: receiving_user, sending_user)
pytest01_study_notes.py::test_email_received (fixtures used: _session_faker, email, mail_admin, receiving_user, request, sending_user).
TEARDOWN F email
TEARDOWN F sending_user
TEARDOWN F receiving_user
TEARDOWN F mail_admin
TEARDOWN S _session_faker
其中,参数列表顺序无关:在测试用例的 (fixtures used: …) 列表中,fixture 的声明顺序可能是字母顺序或代码中定义的顺序,与实际的
SETUP 顺序无关。
Fixture(夹具)执行顺序
作用域层级:更大作用域的 fixture 优先初始化,因为它们需要被多个小作用域共享,比如scope='session’作用域最大依赖优先:如果一个 fixture 依赖其他 fixture,被依赖的 fixture 会优先初始化声明顺序:若多个 fixture 无依赖关系且作用域相同,则按它们在测试函数参数或依赖链中的声明顺序初始化LIFO 原则:清理时 TEARDOWN 顺序与 初始化 SETUP 顺序相反,最小作用域的优先清理
文档:https://pytest.cn/en/8.2.x/reference/fixtures.html#fixture-availability
内置Fixture
1. 临时文件和目录管理
用于创建临时文件或目录,测试结束后自动清理。
Fixture返回类型用途tmp_pathpathlib.Path(Python 3.5+)创建一个临时目录,返回单个测试用例专用的临时路径对象。tmp_path_factoryTempPathFactory用于跨多个测试用例创建临时目录(如 session 或 module 作用域的临时目录)。tmpdirpy.path.local类似 tmp_path,但返回 py.path.local 对象(兼容旧代码)。tmpdir_factoryTempdirFactory类似 tmp_path_factory,返回 py.path.local 对象。示例:
def test_create_file(tmp_path):
file = tmp_path / "test.txt"
file.write_text("Hello")
assert file.read_text() == "Hello"
tmp_path
可以使用 tmp_path 固定装置,它将为每个测试函数提供一个唯一的临时目录(类型为 pathlib.Path),测试结束后自动清理。
def test_create_file(tmp_path):
# 创建子目录
sub_dir = tmp_path / "sub"
sub_dir.mkdir()
# 创建文件并写入内容
file_path = sub_dir / "test.txt"
file_path.write_text("Hello pytest!")
# 检查文件是否存在
assert file_path.exists()
# 读取文件内容并验证
assert file_path.read_text() == "Hello pytest!"
默认情况下,pytest 为最近 3 次 pytest 调用保留临时目录。
临时目录创建为系统临时目录的子目录。基本名称将为 pytest-NUM,其中 NUM 将随着每次测试运行而递增。默认情况下,将删除超过 3
个临时目录的条目。此行为可以通过 pytest.ini 文件中 [pytest] 下的 tmp_path_retention_count 和
tmp_path_retention_policy 进行配置。
使用 --basetemp 选项将在每次运行之前删除目录,实际上意味着只保留最近一次运行的临时目录。
可以按如下方式覆盖默认临时目录设置 pytest --basetemp=mydir
tmp_path_factory
tmp_path_factory 是一个会话作用域固定装置,可用于从任何其他固定装置或测试创建任意临时目录。
若需在多个测试间共享临时目录,使用 tmp_path_factory 并指定作用域:
@pytest.fixture(scope="module")
def shared_temp_dir(tmp_path_factory):
# 创建模块级别的临时目录
return tmp_path_factory.mktemp("shared_data")
def test_shared_1(shared_temp_dir):
file = shared_temp_dir / "data.txt"
file.write_text("test data")
def test_shared_2(shared_temp_dir):
file = shared_temp_dir / "data.txt"
assert file.read_text() == "test data"
注意:共享目录会绕过测试隔离,需谨慎使用。
2. 测试上下文和请求信息
提供测试用例的上下文信息或操作能力。
Fixture返回类型用途requestFixtureRequest获取当前测试请求的元数据(如测试函数名、参数、模块等)。pytestconfigConfig访问 pytest 的全局配置对象(如命令行参数、插件配置)。示例:
def test_use_request(request):
print(f"当前测试函数名: {request.node.name}")
request
提供对测试用例或 fixture 的上下文信息的访问能力
常用属性:
request.node: 当前测试用例的节点对象(如函数、类)。
通过 request.node.get_closest_marker 获取测试用例的标记(如 @pytest.mark.slow)
request.function: 当前测试函数对象。request.cls: 当前测试类对象(如果测试在类中)。request.module: 当前测试所在的模块对象。
request.module.__name__
request.config: pytest 的全局配置对象。
通过 request.config.getoption 或 request.config.getini 获取 pytest 命令行或配置文件中的参数
base_url = request.config.getoption("--base-url") # 获取命令行参数,pytest --base-url=http://api.example.com test_demo.py
request.param: 获取其他 fixture 的参数或动态生成的配置值.
常用方法:
通过 request.addfinalizer() 或 request.addcleanup() 注册清理函数.addfinalizer vs addcleanup:
addfinalizer: 严格遵循 LIFO(后进先出)顺序执行。
addcleanup: 在测试结束后按注册顺序执行,且即使前面的清理函数抛出异常,后续清理函数仍会执行。
pytestconfig
可以使用 pytest config 对象设置/获取缓存值
# content of test_caching.py
import pytest
def expensive_computation():
print("running expensive computation...")
@pytest.fixture
def mydata(pytestconfig):
val = pytestconfig.cache.get("example/value", None) # 获取值
if val is None:
expensive_computation()
val = 42
pytestconfig.cache.set("example/value", val) # 设置值
return val
def test_function(mydata):
assert mydata == 23
3. 输出和日志捕获
捕获测试运行时的输出、日志或警告。
Fixture返回类型用途capsysCaptureFixture[str]捕获 stdout 和 stderr 的输出(不捕获文件描述符级别的输出)。capfdCaptureFixture[str]捕获文件描述符级别的输出(包括 stdout 和 stderr)。caplogLogCaptureFixture捕获 logging 模块的日志记录。recwarnWarningsRecorder捕获代码中触发的警告(Python 的 warnings 模块)。示例:
def test_output(capsys):
print("Hello pytest")
captured = capsys.readouterr()
assert captured.out == "Hello pytest\n" 拼多多帮助力入口
caplog
更改捕获的日志消息的日志级别.
def test_foo(caplog):
caplog.set_level(logging.CRITICAL, logger="root.baz")
可以使用以下方法更改任何日志记录器的级别
def test_bar(caplog):
with caplog.at_level(logging.CRITICAL, logger="root.baz"):
pass
当您想要断言消息的内容时,遍历caplog.records
def test_baz(caplog):
func_under_test()
for record in caplog.records:
assert record.levelname != "CRITICAL"
assert "wally" not in caplog.text
caplog.records 属性仅包含当前阶段的记录,因此在 setup 阶段中,它仅包含设置日志,与 call 和 teardown 阶段相同。
要访问其他阶段的日志,请使用 caplog.get_records(when) 方法。
@pytest.fixture
def window(caplog):
window = create_window()
yield window
for when in ("setup", "call"):
messages = [
x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
]
if messages:
pytest.fail(f"warning messages encountered during testing: {messages}")
如果您只想确保在给定的日志记录器名称下使用给定的严重性和消息记录了某些消息,还可以使用 record_tuples
def test_foo(caplog):
logging.getLogger().info("boo %s", "arg")
assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]
还可以调用 caplog.clear() 来重置测试中捕获的日志记录
4. 模拟和补丁
用于动态修改运行环境或模拟对象。
Fixture返回类型用途monkeypatchMonkeyPatch临时修改环境变量、模块属性、类方法、sys.path 等,测试结束后自动恢复。示例:
def test_env(monkeypatch):
monkeypatch.setenv("DEBUG", "True")
assert os.getenv("DEBUG") == "True"
5. 缓存管理
用于跨测试会话(Session)存储数据。
Fixture返回类型用途cacheCache提供读写 pytest 缓存的功能(如 --lf 和 --ff 功能依赖此缓存)。示例:
def test_cache(cache):
cache.set("key", {"data": 123})
assert cache.get("key", None) == {"data": 123}
6. 测试运行器集成
用于插件开发或复杂测试场景。
Fixture返回类型用途testdirTestdir创建一个临时项目目录,并运行 pytest 子进程(常用于测试插件或命令行工具)。示例:
def test_plugin(testdir):
testdir.makepyfile("def test_pass(): assert True")
result = testdir.runpytest()
result.assert_outcomes(passed=1)
7. 参数化扩展
用于动态生成测试参数。
Fixture用途@pytest.mark.parametrize非 Fixture,但常用装饰器,用于为测试函数提供多组参数。
总结
核心用途:内置 Fixture 覆盖了测试环境管理、输出捕获、模拟补丁、上下文访问等高频需求。选择依据:优先使用 tmp_path 和 pathlib(更现代),而非 tmpdir(旧版 py.path.local)。组合使用:例如用 monkeypatch 修改环境变量,用 capsys 验证输出,用 tmp_path 管理临时文件。
其他相关
@pytest.mark.usefixtures(…)
@pytest.mark.usefixtures(...) 是 Pytest 中用于在测试类或模块级别自动应用 Fixture 的装饰器,它允许你不必在每个测试函数中显式声明
Fixture 参数,而是直接复用预定义的 Fixture 逻辑
注意事项
返回值不可见:若需使用 Fixture 返回的对象,仍需通过参数传递。执行顺序:多个 Fixture 按声明顺序执行。避免滥用:过度使用可能导致测试逻辑不直观。
警告
请注意,此标记在固定装置函数中不起作用。例如,这不会按预期工作
@pytest.mark.usefixtures("my_other_fixture")
@pytest.fixture
def my_fixture_that_sadly_wont_use_my_other_fixture(): ...
柚子快报激活码778899分享:pytest fixture