在 Python 单元测试 TestLoader 中指定特定的测试用例 [英] Specify specific testcases in Python unit test TestLoader

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

问题描述

我有以下文件夹结构.

Unit
    smoke.py
    Test1
         Test1.py
    Test2
         Test2.py

两个测试文件各有两个测试用例.

Both the test files have two test cases each.

文件 smoke.py 包含

suite1 = unittest.TestLoader().discover('Test1', pattern = "Test*.py")
suite2 = unittest.TestLoader().discover('Test2', pattern = "Test*.py")
alltests = unittest.TestSuite((suite1, suite2))
unittest.TextTestRunner(verbosity=2).run(alltests)

上面的代码运行了四个预期的测试用例.

The above code runs four test cases which is expected.

有没有办法从文件 test1.pytest2.py 中运行一些特定的测试用例,我可以在其中显式地将这些测试用例添加到套件 1 和套件 2 中上面的代码.

Is there a way to run some specific test cases from file test1.py and test2.py where I can explicitly add those testcases to the suite1 and suite 2 in the above code.

如果 Test1.py 在类 Test1 中包含一个测试用例名称 test_system,那么 TestLoader 如何加载该特定测试用例而不是运行该模块中的所有测试用例.

If Test1.py contains a testcase name test_system in the class Test1, how can TestLoader load that specific test case instead of running all the testcases in that module.

推荐答案

您可以将测试加载器配置为仅运行具有特定前缀的测试:

You can configure your test loader to run only tests with a certain prefix:

loader = unittest.TestLoader()
loader.testMethodPrefix = "test_prefix"# default value is "test"

suite1 = loader.discover('Test1', pattern = "Test*.py") 
suite2 = loader.discover('Test2', pattern = "Test*.py")
alltests = unittest.TestSuite((suite1, suite2))
unittest.TextTestRunner(verbosity=2).run(alltests)

这篇关于在 Python 单元测试 TestLoader 中指定特定的测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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