简体   繁体   English

模拟时间戳单元测试 Python

[英]Mock timestamp Unit Test Python

I have that code:我有那个代码:

from datetime import datetime, timedelta
    def func():
   
        date = datetime.today() - timedelta(days=1)
        timestamp = (str(date.timestamp()).split(".")[0]) + "000"
    
        return DataAccess().get(
            sort_key="CampaignRecipientsReport#" + timestamp,
        )

Now I need to mock a variable timestamp to use it in my unit test现在我需要模拟一个变量时间戳以在我的单元测试中使用它

mock_data_access.return_value.get.assert_called_once_with(
      sort_key="CampaignRecipientsReport#" + timestamp,
)

No, you don't need to mock the function's local variable timestamp .不,您不需要模拟函数的局部变量timestamp Instead you need to redesign your function.相反,您需要重新设计您的 function。 You problem is, that your function is state-dependent and thusly has side-effects.你的问题是,你的 function 是状态相关的,因此有副作用。

Ie you should be able to pass in the timestamp.即你应该能够传递时间戳。 If you frequently need the current datetime, you can default it to that value iff no value was specified.如果您经常需要当前日期时间,则可以将其默认为该值,前提是未指定任何值。 This makes the function more flexible, less state-dependent and testable.这使得 function 更加灵活,状态依赖性和可测试性更低。

from datetime import datetime, timedelta
from typing import Optional


def func(timestamp: Optional[datetime] = None):
   
    if timestamp is None:
        timestamp = datetime.today() - timedelta(days=1)

    timestamp = (str(timestamp.timestamp()).split(".")[0]) + "000"
    
    return DataAccess().get(
        sort_key="CampaignRecipientsReport#" + timestamp
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM