在 Python 中测试时间相关代码时,我如何 "speed up time" 不跳过秒?

When testing time-dependent code in Python, how can I "speed up time" without skipping seconds?

背景

我目前正在为一家公司开展一个项目,他们正在尝试创建软件来管理您在商场中看到的那些电视屏幕大小的动态视频广告。

作为测试软件的一部分,我学会了如何使用 freezegun 包进行 运行 时间冻结在特定值的测试。我还看到它可以选择以秒为单位向前勾选时间:

tick argument

FreezeGun has an additional tick argument which will restart time at the given value, but then time will keep ticking. This is alternative to the default parameters which will keep time stopped.

auto_tick_seconds argument

FreezeGun has an additional auto_tick_seconds argument which will autoincrement the value every time by the given amount from the start value. This is alternative to the default parameters which will keep time stopped. Note that given auto_tick_seconds the tick parameter will be ignored.


问题

上述解决方案的问题在于,为了测试我正在使用的广告牌管理软件的一整天,我需要既要显着加快时间速率又要保持分钟的粒度和秒,因为有些函数需要在其他函数之前执行几秒或几分钟 运行.

如何在不跳过时间的情况下加快时间?

我的解决方案是提取我想测试的核心逻辑(函数),而不是 运行 从实际生产入口点提取程序,然后只需要一个 while 循环向前滴答 1 秒,然后运行我要测试的函数,并在日期时间达到特定值时退出循环:

def test_one_day(self):
    initial_datetime = datetime(year=2018, month=12, day=21)

    with freeze_time(initial_datetime) as frozen_datetime:
        # Set up the test here

        while datetime.now() < initial_datetime + timedelta(days=1):
            # Run whatever code you want here

            frozen_datetime.tick()