模拟不';t在用于Python 2.7的unittest中工作

模拟不';t在用于Python 2.7的unittest中工作,python,python-2.7,unit-testing,Python,Python 2.7,Unit Testing,我的项目结构如下: py_test | +---my_module | | | +--- __init__.py (empty) | | | +--- futil.py | +---test | +--- __init__.py (empty) | +--- futil_test.py import mock import unittest from m

我的项目结构如下:

py_test
   |
   +---my_module
   |    |  
   |    +--- __init__.py (empty)
   |    |
   |    +--- futil.py
   |
   +---test
        |
        +--- __init__.py (empty)
        |
        +--- futil_test.py
import mock
import unittest

from my_module.futil import check_exists


class TestExists(unittest.TestCase):

    @mock.patch('my_module.futil.os.path')        # <---leads to error, as well as my_module.os.path
    def test_exists(self, mock_path):
        mock_path.exists.return_value = True
        self.assertTrue(check_exists('ba'))


if __name__ == '__main__':
    unittest.main()
futil.py中,我有以下内容:

from os import path


def check_exists(file_path):
    return path.exists(file_path)
在futil_test.py中我试图实现如下单元测试:

py_test
   |
   +---my_module
   |    |  
   |    +--- __init__.py (empty)
   |    |
   |    +--- futil.py
   |
   +---test
        |
        +--- __init__.py (empty)
        |
        +--- futil_test.py
import mock
import unittest

from my_module.futil import check_exists


class TestExists(unittest.TestCase):

    @mock.patch('my_module.futil.os.path')        # <---leads to error, as well as my_module.os.path
    def test_exists(self, mock_path):
        mock_path.exists.return_value = True
        self.assertTrue(check_exists('ba'))


if __name__ == '__main__':
    unittest.main()
导入模拟
导入单元测试
从my_module.futil导入检查_存在
类TestExists(unittest.TestCase):
@mock.patch('my_module.futil.os.path')#“从操作系统导入路径”,将使路径函数成为futil的一部分。与其模仿“my_module.futil.os.path”,不如模仿“my_module.futil.path”,这样应该可以


我发现这篇文章在过去非常有用

“从操作系统导入路径”,将使路径功能成为futil的一部分。不要嘲笑“my_module.futil.os.path”,只要嘲笑“my_module.futil.path”就行了。哦,该死的,谢谢!事实上,我发现这篇文章在过去非常有用,请把它贴到答案中,这样我就可以把问题标记为已回答