我正在用 Python 开发一个包。我使用虚拟环境。我在我的 virtualenv 中将路径设置为 .pth 路径中的模块根目录,以便我可以在开发代码时导入包的模块并进行测试(问题 1:这是一个好方法吗?)。这很好用(这是一个例子,这是我想要的行为):
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python
Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from rc import ns
>>> exit()
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python tests/test_ns.py
issued command: echo hello
command output: hello
但是,如果我尝试使用 PyTest,我会收到一些导入错误消息:
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ pytest
=========================================== test session starts ============================================
platform linux2 -- Python 2.7.12, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /home/zz/Desktop/GitFolders/rc, inifile:
collected 0 items / 1 errors
================================================== ERRORS ==================================================
________________________________ ERROR collecting tests/test_ns.py ________________________________
ImportError while importing test module '/home/zz/Desktop/GitFolders/rc/tests/test_ns.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_ns.py:2: in <module>
from rc import ns
E ImportError: cannot import name ns
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
========================================= 1 error in 0.09 seconds ==========================================
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ which pytest
/home/zz/Desktop/VirtualEnvs/VEnvTestRc/bin/pytest
我有点疑惑,这看起来像是导入错误,但 Python 没问题,那么为什么 PyTest 会出现问题?对原因/补救措施有何建议(问题 2)?我用谷歌搜索并堆栈溢出了 PyTest 的“ImportError: cannot import”错误,但我得到的结果与缺少 python 路径和补救措施有关,这似乎不是这里的问题。有什么建议么?
原文由 Zorglub29 发布,翻译遵循 CC BY-SA 4.0 许可协议
找到答案:
如果您计划使用 pytest,请不要将
__init__.py
文件放入包含 TESTS 的文件夹中。我有一个这样的文件,删除它解决了问题。这实际上隐藏在对 PATH 问题的第二个答案的评论中,pytest ‘ImportError: No module named YadaYadaYada’ 所以我没有看到它,希望它能在这里得到更多的关注。