pycharm 与命令行 pytest

问题描述 投票:0回答:1

当从 PyCharm 运行我的 pytest 测试套件时,我的所有测试都取得了成功的结果。 运行命令行时,我收到模块导入错误。

folder structure

pytest.ini:

[pytest]
minversion = 7.0
addopts = --cov --cov-report=html:converter_coverage
pythonpath = src/converter
testpaths = 
 tests

样品测试

from converter.question_parser import readSingleFile, getAllQuestionsFromFiles

def test_ifTheLanguageIsDutch_andValidTextInputIsGiven_ThenAQuestionIsMade():   
    foundQuestions = readSingleFile("tests/resources/SingleMinimalQuestion_NL.txt", "NL")
    assert len(foundQuestions) == 1
    
    question = foundQuestions[0]
    assert question.longQuestion == "This is the long question?"
    assert question.shortQuestion == "This is the short question?"
    assert question.answer == "This is the answer"
    assert question.category == "This is the category"
    assert question.round == "This is the round"

错误:

_________________________________________________________________ ERROR collecting tests/test_question_parser.py __________________________________________________________________ 
ImportError while importing test module 'C:\Users\peter\Projects\kwismaster\converter\tests\test_question_parser.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\..\..\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py:90: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test_question_parser.py:1: in <module>
    from converter.question_parser import readSingleFile, getAllQuestionsFromFiles
E   ModuleNotFoundError: No module named 'converter'

pytest test settings

我尝试更改 pytest.ini 中的路径,但什么也没做。 如果我更改导入语句以包含 src.并且 pythonpath 为

. src src/converter
测试将在命令行和 pycharm 中运行,但会出现导入错误,这会禁用 pycharm 点击导航。

任何可以使用 pytest 命令行(用于 jenkins 或 github 操作或...)以及 pycharm(用于第 2 天开发)并具有点击导航功能的解决方案都值得赞赏!

python pycharm pytest
1个回答
0
投票

您可以通过运行以下命令行将 src/ 显式添加到tests/conftest.py 中的sys.path:

python -c "from pathlib import Path;p=Path('tests/conftest.py');s='import os,sys;d=os.path.dirname;p=d(d(__file__));s=os.path.join(p,\'src\');s in sys.path or sys.path.append(s)';p.exists() or p.write_text(s)"
© www.soinside.com 2019 - 2024. All rights reserved.