如何使用 django.test.TestCase 断言异常?



我正在使用Django 3(最新(,并试图使用文档中的unittestassertRaises断言异常。

我的代码在获得IndexError时会引发django.template.TemplateSyntaxError

from django import template
register = template.Library()
@register.tag(name="autopaginate")
def do_autopaginate(parser, token):
split = token.split_contents()
as_index = None
context_var = None
for i, bit in enumerate(split):
if bit == "as":
as_index = i
break
if as_index is not None:
try:
context_var = split[as_index + 1]
except IndexError:
raise template.TemplateSyntaxError(
(
f"Context variable assignment "
f"must take the form of {{% {split[0]} object.example_set.all ... as "
f"context_var_name %}}"
)
)
del split[as_index : as_index + 2]
if len(split) == 2:
return AutoPaginateNode(split[1])
if len(split) == 3:
return AutoPaginateNode(split[1], paginate_by=split[2], context_var=context_var)
if len(split) == 4:
try:
orphans = int(split[3])
except ValueError:
raise template.TemplateSyntaxError(f"Got {split[3]}, but expected integer.")
return AutoPaginateNode(
split[1], paginate_by=split[2], orphans=orphans, context_var=context_var
)
raise template.TemplateSyntaxError(
f"{split[0]} tag takes one required argument and one optional argument"
)

我的测试代码以下文档是:

from django import template
from django.http import HttpRequest
from django.test import TestCase
class TestHttpRequest(HttpRequest):
__test__ = False
page = 1
class TestTemplatePaginateTags(TestCase):
def test_render_range_by_var_as_index_error(self):
t = template.Template(
"{% load pagination_tags %}{% autopaginate var by as %}{{ foo }}"
)
c = template.Context({"var": range(21), "request": TestHttpRequest()})
with self.assertRaises(template.TemplateSyntaxError):
t.render(c)

完整代码在此 PR 中。

不幸的是,它没有通过测试,而是失败了,说它抛出了异常:

失败 tests/test_pagination_tags.py::testTemplatePaginateTags::test_render_range_by_var_as_index_error

  • django.template.exceptions.TemplateSyntaxError: 上下文变量赋值必须采用 {% autopaginate 的形式 object.example_set.全部...作为 context_var_name %}

这正是我期望使此测试通过的内容。我不知道这里出了什么问题。

构造Template对象时将引发错误,而不是在渲染对象时引发错误。因此,您希望错误随t.render(c)引发,但错误在t = template.Template(…)中,因此您需要在上下文管理器中包装另一个语句:

class TestTemplatePaginateTags(TestCase):
def test_render_range_by_var_as_index_error(self):
with self.assertRaises(template.TemplateSyntaxError):
template.Template(
"{% load pagination_tags %}{% autopaginate var by as %}{{ foo }}"
)

最新更新