gpt4 book ai didi

python - Pytest 模块未找到错误

转载 作者:行者123 更新时间:2023-12-03 08:49:34 29 4
gpt4 key购买 nike

即使我使用 Python 工作这么久,我仍然偶尔会遇到包结构的问题。

我正在尝试从下面的目录结构的根目录运行$ pipelinenv run pytest(即src/上方的..)

src/
physics/
__init__.py
pathing.py
road/
tests/
__init__.py
test_traffic.py
__init__.py
traffic.py
__init__.py
main.py

交通.py:


from physics import pathing

class Intersection():
...

class Vehicle():
...

test_traffic.py


from src.road.traffic import Intersection, Vehicle

def test_intersection():
...

但是,我受到以下打击:

======================================================================= ERRORS ========================================================================
___________________________________________________ ERROR collecting src/road/tests/test_traffic.py ___________________________________________________
ImportError while importing test module '/Users/justian/scripts/py-traffic-sim/src/road/tests/test_traffic.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
src/road/tests/test_traffic.py:1: in <module>
from src.road.traffic import Intersection, Vehicle
src/road/traffic.py:13: in <module>
from physics import pathing
E ModuleNotFoundError: No module named 'physics'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
================================================================== 1 error in 0.38s ===================================================================

看起来我误解了 pytest 如何导入我的模块,或者误解了我的模块如何相互引用。 $ pipelinenv run pytest$ pipelinenv run python -m pytest 产生相同的结果。

如何正确地将 IntersectionVehicle 导入到 test_traffic.py 中?

最佳答案

src中删除__init__.py文件。

例如

src/
physics/
__init__.py
pathing.py
road/
tests/
__init__.py
test_traffic.py
__init__.py
traffic.py
__init__.py # Remove this one
main.py

关于python - Pytest 模块未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59834619/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com