Search code examples
djangodjango-unittest

Retrieving Django Unittest result in view


I can't find this anywhere, but is it possible to run a unittest from within a django view, to be output to a template? Currently if I run python manage.py test, I get a message like "Ran 10 tests in 0.401s OK". I would like to access this information from one of my views. Any suggestions? Thanks!

Edit: Tried, didnt work:

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

Solution

  • Ended up getting what I wanted with:

    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