社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Mock在Python 2.7的unittest中不起作用

Anton Pilyak • 4 年前 • 529 次点击  

我的项目结构如下:

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

无用的.py 我有以下资料:

from os import path


def check_exists(file_path):
    return path.exists(file_path)

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()

当我尝试启动单元测试时,它失败并出现错误:

Error
Traceback (most recent call last):
  File "/usr/lib64/python2.7/unittest/case.py", line 367, in run
    testMethod()
  File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1322, in patched
    arg = patching.__enter__()
  File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1378, in __enter__
    self.target = self.getter()
  File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1548, in <lambda>
    getter = lambda: _importer(target)
  File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1235, in _importer
    thing = _dot_lookup(thing, comp, import_path)
  File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1224, in _dot_lookup
    __import__(import_path)
ImportError: No module named os

在这个例子中 here 类似的建设似乎也在起作用。我做错什么了?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50747
 
529 次点击  
文章 [ 1 ]  |  最新文章 4 年前