When using patch in a mock of Python, you have encountered a possible error spot, specifically recorded.
First use Patch.object, there is no error in it.
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
mocks 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 =
assert fuction_uu () = =
@patch. Object (test_module, ' OS ')
def TEST_RM (mock_os):
rm ("any path") # Test this RM called Os.remove with the right parameters
Mock_os.remove . Assert_called_with ("Any path")
But when using patch, there was a problem. The following code in the Python->run when all OK, but I use the nose frame, is run as UnitTest, the error: "No module named Test_module."
Import nose from
mocks import magicmock,patch from
test_module import fuction_uu,rm
import Test_module
Import mock
@patch (' Test_module.myfuction ', magicmock (return_value =))
def test_faction_uu ():
print Fuction_uu () =
@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 ()
Then I checked the official mock documents to find out what the problem was. The first argument should be "should is a string in the" form ' package.module.ClassName '. "Change to the following code, all OK.
Import nose from
mocks 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 =))
def test_ Faction_uu ():
assert fuction_uu () =
@patch (' Test_mock_fuction.test_module.os ')
def test_rm (mock_os ):
rm ("any path") # Test this RM called Os.remove with the right parameters
Mock_os.remove.assert_called_ With ("Any path")
if __name__ = = ' __main__ ':
test_faction_uu ()
test_rm ()