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


当前回答

编辑你的conftest.py并添加以下代码行:

import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), '..')))

如果试图通过终端运行测试用例,请使用以下ex:

python -m pytest test_some_step_file_steps.py --html=HTML_step_file_output.html --self-contained-html

其他回答

我通过在环境变量中为我正在运行测试的特定配置设置PYTHONPATH来解决我的问题。

当你在PyCharm上查看测试文件时:

Ctrl + Shift + A 编辑配置 在Environment >环境变量下设置PYTHONPATH。

更新

移动到项目的根目录 创建虚拟环境 激活新创建的虚拟环境 将变量$PYTHONPATH设置为项目的根目录并导出它:

export PYTHONPATH=$(pwd)

不要从tests/目录或src/目录中删除__init__.py。

还要注意:

你的目录的根目录不是python模块,所以不要添加__init__.py py在项目的根目录中是不必要的。

$PYTHONPATH变量只在当前终端/控制台会话期间可用;所以你每次都需要设置这个。 (如果您正在使用pycharm,可以按照此更新之前的步骤操作)。

另一种特殊情况:

我用毒理剂有问题。所以我的程序运行良好,但通过tox的单元测试一直抱怨。 在安装包(程序所需)之后,您需要在tox.ini中额外指定单元测试中使用的包

[testenv]
deps =
    package1
    package2 
...

我最近也遇到了类似的问题。对我来说,它的工作方式是意识到“setup.py”是错误的

以前我删除了我以前的src文件夹,并添加了一个新的与其他名称,但我没有改变setup.py(新手错误我猜)。

因此,将setup.py指向正确的packages文件夹对我来说很有用

from setuptools import find_packages, setup

setup(
    name="-> YOUR SERVICE NAME <-",
    extras_Require=dict(test=["pytest"]),
    packages=find_packages(where="->CORRECT FOLDER<-"),
    package_dir={"": "->CORRECT FOLDER<-"},
)

另外,不要在test文件夹或根文件夹中使用init.py。

希望它能帮助到别人=)

最好!

保持一切不变,只是在根文件夹中添加了一个空白的测试文件。解决了这个问题

以下是调查结果,这个问题确实困扰了我一段时间。 文件夹结构是

mathapp/
    - server.py  
    - configuration.py 
    - __init__.py 
    - static/ 
       - home.html  
tests/            
    - functional 
       - test_errors.py 
    - unit  
       - test_add.py

和pytest会抱怨ModuleNotFoundError,并给出提示:

确保你的测试模块/包有有效的Python名称。

我介绍了一个与mathsapp和tests目录相同级别的模拟测试文件。文件里什么也没有。现在pytest没有抱怨了。

不包含文件的结果

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error

=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
    from mathapp.service import sum
E   ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================

文件的结果

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items

tests\functional\test_func.py .                                          [ 50%]
tests\unit\test_unit.py .                                                [100%]

============================== 2 passed in 0.11s ==============================

我不同意那些说你必须删除任何__init__.py文件的帖子。相反,您必须更改sys.path。

做个实验,打印sys。路径时正常运行的代码。 然后输出sys。路径,同时通过pytest运行代码。我想你会发现这两条路径之间有区别,这就是为什么pytest会中断。

为了解决这个问题,在第二个实验的第0个索引处插入第一个实验的路径。

让'/usr/exampleUser/Documents/foo'作为实验1的print(sys.path)的第一个元素。

下面是代码,应该解决你的问题:

导入系统 sys。path[0] = '/usr/exampleUser/Documents/foo'

把它放在文件的顶部,在实际的import语句之前。

来源:我自己也在处理这个问题,上面的过程解决了这个问题。