【问题标题】:Attempted relative import with no known parent package when doing automated testing进行自动化测试时尝试在没有已知父包的情况下进行相对导入
【发布时间】:2021-12-30 20:40:31
【问题描述】:

我的简化文件夹结构是:

projectroot/
 __init__.py
 src/
   __init__.py
   util.py
 tests/
   __init__.py
   test_util.py

util.py我有如下功能:

def build_format_string(date: bool = True, time: bool = True) -> str:
    format_str = ""
    if date: 
        format_str += "%Y-%m-%d"
    if time:
        if format_str[-1] != " ":
            format_str += " "
        format_str += "%H:%M:%S"
    return format_str

我在test_util.py里面写了对应的test_build_format_string函数如下:

from ..src.util import build_format_string
import pytest 

@pytest.mark.parametrize('date, time, expected', [(True, True, "%Y-%m-%d %H:%M:%S")])
def test_build_format_string(date, time, expected):
    assert type(date) == bool , f"date arg of build_format_string must be boolean, not {type(date)}!"
    assert type(time) == bool , f"time arg of build_format_string must be boolean, not {type(time)}!"
    assert build_format_string(date, time) == expected,  f"""Result of build_format_string when called with date={date} and time={time} 
                                                             must be {expected}; got {build_format_string(date, time)} instead."""

从命令行以python -m pytest test_util.pypy.test test_util.py 运行自动化测试时,我收到attempted relative import beyond top-level package 错误消息,而在我的代码编辑器中以调试模式运行test_util.py 时,我收到类似的@987654331 @错误。

我已经阅读了一堆关于这个非常频繁的错误的 SO cmets,但我现在比以前更加困惑。在许多情况下,我读到__init__.py 应该放在每个文件夹和子文件夹中,但这正是我在这里所拥有的;仍然,相对导入不起作用。但是如果不导入位于src.util 中的函数,我就无法运行我的自动化测试。我怎样才能让它工作?

【问题讨论】:

    标签: python pytest python-import importerror relative-import


    【解决方案1】:

    您正在从其目录中运行测试脚本 - python 无法知道这是包的一部分。尝试 cd 到 projectroot 并从那里:

    $ python -m pytest -m tests.test_util # note no py
    

    【讨论】:

    • 遗憾的是,这并不能解决错误。在命令提示符下运行 python -m pytest -m tests.test_util 会引发相同的 ValueError: attempted relative import beyond top-level package 错误。
    • 来自同一行代码?你是从 projectroot 运行的吗?如果是,请尝试转到 porojectroot 的父级并运行 python -m pytest -m projectroot.tests.test_util
    猜你喜欢
    • 2020-11-03
    • 2019-07-31
    • 1970-01-01
    • 2021-11-24
    • 2020-10-13
    • 2021-02-07
    • 2021-10-31
    • 2021-10-20
    • 2021-12-19
    相关资源
    最近更新 更多