2

I'm trying to run tests that involve mocking datetime within logbook (for logic around logbook.TimedRotatingFileHandler). But freezegun doesn't reach logbook. Logs print as the current (un-mocked, correct) current time!

my example prints the confusing message

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

for the following 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
4

1 回答 1

2

导入后您正在冻结时间logbook,而不是在模块级别覆盖一些初始化。在冻结时间的范围内移动导入;例子:

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'
于 2019-07-10T08:24:56.230 回答