[英]Python unittest ModuleNotFound for import from same module
I kept getting ModuleNotFound error when trying to create unit test on my module.尝试在我的模块上创建单元测试时,我不断收到ModuleNotFound错误。 Here is my folder structure这是我的文件夹结构
- mod1/
- __init__.py
- file1.py
- numbers.py
- tests/
- __init__.py
- test_file1.py
The problem is in file1.py
there is this statement from numbers import five
.问题出在file1.py
中有这个语句from numbers import five
。
file1.py文件1.py
from numbers import five
def five_plus_one():
return five()+1
test_file1.py 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())
Using nosetests, this will generate this error使用鼻子测试,这将产生此错误
ModuleNotFoundError: No module named 'numbers'
From going through multiple stackoverflow questions, here is what if tried.通过多个 stackoverflow 问题,这里是如果尝试的话。
Removing and adding __init__.py
删除和添加__init__.py
I've tried removing one, in both places and removed both, and it doesn't change the error我已经尝试在两个地方都删除一个并删除了两个,但它并没有改变错误
replace the patch with @unittest.mock.patch('numbers.five')
or @unittest.mock.patch('mod1.numbers.five')
用@unittest.mock.patch('numbers.five')
或@unittest.mock.patch('mod1.numbers.five')
替换补丁
using import numbers
instead of from numbers import five
in file1.py
使用import numbers
而不是from numbers import five
在file1.py
中导入五个
using local import, but it produces this error使用本地导入,但会产生此错误
AttributeError: <module 'mod1.file1' from '/mod1/file1.py'> does not have the attribute 'five'
The only time it ever worked is if I modify file1.py
to have from.numbers import five
but it caused this error when running the code regularly它唯一有效的时候是如果我将file1.py
修改为from.numbers import five
,但在定期运行代码时会导致此错误
ImportError: attempted relative import with no known parent package
I'm quite new to python and don't really understand the namespace and how it imports.我对 python 很陌生,并不真正了解命名空间及其导入方式。
Note.笔记。 I wouldn't be able to modify PYTHONPATH or the way this code is being ran.我将无法修改 PYTHONPATH 或运行此代码的方式。
In file1.py
replace your current import with this:在file1.py
,将您当前的导入替换为:
from mod1.numbers import five
Honestly, I don't know how it works either.老实说,我也不知道它是如何工作的。 Always had to do this for multi-folder projects and never really questioned it.总是必须为多文件夹项目执行此操作,并且从未真正质疑过它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.