Converted templates doctests into unittests. We have always been at war with doctests.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14448 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Alex Gaynor 2010-11-04 04:47:05 +00:00
parent cabc21ca60
commit 0659391baf
5 changed files with 115 additions and 177 deletions

View File

@ -1,22 +1,16 @@
# coding: utf-8 # coding: utf-8
from django.template import Context
from django.utils.unittest import TestCase
context_tests = r"""
>>> from django.template import Context
>>> c = Context({'a': 1, 'b': 'xyzzy'})
>>> c['a']
1
>>> c.push()
{}
>>> c['a'] = 2
>>> c['a']
2
>>> c.get('a')
2
>>> c.pop()
{'a': 2}
>>> c['a']
1
>>> c.get('foo', 42)
42
"""
class ContextTests(TestCase):
def test_context(self):
c = Context({"a": 1, "b": "xyzzy"})
self.assertEqual(c["a"], 1)
self.assertEqual(c.push(), {})
c["a"] = 2
self.assertEqual(c["a"], 2)
self.assertEqual(c.get("a"), 2)
self.assertEqual(c.pop(), {"a": 2})
self.assertEqual(c["a"], 1)
self.assertEqual(c.get("foo", 42), 42)

View File

@ -1,11 +1,11 @@
from django import test
from django import template from django import template
from django.utils.unittest import TestCase
custom_filters = """ class CustomTests(TestCase):
>>> t = template.Template("{% load custom %}{{ string|trim:5 }}") def test_filter(self):
>>> ctxt = template.Context({"string": "abcdefghijklmnopqrstuvwxyz"}) t = template.Template("{% load custom %}{{ string|trim:5 }}")
>>> t.render(ctxt) self.assertEqual(
u"abcde" t.render(template.Context({"string": "abcdefghijklmnopqrstuvwxyz"})),
""" u"abcde"
)

View File

@ -1,121 +1,83 @@
""" """
Testing some internals of the template processing. These are *not* examples to be copied in user code. Testing some internals of the template processing. These are *not* examples to be copied in user code.
""" """
from django.template import (TokenParser, FilterExpression, Parser, Variable,
token_parsing=r""" TemplateSyntaxError)
Tests for TokenParser behavior in the face of quoted strings with spaces. from django.utils.unittest import TestCase
>>> from django.template import TokenParser
Test case 1: {% tag thevar|filter sometag %} class ParserTests(TestCase):
def test_token_parsing(self):
# Tests for TokenParser behavior in the face of quoted strings with
# spaces.
>>> p = TokenParser("tag thevar|filter sometag") p = TokenParser("tag thevar|filter sometag")
>>> p.tagname self.assertEqual(p.tagname, "tag")
'tag' self.assertEqual(p.value(), "thevar|filter")
>>> p.value() self.assertTrue(p.more())
'thevar|filter' self.assertEqual(p.tag(), "sometag")
>>> p.more() self.assertFalse(p.more())
True
>>> p.tag()
'sometag'
>>> p.more()
False
Test case 2: {% tag "a value"|filter sometag %} p = TokenParser('tag "a value"|filter sometag')
self.assertEqual(p.tagname, "tag")
self.assertEqual(p.value(), '"a value"|filter')
self.assertTrue(p.more())
self.assertEqual(p.tag(), "sometag")
self.assertFalse(p.more())
>>> p = TokenParser('tag "a value"|filter sometag') p = TokenParser("tag 'a value'|filter sometag")
>>> p.tagname self.assertEqual(p.tagname, "tag")
'tag' self.assertEqual(p.value(), "'a value'|filter")
>>> p.value() self.assertTrue(p.more())
'"a value"|filter' self.assertEqual(p.tag(), "sometag")
>>> p.more() self.assertFalse(p.more())
True
>>> p.tag()
'sometag'
>>> p.more()
False
Test case 3: {% tag 'a value'|filter sometag %} def test_filter_parsing(self):
c = {"article": {"section": u"News"}}
p = Parser("")
>>> p = TokenParser("tag 'a value'|filter sometag") def fe_test(s, val):
>>> p.tagname self.assertEqual(FilterExpression(s, p).resolve(c), val)
'tag'
>>> p.value()
"'a value'|filter"
>>> p.more()
True
>>> p.tag()
'sometag'
>>> p.more()
False
"""
filter_parsing = r""" fe_test("article.section", u"News")
>>> from django.template import FilterExpression, Parser fe_test("article.section|upper", u"NEWS")
fe_test(u'"News"', u"News")
fe_test(u"'News'", u"News")
fe_test(ur'"Some \"Good\" News"', u'Some "Good" News')
fe_test(ur'"Some \"Good\" News"', u'Some "Good" News')
fe_test(ur"'Some \'Bad\' News'", u"Some 'Bad' News")
>>> c = {'article': {'section': u'News'}} fe = FilterExpression(ur'"Some \"Good\" News"', p)
>>> p = Parser("") self.assertEqual(fe.filters, [])
>>> def fe_test(s): return FilterExpression(s, p).resolve(c) self.assertEqual(fe.var, u'Some "Good" News')
>>> fe_test('article.section') # Filtered variables should reject access of attributes beginning with
u'News' # underscores.
>>> fe_test('article.section|upper') self.assertRaises(TemplateSyntaxError,
u'NEWS' FilterExpression, "article._hidden|upper", p
>>> fe_test(u'"News"') )
u'News'
>>> fe_test(u"'News'")
u'News'
>>> fe_test(ur'"Some \"Good\" News"')
u'Some "Good" News'
>>> fe_test(ur"'Some \'Bad\' News'")
u"Some 'Bad' News"
>>> fe = FilterExpression(ur'"Some \"Good\" News"', p) def test_variable_parsing(self):
>>> fe.filters c = {"article": {"section": u"News"}}
[] self.assertEqual(Variable("article.section").resolve(c), "News")
>>> fe.var self.assertEqual(Variable(u'"News"').resolve(c), "News")
u'Some "Good" News' self.assertEqual(Variable(u"'News'").resolve(c), "News")
Filtered variables should reject access of attributes beginning with underscores. # Translated strings are handled correctly.
self.assertEqual(Variable("_(article.section)").resolve(c), "News")
self.assertEqual(Variable('_("Good News")').resolve(c), "Good News")
self.assertEqual(Variable("_('Better News')").resolve(c), "Better News")
>>> FilterExpression('article._hidden|upper', p) # Escaped quotes work correctly as well.
Traceback (most recent call last): self.assertEqual(
... Variable(ur'"Some \"Good\" News"').resolve(c), 'Some "Good" News'
TemplateSyntaxError: Variables and attributes may not begin with underscores: 'article._hidden' )
""" self.assertEqual(
Variable(ur"'Some \'Better\' News'").resolve(c), "Some 'Better' News"
)
variable_parsing = r""" # Variables should reject access of attributes beginning with
>>> from django.template import Variable # underscores.
self.assertRaises(TemplateSyntaxError,
>>> c = {'article': {'section': u'News'}} Variable, "article._hidden"
>>> Variable('article.section').resolve(c) )
u'News'
>>> Variable(u'"News"').resolve(c)
u'News'
>>> Variable(u"'News'").resolve(c)
u'News'
Translated strings are handled correctly.
>>> Variable('_(article.section)').resolve(c)
u'News'
>>> Variable('_("Good News")').resolve(c)
u'Good News'
>>> Variable("_('Better News')").resolve(c)
u'Better News'
Escaped quotes work correctly as well.
>>> Variable(ur'"Some \"Good\" News"').resolve(c)
u'Some "Good" News'
>>> Variable(ur"'Some \'Better\' News'").resolve(c)
u"Some 'Better' News"
Variables should reject access of attributes beginning with underscores.
>>> Variable('article._hidden')
Traceback (most recent call last):
...
TemplateSyntaxError: Variables and attributes may not begin with underscores: 'article._hidden'
"""

View File

@ -21,10 +21,10 @@ from django.utils.translation import activate, deactivate, ugettext as _
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.tzinfo import LocalTimezone from django.utils.tzinfo import LocalTimezone
from context import context_tests from context import ContextTests
from custom import custom_filters from custom import CustomTests
from parser import token_parsing, filter_parsing, variable_parsing from parser import ParserTests
from unicode import unicode_tests from unicode import UnicodeTests
from nodelist import NodelistTest from nodelist import NodelistTest
from smartif import * from smartif import *
@ -35,16 +35,6 @@ except ImportError:
import filters import filters
# Some other tests we would like to run
__test__ = {
'unicode': unicode_tests,
'context': context_tests,
'token_parsing': token_parsing,
'filter_parsing': filter_parsing,
'variable_parsing': variable_parsing,
'custom_filters': custom_filters,
}
################################# #################################
# Custom template tag for tests # # Custom template tag for tests #
################################# #################################

View File

@ -1,37 +1,29 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from django.template import Template, TemplateEncodingError, Context
from django.utils.safestring import SafeData
from django.utils.unittest import TestCase
unicode_tests = ur"""
Templates can be created from unicode strings.
>>> from django.template import *
>>> from django.utils.safestring import SafeData
>>> t1 = Template(u'ŠĐĆŽćžšđ {{ var }}')
Templates can also be created from bytestrings. These are assumed by encoded class UnicodeTests(TestCase):
using UTF-8. def test_template(self):
# Templates can be created from unicode strings.
t1 = Template(u'ŠĐĆŽćžšđ {{ var }}')
# Templates can also be created from bytestrings. These are assumed to
# be encoded using UTF-8.
s = '\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}'
t2 = Template(s)
s = '\x80\xc5\xc0'
self.assertRaises(TemplateEncodingError, Template, s)
>>> s = '\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}' # Contexts can be constructed from unicode or UTF-8 bytestrings.
>>> t2 = Template(s) c1 = Context({"var": "foo"})
>>> s = '\x80\xc5\xc0' c2 = Context({u"var": "foo"})
>>> Template(s) c3 = Context({"var": u"Đđ"})
Traceback (most recent call last): c4 = Context({u"var": "\xc4\x90\xc4\x91"})
...
TemplateEncodingError: Templates can only be constructed from unicode or UTF-8 strings.
Contexts can be constructed from unicode or UTF-8 bytestrings. # Since both templates and all four contexts represent the same thing,
# they all render the same (and are returned as unicode objects and
>>> c1 = Context({'var': 'foo'}) # "safe" objects as well, for auto-escaping purposes).
>>> c2 = Context({u'var': 'foo'}) self.assertEqual(t1.render(c3), t2.render(c3))
>>> c3 = Context({'var': u'Đđ'}) self.assertIsInstance(t1.render(c3), unicode)
>>> c4 = Context({u'var': '\xc4\x90\xc4\x91'}) self.assertIsInstance(t1.render(c3), SafeData)
Since both templates and all four contexts represent the same thing, they all
render the same (and are returned as unicode objects and "safe" objects as
well, for auto-escaping purposes).
>>> t1.render(c3) == t2.render(c3)
True
>>> isinstance(t1.render(c3), unicode)
True
>>> isinstance(t1.render(c3), SafeData)
True
"""