如何在用于单元测试的类方法中模拟python的datetime.now()? [英] How to mock python's datetime.now() in a class method for unit testing?
问题描述
我正在尝试为具有以下方法的类编写测试:
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 datetime.datetime.now(timezone)
def do_many_things(self, tz_string='Europe/London'):
tz = pytz.timezone(tz_string)
localtime_now = self.get_now(tz)
...
return things
我想测试它,为此,我需要确保datetime.datetime.now()
调用返回可预测的结果.
I want to test it, and to do so I need to make sure that the datetime.datetime.now()
call returns something predictable.
我一直在阅读许多在测试中使用模拟的示例,但是找不到与我需要的东西完全一样的东西,而且我无法确定如何在测试中使用它.
I've been reading lots of examples of using Mock in tests, but haven't found anything quite like what I need, and I can't work out how to use it in my tests.
我将get_now()
方法分离出来,以防更容易模拟它,而不是datetime.datetime.now()
,但是我仍然很困惑.关于如何使用Mock为此编写UnitTest的任何想法? (这一切都在Django中,fwiw;在这种情况下,我不确定是否会有所不同.)
I separated the get_now()
method out in case it's easier to mock that, instead of datetime.datetime.now()
, but I'm still stumped. Any thoughts on how to write UnitTests for this using Mock? (This is all in Django, fwiw; I'm not sure if this makes a difference in this case.)
推荐答案
您将创建一个函数,该函数返回特定的日期时间,该日期时间本地化为传入的时区:
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.
在模拟get_now
时,可以将mocked_get_now
函数用作副作用.每当代码调用get_now
时,调用都会被mock
,和 mocked_get_now
记录下来,并且其返回值用作返回给get_now
的调用者的值.
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
.
这篇关于如何在用于单元测试的类方法中模拟python的datetime.now()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!