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


当前回答

我的观点是:如果不使用虚拟环境,pytest可能会失败。有时它会起作用,有时则不会。

因此,解决方案是:

使用PIP卸载删除pytest 创建你的venv 激活你的venv PIP在可编辑模式下安装项目路径,因此pytest将它视为一个模块(否则,pytest不会找到您的内部导入)。为此,您需要一个setup.py文件 安装包,包括pytest 最后,运行测试

代码,使用windows PowerShell:

pip uninstall pytest
python.exe -m venv my_env
.\my_env\Scripts\activate
(my_env) pip install -e .
(my_env) pip install pytest pytest-html pandas numpy

最后

(my_env) pytest --html="my_testing_report.html"

一个setup.py的例子,用于pip install -e:

import setuptools

setuptools.setup(
    name='my_package',
    version='devel',
    author='erickfis',
    author_email='erickfis@gmail.com',
    description='My package',
    long_description='My gooood package',
    packages=setuptools.find_packages(),
    classifiers=[
        'Programming Language :: Python :: 3',
        'Operating System :: OS Independent',
    ],
    include_package_data=True
)

其他回答

我也遇到了同样的问题,但原因不是上面提到的那些:

py。测试是全局安装的,而包是安装在虚拟环境中的。

解决方案是在虚拟环境中安装pytest。(如果你的shell像Bash一样散列可执行文件,使用hash -r,或者使用py.test的完整路径)

这是一篇中篇文章!描述问题!

问题在于您使用的是哪个pytest以及您使用的是虚拟环境。 如果您在系统范围内(换句话说,在虚拟环境之外)安装了pytest,那么pytest有一个讨厌的习惯,就是只在虚拟环境之外寻找模块!如果您的项目使用的模块只安装在您的虚拟环境中,并且您正在使用系统范围的pytest,那么即使您激活了虚拟环境,它也不会找到该模块

以下是具体步骤

退出任何虚拟环境 使用Pip卸载pytest 激活项目的虚拟环境 在虚拟环境中安装pytest Pytest现在将找到仅虚拟环境的包!

如果你在终端上运行Pytest:

使用——import-mode=append命令行标志运行pytest。

官方文档中的参数说明:https://docs.pytest.org/en/stable/pythonpath.html


乌利希期刊指南: 之前我也写过如果你使用PyCharm如何做同样的事情,但是社区不喜欢扩展答案,所以我删除了可能对有类似问题的人有帮助的额外信息。

我通常建议使用绝对路径,并从根文件夹或父文件夹运行应用程序和/或测试。

如果有人在Uvicorn的FastAPI中收到这个错误,只需运行例如。

uvicorn app.main:app --host 0.0.0.0 --port 8080

我只是通过删除项目根目录中的__init__.py来解决这个问题:

.
├── __init__.py <--- removed
├── models
│   ├── __init__.py
│   ├── address.py
│   ├── appointment.py
│   └── client.py
├── requirements.txt
├── setup.cfg
├── tests
│   ├── __init__.py
│   ├── models
│   │   ├── __init__.py
│   │   ├── appointment_test.py
│   │   └── client_test.py
│   └── other_test.py
└── script.py