偏离常规测试文件名规则时pytest AssertionError无差异输出
问题:Hy语言pytest插件中test-开头文件AssertionError无差异展示
我为Hy语言开发了一个pytest插件,conftest.py改编自官方Hy的conftest文件,但发现以test-开头的测试文件触发AssertionError时,即使使用-vv命令行参数,也不会显示差异,只有test_开头的文件能正常展示差异。
相关代码如下:
conftest.py
import os from pathlib import Path import pytest import hy NATIVE_TESTS = Path.cwd().joinpath("tests", "native_tests") # https://github.com/hylang/hy/issues/2029 os.environ.pop("HYSTARTUP", None) def pytest_collect_file(parent, path): if ( path.ext in (".hy", ".py") and ( path.basename.startswith("test_") or path.basename.startswith("test-") or path.basename.endswith("_test") or path.basename.endswith("-test") ) # Mimics https://github.com/hylang/hy/blob/master/conftest.py#L38: and ( (not NATIVE_TESTS.exists()) or ( NATIVE_TESTS.exists() and (str(NATIVE_TESTS) in (path.dirname + os.sep)) ) ) and path.basename != "__init__.hy" ): path = Path(path) path.touch(exist_ok=True) return pytest.Module.from_parent(parent, path=path)
init.py
import pytest pytest.register_assert_rewrite("pytest_hy")
问题原因
pytest的断言重写机制默认只针对符合特定命名规范的文件生效,其中包含test_开头的文件,但不涵盖test-开头的。你当前调用的pytest.register_assert_rewrite("pytest_hy")仅重写了插件内部模块,并没有让pytest对test-开头的测试文件启用断言重写,导致这类文件触发断言错误时无法展示差异。
解决方案
提供两种可行的修复方式:
方案1:收集文件时手动触发断言重写
修改conftest.py中的pytest_collect_file函数,识别到test-开头或-test结尾的文件时,手动调用pytest的断言重写接口:
import os from pathlib import Path import pytest from pytest._assertion.rewrite import rewrite_asserts import hy NATIVE_TESTS = Path.cwd().joinpath("tests", "native_tests") os.environ.pop("HYSTARTUP", None) def pytest_collect_file(parent, path): if ( path.ext in (".hy", ".py") and ( path.basename.startswith("test_") or path.basename.startswith("test-") or path.basename.endswith("_test") or path.basename.endswith("-test") ) and ( (not NATIVE_TESTS.exists()) or ( NATIVE_TESTS.exists() and (str(NATIVE_TESTS) in (path.dirname + os.sep)) ) ) and path.basename != "__init__.hy" ): path = Path(path) path.touch(exist_ok=True) # 为test-开头和-test结尾的文件手动启用断言重写 if path.basename.startswith("test-") or path.basename.endswith("-test"): rewrite_asserts(path) return pytest.Module.from_parent(parent, path=path)
方案2:扩展pytest断言重写的文件匹配规则
在插件的__init__.py中添加配置钩子,让pytest默认将test-*和*-test模式的文件纳入断言重写范围:
import pytest pytest.register_assert_rewrite("pytest_hy") def pytest_configure(config): # 添加test-开头的文件到断言重写白名单 config.addinivalue_line("assert_rewrite", "test-*") # 添加-test结尾的文件到断言重写白名单 config.addinivalue_line("assert_rewrite", "*-test")
内容的提问来源于stack exchange,提问作者syvlorg
相关产品推荐
相关产品推荐

