【问题标题】:Any ways to add custom/debug message to details of failed test method of python/django unittest.TestCase?有什么方法可以将自定义/调试消息添加到 python/django unittest.TestCase 的失败测试方法的详细信息中?
【发布时间】:2012-02-29 19:19:07
【问题描述】:

我正在使用 unittest.TestCase 为我的 django 应用程序编写测试用例(这与 python 中的 unittest.TestCase 基本相同)。每当测试方法失败时,我都会以下面的格式得到它的解释。有没有办法可以将自定义/调试消息添加到失败的测试方法的输出中?

======================================================================
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.']

【问题讨论】:

    标签: python django django-testing


    【解决方案1】:

    一般来说,你想继承django的unittest类TestCase,可以通过从django.test中导入来获得。也就是说,您可以将 msg 参数传递给您要评估的任何内容,其中包含失败消息。

    这是 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))
    

    显然,你的不需要像上面那样,但你可以看到 msg 参数的作用。

    【讨论】:

    • 如果你检查assertEqual函数的定义,你可以看到它接受了msg参数def assertEqual(self, first, second, msg=None):
    猜你喜欢
    • 2018-04-06
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多