尝试记录py.test设置,调用和拆卸持续时间会导致日志输出的意外顺序

时间:2015-08-26 19:48:40

标签: python logging pytest

我使用的是Python 3.4.3和pytest-2.7.2。在文档之后,我在conftest.py中写了这个:

import logging
import time

import pytest


logging.basicConfig(
    level='INFO',
    handlers=(
        logging.StreamHandler(),
        logging.FileHandler('log.txt')
    )
)

@pytest.mark.hookwrapper
def pytest_runtest_teardown(item, nextitem):
    logging.info('%s TEARDOWN >>>', item.nodeid)
    start = time.time()
    outcome = yield
    end = time.time()
    logging.info('%s TEARDOWN <<< %fs', item.nodeid, end - start)

一个简单的test.py:

def test_something():
    pass

使用py.test test.py -vvv,显示问题。请注意,日志消息,我希望py.test隐藏,转义并稍后打印(在摘要行之后)。

======= test session starts ======
...snip...

test.py::test_something PASSED


==== 1 passed in 0.03 seconds ====
INFO:root:test.py::test_something TEARDOWN <<< 0.000368s

添加-s以避免捕获,按预期显示所有内容:

======= test session starts ======
...snip...

test.py::test_something PASSEDINFO:root:test.py::test_something TEARDOWN >>>
INFO:root:test.py::test_something TEARDOWN <<< 0.000207s


==== 1 passed in 0.02 seconds ====

现在,这个例子有点简化了。在我的实际conftest.py中,我也为pytest_runtest_setup()和pytest_runtest_call()输出了相同类型的日志记录。

log.txt对于两个调用都很好:

INFO:root:test.py::test_something TEARDOWN >>>
INFO:root:test.py::test_something TEARDOWN <<< 0.000207s
INFO:root:test.py::test_something TEARDOWN >>>
INFO:root:test.py::test_something TEARDOWN <<< 0.000326s

我甚至实现了pytest_unconfigure(),它在运行结束时打印(使用print)一些链接。设法转义的消息(仅指定-s)甚至显示在该内容之后!

使用py.test --debug,你可以看到pytest_runtest_teardown()的范围不应该包含pytest_unconfigure():

...snip...
        pytest_runtest_teardown [hook]
            item: <Function 'test_something'>
            nextitem: None
        finish pytest_runtest_teardown --> [] [hook]
...snip...
      finish pytest_runtest_protocol --> True [hook]
    finish pytest_runtestloop --> True [hook]
    pytest_sessionfinish [hook]
...snip...
    finish pytest_sessionfinish --> [] [hook]
    pytest_unconfigure [hook]
        config: <_pytest.config.Config object at 0x7f8a46be6a90>
    finish [config:tmpdir]

我不确定这是不是py.test错误(在hookwrapper或输出捕获中,也许?)或某种日志记录缓冲咬我...有什么想法吗?

0 个答案:

没有答案