python mock patch 的使用

关于python 的mock中使用patch时,遇到了一个可能出错的地方,特别记录下来。

首先使用patch.object,这里面是不会出错的。

test_module.py

import os
def rm(filename):
    os.remove(filename)


def myfuction():
    return 2


def fuction_uu():
    return myfuction()

test_mock_fuction.py

import nose
from mock import MagicMock,patch
from test_module import fuction_uu,rm
import test_module
import mock


@patch.object(test_module,'myfuction')
def test_faction_uu(mock_myfuction):
    mock_myfuction.return_value = 13
    assert  fuction_uu() == 13
    
@patch.object(test_module,'os')
def test_rm(mock_os):
    rm("any path")        # test that rm called os.remove with the right parameters
    mock_os.remove.assert_called_with("any path")  


但是在使用patch的时候,出了问题。下面的代码在python->run的时候一切OK,但是我用nose框架的时候,就是run as unittest的时候,报错:“no module named test_module"。

import nose
from mock import MagicMock,patch
from test_module import fuction_uu,rm
import test_module
import mock


@patch('test_module.myfuction',MagicMock(return_value = 13))
def test_faction_uu():
    print fuction_uu() == 13
    
@patch('test_module.os')
def test_rm(mock_os):
    rm("any path")        # test that rm called os.remove with the right parameters
    mock_os.remove.assert_called_with("any path")        


if __name__ == '__main__':
    test_faction_uu()
    test_rm()


后来去查了一下mock的官方文档,才找到问题所在。第一个参数应该是”should be a string in the form‘package.module.ClassName’. “,改成下面的代码,一切OK!

import nose
from mock import MagicMock,patch
from test_module import fuction_uu,rm
import test_module
import mock


@patch('test_mock_fuction.test_module.myfuction',MagicMock(return_value = 13))
def test_faction_uu():
    assert fuction_uu() == 13
    
@patch('test_mock_fuction.test_module.os')
def test_rm(mock_os):
    rm("any path")        # test that rm called os.remove with the right parameters
    mock_os.remove.assert_called_with("any path")        


if __name__ == '__main__':
    test_faction_uu()
    test_rm()





你可能感兴趣的:(python)