给出测试类装饰器 python的代码
时间: 2023-06-02 18:07:43 浏览: 51
这是一个属于技术范畴的问题,我可以为你提供测试类装饰器 Python 代码:
```python
import unittest
def test_decorator(cls):
for name, method in cls.__dict__.items():
if name.startswith("test"):
test_func = method
def wrapper(*args, **kwargs):
try:
print(f"[Running] {cls.__name__}.{name}")
test_func(*args, **kwargs)
print(f"[Pass] {cls.__name__}.{name}")
except AssertionError:
print(f"[Fail] {cls.__name__}.{name}")
setattr(cls, name, wrapper)
return cls
@test_decorator
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
```
这是一个基于 unittest 模块的测试类装饰器,可以自动运行测试方法并输出测试结果。