gpt4 book ai didi

python - 发现后过滤测试

转载 作者:太空狗 更新时间:2023-10-30 01:20:36 25 4
gpt4 key购买 nike

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

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

现在我想运行一个知道他的名字(比如 test_valid_user)但不知道他的类(class)的特定测试。如果有多个具有此类名称的测试,那么我想运行所有此类测试。在discover之后有什么方法可以过滤测试吗?

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

最佳答案

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

假设您有一个包含单元测试之王的 tests 目录:

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")

您可以编写自己的 discover 函数来仅发现以“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

关于python - 发现后过滤测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38183678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com