我简化后的文件夹结构如下:
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.py
或 py.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
中的函数,则无法运行我的自动化测试。我该如何解决这个问题?
python -m pytest -m tests.test_util
会引发相同的ValueError: attempted relative import beyond top-level package
错误。 - lazareapython -m pytest -m projectroot.tests.test_util
。 - Mr_and_Mrs_D