2017-06-25 5 views
0

私は、私が)(datetime.nowモックする必要がDjangoのテストを持っている()私はマイケルFoordのモックライブラリを使用していDjangoのテストモック日時が今

、バージョン1.0.1。
freezegunなどの他のライブラリを使用しないで解決策を探しています。

thisthisインポート日時などのほとんどの例と、それを上書きし、私はそれを上書きしようとしているの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()を使用しています。

+2

は、なぜあなたは日時= FixedDateを使用して日時を上書きしていますか? –

+0

間違いです。それを取り除いた。 – Kemeia

答えて

1

あなたがテストしているモジュールのオブジェクトテストのあるモジュールではありません。あなたのコードに基づいて

最小限の作業例:

app.py

from datetime import datetime 

def my_great_func(): 
    # do something 
    return datetime.now() 

tests.py

from datetime import datetime 
from unittest import mock 
from app import my_great_func 

@mock.patch('app.datetime') 
def test_my_great_func(mocked_datetime): 
    mocked_datetime.now.return_value = datetime(2010, 1, 1) 
    assert my_great_func() == datetime(2010, 1, 1) 
app.pydatetime はパッチが適用されている様子がわかり)

テストの実行結果:

$ pytest -vvv tests.py 
======================= test session starts ========================= 
platform linux -- Python 3.5.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 
cachedir: .cache 
rootdir: /home/kris/projects/tmp, inifile: 
plugins: mock-1.6.2, celery-4.1.0 
collected 1 item             

tests.py::test_my_great_func PASSED 

==================== 1 passed in 0.00 seconds ======================= 
+0

答えをありがとう! ビルドインunittestライブラリでPython3を使用していませんが、Michael Foordの模擬ライブラリでPython2.7を使用しています 回答に続いて、@ mock.patch( 'app.datetime')をインポートしようとしましたが、 。 – Kemeia

+0

@marmai:あなたが持っているエラーを投稿できますか? – kchomski

+0

実際に私はPython 2.7で作業していますが、datetimeオブジェクト(datetime(2017、8、22)やdatetimeなど)を使用するdatetime.nowだけでなく、datetimeオブジェクト全体をオーバーライドしているという問題があります。 .timedelta())不可能 – Kemeia