Python 单元测试应该在一个单独的模块中吗? [英] Should Python unittests be in a separate module?

查看:33
本文介绍了Python 单元测试应该在一个单独的模块中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否就放置 Python 单元测试的最佳位置达成了共识?

Is there a consensus about the best place to put Python unittests?

单元测试是否应该包含在与被测试功能相同的模块中(在模块自行运行时执行(if __name__ == '__main__' 等)),或者是将单元测试包含在不同的模块中会更好吗?

Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (if __name__ == '__main__', etc.)), or is it better to include the unittests within different modules?

也许两种方法的结合是最好的,包括每个模块内的模块级测试,并添加更高级别的测试,这些测试将包含在多个模块中的功能作为单独的模块(可能在/test 子目录中?).

Perhaps a combination of both approaches is best, including module level tests within each module and adding higher level tests which test functionality included in more than one module as separate modules (perhaps in a /test subdirectory?).

我认为如果测试包含在单独的模块中,测试发现会更直接,但如果开发人员必须记住在被测模块被修改时更新额外的测试模块,这会给开发人员带来额外的负担.

I assume that test discovery is more straightforward if the tests are included in separate modules, but there's an additional burden on the developer if he/she has to remember to update the additional test module if the module under test is modified.

我很想知道人们对组织单元测试的最佳方式的看法.

I'd be interested to know peoples' thoughts on the best way of organizing unittests.

推荐答案

  1. 如果使用库指定单元测试应该在哪里,您必须在哪里,
  2. 在小项目的模块本身中,或
  3. 在用于大型项目的包中的 tests/ 子目录中.
  1. Where you have to if using a library specifying where unittests should live,
  2. in the modules themselves for small projects, or
  3. in a tests/ subdirectory in your package for larger projects.

这是一个最适合您正在创建的项目的问题.

It's a matter of what works best for the project you're creating.

有时您使用的库决定了测试的去向,就像 Django 的情况一样(您将测试放在 models.pytests.py或应用中的 tests/ 子目录).

Sometimes the libraries you're using determine where tests should go, as is the case with Django (where you put your tests in models.py, tests.py or a tests/ subdirectory in your apps).

如果没有现有限制,那就是个人喜好问题.对于一小组模块,将单元测试放在您正在创建的文件中可能更方便.

If there are no existing constraints, it's a matter of personal preference. For a small set of modules, it may be more convenient to put the unittests in the files you're creating.

除了几个模块之外,我会在包的 tests/ 目录中单独创建测试.将测试代码与实现混合在一起会给任何阅读代码的人带来不必要的干扰.

For anything more than a few modules I create the tests separately in a tests/ directory in the package. Having testing code mixed with the implementation adds unnecessary noise for anyone reading the code.

这篇关于Python 单元测试应该在一个单独的模块中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆