【发布时间】: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.py 或py.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