0
给出一个测试套件,文本文件:解析单元测试断言使用抽象语法树
class MyTestSuite(unittest.TestCase):
def test_foo(self):
self.assertLessEqual(temperature, boiling, "boiling will burn the cake")
self.assertEqual(colour, 'golden brown', "the cake should be cooked until golden brown")
def test_bar(self):
self.assertIn('flour', ['flour', 'eggs'], "the flour should be mixed in with the eggs")
我想产生描述所有的断言和测试的文本文件。例如:
My Test Suite
Test foo:
* temperature <= boiling because boiling will burn the cake
* colour == 'golden brown' because the cake should be cooked until golden brown
Test bar:
* 'flour' in ['flour', 'eggs'] because the flour should be mixed in with the eggs
更新
使用inspect
我设法得到一个模块中的所有测试方法可迭代列表:
def __init__(self, module='__main__'):
if isinstance(module, basestring):
self.module = __import__(module)
for part in module.split('.')[1:]:
self.module = getattr(self.module, part)
else:
self.module = module
self.tests = {}
for name, obj in inspect.getmembers(self.module):
if inspect.isclass(obj):
for method_name in dir(obj):
method = callable(getattr(obj, method_name))
if method and re.match('test.*', method_name):
spec = ' '.join(re.findall('[A-Za-z][^A-Z_]*(?=_[A-Z])?|[A-Z][^A-Z_]*', obj.__name__)).title()
test = ' '.join(re.findall('[A-Za-z][^A-Z_]*(?=_[A-Z])?|[A-Z][^A-Z_]*', method_name)).capitalize()
assertions = # a list of strings describing the assertions
try:
self.tests[spec][test] = assertions
except KeyError:
self.tests[spec] = {test: assertions}
的最后一步是提取描述测试方法断言的字符串列表。我的第一个解决方案是使用与inspect.getsourcelines(method)
结合使用正则表达式的负载,但必须有更少的依赖于语法的解决方案。感谢凯文建议ast
作为一个可行的选择,但这带来了一个更具体的问题。
如何使用ast
将测试方法中的断言解析为人类可读的格式?
失败这可能有更好的选择吗?
你有试过在你的单元测试中挥动[ast魔杖](https://docs.python.org/3/library/ast.html#ast.parse)吗? – Kevin