在终结器中访问 pytest 断言消息

Accessing pytest assert message in finalizer

我正在尝试使用 pytest 生成自定义报告,并尝试访问由 pytest 生成的断言消息,以防失败,在 conftest.py 文件中的全局固定装置的终结器中。我可以访问测试状态,但无法收到错误消息。

我想通过以下方式访问状态消息

@pytest.fixture(scope='function',autouse = True)
def logFunctionLevel(request):
    start = int(time.time() * 1000)
    def fin():
        stop = int(time.time())
        fo = open("/Users/mahesh.nayak/Desktop/logs/test1.log", "a")
        fo.write(request.cls.__name__ + "." + request.function.__name__ + " " + str(start) + " " + str(stop) + "\n")

感谢任何访问异常消息的帮助

谢谢

编辑:Bruno 的回答确实有帮助。添加以下行打印断言。

  l = str(report.longrepr)
  fo.write(l)

我不确定您是否可以从固定装置访问异常消息,但您可以实现自定义 pytest_runtest_logreport 挂钩(未测试):

def pytest_runtest_logreport(report):
    fo = open("/Users/mahesh.nayak/Desktop/logs/test1.log", "a")
    fo.write('%s (duration: %s)\n' % (report.nodeid, report.duration))
    fo.close()

希望对您有所帮助。

要从夹具访问断言消息,您可以按照此处的文档进行操作:

https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures

你的问题看起来像这样:(未经测试的代码)

# content of conftest.py

import pytest


 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
 def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    # set a report attribute for each phase of a call, which can
    # be "setup", "call", "teardown"

    setattr(item, "rep_" + rep.when, rep)


@pytest.fixture
def something(request):
    yield

    # request.node is an "item" because we use the default
    # "function" scope
    error_message= ""
    if request.node.rep_setup.failed:
        print("setting up a test failed!", request.node.nodeid)
        error_message = request.node.rep_setup.longreprtext
    elif request.node.rep_setup.passed:
        if request.node.rep_call.failed:
            print("executing test failed", request.node.nodeid)
            error_message = request.node.rep_call.longreprtext

    fo = open("/Users/mahesh.nayak/Desktop/logs/test1.log", "a")
    if error_message:
        fo.write('%s (duration: %s) - ERROR - %s \n' % (report.nodeid, report.duration,
                                                        error_message))
    else:
        fo.write('%s (duration: %s) - PASSED \n' % (report.nodeid, report.duration))
    fo.close()

与 Bruno Oliveira 回答的主要区别在于 pytest_runtest_logreport 被调用用于 each 不同的测试步骤( setup/call/teardown? ), 当一个 fixture 在测试结束时 只能被调用一次