1

我收到以下错误消息:

BadValueError: Expected datetime, got datetime.datetime(2013, 4, 19, 19, 48, 2, 566558)

ndb 的 model.py 第 1190 行中出现了错误,这里有一段代码。

def _validate(self, value):
    if not isinstance(value, datetime.datetime):
        raise datastore_errors.BadValueError('Expected datetime, got %r' % (value,))

这个 DateTime 被传递到这样的模型中:

#user is a parameter that's passed into the function this code is inside
#the same goes for lifetime, which is a number of seconds

token = os.urandom(16).encode("hex")
expires=datetime.datetime.now() + datetime.timedelta(seconds=lifetime)
instance = cls(token=token, user=user, expires=expires)

但是,我正在使用 pytest 的 monkeypatch 参数对 datetime.datetime 进行monkeypatching。

newnow = datetime.datetime.now()
later = newnow + datetime.timedelta(seconds=10)

class fake_dt(datetime.datetime):
    @classmethod
        def now(cls):
            return newnow

monkeypatch.setattr(datetime,"datetime", fake_dt)
    #after that, I call my model creation function for the test.

我正在猴子修补 datetime.datetime 的事实可能是问题吗?我该如何解决?我需要确保 datetime.datetime.now() 返回我在测试开始时捕获的日期。

4

0 回答 0