加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 发现后过滤测试

发布时间:2020-12-16 22:47:20 所属栏目:Python 来源:网络整理
导读:我目前正在运行这样的测试: tests = unittest.TestLoader().discover('tests')unittest.TextTestRunner().run(tests) 现在我想运行一个特定的测试,知道他的名字(比如test_valid_user),但不知道他的班级.如果有一个以上的测试名称比我想要运行所有这些测试.

我目前正在运行这样的测试:

tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner().run(tests)

现在我想运行一个特定的测试,知道他的名字(比如test_valid_user),但不知道他的班级.如果有一个以上的测试名称比我想要运行所有这些测试.发现后有没有办法过滤测试?

或者也许还有其他解决方案可以解决这个问题(请注意,不应该从命令行完成)?

最佳答案
您可以使用unittest.loader.TestLoader.testMethodPrefix实例变量根据与“test”不同的前缀更改测试方法过滤器.

假设你有一个带有这个单元测试之王的测试目录:

import unittest


class MyTest(unittest.TestCase):
    def test_suite_1(self):
        self.assertFalse("test_suite_1")

    def test_suite_2(self):
        self.assertFalse("test_suite_2")

    def test_other(self):
        self.assertFalse("test_other")

您可以编写自己的发现函数,仅发现以“test_suite_”开头的测试函数,例如:

import unittest


def run_suite():
    loader = unittest.TestLoader()
    loader.testMethodPrefix = "test_suite_"
    suite = loader.discover("tests")
    result = unittest.TestResult()
    suite.run(result)
    for test,info in result.failures:
        print(info)


if __name__ == '__main__':
    run_suite()

注意:discover方法中的参数“tests”是一个目录路径,因此您可能需要编写一个完整路径.

结果,你会得到:

Traceback (most recent call last):
  File "/path/to/tests/test_my_module.py",line 8,in test_suite_1
    self.assertFalse("test_suite_1")
AssertionError: 'test_suite_1' is not false

Traceback (most recent call last):
  File "/path/to/tests/test_my_module.py",line 11,in test_suite_2
    self.assertFalse("test_suite_2")
AssertionError: 'test_suite_2' is not false

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读