【问题标题】:What is the proper way to write unit tests on modules (in subdirectories) which use other modules in the parent directory in Python在 Python 的父目录中使用其他模块的模块(在子目录中)编写单元测试的正确方法是什么
【发布时间】:2020-12-03 05:17:45
【问题描述】:

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

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

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

我的项目将在我启动 main.py 时运行。

我知道我可以通过在每个“事物”中使用 if __name__ == '__main__': 来为每个“事物”编写简单的单元测试,这就是我所做的。

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

什么是正确的方法?

【问题讨论】:

  • 您不是将测试存储在单独的文件中吗?你的描述有点模棱两可,你说你已经阅读了手册,我假设 unittest 文档,他们对生活在自己的模块中的测试非常清楚(one example)。另请参阅this SO answer
  • 我没有读过关于单元测试的文章,我是根据6.1.1 Executing modules as script 这个问题提出的,这足以满足我的需求......我认为。

标签: python python-unittest python-module directory-structure


【解决方案1】:

你应该从你的主目录运行所有东西:

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

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

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

【讨论】:

  • 有道理!伟大的!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多