pytest "No module named" 错误

3

我是Python的新手,正在尝试为我的第一个应用程序编写测试。

简单的应用程序结构:

- app
      - tests
        __init__.py
        - test_main.py
      - __init__.py
      - main.py

main.py包含main_func

test_main.py:

from main import main_func

def test_check():
    assert main_func() is True

如果我手动运行测试,在app目录下输入命令pytest - 会出现以下错误:
C:\Users\*****\PycharmProjects\checker3>pytest
============================= test session starts =============================
platform win32 -- Python 3.5.2, pytest-3.0.3, py-1.4.31, pluggy-0.4.0
rootdir: C:\Users\*****\PycharmProjects\app, inifile:
collected 0 items / 1 errors 

=================================== ERRORS ====================================
_____________________ ERROR collecting tests/test_main.py _____________________
ImportError while importing test module 'C:\Users\*****\PycharmProjects\app\tests\test_main.py'.
Original error message:
'No module named 'main''
Make sure your test modules/packages have valid Python names.
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.14 seconds ===========================

包名是正确的。此外,我使用 PyCharm 集成开发环境,它没有跟踪到任何导入包错误。

此外,当我通过IDE执行pytest测试配置时,测试是正常工作的。


1
tests文件夹中,你需要一个空的__init__.py文件。 - 2ps
我已经删除了,现在刚刚添加 - 没有任何更改。 - user1935987
像魔法一样运作良好。 - Alexander.Iljushkin
1个回答

7
我认为它能在PyCharm中运行,是因为在PyCharm项目中标记了文件夹配置。如果您在设置中将应用程序文件夹设置为“Source”,则PyCharm可以包含任何路径。
具体详情请参见:https://www.jetbrains.com/help/pycharm/2016.1/configuring-folders-within-a-content-root.html 它无法在shell中运行,因为无法包含主要文件。如果您想要包含并运行,则应该在sys中插入应用程序路径。
import sys
sys.path.insert(0, <app folder path>)

没错,我已经这样做了。 在PyCharm中运行没有问题。问题是为什么它不能通过“pytest”命令运行。 - user1935987
我添加了详细说明,如何在shell中运行测试。 - umut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接