在视图中检索Django Unittest结果

时间:2014-02-11 03:26:59

标签: django django-unittest

我无法在任何地方找到它,但是可以在django视图中运行unittest,输出到模板吗?目前,如果我运行python manage.py test,我会收到类似" Ran 10 tests in 0.401s OK"的消息。我想从我的一个观点中获取此信息。有什么建议?谢谢!

编辑:尝试过,没有工作:

import StringIO
from django.core import manegement
output = StringIO.StringIO()
management.call_command('test', stdout=output)
print output.contents

1 个答案:

答案 0 :(得分:1)

结束了我想要的东西:

import unittest
from testAdditional import UserTestCase #Where my unittest was defined
suite=unittest.TestLoader().loadTestsFromTestCase(UserTestCase)
testResult = unittest.TextTestRunner(verbosity=2).run(suite)
response_data['nrFailed'] = len(testResult.failures)
response_data['output'] = "{}{}".format('\n'.join([result[1] for result in testResult.errors]),'\n'.join([result[1] for result in testResult.failures]))
response_data['totalTests'] = testResult.testsRun