Qum*_*ric 5 python python-unittest
我目前正在运行这样的测试:
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner().run(tests)
Run Code Online (Sandbox Code Playgroud)
现在我想知道他的名字(比如test_valid_user),但不知道他的班级.如果有一个以上的测试名称比我想要运行所有这些测试.以后有什么方法可以过滤测试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")
Run Code Online (Sandbox Code Playgroud)
您可以编写自己的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()
Run Code Online (Sandbox Code Playgroud)
备注:方法中的参数“tests”discover是目录路径,因此您可能需要编写完整路径。
结果,您将得到:
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
Run Code Online (Sandbox Code Playgroud)