首页 > 解决方案 > pytest_report_teststatus 钩子在会话范围的拆卸固定装置之后执行

问题描述

似乎挂钩函数 pytest_report_teststatus 的拆卸部分/触发器在任何具有 yield 语句的会话范围内的固定装置之后执行。我该如何改变呢?例如,这是我的钩子函数:

def pytest_report_teststatus(report,): 
    """
    Using the pytest hook pytest_report_teststatus.  This will give us
    the test result of each test function.
    Note, this hook can get called up to 3 times for one test funtion.
    Test Setup, Call, and Teardown.  Call is the actual test function.

    This hook function will write out test results for each
    test to the summary.log file.

    """
    sum_log = dnet_generic.get_logger()
    if report.when == 'setup' and report.outcome == 'failed':
        sum_log.info("\n    --------------------------------------")
        sum_log.info("    ---- Test Setup Stage FAILED!")
        sum_log.info(f'    ---- Test: {report.nodeid}' )
        sum_log.info("    --------------------------------------\n")
    elif report.when == 'call':
        now = datetime.datetime.now()
        end_time = now.strftime('%a %b %d %H:%M:%S %Z %Y')
        sum_log.info("\n    --------------------------------------")
        sum_log.info('    ---- Test Function completed at: %s' % (end_time) )
        sum_log.info(f'    ---- Test: {report.nodeid}' )
        sum_log.info(f'    ---- Result: {report.outcome.upper()}' )
        sum_log.info("    --------------------------------------\n")
    elif report.when == 'teardown' and report.outcome == 'failed':
        sum_log.info("\n    --------------------------------------")
        sum_log.info("    ---- Test Teardown Stage FAILED!")
        sum_log.info(f'    ---- Test: {report.nodeid}' )
        sum_log.info("    --------------------------------------\n")

这是带有 yield 语句的会话范围固定装置:

@pytest.fixture(scope="session")
def logger(testinfo):

    sum_log = dnet_generic.get_logger(initialize=True)

    ############################################################
    # Don't like to do this but I'm going to add a new key
    # to testinfo which defines the summary.log logger
    # Since dictionaries are mutable this should work fine....
    ############################################################
    testinfo.update({"sum_log" : sum_log })

    start_time = testinfo['start_time'].strftime('%a %b %d %H:%M:%S %Z %Y')
    script_name = sys.argv[0]
    script_args = sys.argv[1:] # all remaining arguments other than script name
    script_basename = os.path.basename(script_name)

    sum_log.info("\n\n----------------------------------------------------------")
    sum_log.info("----------------------------------------------------------")
    sum_log.info('-----Pytest Session Started' )
    sum_log.info('-----Start Time:: %s' % (start_time) )
    sum_log.info('-----Results for script_name %s' % (script_basename))
    sum_log.info('-----Script Arguments %s' % ' '.join(map(str,script_args)))
    sum_log.info("----------------------------------------------------------")
    sum_log.info("----------------------------------------------------------")

    yield sum_log

    now = datetime.datetime.now()
    end_time = now.strftime('%a %b %d %H:%M:%S %Z %Y')
    script_basename = os.path.basename(script_name)

    sum_log.info("+++++++++++++++++++++++++++++++++++++++++++++")
    sum_log.info("+++++++++++++++++++++++++++++++++++++++++++++")
    sum_log.info('-----Pytest Session Ended' )
    sum_log.info('-----End Time: %s' % (end_time) )
    sum_log.info("+++++++++++++++++++++++++++++++++++++++++++++")
    sum_log.info("+++++++++++++++++++++++++++++++++++++++++++++")

我只有拆解的问题。如果我在一个模块中有 5 个单独的测试函数,则此挂钩会被调用 5 次并将适当的消息写入日志文件,然后会话范围的夹具最后写入日志文件。

这是当另一个“功能范围”夹具在 yield 语句之后失败时日志文件的输出的样子(我需要在“Pytest 会话结束”消息之前出现拆解消息:

+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++
-----Pytest Session Ended
-----End Time: Wed Apr 08 02:48:31  2020
+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++

    --------------------------------------
    ---- Test Teardown Stage FAILED!
    ---- Test: lag/test_preconfig_setup.py::test_lag_load_balance[au22-bundle-28130-4-80-128-True-60-lag_setup_test.yml]
    --------------------------------------

谢谢你

标签: pytest

解决方案


将会话日志从夹具“记录器”传输到与测试会话相关的钩子中。
示例 - “pytest_sessionstart”和“pytest_sessionfinish”
https://docs.pytest.org/en/stable/_modules/_pytest/hookspec.html#pytest_sessionfinish
我的简单检查 -

@pytest.hookspec(firstresult=True)
def pytest_sessionstart(session):

    print("\n+++++++++++++++++++++++++++++++++++++++++++++")
    print('\n-----Pytest Session Started')
    print("\n+++++++++++++++++++++++++++++++++++++++++++++")


@pytest.hookspec(firstresult=True)
def pytest_sessionfinish(session, exitstatus):

    print("\n+++++++++++++++++++++++++++++++++++++++++++++")
    print('\n-----Pytest Session Ended')
    print("\n+++++++++++++++++++++++++++++++++++++++++++++")
  • 使用您的“pytest_report_teststatus”,当夹具在产量后失败时

推荐阅读