use*_*987 3 python pytest pycharm
我是python的新手,并试图为我的第一个应用程序编写测试.简单的app结构:
- app
- tests
__init__.py
- test_main.py
- __init__.py
- main.py
Run Code Online (Sandbox Code Playgroud)
该main.py包含 main_func
test_main.py:
from main import main_func
def test_check():
assert main_func() is True
Run Code Online (Sandbox Code Playgroud)
如果我pytest在app目录中手动运行测试- 得到此错误:
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 ===========================
Run Code Online (Sandbox Code Playgroud)
包名称是对的.此外,我使用PyCharmIDE,它不会跟踪任何导入包错误.
而且,当我通过IDE执行pytest测试配置时 - 测试工作正常.
我认为它在pycharm中运行是因为pycharm项目中的文件夹配置标记.如果在设置中将app文件夹设置为"Source",则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>)
Run Code Online (Sandbox Code Playgroud)