2017-12-28 23 views
1

「assert_called_once_with」属性私はpytestを使用して、次のテストを実行しようとしているとpytest_mock「関数」オブジェクトには

def rm(filename): 
    helper(filename, 5) 

def helper(filename): 
    pass 

def test_unix_fs(mocker): 
    mocker.patch('module.helper') 
    rm('file') 
    helper.assert_called_once_with('file', 5) 

を持っていないしかし、私はAttributeError: 'function' object has no attribute 'assert_called_once_with'

は私が間違って何をやっている例外を取得しますか?

答えて

2

バニラ機能で.assert_called_once_with機能を実行することはできません。まず、mock.create_autospecデコレータでラップする必要があります。だから、例えば:

エレガント
import unittest.mock as mock 

def rm(filename): 
    helper(filename, 5) 

def helper(filename): 
    pass 

helper = mock.create_autospec(helper) 

def test_unix_fs(mocker): 
    mocker.patch('module.helper') 
    rm('file') 
    helper.assert_called_once_with('file', 5)

以上:

import unittest.mock as mock 

def rm(filename): 
    helper(filename, 5) 

@mock.create_autospec 
def helper(filename): 
    pass 

def test_unix_fs(mocker): 
    mocker.patch('module.helper') 
    rm('file') 
    helper.assert_called_once_with('file', 5)

アサーションが失敗することに注意してください、あなただけ'file'でそれを呼び出すことから。だから、有効なテストは次のようになります。

import unittest.mock as mock 

def rm(filename): 
    helper(filename, 5) 

@mock.create_autospec 
def helper(filename): 
    pass 

def test_unix_fs(mocker): 
    mocker.patch('module.helper') 
    rm('file') 
    helper.assert_called_once_with('file')

EDIT:関数は、いくつかのモジュールで定義されている場合は、ローカルにデコレータでそれをラップすることができます。たとえば:オブジェクト指向場合

import unittest.mock as mock 
from some_module import some_function 

some_function = mock.create_autospec(some_function) 

def test_unix_fs(mocker): 
    some_function('file') 
    some_function.assert_called_once_with('file')
+1

は、私はそれをクリック&覚えることができるように、SOお気に入りの答えと星があればいいのに。 – Axalix

+0

問題は、他のモジュールで 'helper'関数が定義されていることです。アプリケーションコードに '@ mock.create_autospec'のようなテスト項目を追加するのは良い考えではないと思います。 –

+0

@ Overflow012:そうする必要はありません。モジュールから関数を取得し、デコレータをローカルに追加することができます。 –

0

class Foo: 
    def rm(self, filename): 
     self.helper(filename, 5) 

    def helper(self, filename, number): 
     pass 

def test_unix_fs(mocker): 
    mocker.patch.object(Foo, 'helper') 
    foo = Foo() 
    foo.rm('file') 
    helper.assert_called_once_with('file', 5) 
関連する問題