pytest“没有命名的模块”

2024-06-08 12:56:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在尝试为我的第一个应用程序编写测试。 简单的应用程序结构:

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

main.py包含main_func

测试.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 ===========================

包裹的名字是对的。另外,我使用PyCharmIDE,它不会跟踪任何导入包错误。

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


Tags: pytestapp应用程序initpytestmain错误
1条回答
网友
1楼 · 发布于 2024-06-08 12:56:06

我认为它在pycharm中运行是因为pycharm项目中的文件夹配置标记。如果在设置中将应用程序文件夹设置为“源”,则pycharm可以包含在任何路径中。

详细情况; https://www.jetbrains.com/help/pycharm/2016.1/configuring-folders-within-a-content-root.html

它不在shell中运行,因为它不能包含main。如果要包含并运行,应在sys中插入应用程序路径。

import sys
sys.path.insert(0, <app folder path>)

相关问题 更多 >