简体   繁体   中英

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 . Instead you need to redesign your function. You problem is, that your function is state-dependent and thusly has side-effects.

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.

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
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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