Python 3.x 当我将测试放在单独的目录中时,pytest找不到包
我有一个非常基本的Python包示例和一个测试,我正在尝试使用pytest运行它Python 3.x 当我将测试放在单独的目录中时,pytest找不到包,python-3.x,pytest,Python 3.x,Pytest,我有一个非常基本的Python包示例和一个测试,我正在尝试使用pytest运行它 package \-- __init__.py spam.py spam_test.py \uuuu init\uuuu.py为空,spam.py定义单个函数func(),而spam\u test.py为: import package.spam def test_func(): assert(package.spam.func() == 5) 在根目录中,我运行py.test,它
package
\--
__init__.py
spam.py
spam_test.py
\uuuu init\uuuu.py
为空,spam.py
定义单个函数func()
,而spam\u test.py
为:
import package.spam
def test_func():
assert(package.spam.func() == 5)
在根目录中,我运行py.test
,它全部工作,返回一个通过的测试
我想我也可以这样组织事情:
package
\--
__init__.py
spam.py
tests
\--
spam_test.py
但是现在,当我在根目录中运行py.test
时,我得到:
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.0.5, py-1.4.32, pluggy-0.4.0
rootdir: C:\Users\MattUser\Documents\m_drive\notebooks\testing, inifile:
collected 0 items / 1 errors
=================================== ERRORS ====================================
_____________________ ERROR collecting tests/spam_test.py _____________________
ImportError while importing test module 'C:\Users\MattUser\Documents\m_drive\not
ebooks\testing\tests\spam_test.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\spam_test.py:1: in
import package.spam
E ModuleNotFoundError: No module named 'package'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.19 seconds ===========================
===========================================测试会话开始=============================
平台win32——Python 3.6.0、pytest-3.0.5、py-1.4.32、Plugy-0.4.0
rootdir:C:\Users\MattUser\Documents\m\u drive\notebooks\testing,文件:
已收集0项/1个错误
===================================================错误====================================
_____________________收集测试时出错/spam_test.py_____________________
导入测试模块“C:\Users\MattUser\Documents\m\u drive\not”时导入错误
电子书\testing\tests\spam\u test.py'。
提示:确保您的测试模块/包具有有效的Python名称。
回溯:
tests\spam\u test.py:1:in
导入package.spam
E ModuleNotFoundError:没有名为“package”的模块
!!!!!!!!!!!!!!!!!!! 中断:收集过程中出现1个错误!!!!!!!!!!!!!!!!!!!
===========================================0.19秒内出现1个错误===========================
我试过各种各样的方法,但都没有成功。我做错了什么???好吧,我让它工作了。在
tests
目录中添加一个空的\uuuuu init\uuuuuuuuuuuuuuuuuupy
文件
为什么这样做有效?从:
确定basedir
:这是第一个“向上”(朝向根)目录,不包含\uuuu init\uuuuuu.py
因此,如果
测试
不包含\uuuu init\uuuuuu.py
,pytest将其确定为basedir
。添加\uuuu init\uuuuuuuuuuuy.py
强制pytest递归到根目录,从那里它可以导入它需要的内容…我在让一些简单的测试工作时遇到问题,没有意识到它们必须命名为test\u foo
而不是foo\u test
,与文件名不同……这真的是推荐的方法吗?还是只是副作用?