【问题标题】:Using local imports in Pytest在 Pytest 中使用本地导入
【发布时间】:2018-11-18 15:00:59
【问题描述】:

我从来没有真正完全理解 Python 是如何处理包的,我现在遇到了问题。但是谷歌搜索似乎没有帮助,因为我发现这个话题真的很混乱。

我有一个具有这种结构的项目:

project_name/
    src/
        main.py
        utils/
            string_utils.py
    tests/
        test_string_utils.py

我正在使用 Pytest 运行单元测试,目前在“test_string_utils.py”文件中我有以下内容:

from ..src.utils.string_utils import StringUtilsClass

但我转到文件夹“project_name”并尝试使用以下任何命令运行测试时出现错误:

$ pytest tests/

ValueError: 尝试相对导入超出顶级包

我知道 python 的 -m 参数,但运行“pytest -m”似乎有完全不同的行为。

我该如何解决这个问题?我使用了错误的文件夹架构吗?我不认为我正在构建的应该是一个 pip 包(这将简化导入)

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您是否尝试过:from src.utils.string_utils import StringUtilsClass 没有 .. 在 src 之前? 或from string_utils import StringUtilsClass

    【讨论】:

    • from src.utils.string_utils import StringUtilsClas 有效。那个怎么样? pytest 自己加载“src”模块吗?
    • "导入包时,Python 会在 sys.path 上的目录中搜索包子目录。" docs.python.org/3/tutorial/modules.html
    猜你喜欢
    • 2022-09-23
    • 2023-04-05
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多