问题描述
我的代码结构是:
+ project
|
+ - - project_code
| | __init__.py
| \ main.py
|
+ - - test
| __init__.py
\ test_main.py
在我的test_main.py中,我有:
In my test_main.py I have:
import unittest
from project_code.main import MainClass
MainClass只是main.py中的一个类
where MainClass is just a class in main.py
然后我导航到项目目录,并运行以下命令:
I then navigate to the project directory, and run the following command:
python -m unittest discover -v
然后我得到一个错误,提示没有模块名称project_code.main
I then get an error saying no module name project_code.main
有什么想法为什么不起作用?
Any ideas why this isn't working?
推荐答案
在您的项目文件夹中放置一个空的__init__.py
使其成为一个包,然后将您的代码更改为
Put an empty __init__.py
in your project folder to make it a package and then either change your code to
import unittest
from project.project_code.main import MainClass
或以相对方式进行
import unittest
from ..project_code.main import MainClass
您的软件包test
中的test_main
将找不到名为project_code
的模块或软件包,因为它希望它位于test
软件包中.
Your test_main
in package test
, will not find a module or package named project_code
, because it expects it to be inside the test
package.
这篇关于单元测试未导入项目模块(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!