Python 单元测试和发现 [英] Python unittest and discovery

查看:29
本文介绍了Python 单元测试和发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有目录,其中包含名为如下的文件:test_foo.py

I have directories, which contain files named like: test_foo.py

每个文件都是一个测试用例.

Each file is a test case.

我愿意

  1. 从命令行运行目录中的所有测试.我正在使用 unittest2,因为我们运行的是 Python 2.5.1.从这些目录之一,我尝试在命令行中输入:

  1. Run all the tests in a directory from the command line. I am using unittest2, since we are running Python 2.5.1. From one of these directories I tried typing this at the command line:

 python -m unittest2 discover -p 'test_*.py'

和几种不同的变体.我没有收到错误,但没有任何反应.我希望该目录中所有测试用例中的所有测试都能运行并获得结果.

and several different variants. I get no error, but nothing happens. I was expecting all the tests within all the test cases in that directory to run and get results.

我还尝试在我执行此操作的目录中放置一个脚本:

I also tried having a script in the directory where I did this:

 loader = unittest2.TestLoader()
 t = loader.discover('.')

如果我打印 t 变量,我可以看到我的测试用例,但是从文档中我无法弄清楚一旦我拥有加载器对象该怎么办.

If I print the t variable, I can see my test cases, but from the documentation I can't figure out what to do with the loader object once I have it.

推荐答案

我在运行 python -m unittest discover 时遇到了同样的问题.这是一个很好的清单,可以验证您的设置.Nose 在允许的配置下更灵活,但不一定更好.

I ran into the same issue when running python -m unittest discover. Here is a good checklist to verify your setup. Nose is more flexible with the allowed configurations, but not necessarily better.

  1. 确保所有文件/目录都以 test 开头.不要不要使用test-something.py,因为那不是有效的Python模块名称.使用 test_something.py.

  1. Make sure all files/directories start with test. Do not use test-something.py, since that is not a valid Python module name. Use test_something.py.

如果您将测试放在子目录中(例如 test/),请确保创建一个 test/__init__.py 文件,以便 python将目录视为一个包.

If you are putting your tests in a sub-directory (e.g. test/), make sure you create a test/__init__.py file so python will treat the directory as a package.

所有类测试用例定义必须扩展unittest.TestCase.例如,

All class test cases definitions must be extend unittest.TestCase. For example,

class DataFormatTests(unittest.TestCase)

  • 所有测试用例方法定义必须以test_

     def test_data_format(self):
    

  • 这篇关于Python 单元测试和发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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