gpt4 book ai didi

python - 如何在断言上调用方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:46 25 4
gpt4 key购买 nike

我试图在断言发生时和调用任何清理代码之前捕获尽可能多的信息。下面是我们大多数现有测试的简化代码:

在我的conftest.py中:

import pytest
from datetime import datetime

def pytest_runtest_makereport(item, call):
print('%s: pytest_runtest_makereport(%s)' % (datetime.now(), call))

def pytest_exception_interact(node, call, report):
print('\n%s: pytest_exception_interact' % datetime.now())

在我的测试文件中:

import pytest
from datetime import datetime

@pytest.fixture(scope='function')
def marshall_me():
print('\n%s: starting test' % datetime.now())
yield marshall_me
print('\n%s: ending test' % datetime.now())

class Device(object):
def __enter__(self):
print('\n%s: create object' % datetime.now())
return self

def __exit__(self, type, value, traceback):
print('\n%s: clean-up object' % datetime.now())

def test_fails(marshall_me):
with Device():
assert False

当我运行这个时,我得到:

test_fails.py::test_fails  2017-04-26 17:07:37.447359: starting test
2017-04-26 17:07:37.447453: pytest_runtest_makereport(<CallInfowhen='setup' result: []>)
2017-04-26 17:07:37.447583: create object
2017-04-26 17:07:37.448397: clean-up object
2017-04-26 17:07:37.448614: pytest_runtest_makereport(<CallInfowhen='call' exception: assert False>)
FAILED
2017-04-26 17:07:37.462267: pytest_exception_interact
2017-04-26 17:07:37.462353: ending test
2017-04-26 17:07:37.462428: pytest_runtest_makereport(<CallInfo when='teardown' result: []>)

我无法使用 pytest_runtest_makereport 和 pytest_exception_interact 因为它们在清理函数之后被调用,这样我就无法收集重要信息了。在实际生成断言时是否有其他类似的函数被调用?

最佳答案

您有断言语句的替代形式:

assert <cond>, <expr>

这意味着解释器首先评估条件,如果条件为假,它将评估用作 AssertionError 参数的表达式。因此,要在断言失败时调用函数,您可以使用:

assert condition_to_be_true(), function_to_call_if_not_true()

请注意,function_to_call_if_not_true() 的返回值将用作 AssertionError 的参数。如果这不是您想要的,您将需要采取一些技巧来更改表达式的结果 - 您可以使用 bool 运算符来做到这一点。无论x是什么,表达式(x和False)或y都会计算为y(根据Python的短路规则)。

要结束它,你会这样做:

assert condition_to_be_true(), (function_to_call_if_not_true() 
and False) or ARGUMENT_TO_AssertionError

另一种方法是在必要时滥用语言(这应该被认为是邪恶的)。由于断言语句相当于在确认条件为假后引发 AssertionError 你可以简单地重新定义它:

class AssertionError(Exception):
def __init__(self, *args, **kwds):
Exception(self, *args, **kwds)
print("Assertion")

assert condition_to_check()

请注意,您需要重新定义的是 assert 语句当前范围内的 AssertionError 值。

关于python - 如何在断言上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43625626/

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