Pytest ModuleNotFoundError

Pytest ModuleNotFoundError

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

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

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

traffic.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 如何导入我的模块或误解了我的模块如何相互引用。 $ pipenv run pytest$ pipenv 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