我正在用Python编写一个包。我使用virtualenv。我在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路径和补救措施有关,这似乎不是这里的问题。有什么建议吗?


当前回答

注意事项,顺序如下:

确保你的应用程序的每个文件夹和子文件夹都有__init__.py 文件。 确保tests文件夹(模块)在app文件夹(模块)中。 试试pytest命令,如果不行,试试python3 -m pytest。

其他回答

如果它与最初在python 2.7中开发,现在迁移到python 3的python代码有关。X认为这个问题可能与进口问题有关。

如。 当从位于同一目录的file: base导入一个对象时,这在python 2.x中是有效的:

from base import MyClass

在python中3。X你应该替换为基本全路径或。base 不这样做会导致上述问题。 所以尝试:

from .base import MyClass

找到了答案:

如果你计划使用pytest,不要将__init__.py文件放在包含TESTS的文件夹中。我有一个这样的文件,删除它就解决了问题。

这实际上被埋在pytest 'ImportError: No module named YadaYadaYada'的PATH问题的第二个答案的评论中,所以我没有看到它,希望它在这里得到更多的可见性。

将包安装到虚拟环境中。 然后启动一个新的shell并再次源您的虚拟环境。

请查看这里:https://docs.pytest.org/en/documentation-restructure/background/pythonpath.html

我有一个问题与pytest(已解决使用python -m pytest);错误在于

FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.9/site-packages/...

我发现问题是在tests/和tests/子文件夹中缺少__init__.py。

从pytest 7.0开始,你现在可以在pytest.ini中添加pythonpath。不需要在根目录中添加__init__.py或conftest.py。

[pytest]
minversion = 7.0
addopts = --cov=src
pythonpath = src
testpaths =
    tests

可以不带任何参数运行pytest。

https://docs.pytest.org/en/7.0.x/reference/reference.html#confval-pythonpath