如何在日志上使用freezegun

时间:2019-07-09 22:24:40

标签: python pytest freezegun logbook

我正在尝试运行涉及在日志中模拟日期时间的测试(用于logbook.TimedRotatingFileHandler周围的逻辑)。但是freezegun没有达到日志。日志打印为当前(未模拟,正确)的当前时间!

我的示例打印出令人困惑的消息

[2019-07-09 22:01:21.583288] INFO: None: test time: 2000-01-01 00:01:00

对于以下pytest

from freezegun import freeze_time
import logbook
import sys
import datetime as dt

def test_logbook():
    faketime = freeze_time('2000-01-01 00:01')
    faketime.start()
    assert dt.datetime.now().strftime('%Y%d%m') == '20000101'
    log = logbook.Logger()
    log.handlers.append(logbook.StreamHandler(sys.stdout))
    log.info('test time: ' + str(dt.datetime.now()))
    faketime.stop()
    assert 0

1 个答案:

答案 0 :(得分:1)

您正在冻结导入logbook之后的时间,而没有涵盖模块级别的某些init。在冻结的时间范围内移动导入;例如:

from freezegun import freeze_time
import sys
import datetime as dt

def test_logbook(capsys):
    with freeze_time('2000-01-01 00:01'):
        import logbook
        assert dt.datetime.now().strftime('%Y%d%m') == '20000101'
        log = logbook.Logger()
        log.handlers.append(logbook.StreamHandler(sys.stdout))
        log.info('hello world')
    assert capsys.readouterr().out == '[2000-01-01 00:01:00.000000] INFO: None: hello world\n'