2016-08-14 2 views
3

私は電子メールの件名とメッセージをフォーマットするsend_formatted_emailという関数を書いて、別のモジュールのsend_email関数を呼び出します。モックがモジュール機能で動作しない

ここで、send_formatted_emailが期待される引数でsend_emailを呼び出していることをテストする必要があります。この目的のために私はpatchを使ってsend_emailを嘲笑しようとしていますが、嘲笑されていません。

test.py

@patch('app.util.send_email') 
def test_send_formatted_email(self, mock_send_email): 
    mock_send_email.return_value = True 
    response = send_formatted_email(self.comment, to_email) 
    mock_send_email.call_args_list 
    .... 

views.py

def send_formatted_email(comment, to_email): 
    ... 
    message = comment.comment 
    subject = 'Comment posted' 
    from_email = comment.user.email 
    ... 
    return send_email(subject, message, to_email, from_email) 

util.py

def send_email(subject, message, to, from): 
    return requests.post(
     ... 
    ) 

私もapp.util.send_email = MagicMock(return_value=True)を試してみましたが、これはどちらか動作しませんでした。私が間違って何をしているのか?

+3

*定義されている場所ではなく、関数が*使用されている箇所にパッチを当てます。 '@patch( 'app.views.send_email')' – jonrsharpe

+0

[モックの@patchを使って別のPythonモジュールで定義された関数をモックする方法(http://stackoverflow.com/questions/14654009/how-機能別に定義された別のPythonモジュールを使用した模擬パッチ) – jonrsharpe

+0

@jonrsharpeありがとうございました。 –

答えて

1

既に言及したように、jonrsharpeは既にanother questionの下に回答があります。

私のケースでは、提供されている選択肢の1つ(自分のモジュールをリロードまたはパッチする)を使用できませんでした。

しかし、私は今ちょうど、使用する前に必要な方法をインポートする:あなたはそれをパッチを適用した後

def send_formatted_email(comment, to_email): 
    ... 
    message = comment.comment 
    subject = 'Comment posted' 
    from_email = comment.user.email 
    ... 
    from app.util import send_email 
    return send_email(subject, message, to_email, from_email) 

これはモジュール方式をロードします。

短所:

  • インポートは、各メソッド呼び出しの前に実行されます。
関連する問題