在 Python 的 parent 目录中使用其他模块的模块(在子目录中)编写单元测试的正确方法是什么

What is the proper way to write unit tests on modules (in subdirectories) which use other modules in the parent directory in Python

尝试在标题中尽可能地描述它。我对在大型项目中使用 python 还很陌生。通常,我只将它用于小脚本。我通读了手册,找到了制作模块的正确方法。

所以我现在设置了以下文件结构:

- main.py
- module1
  - __init__.py
  - thing1.py
  - thing2.py
- module2
  - __init__.py
  - thingA.py
  - thingB.py

我的项目将在我开始时 运行 main.py。

我知道我可以为每个 'thing' 编写简单的单元测试,方法是在每个测试中使用 if __name__ == '__main__':,这就是我所做的。

文件 thingB.py 需要 thing2.py 才能工作。只要启动main.py,thingB就会找到thing2。但是当我在它自己的目录中直接启动 thingB(进行单元测试 运行)时,它不会找到 thing2.

正确的做法是什么?

您应该 运行 主目录中的所有内容:

python -m module1.thing1
python -m module2.thingA

这样 module1module2 就可以相互导入了。单元测试应该是 运行 同样的方式:

python -m unittest discover module1
python -m unittest discover module2