关于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")
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()
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()