I am using Django 3 (latest) and tried to assert exception using unittest assertRaises as in the documentation.
My code is raising django.template.TemplateSyntaxError when it gets an IndexError:
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"
)
My test code following documentation is:
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)
Full code is in this PR.
Unfortunately, instead of passing the test it is failing saying that it is throwing the exception:
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 %}
This is exactly what I expect to make this test pass. I don't know what is wrong here.