gpt4 book ai didi

python - 如何让pytest重写非测试模块中的assert

转载 作者:太空狗 更新时间:2023-10-29 22:21:30 26 4
gpt4 key购买 nike

我们在一个单独的 python 文件中定义了所有自定义断言,该文件不是测试模块。

例如:custom_asserts.py

class CustomAsserts(object):
def silly_assert(self, foo, bar):
assert foo == bar , 'some error message'

如果我们在测试中直接使用assert,我们会得到关于AssertionError的额外信息,这非常有用。

在测试中直接使用断言的输出:

>       assert 'foo' == 'bar', 'some error message'
E AssertionError: some error message
E assert 'foo' == 'bar'
E - foo
E + bar

但是我们发现,如果我们调用我们在单独模块中定义的断言方法,则不会显示额外的信息。

from custom_asserts import CustomAsserts
asserts = CustomAsserts()
def test_silly():
asserts.silly_assert('foo', 'bar')

运行测试后的输出:

>       assert 'foo' == 'bar', 'some error message'
E AssertionError: some error message

我们还在 pytest 文档中找到了这个:Advanced assertion introspection

pytest only rewrites test modules directly discovered by its test collection process, so asserts in supporting modules which are not themselves test modules will not be rewritten.

所以我的问题是,有没有办法让pytest像测试模块一样对其他模块做同样的断言重写?或者有什么 hacky 的方法可以实现吗?

最佳答案

更新:

Pytest 3.0 引入了一个新方法 register_assert_rewrite 来实现这个特性。如果您使用的是 pytest 3.0 或更高版本,请尝试此操作。 register_assert_rewrite

原答案:

它有点想回答我自己的问题,但我想我找到了解决方案并想分享。

诀窍在于 pytest 如何收集测试模块。我们可以在pytest.ini中定义python_files,这样pytest会把更多的模块当作测试模块。

例如,在我的例子中,我所有的自定义断言模块都以“断言”结尾,所以我的 pytest.ini 是:

[pytest]
python_files = *asserts.py test_*.py *_test.py

另一个棘手的事情是在 conftest.py 中。看来我们必须避免在 conftest.py 中导入 asserts 模块。我的假设是,看起来pytest用于重写断言的技术实际上是重写.pyc文件,并且由于conftest.py是在收集之前加载的,如果我们导入断言module,模块的.pyc会在采集前生成,这可能会导致pytest无法再次重写.pyc文件。

所以在我的 conftest.py 中,我必须做这样的事情:

@pytest.fixture(autouse=Ture)
def setup_asserts(request):
from custom_asserts import CustomAsserts
request.instance.asserts = CustomAsserts()

我会得到额外的错误信息,就像直接在测试脚本中使用关键字 assert 一样。

关于python - 如何让pytest重写非测试模块中的assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38134430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com