python - Pytest 模块未找到错误

标签 python python-3.x module pytest python-import

即使我使用 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/

相关文章:

python - 使用 Python 处理 GitHub Wiki 存储库

python - 卡住骰子滚动?

python - 无法连接到 Cosmos 以使用 Python 或 Node.js 客户端查询 Hive

python - 为什么 "column width"设置为不同的值?

mysql - Django保存/更新不更改数据库中的数据

python - 如何在Azure上运行Python3项目?

python - 在 virtualenv 中使用 pip 时如何避免 "Permission denied"

python - 'random' 的独立实例

python - 导入同名的 Python 模块

Angular 2模块通信