How to mock python's datetime.now() in a class method for unit testing?

前端 未结 7 1235
南旧
南旧 2020-12-14 05:38

I\'m trying to write tests for a class that has methods like:

import datetime
import pytz

class MyClass:
    def get_now(self, timezone):
        return dat         


        
7条回答
  •  太阳男子
    2020-12-14 06:17

    You'd create a function that returns a specific datetime, localized to the timezone passed in:

    import mock
    
    def mocked_get_now(timezone):
        dt = datetime.datetime(2012, 1, 1, 10, 10, 10)
        return timezone.localize(dt)
    
    @mock.patch('path.to.your.models.MyClass.get_now', side_effect=mocked_get_now)
    def your_test(self, mock_obj):
        # Within this test, `MyClass.get_now()` is a mock that'll return a predictable
        # timezone-aware datetime object, set to 2012-01-01 10:10:10.
    

    That way you can test if the resulting timezone-aware datetime is correctly being handled; results elsewhere should show the correct timezone but will have a predictable date and time.

    You use the mocked_get_now function as a side-effect when mocking get_now; whenever code calls get_now the call is recorded by mock, and mocked_get_now is called, and it's return value used as the value returned to the caller of get_now.

提交回复
热议问题