【发布时间】:2018-09-26 19:09:09
【问题描述】:
我目前正在尝试使用 mock 来测试一个包。当我使用 __init__.py 在不同目录中构建我的 python 模块时,Mock 似乎不喜欢它
我的文件树如下:
.\pkg
|_ module
|_ __init__.py
|_ module.py
|_ tests
|_ __init__.py
|_ test_basic.py
当我尝试使用以下单元测试模拟文件大小中的方法时:
@mock.patch('module.os')
def test_filesize(self, mock_os):
class file_info:
st_size = 1000
mock_os.path.isfile.return_value = True
mock_os.stat.return_value = file_info
output = self.response.file_size("filename")
我得到一个错误的回溯:
======================================================================
ERROR: test_filesize (__main__.cl_test_build_search_url)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\mock\mock.py", line 1297, in patched
arg = patching.__enter__()
File "C:\Python36\lib\site-packages\mock\mock.py", line 1369, in __enter__
original, local = self.get_original()
File "C:\Python36\lib\site-packages\mock\mock.py", line 1343, in get_original
"%s does not have the attribute %r" % (target, name)
AttributeError: <module 'module' from 'C:\\Users\\username\\work\\open_source\\pkg\\module\\__init__.py'> does not have the attribute 'os'
我已经在module.py 中导入了 os 模块,但我认为它会变得混乱,因为__init__.py 会混淆解释器?
我查看了可用的 mock.patch 参数和
@mock.patch('module.os', create = True)
允许代码运行,但 os 根本不会被模拟,os.path.isfile 和 os.stat 在运行时不会被覆盖。
【问题讨论】:
标签: python unit-testing mocking python-unittest