【问题标题】:How to (py)test a function that relies on the current time? [duplicate]如何(py)测试依赖于当前时间的函数? [复制]
【发布时间】:2021-04-14 06:48:26
【问题描述】:

我有一个具有以下结构的函数。

def foo(*args, **kwargs):
    # ... code
    now = pd.Timestamp('now', tz=0)
    # ... more code
    return result # result depends on "now" variable

我不能在 foo 执行之前或之后获取时间戳并将其用于与返回值进行比较,因为它与函数内部 now 的值不同。

【问题讨论】:

    标签: python pandas pytest


    【解决方案1】:

    您可以使用时间模拟库,例如。 G。 https://pypi.org/project/freezegun/ 将时间冻结到测试中的已知时刻。

    def test_foo():
        with freezegun.freeze_time("2021-04-14"):
            result = foo()  # assert that result is correct for the above date
    

    【讨论】:

    • 谢谢。也许在答案本身中包含一个小例子?
    • 当然。最初回答时我在手机上,这使得编写代码很乏味。很高兴我能帮上忙!
    • freezegun 似乎不会影响pd.Timestamp('now')。作为一种解决方法,您可以使用pd.Timestamp(datetime.datetime.now())。
    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2019-03-21
    相关资源
    最近更新 更多