首页 > 解决方案 > 单元测试结构和导入

问题描述

我想知道如何在我的测试文件中正确导入文件而不使用__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

标签: pythonunit-testingpytest

解决方案


推荐阅读