尝试使用未知父包进行自动化测试时出现了相对导入错误

3

我简化后的文件夹结构如下:

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 时,会收到类似的 attempted relative import with no known parent package 错误。

我已经阅读了许多关于这个非常频繁的错误的 SO 评论,但现在比以前更加困惑了。在许多评论中,我看到应该在每个文件夹和子文件夹中放置 __init__.py,但这正是我在这里所做的;然而,相对导入并不起作用。但是如果不导入位于 src.util 中的函数,则无法运行我的自动化测试。我该如何解决这个问题?

1个回答

0

您正在从其目录中运行测试脚本 - Python 无法知道这是包的一部分。尝试切换到项目根目录,然后执行以下操作:

$ 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 错误。 - lazarea
这是来自同一行代码吗?你是在项目根目录下运行吗?如果是,请尝试进入项目根目录的父级目录并运行 python -m pytest -m projectroot.tests.test_util - Mr_and_Mrs_D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接