私は、私が)(datetime.nowモックする必要がDjangoのテストを持っている()私はマイケルFoordのモックライブラリを使用していDjangoのテストモック日時が今
、バージョン1.0.1。
freezegunなどの他のライブラリを使用しないで解決策を探しています。
thisとthisインポート日時などのほとんどの例と、それを上書きし、私はそれを上書きしようとしているのdatetime.datetimeとイムをインポートしていて、何らかの理由で、これは動作しません。
オーバーライド日時は動作します:
import mock
import datetime
class FixedDate(datetime.datetime):
@classmethod
def now(cls):
return cls(2010, 1, 1)
@mock.patch('datetime.datetime', FixedDate)
def myTest():
print(datetime.datetime.now())
myTest()
しかし、私はこのような何かをdatetime.datetimeのを輸入してやりたい:
import mock
from datetime import datetime
class FixedDate(datetime):
@classmethod
def now(cls):
return cls(2010, 1, 1)
@mock.patch('datetime', FixedDate)
def myTest():
print(datetime.now())
myTest()
は、これは例外TypeErrorが発生します。パッチに有効なターゲットが必要です。あなたは 'datetime'を指定しました。
モックライブラリも述べている:
target should be a string in the form ‘package.module.ClassName’. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling patch from.
だけで日時やないdatetime.datetimeのパスに方法はありますか?
Nb。私もthisの例を見ましたが、datetime.now()を使用する関数が1つもありません。なぜなら、私のビューはdatetime.now()を使用しています。
は、なぜあなたは日時= FixedDateを使用して日時を上書きしていますか? –
間違いです。それを取り除いた。 – Kemeia