Django-1.8.7/ 0000775 0001750 0001750 00000000000 12625116243 012341 5 ustar tim tim 0000000 0000000 Django-1.8.7/LICENSE 0000664 0001750 0001750 00000003020 12603513306 013336 0 ustar tim tim 0000000 0000000 Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Django nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Django-1.8.7/tests/ 0000775 0001750 0001750 00000000000 12625116243 013503 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/timezones/ 0000775 0001750 0001750 00000000000 12625116243 015520 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/timezones/urls.py 0000664 0001750 0001750 00000000311 12625116214 017050 0 ustar tim tim 0000000 0000000 from django.conf.urls import include, url
from django.contrib import admin
from . import admin as tz_admin # NOQA: register tz_admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
Django-1.8.7/tests/timezones/tests.py 0000664 0001750 0001750 00000151626 12625116214 017245 0 ustar tim tim 0000000 0000000 from __future__ import unicode_literals
import datetime
import re
import sys
import warnings
from unittest import skipIf
from xml.dom.minidom import parseString
from django.core import serializers
from django.core.urlresolvers import reverse
from django.db.models import Max, Min
from django.http import HttpRequest
from django.template import (
Context, RequestContext, Template, TemplateSyntaxError, context_processors,
)
from django.test import (
TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature,
)
from django.test.utils import requires_tz_support
from django.utils import six, timezone
from .forms import (
EventForm, EventLocalizedForm, EventLocalizedModelForm, EventModelForm,
EventSplitForm,
)
from .models import (
AllDayEvent, Event, MaybeEvent, Session, SessionEvent, Timestamp,
)
try:
import pytz
except ImportError:
pytz = None
# These tests use the EAT (Eastern Africa Time) and ICT (Indochina Time)
# who don't have Daylight Saving Time, so we can represent them easily
# with FixedOffset, and use them directly as tzinfo in the constructors.
# settings.TIME_ZONE is forced to EAT. Most tests use a variant of
# datetime.datetime(2011, 9, 1, 13, 20, 30), which translates to
# 10:20:30 in UTC and 17:20:30 in ICT.
UTC = timezone.utc
EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi
ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok
@override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=False)
class LegacyDatabaseTests(TestCase):
def test_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertEqual(event.dt, dt)
@skipUnlessDBFeature('supports_microsecond_precision')
def test_naive_datetime_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertEqual(event.dt, dt)
@skipIfDBFeature('supports_microsecond_precision')
def test_naive_datetime_with_microsecond_unsupported(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
Event.objects.create(dt=dt)
event = Event.objects.get()
# microseconds are lost during a round-trip in the database
self.assertEqual(event.dt, dt.replace(microsecond=0))
@skipUnlessDBFeature('supports_timezones')
def test_aware_datetime_in_local_timezone(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertIsNone(event.dt.tzinfo)
# interpret the naive datetime in local time to get the correct value
self.assertEqual(event.dt.replace(tzinfo=EAT), dt)
@skipUnlessDBFeature('supports_timezones')
@skipUnlessDBFeature('supports_microsecond_precision')
def test_aware_datetime_in_local_timezone_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertIsNone(event.dt.tzinfo)
# interpret the naive datetime in local time to get the correct value
self.assertEqual(event.dt.replace(tzinfo=EAT), dt)
# This combination actually never happens.
@skipUnlessDBFeature('supports_timezones')
@skipIfDBFeature('supports_microsecond_precision')
def test_aware_datetime_in_local_timezone_with_microsecond_unsupported(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertIsNone(event.dt.tzinfo)
# interpret the naive datetime in local time to get the correct value
# microseconds are lost during a round-trip in the database
self.assertEqual(event.dt.replace(tzinfo=EAT), dt.replace(microsecond=0))
@skipUnlessDBFeature('supports_timezones')
@skipIfDBFeature('needs_datetime_string_cast')
def test_aware_datetime_in_utc(self):
dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertIsNone(event.dt.tzinfo)
# interpret the naive datetime in local time to get the correct value
self.assertEqual(event.dt.replace(tzinfo=EAT), dt)
# This combination is no longer possible since timezone support
# was removed from the SQLite backend -- it didn't work.
@skipUnlessDBFeature('supports_timezones')
@skipUnlessDBFeature('needs_datetime_string_cast')
def test_aware_datetime_in_utc_unsupported(self):
dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertIsNone(event.dt.tzinfo)
# django.db.backends.utils.typecast_dt will just drop the
# timezone, so a round-trip in the database alters the data (!)
# interpret the naive datetime in local time and you get a wrong value
self.assertNotEqual(event.dt.replace(tzinfo=EAT), dt)
# interpret the naive datetime in original time to get the correct value
self.assertEqual(event.dt.replace(tzinfo=UTC), dt)
@skipUnlessDBFeature('supports_timezones')
@skipIfDBFeature('needs_datetime_string_cast')
def test_aware_datetime_in_other_timezone(self):
dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertIsNone(event.dt.tzinfo)
# interpret the naive datetime in local time to get the correct value
self.assertEqual(event.dt.replace(tzinfo=EAT), dt)
# This combination is no longer possible since timezone support
# was removed from the SQLite backend -- it didn't work.
@skipUnlessDBFeature('supports_timezones')
@skipUnlessDBFeature('needs_datetime_string_cast')
def test_aware_datetime_in_other_timezone_unsupported(self):
dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertIsNone(event.dt.tzinfo)
# django.db.backends.utils.typecast_dt will just drop the
# timezone, so a round-trip in the database alters the data (!)
# interpret the naive datetime in local time and you get a wrong value
self.assertNotEqual(event.dt.replace(tzinfo=EAT), dt)
# interpret the naive datetime in original time to get the correct value
self.assertEqual(event.dt.replace(tzinfo=ICT), dt)
@skipIfDBFeature('supports_timezones')
def test_aware_datetime_unspported(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)
with self.assertRaises(ValueError):
Event.objects.create(dt=dt)
def test_auto_now_and_auto_now_add(self):
now = datetime.datetime.now()
past = now - datetime.timedelta(seconds=2)
future = now + datetime.timedelta(seconds=2)
Timestamp.objects.create()
ts = Timestamp.objects.get()
self.assertLess(past, ts.created)
self.assertLess(past, ts.updated)
self.assertGreater(future, ts.updated)
self.assertGreater(future, ts.updated)
def test_query_filter(self):
dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30)
dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30)
Event.objects.create(dt=dt1)
Event.objects.create(dt=dt2)
self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2)
self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1)
self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1)
self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0)
def test_query_datetime_lookups(self):
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0))
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0))
self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2)
self.assertEqual(Event.objects.filter(dt__month=1).count(), 2)
self.assertEqual(Event.objects.filter(dt__day=1).count(), 2)
self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2)
self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1)
self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2)
self.assertEqual(Event.objects.filter(dt__second=0).count(), 2)
def test_query_aggregation(self):
# Only min and max make sense for datetimes.
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40))
result = Event.objects.all().aggregate(Min('dt'), Max('dt'))
self.assertEqual(result, {
'dt__min': datetime.datetime(2011, 9, 1, 3, 20, 40),
'dt__max': datetime.datetime(2011, 9, 1, 23, 20, 20),
})
def test_query_annotation(self):
# Only min and max make sense for datetimes.
morning = Session.objects.create(name='morning')
afternoon = Session.objects.create(name='afternoon')
SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20), session=afternoon)
SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30), session=afternoon)
SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40), session=morning)
morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40)
afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30)
self.assertQuerysetEqual(
Session.objects.annotate(dt=Min('events__dt')).order_by('dt'),
[morning_min_dt, afternoon_min_dt],
transform=lambda d: d.dt)
self.assertQuerysetEqual(
Session.objects.annotate(dt=Min('events__dt')).filter(dt__lt=afternoon_min_dt),
[morning_min_dt],
transform=lambda d: d.dt)
self.assertQuerysetEqual(
Session.objects.annotate(dt=Min('events__dt')).filter(dt__gte=afternoon_min_dt),
[afternoon_min_dt],
transform=lambda d: d.dt)
def test_query_datetimes(self):
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0))
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0))
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'year'),
[datetime.datetime(2011, 1, 1, 0, 0, 0)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'month'),
[datetime.datetime(2011, 1, 1, 0, 0, 0)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'day'),
[datetime.datetime(2011, 1, 1, 0, 0, 0)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'hour'),
[datetime.datetime(2011, 1, 1, 1, 0, 0),
datetime.datetime(2011, 1, 1, 4, 0, 0)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'minute'),
[datetime.datetime(2011, 1, 1, 1, 30, 0),
datetime.datetime(2011, 1, 1, 4, 30, 0)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'second'),
[datetime.datetime(2011, 1, 1, 1, 30, 0),
datetime.datetime(2011, 1, 1, 4, 30, 0)],
transform=lambda d: d)
def test_raw_sql(self):
# Regression test for #17755
dt = datetime.datetime(2011, 9, 1, 13, 20, 30)
event = Event.objects.create(dt=dt)
self.assertQuerysetEqual(
Event.objects.raw('SELECT * FROM timezones_event WHERE dt = %s', [dt]),
[event],
transform=lambda d: d)
def test_filter_date_field_with_aware_datetime(self):
# Regression test for #17742
day = datetime.date(2011, 9, 1)
AllDayEvent.objects.create(day=day)
# This is 2011-09-02T01:30:00+03:00 in EAT
dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC)
self.assertTrue(AllDayEvent.objects.filter(day__gte=dt).exists())
@override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True)
class NewDatabaseTests(TestCase):
@requires_tz_support
def test_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30)
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always')
Event.objects.create(dt=dt)
self.assertEqual(len(recorded), 1)
msg = str(recorded[0].message)
self.assertTrue(msg.startswith("DateTimeField Event.dt received "
"a naive datetime"))
event = Event.objects.get()
# naive datetimes are interpreted in local time
self.assertEqual(event.dt, dt.replace(tzinfo=EAT))
@requires_tz_support
def test_datetime_from_date(self):
dt = datetime.date(2011, 9, 1)
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always')
Event.objects.create(dt=dt)
self.assertEqual(len(recorded), 1)
msg = str(recorded[0].message)
self.assertTrue(msg.startswith("DateTimeField Event.dt received "
"a naive datetime"))
event = Event.objects.get()
self.assertEqual(event.dt, datetime.datetime(2011, 9, 1, tzinfo=EAT))
@requires_tz_support
@skipUnlessDBFeature('supports_microsecond_precision')
def test_naive_datetime_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always')
Event.objects.create(dt=dt)
self.assertEqual(len(recorded), 1)
msg = str(recorded[0].message)
self.assertTrue(msg.startswith("DateTimeField Event.dt received "
"a naive datetime"))
event = Event.objects.get()
# naive datetimes are interpreted in local time
self.assertEqual(event.dt, dt.replace(tzinfo=EAT))
@requires_tz_support
@skipIfDBFeature('supports_microsecond_precision')
def test_naive_datetime_with_microsecond_unsupported(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always')
Event.objects.create(dt=dt)
self.assertEqual(len(recorded), 1)
msg = str(recorded[0].message)
self.assertTrue(msg.startswith("DateTimeField Event.dt received "
"a naive datetime"))
event = Event.objects.get()
# microseconds are lost during a round-trip in the database
# naive datetimes are interpreted in local time
self.assertEqual(event.dt, dt.replace(microsecond=0, tzinfo=EAT))
def test_aware_datetime_in_local_timezone(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertEqual(event.dt, dt)
@skipUnlessDBFeature('supports_microsecond_precision')
def test_aware_datetime_in_local_timezone_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertEqual(event.dt, dt)
@skipIfDBFeature('supports_microsecond_precision')
def test_aware_datetime_in_local_timezone_with_microsecond_unsupported(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT)
Event.objects.create(dt=dt)
event = Event.objects.get()
# microseconds are lost during a round-trip in the database
self.assertEqual(event.dt, dt.replace(microsecond=0))
def test_aware_datetime_in_utc(self):
dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertEqual(event.dt, dt)
def test_aware_datetime_in_other_timezone(self):
dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT)
Event.objects.create(dt=dt)
event = Event.objects.get()
self.assertEqual(event.dt, dt)
def test_auto_now_and_auto_now_add(self):
now = timezone.now()
past = now - datetime.timedelta(seconds=2)
future = now + datetime.timedelta(seconds=2)
Timestamp.objects.create()
ts = Timestamp.objects.get()
self.assertLess(past, ts.created)
self.assertLess(past, ts.updated)
self.assertGreater(future, ts.updated)
self.assertGreater(future, ts.updated)
def test_query_filter(self):
dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT)
dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30, tzinfo=EAT)
Event.objects.create(dt=dt1)
Event.objects.create(dt=dt2)
self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2)
self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1)
self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1)
self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0)
@skipIf(pytz is None, "this test requires pytz")
def test_query_filter_with_pytz_timezones(self):
tz = pytz.timezone('Europe/Paris')
dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=tz)
Event.objects.create(dt=dt)
next = dt + datetime.timedelta(seconds=3)
prev = dt - datetime.timedelta(seconds=3)
self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1)
self.assertEqual(Event.objects.filter(dt__exact=next).count(), 0)
self.assertEqual(Event.objects.filter(dt__in=(prev, next)).count(), 0)
self.assertEqual(Event.objects.filter(dt__in=(prev, dt, next)).count(), 1)
self.assertEqual(Event.objects.filter(dt__range=(prev, next)).count(), 1)
@requires_tz_support
def test_query_filter_with_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT)
Event.objects.create(dt=dt)
dt = dt.replace(tzinfo=None)
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always')
# naive datetimes are interpreted in local time
self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1)
self.assertEqual(Event.objects.filter(dt__lte=dt).count(), 1)
self.assertEqual(Event.objects.filter(dt__gt=dt).count(), 0)
self.assertEqual(len(recorded), 3)
for warning in recorded:
msg = str(warning.message)
self.assertTrue(msg.startswith("DateTimeField Event.dt "
"received a naive datetime"))
@skipUnlessDBFeature('has_zoneinfo_database')
def test_query_datetime_lookups(self):
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT))
self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2)
self.assertEqual(Event.objects.filter(dt__month=1).count(), 2)
self.assertEqual(Event.objects.filter(dt__day=1).count(), 2)
self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2)
self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1)
self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2)
self.assertEqual(Event.objects.filter(dt__second=0).count(), 2)
@skipUnlessDBFeature('has_zoneinfo_database')
def test_query_datetime_lookups_in_other_timezone(self):
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT))
with timezone.override(UTC):
# These two dates fall in the same day in EAT, but in different days,
# years and months in UTC.
self.assertEqual(Event.objects.filter(dt__year=2011).count(), 1)
self.assertEqual(Event.objects.filter(dt__month=1).count(), 1)
self.assertEqual(Event.objects.filter(dt__day=1).count(), 1)
self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 1)
self.assertEqual(Event.objects.filter(dt__hour=22).count(), 1)
self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2)
self.assertEqual(Event.objects.filter(dt__second=0).count(), 2)
def test_query_aggregation(self):
# Only min and max make sense for datetimes.
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT))
result = Event.objects.all().aggregate(Min('dt'), Max('dt'))
self.assertEqual(result, {
'dt__min': datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT),
'dt__max': datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT),
})
def test_query_annotation(self):
# Only min and max make sense for datetimes.
morning = Session.objects.create(name='morning')
afternoon = Session.objects.create(name='afternoon')
SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT), session=afternoon)
SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), session=afternoon)
SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT), session=morning)
morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT)
afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)
self.assertQuerysetEqual(
Session.objects.annotate(dt=Min('events__dt')).order_by('dt'),
[morning_min_dt, afternoon_min_dt],
transform=lambda d: d.dt)
self.assertQuerysetEqual(
Session.objects.annotate(dt=Min('events__dt')).filter(dt__lt=afternoon_min_dt),
[morning_min_dt],
transform=lambda d: d.dt)
self.assertQuerysetEqual(
Session.objects.annotate(dt=Min('events__dt')).filter(dt__gte=afternoon_min_dt),
[afternoon_min_dt],
transform=lambda d: d.dt)
@skipUnlessDBFeature('has_zoneinfo_database')
def test_query_datetimes(self):
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT))
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'year'),
[datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'month'),
[datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'day'),
[datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'hour'),
[datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=EAT),
datetime.datetime(2011, 1, 1, 4, 0, 0, tzinfo=EAT)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'minute'),
[datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT),
datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'second'),
[datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT),
datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)],
transform=lambda d: d)
@skipUnlessDBFeature('has_zoneinfo_database')
def test_query_datetimes_in_other_timezone(self):
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT))
with timezone.override(UTC):
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'year'),
[datetime.datetime(2010, 1, 1, 0, 0, 0, tzinfo=UTC),
datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'month'),
[datetime.datetime(2010, 12, 1, 0, 0, 0, tzinfo=UTC),
datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'day'),
[datetime.datetime(2010, 12, 31, 0, 0, 0, tzinfo=UTC),
datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'hour'),
[datetime.datetime(2010, 12, 31, 22, 0, 0, tzinfo=UTC),
datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=UTC)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'minute'),
[datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC),
datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC)],
transform=lambda d: d)
self.assertQuerysetEqual(
Event.objects.datetimes('dt', 'second'),
[datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC),
datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC)],
transform=lambda d: d)
def test_raw_sql(self):
# Regression test for #17755
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)
event = Event.objects.create(dt=dt)
self.assertQuerysetEqual(
Event.objects.raw('SELECT * FROM timezones_event WHERE dt = %s', [dt]),
[event],
transform=lambda d: d)
@requires_tz_support
def test_filter_date_field_with_aware_datetime(self):
# Regression test for #17742
day = datetime.date(2011, 9, 1)
AllDayEvent.objects.create(day=day)
# This is 2011-09-02T01:30:00+03:00 in EAT
dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC)
self.assertFalse(AllDayEvent.objects.filter(day__gte=dt).exists())
def test_null_datetime(self):
# Regression test for #17294
e = MaybeEvent.objects.create()
self.assertEqual(e.dt, None)
@override_settings(TIME_ZONE='Africa/Nairobi')
class SerializationTests(TestCase):
# Backend-specific notes:
# - JSON supports only milliseconds, microseconds will be truncated.
# - PyYAML dumps the UTC offset correctly for timezone-aware datetimes,
# but when it loads this representation, it substracts the offset and
# returns a naive datetime object in UTC (http://pyyaml.org/ticket/202).
# Tests are adapted to take these quirks into account.
def assert_python_contains_datetime(self, objects, dt):
self.assertEqual(objects[0]['fields']['dt'], dt)
def assert_json_contains_datetime(self, json, dt):
self.assertIn('"fields": {"dt": "%s"}' % dt, json)
def assert_xml_contains_datetime(self, xml, dt):
field = parseString(xml).getElementsByTagName('field')[0]
self.assertXMLEqual(field.childNodes[0].wholeText, dt)
def assert_yaml_contains_datetime(self, yaml, dt):
# Depending on the yaml dumper, '!timestamp' might be absent
six.assertRegex(self, yaml,
r"- fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt))
def test_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30)
data = serializers.serialize('python', [Event(dt=dt)])
self.assert_python_contains_datetime(data, dt)
obj = next(serializers.deserialize('python', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('json', [Event(dt=dt)])
self.assert_json_contains_datetime(data, "2011-09-01T13:20:30")
obj = next(serializers.deserialize('json', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('xml', [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30")
obj = next(serializers.deserialize('xml', data)).object
self.assertEqual(obj.dt, dt)
if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer):
data = serializers.serialize('yaml', [Event(dt=dt)])
self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30")
obj = next(serializers.deserialize('yaml', data)).object
self.assertEqual(obj.dt, dt)
def test_naive_datetime_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
data = serializers.serialize('python', [Event(dt=dt)])
self.assert_python_contains_datetime(data, dt)
obj = next(serializers.deserialize('python', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('json', [Event(dt=dt)])
self.assert_json_contains_datetime(data, "2011-09-01T13:20:30.405")
obj = next(serializers.deserialize('json', data)).object
self.assertEqual(obj.dt, dt.replace(microsecond=405000))
data = serializers.serialize('xml', [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30.405060")
obj = next(serializers.deserialize('xml', data)).object
self.assertEqual(obj.dt, dt)
if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer):
data = serializers.serialize('yaml', [Event(dt=dt)])
self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30.405060")
obj = next(serializers.deserialize('yaml', data)).object
self.assertEqual(obj.dt, dt)
def test_aware_datetime_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 17, 20, 30, 405060, tzinfo=ICT)
data = serializers.serialize('python', [Event(dt=dt)])
self.assert_python_contains_datetime(data, dt)
obj = next(serializers.deserialize('python', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('json', [Event(dt=dt)])
self.assert_json_contains_datetime(data, "2011-09-01T17:20:30.405+07:00")
obj = next(serializers.deserialize('json', data)).object
self.assertEqual(obj.dt, dt.replace(microsecond=405000))
data = serializers.serialize('xml', [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T17:20:30.405060+07:00")
obj = next(serializers.deserialize('xml', data)).object
self.assertEqual(obj.dt, dt)
if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer):
data = serializers.serialize('yaml', [Event(dt=dt)])
self.assert_yaml_contains_datetime(data, "2011-09-01 17:20:30.405060+07:00")
obj = next(serializers.deserialize('yaml', data)).object
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
def test_aware_datetime_in_utc(self):
dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
data = serializers.serialize('python', [Event(dt=dt)])
self.assert_python_contains_datetime(data, dt)
obj = next(serializers.deserialize('python', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('json', [Event(dt=dt)])
self.assert_json_contains_datetime(data, "2011-09-01T10:20:30Z")
obj = next(serializers.deserialize('json', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('xml', [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T10:20:30+00:00")
obj = next(serializers.deserialize('xml', data)).object
self.assertEqual(obj.dt, dt)
if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer):
data = serializers.serialize('yaml', [Event(dt=dt)])
self.assert_yaml_contains_datetime(data, "2011-09-01 10:20:30+00:00")
obj = next(serializers.deserialize('yaml', data)).object
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
def test_aware_datetime_in_local_timezone(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)
data = serializers.serialize('python', [Event(dt=dt)])
self.assert_python_contains_datetime(data, dt)
obj = next(serializers.deserialize('python', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('json', [Event(dt=dt)])
self.assert_json_contains_datetime(data, "2011-09-01T13:20:30+03:00")
obj = next(serializers.deserialize('json', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('xml', [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30+03:00")
obj = next(serializers.deserialize('xml', data)).object
self.assertEqual(obj.dt, dt)
if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer):
data = serializers.serialize('yaml', [Event(dt=dt)])
self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30+03:00")
obj = next(serializers.deserialize('yaml', data)).object
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
def test_aware_datetime_in_other_timezone(self):
dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT)
data = serializers.serialize('python', [Event(dt=dt)])
self.assert_python_contains_datetime(data, dt)
obj = next(serializers.deserialize('python', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('json', [Event(dt=dt)])
self.assert_json_contains_datetime(data, "2011-09-01T17:20:30+07:00")
obj = next(serializers.deserialize('json', data)).object
self.assertEqual(obj.dt, dt)
data = serializers.serialize('xml', [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T17:20:30+07:00")
obj = next(serializers.deserialize('xml', data)).object
self.assertEqual(obj.dt, dt)
if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer):
data = serializers.serialize('yaml', [Event(dt=dt)])
self.assert_yaml_contains_datetime(data, "2011-09-01 17:20:30+07:00")
obj = next(serializers.deserialize('yaml', data)).object
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
@override_settings(DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=True)
class TemplateTests(TestCase):
@requires_tz_support
def test_localtime_templatetag_and_filters(self):
"""
Test the {% localtime %} templatetag and related filters.
"""
datetimes = {
'utc': datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC),
'eat': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT),
'ict': datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT),
'naive': datetime.datetime(2011, 9, 1, 13, 20, 30),
}
templates = {
'notag': Template("{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}"),
'noarg': Template("{% load tz %}{% localtime %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"),
'on': Template("{% load tz %}{% localtime on %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"),
'off': Template("{% load tz %}{% localtime off %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"),
}
# Transform a list of keys in 'datetimes' to the expected template
# output. This makes the definition of 'results' more readable.
def t(*result):
return '|'.join(datetimes[key].isoformat() for key in result)
# Results for USE_TZ = True
results = {
'utc': {
'notag': t('eat', 'eat', 'utc', 'ict'),
'noarg': t('eat', 'eat', 'utc', 'ict'),
'on': t('eat', 'eat', 'utc', 'ict'),
'off': t('utc', 'eat', 'utc', 'ict'),
},
'eat': {
'notag': t('eat', 'eat', 'utc', 'ict'),
'noarg': t('eat', 'eat', 'utc', 'ict'),
'on': t('eat', 'eat', 'utc', 'ict'),
'off': t('eat', 'eat', 'utc', 'ict'),
},
'ict': {
'notag': t('eat', 'eat', 'utc', 'ict'),
'noarg': t('eat', 'eat', 'utc', 'ict'),
'on': t('eat', 'eat', 'utc', 'ict'),
'off': t('ict', 'eat', 'utc', 'ict'),
},
'naive': {
'notag': t('naive', 'eat', 'utc', 'ict'),
'noarg': t('naive', 'eat', 'utc', 'ict'),
'on': t('naive', 'eat', 'utc', 'ict'),
'off': t('naive', 'eat', 'utc', 'ict'),
}
}
for k1, dt in six.iteritems(datetimes):
for k2, tpl in six.iteritems(templates):
ctx = Context({'dt': dt, 'ICT': ICT})
actual = tpl.render(ctx)
expected = results[k1][k2]
self.assertEqual(actual, expected, '%s / %s: %r != %r' % (k1, k2, actual, expected))
# Changes for USE_TZ = False
results['utc']['notag'] = t('utc', 'eat', 'utc', 'ict')
results['ict']['notag'] = t('ict', 'eat', 'utc', 'ict')
with self.settings(USE_TZ=False):
for k1, dt in six.iteritems(datetimes):
for k2, tpl in six.iteritems(templates):
ctx = Context({'dt': dt, 'ICT': ICT})
actual = tpl.render(ctx)
expected = results[k1][k2]
self.assertEqual(actual, expected, '%s / %s: %r != %r' % (k1, k2, actual, expected))
@skipIf(pytz is None, "this test requires pytz")
def test_localtime_filters_with_pytz(self):
"""
Test the |localtime, |utc, and |timezone filters with pytz.
"""
# Use a pytz timezone as local time
tpl = Template("{% load tz %}{{ dt|localtime }}|{{ dt|utc }}")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 12, 20, 30)})
with self.settings(TIME_ZONE='Europe/Paris'):
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00|2011-09-01T10:20:30+00:00")
# Use a pytz timezone as argument
tpl = Template("{% load tz %}{{ dt|timezone:tz }}")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30),
'tz': pytz.timezone('Europe/Paris')})
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00")
# Use a pytz timezone name as argument
tpl = Template("{% load tz %}{{ dt|timezone:'Europe/Paris' }}")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30),
'tz': pytz.timezone('Europe/Paris')})
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00")
def test_localtime_templatetag_invalid_argument(self):
with self.assertRaises(TemplateSyntaxError):
Template("{% load tz %}{% localtime foo %}{% endlocaltime %}").render()
def test_localtime_filters_do_not_raise_exceptions(self):
"""
Test the |localtime, |utc, and |timezone filters on bad inputs.
"""
tpl = Template("{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:tz }}")
with self.settings(USE_TZ=True):
# bad datetime value
ctx = Context({'dt': None, 'tz': ICT})
self.assertEqual(tpl.render(ctx), "None|||")
ctx = Context({'dt': 'not a date', 'tz': ICT})
self.assertEqual(tpl.render(ctx), "not a date|||")
# bad timezone value
tpl = Template("{% load tz %}{{ dt|timezone:tz }}")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30), 'tz': None})
self.assertEqual(tpl.render(ctx), "")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30), 'tz': 'not a tz'})
self.assertEqual(tpl.render(ctx), "")
@requires_tz_support
def test_timezone_templatetag(self):
"""
Test the {% timezone %} templatetag.
"""
tpl = Template(
"{% load tz %}"
"{{ dt }}|"
"{% timezone tz1 %}"
"{{ dt }}|"
"{% timezone tz2 %}"
"{{ dt }}"
"{% endtimezone %}"
"{% endtimezone %}"
)
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC),
'tz1': ICT, 'tz2': None})
self.assertEqual(tpl.render(ctx), "2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|2011-09-01T13:20:30+03:00")
@skipIf(pytz is None, "this test requires pytz")
def test_timezone_templatetag_with_pytz(self):
"""
Test the {% timezone %} templatetag with pytz.
"""
tpl = Template("{% load tz %}{% timezone tz %}{{ dt }}{% endtimezone %}")
# Use a pytz timezone as argument
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT),
'tz': pytz.timezone('Europe/Paris')})
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00")
# Use a pytz timezone name as argument
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT),
'tz': 'Europe/Paris'})
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00")
def test_timezone_templatetag_invalid_argument(self):
with self.assertRaises(TemplateSyntaxError):
Template("{% load tz %}{% timezone %}{% endtimezone %}").render()
with self.assertRaises(ValueError if pytz is None else pytz.UnknownTimeZoneError):
Template("{% load tz %}{% timezone tz %}{% endtimezone %}").render(Context({'tz': 'foobar'}))
@skipIf(sys.platform.startswith('win'), "Windows uses non-standard time zone names")
def test_get_current_timezone_templatetag(self):
"""
Test the {% get_current_timezone %} templatetag.
"""
tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}")
self.assertEqual(tpl.render(Context()), "Africa/Nairobi" if pytz else "EAT")
with timezone.override(UTC):
self.assertEqual(tpl.render(Context()), "UTC")
tpl = Template("{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}{% endtimezone %}{{ time_zone }}")
self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700")
with timezone.override(UTC):
self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700")
@skipIf(pytz is None, "this test requires pytz")
def test_get_current_timezone_templatetag_with_pytz(self):
"""
Test the {% get_current_timezone %} templatetag with pytz.
"""
tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}")
with timezone.override(pytz.timezone('Europe/Paris')):
self.assertEqual(tpl.render(Context()), "Europe/Paris")
tpl = Template("{% load tz %}{% timezone 'Europe/Paris' %}{% get_current_timezone as time_zone %}{% endtimezone %}{{ time_zone }}")
self.assertEqual(tpl.render(Context()), "Europe/Paris")
def test_get_current_timezone_templatetag_invalid_argument(self):
with self.assertRaises(TemplateSyntaxError):
Template("{% load tz %}{% get_current_timezone %}").render()
@skipIf(sys.platform.startswith('win'), "Windows uses non-standard time zone names")
def test_tz_template_context_processor(self):
"""
Test the django.template.context_processors.tz template context processor.
"""
tpl = Template("{{ TIME_ZONE }}")
context = Context()
self.assertEqual(tpl.render(context), "")
request_context = RequestContext(HttpRequest(), processors=[context_processors.tz])
self.assertEqual(tpl.render(request_context), "Africa/Nairobi" if pytz else "EAT")
@requires_tz_support
def test_date_and_time_template_filters(self):
tpl = Template("{{ dt|date:'Y-m-d' }} at {{ dt|time:'H:i:s' }}")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)})
self.assertEqual(tpl.render(ctx), "2011-09-01 at 23:20:20")
with timezone.override(ICT):
self.assertEqual(tpl.render(ctx), "2011-09-02 at 03:20:20")
def test_date_and_time_template_filters_honor_localtime(self):
tpl = Template("{% load tz %}{% localtime off %}{{ dt|date:'Y-m-d' }} at {{ dt|time:'H:i:s' }}{% endlocaltime %}")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)})
self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20")
with timezone.override(ICT):
self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20")
def test_localtime_with_time_zone_setting_set_to_none(self):
# Regression for #17274
tpl = Template("{% load tz %}{{ dt }}")
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT)})
with self.settings(TIME_ZONE=None):
# the actual value depends on the system time zone of the host
self.assertTrue(tpl.render(ctx).startswith("2011"))
@requires_tz_support
def test_now_template_tag_uses_current_time_zone(self):
# Regression for #17343
tpl = Template("{% now \"O\" %}")
self.assertEqual(tpl.render(Context({})), "+0300")
with timezone.override(ICT):
self.assertEqual(tpl.render(Context({})), "+0700")
@override_settings(DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=False)
class LegacyFormsTests(TestCase):
def test_form(self):
form = EventForm({'dt': '2011-09-01 13:20:30'})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 13, 20, 30))
@skipIf(pytz is None, "this test requires pytz")
def test_form_with_non_existent_time(self):
form = EventForm({'dt': '2011-03-27 02:30:00'})
with timezone.override(pytz.timezone('Europe/Paris')):
# this is obviously a bug
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 3, 27, 2, 30, 0))
@skipIf(pytz is None, "this test requires pytz")
def test_form_with_ambiguous_time(self):
form = EventForm({'dt': '2011-10-30 02:30:00'})
with timezone.override(pytz.timezone('Europe/Paris')):
# this is obviously a bug
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 10, 30, 2, 30, 0))
def test_split_form(self):
form = EventSplitForm({'dt_0': '2011-09-01', 'dt_1': '13:20:30'})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 13, 20, 30))
def test_model_form(self):
EventModelForm({'dt': '2011-09-01 13:20:30'}).save()
e = Event.objects.get()
self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 13, 20, 30))
@override_settings(DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=True)
class NewFormsTests(TestCase):
@requires_tz_support
def test_form(self):
form = EventForm({'dt': '2011-09-01 13:20:30'})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
def test_form_with_other_timezone(self):
form = EventForm({'dt': '2011-09-01 17:20:30'})
with timezone.override(ICT):
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
def test_form_with_explicit_timezone(self):
form = EventForm({'dt': '2011-09-01 17:20:30+07:00'})
# Datetime inputs formats don't allow providing a time zone.
self.assertFalse(form.is_valid())
@skipIf(pytz is None, "this test requires pytz")
def test_form_with_non_existent_time(self):
with timezone.override(pytz.timezone('Europe/Paris')):
form = EventForm({'dt': '2011-03-27 02:30:00'})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['dt'],
["2011-03-27 02:30:00 couldn't be interpreted in time zone "
"Europe/Paris; it may be ambiguous or it may not exist."])
@skipIf(pytz is None, "this test requires pytz")
def test_form_with_ambiguous_time(self):
with timezone.override(pytz.timezone('Europe/Paris')):
form = EventForm({'dt': '2011-10-30 02:30:00'})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['dt'],
["2011-10-30 02:30:00 couldn't be interpreted in time zone "
"Europe/Paris; it may be ambiguous or it may not exist."])
@requires_tz_support
def test_split_form(self):
form = EventSplitForm({'dt_0': '2011-09-01', 'dt_1': '13:20:30'})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
@requires_tz_support
def test_localized_form(self):
form = EventLocalizedForm(initial={'dt': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)})
with timezone.override(ICT):
self.assertIn("2011-09-01 17:20:30", str(form))
@requires_tz_support
def test_model_form(self):
EventModelForm({'dt': '2011-09-01 13:20:30'}).save()
e = Event.objects.get()
self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
@requires_tz_support
def test_localized_model_form(self):
form = EventLocalizedModelForm(instance=Event(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)))
with timezone.override(ICT):
self.assertIn("2011-09-01 17:20:30", str(form))
@override_settings(DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=True,
PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='timezones.urls')
class AdminTests(TestCase):
fixtures = ['tz_users.xml']
def setUp(self):
self.client.login(username='super', password='secret')
@requires_tz_support
def test_changelist(self):
e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
response = self.client.get(reverse('admin:timezones_event_changelist'))
self.assertContains(response, e.dt.astimezone(EAT).isoformat())
def test_changelist_in_other_timezone(self):
e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
with timezone.override(ICT):
response = self.client.get(reverse('admin:timezones_event_changelist'))
self.assertContains(response, e.dt.astimezone(ICT).isoformat())
@requires_tz_support
def test_change_editable(self):
e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
response = self.client.get(reverse('admin:timezones_event_change', args=(e.pk,)))
self.assertContains(response, e.dt.astimezone(EAT).date().isoformat())
self.assertContains(response, e.dt.astimezone(EAT).time().isoformat())
def test_change_editable_in_other_timezone(self):
e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
with timezone.override(ICT):
response = self.client.get(reverse('admin:timezones_event_change', args=(e.pk,)))
self.assertContains(response, e.dt.astimezone(ICT).date().isoformat())
self.assertContains(response, e.dt.astimezone(ICT).time().isoformat())
@requires_tz_support
def test_change_readonly(self):
Timestamp.objects.create()
# re-fetch the object for backends that lose microseconds (MySQL)
t = Timestamp.objects.get()
response = self.client.get(reverse('admin:timezones_timestamp_change', args=(t.pk,)))
self.assertContains(response, t.created.astimezone(EAT).isoformat())
def test_change_readonly_in_other_timezone(self):
Timestamp.objects.create()
# re-fetch the object for backends that lose microseconds (MySQL)
t = Timestamp.objects.get()
with timezone.override(ICT):
response = self.client.get(reverse('admin:timezones_timestamp_change', args=(t.pk,)))
self.assertContains(response, t.created.astimezone(ICT).isoformat())
Django-1.8.7/tests/timezones/fixtures/ 0000775 0001750 0001750 00000000000 12625116243 017371 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/timezones/fixtures/tz_users.xml 0000664 0001750 0001750 00000002026 12625113144 021766 0 ustar tim tim 0000000 0000000
Django-1.8.7/tests/timezones/__init__.py 0000664 0001750 0001750 00000000000 12603513307 017615 0 ustar tim tim 0000000 0000000 Django-1.8.7/tests/timezones/forms.py 0000664 0001750 0001750 00000001020 12603513307 017207 0 ustar tim tim 0000000 0000000 from django import forms
from .models import Event
class EventForm(forms.Form):
dt = forms.DateTimeField()
class EventSplitForm(forms.Form):
dt = forms.SplitDateTimeField()
class EventLocalizedForm(forms.Form):
dt = forms.DateTimeField(localize=True)
class EventModelForm(forms.ModelForm):
class Meta:
model = Event
fields = '__all__'
class EventLocalizedModelForm(forms.ModelForm):
class Meta:
model = Event
fields = '__all__'
localized_fields = '__all__'
Django-1.8.7/tests/timezones/models.py 0000664 0001750 0001750 00000001110 12625113144 017343 0 ustar tim tim 0000000 0000000 from django.db import models
class Event(models.Model):
dt = models.DateTimeField()
class MaybeEvent(models.Model):
dt = models.DateTimeField(blank=True, null=True)
class Session(models.Model):
name = models.CharField(max_length=20)
class SessionEvent(models.Model):
dt = models.DateTimeField()
session = models.ForeignKey(Session, related_name='events')
class Timestamp(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class AllDayEvent(models.Model):
day = models.DateField()
Django-1.8.7/tests/timezones/admin.py 0000664 0001750 0001750 00000000467 12625113144 017166 0 ustar tim tim 0000000 0000000 from django.contrib import admin
from .models import Event, Timestamp
class EventAdmin(admin.ModelAdmin):
list_display = ('dt',)
admin.site.register(Event, EventAdmin)
class TimestampAdmin(admin.ModelAdmin):
readonly_fields = ('created', 'updated')
admin.site.register(Timestamp, TimestampAdmin)
Django-1.8.7/tests/template_tests/ 0000775 0001750 0001750 00000000000 12625116243 016540 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/alternate_urls.py 0000664 0001750 0001750 00000000421 12625116214 022131 0 ustar tim tim 0000000 0000000 from django.conf.urls import url
from . import views
urlpatterns = [
# View returning a template response
url(r'^template_response_view/$', views.template_response_view),
# A view that can be hard to find...
url(r'^snark/', views.snark, name='snark'),
]
Django-1.8.7/tests/template_tests/syntax_tests/ 0000775 0001750 0001750 00000000000 12625116243 021310 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/syntax_tests/test_basic.py 0000664 0001750 0001750 00000026173 12625116214 024011 0 ustar tim tim 0000000 0000000 from django.template.base import Context, TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import SilentAttrClass, SilentGetItemClass, SomeClass, setup
basic_templates = {
'basic-syntax01': 'something cool',
'basic-syntax02': '{{ headline }}',
'basic-syntax03': '{{ first }} --- {{ second }}',
}
class BasicSyntaxTests(SimpleTestCase):
@setup(basic_templates)
def test_basic_syntax01(self):
"""
Plain text should go through the template parser untouched.
"""
output = self.engine.render_to_string('basic-syntax01')
self.assertEqual(output, "something cool")
@setup(basic_templates)
def test_basic_syntax02(self):
"""
Variables should be replaced with their value in the current
context
"""
output = self.engine.render_to_string('basic-syntax02', {'headline': 'Success'})
self.assertEqual(output, 'Success')
@setup(basic_templates)
def test_basic_syntax03(self):
"""
More than one replacement variable is allowed in a template
"""
output = self.engine.render_to_string('basic-syntax03', {"first": 1, "second": 2})
self.assertEqual(output, '1 --- 2')
@setup({'basic-syntax04': 'as{{ missing }}df'})
def test_basic_syntax04(self):
"""
Fail silently when a variable is not found in the current context
"""
output = self.engine.render_to_string('basic-syntax04')
if self.engine.string_if_invalid:
self.assertEqual(output, 'asINVALIDdf')
else:
self.assertEqual(output, 'asdf')
@setup({'basic-syntax06': '{{ multi word variable }}'})
def test_basic_syntax06(self):
"""
A variable may not contain more than one word
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax06')
@setup({'basic-syntax07': '{{ }}'})
def test_basic_syntax07(self):
"""
Raise TemplateSyntaxError for empty variable tags.
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax07')
@setup({'basic-syntax08': '{{ }}'})
def test_basic_syntax08(self):
"""
Raise TemplateSyntaxError for empty variable tags.
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax08')
@setup({'basic-syntax09': '{{ var.method }}'})
def test_basic_syntax09(self):
"""
Attribute syntax allows a template to call an object's attribute
"""
output = self.engine.render_to_string('basic-syntax09', {'var': SomeClass()})
self.assertEqual(output, 'SomeClass.method')
@setup({'basic-syntax10': '{{ var.otherclass.method }}'})
def test_basic_syntax10(self):
"""
Multiple levels of attribute access are allowed.
"""
output = self.engine.render_to_string('basic-syntax10', {'var': SomeClass()})
self.assertEqual(output, 'OtherClass.method')
@setup({'basic-syntax11': '{{ var.blech }}'})
def test_basic_syntax11(self):
"""
Fail silently when a variable's attribute isn't found.
"""
output = self.engine.render_to_string('basic-syntax11', {'var': SomeClass()})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'basic-syntax12': '{{ var.__dict__ }}'})
def test_basic_syntax12(self):
"""
Raise TemplateSyntaxError when trying to access a variable
beginning with an underscore.
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax12')
# Raise TemplateSyntaxError when trying to access a variable
# containing an illegal character.
@setup({'basic-syntax13': "{{ va>r }}"})
def test_basic_syntax13(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax13')
@setup({'basic-syntax14': "{{ (var.r) }}"})
def test_basic_syntax14(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax14')
@setup({'basic-syntax15': "{{ sp%am }}"})
def test_basic_syntax15(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax15')
@setup({'basic-syntax16': "{{ eggs! }}"})
def test_basic_syntax16(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax16')
@setup({'basic-syntax17': "{{ moo? }}"})
def test_basic_syntax17(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax17')
@setup({'basic-syntax18': "{{ foo.bar }}"})
def test_basic_syntax18(self):
"""
Attribute syntax allows a template to call a dictionary key's
value.
"""
output = self.engine.render_to_string('basic-syntax18', {"foo": {"bar": "baz"}})
self.assertEqual(output, "baz")
@setup({'basic-syntax19': "{{ foo.spam }}"})
def test_basic_syntax19(self):
"""
Fail silently when a variable's dictionary key isn't found.
"""
output = self.engine.render_to_string('basic-syntax19', {"foo": {"bar": "baz"}})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'basic-syntax20': "{{ var.method2 }}"})
def test_basic_syntax20(self):
"""
Fail silently when accessing a non-simple method
"""
output = self.engine.render_to_string('basic-syntax20', {'var': SomeClass()})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'basic-syntax20b': "{{ var.method5 }}"})
def test_basic_syntax20b(self):
"""
Don't silence a TypeError if it was raised inside a callable.
"""
template = self.engine.get_template('basic-syntax20b')
with self.assertRaises(TypeError):
template.render(Context({'var': SomeClass()}))
# Don't get confused when parsing something that is almost, but not
# quite, a template tag.
@setup({'basic-syntax21': "a {{ moo %} b"})
def test_basic_syntax21(self):
output = self.engine.render_to_string('basic-syntax21')
self.assertEqual(output, "a {{ moo %} b")
@setup({'basic-syntax22': "{{ moo #}"})
def test_basic_syntax22(self):
output = self.engine.render_to_string('basic-syntax22')
self.assertEqual(output, "{{ moo #}")
@setup({'basic-syntax23': "{{ moo #} {{ cow }}"})
def test_basic_syntax23(self):
"""
Treat "moo #} {{ cow" as the variable. Not ideal, but costly to work
around, so this triggers an error.
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('basic-syntax23')
@setup({'basic-syntax24': "{{ moo\n }}"})
def test_basic_syntax24(self):
"""
Embedded newlines make it not-a-tag.
"""
output = self.engine.render_to_string('basic-syntax24')
self.assertEqual(output, "{{ moo\n }}")
# Literal strings are permitted inside variables, mostly for i18n
# purposes.
@setup({'basic-syntax25': '{{ "fred" }}'})
def test_basic_syntax25(self):
output = self.engine.render_to_string('basic-syntax25')
self.assertEqual(output, "fred")
@setup({'basic-syntax26': r'{{ "\"fred\"" }}'})
def test_basic_syntax26(self):
output = self.engine.render_to_string('basic-syntax26')
self.assertEqual(output, "\"fred\"")
@setup({'basic-syntax27': r'{{ _("\"fred\"") }}'})
def test_basic_syntax27(self):
output = self.engine.render_to_string('basic-syntax27')
self.assertEqual(output, "\"fred\"")
# #12554 -- Make sure a silent_variable_failure Exception is
# suppressed on dictionary and attribute lookup.
@setup({'basic-syntax28': "{{ a.b }}"})
def test_basic_syntax28(self):
output = self.engine.render_to_string('basic-syntax28', {'a': SilentGetItemClass()})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'basic-syntax29': "{{ a.b }}"})
def test_basic_syntax29(self):
output = self.engine.render_to_string('basic-syntax29', {'a': SilentAttrClass()})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
# Something that starts like a number but has an extra lookup works
# as a lookup.
@setup({'basic-syntax30': "{{ 1.2.3 }}"})
def test_basic_syntax30(self):
output = self.engine.render_to_string(
'basic-syntax30',
{"1": {"2": {"3": "d"}}}
)
self.assertEqual(output, 'd')
@setup({'basic-syntax31': "{{ 1.2.3 }}"})
def test_basic_syntax31(self):
output = self.engine.render_to_string(
'basic-syntax31',
{"1": {"2": ("a", "b", "c", "d")}},
)
self.assertEqual(output, 'd')
@setup({'basic-syntax32': "{{ 1.2.3 }}"})
def test_basic_syntax32(self):
output = self.engine.render_to_string(
'basic-syntax32',
{"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))},
)
self.assertEqual(output, 'd')
@setup({'basic-syntax33': "{{ 1.2.3 }}"})
def test_basic_syntax33(self):
output = self.engine.render_to_string(
'basic-syntax33',
{"1": ("xxxx", "yyyy", "abcd")},
)
self.assertEqual(output, 'd')
@setup({'basic-syntax34': "{{ 1.2.3 }}"})
def test_basic_syntax34(self):
output = self.engine.render_to_string(
'basic-syntax34',
{"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})}
)
self.assertEqual(output, 'd')
# Numbers are numbers even if their digits are in the context.
@setup({'basic-syntax35': "{{ 1 }}"})
def test_basic_syntax35(self):
output = self.engine.render_to_string('basic-syntax35', {"1": "abc"})
self.assertEqual(output, '1')
@setup({'basic-syntax36': "{{ 1.2 }}"})
def test_basic_syntax36(self):
output = self.engine.render_to_string('basic-syntax36', {"1": "abc"})
self.assertEqual(output, '1.2')
@setup({'basic-syntax37': '{{ callable }}'})
def test_basic_syntax37(self):
"""
Call methods in the top level of the context.
"""
output = self.engine.render_to_string('basic-syntax37', {"callable": lambda: "foo bar"})
self.assertEqual(output, 'foo bar')
@setup({'basic-syntax38': '{{ var.callable }}'})
def test_basic_syntax38(self):
"""
Call methods returned from dictionary lookups.
"""
output = self.engine.render_to_string('basic-syntax38', {"var": {"callable": lambda: "foo bar"}})
self.assertEqual(output, 'foo bar')
Django-1.8.7/tests/template_tests/syntax_tests/test_width_ratio.py 0000664 0001750 0001750 00000013616 12625116214 025243 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from django.utils import six
from ..utils import setup
class WidthRatioTagTests(SimpleTestCase):
@setup({'widthratio01': '{% widthratio a b 0 %}'})
def test_widthratio01(self):
output = self.engine.render_to_string('widthratio01', {'a': 50, 'b': 100})
self.assertEqual(output, '0')
@setup({'widthratio02': '{% widthratio a b 100 %}'})
def test_widthratio02(self):
output = self.engine.render_to_string('widthratio02', {'a': 0, 'b': 0})
self.assertEqual(output, '0')
@setup({'widthratio03': '{% widthratio a b 100 %}'})
def test_widthratio03(self):
output = self.engine.render_to_string('widthratio03', {'a': 0, 'b': 100})
self.assertEqual(output, '0')
@setup({'widthratio04': '{% widthratio a b 100 %}'})
def test_widthratio04(self):
output = self.engine.render_to_string('widthratio04', {'a': 50, 'b': 100})
self.assertEqual(output, '50')
@setup({'widthratio05': '{% widthratio a b 100 %}'})
def test_widthratio05(self):
output = self.engine.render_to_string('widthratio05', {'a': 100, 'b': 100})
self.assertEqual(output, '100')
@setup({'widthratio06': '{% widthratio a b 100 %}'})
def test_widthratio06(self):
"""
62.5 should round to 63 on Python 2 and 62 on Python 3
See http://docs.python.org/py3k/whatsnew/3.0.html
"""
output = self.engine.render_to_string('widthratio06', {'a': 50, 'b': 80})
self.assertEqual(output, '62' if six.PY3 else '63')
@setup({'widthratio07': '{% widthratio a b 100 %}'})
def test_widthratio07(self):
"""
71.4 should round to 71
"""
output = self.engine.render_to_string('widthratio07', {'a': 50, 'b': 70})
self.assertEqual(output, '71')
# Raise exception if we don't have 3 args, last one an integer
@setup({'widthratio08': '{% widthratio %}'})
def test_widthratio08(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('widthratio08')
@setup({'widthratio09': '{% widthratio a b %}'})
def test_widthratio09(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('widthratio09', {'a': 50, 'b': 100})
@setup({'widthratio10': '{% widthratio a b 100.0 %}'})
def test_widthratio10(self):
output = self.engine.render_to_string('widthratio10', {'a': 50, 'b': 100})
self.assertEqual(output, '50')
@setup({'widthratio11': '{% widthratio a b c %}'})
def test_widthratio11(self):
"""
#10043: widthratio should allow max_width to be a variable
"""
output = self.engine.render_to_string('widthratio11', {'a': 50, 'c': 100, 'b': 100})
self.assertEqual(output, '50')
# #18739: widthratio should handle None args consistently with
# non-numerics
@setup({'widthratio12a': '{% widthratio a b c %}'})
def test_widthratio12a(self):
output = self.engine.render_to_string('widthratio12a', {'a': 'a', 'c': 100, 'b': 100})
self.assertEqual(output, '')
@setup({'widthratio12b': '{% widthratio a b c %}'})
def test_widthratio12b(self):
output = self.engine.render_to_string('widthratio12b', {'a': None, 'c': 100, 'b': 100})
self.assertEqual(output, '')
@setup({'widthratio13a': '{% widthratio a b c %}'})
def test_widthratio13a(self):
output = self.engine.render_to_string('widthratio13a', {'a': 0, 'c': 100, 'b': 'b'})
self.assertEqual(output, '')
@setup({'widthratio13b': '{% widthratio a b c %}'})
def test_widthratio13b(self):
output = self.engine.render_to_string('widthratio13b', {'a': 0, 'c': 100, 'b': None})
self.assertEqual(output, '')
@setup({'widthratio14a': '{% widthratio a b c %}'})
def test_widthratio14a(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('widthratio14a', {'a': 0, 'c': 'c', 'b': 100})
@setup({'widthratio14b': '{% widthratio a b c %}'})
def test_widthratio14b(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('widthratio14b', {'a': 0, 'c': None, 'b': 100})
@setup({'widthratio15': '{% load custom %}{% widthratio a|noop:"x y" b 0 %}'})
def test_widthratio15(self):
"""
Test whitespace in filter argument
"""
output = self.engine.render_to_string('widthratio15', {'a': 50, 'b': 100})
self.assertEqual(output, '0')
# Widthratio with variable assignment
@setup({'widthratio16': '{% widthratio a b 100 as variable %}-{{ variable }}-'})
def test_widthratio16(self):
output = self.engine.render_to_string('widthratio16', {'a': 50, 'b': 100})
self.assertEqual(output, '-50-')
@setup({'widthratio17': '{% widthratio a b 100 as variable %}-{{ variable }}-'})
def test_widthratio17(self):
output = self.engine.render_to_string('widthratio17', {'a': 100, 'b': 100})
self.assertEqual(output, '-100-')
@setup({'widthratio18': '{% widthratio a b 100 as %}'})
def test_widthratio18(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('widthratio18')
@setup({'widthratio19': '{% widthratio a b 100 not_as variable %}'})
def test_widthratio19(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('widthratio19')
@setup({'widthratio20': '{% widthratio a b 100 %}'})
def test_widthratio20(self):
output = self.engine.render_to_string('widthratio20', {'a': float('inf'), 'b': float('inf')})
self.assertEqual(output, '')
@setup({'widthratio21': '{% widthratio a b 100 %}'})
def test_widthratio21(self):
output = self.engine.render_to_string('widthratio21', {'a': float('inf'), 'b': 2})
self.assertEqual(output, '')
Django-1.8.7/tests/template_tests/syntax_tests/test_cycle.py 0000664 0001750 0001750 00000015511 12625116214 024021 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango110Warning
from ..utils import setup
class CycleTagTests(SimpleTestCase):
@setup({'cycle01': '{% cycle a %}'})
def test_cycle01(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('cycle01')
@setup({'cycle02': '{% cycle a,b,c as abc %}{% cycle abc %}'})
def test_cycle02(self):
output = self.engine.render_to_string('cycle02')
self.assertEqual(output, 'ab')
@setup({'cycle03': '{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}'})
def test_cycle03(self):
output = self.engine.render_to_string('cycle03')
self.assertEqual(output, 'abc')
@setup({'cycle04': '{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}'})
def test_cycle04(self):
output = self.engine.render_to_string('cycle04')
self.assertEqual(output, 'abca')
@setup({'cycle05': '{% cycle %}'})
def test_cycle05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('cycle05')
@setup({'cycle06': '{% cycle a %}'})
def test_cycle06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('cycle06')
@setup({'cycle07': '{% cycle a,b,c as foo %}{% cycle bar %}'})
def test_cycle07(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('cycle07')
@setup({'cycle08': '{% cycle a,b,c as foo %}{% cycle foo %}{{ foo }}{{ foo }}{% cycle foo %}{{ foo }}'})
def test_cycle08(self):
output = self.engine.render_to_string('cycle08')
self.assertEqual(output, 'abbbcc')
@setup({'cycle09': '{% for i in test %}{% cycle a,b %}{{ i }},{% endfor %}'})
def test_cycle09(self):
output = self.engine.render_to_string('cycle09', {'test': list(range(5))})
self.assertEqual(output, 'a0,b1,a2,b3,a4,')
@setup({'cycle10': "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}"})
def test_cycle10(self):
output = self.engine.render_to_string('cycle10')
self.assertEqual(output, 'ab')
@setup({'cycle11': "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}"})
def test_cycle11(self):
output = self.engine.render_to_string('cycle11')
self.assertEqual(output, 'abc')
@setup({'cycle12': "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}"})
def test_cycle12(self):
output = self.engine.render_to_string('cycle12')
self.assertEqual(output, 'abca')
@setup({'cycle13': "{% for i in test %}{% cycle 'a' 'b' %}{{ i }},{% endfor %}"})
def test_cycle13(self):
output = self.engine.render_to_string('cycle13', {'test': list(range(5))})
self.assertEqual(output, 'a0,b1,a2,b3,a4,')
@setup({'cycle14': '{% cycle one two as foo %}{% cycle foo %}'})
def test_cycle14(self):
output = self.engine.render_to_string('cycle14', {'one': '1', 'two': '2'})
self.assertEqual(output, '12')
@setup({'cycle15': '{% for i in test %}{% cycle aye bee %}{{ i }},{% endfor %}'})
def test_cycle15(self):
output = self.engine.render_to_string('cycle15', {'test': list(range(5)), 'aye': 'a', 'bee': 'b'})
self.assertEqual(output, 'a0,b1,a2,b3,a4,')
@setup({'cycle16': '{% cycle one|lower two as foo %}{% cycle foo %}'})
def test_cycle16(self):
output = self.engine.render_to_string('cycle16', {'one': 'A', 'two': '2'})
self.assertEqual(output, 'a2')
@setup({'cycle17': "{% cycle 'a' 'b' 'c' as abc silent %}"
"{% cycle abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}"})
def test_cycle17(self):
output = self.engine.render_to_string('cycle17')
self.assertEqual(output, '')
@setup({'cycle18': "{% cycle 'a' 'b' 'c' as foo invalid_flag %}"})
def test_cycle18(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('cycle18')
@setup({'cycle19': "{% cycle 'a' 'b' as silent %}{% cycle silent %}"})
def test_cycle19(self):
output = self.engine.render_to_string('cycle19')
self.assertEqual(output, 'ab')
@setup({'cycle20': '{% cycle one two as foo %} & {% cycle foo %}'})
def test_cycle20(self):
output = self.engine.render_to_string('cycle20', {'two': 'C & D', 'one': 'A & B'})
self.assertEqual(output, 'A & B & C & D')
@setup({'cycle21': '{% filter force_escape %}'
'{% cycle one two as foo %} & {% cycle foo %}{% endfilter %}'})
def test_cycle21(self):
output = self.engine.render_to_string('cycle21', {'two': 'C & D', 'one': 'A & B'})
self.assertEqual(output, 'A & B & C & D')
@setup({'cycle22': "{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}"})
def test_cycle22(self):
output = self.engine.render_to_string('cycle22', {'values': [1, 2, 3, 4]})
self.assertEqual(output, '1234')
@setup({'cycle23': "{% for x in values %}"
"{% cycle 'a' 'b' 'c' as abc silent %}{{ abc }}{{ x }}{% endfor %}"})
def test_cycle23(self):
output = self.engine.render_to_string('cycle23', {'values': [1, 2, 3, 4]})
self.assertEqual(output, 'a1b2c3a4')
@setup({
'cycle24': "{% for x in values %}"
"{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}",
'included-cycle': '{{ abc }}',
})
def test_cycle24(self):
output = self.engine.render_to_string('cycle24', {'values': [1, 2, 3, 4]})
self.assertEqual(output, 'abca')
@setup({'cycle25': '{% cycle a as abc %}'})
def test_cycle25(self):
output = self.engine.render_to_string('cycle25', {'a': '<'})
self.assertEqual(output, '<')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'cycle26': '{% load cycle from future %}{% cycle a b as ab %}{% cycle ab %}'})
def test_cycle26(self):
output = self.engine.render_to_string('cycle26', {'a': '<', 'b': '>'})
self.assertEqual(output, '<>')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'cycle27': '{% load cycle from future %}'
'{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}'})
def test_cycle27(self):
output = self.engine.render_to_string('cycle27', {'a': '<', 'b': '>'})
self.assertEqual(output, '<>')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'cycle28': '{% load cycle from future %}{% cycle a|safe b as ab %}{% cycle ab %}'})
def test_cycle28(self):
output = self.engine.render_to_string('cycle28', {'a': '<', 'b': '>'})
self.assertEqual(output, '<>')
Django-1.8.7/tests/template_tests/syntax_tests/test_now.py 0000664 0001750 0001750 00000003765 12625116214 023535 0 ustar tim tim 0000000 0000000 from datetime import datetime
from django.test import SimpleTestCase
from django.utils.formats import date_format
from ..utils import setup
class NowTagTests(SimpleTestCase):
@setup({'now01': '{% now "j n Y" %}'})
def test_now01(self):
"""
Simple case
"""
output = self.engine.render_to_string('now01')
self.assertEqual(output, "%d %d %d" % (
datetime.now().day, datetime.now().month, datetime.now().year,
))
# Check parsing of locale strings
@setup({'now02': '{% now "DATE_FORMAT" %}'})
def test_now02(self):
output = self.engine.render_to_string('now02')
self.assertEqual(output, date_format(datetime.now()))
@setup({'now03': '{% now \'j n Y\' %}'})
def test_now03(self):
"""
#15092 - Also accept simple quotes
"""
output = self.engine.render_to_string('now03')
self.assertEqual(output, "%d %d %d" % (
datetime.now().day, datetime.now().month, datetime.now().year,
))
@setup({'now04': '{% now \'DATE_FORMAT\' %}'})
def test_now04(self):
output = self.engine.render_to_string('now04')
self.assertEqual(output, date_format(datetime.now()))
@setup({'now05': '{% now \'j "n" Y\'%}'})
def test_now05(self):
output = self.engine.render_to_string('now05')
self.assertEqual(output, '%d "%d" %d' % (
datetime.now().day, datetime.now().month, datetime.now().year,
))
@setup({'now06': '{% now "j \'n\' Y"%}'})
def test_now06(self):
output = self.engine.render_to_string('now06')
self.assertEqual(output, "%d '%d' %d" % (
datetime.now().day, datetime.now().month, datetime.now().year,
))
@setup({'now07': '{% now "j n Y" as N %}-{{N}}-'})
def test_now07(self):
output = self.engine.render_to_string('now07')
self.assertEqual(output, '-%d %d %d-' % (
datetime.now().day, datetime.now().month, datetime.now().year,
))
Django-1.8.7/tests/template_tests/syntax_tests/test_numpy.py 0000664 0001750 0001750 00000002625 12625116214 024074 0 ustar tim tim 0000000 0000000 import warnings
from unittest import skipIf
from django.test import SimpleTestCase
from ..utils import setup
try:
import numpy
except ImportError:
numpy = False
@skipIf(numpy is False, "Numpy must be installed to run these tests.")
class NumpyTests(SimpleTestCase):
# Ignore numpy deprecation warnings (#23890)
warnings.filterwarnings(
"ignore",
"Using a non-integer number instead of an "
"integer will result in an error in the future",
DeprecationWarning
)
@setup({'numpy-array-index01': '{{ var.1 }}'})
def test_numpy_array_index01(self):
"""
Numpy's array-index syntax allows a template to access a certain
item of a subscriptable object.
"""
output = self.engine.render_to_string(
'numpy-array-index01',
{'var': numpy.array(["first item", "second item"])},
)
self.assertEqual(output, 'second item')
@setup({'numpy-array-index02': '{{ var.5 }}'})
def test_numpy_array_index02(self):
"""
Fail silently when the array index is out of range.
"""
output = self.engine.render_to_string(
'numpy-array-index02',
{'var': numpy.array(["first item", "second item"])},
)
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
Django-1.8.7/tests/template_tests/syntax_tests/test_autoescape.py 0000664 0001750 0001750 00000012707 12625116214 025057 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import SafeClass, UnsafeClass, setup
class AutoescapeTagTests(SimpleTestCase):
@setup({'autoescape-tag01': '{% autoescape off %}hello{% endautoescape %}'})
def test_autoescape_tag01(self):
output = self.engine.render_to_string('autoescape-tag01')
self.assertEqual(output, 'hello')
@setup({'autoescape-tag02': '{% autoescape off %}{{ first }}{% endautoescape %}'})
def test_autoescape_tag02(self):
output = self.engine.render_to_string('autoescape-tag02', {'first': 'hello'})
self.assertEqual(output, 'hello')
@setup({'autoescape-tag03': '{% autoescape on %}{{ first }}{% endautoescape %}'})
def test_autoescape_tag03(self):
output = self.engine.render_to_string('autoescape-tag03', {'first': 'hello'})
self.assertEqual(output, '<b>hello</b>')
# Autoescape disabling and enabling nest in a predictable way.
@setup({'autoescape-tag04': '{% autoescape off %}'
'{{ first }} {% autoescape on %}{{ first }}{% endautoescape %}{% endautoescape %}'})
def test_autoescape_tag04(self):
output = self.engine.render_to_string('autoescape-tag04', {'first': ''})
self.assertEqual(output, ' <a>')
@setup({'autoescape-tag05': '{% autoescape on %}{{ first }}{% endautoescape %}'})
def test_autoescape_tag05(self):
output = self.engine.render_to_string('autoescape-tag05', {'first': 'first'})
self.assertEqual(output, '<b>first</b>')
# Strings (ASCII or unicode) already marked as "safe" are not
# auto-escaped
@setup({'autoescape-tag06': '{{ first }}'})
def test_autoescape_tag06(self):
output = self.engine.render_to_string('autoescape-tag06', {'first': mark_safe('first')})
self.assertEqual(output, 'first')
@setup({'autoescape-tag07': '{% autoescape on %}{{ first }}{% endautoescape %}'})
def test_autoescape_tag07(self):
output = self.engine.render_to_string('autoescape-tag07', {'first': mark_safe('Apple')})
self.assertEqual(output, 'Apple')
@setup({'autoescape-tag08': r'{% autoescape on %}'
r'{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}'})
def test_autoescape_tag08(self):
"""
Literal string arguments to filters, if used in the result, are safe.
"""
output = self.engine.render_to_string('autoescape-tag08', {"var": None})
self.assertEqual(output, ' endquote" hah')
# Objects which return safe strings as their __str__ method
# won't get double-escaped.
@setup({'autoescape-tag09': r'{{ unsafe }}'})
def test_autoescape_tag09(self):
output = self.engine.render_to_string('autoescape-tag09', {'unsafe': UnsafeClass()})
self.assertEqual(output, 'you & me')
@setup({'autoescape-tag10': r'{{ safe }}'})
def test_autoescape_tag10(self):
output = self.engine.render_to_string('autoescape-tag10', {'safe': SafeClass()})
self.assertEqual(output, 'you > me')
@setup({'autoescape-filtertag01': '{{ first }}{% filter safe %}{{ first }} x'})
@setup({'autoescape-ifequal01': '{% ifequal var "this & that" %}yes{% endifequal %}'})
def test_autoescape_ifequal01(self):
"""
ifequal compares unescaped vales.
"""
output = self.engine.render_to_string('autoescape-ifequal01', {'var': 'this & that'})
self.assertEqual(output, 'yes')
# Arguments to filters are 'safe' and manipulate their input unescaped.
@setup({'autoescape-filters01': '{{ var|cut:"&" }}'})
def test_autoescape_filters01(self):
output = self.engine.render_to_string('autoescape-filters01', {'var': 'this & that'})
self.assertEqual(output, 'this that')
@setup({'autoescape-filters02': '{{ var|join:" & " }}'})
def test_autoescape_filters02(self):
output = self.engine.render_to_string('autoescape-filters02', {'var': ('Tom', 'Dick', 'Harry')})
self.assertEqual(output, 'Tom & Dick & Harry')
@setup({'autoescape-literals01': '{{ "this & that" }}'})
def test_autoescape_literals01(self):
"""
Literal strings are safe.
"""
output = self.engine.render_to_string('autoescape-literals01')
self.assertEqual(output, 'this & that')
@setup({'autoescape-stringiterations01': '{% for l in var %}{{ l }},{% endfor %}'})
def test_autoescape_stringiterations01(self):
"""
Iterating over strings outputs safe characters.
"""
output = self.engine.render_to_string('autoescape-stringiterations01', {'var': 'K&R'})
self.assertEqual(output, 'K,&,R,')
@setup({'autoescape-lookup01': '{{ var.key }}'})
def test_autoescape_lookup01(self):
"""
Escape requirement survives lookup.
"""
output = self.engine.render_to_string('autoescape-lookup01', {'var': {'key': 'this & that'}})
self.assertEqual(output, 'this & that')
Django-1.8.7/tests/template_tests/syntax_tests/test_if.py 0000664 0001750 0001750 00000061437 12625116214 023330 0 ustar tim tim 0000000 0000000 import warnings
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase, ignore_warnings
from django.test.utils import reset_warning_registry
from django.utils.deprecation import RemovedInDjango110Warning
from ..utils import TestObj, setup
class IfTagTests(SimpleTestCase):
@setup({'if-tag01': '{% if foo %}yes{% else %}no{% endif %}'})
def test_if_tag01(self):
output = self.engine.render_to_string('if-tag01', {'foo': True})
self.assertEqual(output, 'yes')
@setup({'if-tag02': '{% if foo %}yes{% else %}no{% endif %}'})
def test_if_tag02(self):
output = self.engine.render_to_string('if-tag02', {'foo': False})
self.assertEqual(output, 'no')
@setup({'if-tag03': '{% if foo %}yes{% else %}no{% endif %}'})
def test_if_tag03(self):
output = self.engine.render_to_string('if-tag03')
self.assertEqual(output, 'no')
@setup({'if-tag04': '{% if foo %}foo{% elif bar %}bar{% endif %}'})
def test_if_tag04(self):
output = self.engine.render_to_string('if-tag04', {'foo': True})
self.assertEqual(output, 'foo')
@setup({'if-tag05': '{% if foo %}foo{% elif bar %}bar{% endif %}'})
def test_if_tag05(self):
output = self.engine.render_to_string('if-tag05', {'bar': True})
self.assertEqual(output, 'bar')
@setup({'if-tag06': '{% if foo %}foo{% elif bar %}bar{% endif %}'})
def test_if_tag06(self):
output = self.engine.render_to_string('if-tag06')
self.assertEqual(output, '')
@setup({'if-tag07': '{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}'})
def test_if_tag07(self):
output = self.engine.render_to_string('if-tag07', {'foo': True})
self.assertEqual(output, 'foo')
@setup({'if-tag08': '{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}'})
def test_if_tag08(self):
output = self.engine.render_to_string('if-tag08', {'bar': True})
self.assertEqual(output, 'bar')
@setup({'if-tag09': '{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}'})
def test_if_tag09(self):
output = self.engine.render_to_string('if-tag09')
self.assertEqual(output, 'nothing')
@setup({'if-tag10': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'})
def test_if_tag10(self):
output = self.engine.render_to_string('if-tag10', {'foo': True})
self.assertEqual(output, 'foo')
@setup({'if-tag11': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'})
def test_if_tag11(self):
output = self.engine.render_to_string('if-tag11', {'bar': True})
self.assertEqual(output, 'bar')
@setup({'if-tag12': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'})
def test_if_tag12(self):
output = self.engine.render_to_string('if-tag12', {'baz': True})
self.assertEqual(output, 'baz')
@setup({'if-tag13': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'})
def test_if_tag13(self):
output = self.engine.render_to_string('if-tag13')
self.assertEqual(output, 'nothing')
# Filters
@setup({'if-tag-filter01': '{% if foo|length == 5 %}yes{% else %}no{% endif %}'})
def test_if_tag_filter01(self):
output = self.engine.render_to_string('if-tag-filter01', {'foo': 'abcde'})
self.assertEqual(output, 'yes')
@setup({'if-tag-filter02': '{% if foo|upper == \'ABC\' %}yes{% else %}no{% endif %}'})
def test_if_tag_filter02(self):
output = self.engine.render_to_string('if-tag-filter02')
self.assertEqual(output, 'no')
# Equality
@setup({'if-tag-eq01': '{% if foo == bar %}yes{% else %}no{% endif %}'})
def test_if_tag_eq01(self):
output = self.engine.render_to_string('if-tag-eq01')
self.assertEqual(output, 'yes')
@setup({'if-tag-eq02': '{% if foo == bar %}yes{% else %}no{% endif %}'})
def test_if_tag_eq02(self):
output = self.engine.render_to_string('if-tag-eq02', {'foo': 1})
self.assertEqual(output, 'no')
@setup({'if-tag-eq03': '{% if foo == bar %}yes{% else %}no{% endif %}'})
def test_if_tag_eq03(self):
output = self.engine.render_to_string('if-tag-eq03', {'foo': 1, 'bar': 1})
self.assertEqual(output, 'yes')
@setup({'if-tag-eq04': '{% if foo == bar %}yes{% else %}no{% endif %}'})
def test_if_tag_eq04(self):
output = self.engine.render_to_string('if-tag-eq04', {'foo': 1, 'bar': 2})
self.assertEqual(output, 'no')
@setup({'if-tag-eq05': '{% if foo == \'\' %}yes{% else %}no{% endif %}'})
def test_if_tag_eq05(self):
output = self.engine.render_to_string('if-tag-eq05')
self.assertEqual(output, 'no')
# Comparison
@setup({'if-tag-gt-01': '{% if 2 > 1 %}yes{% else %}no{% endif %}'})
def test_if_tag_gt_01(self):
output = self.engine.render_to_string('if-tag-gt-01')
self.assertEqual(output, 'yes')
@setup({'if-tag-gt-02': '{% if 1 > 1 %}yes{% else %}no{% endif %}'})
def test_if_tag_gt_02(self):
output = self.engine.render_to_string('if-tag-gt-02')
self.assertEqual(output, 'no')
@setup({'if-tag-gte-01': '{% if 1 >= 1 %}yes{% else %}no{% endif %}'})
def test_if_tag_gte_01(self):
output = self.engine.render_to_string('if-tag-gte-01')
self.assertEqual(output, 'yes')
@setup({'if-tag-gte-02': '{% if 1 >= 2 %}yes{% else %}no{% endif %}'})
def test_if_tag_gte_02(self):
output = self.engine.render_to_string('if-tag-gte-02')
self.assertEqual(output, 'no')
@setup({'if-tag-lt-01': '{% if 1 < 2 %}yes{% else %}no{% endif %}'})
def test_if_tag_lt_01(self):
output = self.engine.render_to_string('if-tag-lt-01')
self.assertEqual(output, 'yes')
@setup({'if-tag-lt-02': '{% if 1 < 1 %}yes{% else %}no{% endif %}'})
def test_if_tag_lt_02(self):
output = self.engine.render_to_string('if-tag-lt-02')
self.assertEqual(output, 'no')
@setup({'if-tag-lte-01': '{% if 1 <= 1 %}yes{% else %}no{% endif %}'})
def test_if_tag_lte_01(self):
output = self.engine.render_to_string('if-tag-lte-01')
self.assertEqual(output, 'yes')
@setup({'if-tag-lte-02': '{% if 2 <= 1 %}yes{% else %}no{% endif %}'})
def test_if_tag_lte_02(self):
output = self.engine.render_to_string('if-tag-lte-02')
self.assertEqual(output, 'no')
# Contains
@setup({'if-tag-in-01': '{% if 1 in x %}yes{% else %}no{% endif %}'})
def test_if_tag_in_01(self):
output = self.engine.render_to_string('if-tag-in-01', {'x': [1]})
self.assertEqual(output, 'yes')
@setup({'if-tag-in-02': '{% if 2 in x %}yes{% else %}no{% endif %}'})
def test_if_tag_in_02(self):
output = self.engine.render_to_string('if-tag-in-02', {'x': [1]})
self.assertEqual(output, 'no')
@setup({'if-tag-not-in-01': '{% if 1 not in x %}yes{% else %}no{% endif %}'})
def test_if_tag_not_in_01(self):
output = self.engine.render_to_string('if-tag-not-in-01', {'x': [1]})
self.assertEqual(output, 'no')
@setup({'if-tag-not-in-02': '{% if 2 not in x %}yes{% else %}no{% endif %}'})
def test_if_tag_not_in_02(self):
output = self.engine.render_to_string('if-tag-not-in-02', {'x': [1]})
self.assertEqual(output, 'yes')
# AND
@setup({'if-tag-and01': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and01(self):
output = self.engine.render_to_string('if-tag-and01', {'foo': True, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-and02': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and02(self):
output = self.engine.render_to_string('if-tag-and02', {'foo': True, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-and03': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and03(self):
output = self.engine.render_to_string('if-tag-and03', {'foo': False, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-and04': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and04(self):
output = self.engine.render_to_string('if-tag-and04', {'foo': False, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-and05': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and05(self):
output = self.engine.render_to_string('if-tag-and05', {'foo': False})
self.assertEqual(output, 'no')
@setup({'if-tag-and06': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and06(self):
output = self.engine.render_to_string('if-tag-and06', {'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-and07': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and07(self):
output = self.engine.render_to_string('if-tag-and07', {'foo': True})
self.assertEqual(output, 'no')
@setup({'if-tag-and08': '{% if foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_and08(self):
output = self.engine.render_to_string('if-tag-and08', {'bar': True})
self.assertEqual(output, 'no')
# OR
@setup({'if-tag-or01': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or01(self):
output = self.engine.render_to_string('if-tag-or01', {'foo': True, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-or02': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or02(self):
output = self.engine.render_to_string('if-tag-or02', {'foo': True, 'bar': False})
self.assertEqual(output, 'yes')
@setup({'if-tag-or03': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or03(self):
output = self.engine.render_to_string('if-tag-or03', {'foo': False, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-or04': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or04(self):
output = self.engine.render_to_string('if-tag-or04', {'foo': False, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-or05': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or05(self):
output = self.engine.render_to_string('if-tag-or05', {'foo': False})
self.assertEqual(output, 'no')
@setup({'if-tag-or06': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or06(self):
output = self.engine.render_to_string('if-tag-or06', {'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-or07': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or07(self):
output = self.engine.render_to_string('if-tag-or07', {'foo': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-or08': '{% if foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_or08(self):
output = self.engine.render_to_string('if-tag-or08', {'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-or09': '{% if foo or bar or baz %}yes{% else %}no{% endif %}'})
def test_if_tag_or09(self):
"""
multiple ORs
"""
output = self.engine.render_to_string('if-tag-or09', {'baz': True})
self.assertEqual(output, 'yes')
# NOT
@setup({'if-tag-not01': '{% if not foo %}no{% else %}yes{% endif %}'})
def test_if_tag_not01(self):
output = self.engine.render_to_string('if-tag-not01', {'foo': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-not02': '{% if not not foo %}no{% else %}yes{% endif %}'})
def test_if_tag_not02(self):
output = self.engine.render_to_string('if-tag-not02', {'foo': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not06': '{% if foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not06(self):
output = self.engine.render_to_string('if-tag-not06')
self.assertEqual(output, 'no')
@setup({'if-tag-not07': '{% if foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not07(self):
output = self.engine.render_to_string('if-tag-not07', {'foo': True, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not08': '{% if foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not08(self):
output = self.engine.render_to_string('if-tag-not08', {'foo': True, 'bar': False})
self.assertEqual(output, 'yes')
@setup({'if-tag-not09': '{% if foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not09(self):
output = self.engine.render_to_string('if-tag-not09', {'foo': False, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not10': '{% if foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not10(self):
output = self.engine.render_to_string('if-tag-not10', {'foo': False, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-not11': '{% if not foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not11(self):
output = self.engine.render_to_string('if-tag-not11')
self.assertEqual(output, 'no')
@setup({'if-tag-not12': '{% if not foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not12(self):
output = self.engine.render_to_string('if-tag-not12', {'foo': True, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not13': '{% if not foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not13(self):
output = self.engine.render_to_string('if-tag-not13', {'foo': True, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-not14': '{% if not foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not14(self):
output = self.engine.render_to_string('if-tag-not14', {'foo': False, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-not15': '{% if not foo and bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not15(self):
output = self.engine.render_to_string('if-tag-not15', {'foo': False, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-not16': '{% if foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not16(self):
output = self.engine.render_to_string('if-tag-not16')
self.assertEqual(output, 'yes')
@setup({'if-tag-not17': '{% if foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not17(self):
output = self.engine.render_to_string('if-tag-not17', {'foo': True, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-not18': '{% if foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not18(self):
output = self.engine.render_to_string('if-tag-not18', {'foo': True, 'bar': False})
self.assertEqual(output, 'yes')
@setup({'if-tag-not19': '{% if foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not19(self):
output = self.engine.render_to_string('if-tag-not19', {'foo': False, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not20': '{% if foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not20(self):
output = self.engine.render_to_string('if-tag-not20', {'foo': False, 'bar': False})
self.assertEqual(output, 'yes')
@setup({'if-tag-not21': '{% if not foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not21(self):
output = self.engine.render_to_string('if-tag-not21')
self.assertEqual(output, 'yes')
@setup({'if-tag-not22': '{% if not foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not22(self):
output = self.engine.render_to_string('if-tag-not22', {'foo': True, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-not23': '{% if not foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not23(self):
output = self.engine.render_to_string('if-tag-not23', {'foo': True, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-not24': '{% if not foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not24(self):
output = self.engine.render_to_string('if-tag-not24', {'foo': False, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-not25': '{% if not foo or bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not25(self):
output = self.engine.render_to_string('if-tag-not25', {'foo': False, 'bar': False})
self.assertEqual(output, 'yes')
@setup({'if-tag-not26': '{% if not foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not26(self):
output = self.engine.render_to_string('if-tag-not26')
self.assertEqual(output, 'yes')
@setup({'if-tag-not27': '{% if not foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not27(self):
output = self.engine.render_to_string('if-tag-not27', {'foo': True, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not28': '{% if not foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not28(self):
output = self.engine.render_to_string('if-tag-not28', {'foo': True, 'bar': False})
self.assertEqual(output, 'no')
@setup({'if-tag-not29': '{% if not foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not29(self):
output = self.engine.render_to_string('if-tag-not29', {'foo': False, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not30': '{% if not foo and not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not30(self):
output = self.engine.render_to_string('if-tag-not30', {'foo': False, 'bar': False})
self.assertEqual(output, 'yes')
@setup({'if-tag-not31': '{% if not foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not31(self):
output = self.engine.render_to_string('if-tag-not31')
self.assertEqual(output, 'yes')
@setup({'if-tag-not32': '{% if not foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not32(self):
output = self.engine.render_to_string('if-tag-not32', {'foo': True, 'bar': True})
self.assertEqual(output, 'no')
@setup({'if-tag-not33': '{% if not foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not33(self):
output = self.engine.render_to_string('if-tag-not33', {'foo': True, 'bar': False})
self.assertEqual(output, 'yes')
@setup({'if-tag-not34': '{% if not foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not34(self):
output = self.engine.render_to_string('if-tag-not34', {'foo': False, 'bar': True})
self.assertEqual(output, 'yes')
@setup({'if-tag-not35': '{% if not foo or not bar %}yes{% else %}no{% endif %}'})
def test_if_tag_not35(self):
output = self.engine.render_to_string('if-tag-not35', {'foo': False, 'bar': False})
self.assertEqual(output, 'yes')
# Various syntax errors
@setup({'if-tag-error01': '{% if %}yes{% endif %}'})
def test_if_tag_error01(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error01')
@setup({'if-tag-error02': '{% if foo and %}yes{% else %}no{% endif %}'})
def test_if_tag_error02(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('if-tag-error02', {'foo': True})
@setup({'if-tag-error03': '{% if foo or %}yes{% else %}no{% endif %}'})
def test_if_tag_error03(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('if-tag-error03', {'foo': True})
@setup({'if-tag-error04': '{% if not foo and %}yes{% else %}no{% endif %}'})
def test_if_tag_error04(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('if-tag-error04', {'foo': True})
@setup({'if-tag-error05': '{% if not foo or %}yes{% else %}no{% endif %}'})
def test_if_tag_error05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('if-tag-error05', {'foo': True})
@setup({'if-tag-error06': '{% if abc def %}yes{% endif %}'})
def test_if_tag_error06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error06')
@setup({'if-tag-error07': '{% if not %}yes{% endif %}'})
def test_if_tag_error07(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error07')
@setup({'if-tag-error08': '{% if and %}yes{% endif %}'})
def test_if_tag_error08(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error08')
@setup({'if-tag-error09': '{% if or %}yes{% endif %}'})
def test_if_tag_error09(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error09')
@setup({'if-tag-error10': '{% if == %}yes{% endif %}'})
def test_if_tag_error10(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error10')
@setup({'if-tag-error11': '{% if 1 == %}yes{% endif %}'})
def test_if_tag_error11(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error11')
@setup({'if-tag-error12': '{% if a not b %}yes{% endif %}'})
def test_if_tag_error12(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('if-tag-error12')
@setup({'if-tag-shortcircuit01': '{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}'})
def test_if_tag_shortcircuit01(self):
"""
If evaluations are shortcircuited where possible
"""
output = self.engine.render_to_string('if-tag-shortcircuit01', {'x': TestObj()})
self.assertEqual(output, 'yes')
@setup({'if-tag-shortcircuit02': '{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}'})
def test_if_tag_shortcircuit02(self):
"""
The is_bad() function should not be evaluated. If it is, an
exception is raised.
"""
output = self.engine.render_to_string('if-tag-shortcircuit02', {'x': TestObj()})
self.assertEqual(output, 'no')
@setup({'if-tag-badarg01': '{% if x|default_if_none:y %}yes{% endif %}'})
def test_if_tag_badarg01(self):
"""
Non-existent args
"""
output = self.engine.render_to_string('if-tag-badarg01')
self.assertEqual(output, '')
@setup({'if-tag-badarg02': '{% if x|default_if_none:y %}yes{% endif %}'})
def test_if_tag_badarg02(self):
output = self.engine.render_to_string('if-tag-badarg02', {'y': 0})
self.assertEqual(output, '')
@setup({'if-tag-badarg03': '{% if x|default_if_none:y %}yes{% endif %}'})
def test_if_tag_badarg03(self):
output = self.engine.render_to_string('if-tag-badarg03', {'y': 1})
self.assertEqual(output, 'yes')
@setup({'if-tag-badarg04': '{% if x|default_if_none:y %}yes{% else %}no{% endif %}'})
def test_if_tag_badarg04(self):
output = self.engine.render_to_string('if-tag-badarg04')
self.assertEqual(output, 'no')
@setup({'if-tag-eq-deprecated': '{% if foo = bar %}yes{% else %}no{% endif %}'},
test_once=True)
def test_if_tag_eq_deprecated(self):
reset_warning_registry()
with warnings.catch_warnings(record=True) as warns:
warnings.simplefilter('always')
output = self.engine.render_to_string('if-tag-eq-deprecated')
self.assertEqual(output, 'yes')
self.assertEqual(len(warns), 1)
self.assertEqual(
str(warns[0].message),
"Operator '=' is deprecated and will be removed in Django 1.10. "
"Use '==' instead."
)
@ignore_warnings(category=RemovedInDjango110Warning)
class TestEqualitySingleEqualsSign(SimpleTestCase):
# The following tests should be changed to template.TemplateSyntaxError
# (or simply removed) when the deprecation path ends in Django 1.10.
@setup({'if-tag-eq01': '{% if foo = bar %}yes{% else %}no{% endif %}'})
def test_if_tag_eq01(self):
output = self.engine.render_to_string('if-tag-eq01', {'foo': 1})
self.assertEqual(output, 'no')
@setup({'if-tag-eq02': '{% if foo = bar %}yes{% else %}no{% endif %}'})
def test_if_tag_eq02(self):
output = self.engine.render_to_string('if-tag-eq02', {'foo': 1, 'bar': 1})
self.assertEqual(output, 'yes')
@setup({'if-tag-eq03': '{% if foo = bar %}yes{% else %}no{% endif %}'})
def test_if_tag_eq03(self):
output = self.engine.render_to_string('if-tag-eq03', {'foo': 1, 'bar': 2})
self.assertEqual(output, 'no')
@setup({'if-tag-eq04': '{% if foo == \'\' %}yes{% else %}no{% endif %}'})
def test_if_tag_eq04(self):
output = self.engine.render_to_string('if-tag-eq04')
self.assertEqual(output, 'no')
Django-1.8.7/tests/template_tests/syntax_tests/test_template_tag.py 0000664 0001750 0001750 00000005042 12625116214 025366 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class TemplateTagTests(SimpleTestCase):
@setup({'templatetag01': '{% templatetag openblock %}'})
def test_templatetag01(self):
output = self.engine.render_to_string('templatetag01')
self.assertEqual(output, '{%')
@setup({'templatetag02': '{% templatetag closeblock %}'})
def test_templatetag02(self):
output = self.engine.render_to_string('templatetag02')
self.assertEqual(output, '%}')
@setup({'templatetag03': '{% templatetag openvariable %}'})
def test_templatetag03(self):
output = self.engine.render_to_string('templatetag03')
self.assertEqual(output, '{{')
@setup({'templatetag04': '{% templatetag closevariable %}'})
def test_templatetag04(self):
output = self.engine.render_to_string('templatetag04')
self.assertEqual(output, '}}')
@setup({'templatetag05': '{% templatetag %}'})
def test_templatetag05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('templatetag05')
@setup({'templatetag06': '{% templatetag foo %}'})
def test_templatetag06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('templatetag06')
@setup({'templatetag07': '{% templatetag openbrace %}'})
def test_templatetag07(self):
output = self.engine.render_to_string('templatetag07')
self.assertEqual(output, '{')
@setup({'templatetag08': '{% templatetag closebrace %}'})
def test_templatetag08(self):
output = self.engine.render_to_string('templatetag08')
self.assertEqual(output, '}')
@setup({'templatetag09': '{% templatetag openbrace %}{% templatetag openbrace %}'})
def test_templatetag09(self):
output = self.engine.render_to_string('templatetag09')
self.assertEqual(output, '{{')
@setup({'templatetag10': '{% templatetag closebrace %}{% templatetag closebrace %}'})
def test_templatetag10(self):
output = self.engine.render_to_string('templatetag10')
self.assertEqual(output, '}}')
@setup({'templatetag11': '{% templatetag opencomment %}'})
def test_templatetag11(self):
output = self.engine.render_to_string('templatetag11')
self.assertEqual(output, '{#')
@setup({'templatetag12': '{% templatetag closecomment %}'})
def test_templatetag12(self):
output = self.engine.render_to_string('templatetag12')
self.assertEqual(output, '#}')
Django-1.8.7/tests/template_tests/syntax_tests/test_exceptions.py 0000664 0001750 0001750 00000004063 12625116214 025103 0 ustar tim tim 0000000 0000000 from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
from .test_extends import inheritance_templates
class ExceptionsTests(SimpleTestCase):
@setup({'exception01': "{% extends 'nonexistent' %}"})
def test_exception01(self):
"""
Raise exception for invalid template name
"""
with self.assertRaises(TemplateDoesNotExist):
self.engine.render_to_string('exception01')
@setup({'exception02': '{% extends nonexistent %}'})
def test_exception02(self):
"""
Raise exception for invalid variable template name
"""
if self.engine.string_if_invalid:
with self.assertRaises(TemplateDoesNotExist):
self.engine.render_to_string('exception02')
else:
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('exception02')
@setup(
{'exception03': "{% extends 'inheritance01' %}"
"{% block first %}2{% endblock %}{% extends 'inheritance16' %}"},
inheritance_templates,
)
def test_exception03(self):
"""
Raise exception for extra {% extends %} tags
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('exception03')
@setup(
{'exception04': "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}"},
inheritance_templates,
)
def test_exception04(self):
"""
Raise exception for custom tags used in child with {% load %} tag in parent, not in child
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('exception04')
@setup({'exception05': '{% block first %}{{ block.super }}{% endblock %}'})
def test_exception05(self):
"""
Raise exception for block.super used in base template
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('exception05')
Django-1.8.7/tests/template_tests/syntax_tests/test_filter_tag.py 0000664 0001750 0001750 00000003403 12625116214 025037 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class FilterTagTests(SimpleTestCase):
@setup({'filter01': '{% filter upper %}{% endfilter %}'})
def test_filter01(self):
output = self.engine.render_to_string('filter01')
self.assertEqual(output, '')
@setup({'filter02': '{% filter upper %}django{% endfilter %}'})
def test_filter02(self):
output = self.engine.render_to_string('filter02')
self.assertEqual(output, 'DJANGO')
@setup({'filter03': '{% filter upper|lower %}django{% endfilter %}'})
def test_filter03(self):
output = self.engine.render_to_string('filter03')
self.assertEqual(output, 'django')
@setup({'filter04': '{% filter cut:remove %}djangospam{% endfilter %}'})
def test_filter04(self):
output = self.engine.render_to_string('filter04', {'remove': 'spam'})
self.assertEqual(output, 'django')
@setup({'filter05': '{% filter safe %}fail{% endfilter %}'})
def test_filter05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter05')
@setup({'filter05bis': '{% filter upper|safe %}fail{% endfilter %}'})
def test_filter05bis(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter05bis')
@setup({'filter06': '{% filter escape %}fail{% endfilter %}'})
def test_filter06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter06')
@setup({'filter06bis': '{% filter upper|escape %}fail{% endfilter %}'})
def test_filter06bis(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter06bis')
Django-1.8.7/tests/template_tests/syntax_tests/test_for.py 0000664 0001750 0001750 00000020355 12625116214 023512 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango110Warning
from ..utils import setup
class ForTagTests(SimpleTestCase):
@setup({'for-tag01': '{% for val in values %}{{ val }}{% endfor %}'})
def test_for_tag01(self):
output = self.engine.render_to_string('for-tag01', {'values': [1, 2, 3]})
self.assertEqual(output, '123')
@setup({'for-tag02': '{% for val in values reversed %}{{ val }}{% endfor %}'})
def test_for_tag02(self):
output = self.engine.render_to_string('for-tag02', {'values': [1, 2, 3]})
self.assertEqual(output, '321')
@setup({'for-tag-vars01': '{% for val in values %}{{ forloop.counter }}{% endfor %}'})
def test_for_tag_vars01(self):
output = self.engine.render_to_string('for-tag-vars01', {'values': [6, 6, 6]})
self.assertEqual(output, '123')
@setup({'for-tag-vars02': '{% for val in values %}{{ forloop.counter0 }}{% endfor %}'})
def test_for_tag_vars02(self):
output = self.engine.render_to_string('for-tag-vars02', {'values': [6, 6, 6]})
self.assertEqual(output, '012')
@setup({'for-tag-vars03': '{% for val in values %}{{ forloop.revcounter }}{% endfor %}'})
def test_for_tag_vars03(self):
output = self.engine.render_to_string('for-tag-vars03', {'values': [6, 6, 6]})
self.assertEqual(output, '321')
@setup({'for-tag-vars04': '{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}'})
def test_for_tag_vars04(self):
output = self.engine.render_to_string('for-tag-vars04', {'values': [6, 6, 6]})
self.assertEqual(output, '210')
@setup({'for-tag-vars05': '{% for val in values %}'
'{% if forloop.first %}f{% else %}x{% endif %}{% endfor %}'})
def test_for_tag_vars05(self):
output = self.engine.render_to_string('for-tag-vars05', {'values': [6, 6, 6]})
self.assertEqual(output, 'fxx')
@setup({'for-tag-vars06': '{% for val in values %}'
'{% if forloop.last %}l{% else %}x{% endif %}{% endfor %}'})
def test_for_tag_vars06(self):
output = self.engine.render_to_string('for-tag-vars06', {'values': [6, 6, 6]})
self.assertEqual(output, 'xxl')
@setup({'for-tag-unpack01': '{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}'})
def test_for_tag_unpack01(self):
output = self.engine.render_to_string('for-tag-unpack01', {'items': (('one', 1), ('two', 2))})
self.assertEqual(output, 'one:1/two:2/')
@setup({'for-tag-unpack03': '{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}'})
def test_for_tag_unpack03(self):
output = self.engine.render_to_string('for-tag-unpack03', {'items': (('one', 1), ('two', 2))})
self.assertEqual(output, 'one:1/two:2/')
@setup({'for-tag-unpack04': '{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}'})
def test_for_tag_unpack04(self):
output = self.engine.render_to_string('for-tag-unpack04', {'items': (('one', 1), ('two', 2))})
self.assertEqual(output, 'one:1/two:2/')
@setup({'for-tag-unpack05': '{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}'})
def test_for_tag_unpack05(self):
output = self.engine.render_to_string('for-tag-unpack05', {'items': (('one', 1), ('two', 2))})
self.assertEqual(output, 'one:1/two:2/')
@setup({'for-tag-unpack06': '{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}'})
def test_for_tag_unpack06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('for-tag-unpack06', {'items': (('one', 1), ('two', 2))})
@setup({'for-tag-unpack07': '{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}'})
def test_for_tag_unpack07(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('for-tag-unpack07', {'items': (('one', 1), ('two', 2))})
@setup({'for-tag-unpack08': '{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}'})
def test_for_tag_unpack08(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('for-tag-unpack08', {'items': (('one', 1), ('two', 2))})
@setup({'for-tag-unpack09': '{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}'})
def test_for_tag_unpack09(self):
"""
Ensure that a single loopvar doesn't truncate the list in val.
"""
output = self.engine.render_to_string('for-tag-unpack09', {'items': (('one', 1), ('two', 2))})
self.assertEqual(output, 'one:1/two:2/')
@setup({'for-tag-unpack13': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'})
def test_for_tag_unpack13(self):
output = self.engine.render_to_string('for-tag-unpack13', {'items': (('one', 1, 'carrot'), ('two', 2, 'cheese'))})
if self.engine.string_if_invalid:
self.assertEqual(output, 'one:1,carrot/two:2,cheese/')
else:
self.assertEqual(output, 'one:1,carrot/two:2,cheese/')
@setup({'for-tag-empty01': '{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}'})
def test_for_tag_empty01(self):
output = self.engine.render_to_string('for-tag-empty01', {'values': [1, 2, 3]})
self.assertEqual(output, '123')
@setup({'for-tag-empty02': '{% for val in values %}{{ val }}{% empty %}values array empty{% endfor %}'})
def test_for_tag_empty02(self):
output = self.engine.render_to_string('for-tag-empty02', {'values': []})
self.assertEqual(output, 'values array empty')
@setup({'for-tag-empty03': '{% for val in values %}'
'{{ val }}{% empty %}values array not found{% endfor %}'})
def test_for_tag_empty03(self):
output = self.engine.render_to_string('for-tag-empty03')
self.assertEqual(output, 'values array not found')
@setup({'for-tag-filter-ws': "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}"})
def test_for_tag_filter_ws(self):
"""
#19882
"""
output = self.engine.render_to_string('for-tag-filter-ws', {'s': 'abc'})
self.assertEqual(output, 'abc')
# These tests raise deprecation warnings and will raise an exception
# in Django 1.10. The existing behavior is silent truncation if the
# length of loopvars differs to the length of each set of items.
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'for-tag-unpack10': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'})
def test_for_tag_unpack10(self):
output = self.engine.render_to_string(
'for-tag-unpack10',
{'items': (('one', 1, 'carrot'), ('two', 2, 'orange'))},
)
self.assertEqual(output, 'one:1/two:2/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'for-tag-unpack11': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'})
def test_for_tag_unpack11(self):
output = self.engine.render_to_string(
'for-tag-unpack11',
{'items': (('one', 1), ('two', 2))},
)
if self.engine.string_if_invalid:
self.assertEqual(output, 'one:1,INVALID/two:2,INVALID/')
else:
self.assertEqual(output, 'one:1,/two:2,/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'for-tag-unpack12': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'})
def test_for_tag_unpack12(self):
output = self.engine.render_to_string(
'for-tag-unpack12',
{'items': (('one', 1, 'carrot'), ('two', 2))}
)
if self.engine.string_if_invalid:
self.assertEqual(output, 'one:1,carrot/two:2,INVALID/')
else:
self.assertEqual(output, 'one:1,carrot/two:2,/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'for-tag-unpack14': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'})
def test_for_tag_unpack14(self):
output = self.engine.render_to_string('for-tag-unpack14', {'items': (1, 2)})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID:INVALID/INVALID:INVALID/')
else:
self.assertEqual(output, ':/:/')
Django-1.8.7/tests/template_tests/syntax_tests/test_invalid_string.py 0000664 0001750 0001750 00000004321 12625116214 025733 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class InvalidStringTests(SimpleTestCase):
@setup({'invalidstr01': '{{ var|default:"Foo" }}'})
def test_invalidstr01(self):
output = self.engine.render_to_string('invalidstr01')
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, 'Foo')
@setup({'invalidstr02': '{{ var|default_if_none:"Foo" }}'})
def test_invalidstr02(self):
output = self.engine.render_to_string('invalidstr02')
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'invalidstr03': '{% for v in var %}({{ v }}){% endfor %}'})
def test_invalidstr03(self):
output = self.engine.render_to_string('invalidstr03')
self.assertEqual(output, '')
@setup({'invalidstr04': '{% if var %}Yes{% else %}No{% endif %}'})
def test_invalidstr04(self):
output = self.engine.render_to_string('invalidstr04')
self.assertEqual(output, 'No')
@setup({'invalidstr04_2': '{% if var|default:"Foo" %}Yes{% else %}No{% endif %}'})
def test_invalidstr04_2(self):
output = self.engine.render_to_string('invalidstr04_2')
self.assertEqual(output, 'Yes')
@setup({'invalidstr05': '{{ var }}'})
def test_invalidstr05(self):
output = self.engine.render_to_string('invalidstr05')
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'invalidstr06': '{{ var.prop }}'})
def test_invalidstr06(self):
output = self.engine.render_to_string('invalidstr06')
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'invalidstr07': '{% load i18n %}{% blocktrans %}{{ var }}{% endblocktrans %}'})
def test_invalidstr07(self):
output = self.engine.render_to_string('invalidstr07')
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
Django-1.8.7/tests/template_tests/syntax_tests/test_if_equal.py 0000664 0001750 0001750 00000023244 12625116214 024511 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class IfEqualTagTests(SimpleTestCase):
@setup({'ifequal01': '{% ifequal a b %}yes{% endifequal %}'})
def test_ifequal01(self):
output = self.engine.render_to_string('ifequal01', {'a': 1, 'b': 2})
self.assertEqual(output, '')
@setup({'ifequal02': '{% ifequal a b %}yes{% endifequal %}'})
def test_ifequal02(self):
output = self.engine.render_to_string('ifequal02', {'a': 1, 'b': 1})
self.assertEqual(output, 'yes')
@setup({'ifequal03': '{% ifequal a b %}yes{% else %}no{% endifequal %}'})
def test_ifequal03(self):
output = self.engine.render_to_string('ifequal03', {'a': 1, 'b': 2})
self.assertEqual(output, 'no')
@setup({'ifequal04': '{% ifequal a b %}yes{% else %}no{% endifequal %}'})
def test_ifequal04(self):
output = self.engine.render_to_string('ifequal04', {'a': 1, 'b': 1})
self.assertEqual(output, 'yes')
@setup({'ifequal05': '{% ifequal a \'test\' %}yes{% else %}no{% endifequal %}'})
def test_ifequal05(self):
output = self.engine.render_to_string('ifequal05', {'a': 'test'})
self.assertEqual(output, 'yes')
@setup({'ifequal06': '{% ifequal a \'test\' %}yes{% else %}no{% endifequal %}'})
def test_ifequal06(self):
output = self.engine.render_to_string('ifequal06', {'a': 'no'})
self.assertEqual(output, 'no')
@setup({'ifequal07': '{% ifequal a "test" %}yes{% else %}no{% endifequal %}'})
def test_ifequal07(self):
output = self.engine.render_to_string('ifequal07', {'a': 'test'})
self.assertEqual(output, 'yes')
@setup({'ifequal08': '{% ifequal a "test" %}yes{% else %}no{% endifequal %}'})
def test_ifequal08(self):
output = self.engine.render_to_string('ifequal08', {'a': 'no'})
self.assertEqual(output, 'no')
@setup({'ifequal09': '{% ifequal a "test" %}yes{% else %}no{% endifequal %}'})
def test_ifequal09(self):
output = self.engine.render_to_string('ifequal09')
self.assertEqual(output, 'no')
@setup({'ifequal10': '{% ifequal a b %}yes{% else %}no{% endifequal %}'})
def test_ifequal10(self):
output = self.engine.render_to_string('ifequal10')
self.assertEqual(output, 'yes')
# SMART SPLITTING
@setup({'ifequal-split01': '{% ifequal a "test man" %}yes{% else %}no{% endifequal %}'})
def test_ifequal_split01(self):
output = self.engine.render_to_string('ifequal-split01')
self.assertEqual(output, 'no')
@setup({'ifequal-split02': '{% ifequal a "test man" %}yes{% else %}no{% endifequal %}'})
def test_ifequal_split02(self):
output = self.engine.render_to_string('ifequal-split02', {'a': 'foo'})
self.assertEqual(output, 'no')
@setup({'ifequal-split03': '{% ifequal a "test man" %}yes{% else %}no{% endifequal %}'})
def test_ifequal_split03(self):
output = self.engine.render_to_string('ifequal-split03', {'a': 'test man'})
self.assertEqual(output, 'yes')
@setup({'ifequal-split04': '{% ifequal a \'test man\' %}yes{% else %}no{% endifequal %}'})
def test_ifequal_split04(self):
output = self.engine.render_to_string('ifequal-split04', {'a': 'test man'})
self.assertEqual(output, 'yes')
@setup({'ifequal-split05': '{% ifequal a \'i "love" you\' %}yes{% else %}no{% endifequal %}'})
def test_ifequal_split05(self):
output = self.engine.render_to_string('ifequal-split05', {'a': ''})
self.assertEqual(output, 'no')
@setup({'ifequal-split06': '{% ifequal a \'i "love" you\' %}yes{% else %}no{% endifequal %}'})
def test_ifequal_split06(self):
output = self.engine.render_to_string('ifequal-split06', {'a': 'i "love" you'})
self.assertEqual(output, 'yes')
@setup({'ifequal-split07': '{% ifequal a \'i "love" you\' %}yes{% else %}no{% endifequal %}'})
def test_ifequal_split07(self):
output = self.engine.render_to_string('ifequal-split07', {'a': 'i love you'})
self.assertEqual(output, 'no')
@setup({'ifequal-split08': r"{% ifequal a 'I\'m happy' %}yes{% else %}no{% endifequal %}"})
def test_ifequal_split08(self):
output = self.engine.render_to_string('ifequal-split08', {'a': "I'm happy"})
self.assertEqual(output, 'yes')
@setup({'ifequal-split09': r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}"})
def test_ifequal_split09(self):
output = self.engine.render_to_string('ifequal-split09', {'a': 'slash\man'})
self.assertEqual(output, 'yes')
@setup({'ifequal-split10': r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}"})
def test_ifequal_split10(self):
output = self.engine.render_to_string('ifequal-split10', {'a': 'slashman'})
self.assertEqual(output, 'no')
# NUMERIC RESOLUTION
@setup({'ifequal-numeric01': '{% ifequal x 5 %}yes{% endifequal %}'})
def test_ifequal_numeric01(self):
output = self.engine.render_to_string('ifequal-numeric01', {'x': '5'})
self.assertEqual(output, '')
@setup({'ifequal-numeric02': '{% ifequal x 5 %}yes{% endifequal %}'})
def test_ifequal_numeric02(self):
output = self.engine.render_to_string('ifequal-numeric02', {'x': 5})
self.assertEqual(output, 'yes')
@setup({'ifequal-numeric03': '{% ifequal x 5.2 %}yes{% endifequal %}'})
def test_ifequal_numeric03(self):
output = self.engine.render_to_string('ifequal-numeric03', {'x': 5})
self.assertEqual(output, '')
@setup({'ifequal-numeric04': '{% ifequal x 5.2 %}yes{% endifequal %}'})
def test_ifequal_numeric04(self):
output = self.engine.render_to_string('ifequal-numeric04', {'x': 5.2})
self.assertEqual(output, 'yes')
@setup({'ifequal-numeric05': '{% ifequal x 0.2 %}yes{% endifequal %}'})
def test_ifequal_numeric05(self):
output = self.engine.render_to_string('ifequal-numeric05', {'x': 0.2})
self.assertEqual(output, 'yes')
@setup({'ifequal-numeric06': '{% ifequal x .2 %}yes{% endifequal %}'})
def test_ifequal_numeric06(self):
output = self.engine.render_to_string('ifequal-numeric06', {'x': 0.2})
self.assertEqual(output, 'yes')
@setup({'ifequal-numeric07': '{% ifequal x 2. %}yes{% endifequal %}'})
def test_ifequal_numeric07(self):
output = self.engine.render_to_string('ifequal-numeric07', {'x': 2})
self.assertEqual(output, '')
@setup({'ifequal-numeric08': '{% ifequal x "5" %}yes{% endifequal %}'})
def test_ifequal_numeric08(self):
output = self.engine.render_to_string('ifequal-numeric08', {'x': 5})
self.assertEqual(output, '')
@setup({'ifequal-numeric09': '{% ifequal x "5" %}yes{% endifequal %}'})
def test_ifequal_numeric09(self):
output = self.engine.render_to_string('ifequal-numeric09', {'x': '5'})
self.assertEqual(output, 'yes')
@setup({'ifequal-numeric10': '{% ifequal x -5 %}yes{% endifequal %}'})
def test_ifequal_numeric10(self):
output = self.engine.render_to_string('ifequal-numeric10', {'x': -5})
self.assertEqual(output, 'yes')
@setup({'ifequal-numeric11': '{% ifequal x -5.2 %}yes{% endifequal %}'})
def test_ifequal_numeric11(self):
output = self.engine.render_to_string('ifequal-numeric11', {'x': -5.2})
self.assertEqual(output, 'yes')
@setup({'ifequal-numeric12': '{% ifequal x +5 %}yes{% endifequal %}'})
def test_ifequal_numeric12(self):
output = self.engine.render_to_string('ifequal-numeric12', {'x': 5})
self.assertEqual(output, 'yes')
# FILTER EXPRESSIONS AS ARGUMENTS
@setup({'ifequal-filter01': '{% ifequal a|upper "A" %}x{% endifequal %}'})
def test_ifequal_filter01(self):
output = self.engine.render_to_string('ifequal-filter01', {'a': 'a'})
self.assertEqual(output, 'x')
@setup({'ifequal-filter02': '{% ifequal "A" a|upper %}x{% endifequal %}'})
def test_ifequal_filter02(self):
output = self.engine.render_to_string('ifequal-filter02', {'a': 'a'})
self.assertEqual(output, 'x')
@setup({'ifequal-filter03': '{% ifequal a|upper b|upper %}x{% endifequal %}'})
def test_ifequal_filter03(self):
output = self.engine.render_to_string('ifequal-filter03', {'a': 'x', 'b': 'X'})
self.assertEqual(output, 'x')
@setup({'ifequal-filter04': '{% ifequal x|slice:"1" "a" %}x{% endifequal %}'})
def test_ifequal_filter04(self):
output = self.engine.render_to_string('ifequal-filter04', {'x': 'aaa'})
self.assertEqual(output, 'x')
@setup({'ifequal-filter05': '{% ifequal x|slice:"1"|upper "A" %}x{% endifequal %}'})
def test_ifequal_filter05(self):
output = self.engine.render_to_string('ifequal-filter05', {'x': 'aaa'})
self.assertEqual(output, 'x')
class IfNotEqualTagTests(SimpleTestCase):
@setup({'ifnotequal01': '{% ifnotequal a b %}yes{% endifnotequal %}'})
def test_ifnotequal01(self):
output = self.engine.render_to_string('ifnotequal01', {'a': 1, 'b': 2})
self.assertEqual(output, 'yes')
@setup({'ifnotequal02': '{% ifnotequal a b %}yes{% endifnotequal %}'})
def test_ifnotequal02(self):
output = self.engine.render_to_string('ifnotequal02', {'a': 1, 'b': 1})
self.assertEqual(output, '')
@setup({'ifnotequal03': '{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}'})
def test_ifnotequal03(self):
output = self.engine.render_to_string('ifnotequal03', {'a': 1, 'b': 2})
self.assertEqual(output, 'yes')
@setup({'ifnotequal04': '{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}'})
def test_ifnotequal04(self):
output = self.engine.render_to_string('ifnotequal04', {'a': 1, 'b': 1})
self.assertEqual(output, 'no')
Django-1.8.7/tests/template_tests/syntax_tests/test_i18n.py 0000664 0001750 0001750 00000043300 12625116214 023476 0 ustar tim tim 0000000 0000000 # coding: utf-8
from __future__ import unicode_literals
from django.test import SimpleTestCase
from django.utils import translation
from django.utils.safestring import mark_safe
from ..utils import setup
class I18nTagTests(SimpleTestCase):
@setup({'i18n01': '{% load i18n %}{% trans \'xxxyyyxxx\' %}'})
def test_i18n01(self):
"""
simple translation of a string delimited by '
"""
output = self.engine.render_to_string('i18n01')
self.assertEqual(output, 'xxxyyyxxx')
@setup({'i18n02': '{% load i18n %}{% trans "xxxyyyxxx" %}'})
def test_i18n02(self):
"""
simple translation of a string delimited by "
"""
output = self.engine.render_to_string('i18n02')
self.assertEqual(output, 'xxxyyyxxx')
@setup({'i18n03': '{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}'})
def test_i18n03(self):
"""
simple translation of a variable
"""
output = self.engine.render_to_string('i18n03', {'anton': b'\xc3\x85'})
self.assertEqual(output, 'Ã…')
@setup({'i18n04': '{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}'})
def test_i18n04(self):
"""
simple translation of a variable and filter
"""
output = self.engine.render_to_string('i18n04', {'anton': b'\xc3\x85'})
self.assertEqual(output, 'Ã¥')
@setup({'legacyi18n04': '{% load i18n %}'
'{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}'})
def test_legacyi18n04(self):
"""
simple translation of a variable and filter
"""
output = self.engine.render_to_string('legacyi18n04', {'anton': b'\xc3\x85'})
self.assertEqual(output, 'Ã¥')
@setup({'i18n05': '{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}'})
def test_i18n05(self):
"""
simple translation of a string with interpolation
"""
output = self.engine.render_to_string('i18n05', {'anton': 'yyy'})
self.assertEqual(output, 'xxxyyyxxx')
@setup({'i18n06': '{% load i18n %}{% trans "Page not found" %}'})
def test_i18n06(self):
"""
simple translation of a string to german
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n06')
self.assertEqual(output, 'Seite nicht gefunden')
@setup({'i18n07': '{% load i18n %}'
'{% blocktrans count counter=number %}singular{% plural %}'
'{{ counter }} plural{% endblocktrans %}'})
def test_i18n07(self):
"""
translation of singular form
"""
output = self.engine.render_to_string('i18n07', {'number': 1})
self.assertEqual(output, 'singular')
@setup({'legacyi18n07': '{% load i18n %}'
'{% blocktrans count number as counter %}singular{% plural %}'
'{{ counter }} plural{% endblocktrans %}'})
def test_legacyi18n07(self):
"""
translation of singular form
"""
output = self.engine.render_to_string('legacyi18n07', {'number': 1})
self.assertEqual(output, 'singular')
@setup({'i18n08': '{% load i18n %}'
'{% blocktrans count number as counter %}singular{% plural %}'
'{{ counter }} plural{% endblocktrans %}'})
def test_i18n08(self):
"""
translation of plural form
"""
output = self.engine.render_to_string('i18n08', {'number': 2})
self.assertEqual(output, '2 plural')
@setup({'legacyi18n08': '{% load i18n %}'
'{% blocktrans count counter=number %}singular{% plural %}'
'{{ counter }} plural{% endblocktrans %}'})
def test_legacyi18n08(self):
"""
translation of plural form
"""
output = self.engine.render_to_string('legacyi18n08', {'number': 2})
self.assertEqual(output, '2 plural')
@setup({'i18n09': '{% load i18n %}{% trans "Page not found" noop %}'})
def test_i18n09(self):
"""
simple non-translation (only marking) of a string to german
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n09')
self.assertEqual(output, 'Page not found')
@setup({'i18n10': '{{ bool|yesno:_("yes,no,maybe") }}'})
def test_i18n10(self):
"""
translation of a variable with a translated filter
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n10', {'bool': True})
self.assertEqual(output, 'Ja')
@setup({'i18n11': '{{ bool|yesno:"ja,nein" }}'})
def test_i18n11(self):
"""
translation of a variable with a non-translated filter
"""
output = self.engine.render_to_string('i18n11', {'bool': True})
self.assertEqual(output, 'ja')
@setup({'i18n12': '{% load i18n %}'
'{% get_available_languages as langs %}{% for lang in langs %}'
'{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}'})
def test_i18n12(self):
"""
usage of the get_available_languages tag
"""
output = self.engine.render_to_string('i18n12')
self.assertEqual(output, 'de')
@setup({'i18n13': '{{ _("Password") }}'})
def test_i18n13(self):
"""
translation of constant strings
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n13')
self.assertEqual(output, 'Passwort')
@setup({'i18n14': '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}'})
def test_i18n14(self):
"""
translation of constant strings
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n14')
self.assertEqual(output, 'foo Passwort Passwort')
@setup({'i18n15': '{{ absent|default:_("Password") }}'})
def test_i18n15(self):
"""
translation of constant strings
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n15', {'absent': ''})
self.assertEqual(output, 'Passwort')
@setup({'i18n16': '{{ _("<") }}'})
def test_i18n16(self):
"""
translation of constant strings
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n16')
self.assertEqual(output, '<')
@setup({'i18n17': '{% load i18n %}'
'{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}'})
def test_i18n17(self):
"""
Escaping inside blocktrans and trans works as if it was directly in the template.
"""
output = self.engine.render_to_string('i18n17', {'anton': 'α & β'})
self.assertEqual(output, 'α & β')
@setup({'i18n18': '{% load i18n %}'
'{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}'})
def test_i18n18(self):
output = self.engine.render_to_string('i18n18', {'anton': 'α & β'})
self.assertEqual(output, 'α & β')
@setup({'i18n19': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'})
def test_i18n19(self):
output = self.engine.render_to_string('i18n19', {'andrew': 'a & b'})
self.assertEqual(output, 'a & b')
@setup({'i18n20': '{% load i18n %}{% trans andrew %}'})
def test_i18n20(self):
output = self.engine.render_to_string('i18n20', {'andrew': 'a & b'})
self.assertEqual(output, 'a & b')
@setup({'i18n21': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'})
def test_i18n21(self):
output = self.engine.render_to_string('i18n21', {'andrew': mark_safe('a & b')})
self.assertEqual(output, 'a & b')
@setup({'i18n22': '{% load i18n %}{% trans andrew %}'})
def test_i18n22(self):
output = self.engine.render_to_string('i18n22', {'andrew': mark_safe('a & b')})
self.assertEqual(output, 'a & b')
@setup({'legacyi18n17': '{% load i18n %}'
'{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}'})
def test_legacyi18n17(self):
output = self.engine.render_to_string('legacyi18n17', {'anton': 'α & β'})
self.assertEqual(output, 'α & β')
@setup({'legacyi18n18': '{% load i18n %}'
'{% blocktrans with anton|force_escape as berta %}'
'{{ berta }}{% endblocktrans %}'})
def test_legacyi18n18(self):
output = self.engine.render_to_string('legacyi18n18', {'anton': 'α & β'})
self.assertEqual(output, 'α & β')
@setup({'i18n23': '{% load i18n %}{% trans "Page not found"|capfirst|slice:"6:" %}'})
def test_i18n23(self):
"""
#5972 - Use filters with the {% trans %} tag
"""
with translation.override('de'):
output = self.engine.render_to_string('i18n23')
self.assertEqual(output, 'nicht gefunden')
@setup({'i18n24': '{% load i18n %}{% trans \'Page not found\'|upper %}'})
def test_i18n24(self):
with translation.override('de'):
output = self.engine.render_to_string('i18n24')
self.assertEqual(output, 'SEITE NICHT GEFUNDEN')
@setup({'i18n25': '{% load i18n %}{% trans somevar|upper %}'})
def test_i18n25(self):
with translation.override('de'):
output = self.engine.render_to_string('i18n25', {'somevar': 'Page not found'})
self.assertEqual(output, 'SEITE NICHT GEFUNDEN')
@setup({'i18n26': '{% load i18n %}'
'{% blocktrans with extra_field=myextra_field count counter=number %}'
'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'})
def test_i18n26(self):
"""
translation of plural form with extra field in singular form (#13568)
"""
output = self.engine.render_to_string('i18n26', {'myextra_field': 'test', 'number': 1})
self.assertEqual(output, 'singular test')
@setup({'legacyi18n26': '{% load i18n %}'
'{% blocktrans with myextra_field as extra_field count number as counter %}'
'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'})
def test_legacyi18n26(self):
output = self.engine.render_to_string('legacyi18n26', {'myextra_field': 'test', 'number': 1})
self.assertEqual(output, 'singular test')
@setup({'i18n27': '{% load i18n %}{% blocktrans count counter=number %}'
'{{ counter }} result{% plural %}{{ counter }} results'
'{% endblocktrans %}'})
def test_i18n27(self):
"""
translation of singular form in russian (#14126)
"""
with translation.override('ru'):
output = self.engine.render_to_string('i18n27', {'number': 1})
self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442')
@setup({'legacyi18n27': '{% load i18n %}'
'{% blocktrans count number as counter %}{{ counter }} result'
'{% plural %}{{ counter }} results{% endblocktrans %}'})
def test_legacyi18n27(self):
with translation.override('ru'):
output = self.engine.render_to_string('legacyi18n27', {'number': 1})
self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442')
@setup({'i18n28': '{% load i18n %}'
'{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}'})
def test_i18n28(self):
"""
simple translation of multiple variables
"""
output = self.engine.render_to_string('i18n28', {'anton': 'α', 'berta': 'β'})
self.assertEqual(output, 'α + β')
@setup({'legacyi18n28': '{% load i18n %}'
'{% blocktrans with anton as a and berta as b %}'
'{{ a }} + {{ b }}{% endblocktrans %}'})
def test_legacyi18n28(self):
output = self.engine.render_to_string('legacyi18n28', {'anton': 'α', 'berta': 'β'})
self.assertEqual(output, 'α + β')
# retrieving language information
@setup({'i18n28_2': '{% load i18n %}'
'{% get_language_info for "de" as l %}'
'{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'})
def test_i18n28_2(self):
output = self.engine.render_to_string('i18n28_2')
self.assertEqual(output, 'de: German/Deutsch bidi=False')
@setup({'i18n29': '{% load i18n %}'
'{% get_language_info for LANGUAGE_CODE as l %}'
'{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'})
def test_i18n29(self):
output = self.engine.render_to_string('i18n29', {'LANGUAGE_CODE': 'fi'})
self.assertEqual(output, 'fi: Finnish/suomi bidi=False')
@setup({'i18n30': '{% load i18n %}'
'{% get_language_info_list for langcodes as langs %}'
'{% for l in langs %}{{ l.code }}: {{ l.name }}/'
'{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'})
def test_i18n30(self):
output = self.engine.render_to_string('i18n30', {'langcodes': ['it', 'no']})
self.assertEqual(output, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; ')
@setup({'i18n31': '{% load i18n %}'
'{% get_language_info_list for langcodes as langs %}'
'{% for l in langs %}{{ l.code }}: {{ l.name }}/'
'{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'})
def test_i18n31(self):
output = self.engine.render_to_string('i18n31', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))})
self.assertEqual(
output,
'sl: Slovenian/Sloven\u0161\u010dina bidi=False; '
'fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; '
)
@setup({'i18n32': '{% load i18n %}{{ "hu"|language_name }} '
'{{ "hu"|language_name_local }} {{ "hu"|language_bidi }}'})
def test_i18n32(self):
output = self.engine.render_to_string('i18n32')
self.assertEqual(output, 'Hungarian Magyar False')
@setup({'i18n33': '{% load i18n %}'
'{{ langcode|language_name }} {{ langcode|language_name_local }} '
'{{ langcode|language_bidi }}'})
def test_i18n33(self):
output = self.engine.render_to_string('i18n33', {'langcode': 'nl'})
self.assertEqual(output, 'Dutch Nederlands False')
# blocktrans handling of variables which are not in the context.
# this should work as if blocktrans was not there (#19915)
@setup({'i18n34': '{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}'})
def test_i18n34(self):
output = self.engine.render_to_string('i18n34')
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'i18n34_2': '{% load i18n %}{% blocktrans with a=\'α\' %}{{ missing }}{% endblocktrans %}'})
def test_i18n34_2(self):
output = self.engine.render_to_string('i18n34_2')
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'i18n34_3': '{% load i18n %}{% blocktrans with a=anton %}{{ missing }}{% endblocktrans %}'})
def test_i18n34_3(self):
output = self.engine.render_to_string('i18n34_3', {'anton': '\xce\xb1'})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
# trans tag with as var
@setup({'i18n35': '{% load i18n %}{% trans "Page not found" as page_not_found %}{{ page_not_found }}'})
def test_i18n35(self):
with translation.override('de'):
output = self.engine.render_to_string('i18n35')
self.assertEqual(output, 'Seite nicht gefunden')
@setup({'i18n36': '{% load i18n %}'
'{% trans "Page not found" noop as page_not_found %}{{ page_not_found }}'})
def test_i18n36(self):
with translation.override('de'):
output = self.engine.render_to_string('i18n36')
self.assertEqual(output, 'Page not found')
@setup({'i18n37': '{% load i18n %}'
'{% trans "Page not found" as page_not_found %}'
'{% blocktrans %}Error: {{ page_not_found }}{% endblocktrans %}'})
def test_i18n37(self):
with translation.override('de'):
output = self.engine.render_to_string('i18n37')
self.assertEqual(output, 'Error: Seite nicht gefunden')
# Test whitespace in filter arguments
@setup({'i18n38': '{% load i18n custom %}'
'{% get_language_info for "de"|noop:"x y" as l %}'
'{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'})
def test_i18n38(self):
output = self.engine.render_to_string('i18n38')
self.assertEqual(output, 'de: German/Deutsch bidi=False')
@setup({'i18n38_2': '{% load i18n custom %}'
'{% get_language_info_list for langcodes|noop:"x y" as langs %}'
'{% for l in langs %}{{ l.code }}: {{ l.name }}/'
'{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'})
def test_i18n38_2(self):
output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'no']})
self.assertEqual(output, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; ')
Django-1.8.7/tests/template_tests/syntax_tests/test_list_index.py 0000664 0001750 0001750 00000005206 12625116214 025064 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class ListIndexTests(SimpleTestCase):
@setup({'list-index01': '{{ var.1 }}'})
def test_list_index01(self):
"""
List-index syntax allows a template to access a certain item of a
subscriptable object.
"""
output = self.engine.render_to_string('list-index01', {'var': ['first item', 'second item']})
self.assertEqual(output, 'second item')
@setup({'list-index02': '{{ var.5 }}'})
def test_list_index02(self):
"""
Fail silently when the list index is out of range.
"""
output = self.engine.render_to_string('list-index02', {'var': ['first item', 'second item']})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'list-index03': '{{ var.1 }}'})
def test_list_index03(self):
"""
Fail silently when the list index is out of range.
"""
output = self.engine.render_to_string('list-index03', {'var': None})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'list-index04': '{{ var.1 }}'})
def test_list_index04(self):
"""
Fail silently when variable is a dict without the specified key.
"""
output = self.engine.render_to_string('list-index04', {'var': {}})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID')
else:
self.assertEqual(output, '')
@setup({'list-index05': '{{ var.1 }}'})
def test_list_index05(self):
"""
Dictionary lookup wins out when dict's key is a string.
"""
output = self.engine.render_to_string('list-index05', {'var': {'1': "hello"}})
self.assertEqual(output, 'hello')
@setup({'list-index06': '{{ var.1 }}'})
def test_list_index06(self):
"""
But list-index lookup wins out when dict's key is an int, which
behind the scenes is really a dictionary lookup (for a dict)
after converting the key to an int.
"""
output = self.engine.render_to_string('list-index06', {"var": {1: "hello"}})
self.assertEqual(output, 'hello')
@setup({'list-index07': '{{ var.1 }}'})
def test_list_index07(self):
"""
Dictionary lookup wins out when there is a string and int version
of the key.
"""
output = self.engine.render_to_string('list-index07', {"var": {'1': "hello", 1: "world"}})
self.assertEqual(output, 'hello')
Django-1.8.7/tests/template_tests/syntax_tests/test_static.py 0000664 0001750 0001750 00000004775 12625116214 024223 0 ustar tim tim 0000000 0000000 from django.conf import settings
from django.test import SimpleTestCase, override_settings
from django.utils.six.moves.urllib.parse import urljoin
from ..utils import setup
@override_settings(MEDIA_URL="/media/", STATIC_URL="/static/")
class StaticTagTests(SimpleTestCase):
@setup({'static-prefixtag01': '{% load static %}{% get_static_prefix %}'})
def test_static_prefixtag01(self):
output = self.engine.render_to_string('static-prefixtag01')
self.assertEqual(output, settings.STATIC_URL)
@setup({'static-prefixtag02': '{% load static %}'
'{% get_static_prefix as static_prefix %}{{ static_prefix }}'})
def test_static_prefixtag02(self):
output = self.engine.render_to_string('static-prefixtag02')
self.assertEqual(output, settings.STATIC_URL)
@setup({'static-prefixtag03': '{% load static %}{% get_media_prefix %}'})
def test_static_prefixtag03(self):
output = self.engine.render_to_string('static-prefixtag03')
self.assertEqual(output, settings.MEDIA_URL)
@setup({'static-prefixtag04': '{% load static %}'
'{% get_media_prefix as media_prefix %}{{ media_prefix }}'})
def test_static_prefixtag04(self):
output = self.engine.render_to_string('static-prefixtag04')
self.assertEqual(output, settings.MEDIA_URL)
@setup({'static-statictag01': '{% load static %}{% static "admin/base.css" %}'})
def test_static_statictag01(self):
output = self.engine.render_to_string('static-statictag01')
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
@setup({'static-statictag02': '{% load static %}{% static base_css %}'})
def test_static_statictag02(self):
output = self.engine.render_to_string('static-statictag02', {'base_css': 'admin/base.css'})
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
@setup({'static-statictag03': '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'})
def test_static_statictag03(self):
output = self.engine.render_to_string('static-statictag03')
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
@setup({'static-statictag04': '{% load static %}{% static base_css as foo %}{{ foo }}'})
def test_static_statictag04(self):
output = self.engine.render_to_string('static-statictag04', {'base_css': 'admin/base.css'})
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
Django-1.8.7/tests/template_tests/syntax_tests/test_named_endblock.py 0000664 0001750 0001750 00000004410 12625116214 025643 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class NamedEndblockTests(SimpleTestCase):
@setup({'namedendblocks01': '1{% block first %}_{% block second %}'
'2{% endblock second %}_{% endblock first %}3'})
def test_namedendblocks01(self):
output = self.engine.render_to_string('namedendblocks01')
self.assertEqual(output, '1_2_3')
# Unbalanced blocks
@setup({'namedendblocks02': '1{% block first %}_{% block second %}'
'2{% endblock first %}_{% endblock second %}3'})
def test_namedendblocks02(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('namedendblocks02')
@setup({'namedendblocks03': '1{% block first %}_{% block second %}'
'2{% endblock %}_{% endblock second %}3'})
def test_namedendblocks03(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('namedendblocks03')
@setup({'namedendblocks04': '1{% block first %}_{% block second %}'
'2{% endblock second %}_{% endblock third %}3'})
def test_namedendblocks04(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('namedendblocks04')
@setup({'namedendblocks05': '1{% block first %}_{% block second %}2{% endblock first %}'})
def test_namedendblocks05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('namedendblocks05')
# Mixed named and unnamed endblocks
@setup({'namedendblocks06': '1{% block first %}_{% block second %}'
'2{% endblock %}_{% endblock first %}3'})
def test_namedendblocks06(self):
"""
Mixed named and unnamed endblocks
"""
output = self.engine.render_to_string('namedendblocks06')
self.assertEqual(output, '1_2_3')
@setup({'namedendblocks07': '1{% block first %}_{% block second %}'
'2{% endblock second %}_{% endblock %}3'})
def test_namedendblocks07(self):
output = self.engine.render_to_string('namedendblocks07')
self.assertEqual(output, '1_2_3')
Django-1.8.7/tests/template_tests/syntax_tests/test_multiline.py 0000664 0001750 0001750 00000000552 12625116214 024723 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
multiline_string = """
Hello,
boys.
How
are
you
gentlemen.
"""
class MultilineTests(SimpleTestCase):
@setup({'multiline01': multiline_string})
def test_multiline01(self):
output = self.engine.render_to_string('multiline01')
self.assertEqual(output, multiline_string)
Django-1.8.7/tests/template_tests/syntax_tests/test_comment.py 0000664 0001750 0001750 00000007123 12625116214 024364 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class CommentSyntaxTests(SimpleTestCase):
@setup({'comment-syntax01': '{# this is hidden #}hello'})
def test_comment_syntax01(self):
output = self.engine.render_to_string('comment-syntax01')
self.assertEqual(output, 'hello')
@setup({'comment-syntax02': '{# this is hidden #}hello{# foo #}'})
def test_comment_syntax02(self):
output = self.engine.render_to_string('comment-syntax02')
self.assertEqual(output, 'hello')
@setup({'comment-syntax03': 'foo{# {% if %} #}'})
def test_comment_syntax03(self):
output = self.engine.render_to_string('comment-syntax03')
self.assertEqual(output, 'foo')
@setup({'comment-syntax04': 'foo{# {% endblock %} #}'})
def test_comment_syntax04(self):
output = self.engine.render_to_string('comment-syntax04')
self.assertEqual(output, 'foo')
@setup({'comment-syntax05': 'foo{# {% somerandomtag %} #}'})
def test_comment_syntax05(self):
output = self.engine.render_to_string('comment-syntax05')
self.assertEqual(output, 'foo')
@setup({'comment-syntax06': 'foo{# {% #}'})
def test_comment_syntax06(self):
output = self.engine.render_to_string('comment-syntax06')
self.assertEqual(output, 'foo')
@setup({'comment-syntax07': 'foo{# %} #}'})
def test_comment_syntax07(self):
output = self.engine.render_to_string('comment-syntax07')
self.assertEqual(output, 'foo')
@setup({'comment-syntax08': 'foo{# %} #}bar'})
def test_comment_syntax08(self):
output = self.engine.render_to_string('comment-syntax08')
self.assertEqual(output, 'foobar')
@setup({'comment-syntax09': 'foo{# {{ #}'})
def test_comment_syntax09(self):
output = self.engine.render_to_string('comment-syntax09')
self.assertEqual(output, 'foo')
@setup({'comment-syntax10': 'foo{# }} #}'})
def test_comment_syntax10(self):
output = self.engine.render_to_string('comment-syntax10')
self.assertEqual(output, 'foo')
@setup({'comment-syntax11': 'foo{# { #}'})
def test_comment_syntax11(self):
output = self.engine.render_to_string('comment-syntax11')
self.assertEqual(output, 'foo')
@setup({'comment-syntax12': 'foo{# } #}'})
def test_comment_syntax12(self):
output = self.engine.render_to_string('comment-syntax12')
self.assertEqual(output, 'foo')
@setup({'comment-tag01': '{% comment %}this is hidden{% endcomment %}hello'})
def test_comment_tag01(self):
output = self.engine.render_to_string('comment-tag01')
self.assertEqual(output, 'hello')
@setup({'comment-tag02': '{% comment %}this is hidden{% endcomment %}'
'hello{% comment %}foo{% endcomment %}'})
def test_comment_tag02(self):
output = self.engine.render_to_string('comment-tag02')
self.assertEqual(output, 'hello')
@setup({'comment-tag03': 'foo{% comment %} {% if %} {% endcomment %}'})
def test_comment_tag03(self):
output = self.engine.render_to_string('comment-tag03')
self.assertEqual(output, 'foo')
@setup({'comment-tag04': 'foo{% comment %} {% endblock %} {% endcomment %}'})
def test_comment_tag04(self):
output = self.engine.render_to_string('comment-tag04')
self.assertEqual(output, 'foo')
@setup({'comment-tag05': 'foo{% comment %} {% somerandomtag %} {% endcomment %}'})
def test_comment_tag05(self):
output = self.engine.render_to_string('comment-tag05')
self.assertEqual(output, 'foo')
Django-1.8.7/tests/template_tests/syntax_tests/test_lorem.py 0000664 0001750 0001750 00000000435 12625116214 024037 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class LoremTagTests(SimpleTestCase):
@setup({'lorem1': '{% lorem 3 w %}'})
def test_lorem1(self):
output = self.engine.render_to_string('lorem1')
self.assertEqual(output, 'lorem ipsum dolor')
Django-1.8.7/tests/template_tests/syntax_tests/test_regroup.py 0000664 0001750 0001750 00000007620 12625116214 024407 0 ustar tim tim 0000000 0000000 from datetime import date
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class RegroupTagTests(SimpleTestCase):
@setup({'regroup01': ''
'{% regroup data by bar as grouped %}'
'{% for group in grouped %}'
'{{ group.grouper }}:'
'{% for item in group.list %}'
'{{ item.foo }}'
'{% endfor %},'
'{% endfor %}'})
def test_regroup01(self):
output = self.engine.render_to_string('regroup01', {
'data': [{'foo': 'c', 'bar': 1},
{'foo': 'd', 'bar': 1},
{'foo': 'a', 'bar': 2},
{'foo': 'b', 'bar': 2},
{'foo': 'x', 'bar': 3}],
})
self.assertEqual(output, '1:cd,2:ab,3:x,')
@setup({'regroup02': ''
'{% regroup data by bar as grouped %}'
'{% for group in grouped %}'
'{{ group.grouper }}:'
'{% for item in group.list %}'
'{{ item.foo }}'
'{% endfor %}'
'{% endfor %}'})
def test_regroup02(self):
"""
Test for silent failure when target variable isn't found
"""
output = self.engine.render_to_string('regroup02', {})
self.assertEqual(output, '')
@setup({'regroup03': ''
'{% regroup data by at|date:"m" as grouped %}'
'{% for group in grouped %}'
'{{ group.grouper }}:'
'{% for item in group.list %}'
'{{ item.at|date:"d" }}'
'{% endfor %},'
'{% endfor %}'})
def test_regroup03(self):
"""
Regression tests for #17675
The date template filter has expects_localtime = True
"""
output = self.engine.render_to_string('regroup03', {
'data': [{'at': date(2012, 2, 14)},
{'at': date(2012, 2, 28)},
{'at': date(2012, 7, 4)}],
})
self.assertEqual(output, '02:1428,07:04,')
@setup({'regroup04': ''
'{% regroup data by bar|join:"" as grouped %}'
'{% for group in grouped %}'
'{{ group.grouper }}:'
'{% for item in group.list %}'
'{{ item.foo|first }}'
'{% endfor %},'
'{% endfor %}'})
def test_regroup04(self):
"""
The join template filter has needs_autoescape = True
"""
output = self.engine.render_to_string('regroup04', {
'data': [{'foo': 'x', 'bar': ['ab', 'c']},
{'foo': 'y', 'bar': ['a', 'bc']},
{'foo': 'z', 'bar': ['a', 'd']}],
})
self.assertEqual(output, 'abc:xy,ad:z,')
# Test syntax errors
@setup({'regroup05': '{% regroup data by bar as %}'})
def test_regroup05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('regroup05')
@setup({'regroup06': '{% regroup data by bar thisaintright grouped %}'})
def test_regroup06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('regroup06')
@setup({'regroup07': '{% regroup data thisaintright bar as grouped %}'})
def test_regroup07(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('regroup07')
@setup({'regroup08': '{% regroup data by bar as grouped toomanyargs %}'})
def test_regroup08(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('regroup08')
Django-1.8.7/tests/template_tests/syntax_tests/test_filter_syntax.py 0000664 0001750 0001750 00000021214 12625116214 025612 0 ustar tim tim 0000000 0000000 # coding: utf-8
from __future__ import unicode_literals
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import SomeClass, SomeOtherException, UTF8Class, setup
class FilterSyntaxTests(SimpleTestCase):
@setup({'filter-syntax01': '{{ var|upper }}'})
def test_filter_syntax01(self):
"""
Basic filter usage
"""
output = self.engine.render_to_string('filter-syntax01', {"var": "Django is the greatest!"})
self.assertEqual(output, "DJANGO IS THE GREATEST!")
@setup({'filter-syntax02': '{{ var|upper|lower }}'})
def test_filter_syntax02(self):
"""
Chained filters
"""
output = self.engine.render_to_string('filter-syntax02', {"var": "Django is the greatest!"})
self.assertEqual(output, "django is the greatest!")
@setup({'filter-syntax03': '{{ var |upper }}'})
def test_filter_syntax03(self):
"""
Allow spaces before the filter pipe
"""
output = self.engine.render_to_string('filter-syntax03', {'var': 'Django is the greatest!'})
self.assertEqual(output, 'DJANGO IS THE GREATEST!')
@setup({'filter-syntax04': '{{ var| upper }}'})
def test_filter_syntax04(self):
"""
Allow spaces after the filter pipe
"""
output = self.engine.render_to_string('filter-syntax04', {'var': 'Django is the greatest!'})
self.assertEqual(output, 'DJANGO IS THE GREATEST!')
@setup({'filter-syntax05': '{{ var|does_not_exist }}'})
def test_filter_syntax05(self):
"""
Raise TemplateSyntaxError for a nonexistent filter
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter-syntax05')
@setup({'filter-syntax06': '{{ var|fil(ter) }}'})
def test_filter_syntax06(self):
"""
Raise TemplateSyntaxError when trying to access a filter containing
an illegal character
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter-syntax06')
@setup({'filter-syntax07': "{% nothing_to_see_here %}"})
def test_filter_syntax07(self):
"""
Raise TemplateSyntaxError for invalid block tags
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter-syntax07')
@setup({'filter-syntax08': "{% %}"})
def test_filter_syntax08(self):
"""
Raise TemplateSyntaxError for empty block tags
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter-syntax08')
@setup({'filter-syntax09': '{{ var|cut:"o"|upper|lower }}'})
def test_filter_syntax09(self):
"""
Chained filters, with an argument to the first one
"""
output = self.engine.render_to_string('filter-syntax09', {'var': 'Foo'})
self.assertEqual(output, 'f')
@setup({'filter-syntax10': r'{{ var|default_if_none:" endquote\" hah" }}'})
def test_filter_syntax10(self):
"""
Literal string as argument is always "safe" from auto-escaping.
"""
output = self.engine.render_to_string('filter-syntax10', {"var": None})
self.assertEqual(output, ' endquote" hah')
@setup({'filter-syntax11': r'{{ var|default_if_none:var2 }}'})
def test_filter_syntax11(self):
"""
Variable as argument
"""
output = self.engine.render_to_string('filter-syntax11', {"var": None, "var2": "happy"})
self.assertEqual(output, 'happy')
@setup({'filter-syntax12': r'{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}'})
def test_filter_syntax12(self):
"""
Default argument testing
"""
output = self.engine.render_to_string('filter-syntax12', {"var": True})
self.assertEqual(output, 'yup yes')
@setup({'filter-syntax13': r'1{{ var.method3 }}2'})
def test_filter_syntax13(self):
"""
Fail silently for methods that raise an exception with a
`silent_variable_failure` attribute
"""
output = self.engine.render_to_string('filter-syntax13', {"var": SomeClass()})
if self.engine.string_if_invalid:
self.assertEqual(output, "1INVALID2")
else:
self.assertEqual(output, "12")
@setup({'filter-syntax14': r'1{{ var.method4 }}2'})
def test_filter_syntax14(self):
"""
In methods that raise an exception without a
`silent_variable_attribute` set to True, the exception propagates
"""
with self.assertRaises(SomeOtherException):
self.engine.render_to_string('filter-syntax14', {"var": SomeClass()})
@setup({'filter-syntax15': r'{{ var|default_if_none:"foo\bar" }}'})
def test_filter_syntax15(self):
"""
Escaped backslash in argument
"""
output = self.engine.render_to_string('filter-syntax15', {"var": None})
self.assertEqual(output, r'foo\bar')
@setup({'filter-syntax16': r'{{ var|default_if_none:"foo\now" }}'})
def test_filter_syntax16(self):
"""
Escaped backslash using known escape char
"""
output = self.engine.render_to_string('filter-syntax16', {"var": None})
self.assertEqual(output, r'foo\now')
@setup({'filter-syntax17': r'{{ var|join:"" }}'})
def test_filter_syntax17(self):
"""
Empty strings can be passed as arguments to filters
"""
output = self.engine.render_to_string('filter-syntax17', {'var': ['a', 'b', 'c']})
self.assertEqual(output, 'abc')
@setup({'filter-syntax18': r'{{ var }}'})
def test_filter_syntax18(self):
"""
Make sure that any unicode strings are converted to bytestrings
in the final output.
"""
output = self.engine.render_to_string('filter-syntax18', {'var': UTF8Class()})
self.assertEqual(output, '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
@setup({'filter-syntax19': '{{ var|truncatewords:1 }}'})
def test_filter_syntax19(self):
"""
Numbers as filter arguments should work
"""
output = self.engine.render_to_string('filter-syntax19', {"var": "hello world"})
self.assertEqual(output, "hello ...")
@setup({'filter-syntax20': '{{ ""|default_if_none:"was none" }}'})
def test_filter_syntax20(self):
"""
Filters should accept empty string constants
"""
output = self.engine.render_to_string('filter-syntax20')
self.assertEqual(output, "")
@setup({'filter-syntax21': r'1{{ var.silent_fail_key }}2'})
def test_filter_syntax21(self):
"""
Fail silently for non-callable attribute and dict lookups which
raise an exception with a "silent_variable_failure" attribute
"""
output = self.engine.render_to_string('filter-syntax21', {"var": SomeClass()})
if self.engine.string_if_invalid:
self.assertEqual(output, "1INVALID2")
else:
self.assertEqual(output, "12")
@setup({'filter-syntax22': r'1{{ var.silent_fail_attribute }}2'})
def test_filter_syntax22(self):
"""
Fail silently for non-callable attribute and dict lookups which
raise an exception with a `silent_variable_failure` attribute
"""
output = self.engine.render_to_string('filter-syntax22', {"var": SomeClass()})
if self.engine.string_if_invalid:
self.assertEqual(output, "1INVALID2")
else:
self.assertEqual(output, "12")
@setup({'filter-syntax23': r'1{{ var.noisy_fail_key }}2'})
def test_filter_syntax23(self):
"""
In attribute and dict lookups that raise an unexpected exception
without a `silent_variable_attribute` set to True, the exception
propagates
"""
with self.assertRaises(SomeOtherException):
self.engine.render_to_string('filter-syntax23', {"var": SomeClass()})
@setup({'filter-syntax24': r'1{{ var.noisy_fail_attribute }}2'})
def test_filter_syntax24(self):
"""
In attribute and dict lookups that raise an unexpected exception
without a `silent_variable_attribute` set to True, the exception
propagates
"""
with self.assertRaises(SomeOtherException):
self.engine.render_to_string('filter-syntax24', {"var": SomeClass()})
@setup({'filter-syntax25': '{{ var.attribute_error_attribute }}'})
def test_filter_syntax25(self):
"""
#16383 - Attribute errors from an @property value should be
reraised.
"""
with self.assertRaises(AttributeError):
self.engine.render_to_string('filter-syntax25', {'var': SomeClass()})
Django-1.8.7/tests/template_tests/syntax_tests/__init__.py 0000664 0001750 0001750 00000000000 12625116214 023405 0 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/syntax_tests/test_verbatim.py 0000664 0001750 0001750 00000003172 12625116214 024533 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class VerbatimTagTests(SimpleTestCase):
@setup({'verbatim-tag01': '{% verbatim %}{{bare }}{% endverbatim %}'})
def test_verbatim_tag01(self):
output = self.engine.render_to_string('verbatim-tag01')
self.assertEqual(output, '{{bare }}')
@setup({'verbatim-tag02': '{% verbatim %}{% endif %}{% endverbatim %}'})
def test_verbatim_tag02(self):
output = self.engine.render_to_string('verbatim-tag02')
self.assertEqual(output, '{% endif %}')
@setup({'verbatim-tag03': '{% verbatim %}It\'s the {% verbatim %} tag{% endverbatim %}'})
def test_verbatim_tag03(self):
output = self.engine.render_to_string('verbatim-tag03')
self.assertEqual(output, 'It\'s the {% verbatim %} tag')
@setup({'verbatim-tag04': '{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}'})
def test_verbatim_tag04(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('verbatim-tag04')
@setup({'verbatim-tag05': '{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}'})
def test_verbatim_tag05(self):
output = self.engine.render_to_string('verbatim-tag05')
self.assertEqual(output, '')
@setup({'verbatim-tag06': '{% verbatim special %}'
'Don\'t {% endverbatim %} just yet{% endverbatim special %}'})
def test_verbatim_tag06(self):
output = self.engine.render_to_string('verbatim-tag06')
self.assertEqual(output, 'Don\'t {% endverbatim %} just yet')
Django-1.8.7/tests/template_tests/syntax_tests/test_setup.py 0000664 0001750 0001750 00000001333 12625116214 024057 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class SetupTests(SimpleTestCase):
def test_setup(self):
"""
Let's just make sure setup runs cases in the right order.
"""
cases = []
@setup({})
def method(self):
cases.append([
self.engine.string_if_invalid,
self.engine.debug,
])
method(self)
self.assertEqual(cases[0], ['', False])
self.assertEqual(cases[1], ['', False])
self.assertEqual(cases[2], ['INVALID', False])
self.assertEqual(cases[3], ['INVALID', False])
self.assertEqual(cases[4], ['', True])
self.assertEqual(cases[5], ['', True])
Django-1.8.7/tests/template_tests/syntax_tests/test_spaceless.py 0000664 0001750 0001750 00000003346 12625116214 024707 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class SpacelessTagTests(SimpleTestCase):
@setup({'spaceless01': "{% spaceless %} text {% endspaceless %}"})
def test_spaceless01(self):
output = self.engine.render_to_string('spaceless01')
self.assertEqual(output, " text ")
@setup({'spaceless02': "{% spaceless %} \n text \n {% endspaceless %}"})
def test_spaceless02(self):
output = self.engine.render_to_string('spaceless02')
self.assertEqual(output, " text ")
@setup({'spaceless03': "{% spaceless %}text{% endspaceless %}"})
def test_spaceless03(self):
output = self.engine.render_to_string('spaceless03')
self.assertEqual(output, "text")
@setup({'spaceless04': "{% spaceless %} {{ text }} {% endspaceless %}"})
def test_spaceless04(self):
output = self.engine.render_to_string('spaceless04', {'text': 'This & that'})
self.assertEqual(output, "This & that")
@setup({'spaceless05': "{% autoescape off %}{% spaceless %}"
" {{ text }} {% endspaceless %}"
"{% endautoescape %}"})
def test_spaceless05(self):
output = self.engine.render_to_string('spaceless05', {'text': 'This & that'})
self.assertEqual(output, "This & that")
@setup({'spaceless06': "{% spaceless %} {{ text|safe }} {% endspaceless %}"})
def test_spaceless06(self):
output = self.engine.render_to_string('spaceless06', {'text': 'This & that'})
self.assertEqual(output, "This & that")
Django-1.8.7/tests/template_tests/syntax_tests/test_extends.py 0000664 0001750 0001750 00000036112 12625116214 024374 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
inheritance_templates = {
'inheritance01': "1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}",
'inheritance02': "{% extends 'inheritance01' %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
'inheritance03': "{% extends 'inheritance02' %}",
'inheritance04': "{% extends 'inheritance01' %}",
'inheritance05': "{% extends 'inheritance02' %}",
'inheritance06': "{% extends foo %}",
'inheritance07': "{% extends 'inheritance01' %}{% block second %}5{% endblock %}",
'inheritance08': "{% extends 'inheritance02' %}{% block second %}5{% endblock %}",
'inheritance09': "{% extends 'inheritance04' %}",
'inheritance10': "{% extends 'inheritance04' %} ",
'inheritance11': "{% extends 'inheritance04' %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
'inheritance12': "{% extends 'inheritance07' %}{% block first %}2{% endblock %}",
'inheritance13': "{% extends 'inheritance02' %}"
"{% block first %}a{% endblock %}{% block second %}b{% endblock %}",
'inheritance14': "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}",
'inheritance15': "{% extends 'inheritance01' %}"
"{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}",
'inheritance16': "{% extends 'inheritance15' %}{% block inner %}out{% endblock %}",
'inheritance17': "{% load testtags %}{% block first %}1234{% endblock %}",
'inheritance18': "{% load testtags %}{% echo this that theother %}5678",
'inheritance19': "{% extends 'inheritance01' %}"
"{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}",
'inheritance20': "{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}",
'inheritance21': "{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}",
'inheritance22': "{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}",
'inheritance23': "{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}",
'inheritance24': "{% extends context_template %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
'inheritance25': "{% extends context_template.1 %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
'inheritance26': "no tags",
'inheritance27': "{% extends 'inheritance26' %}",
'inheritance 28': "{% block first %}!{% endblock %}",
'inheritance29': "{% extends 'inheritance 28' %}",
'inheritance30': "1{% if optional %}{% block opt %}2{% endblock %}{% endif %}3",
'inheritance31': "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}",
'inheritance32': "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}",
'inheritance33': "1{% ifequal optional 1 %}{% block opt %}2{% endblock %}{% endifequal %}3",
'inheritance34': "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}",
'inheritance35': "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}",
'inheritance36': "{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_",
'inheritance37': "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}",
'inheritance38': "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}",
'inheritance39': "{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}",
'inheritance40': "{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}",
'inheritance41': "{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}",
'inheritance42': "{% extends 'inheritance02'|cut:' ' %}",
}
class InheritanceTests(SimpleTestCase):
@setup(inheritance_templates)
def test_inheritance01(self):
"""
Standard template with no inheritance
"""
output = self.engine.render_to_string('inheritance01')
self.assertEqual(output, '1&3_')
@setup(inheritance_templates)
def test_inheritance02(self):
"""
Standard two-level inheritance
"""
output = self.engine.render_to_string('inheritance02')
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance03(self):
"""
Three-level with no redefinitions on third level
"""
output = self.engine.render_to_string('inheritance03')
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance04(self):
"""
Two-level with no redefinitions on second level
"""
output = self.engine.render_to_string('inheritance04')
self.assertEqual(output, '1&3_')
@setup(inheritance_templates)
def test_inheritance05(self):
"""
Two-level with double quotes instead of single quotes
"""
output = self.engine.render_to_string('inheritance05')
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance06(self):
"""
Three-level with variable parent-template name
"""
output = self.engine.render_to_string('inheritance06', {'foo': 'inheritance02'})
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance07(self):
"""
Two-level with one block defined, one block not defined
"""
output = self.engine.render_to_string('inheritance07')
self.assertEqual(output, '1&35')
@setup(inheritance_templates)
def test_inheritance08(self):
"""
Three-level with one block defined on this level, two blocks
defined next level
"""
output = self.engine.render_to_string('inheritance08')
self.assertEqual(output, '1235')
@setup(inheritance_templates)
def test_inheritance09(self):
"""
Three-level with second and third levels blank
"""
output = self.engine.render_to_string('inheritance09')
self.assertEqual(output, '1&3_')
@setup(inheritance_templates)
def test_inheritance10(self):
"""
Three-level with space NOT in a block -- should be ignored
"""
output = self.engine.render_to_string('inheritance10')
self.assertEqual(output, '1&3_')
@setup(inheritance_templates)
def test_inheritance11(self):
"""
Three-level with both blocks defined on this level, but none on
second level
"""
output = self.engine.render_to_string('inheritance11')
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance12(self):
"""
Three-level with this level providing one and second level
providing the other
"""
output = self.engine.render_to_string('inheritance12')
self.assertEqual(output, '1235')
@setup(inheritance_templates)
def test_inheritance13(self):
"""
Three-level with this level overriding second level
"""
output = self.engine.render_to_string('inheritance13')
self.assertEqual(output, '1a3b')
@setup(inheritance_templates)
def test_inheritance14(self):
"""
A block defined only in a child template shouldn't be displayed
"""
output = self.engine.render_to_string('inheritance14')
self.assertEqual(output, '1&3_')
@setup(inheritance_templates)
def test_inheritance15(self):
"""
A block within another block
"""
output = self.engine.render_to_string('inheritance15')
self.assertEqual(output, '12inner3_')
@setup(inheritance_templates)
def test_inheritance16(self):
"""
A block within another block (level 2)
"""
output = self.engine.render_to_string('inheritance16')
self.assertEqual(output, '12out3_')
@setup(inheritance_templates)
def test_inheritance17(self):
"""
{% load %} tag (parent -- setup for exception04)
"""
output = self.engine.render_to_string('inheritance17')
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance18(self):
"""
{% load %} tag (standard usage, without inheritance)
"""
output = self.engine.render_to_string('inheritance18')
self.assertEqual(output, 'this that theother5678')
@setup(inheritance_templates)
def test_inheritance19(self):
"""
{% load %} tag (within a child template)
"""
output = self.engine.render_to_string('inheritance19')
self.assertEqual(output, '140056783_')
@setup(inheritance_templates)
def test_inheritance20(self):
"""
Two-level inheritance with {{ block.super }}
"""
output = self.engine.render_to_string('inheritance20')
self.assertEqual(output, '1&a3_')
@setup(inheritance_templates)
def test_inheritance21(self):
"""
Three-level inheritance with {{ block.super }} from parent
"""
output = self.engine.render_to_string('inheritance21')
self.assertEqual(output, '12a34')
@setup(inheritance_templates)
def test_inheritance22(self):
"""
Three-level inheritance with {{ block.super }} from grandparent
"""
output = self.engine.render_to_string('inheritance22')
self.assertEqual(output, '1&a3_')
@setup(inheritance_templates)
def test_inheritance23(self):
"""
Three-level inheritance with {{ block.super }} from parent and
grandparent
"""
output = self.engine.render_to_string('inheritance23')
self.assertEqual(output, '1&ab3_')
@setup(inheritance_templates)
def test_inheritance24(self):
"""
Inheritance from local context without use of template loader
"""
context_template = self.engine.from_string("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}")
output = self.engine.render_to_string('inheritance24', {'context_template': context_template})
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance25(self):
"""
Inheritance from local context with variable parent template
"""
context_template = [
self.engine.from_string("Wrong"),
self.engine.from_string("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}"),
]
output = self.engine.render_to_string('inheritance25', {'context_template': context_template})
self.assertEqual(output, '1234')
@setup(inheritance_templates)
def test_inheritance26(self):
"""
Set up a base template to extend
"""
output = self.engine.render_to_string('inheritance26')
self.assertEqual(output, 'no tags')
@setup(inheritance_templates)
def test_inheritance27(self):
"""
Inheritance from a template that doesn't have any blocks
"""
output = self.engine.render_to_string('inheritance27')
self.assertEqual(output, 'no tags')
@setup(inheritance_templates)
def test_inheritance_28(self):
"""
Set up a base template with a space in it.
"""
output = self.engine.render_to_string('inheritance 28')
self.assertEqual(output, '!')
@setup(inheritance_templates)
def test_inheritance29(self):
"""
Inheritance from a template with a space in its name should work.
"""
output = self.engine.render_to_string('inheritance29')
self.assertEqual(output, '!')
@setup(inheritance_templates)
def test_inheritance30(self):
"""
Base template, putting block in a conditional {% if %} tag
"""
output = self.engine.render_to_string('inheritance30', {'optional': True})
self.assertEqual(output, '123')
# Inherit from a template with block wrapped in an {% if %} tag
# (in parent), still gets overridden
@setup(inheritance_templates)
def test_inheritance31(self):
output = self.engine.render_to_string('inheritance31', {'optional': True})
self.assertEqual(output, '1two3')
@setup(inheritance_templates)
def test_inheritance32(self):
output = self.engine.render_to_string('inheritance32')
self.assertEqual(output, '13')
@setup(inheritance_templates)
def test_inheritance33(self):
"""
Base template, putting block in a conditional {% ifequal %} tag
"""
output = self.engine.render_to_string('inheritance33', {'optional': 1})
self.assertEqual(output, '123')
@setup(inheritance_templates)
def test_inheritance34(self):
"""
Inherit from a template with block wrapped in an {% ifequal %} tag
(in parent), still gets overridden
"""
output = self.engine.render_to_string('inheritance34', {'optional': 1})
self.assertEqual(output, '1two3')
@setup(inheritance_templates)
def test_inheritance35(self):
"""
Inherit from a template with block wrapped in an {% ifequal %} tag
(in parent), still gets overridden
"""
output = self.engine.render_to_string('inheritance35', {'optional': 2})
self.assertEqual(output, '13')
@setup(inheritance_templates)
def test_inheritance36(self):
"""
Base template, putting block in a {% for %} tag
"""
output = self.engine.render_to_string('inheritance36', {'numbers': '123'})
self.assertEqual(output, '_1_2_3_')
@setup(inheritance_templates)
def test_inheritance37(self):
"""
Inherit from a template with block wrapped in an {% for %} tag
(in parent), still gets overridden
"""
output = self.engine.render_to_string('inheritance37', {'numbers': '123'})
self.assertEqual(output, '_X_X_X_')
@setup(inheritance_templates)
def test_inheritance38(self):
"""
Inherit from a template with block wrapped in an {% for %} tag
(in parent), still gets overridden
"""
output = self.engine.render_to_string('inheritance38')
self.assertEqual(output, '_')
# The super block will still be found.
@setup(inheritance_templates)
def test_inheritance39(self):
output = self.engine.render_to_string('inheritance39', {'optional': True})
self.assertEqual(output, '1new23')
@setup(inheritance_templates)
def test_inheritance40(self):
output = self.engine.render_to_string('inheritance40', {'optional': 1})
self.assertEqual(output, '1new23')
@setup(inheritance_templates)
def test_inheritance41(self):
output = self.engine.render_to_string('inheritance41', {'numbers': '123'})
self.assertEqual(output, '_new1_new2_new3_')
@setup(inheritance_templates)
def test_inheritance42(self):
"""
Expression starting and ending with a quote
"""
output = self.engine.render_to_string('inheritance42')
self.assertEqual(output, '1234')
Django-1.8.7/tests/template_tests/syntax_tests/test_firstof.py 0000664 0001750 0001750 00000006506 12625116214 024402 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango110Warning
from ..utils import setup
class FirstOfTagTests(SimpleTestCase):
@setup({'firstof01': '{% firstof a b c %}'})
def test_firstof01(self):
output = self.engine.render_to_string('firstof01', {'a': 0, 'c': 0, 'b': 0})
self.assertEqual(output, '')
@setup({'firstof02': '{% firstof a b c %}'})
def test_firstof02(self):
output = self.engine.render_to_string('firstof02', {'a': 1, 'c': 0, 'b': 0})
self.assertEqual(output, '1')
@setup({'firstof03': '{% firstof a b c %}'})
def test_firstof03(self):
output = self.engine.render_to_string('firstof03', {'a': 0, 'c': 0, 'b': 2})
self.assertEqual(output, '2')
@setup({'firstof04': '{% firstof a b c %}'})
def test_firstof04(self):
output = self.engine.render_to_string('firstof04', {'a': 0, 'c': 3, 'b': 0})
self.assertEqual(output, '3')
@setup({'firstof05': '{% firstof a b c %}'})
def test_firstof05(self):
output = self.engine.render_to_string('firstof05', {'a': 1, 'c': 3, 'b': 2})
self.assertEqual(output, '1')
@setup({'firstof06': '{% firstof a b c %}'})
def test_firstof06(self):
output = self.engine.render_to_string('firstof06', {'c': 3, 'b': 0})
self.assertEqual(output, '3')
@setup({'firstof07': '{% firstof a b "c" %}'})
def test_firstof07(self):
output = self.engine.render_to_string('firstof07', {'a': 0})
self.assertEqual(output, 'c')
@setup({'firstof08': '{% firstof a b "c and d" %}'})
def test_firstof08(self):
output = self.engine.render_to_string('firstof08', {'a': 0, 'b': 0})
self.assertEqual(output, 'c and d')
@setup({'firstof09': '{% firstof %}'})
def test_firstof09(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('firstof09')
@setup({'firstof10': '{% firstof a %}'})
def test_firstof10(self):
output = self.engine.render_to_string('firstof10', {'a': '<'})
self.assertEqual(output, '<')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'firstof11': '{% load firstof from future %}{% firstof a b %}'})
def test_firstof11(self):
output = self.engine.render_to_string('firstof11', {'a': '<', 'b': '>'})
self.assertEqual(output, '<')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'firstof12': '{% load firstof from future %}{% firstof a b %}'})
def test_firstof12(self):
output = self.engine.render_to_string('firstof12', {'a': '', 'b': '>'})
self.assertEqual(output, '>')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'firstof13': '{% load firstof from future %}'
'{% autoescape off %}{% firstof a %}{% endautoescape %}'})
def test_firstof13(self):
output = self.engine.render_to_string('firstof13', {'a': '<'})
self.assertEqual(output, '<')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'firstof14': '{% load firstof from future %}{% firstof a|safe b %}'})
def test_firstof14(self):
output = self.engine.render_to_string('firstof14', {'a': '<'})
self.assertEqual(output, '<')
Django-1.8.7/tests/template_tests/syntax_tests/test_cache.py 0000664 0001750 0001750 00000014434 12625116214 023770 0 ustar tim tim 0000000 0000000 from django.core.cache import cache
from django.template import Context, Template, TemplateSyntaxError
from django.test import SimpleTestCase, override_settings
from ..utils import setup
class CacheTagTests(SimpleTestCase):
def tearDown(self):
cache.clear()
@setup({'cache03': '{% load cache %}{% cache 2 test %}cache03{% endcache %}'})
def test_cache03(self):
output = self.engine.render_to_string('cache03')
self.assertEqual(output, 'cache03')
@setup({
'cache03': '{% load cache %}{% cache 2 test %}cache03{% endcache %}',
'cache04': '{% load cache %}{% cache 2 test %}cache04{% endcache %}',
})
def test_cache04(self):
self.engine.render_to_string('cache03')
output = self.engine.render_to_string('cache04')
self.assertEqual(output, 'cache03')
@setup({'cache05': '{% load cache %}{% cache 2 test foo %}cache05{% endcache %}'})
def test_cache05(self):
output = self.engine.render_to_string('cache05', {'foo': 1})
self.assertEqual(output, 'cache05')
@setup({'cache06': '{% load cache %}{% cache 2 test foo %}cache06{% endcache %}'})
def test_cache06(self):
output = self.engine.render_to_string('cache06', {'foo': 2})
self.assertEqual(output, 'cache06')
@setup({
'cache05': '{% load cache %}{% cache 2 test foo %}cache05{% endcache %}',
'cache07': '{% load cache %}{% cache 2 test foo %}cache07{% endcache %}',
})
def test_cache07(self):
context = {'foo': 1}
self.engine.render_to_string('cache05', context)
output = self.engine.render_to_string('cache07', context)
self.assertEqual(output, 'cache05')
@setup({
'cache06': '{% load cache %}{% cache 2 test foo %}cache06{% endcache %}',
'cache08': '{% load cache %}{% cache time test foo %}cache08{% endcache %}',
})
def test_cache08(self):
"""
Allow first argument to be a variable.
"""
context = {'foo': 2, 'time': 2}
self.engine.render_to_string('cache06', context)
output = self.engine.render_to_string('cache08', context)
self.assertEqual(output, 'cache06')
# Raise exception if we don't have at least 2 args, first one integer.
@setup({'cache11': '{% load cache %}{% cache %}{% endcache %}'})
def test_cache11(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('cache11')
@setup({'cache12': '{% load cache %}{% cache 1 %}{% endcache %}'})
def test_cache12(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('cache12')
@setup({'cache13': '{% load cache %}{% cache foo bar %}{% endcache %}'})
def test_cache13(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('cache13')
@setup({'cache14': '{% load cache %}{% cache foo bar %}{% endcache %}'})
def test_cache14(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('cache14', {'foo': 'fail'})
@setup({'cache15': '{% load cache %}{% cache foo bar %}{% endcache %}'})
def test_cache15(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('cache15', {'foo': []})
@setup({'cache16': '{% load cache %}{% cache 1 foo bar %}{% endcache %}'})
def test_cache16(self):
"""
Regression test for #7460.
"""
output = self.engine.render_to_string('cache16', {'foo': 'foo', 'bar': 'with spaces'})
self.assertEqual(output, '')
@setup({'cache17': '{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}'})
def test_cache17(self):
"""
Regression test for #11270.
"""
output = self.engine.render_to_string('cache17', {'poem': 'Oh freddled gruntbuggly/'
'Thy micturations are to me/'
'As plurdled gabbleblotchits/'
'On a lurgid bee/'
'That mordiously hath bitled out/'
'Its earted jurtles/'
'Into a rancid festering/'
'Or else I shall rend thee in the gobberwarts'
'with my blurglecruncheon/'
'See if I dont.'})
self.assertEqual(output, 'Some Content')
@setup({'cache18': '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}'})
def test_cache18(self):
"""
Test whitespace in filter arguments
"""
output = self.engine.render_to_string('cache18')
self.assertEqual(output, 'cache18')
class CacheTests(SimpleTestCase):
def test_cache_regression_20130(self):
t = Template('{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}')
cachenode = t.nodelist[1]
self.assertEqual(cachenode.fragment_name, 'regression_20130')
@override_settings(CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'default',
},
'template_fragments': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'fragments',
},
})
def test_cache_fragment_cache(self):
"""
When a cache called "template_fragments" is present, the cache tag
will use it in preference to 'default'
"""
t1 = Template('{% load cache %}{% cache 1 fragment %}foo{% endcache %}')
t2 = Template('{% load cache %}{% cache 1 fragment using="default" %}bar{% endcache %}')
ctx = Context()
o1 = t1.render(ctx)
o2 = t2.render(ctx)
self.assertEqual(o1, 'foo')
self.assertEqual(o2, 'bar')
def test_cache_missing_backend(self):
"""
When a cache that doesn't exist is specified, the cache tag will
raise a TemplateSyntaxError
'"""
t = Template('{% load cache %}{% cache 1 backend using="unknown" %}bar{% endcache %}')
ctx = Context()
with self.assertRaises(TemplateSyntaxError):
t.render(ctx)
Django-1.8.7/tests/template_tests/syntax_tests/test_with.py 0000664 0001750 0001750 00000004305 12625116214 023674 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class WithTagTests(SimpleTestCase):
@setup({'with01': '{% with key=dict.key %}{{ key }}{% endwith %}'})
def test_with01(self):
output = self.engine.render_to_string('with01', {'dict': {'key': 50}})
self.assertEqual(output, '50')
@setup({'legacywith01': '{% with dict.key as key %}{{ key }}{% endwith %}'})
def test_legacywith01(self):
output = self.engine.render_to_string('legacywith01', {'dict': {'key': 50}})
self.assertEqual(output, '50')
@setup({'with02': '{{ key }}{% with key=dict.key %}'
'{{ key }}-{{ dict.key }}-{{ key }}'
'{% endwith %}{{ key }}'})
def test_with02(self):
output = self.engine.render_to_string('with02', {'dict': {'key': 50}})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID50-50-50INVALID')
else:
self.assertEqual(output, '50-50-50')
@setup({'legacywith02': '{{ key }}{% with dict.key as key %}'
'{{ key }}-{{ dict.key }}-{{ key }}'
'{% endwith %}{{ key }}'})
def test_legacywith02(self):
output = self.engine.render_to_string('legacywith02', {'dict': {'key': 50}})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID50-50-50INVALID')
else:
self.assertEqual(output, '50-50-50')
@setup({'with03': '{% with a=alpha b=beta %}{{ a }}{{ b }}{% endwith %}'})
def test_with03(self):
output = self.engine.render_to_string('with03', {'alpha': 'A', 'beta': 'B'})
self.assertEqual(output, 'AB')
@setup({'with-error01': '{% with dict.key xx key %}{{ key }}{% endwith %}'})
def test_with_error01(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('with-error01', {'dict': {'key': 50}})
@setup({'with-error02': '{% with dict.key as %}{{ key }}{% endwith %}'})
def test_with_error02(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('with-error02', {'dict': {'key': 50}})
Django-1.8.7/tests/template_tests/syntax_tests/test_include.py 0000664 0001750 0001750 00000031051 12625116214 024342 0 ustar tim tim 0000000 0000000 from django.template import (
Context, Template, TemplateDoesNotExist, TemplateSyntaxError, engines,
)
from django.test import SimpleTestCase, override_settings
from ..utils import setup
from .test_basic import basic_templates
include_fail_templates = {
'include-fail1': '{% load bad_tag %}{% badtag %}',
'include-fail2': '{% load broken_tag %}',
}
class IncludeTagTests(SimpleTestCase):
@setup({'include01': '{% include "basic-syntax01" %}'}, basic_templates)
def test_include01(self):
output = self.engine.render_to_string('include01')
self.assertEqual(output, 'something cool')
@setup({'include02': '{% include "basic-syntax02" %}'}, basic_templates)
def test_include02(self):
output = self.engine.render_to_string('include02', {'headline': 'Included'})
self.assertEqual(output, 'Included')
@setup({'include03': '{% include template_name %}'}, basic_templates)
def test_include03(self):
output = self.engine.render_to_string(
'include03',
{'template_name': 'basic-syntax02', 'headline': 'Included'},
)
self.assertEqual(output, 'Included')
@setup({'include04': 'a{% include "nonexistent" %}b'})
def test_include04(self):
template = self.engine.get_template('include04')
if self.engine.debug:
with self.assertRaises(TemplateDoesNotExist):
template.render(Context({}))
else:
output = template.render(Context({}))
self.assertEqual(output, "ab")
@setup({
'include 05': 'template with a space',
'include06': '{% include "include 05"%}',
})
def test_include06(self):
output = self.engine.render_to_string('include06')
self.assertEqual(output, "template with a space")
@setup({'include07': '{% include "basic-syntax02" with headline="Inline" %}'}, basic_templates)
def test_include07(self):
output = self.engine.render_to_string('include07', {'headline': 'Included'})
self.assertEqual(output, 'Inline')
@setup({'include08': '{% include headline with headline="Dynamic" %}'}, basic_templates)
def test_include08(self):
output = self.engine.render_to_string('include08', {'headline': 'basic-syntax02'})
self.assertEqual(output, 'Dynamic')
@setup(
{'include09': '{{ first }}--'
'{% include "basic-syntax03" with first=second|lower|upper second=first|upper %}'
'--{{ second }}'},
basic_templates,
)
def test_include09(self):
output = self.engine.render_to_string('include09', {'first': 'Ul', 'second': 'lU'})
self.assertEqual(output, 'Ul--LU --- UL--lU')
@setup({'include10': '{% include "basic-syntax03" only %}'}, basic_templates)
def test_include10(self):
output = self.engine.render_to_string('include10', {'first': '1'})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID --- INVALID')
else:
self.assertEqual(output, ' --- ')
@setup({'include11': '{% include "basic-syntax03" only with second=2 %}'}, basic_templates)
def test_include11(self):
output = self.engine.render_to_string('include11', {'first': '1'})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID --- 2')
else:
self.assertEqual(output, ' --- 2')
@setup({'include12': '{% include "basic-syntax03" with first=1 only %}'}, basic_templates)
def test_include12(self):
output = self.engine.render_to_string('include12', {'second': '2'})
if self.engine.string_if_invalid:
self.assertEqual(output, '1 --- INVALID')
else:
self.assertEqual(output, '1 --- ')
@setup(
{'include13': '{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}'},
basic_templates,
)
def test_include13(self):
output = self.engine.render_to_string('include13', {'first': '&'})
if self.engine.string_if_invalid:
self.assertEqual(output, '& --- INVALID')
else:
self.assertEqual(output, '& --- ')
@setup(
{'include14': '{% autoescape off %}'
'{% include "basic-syntax03" with first=var1 only %}'
'{% endautoescape %}'},
basic_templates,
)
def test_include14(self):
output = self.engine.render_to_string('include14', {'var1': '&'})
if self.engine.string_if_invalid:
self.assertEqual(output, '& --- INVALID')
else:
self.assertEqual(output, '& --- ')
# Include syntax errors
@setup({'include-error01': '{% include "basic-syntax01" with %}'})
def test_include_error01(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('include-error01')
@setup({'include-error02': '{% include "basic-syntax01" with "no key" %}'})
def test_include_error02(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('include-error02')
@setup({'include-error03': '{% include "basic-syntax01" with dotted.arg="error" %}'})
def test_include_error03(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('include-error03')
@setup({'include-error04': '{% include "basic-syntax01" something_random %}'})
def test_include_error04(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('include-error04')
@setup({'include-error05': '{% include "basic-syntax01" foo="duplicate" foo="key" %}'})
def test_include_error05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('include-error05')
@setup({'include-error06': '{% include "basic-syntax01" only only %}'})
def test_include_error06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('include-error06')
@setup(include_fail_templates)
def test_include_fail1(self):
with self.assertRaises(RuntimeError):
self.engine.get_template('include-fail1')
@setup(include_fail_templates)
def test_include_fail2(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('include-fail2')
@setup({'include-error07': '{% include "include-fail1" %}'}, include_fail_templates)
def test_include_error07(self):
template = self.engine.get_template('include-error07')
if self.engine.debug:
with self.assertRaises(RuntimeError):
template.render(Context())
else:
self.assertEqual(template.render(Context()), '')
@setup({'include-error08': '{% include "include-fail2" %}'}, include_fail_templates)
def test_include_error08(self):
template = self.engine.get_template('include-error08')
if self.engine.debug:
with self.assertRaises(TemplateSyntaxError):
template.render(Context())
else:
self.assertEqual(template.render(Context()), '')
@setup({'include-error09': '{% include failed_include %}'}, include_fail_templates)
def test_include_error09(self):
context = Context({'failed_include': 'include-fail1'})
template = self.engine.get_template('include-error09')
if self.engine.debug:
with self.assertRaises(RuntimeError):
template.render(context)
else:
self.assertEqual(template.render(context), '')
@setup({'include-error10': '{% include failed_include %}'}, include_fail_templates)
def test_include_error10(self):
context = Context({'failed_include': 'include-fail2'})
template = self.engine.get_template('include-error10')
if self.engine.debug:
with self.assertRaises(TemplateSyntaxError):
template.render(context)
else:
self.assertEqual(template.render(context), '')
class IncludeTests(SimpleTestCase):
# Test the base loader class via the app loader. load_template
# from base is used by all shipped loaders excepting cached,
# which has its own test.
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
# Enable debug, otherwise the exception raised during
# {% include %} processing will be suppressed.
'debug': True,
}
}])
def test_include_missing_template(self):
"""
Tests that the correct template is identified as not existing
when {% include %} specifies a template that does not exist.
"""
template = engines['django'].get_template('test_include_error.html')
with self.assertRaises(TemplateDoesNotExist) as e:
template.render()
self.assertEqual(e.exception.args[0], 'missing.html')
# Test the base loader class via the app loader. load_template
# from base is used by all shipped loaders excepting cached,
# which has its own test.
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
# Enable debug, otherwise the exception raised during
# {% include %} processing will be suppressed.
'debug': True,
}
}])
def test_extends_include_missing_baseloader(self):
"""
#12787 -- Tests that the correct template is identified as not existing
when {% extends %} specifies a template that does exist, but that
template has an {% include %} of something that does not exist.
"""
template = engines['django'].get_template('test_extends_error.html')
with self.assertRaises(TemplateDoesNotExist) as e:
template.render()
self.assertEqual(e.exception.args[0], 'missing.html')
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'debug': True,
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.app_directories.Loader',
]),
],
},
}])
def test_extends_include_missing_cachedloader(self):
"""
Test the cache loader separately since it overrides load_template.
"""
template = engines['django'].get_template('test_extends_error.html')
with self.assertRaises(TemplateDoesNotExist) as e:
template.render()
self.assertEqual(e.exception.args[0], 'missing.html')
# Repeat to ensure it still works when loading from the cache
template = engines['django'].get_template('test_extends_error.html')
with self.assertRaises(TemplateDoesNotExist) as e:
template.render()
self.assertEqual(e.exception.args[0], 'missing.html')
def test_include_template_argument(self):
"""
Support any render() supporting object
"""
ctx = Context({
'tmpl': Template('This worked!'),
})
outer_tmpl = Template('{% include tmpl %}')
output = outer_tmpl.render(ctx)
self.assertEqual(output, 'This worked!')
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'debug': True,
},
}])
def test_include_immediate_missing(self):
"""
#16417 -- Include tags pointing to missing templates should not raise
an error at parsing time.
"""
template = Template('{% include "this_does_not_exist.html" %}')
self.assertIsInstance(template, Template)
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
},
}])
def test_include_recursive(self):
comments = [
{
'comment': 'A1',
'children': [
{'comment': 'B1', 'children': []},
{'comment': 'B2', 'children': []},
{'comment': 'B3', 'children': [
{'comment': 'C1', 'children': []}
]},
]
}
]
t = engines['django'].get_template('recursive_include.html')
self.assertEqual(
"Recursion! A1 Recursion! B1 B2 B3 Recursion! C1",
t.render({'comments': comments}).replace(' ', '').replace('\n', ' ').strip(),
)
Django-1.8.7/tests/template_tests/syntax_tests/test_builtins.py 0000664 0001750 0001750 00000001165 12625116214 024553 0 ustar tim tim 0000000 0000000 from django.test import SimpleTestCase
from ..utils import setup
class BuiltinsTests(SimpleTestCase):
@setup({'builtins01': '{{ True }}'})
def test_builtins01(self):
output = self.engine.render_to_string('builtins01')
self.assertEqual(output, 'True')
@setup({'builtins02': '{{ False }}'})
def test_builtins02(self):
output = self.engine.render_to_string('builtins02')
self.assertEqual(output, 'False')
@setup({'builtins03': '{{ None }}'})
def test_builtins03(self):
output = self.engine.render_to_string('builtins03')
self.assertEqual(output, 'None')
Django-1.8.7/tests/template_tests/syntax_tests/test_url.py 0000664 0001750 0001750 00000025455 12625116214 023534 0 ustar tim tim 0000000 0000000 # coding: utf-8
from django.core.urlresolvers import NoReverseMatch
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase, ignore_warnings, override_settings
from django.utils.deprecation import RemovedInDjango110Warning
from ..utils import setup
@override_settings(ROOT_URLCONF='template_tests.urls')
class UrlTagTests(SimpleTestCase):
# Successes
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url01': '{% url "template_tests.views.client" client.id %}'})
def test_url01(self):
output = self.engine.render_to_string('url01', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url02': '{% url "template_tests.views.client_action" id=client.id action="update" %}'})
def test_url02(self):
output = self.engine.render_to_string('url02', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url02a': '{% url "template_tests.views.client_action" client.id "update" %}'})
def test_url02a(self):
output = self.engine.render_to_string('url02a', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url02b': "{% url 'template_tests.views.client_action' id=client.id action='update' %}"})
def test_url02b(self):
output = self.engine.render_to_string('url02b', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url02c': "{% url 'template_tests.views.client_action' client.id 'update' %}"})
def test_url02c(self):
output = self.engine.render_to_string('url02c', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url03': '{% url "template_tests.views.index" %}'})
def test_url03(self):
output = self.engine.render_to_string('url03')
self.assertEqual(output, '/')
@setup({'url04': '{% url "named.client" client.id %}'})
def test_url04(self):
output = self.engine.render_to_string('url04', {'client': {'id': 1}})
self.assertEqual(output, '/named-client/1/')
@setup({'url05': '{% url "метка_оператора" v %}'})
def test_url05(self):
output = self.engine.render_to_string('url05', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
@setup({'url06': '{% url "метка_оператора_2" tag=v %}'})
def test_url06(self):
output = self.engine.render_to_string('url06', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url07': '{% url "template_tests.views.client2" tag=v %}'})
def test_url07(self):
output = self.engine.render_to_string('url07', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
@setup({'url08': '{% url "метка_оператора" v %}'})
def test_url08(self):
output = self.engine.render_to_string('url08', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
@setup({'url09': '{% url "метка_оператора_2" tag=v %}'})
def test_url09(self):
output = self.engine.render_to_string('url09', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url10': '{% url "template_tests.views.client_action" id=client.id action="two words" %}'})
def test_url10(self):
output = self.engine.render_to_string('url10', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/two%20words/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url11': '{% url "template_tests.views.client_action" id=client.id action="==" %}'})
def test_url11(self):
output = self.engine.render_to_string('url11', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/==/')
@setup({'url12': '{% url "template_tests.views.client_action" '
'id=client.id action="!$&\'()*+,;=~:@," %}'})
@ignore_warnings(category=RemovedInDjango110Warning)
def test_url12(self):
output = self.engine.render_to_string('url12', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/!$&\'()*+,;=~:@,/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url13': '{% url "template_tests.views.client_action" '
'id=client.id action=arg|join:"-" %}'})
def test_url13(self):
output = self.engine.render_to_string('url13', {'client': {'id': 1}, 'arg': ['a', 'b']})
self.assertEqual(output, '/client/1/a-b/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url14': '{% url "template_tests.views.client_action" client.id arg|join:"-" %}'})
def test_url14(self):
output = self.engine.render_to_string('url14', {'client': {'id': 1}, 'arg': ['a', 'b']})
self.assertEqual(output, '/client/1/a-b/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url15': '{% url "template_tests.views.client_action" 12 "test" %}'})
def test_url15(self):
output = self.engine.render_to_string('url15')
self.assertEqual(output, '/client/12/test/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url18': '{% url "template_tests.views.client" "1,2" %}'})
def test_url18(self):
output = self.engine.render_to_string('url18')
self.assertEqual(output, '/client/1,2/')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url19': '{% url named_url client.id %}'})
def test_url19(self):
output = self.engine.render_to_string('url19', {'client': {'id': 1}, 'named_url': 'template_tests.views.client'})
self.assertEqual(output, '/client/1/')
@setup({'url20': '{% url url_name_in_var client.id %}'})
def test_url20(self):
output = self.engine.render_to_string('url20', {'client': {'id': 1}, 'url_name_in_var': 'named.client'})
self.assertEqual(output, '/named-client/1/')
# Failures
@setup({'url-fail01': '{% url %}'})
def test_url_fail01(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('url-fail01')
@setup({'url-fail02': '{% url "no_such_view" %}'})
def test_url_fail02(self):
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail02')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url-fail03': '{% url "template_tests.views.client" %}'})
def test_url_fail03(self):
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail03')
@setup({'url-fail04': '{% url "view" id, %}'})
def test_url_fail04(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('url-fail04')
@setup({'url-fail05': '{% url "view" id= %}'})
def test_url_fail05(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('url-fail05')
@setup({'url-fail06': '{% url "view" a.id=id %}'})
def test_url_fail06(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('url-fail06')
@setup({'url-fail07': '{% url "view" a.id!id %}'})
def test_url_fail07(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('url-fail07')
@setup({'url-fail08': '{% url "view" id="unterminatedstring %}'})
def test_url_fail08(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('url-fail08')
@setup({'url-fail09': '{% url "view" id=", %}'})
def test_url_fail09(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('url-fail09')
@setup({'url-fail11': '{% url named_url %}'})
def test_url_fail11(self):
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail11')
@setup({'url-fail12': '{% url named_url %}'})
def test_url_fail12(self):
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail12', {'named_url': 'no_such_view'})
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url-fail13': '{% url named_url %}'})
def test_url_fail13(self):
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail13', {'named_url': 'template_tests.views.client'})
@setup({'url-fail14': '{% url named_url id, %}'})
def test_url_fail14(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('url-fail14', {'named_url': 'view'})
@setup({'url-fail15': '{% url named_url id= %}'})
def test_url_fail15(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('url-fail15', {'named_url': 'view'})
@setup({'url-fail16': '{% url named_url a.id=id %}'})
def test_url_fail16(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('url-fail16', {'named_url': 'view'})
@setup({'url-fail17': '{% url named_url a.id!id %}'})
def test_url_fail17(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('url-fail17', {'named_url': 'view'})
@setup({'url-fail18': '{% url named_url id="unterminatedstring %}'})
def test_url_fail18(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('url-fail18', {'named_url': 'view'})
@setup({'url-fail19': '{% url named_url id=", %}'})
def test_url_fail19(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('url-fail19', {'named_url': 'view'})
# {% url ... as var %}
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url-asvar01': '{% url "template_tests.views.index" as url %}'})
def test_url_asvar01(self):
output = self.engine.render_to_string('url-asvar01')
self.assertEqual(output, '')
@ignore_warnings(category=RemovedInDjango110Warning)
@setup({'url-asvar02': '{% url "template_tests.views.index" as url %}{{ url }}'})
def test_url_asvar02(self):
output = self.engine.render_to_string('url-asvar02')
self.assertEqual(output, '/')
@setup({'url-asvar03': '{% url "no_such_view" as url %}{{ url }}'})
def test_url_asvar03(self):
output = self.engine.render_to_string('url-asvar03')
self.assertEqual(output, '')
Django-1.8.7/tests/template_tests/syntax_tests/test_load.py 0000664 0001750 0001750 00000005443 12625116214 023644 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class LoadTagTests(SimpleTestCase):
@setup({'load01': '{% load testtags subpackage.echo %}{% echo test %} {% echo2 "test" %}'})
def test_load01(self):
output = self.engine.render_to_string('load01')
self.assertEqual(output, 'test test')
@setup({'load02': '{% load subpackage.echo %}{% echo2 "test" %}'})
def test_load02(self):
output = self.engine.render_to_string('load02')
self.assertEqual(output, 'test')
# {% load %} tag, importing individual tags
@setup({'load03': '{% load echo from testtags %}{% echo this that theother %}'})
def test_load03(self):
output = self.engine.render_to_string('load03')
self.assertEqual(output, 'this that theother')
@setup({'load04': '{% load echo other_echo from testtags %}'
'{% echo this that theother %} {% other_echo and another thing %}'})
def test_load04(self):
output = self.engine.render_to_string('load04')
self.assertEqual(output, 'this that theother and another thing')
@setup({'load05': '{% load echo upper from testtags %}'
'{% echo this that theother %} {{ statement|upper }}'})
def test_load05(self):
output = self.engine.render_to_string('load05', {'statement': 'not shouting'})
self.assertEqual(output, 'this that theother NOT SHOUTING')
@setup({'load06': '{% load echo2 from subpackage.echo %}{% echo2 "test" %}'})
def test_load06(self):
output = self.engine.render_to_string('load06')
self.assertEqual(output, 'test')
# {% load %} tag errors
@setup({'load07': '{% load echo other_echo bad_tag from testtags %}'})
def test_load07(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('load07')
@setup({'load08': '{% load echo other_echo bad_tag from %}'})
def test_load08(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('load08')
@setup({'load09': '{% load from testtags %}'})
def test_load09(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('load09')
@setup({'load10': '{% load echo from bad_library %}'})
def test_load10(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('load10')
@setup({'load11': '{% load subpackage.echo_invalid %}'})
def test_load11(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('load11')
@setup({'load12': '{% load subpackage.missing %}'})
def test_load12(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('load12')
Django-1.8.7/tests/template_tests/syntax_tests/test_if_changed.py 0000664 0001750 0001750 00000022547 12625116214 025000 0 ustar tim tim 0000000 0000000 from django.template import Context, Template
from django.test import SimpleTestCase
from ..utils import setup
class IfChangedTagTests(SimpleTestCase):
@setup({'ifchanged01': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}'})
def test_ifchanged01(self):
output = self.engine.render_to_string('ifchanged01', {'num': (1, 2, 3)})
self.assertEqual(output, '123')
@setup({'ifchanged02': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}'})
def test_ifchanged02(self):
output = self.engine.render_to_string('ifchanged02', {'num': (1, 1, 3)})
self.assertEqual(output, '13')
@setup({'ifchanged03': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}'})
def test_ifchanged03(self):
output = self.engine.render_to_string('ifchanged03', {'num': (1, 1, 1)})
self.assertEqual(output, '1')
@setup({'ifchanged04': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}'
'{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}'
'{% endfor %}{% endfor %}'})
def test_ifchanged04(self):
output = self.engine.render_to_string('ifchanged04', {'num': (1, 2, 3), 'numx': (2, 2, 2)})
self.assertEqual(output, '122232')
@setup({'ifchanged05': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}'
'{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}'
'{% endfor %}{% endfor %}'})
def test_ifchanged05(self):
output = self.engine.render_to_string('ifchanged05', {'num': (1, 1, 1), 'numx': (1, 2, 3)})
self.assertEqual(output, '1123123123')
@setup({'ifchanged06': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}'
'{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}'
'{% endfor %}{% endfor %}'})
def test_ifchanged06(self):
output = self.engine.render_to_string('ifchanged06', {'num': (1, 1, 1), 'numx': (2, 2, 2)})
self.assertEqual(output, '1222')
@setup({'ifchanged07': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}'
'{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}'
'{% for y in numy %}{% ifchanged %}{{ y }}{% endifchanged %}'
'{% endfor %}{% endfor %}{% endfor %}'})
def test_ifchanged07(self):
output = self.engine.render_to_string('ifchanged07', {'num': (1, 1, 1), 'numx': (2, 2, 2), 'numy': (3, 3, 3)})
self.assertEqual(output, '1233323332333')
@setup({'ifchanged08': '{% for data in datalist %}{% for c,d in data %}'
'{% if c %}{% ifchanged %}{{ d }}{% endifchanged %}'
'{% endif %}{% endfor %}{% endfor %}'})
def test_ifchanged08(self):
output = self.engine.render_to_string('ifchanged08', {'datalist': [
[(1, 'a'), (1, 'a'), (0, 'b'), (1, 'c')],
[(0, 'a'), (1, 'c'), (1, 'd'), (1, 'd'), (0, 'e')]
]})
self.assertEqual(output, 'accd')
@setup({'ifchanged-param01': '{% for n in num %}{% ifchanged n %}..{% endifchanged %}'
'{{ n }}{% endfor %}'})
def test_ifchanged_param01(self):
"""
Test one parameter given to ifchanged.
"""
output = self.engine.render_to_string('ifchanged-param01', {'num': (1, 2, 3)})
self.assertEqual(output, '..1..2..3')
@setup({'ifchanged-param02': '{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}'
'{{ x }}{% endfor %}{% endfor %}'})
def test_ifchanged_param02(self):
output = self.engine.render_to_string('ifchanged-param02', {'num': (1, 2, 3), 'numx': (5, 6, 7)})
self.assertEqual(output, '..567..567..567')
@setup({'ifchanged-param03': '{% for n in num %}{{ n }}{% for x in numx %}'
'{% ifchanged x n %}{{ x }}{% endifchanged %}'
'{% endfor %}{% endfor %}'})
def test_ifchanged_param03(self):
"""
Test multiple parameters to ifchanged.
"""
output = self.engine.render_to_string('ifchanged-param03', {'num': (1, 1, 2), 'numx': (5, 6, 6)})
self.assertEqual(output, '156156256')
@setup({'ifchanged-param04': '{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}'
'{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}'
'{% endfor %}{% endfor %}'})
def test_ifchanged_param04(self):
"""
Test a date+hour like construct, where the hour of the last day is
the same but the date had changed, so print the hour anyway.
"""
output = self.engine.render_to_string(
'ifchanged-param04',
{'days': [{'hours': [1, 2, 3], 'day': 1}, {'hours': [3], 'day': 2}]},
)
self.assertEqual(output, '112323')
@setup({'ifchanged-param05': '{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}'
'{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}'
'{% endfor %}{% endfor %}'})
def test_ifchanged_param05(self):
"""
Logically the same as above, just written with explicit ifchanged
for the day.
"""
output = self.engine.render_to_string(
'ifchanged-param05',
{'days': [{'hours': [1, 2, 3], 'day': 1}, {'hours': [3], 'day': 2}]},
)
self.assertEqual(output, '112323')
@setup({'ifchanged-else01': '{% for id in ids %}{{ id }}'
'{% ifchanged id %}-first{% else %}-other{% endifchanged %}'
',{% endfor %}'})
def test_ifchanged_else01(self):
"""
Test the else clause of ifchanged.
"""
output = self.engine.render_to_string('ifchanged-else01', {'ids': [1, 1, 2, 2, 2, 3]})
self.assertEqual(output, '1-first,1-other,2-first,2-other,2-other,3-first,')
@setup({'ifchanged-else02': '{% for id in ids %}{{ id }}-'
'{% ifchanged id %}{% cycle red,blue %}{% else %}grey{% endifchanged %}'
',{% endfor %}'})
def test_ifchanged_else02(self):
output = self.engine.render_to_string('ifchanged-else02', {'ids': [1, 1, 2, 2, 2, 3]})
self.assertEqual(output, '1-red,1-grey,2-blue,2-grey,2-grey,3-red,')
@setup({'ifchanged-else03': '{% for id in ids %}{{ id }}'
'{% ifchanged id %}-{% cycle red,blue %}{% else %}{% endifchanged %}'
',{% endfor %}'})
def test_ifchanged_else03(self):
output = self.engine.render_to_string('ifchanged-else03', {'ids': [1, 1, 2, 2, 2, 3]})
self.assertEqual(output, '1-red,1,2-blue,2,2,3-red,')
@setup({'ifchanged-else04': '{% for id in ids %}'
'{% ifchanged %}***{{ id }}*{% else %}...{% endifchanged %}'
'{{ forloop.counter }}{% endfor %}'})
def test_ifchanged_else04(self):
output = self.engine.render_to_string('ifchanged-else04', {'ids': [1, 1, 2, 2, 2, 3, 4]})
self.assertEqual(output, '***1*1...2***2*3...4...5***3*6***4*7')
@setup({'ifchanged-filter-ws': '{% load custom %}{% for n in num %}'
'{% ifchanged n|noop:"x y" %}..{% endifchanged %}{{ n }}'
'{% endfor %}'})
def test_ifchanged_filter_ws(self):
"""
Test whitespace in filter arguments
"""
output = self.engine.render_to_string('ifchanged-filter-ws', {'num': (1, 2, 3)})
self.assertEqual(output, '..1..2..3')
class IfChangedTests(SimpleTestCase):
def test_ifchanged_concurrency(self):
"""
#15849 -- ifchanged should be thread-safe.
"""
template = Template('[0{% for x in foo %},{% with var=get_value %}{% ifchanged %}{{ var }}{% endifchanged %}{% endwith %}{% endfor %}]')
# Using generator to mimic concurrency.
# The generator is not passed to the 'for' loop, because it does a list(values)
# instead, call gen.next() in the template to control the generator.
def gen():
yield 1
yield 2
# Simulate that another thread is now rendering.
# When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below.
iter2 = iter([1, 2, 3])
output2 = template.render(Context({'foo': range(3), 'get_value': lambda: next(iter2)}))
self.assertEqual(output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {}'.format(output2))
yield 3
gen1 = gen()
output1 = template.render(Context({'foo': range(3), 'get_value': lambda: next(gen1)}))
self.assertEqual(output1, '[0,1,2,3]', 'Expected [0,1,2,3] in first template, got {}'.format(output1))
def test_ifchanged_render_once(self):
"""
#19890. The content of ifchanged template tag was rendered twice.
"""
template = Template('{% ifchanged %}{% cycle "1st time" "2nd time" %}{% endifchanged %}')
output = template.render(Context({}))
self.assertEqual(output, '1st time')
Django-1.8.7/tests/template_tests/syntax_tests/test_simple_tag.py 0000664 0001750 0001750 00000001507 12625116214 025046 0 ustar tim tim 0000000 0000000 from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class SimpleTagTests(SimpleTestCase):
@setup({'simpletag-renamed01': '{% load custom %}{% minusone 7 %}'})
def test_simpletag_renamed01(self):
output = self.engine.render_to_string('simpletag-renamed01')
self.assertEqual(output, '6')
@setup({'simpletag-renamed02': '{% load custom %}{% minustwo 7 %}'})
def test_simpletag_renamed02(self):
output = self.engine.render_to_string('simpletag-renamed02')
self.assertEqual(output, '5')
@setup({'simpletag-renamed03': '{% load custom %}{% minustwo_overridden_name 7 %}'})
def test_simpletag_renamed03(self):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('simpletag-renamed03')
Django-1.8.7/tests/template_tests/syntax_tests/test_ssi.py 0000664 0001750 0001750 00000010511 12625116214 023513 0 ustar tim tim 0000000 0000000 from __future__ import unicode_literals
import os
from django.template import Context, Engine
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import (
RemovedInDjango19Warning, RemovedInDjango110Warning,
)
from ..utils import ROOT, setup
@ignore_warnings(category=RemovedInDjango110Warning)
class SsiTagTests(SimpleTestCase):
# Test normal behavior
@setup({'ssi01': '{%% ssi "%s" %%}' % os.path.join(
ROOT, 'templates', 'ssi_include.html',
)})
def test_ssi01(self):
output = self.engine.render_to_string('ssi01')
self.assertEqual(output, 'This is for testing an ssi include. {{ test }}\n')
@setup({'ssi02': '{%% ssi "%s" %%}' % os.path.join(
ROOT, 'not_here',
)})
def test_ssi02(self):
output = self.engine.render_to_string('ssi02')
self.assertEqual(output, ''),
@setup({'ssi03': "{%% ssi '%s' %%}" % os.path.join(
ROOT, 'not_here',
)})
def test_ssi03(self):
output = self.engine.render_to_string('ssi03')
self.assertEqual(output, ''),
# Test passing as a variable
@ignore_warnings(category=RemovedInDjango19Warning)
@setup({'ssi04': '{% load ssi from future %}{% ssi ssi_file %}'})
def test_ssi04(self):
output = self.engine.render_to_string('ssi04', {
'ssi_file': os.path.join(ROOT, 'templates', 'ssi_include.html')
})
self.assertEqual(output, 'This is for testing an ssi include. {{ test }}\n')
@ignore_warnings(category=RemovedInDjango19Warning)
@setup({'ssi05': '{% load ssi from future %}{% ssi ssi_file %}'})
def test_ssi05(self):
output = self.engine.render_to_string('ssi05', {'ssi_file': 'no_file'})
self.assertEqual(output, '')
# Test parsed output
@setup({'ssi06': '{%% ssi "%s" parsed %%}' % os.path.join(
ROOT, 'templates', 'ssi_include.html',
)})
def test_ssi06(self):
output = self.engine.render_to_string('ssi06', {'test': 'Look ma! It parsed!'})
self.assertEqual(output, 'This is for testing an ssi include. '
'Look ma! It parsed!\n')
@setup({'ssi07': '{%% ssi "%s" parsed %%}' % os.path.join(
ROOT, 'not_here',
)})
def test_ssi07(self):
output = self.engine.render_to_string('ssi07', {'test': 'Look ma! It parsed!'})
self.assertEqual(output, '')
# Test space in file name
@setup({'ssi08': '{%% ssi "%s" %%}' % os.path.join(
ROOT, 'templates', 'ssi include with spaces.html',
)})
def test_ssi08(self):
output = self.engine.render_to_string('ssi08')
self.assertEqual(output, 'This is for testing an ssi include '
'with spaces in its name. {{ test }}\n')
@setup({'ssi09': '{%% ssi "%s" parsed %%}' % os.path.join(
ROOT, 'templates', 'ssi include with spaces.html',
)})
def test_ssi09(self):
output = self.engine.render_to_string('ssi09', {'test': 'Look ma! It parsed!'})
self.assertEqual(output, 'This is for testing an ssi include '
'with spaces in its name. Look ma! It parsed!\n')
@ignore_warnings(category=RemovedInDjango110Warning)
class SSISecurityTests(SimpleTestCase):
def setUp(self):
self.ssi_dir = os.path.join(ROOT, "templates", "first")
self.engine = Engine(allowed_include_roots=(self.ssi_dir,))
def render_ssi(self, path):
# the path must exist for the test to be reliable
self.assertTrue(os.path.exists(path))
return self.engine.from_string('{%% ssi "%s" %%}' % path).render(Context({}))
def test_allowed_paths(self):
acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html")
self.assertEqual(self.render_ssi(acceptable_path), 'First template\n')
def test_relative_include_exploit(self):
"""
May not bypass allowed_include_roots with relative paths
e.g. if allowed_include_roots = ("/var/www",), it should not be
possible to do {% ssi "/var/www/../../etc/passwd" %}
"""
disallowed_paths = [
os.path.join(self.ssi_dir, "..", "ssi_include.html"),
os.path.join(self.ssi_dir, "..", "second", "test.html"),
]
for disallowed_path in disallowed_paths:
self.assertEqual(self.render_ssi(disallowed_path), '')
Django-1.8.7/tests/template_tests/test_unicode.py 0000664 0001750 0001750 00000002536 12625116214 021603 0 ustar tim tim 0000000 0000000 # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unittest import TestCase
from django.template import Context, Template
from django.template.base import TemplateEncodingError
from django.utils import six
from django.utils.safestring import SafeData
class UnicodeTests(TestCase):
def test_template(self):
# Templates can be created from unicode strings.
t1 = Template('Å ÄĆŽćžšđ {{ var }}')
# Templates can also be created from bytestrings. These are assumed to
# be encoded using UTF-8.
s = b'\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}'
t2 = Template(s)
s = b'\x80\xc5\xc0'
self.assertRaises(TemplateEncodingError, Template, s)
# Contexts can be constructed from unicode or UTF-8 bytestrings.
Context({b"var": b"foo"})
Context({"var": b"foo"})
c3 = Context({b"var": "ÄÄ‘"})
Context({"var": b"\xc4\x90\xc4\x91"})
# 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).
self.assertEqual(t1.render(c3), t2.render(c3))
self.assertIsInstance(t1.render(c3), six.text_type)
self.assertIsInstance(t1.render(c3), SafeData)
Django-1.8.7/tests/template_tests/views.py 0000664 0001750 0001750 00000000700 12603513307 020242 0 ustar tim tim 0000000 0000000 # Fake views for testing url reverse lookup
from django.http import HttpResponse
from django.template.response import TemplateResponse
def index(request):
pass
def client(request, id):
pass
def client_action(request, id, action):
pass
def client2(request, tag):
pass
def template_response_view(request):
return TemplateResponse(request, 'response.html', {})
def snark(request):
return HttpResponse('Found him!')
Django-1.8.7/tests/template_tests/other_templates/ 0000775 0001750 0001750 00000000000 12625116243 021737 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/other_templates/test_dirs.html 0000664 0001750 0001750 00000000023 12603513307 024616 0 ustar tim tim 0000000 0000000 spam eggs{{ obj }}
Django-1.8.7/tests/template_tests/other_templates/priority/ 0000775 0001750 0001750 00000000000 12625116243 023620 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/other_templates/priority/foo.html 0000664 0001750 0001750 00000000011 12625116214 025257 0 ustar tim tim 0000000 0000000 priority
Django-1.8.7/tests/template_tests/utils.py 0000664 0001750 0001750 00000011463 12625116214 020255 0 ustar tim tim 0000000 0000000 # coding: utf-8
from __future__ import unicode_literals
import functools
import os
from django import template
from django.template import Library
from django.template.base import libraries
from django.template.engine import Engine
from django.test.utils import override_settings
from django.utils._os import upath
from django.utils.encoding import python_2_unicode_compatible
from django.utils.safestring import mark_safe
ROOT = os.path.dirname(os.path.abspath(upath(__file__)))
TEMPLATE_DIR = os.path.join(ROOT, 'templates')
def setup(templates, *args, **kwargs):
"""
Runs test method multiple times in the following order:
debug cached string_if_invalid
----- ------ -----------------
False False
False True
False False INVALID
False True INVALID
True False
True True
"""
# when testing deprecation warnings, it's useful to run just one test since
# the message won't be displayed multiple times
test_once = kwargs.get('test_once', False)
for arg in args:
templates.update(arg)
# numerous tests make use of an inclusion tag
# add this in here for simplicity
templates["inclusion.html"] = "{{ result }}"
loaders = [
('django.template.loaders.cached.Loader', [
('django.template.loaders.locmem.Loader', templates),
]),
]
def decorator(func):
@register_test_tags
# Make Engine.get_default() raise an exception to ensure that tests
# are properly isolated from Django's global settings.
@override_settings(TEMPLATES=None)
@functools.wraps(func)
def inner(self):
self.engine = Engine(
allowed_include_roots=[ROOT],
loaders=loaders,
)
func(self)
if test_once:
return
func(self)
self.engine = Engine(
allowed_include_roots=[ROOT],
loaders=loaders,
string_if_invalid='INVALID',
)
func(self)
func(self)
self.engine = Engine(
allowed_include_roots=[ROOT],
debug=True,
loaders=loaders,
)
func(self)
func(self)
return inner
return decorator
# Custom template tag for tests
register = Library()
class EchoNode(template.Node):
def __init__(self, contents):
self.contents = contents
def render(self, context):
return ' '.join(self.contents)
@register.tag
def echo(parser, token):
return EchoNode(token.contents.split()[1:])
register.tag('other_echo', echo)
@register.filter
def upper(value):
return value.upper()
def register_test_tags(func):
@functools.wraps(func)
def inner(self):
libraries['testtags'] = register
try:
func(self)
finally:
del libraries['testtags']
return inner
# Helper objects
class SomeException(Exception):
silent_variable_failure = True
class SomeOtherException(Exception):
pass
class ShouldNotExecuteException(Exception):
pass
class SomeClass:
def __init__(self):
self.otherclass = OtherClass()
def method(self):
return 'SomeClass.method'
def method2(self, o):
return o
def method3(self):
raise SomeException
def method4(self):
raise SomeOtherException
def method5(self):
raise TypeError
def __getitem__(self, key):
if key == 'silent_fail_key':
raise SomeException
elif key == 'noisy_fail_key':
raise SomeOtherException
raise KeyError
@property
def silent_fail_attribute(self):
raise SomeException
@property
def noisy_fail_attribute(self):
raise SomeOtherException
@property
def attribute_error_attribute(self):
raise AttributeError
class OtherClass:
def method(self):
return 'OtherClass.method'
class TestObj(object):
def is_true(self):
return True
def is_false(self):
return False
def is_bad(self):
raise ShouldNotExecuteException()
class SilentGetItemClass(object):
def __getitem__(self, key):
raise SomeException
class SilentAttrClass(object):
def b(self):
raise SomeException
b = property(b)
@python_2_unicode_compatible
class UTF8Class:
"Class whose __str__ returns non-ASCII data on Python 2"
def __str__(self):
return 'Å ÄĆŽćžšđ'
# These two classes are used to test auto-escaping of unicode output.
@python_2_unicode_compatible
class UnsafeClass:
def __str__(self):
return 'you & me'
@python_2_unicode_compatible
class SafeClass:
def __str__(self):
return mark_safe('you > me')
Django-1.8.7/tests/template_tests/templatetags/ 0000775 0001750 0001750 00000000000 12625116243 021232 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templatetags/inclusion.py 0000664 0001750 0001750 00000020351 12625116214 023606 0 ustar tim tim 0000000 0000000 import operator
from django.template import Library
from django.template.loader import get_template
from django.utils import six
register = Library()
@register.inclusion_tag('inclusion.html')
def inclusion_no_params():
"""Expected inclusion_no_params __doc__"""
return {"result": "inclusion_no_params - Expected result"}
inclusion_no_params.anything = "Expected inclusion_no_params __dict__"
@register.inclusion_tag(get_template('inclusion.html'))
def inclusion_no_params_from_template():
"""Expected inclusion_no_params_from_template __doc__"""
return {"result": "inclusion_no_params_from_template - Expected result"}
inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_one_param(arg):
"""Expected inclusion_one_param __doc__"""
return {"result": "inclusion_one_param - Expected result: %s" % arg}
inclusion_one_param.anything = "Expected inclusion_one_param __dict__"
@register.inclusion_tag(get_template('inclusion.html'))
def inclusion_one_param_from_template(arg):
"""Expected inclusion_one_param_from_template __doc__"""
return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg}
inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__"
@register.inclusion_tag('inclusion.html', takes_context=False)
def inclusion_explicit_no_context(arg):
"""Expected inclusion_explicit_no_context __doc__"""
return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg}
inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__"
@register.inclusion_tag(get_template('inclusion.html'), takes_context=False)
def inclusion_explicit_no_context_from_template(arg):
"""Expected inclusion_explicit_no_context_from_template __doc__"""
return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg}
inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__"
@register.inclusion_tag('inclusion.html', takes_context=True)
def inclusion_no_params_with_context(context):
"""Expected inclusion_no_params_with_context __doc__"""
return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']}
inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__"
@register.inclusion_tag(get_template('inclusion.html'), takes_context=True)
def inclusion_no_params_with_context_from_template(context):
"""Expected inclusion_no_params_with_context_from_template __doc__"""
return {"result": "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value']}
inclusion_no_params_with_context_from_template.anything = "Expected inclusion_no_params_with_context_from_template __dict__"
@register.inclusion_tag('inclusion.html', takes_context=True)
def inclusion_params_and_context(context, arg):
"""Expected inclusion_params_and_context __doc__"""
return {"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)}
inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__"
@register.inclusion_tag(get_template('inclusion.html'), takes_context=True)
def inclusion_params_and_context_from_template(context, arg):
"""Expected inclusion_params_and_context_from_template __doc__"""
return {"result": "inclusion_params_and_context_from_template - Expected result (context value: %s): %s" % (context['value'], arg)}
inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_two_params(one, two):
"""Expected inclusion_two_params __doc__"""
return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)}
inclusion_two_params.anything = "Expected inclusion_two_params __dict__"
@register.inclusion_tag(get_template('inclusion.html'))
def inclusion_two_params_from_template(one, two):
"""Expected inclusion_two_params_from_template __doc__"""
return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)}
inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_one_default(one, two='hi'):
"""Expected inclusion_one_default __doc__"""
return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)}
inclusion_one_default.anything = "Expected inclusion_one_default __dict__"
@register.inclusion_tag(get_template('inclusion.html'))
def inclusion_one_default_from_template(one, two='hi'):
"""Expected inclusion_one_default_from_template __doc__"""
return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)}
inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_unlimited_args(one, two='hi', *args):
"""Expected inclusion_unlimited_args __doc__"""
return {"result": "inclusion_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))}
inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__"
@register.inclusion_tag(get_template('inclusion.html'))
def inclusion_unlimited_args_from_template(one, two='hi', *args):
"""Expected inclusion_unlimited_args_from_template __doc__"""
return {"result": "inclusion_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))}
inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_only_unlimited_args(*args):
"""Expected inclusion_only_unlimited_args __doc__"""
return {"result": "inclusion_only_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))}
inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__"
@register.inclusion_tag(get_template('inclusion.html'))
def inclusion_only_unlimited_args_from_template(*args):
"""Expected inclusion_only_unlimited_args_from_template __doc__"""
return {"result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))}
inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__"
@register.inclusion_tag('test_incl_tag_current_app.html', takes_context=True)
def inclusion_tag_current_app(context):
"""Expected inclusion_tag_current_app __doc__"""
return {}
inclusion_tag_current_app.anything = "Expected inclusion_tag_current_app __dict__"
@register.inclusion_tag('test_incl_tag_use_l10n.html', takes_context=True)
def inclusion_tag_use_l10n(context):
"""Expected inclusion_tag_use_l10n __doc__"""
return {}
inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
"""Expected inclusion_unlimited_args_kwargs __doc__"""
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)}
inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__"
@register.inclusion_tag('inclusion.html', takes_context=True)
def inclusion_tag_without_context_parameter(arg):
"""Expected inclusion_tag_without_context_parameter __doc__"""
return {}
inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__"
@register.inclusion_tag('inclusion_extends1.html')
def inclusion_extends1():
return {}
@register.inclusion_tag('inclusion_extends2.html')
def inclusion_extends2():
return {}
Django-1.8.7/tests/template_tests/templatetags/subpackage/ 0000775 0001750 0001750 00000000000 12625116243 023337 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templatetags/subpackage/echo.py 0000664 0001750 0001750 00000000161 12603513307 024623 0 ustar tim tim 0000000 0000000 from django import template
register = template.Library()
@register.simple_tag
def echo2(arg):
return arg
Django-1.8.7/tests/template_tests/templatetags/subpackage/__init__.py 0000664 0001750 0001750 00000000000 12603513307 025434 0 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templatetags/subpackage/echo_invalid.py 0000664 0001750 0001750 00000000042 12625113144 026326 0 ustar tim tim 0000000 0000000 import nonexistent.module # NOQA
Django-1.8.7/tests/template_tests/templatetags/custom.py 0000664 0001750 0001750 00000017171 12625116214 023123 0 ustar tim tim 0000000 0000000 import operator
from django import template
from django.template.defaultfilters import stringfilter
from django.utils import six
register = template.Library()
@register.filter
@stringfilter
def trim(value, num):
return value[:num]
@register.filter
def noop(value, param=None):
"""A noop filter that always return its first argument and does nothing with
its second (optional) one.
Useful for testing out whitespace in filter arguments (see #19882)."""
return value
@register.simple_tag(takes_context=True)
def context_stack_length(context):
return len(context.dicts)
@register.simple_tag
def no_params():
"""Expected no_params __doc__"""
return "no_params - Expected result"
no_params.anything = "Expected no_params __dict__"
@register.simple_tag
def one_param(arg):
"""Expected one_param __doc__"""
return "one_param - Expected result: %s" % arg
one_param.anything = "Expected one_param __dict__"
@register.simple_tag(takes_context=False)
def explicit_no_context(arg):
"""Expected explicit_no_context __doc__"""
return "explicit_no_context - Expected result: %s" % arg
explicit_no_context.anything = "Expected explicit_no_context __dict__"
@register.simple_tag(takes_context=True)
def no_params_with_context(context):
"""Expected no_params_with_context __doc__"""
return "no_params_with_context - Expected result (context value: %s)" % context['value']
no_params_with_context.anything = "Expected no_params_with_context __dict__"
@register.simple_tag(takes_context=True)
def params_and_context(context, arg):
"""Expected params_and_context __doc__"""
return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
params_and_context.anything = "Expected params_and_context __dict__"
@register.simple_tag
def simple_two_params(one, two):
"""Expected simple_two_params __doc__"""
return "simple_two_params - Expected result: %s, %s" % (one, two)
simple_two_params.anything = "Expected simple_two_params __dict__"
@register.simple_tag
def simple_one_default(one, two='hi'):
"""Expected simple_one_default __doc__"""
return "simple_one_default - Expected result: %s, %s" % (one, two)
simple_one_default.anything = "Expected simple_one_default __dict__"
@register.simple_tag
def simple_unlimited_args(one, two='hi', *args):
"""Expected simple_unlimited_args __doc__"""
return "simple_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))
simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__"
@register.simple_tag
def simple_only_unlimited_args(*args):
"""Expected simple_only_unlimited_args __doc__"""
return "simple_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args)
simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__"
@register.simple_tag
def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
"""Expected simple_unlimited_args_kwargs __doc__"""
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return "simple_unlimited_args_kwargs - Expected result: %s / %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)
simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__"
@register.simple_tag(takes_context=True)
def simple_tag_without_context_parameter(arg):
"""Expected simple_tag_without_context_parameter __doc__"""
return "Expected result"
simple_tag_without_context_parameter.anything = "Expected simple_tag_without_context_parameter __dict__"
@register.simple_tag(takes_context=True)
def current_app(context):
return "%s" % context.current_app
@register.simple_tag(takes_context=True)
def use_l10n(context):
return "%s" % context.use_l10n
@register.simple_tag(name='minustwo')
def minustwo_overridden_name(value):
return value - 2
register.simple_tag(lambda x: x - 1, name='minusone')
@register.assignment_tag
def assignment_no_params():
"""Expected assignment_no_params __doc__"""
return "assignment_no_params - Expected result"
assignment_no_params.anything = "Expected assignment_no_params __dict__"
@register.assignment_tag
def assignment_one_param(arg):
"""Expected assignment_one_param __doc__"""
return "assignment_one_param - Expected result: %s" % arg
assignment_one_param.anything = "Expected assignment_one_param __dict__"
@register.assignment_tag(takes_context=False)
def assignment_explicit_no_context(arg):
"""Expected assignment_explicit_no_context __doc__"""
return "assignment_explicit_no_context - Expected result: %s" % arg
assignment_explicit_no_context.anything = "Expected assignment_explicit_no_context __dict__"
@register.assignment_tag(takes_context=True)
def assignment_no_params_with_context(context):
"""Expected assignment_no_params_with_context __doc__"""
return "assignment_no_params_with_context - Expected result (context value: %s)" % context['value']
assignment_no_params_with_context.anything = "Expected assignment_no_params_with_context __dict__"
@register.assignment_tag(takes_context=True)
def assignment_params_and_context(context, arg):
"""Expected assignment_params_and_context __doc__"""
return "assignment_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
assignment_params_and_context.anything = "Expected assignment_params_and_context __dict__"
@register.assignment_tag
def assignment_two_params(one, two):
"""Expected assignment_two_params __doc__"""
return "assignment_two_params - Expected result: %s, %s" % (one, two)
assignment_two_params.anything = "Expected assignment_two_params __dict__"
@register.assignment_tag
def assignment_one_default(one, two='hi'):
"""Expected assignment_one_default __doc__"""
return "assignment_one_default - Expected result: %s, %s" % (one, two)
assignment_one_default.anything = "Expected assignment_one_default __dict__"
@register.assignment_tag
def assignment_unlimited_args(one, two='hi', *args):
"""Expected assignment_unlimited_args __doc__"""
return "assignment_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))
assignment_unlimited_args.anything = "Expected assignment_unlimited_args __dict__"
@register.assignment_tag
def assignment_only_unlimited_args(*args):
"""Expected assignment_only_unlimited_args __doc__"""
return "assignment_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args)
assignment_only_unlimited_args.anything = "Expected assignment_only_unlimited_args __dict__"
@register.assignment_tag
def assignment_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
"""Expected assignment_unlimited_args_kwargs __doc__"""
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return "assignment_unlimited_args_kwargs - Expected result: %s / %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)
assignment_unlimited_args_kwargs.anything = "Expected assignment_unlimited_args_kwargs __dict__"
@register.assignment_tag(takes_context=True)
def assignment_tag_without_context_parameter(arg):
"""Expected assignment_tag_without_context_parameter __doc__"""
return "Expected result"
assignment_tag_without_context_parameter.anything = "Expected assignment_tag_without_context_parameter __dict__"
Django-1.8.7/tests/template_tests/templatetags/broken_tag.py 0000664 0001750 0001750 00000000045 12625113144 023713 0 ustar tim tim 0000000 0000000 from django import Xtemplate # NOQA
Django-1.8.7/tests/template_tests/templatetags/bad_tag.py 0000664 0001750 0001750 00000000351 12625116214 023162 0 ustar tim tim 0000000 0000000 from django import template
register = template.Library()
@register.tag
def badtag(parser, token):
raise RuntimeError("I am a bad tag")
@register.simple_tag
def badsimpletag():
raise RuntimeError("I am a bad simpletag")
Django-1.8.7/tests/template_tests/templatetags/__init__.py 0000664 0001750 0001750 00000000000 12603513307 023327 0 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/test_smartif.py 0000664 0001750 0001750 00000004202 12603513307 021612 0 ustar tim tim 0000000 0000000 import unittest
from django.template.smartif import IfParser
class SmartIfTests(unittest.TestCase):
def assertCalcEqual(self, expected, tokens):
self.assertEqual(expected, IfParser(tokens).parse().eval({}))
# We only test things here that are difficult to test elsewhere
# Many other tests are found in the main tests for builtin template tags
# Test parsing via the printed parse tree
def test_not(self):
var = IfParser(["not", False]).parse()
self.assertEqual("(not (literal False))", repr(var))
self.assertTrue(var.eval({}))
self.assertFalse(IfParser(["not", True]).parse().eval({}))
def test_or(self):
var = IfParser([True, "or", False]).parse()
self.assertEqual("(or (literal True) (literal False))", repr(var))
self.assertTrue(var.eval({}))
def test_in(self):
list_ = [1, 2, 3]
self.assertCalcEqual(True, [1, 'in', list_])
self.assertCalcEqual(False, [1, 'in', None])
self.assertCalcEqual(False, [None, 'in', list_])
def test_not_in(self):
list_ = [1, 2, 3]
self.assertCalcEqual(False, [1, 'not', 'in', list_])
self.assertCalcEqual(True, [4, 'not', 'in', list_])
self.assertCalcEqual(False, [1, 'not', 'in', None])
self.assertCalcEqual(True, [None, 'not', 'in', list_])
def test_precedence(self):
# (False and False) or True == True <- we want this one, like Python
# False and (False or True) == False
self.assertCalcEqual(True, [False, 'and', False, 'or', True])
# True or (False and False) == True <- we want this one, like Python
# (True or False) and False == False
self.assertCalcEqual(True, [True, 'or', False, 'and', False])
# (1 or 1) == 2 -> False
# 1 or (1 == 2) -> True <- we want this one
self.assertCalcEqual(True, [1, 'or', 1, '==', 2])
self.assertCalcEqual(True, [True, '==', True, 'or', True, '==', False])
self.assertEqual("(or (and (== (literal 1) (literal 2)) (literal 3)) (literal 4))",
repr(IfParser([1, '==', 2, 'and', 3, 'or', 4]).parse()))
Django-1.8.7/tests/template_tests/test_engine.py 0000664 0001750 0001750 00000010414 12625116214 021414 0 ustar tim tim 0000000 0000000 import os
from django.template import Context
from django.template.engine import Engine
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango110Warning
from .utils import ROOT, TEMPLATE_DIR
OTHER_DIR = os.path.join(ROOT, 'other_templates')
@ignore_warnings(category=RemovedInDjango110Warning)
class DeprecatedRenderToStringTest(SimpleTestCase):
def setUp(self):
self.engine = Engine(dirs=[TEMPLATE_DIR])
def test_basic_context(self):
self.assertEqual(
self.engine.render_to_string('test_context.html', {'obj': 'test'}),
'obj:test\n',
)
def test_existing_context_kept_clean(self):
context = Context({'obj': 'before'})
output = self.engine.render_to_string(
'test_context.html', {'obj': 'after'}, context_instance=context,
)
self.assertEqual(output, 'obj:after\n')
self.assertEqual(context['obj'], 'before')
def test_no_empty_dict_pushed_to_stack(self):
"""
#21741 -- An empty dict should not be pushed to the context stack when
render_to_string is called without a context argument.
"""
# The stack should have a length of 1, corresponding to the builtins
self.assertEqual(
'1',
self.engine.render_to_string('test_context_stack.html').strip(),
)
self.assertEqual(
'1',
self.engine.render_to_string(
'test_context_stack.html',
context_instance=Context()
).strip(),
)
class LoaderTests(SimpleTestCase):
def test_debug_nodelist_name(self):
engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
template_name = 'index.html'
template = engine.get_template(template_name)
name = template.nodelist[0].source[0].name
self.assertTrue(name.endswith(template_name))
def test_origin(self):
engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
template = engine.get_template('index.html')
self.assertEqual(template.origin.loadname, 'index.html')
def test_origin_debug_false(self):
engine = Engine(dirs=[TEMPLATE_DIR], debug=False)
template = engine.get_template('index.html')
self.assertEqual(template.origin, None)
def test_loader_priority(self):
"""
#21460 -- Check that the order of template loader works.
"""
loaders = [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]
engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders)
template = engine.get_template('priority/foo.html')
self.assertEqual(template.render(Context()), 'priority\n')
def test_cached_loader_priority(self):
"""
Check that the order of template loader works. Refs #21460.
"""
loaders = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
]
engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders)
template = engine.get_template('priority/foo.html')
self.assertEqual(template.render(Context()), 'priority\n')
template = engine.get_template('priority/foo.html')
self.assertEqual(template.render(Context()), 'priority\n')
@ignore_warnings(category=RemovedInDjango110Warning)
class TemplateDirsOverrideTests(SimpleTestCase):
DIRS = ((OTHER_DIR, ), [OTHER_DIR])
def setUp(self):
self.engine = Engine()
def test_render_to_string(self):
for dirs in self.DIRS:
self.assertEqual(
self.engine.render_to_string('test_dirs.html', dirs=dirs),
'spam eggs\n',
)
def test_get_template(self):
for dirs in self.DIRS:
template = self.engine.get_template('test_dirs.html', dirs=dirs)
self.assertEqual(template.render(Context()), 'spam eggs\n')
def test_select_template(self):
for dirs in self.DIRS:
template = self.engine.select_template(['test_dirs.html'], dirs=dirs)
self.assertEqual(template.render(Context()), 'spam eggs\n')
Django-1.8.7/tests/template_tests/urls.py 0000664 0001750 0001750 00000001327 12625116214 020100 0 ustar tim tim 0000000 0000000 # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
# Test urls for testing reverse lookups
url(r'^$', views.index),
url(r'^client/([0-9,]+)/$', views.client),
url(r'^client/(?P[0-9]+)/(?P[^/]+)/$', views.client_action),
url(r'^client/(?P[0-9]+)/(?P[^/]+)/$', views.client_action),
url(r'^named-client/([0-9]+)/$', views.client2, name="named.client"),
# Unicode strings are permitted everywhere.
url(r'^Юникод/(\w+)/$', views.client2, name="метка_оператора"),
url(r'^Юникод/(?P\S+)/$', views.client2, name="метка_оператора_2"),
]
Django-1.8.7/tests/template_tests/templates/ 0000775 0001750 0001750 00000000000 12625116243 020536 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templates/broken_base.html 0000664 0001750 0001750 00000000035 12603513307 023672 0 ustar tim tim 0000000 0000000 {% include "missing.html" %}
Django-1.8.7/tests/template_tests/templates/template_tests/ 0000775 0001750 0001750 00000000000 12625116243 023573 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templates/template_tests/using.html 0000664 0001750 0001750 00000000004 12625116214 025576 0 ustar tim tim 0000000 0000000 DTL
Django-1.8.7/tests/template_tests/templates/test_incl_tag_current_app.html 0000664 0001750 0001750 00000000043 12625113144 026637 0 ustar tim tim 0000000 0000000 {% load custom %}{% current_app %}
Django-1.8.7/tests/template_tests/templates/second/ 0000775 0001750 0001750 00000000000 12625116243 022011 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templates/second/test.html 0000664 0001750 0001750 00000000020 12603513307 023644 0 ustar tim tim 0000000 0000000 Second template
Django-1.8.7/tests/template_tests/templates/included_content.html 0000664 0001750 0001750 00000000270 12603513307 024742 0 ustar tim tim 0000000 0000000 {% extends "included_base.html" %}
{% block content %}
content
{{ block.super }}
{% endblock %}
{% block error_here %}
error here
{% url "non_existing_url" %}
{% endblock %}
Django-1.8.7/tests/template_tests/templates/inclusion_extends1.html 0000664 0001750 0001750 00000000111 12625116214 025231 0 ustar tim tim 0000000 0000000 {% extends 'inclusion_base.html' %}
{% block content %}one{% endblock %}
Django-1.8.7/tests/template_tests/templates/index.html 0000664 0001750 0001750 00000000006 12625116214 022525 0 ustar tim tim 0000000 0000000 index
Django-1.8.7/tests/template_tests/templates/inclusion_extends2.html 0000664 0001750 0001750 00000000111 12625116214 025232 0 ustar tim tim 0000000 0000000 {% extends 'inclusion_base.html' %}
{% block content %}two{% endblock %}
Django-1.8.7/tests/template_tests/templates/included_base.html 0000664 0001750 0001750 00000000112 12603513307 024175 0 ustar tim tim 0000000 0000000 {% block content %}
{% block error_here %}{% endblock %}
{% endblock %}
Django-1.8.7/tests/template_tests/templates/ssi include with spaces.html 0000664 0001750 0001750 00000000107 12603513307 026015 0 ustar tim tim 0000000 0000000 This is for testing an ssi include with spaces in its name. {{ test }}
Django-1.8.7/tests/template_tests/templates/test_incl_tag_use_l10n.html 0000664 0001750 0001750 00000000040 12603513307 025741 0 ustar tim tim 0000000 0000000 {% load custom %}{% use_l10n %}
Django-1.8.7/tests/template_tests/templates/test_context_stack.html 0000664 0001750 0001750 00000000055 12603513307 025332 0 ustar tim tim 0000000 0000000 {% load custom %}
{% context_stack_length %}
Django-1.8.7/tests/template_tests/templates/test_extends_error.html 0000664 0001750 0001750 00000000041 12603513307 025337 0 ustar tim tim 0000000 0000000 {% extends "broken_base.html" %}
Django-1.8.7/tests/template_tests/templates/priority/ 0000775 0001750 0001750 00000000000 12625116243 022417 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templates/priority/foo.html 0000664 0001750 0001750 00000000014 12603513307 024061 0 ustar tim tim 0000000 0000000 no priority
Django-1.8.7/tests/template_tests/templates/recursive_include.html 0000664 0001750 0001750 00000000314 12603513307 025132 0 ustar tim tim 0000000 0000000 Recursion!
{% for comment in comments %}
{{ comment.comment }}
{% if comment.children %}
{% include "recursive_include.html" with comments=comment.children %}
{% endif %}
{% endfor %}
Django-1.8.7/tests/template_tests/templates/test_context.html 0000664 0001750 0001750 00000000016 12625116214 024142 0 ustar tim tim 0000000 0000000 obj:{{ obj }}
Django-1.8.7/tests/template_tests/templates/inclusion_base.html 0000664 0001750 0001750 00000000046 12625116214 024417 0 ustar tim tim 0000000 0000000 {% block content %}base{% endblock %}
Django-1.8.7/tests/template_tests/templates/response.html 0000664 0001750 0001750 00000000110 12603513307 023250 0 ustar tim tim 0000000 0000000 This is where you can find the snark: {% url "snark" %}
{% now "U.u" %}
Django-1.8.7/tests/template_tests/templates/first/ 0000775 0001750 0001750 00000000000 12625116243 021665 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/templates/first/test.html 0000664 0001750 0001750 00000000017 12603513307 023526 0 ustar tim tim 0000000 0000000 First template
Django-1.8.7/tests/template_tests/templates/ssi_include.html 0000664 0001750 0001750 00000000057 12603513307 023725 0 ustar tim tim 0000000 0000000 This is for testing an ssi include. {{ test }}
Django-1.8.7/tests/template_tests/templates/inclusion.html 0000664 0001750 0001750 00000000015 12603513307 023421 0 ustar tim tim 0000000 0000000 {{ result }}
Django-1.8.7/tests/template_tests/templates/test_include_error.html 0000664 0001750 0001750 00000000035 12625116214 025313 0 ustar tim tim 0000000 0000000 {% include "missing.html" %}
Django-1.8.7/tests/template_tests/eggs/ 0000775 0001750 0001750 00000000000 12625116243 017465 5 ustar tim tim 0000000 0000000 Django-1.8.7/tests/template_tests/eggs/tagsegg.egg 0000664 0001750 0001750 00000005025 12603513307 021572 0 ustar tim tim 0000000 0000000 PK †¹Ž<“×2 EGG-INFO/dependency_links.txtã PK †¹Ž