我正在使用Django3(最新版本),并尝试使用unittest
{
我的代码在获得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)
完整代码在this PR中
不幸的是,它没有通过测试,而是说它正在抛出异常:
FAILED tests/test_pagination_tags.py::TestTemplatePaginateTags::test_render_range_by_var_as_index_error
- django.template.exceptions.TemplateSyntaxError: Context variable assignment must take the form of {% autopaginate object.example_set.all ... as context_var_name %}
这正是我希望通过这次测试的原因。我不知道这里怎么了
当渲染
Template
对象时,而不是构建^{对象时,将引发错误。因此,您希望在t.render(c)
时出现错误,但错误在t = template.Template(…)
中,因此需要在上下文管理器中包装另一条语句:相关问题 更多 >
编程相关推荐