Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any ways to add custom/debug message to details of failed test method of python/django unittest.TestCase?

I am using unittest.TestCase to write test cases for my django app (which is essentially the same unittest.TestCase from python). Whenever a test method fails, I get the explanation of it in the format below. Is there a way that I can add custom/debug messages to the output of failed test method?

======================================================================
FAIL: test_bad_votes (polls.tests.views.PollsViewsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/colinh/Development/tutorials/guide-to-testing-in-django/polls/tests/views.py", line 66, in test_bad_votes
    self.assertEqual(resp.context['form']['choice'].errors, [u'This field is required.'])
AssertionError: [] != [u'This field is required.']
like image 734
tamakisquare Avatar asked Feb 29 '12 19:02

tamakisquare


1 Answers

In general, you want to inherit from django's unittest class TestCase, which you can get by importing from django.test. That said, you can pass a msg argument to whatever you're trying to evaluate, containing the failure message.

Here's an example from Humanize:

class HumanizeTests(TestCase):

    def humanize_tester(self, test_list, result_list, method):
        # Using max below ensures we go through both lists
        # However, if the lists are not equal length, this raises an exception
        for test_content, result in zip(test_list, result_list):
            t = Template('{%% load humanize %%}{{ test_content|%s }}' % method)
            rendered = t.render(Context(locals())).strip()
            self.assertEqual(rendered, escape(result),
                         msg="%s test failed, produced '%s', should've produced '%s'" %     (method, rendered, result))

Obviously, yours doesn't need to look like the above, but you can see the msg argument in action.

like image 122
James R Avatar answered Oct 19 '22 23:10

James R