如何将pytest、hypothesis与line_profiler/kernprof配合使用?
解决方案
前置说明
你遇到的报错绝大多数是因为同时启用了 pytest-xdist 的多进程参数 -n,不管是原生 line_profiler 还是 pytest-line-profiler 插件,都不兼容多进程分布式运行模式,首先需要把 -n 参数移除,或者设置为 -n 1 强制单 worker 运行。
方案1:使用 pytest-line-profiler 插件
- 函数路径填写规则:需要用点号拼接完整层级,
tests/test_conv.py中的test_padding函数完整路径为tests.test_conv.test_padding - 命令行调用的正确写法:
pytest --line-profile tests.test_conv.test_padding tests/test_conv.py --hypothesis-profile default
如果需要同时分析 hypothesis 的生成逻辑,可追加多个 --line-profile 参数传入对应内部函数的完整路径即可。
3. 装饰器调用的正确写法:
hypothesis 的参数注入不影响标记生效,直接按文档要求传入要分析的函数即可:
import pytest from hypothesis import given, strategies as st # 括号内传入所有你需要做逐行分析的函数对象 @pytest.mark.line_profile.with_args(test_padding) @given(st.integers()) # 这里放你的hypothesis参数装饰器 def test_padding(padding_value): # 测试逻辑
添加标记后直接运行以下命令即可输出分析结果:
pytest tests/test_conv.py --hypothesis-profile default
方案2:使用原生 line_profiler
- 给所有需要分析的函数添加
@profile装饰器,不需要额外导入该装饰器,运行时kernprof会自动注入 - 正确的运行命令:
kernprof -l -m pytest tests/test_conv.py --hypothesis-profile default
你之前报错找不到 @profile 装饰器是因为漏加了 -l 参数启用逐行分析模式
3. 运行结束后会生成 pytest.lprof 结果文件,用以下命令查看分析报告:
python -m line_profiler pytest.lprof
兼容多进程的特殊配置
如果必须使用多进程运行测试,可将 worker 数固定为1,即可正常生成分析结果:
pytest -n 1 --line-profile tests.test_conv.test_padding tests/test_conv.py --hypothesis-profile default
内容的提问来源于stack exchange,提问作者phdoerfler
相关产品推荐
相关产品推荐

