PyCharm中pytest测试正常,命令行运行遇模块导入错误求助
问题:PyCharm中pytest测试正常,命令行运行出现模块导入错误
场景描述
在PyCharm中运行pytest测试套件时所有测试均成功,但通过命令行运行时出现模块导入错误。
项目配置与代码信息
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.ini中的路径配置,无效果
- 修改导入语句为
from src.converter.question_parser import ...,并设置pythonpath = . src src/converter,命令行测试可运行,但PyCharm中的代码跳转导航功能失效
需求
寻求兼容命令行与PyCharm运行,同时保留PyCharm代码跳转导航功能的解决方案。
内容的提问来源于stack exchange,提问作者ShadowFlame
相关产品推荐
相关产品推荐

