【问题标题】:Python3 - Pytest directory structure and importsPython3 - Pytest 目录结构和导入
【发布时间】:2017-11-28 06:47:12
【问题描述】:

我有以下项目文件(使用 Python3):

pyproj
├── __init__.py
├── main.py
├── module1.py
├── module2.py
└── tests
    ├── __init__.py
    └── test_module.py

module1 不包含导入。

module2 从模块 1 导入如下:

import module1

main.py 从 module1 和 module2 导入如下:

from module1 import *
from module2 import *

我希望 tests/test_module 能够从模块 2 和模块 1 导入,并且能够使用 pyproj 目录中的 pytest 运行它。但是尝试使用以下方式导入 module2:

 from ..module2 import *

pyproj 目录或tests 目录运行pytest 时会导致以下错误:

tests/test_module.py:1: in <module> from ..module2 import * module2.py:1: in <module> import module1 E ImportError: No module named 'module1'

问题似乎出在 module1 正在导入 module2 时。但是python3 main.py 运行正常。

我尝试了许多更改,但似乎没有一个可以让main.py 和测试都正常工作。构建项目并适当导入文件以执行此操作的正确方法是什么?

【问题讨论】:

    标签: python python-3.x testing pytest


    【解决方案1】:

    在测试中使用绝对导入:from module2 import *,并在运行测试之前将 PYTHONPATH 配置为 pyproj。或者在安装了 pyproj 的虚拟环境中运行测试。或者使用 tox 为你创建这样的 venvs。

    【讨论】:

      【解决方案2】:

      我的解决方案可能不是最佳实践,但经过一些试验后可以工作:

      • 使用 from myproj.module2 导入一些东西

      • 使 PYTHONPATH 包含 myproj

      • 在测试目录中使用 init.py

      我的实验仓库在这里:https://github.com/epogrebnyak/question-package-structure-for-testing/tree/master/which

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-15
        • 2020-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        相关资源
        最近更新 更多