python - 如何以动态方式自定义通过的测试消息
问题描述
我可能会对以我不应该的方式使用 pytest 感到内疚,但假设我想在成功完成测试时生成并显示一些短消息。就像我正在开发一种压缩算法,而不是“PASSED”,我希望看到“SQUEEZED BY 65.43%”或类似的东西。这甚至可能吗?我应该从哪里开始定制,或者我可能会使用一个插件?
我偶然发现了pytest-custom-report,但它只提供静态消息,这些消息是在测试运行之前设置的。那不是我需要的。
解决方案
我可能会因为我不应该使用 pytest 的方式而感到内疚
一点也不——这正是pytest
插件系统应该解决的用例。
要回答您的实际问题:尚不清楚百分比值的来源。假设它是由函数返回的squeeze()
,我首先将百分比存储在测试中,例如使用record_property
夹具:
from mylib import squeeze
def test_spam(record_property):
value = squeeze()
record_property('x', value)
...
要显示存储的百分比值,请在项目或测试根目录pytest_report_teststatus
的 a 中添加自定义 hookimpl :conftest.py
# conftest.py
def pytest_report_teststatus(report, config):
if report.when == 'call' and report.passed:
percentage = dict(report.user_properties).get('x', float("nan"))
short_outcome = f'{percentage * 100}%'
long_outcome = f'SQUEEZED BY {percentage * 100}%'
return report.outcome, short_outcome, long_outcome
现在test_spam
以默认输出模式运行会产生
test_spam.py 10.0% [100%]
以详细模式运行
test_spam.py::test_spam SQUEEZED BY 10.0% [100%]
推荐阅读
- elasticsearch - 如果未选择过滤器,则 Elasticsearch 默认过滤器行为
- javascript - JavaScript 中的异步和获取问题
- javascript - 了解我们如何避免在 ReactJS 中通过多个级别的组件层次结构传递 props
- python - Discord.py 中的丰富嵌入按钮
- c++ - 使用元素指针删除列表元素
- spring-boot - Spring 控制器单元测试
- spring - Ignite 2.9 SpringCacheManager 中的 NPE
- python - OpenCV:为了显示视频,为什么while循环有2个变量设置为myVideo.read()
- aem - lombok 委托模式没有为 Tabs 组件返回 model.json(Json Exporter) 中的所有方法
- json - 我如何将数据从 xcode 项目发送到个人网站,然后返回不同的数据?