【发布时间】:2021-05-04 20:26:00
【问题描述】:
尝试在我的模块上创建单元测试时,我不断收到 ModuleNotFound 错误。 这是我的文件夹结构
- mod1/
- __init__.py
- file1.py
- numbers.py
- tests/
- __init__.py
- test_file1.py
问题出在file1.py有这个说法from numbers import five。
file1.py
from numbers import five
def five_plus_one():
return five()+1
test_file1.py
import unittest
from mod1.file1 import five_plus_one
class MyTestCase(unittest.TestCase):
@unittest.mock.patch('mod1.file1.five')
def test_five_plus_one(self, five_mock):
five_mock.return_value = 7
self.assert_true(8, five_plus_one())
使用鼻子测试,这会产生这个错误
ModuleNotFoundError: No module named 'numbers'
通过多个 stackoverflow 问题,如果尝试了以下内容。
-
删除和添加
__init__.py我尝试在两个地方都删除一个并删除了两个,它并没有改变错误
-
用
@unittest.mock.patch('numbers.five')或@unittest.mock.patch('mod1.numbers.five')替换补丁 -
在
file1.py中使用import numbers而不是from numbers import five -
使用本地导入,但会产生此错误
AttributeError: <module 'mod1.file1' from '/mod1/file1.py'> does not have the attribute 'five'
它唯一有效的一次是如果我将file1.py 修改为from .numbers import five,但它在定期运行代码时会导致此错误
ImportError: attempted relative import with no known parent package
我对 python 很陌生,并不真正了解命名空间及其导入方式。
注意。我将无法修改 PYTHONPATH 或此代码的运行方式。
【问题讨论】:
标签: python python-3.x python-import python-unittest