python - 单元测试结构和导入
问题描述
我想知道如何在我的测试文件中正确导入文件而不使用__init__.py
测试根文件夹。本文的最后一句指出,该test
目录不应该有init
文件。
我对python不太了解,所以我想知道:1)为什么不 2)如何在不使用文件作为插入PYTHONPATHS路径的脚本的情况下将文件导入tested.py
到其中test_main.py
以测试其功能?init
我的项目具有以下结构
.
├── __init__.py
├── my
│ ├── __init__.py
│ ├── main.py
│ └── my_sub
│ ├── __init__.py
│ └── tested.py
└── test
└── test_main.py
文件包含以下代码
#/Python_test/__init__.py
import my.main
#/Python_test/my/__init__.py
#empty
#/Python_test/my/main.py
from .my_sub.tested import inc
print(inc(5))
#/Python_test/my/my_sub/__init__.py
#empty
#/Python_test/my/my_sub/tested.py
def inc(x):
return x+1
#/Python_test/test/test_main.py
from Python_pytest.my.my_sub.tested import func
def test_answer():
assert func(3) == 3
当我从命令行 python 运行代码时,__init__.py
它会打印 6,这是正确的。
我想测试文件中的inc()
功能tested.py
。1. 我安装了pytest
包作为测试框架,
2. 创建了类似于教程中的测试文件test_main.py
。3.添加__init__.py
了找到根目录的路径并将其添加到的代码sys.path
它运作良好,但后来我读到不应该这样做。但是应该怎么做呢?我很难从一些经过测试且不使用 init 文件的 github 存储库中读取一些经过单元测试的代码。(其中之一是boto3)我找不到任何提示如何正确使用它的线索。
我也尝试以这种方式使用相对导入
from ..my.main import func
但它会抛出ValueError: attempted relative import beyond top-level package.
这没关系。但我还是试过了。
现在我不知道该怎么做。有关导入的教程通常指出我们应该添加导入模块的路径(如果它们不存在的话)但是当不应该有可以保存功能的文件sys.path
时我应该怎么做呢?init
解决方案
推荐阅读
- serenity-bdd - 如何使用 Get.resource("path") REST API,将 Serenity Screenplay 与 HTTPS 验证作为 Actor
- javascript - Angular Material Autocomplete - 如何选择选项
- svelte - 为什么我不能在 svelte3 的脚本标签中访问“$:”又名反应变量?
- python-3.x - 打印语句在函数中工作但不在代码主体中
- image - 如何使用 micropython 语言将图像发送到 API
- python - 如何使用python在多处理中动态更改参数到进程
- session - 在 maxscale 上的 mariadb 中显示详细的进程列表
- database - 这是 Database System Concepts 6th edition-Figure 11.11 Querying a B+-tree.-procedure printAll(value V) 中的错误吗?
- python - BeautifulSoup 输出的奇怪编码文件格式
- reactjs - 无法在传单地图上单击使用 PIXI.Sprite 创建的标记,尽管交互属性为 true 并添加了单击事件