pytest日志记录到文件和标准输出

时间:2016-08-30 17:05:08

标签: python pytest logbook

我正在尝试在PyTest测试中设置(function(history) { var pushState = history.pushState; function e(event) { console.log("location: " + document.location + ", state: " + JSON.stringify(event.state)); } function proxyPopstateEvent (evt) { history.pushState = function(state) { if (typeof history.onpushstate == "function") { history.onpushstate({ state: state }); } return pushState.apply(history, arguments); } var proxy = function (e) { this.event = e; this.isBound = false; this.bindPopstateEvent = function() { window.addEventListener('popstate', this.event); history.onpushstate = this.event; this.isBound = true; } this.removePopstateEvent = function() { window.removeEventListener('popstate', this.event); history.onpushstate = {}; } }; window.popstateEventProxy = new proxy(evt); window.popstateEventProxy.bindPopstateEvent(); } if (!window.popstateEventProxy) { proxyPopstateEvent(e); } })(window.history) ,以便将所有内容输出到logbook和文件。该文件应该获得每个日志级别,但stderr应该具有更高的阈值(PyTest将使用它通常的捕获设置来管理)。

我有stderr插件。将pytest-logbook重定向到PyTest捕获,但我不确定如何添加文件输出。

对于知道日志的人来说(希望)这是显而易见的,但这对我来说是新的。

还有一件事,我希望文件记录是实时的。我的测试通常是长时间运行的,PyTest只在失败时显示输出的正常行为在我需要查看是否挂起时无效。

这是我认为应该有效的代码,但不是。我得到了日志文件,但没有stderr / stdout(即使失败):

stderr

conftest.py

import os import pytest import logbook import sys @pytest.fixture(scope='module') def modlog(request): """Logger that also writes to a file.""" name = request.module.__name__ if name.startswith('test_'): name = name[5:] logname = 'TEST-'+name+'.log' if os.path.exists(logname): os.rename(logname, logname+"~") logger = logbook.Logger(name) logger.handlers.append(logbook.FileHandler(logname, level='DEBUG')) logger.handlers.append(logbook.StreamHandler(sys.stdout, level='INFO')) logger.warn("Start of logging") return logger

test_loggy.py

1 个答案:

答案 0 :(得分:4)

Answering my own question (in case other run into the same thing).

The logging handlers form a stack and you have to allow messages to "bubble" through. This is done as an option when the handlers are created.

So the handler creation should be:

logger.handlers.append(logbook.FileHandler(logname, level='DEBUG', bubble=True))
logger.handlers.append(logbook.StreamHandler(sys.stderr, level='INFO', bubble=True))

If you run py.test -s, then you will see the info level messages in real time. If the test fails, the logbook plugin will show all log messages for the failed test (including debug). You will also get a copy in the file (in real time).