summaryrefslogtreecommitdiff
path: root/tests/othertests
diff options
context:
space:
mode:
authorJason Pellerin <jpellerin@gmail.com>2006-09-04 02:20:26 +0000
committerJason Pellerin <jpellerin@gmail.com>2006-09-04 02:20:26 +0000
commitb17f250907351923f39f8a50b87a35b26d2ca307 (patch)
treebd0202dea501c6678a0b56b8e108194aab78468d /tests/othertests
parent5a58772a1ee470e2890d3c716ce4918555100a55 (diff)
[multi-db] Merge trunk to [3661]
git-svn-id: http://code.djangoproject.com/svn/django/branches/multiple-db-support@3712 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'tests/othertests')
-rw-r--r--tests/othertests/__init__.py0
-rw-r--r--tests/othertests/ansi_sql.py147
-rw-r--r--tests/othertests/cache.py60
-rw-r--r--tests/othertests/dateformat.py80
-rw-r--r--tests/othertests/db_typecasts.py51
-rw-r--r--tests/othertests/defaultfilters.py361
-rw-r--r--tests/othertests/httpwrappers.py358
-rw-r--r--tests/othertests/manager_db.py23
-rw-r--r--tests/othertests/manager_schema_manipulation.py143
-rw-r--r--tests/othertests/markup.py70
-rw-r--r--tests/othertests/request_isolation.py140
-rw-r--r--tests/othertests/sql/car.sql2
-rw-r--r--tests/othertests/templates.py634
-rw-r--r--tests/othertests/thread_isolation.py300
-rw-r--r--tests/othertests/urlpatterns_reverse.py47
15 files changed, 0 insertions, 2416 deletions
diff --git a/tests/othertests/__init__.py b/tests/othertests/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
--- a/tests/othertests/__init__.py
+++ /dev/null
diff --git a/tests/othertests/ansi_sql.py b/tests/othertests/ansi_sql.py
deleted file mode 100644
index 3242172ec3..0000000000
--- a/tests/othertests/ansi_sql.py
+++ /dev/null
@@ -1,147 +0,0 @@
-"""
->>> from django.db.backends.ansi import sql
-
-# so we can test with a predicatable constraint setting
->>> real_cnst = Mod._default_manager.db.backend.supports_constraints
->>> Mod._default_manager.db.backend.supports_constraints = True
-
-# generate create sql
->>> builder = sql.SchemaBuilder()
->>> builder.get_create_table(Car)
-([BoundStatement('CREATE TABLE "ansi_sql_car" (...);')], {})
->>> builder.models_already_seen
-Set([<class 'othertests.ansi_sql.Car'>])
->>> builder.models_already_seen = set()
-
-# test that styles are used
->>> builder.get_create_table(Car, style=mockstyle())
-([BoundStatement('SQL_KEYWORD(CREATE TABLE) SQL_TABLE("ansi_sql_car") (...SQL_FIELD("id")...);')], {})
-
-# test pending relationships
->>> builder.models_already_seen = set()
->>> builder.get_create_table(Mod)
-([BoundStatement('CREATE TABLE "ansi_sql_mod" (..."car_id" integer NOT NULL,...);')], {<class 'othertests.ansi_sql.Car'>: [BoundStatement('ALTER TABLE "ansi_sql_mod" ADD CONSTRAINT ... FOREIGN KEY ("car_id") REFERENCES "ansi_sql_car" ("id");')]})
->>> builder.models_already_seen = set()
->>> builder.get_create_table(Car)
-([BoundStatement('CREATE TABLE "ansi_sql_car" (...);')], {})
->>> builder.get_create_table(Mod)
-([BoundStatement('CREATE TABLE "ansi_sql_mod" (..."car_id" integer NOT NULL REFERENCES "ansi_sql_car" ("id"),...);')], {})
-
-# test many-many
->>> builder.get_create_table(Collector)
-([BoundStatement('CREATE TABLE "ansi_sql_collector" (...);')], {})
->>> builder.get_create_many_to_many(Collector)
-{<class 'othertests.ansi_sql.Car'>: [BoundStatement('CREATE TABLE "ansi_sql_collector_cars" (...);')]}
-
-# test indexes
->>> builder.get_create_indexes(Car)
-[]
->>> builder.get_create_indexes(Mod)
-[BoundStatement('CREATE INDEX ... ON "ansi_sql_mod" ("car_id");'), BoundStatement('CREATE INDEX ... ON "ansi_sql_mod" ("part");')]
->>> builder.get_create_indexes(Collector)
-[]
-
-# test initial data
-# patch builder so that it looks for initial data where we want it to
->>> builder.get_initialdata_path = othertests_sql
->>> builder.get_initialdata(Car)
-[BoundStatement('insert into ansi_sql_car (...)...values (...);')]
-
-# test drop
->>> builder.get_drop_table(Mod)
-[BoundStatement('DROP TABLE "ansi_sql_mod";')]
->>> builder.get_drop_table(Mod, cascade=True)
-[BoundStatement('DROP TABLE "ansi_sql_mod";')]
->>> builder.get_drop_table(Car)
-[BoundStatement('DROP TABLE "ansi_sql_car";')]
-
-# drop with cascade
->>> builder.tables = ['ansi_sql_car', 'ansi_sql_mod', 'ansi_sql_collector']
->>> Mod._default_manager.db.backend.supports_constraints = False
->>> Mod._default_manager.db.backend.supports_constraints
-False
->>> Car._default_manager.db.backend.supports_constraints
-False
->>> builder.get_drop_table(Car, cascade=True)
-[BoundStatement('DROP TABLE "ansi_sql_car";')]
->>> Mod._default_manager.db.backend.supports_constraints = True
->>> Mod._default_manager.db.backend.supports_constraints
-True
->>> Car._default_manager.db.backend.supports_constraints
-True
->>> builder.get_drop_table(Car, cascade=True)
-[BoundStatement('DROP TABLE "ansi_sql_car";'), BoundStatement('ALTER TABLE "ansi_sql_mod" ...')]
->>> builder.get_drop_table(Collector)
-[BoundStatement('DROP TABLE "ansi_sql_collector";')]
->>> builder.get_drop_table(Collector, cascade=True)
-[BoundStatement('DROP TABLE "ansi_sql_collector";'), BoundStatement('DROP TABLE "ansi_sql_collector_cars";')]
->>> Mod._default_manager.db.backend.supports_constraints = real_cnst
-
-"""
-import os
-import sys
-from django.conf import settings
-from django.core.management import install
-from django.db import models
-from django.db.models import loading
-
-
-# For Python 2.3
-if not hasattr(__builtins__, 'set'):
- from sets import Set as set
-
-
-# test models
-class Car(models.Model):
- make = models.CharField(maxlength=32)
- model = models.CharField(maxlength=32)
- year = models.IntegerField()
- condition = models.CharField(maxlength=32)
-
- class Meta:
- app_label = 'ansi_sql'
-
-
-class Collector(models.Model):
- name = models.CharField(maxlength=32)
- cars = models.ManyToManyField(Car)
-
- class Meta:
- app_label = 'ansi_sql'
-
-
-class Mod(models.Model):
- car = models.ForeignKey(Car)
- part = models.CharField(maxlength=32, db_index=True)
- description = models.TextField()
-
- class Meta:
- app_label = 'ansi_sql'
-
-
-class mockstyle:
- """mock style that wraps text in STYLE(text), for testing"""
- def __getattr__(self, attr):
- if attr in ('ERROR', 'ERROR_OUTPUT', 'SQL_FIELD', 'SQL_COLTYPE',
- 'SQL_KEYWORD', 'SQL_TABLE'):
- return lambda text: "%s(%s)" % (attr, text)
-
-
-def othertests_sql(mod):
- """Look in othertests/sql for sql initialdata"""
- return os.path.normpath(os.path.join(os.path.dirname(__file__), 'sql'))
-
-
-# install my models and force myself into the registry of apps and models
-# (without this, references and such to/from the models installed here
-# won't be picked up in get_models(), since get_models() looks only at
-# models from apps in INSTALLED_APPS, and the model and app lookup rules
-# enforce a module structure that this test file can't follow)
-Car.objects.install()
-Collector.objects.install()
-Mod.objects.install()
-loading.get_apps()
-loading._app_list.append(sys.modules[__name__])
-
-# model lookup only works for pk.models, so fake up my module name
-__name__ = 'othertests.ansi_sql.models'
diff --git a/tests/othertests/cache.py b/tests/othertests/cache.py
deleted file mode 100644
index 81f2c20328..0000000000
--- a/tests/othertests/cache.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# Unit tests for cache framework
-# Uses whatever cache backend is set in the test settings file.
-
-from django.core.cache import cache
-import time
-
-# functions/classes for complex data type tests
-def f():
- return 42
-class C:
- def m(n):
- return 24
-
-# simple set/get
-cache.set("key", "value")
-assert cache.get("key") == "value"
-
-# get with non-existent keys
-assert cache.get("does not exist") is None
-assert cache.get("does not exist", "bang!") == "bang!"
-
-# get_many
-cache.set('a', 'a')
-cache.set('b', 'b')
-cache.set('c', 'c')
-cache.set('d', 'd')
-assert cache.get_many(['a', 'c', 'd']) == {'a' : 'a', 'c' : 'c', 'd' : 'd'}
-assert cache.get_many(['a', 'b', 'e']) == {'a' : 'a', 'b' : 'b'}
-
-# delete
-cache.set("key1", "spam")
-cache.set("key2", "eggs")
-assert cache.get("key1") == "spam"
-cache.delete("key1")
-assert cache.get("key1") is None
-assert cache.get("key2") == "eggs"
-
-# has_key
-cache.set("hello", "goodbye")
-assert cache.has_key("hello") == True
-assert cache.has_key("goodbye") == False
-
-# test data types
-stuff = {
- 'string' : 'this is a string',
- 'int' : 42,
- 'list' : [1, 2, 3, 4],
- 'tuple' : (1, 2, 3, 4),
- 'dict' : {'A': 1, 'B' : 2},
- 'function' : f,
- 'class' : C,
-}
-for (key, value) in stuff.items():
- cache.set(key, value)
- assert cache.get(key) == value
-
-# expiration
-cache.set('expire', 'very quickly', 1)
-time.sleep(2)
-assert cache.get("expire") == None
diff --git a/tests/othertests/dateformat.py b/tests/othertests/dateformat.py
deleted file mode 100644
index 0287587b4a..0000000000
--- a/tests/othertests/dateformat.py
+++ /dev/null
@@ -1,80 +0,0 @@
-r"""
->>> format(my_birthday, '')
-''
->>> format(my_birthday, 'a')
-'p.m.'
->>> format(my_birthday, 'A')
-'PM'
->>> format(my_birthday, 'd')
-'08'
->>> format(my_birthday, 'j')
-'8'
->>> format(my_birthday, 'l')
-'Sunday'
->>> format(my_birthday, 'L')
-'False'
->>> format(my_birthday, 'm')
-'07'
->>> format(my_birthday, 'M')
-'Jul'
->>> format(my_birthday, 'n')
-'7'
->>> format(my_birthday, 'N')
-'July'
->>> format(my_birthday, 'O')
-'+0100'
->>> format(my_birthday, 'P')
-'10 p.m.'
->>> format(my_birthday, 'r')
-'Sun, 8 Jul 1979 22:00:00 +0100'
->>> format(my_birthday, 's')
-'00'
->>> format(my_birthday, 'S')
-'th'
->>> format(my_birthday, 't')
-'31'
->>> format(my_birthday, 'T')
-'CET'
->>> format(my_birthday, 'U')
-'300531600'
->>> format(my_birthday, 'w')
-'0'
->>> format(my_birthday, 'W')
-'27'
->>> format(my_birthday, 'y')
-'79'
->>> format(my_birthday, 'Y')
-'1979'
->>> format(my_birthday, 'z')
-'189'
->>> format(my_birthday, 'Z')
-'3600'
-
->>> format(summertime, 'I')
-'1'
->>> format(summertime, 'O')
-'+0200'
->>> format(wintertime, 'I')
-'0'
->>> format(wintertime, 'O')
-'+0100'
-
->>> format(my_birthday, r'Y z \C\E\T')
-'1979 189 CET'
-
->>> format(my_birthday, r'jS o\f F')
-'8th of July'
-"""
-
-from django.utils import dateformat, translation
-import datetime, os, time
-
-format = dateformat.format
-os.environ['TZ'] = 'Europe/Copenhagen'
-translation.activate('en-us')
-
-time.tzset()
-
-my_birthday = datetime.datetime(1979, 7, 8, 22, 00)
-summertime = datetime.datetime(2005, 10, 30, 1, 00)
-wintertime = datetime.datetime(2005, 10, 30, 4, 00)
diff --git a/tests/othertests/db_typecasts.py b/tests/othertests/db_typecasts.py
deleted file mode 100644
index ffc9b34aec..0000000000
--- a/tests/othertests/db_typecasts.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# Unit tests for typecast functions in django.db.backends.util
-
-from django.db.backends import util as typecasts
-import datetime
-
-TEST_CASES = {
- 'typecast_date': (
- ('', None),
- (None, None),
- ('2005-08-11', datetime.date(2005, 8, 11)),
- ('1990-01-01', datetime.date(1990, 1, 1)),
- ),
- 'typecast_time': (
- ('', None),
- (None, None),
- ('0:00:00', datetime.time(0, 0)),
- ('0:30:00', datetime.time(0, 30)),
- ('8:50:00', datetime.time(8, 50)),
- ('08:50:00', datetime.time(8, 50)),
- ('12:00:00', datetime.time(12, 00)),
- ('12:30:00', datetime.time(12, 30)),
- ('13:00:00', datetime.time(13, 00)),
- ('23:59:00', datetime.time(23, 59)),
- ('00:00:12', datetime.time(0, 0, 12)),
- ('00:00:12.5', datetime.time(0, 0, 12, 500000)),
- ('7:22:13.312', datetime.time(7, 22, 13, 312000)),
- ),
- 'typecast_timestamp': (
- ('', None),
- (None, None),
- ('2005-08-11 0:00:00', datetime.datetime(2005, 8, 11)),
- ('2005-08-11 0:30:00', datetime.datetime(2005, 8, 11, 0, 30)),
- ('2005-08-11 8:50:30', datetime.datetime(2005, 8, 11, 8, 50, 30)),
- ('2005-08-11 8:50:30.123', datetime.datetime(2005, 8, 11, 8, 50, 30, 123000)),
- ('2005-08-11 8:50:30.9', datetime.datetime(2005, 8, 11, 8, 50, 30, 900000)),
- ('2005-08-11 8:50:30.312-05', datetime.datetime(2005, 8, 11, 8, 50, 30, 312000)),
- ('2005-08-11 8:50:30.312+02', datetime.datetime(2005, 8, 11, 8, 50, 30, 312000)),
- ),
- 'typecast_boolean': (
- (None, None),
- ('', False),
- ('t', True),
- ('f', False),
- ('x', False),
- ),
-}
-
-for k, v in TEST_CASES.items():
- for inpt, expected in v:
- got = getattr(typecasts, k)(inpt)
- assert got == expected, "In %s: %r doesn't match %r. Got %r instead." % (k, inpt, expected, got)
diff --git a/tests/othertests/defaultfilters.py b/tests/othertests/defaultfilters.py
deleted file mode 100644
index 9b1cfda833..0000000000
--- a/tests/othertests/defaultfilters.py
+++ /dev/null
@@ -1,361 +0,0 @@
-r"""
->>> floatformat(7.7)
-'7.7'
->>> floatformat(7.0)
-'7'
->>> floatformat(0.7)
-'0.7'
->>> floatformat(0.07)
-'0.1'
->>> floatformat(0.007)
-'0.0'
->>> floatformat(0.0)
-'0'
-
->>> addslashes('"double quotes" and \'single quotes\'')
-'\\"double quotes\\" and \\\'single quotes\\\''
-
->>> capfirst('hello world')
-'Hello world'
-
->>> fix_ampersands('Jack & Jill & Jeroboam')
-'Jack &amp; Jill &amp; Jeroboam'
-
->>> linenumbers('line 1\nline 2')
-'1. line 1\n2. line 2'
-
->>> linenumbers('\n'.join(['x'] * 10))
-'01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09. x\n10. x'
-
->>> lower('TEST')
-'test'
-
->>> lower(u'\xcb') # uppercase E umlaut
-u'\xeb'
-
->>> make_list('abc')
-['a', 'b', 'c']
-
->>> make_list(1234)
-['1', '2', '3', '4']
-
->>> slugify(' Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/')
-'jack-jill-like-numbers-123-and-4-and-silly-characters'
-
->>> stringformat(1, '03d')
-'001'
-
->>> stringformat(1, 'z')
-''
-
->>> title('a nice title, isn\'t it?')
-"A Nice Title, Isn't It?"
-
-
->>> truncatewords('A sentence with a few words in it', 1)
-'A ...'
-
->>> truncatewords('A sentence with a few words in it', 5)
-'A sentence with a few ...'
-
->>> truncatewords('A sentence with a few words in it', 100)
-'A sentence with a few words in it'
-
->>> truncatewords('A sentence with a few words in it', 'not a number')
-'A sentence with a few words in it'
-
-
->>> upper('Mixed case input')
-'MIXED CASE INPUT'
-
->>> upper(u'\xeb') # lowercase e umlaut
-u'\xcb'
-
-
->>> urlencode('jack & jill')
-'jack%20%26%20jill'
-
-
->>> urlizetrunc('http://short.com/', 20)
-'<a href="http://short.com/" rel="nofollow">http://short.com/</a>'
-
->>> urlizetrunc('http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=', 20)
-'<a href="http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=" rel="nofollow">http://www.google.co...</a>'
-
->>> wordcount('')
-0
-
->>> wordcount('oneword')
-1
-
->>> wordcount('lots of words')
-3
-
->>> wordwrap('this is a long paragraph of text that really needs to be wrapped I\'m afraid', 14)
-"this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid"
-
->>> ljust('test', 10)
-'test '
-
->>> ljust('test', 3)
-'test'
-
->>> rjust('test', 10)
-' test'
-
->>> rjust('test', 3)
-'test'
-
->>> center('test', 6)
-' test '
-
->>> cut('a string to be mangled', 'a')
-' string to be mngled'
-
->>> cut('a string to be mangled', 'ng')
-'a stri to be maled'
-
->>> cut('a string to be mangled', 'strings')
-'a string to be mangled'
-
->>> escape('<some html & special characters > here')
-'&lt;some html &amp; special characters &gt; here'
-
->>> linebreaks('line 1')
-'<p>line 1</p>'
-
->>> linebreaks('line 1\nline 2')
-'<p>line 1<br />line 2</p>'
-
->>> removetags('some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags', 'script img')
-'some <b>html</b> with alert("You smell") disallowed tags'
-
->>> striptags('some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags')
-'some html with alert("You smell") disallowed tags'
-
->>> dictsort([{'age': 23, 'name': 'Barbara-Ann'},
-... {'age': 63, 'name': 'Ra Ra Rasputin'},
-... {'name': 'Jonny B Goode', 'age': 18}], 'age')
-[{'age': 18, 'name': 'Jonny B Goode'}, {'age': 23, 'name': 'Barbara-Ann'}, {'age': 63, 'name': 'Ra Ra Rasputin'}]
-
->>> dictsortreversed([{'age': 23, 'name': 'Barbara-Ann'},
-... {'age': 63, 'name': 'Ra Ra Rasputin'},
-... {'name': 'Jonny B Goode', 'age': 18}], 'age')
-[{'age': 63, 'name': 'Ra Ra Rasputin'}, {'age': 23, 'name': 'Barbara-Ann'}, {'age': 18, 'name': 'Jonny B Goode'}]
-
->>> first([0,1,2])
-0
-
->>> first('')
-''
-
->>> first('test')
-'t'
-
->>> join([0,1,2], 'glue')
-'0glue1glue2'
-
->>> length('1234')
-4
-
->>> length([1,2,3,4])
-4
-
->>> length_is([], 0)
-True
-
->>> length_is([], 1)
-False
-
->>> length_is('a', 1)
-True
-
->>> length_is('a', 10)
-False
-
->>> slice_('abcdefg', '0')
-''
-
->>> slice_('abcdefg', '1')
-'a'
-
->>> slice_('abcdefg', '-1')
-'abcdef'
-
->>> slice_('abcdefg', '1:2')
-'b'
-
->>> slice_('abcdefg', '1:3')
-'bc'
-
->>> slice_('abcdefg', '0::2')
-'aceg'
-
->>> unordered_list(['item 1', []])
-'\t<li>item 1</li>'
-
->>> unordered_list(['item 1', [['item 1.1', []]]])
-'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>'
-
->>> unordered_list(['item 1', [['item 1.1', []], ['item 1.2', []]]])
-'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>'
-
->>> add('1', '2')
-3
-
->>> get_digit(123, 1)
-3
-
->>> get_digit(123, 2)
-2
-
->>> get_digit(123, 3)
-1
-
->>> get_digit(123, 4)
-0
-
->>> get_digit(123, 0)
-123
-
->>> get_digit('xyz', 0)
-'xyz'
-
-# real testing of date() is in dateformat.py
->>> date(datetime.datetime(2005, 12, 29), "d F Y")
-'29 December 2005'
->>> date(datetime.datetime(2005, 12, 29), r'jS o\f F')
-'29th of December'
-
-# real testing of time() is done in dateformat.py
->>> time(datetime.time(13), "h")
-'01'
-
->>> time(datetime.time(0), "h")
-'12'
-
-# real testing is done in timesince.py, where we can provide our own 'now'
->>> timesince(datetime.datetime.now() - datetime.timedelta(1))
-'1 day'
-
->>> default("val", "default")
-'val'
-
->>> default(None, "default")
-'default'
-
->>> default('', "default")
-'default'
-
->>> default_if_none("val", "default")
-'val'
-
->>> default_if_none(None, "default")
-'default'
-
->>> default_if_none('', "default")
-''
-
->>> divisibleby(4, 2)
-True
-
->>> divisibleby(4, 3)
-False
-
->>> yesno(True)
-'yes'
-
->>> yesno(False)
-'no'
-
->>> yesno(None)
-'maybe'
-
->>> yesno(True, 'certainly,get out of town,perhaps')
-'certainly'
-
->>> yesno(False, 'certainly,get out of town,perhaps')
-'get out of town'
-
->>> yesno(None, 'certainly,get out of town,perhaps')
-'perhaps'
-
->>> yesno(None, 'certainly,get out of town')
-'get out of town'
-
->>> filesizeformat(1023)
-'1023 bytes'
-
->>> filesizeformat(1024)
-'1.0 KB'
-
->>> filesizeformat(10*1024)
-'10.0 KB'
-
->>> filesizeformat(1024*1024-1)
-'1024.0 KB'
-
->>> filesizeformat(1024*1024)
-'1.0 MB'
-
->>> filesizeformat(1024*1024*50)
-'50.0 MB'
-
->>> filesizeformat(1024*1024*1024-1)
-'1024.0 MB'
-
->>> filesizeformat(1024*1024*1024)
-'1.0 GB'
-
->>> pluralize(1)
-''
-
->>> pluralize(0)
-'s'
-
->>> pluralize(2)
-'s'
-
->>> pluralize([1])
-''
-
->>> pluralize([])
-'s'
-
->>> pluralize([1,2,3])
-'s'
-
->>> pluralize(1,'es')
-''
-
->>> pluralize(0,'es')
-'es'
-
->>> pluralize(2,'es')
-'es'
-
->>> pluralize(1,'y,ies')
-'y'
-
->>> pluralize(0,'y,ies')
-'ies'
-
->>> pluralize(2,'y,ies')
-'ies'
-
->>> pluralize(0,'y,ies,error')
-''
-
->>> phone2numeric('0800 flowers')
-'0800 3569377'
-
-
-
-"""
-
-from django.template.defaultfilters import *
-import datetime
-
-if __name__ == '__main__':
- import doctest
- doctest.testmod()
diff --git a/tests/othertests/httpwrappers.py b/tests/othertests/httpwrappers.py
deleted file mode 100644
index 385c3048d9..0000000000
--- a/tests/othertests/httpwrappers.py
+++ /dev/null
@@ -1,358 +0,0 @@
-"""
-###################
-# Empty QueryDict #
-###################
-
->>> q = QueryDict('')
-
->>> q['foo']
-Traceback (most recent call last):
-...
-MultiValueDictKeyError: "Key 'foo' not found in <MultiValueDict: {}>"
-
->>> q['something'] = 'bar'
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.get('foo', 'default')
-'default'
-
->>> q.getlist('foo')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.appendlist('foo', ['bar'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.has_key('foo')
-False
-
->>> q.items()
-[]
-
->>> q.lists()
-[]
-
->>> q.keys()
-[]
-
->>> q.values()
-[]
-
->>> len(q)
-0
-
->>> q.update({'foo': 'bar'})
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.pop('foo')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.popitem()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.clear()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.setdefault('foo', 'bar')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.urlencode()
-''
-
-###################################
-# Mutable copy of empty QueryDict #
-###################################
-
->>> q = q.copy()
-
->>> q['foo']
-Traceback (most recent call last):
-...
-MultiValueDictKeyError: "Key 'foo' not found in <MultiValueDict: {}>"
-
->>> q['name'] = 'john'
-
->>> q['name']
-'john'
-
->>> q.get('foo', 'default')
-'default'
-
->>> q.get('name', 'default')
-'john'
-
->>> q.getlist('name')
-['john']
-
->>> q.getlist('foo')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-
->>> q.get('foo', 'default')
-'baz'
-
->>> q.getlist('foo')
-['bar', 'baz']
-
->>> q.appendlist('foo', 'another')
-
->>> q.getlist('foo')
-['bar', 'baz', 'another']
-
->>> q['foo']
-'another'
-
->>> q.has_key('foo')
-True
-
->>> q.items()
-[('foo', 'another'), ('name', 'john')]
-
->>> q.lists()
-[('foo', ['bar', 'baz', 'another']), ('name', ['john'])]
-
->>> q.keys()
-['foo', 'name']
-
->>> q.values()
-['another', 'john']
-
->>> len(q)
-2
-
->>> q.update({'foo': 'hello'})
-
-# Displays last value
->>> q['foo']
-'hello'
-
->>> q.get('foo', 'not available')
-'hello'
-
->>> q.getlist('foo')
-['bar', 'baz', 'another', 'hello']
-
->>> q.pop('foo')
-['bar', 'baz', 'another', 'hello']
-
->>> q.get('foo', 'not there')
-'not there'
-
->>> q.setdefault('foo', 'bar')
-'bar'
-
->>> q['foo']
-'bar'
-
->>> q.getlist('foo')
-['bar']
-
->>> q.urlencode()
-'foo=bar&name=john'
-
->>> q.clear()
-
->>> len(q)
-0
-
-#####################################
-# QueryDict with one key/value pair #
-#####################################
-
->>> q = QueryDict('foo=bar')
-
->>> q['foo']
-'bar'
-
->>> q['bar']
-Traceback (most recent call last):
-...
-MultiValueDictKeyError: "Key 'bar' not found in <MultiValueDict: {'foo': ['bar']}>"
-
->>> q['something'] = 'bar'
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.get('foo', 'default')
-'bar'
-
->>> q.get('bar', 'default')
-'default'
-
->>> q.getlist('foo')
-['bar']
-
->>> q.getlist('bar')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.appendlist('foo', ['bar'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.has_key('foo')
-True
-
->>> q.has_key('bar')
-False
-
->>> q.items()
-[('foo', 'bar')]
-
->>> q.lists()
-[('foo', ['bar'])]
-
->>> q.keys()
-['foo']
-
->>> q.values()
-['bar']
-
->>> len(q)
-1
-
->>> q.update({'foo': 'bar'})
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.pop('foo')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.popitem()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.clear()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.setdefault('foo', 'bar')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.urlencode()
-'foo=bar'
-
-#####################################################
-# QueryDict with two key/value pairs with same keys #
-#####################################################
-
->>> q = QueryDict('vote=yes&vote=no')
-
->>> q['vote']
-'no'
-
->>> q['something'] = 'bar'
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.get('vote', 'default')
-'no'
-
->>> q.get('foo', 'default')
-'default'
-
->>> q.getlist('vote')
-['yes', 'no']
-
->>> q.getlist('foo')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.appendlist('foo', ['bar'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.has_key('vote')
-True
-
->>> q.has_key('foo')
-False
-
->>> q.items()
-[('vote', 'no')]
-
->>> q.lists()
-[('vote', ['yes', 'no'])]
-
->>> q.keys()
-['vote']
-
->>> q.values()
-['no']
-
->>> len(q)
-1
-
->>> q.update({'foo': 'bar'})
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.pop('foo')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.popitem()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.clear()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.setdefault('foo', 'bar')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.urlencode()
-'vote=yes&vote=no'
-
-"""
-
-from django.http import QueryDict
-
-if __name__ == "__main__":
- import doctest
- doctest.testmod()
diff --git a/tests/othertests/manager_db.py b/tests/othertests/manager_db.py
deleted file mode 100644
index 936b6a21d5..0000000000
--- a/tests/othertests/manager_db.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from django.db import models
-
-def run_tests(verbosity=0):
- class Insect(models.Model):
- common_name = models.CharField(maxlength=64)
- latin_name = models.CharField(maxlength=128)
-
- class Meta:
- app_label = 'manager_db'
-
- m = Insect.objects
- db = Insect.objects.db
-
- assert db
- assert db.connection
- assert db.connection.cursor
- assert db.backend
- assert db.backend.quote_name
- assert db.get_creation_module
-
-if __name__ == '__main__':
- run_tests()
- print "ok"
diff --git a/tests/othertests/manager_schema_manipulation.py b/tests/othertests/manager_schema_manipulation.py
deleted file mode 100644
index 259b078d27..0000000000
--- a/tests/othertests/manager_schema_manipulation.py
+++ /dev/null
@@ -1,143 +0,0 @@
-"""
-# Django uses a model's default manager to perform schema
-# manipulations such as creating or dropping the model's table.
-
->>> from django.db import models
->>> from django.conf import settings
->>> import copy
-
-# save copy of settings so we can restore it later
->>> odb = copy.deepcopy(settings.OTHER_DATABASES)
->>> settings.OTHER_DATABASES['django_test_db_a']['MODELS'] = [ 'msm.PA', 'msm.P', 'msm.PC' ]
->>> settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = [ 'msm.QA', 'msm.QB', 'msm.QC', 'msm.QD' ]
-
-# default connection
->>> class DA(models.Model):
-... name = models.CharField(maxlength=20)
-...
-... def __str__(self):
-... return self.name
-
-# connection django_test_db_a
->>> class PA(models.Model):
-... name = models.CharField(maxlength=20)
-... # This creates a cycle in the dependency graph
-... c = models.ForeignKey('PC', null=True)
-...
-... def __str__(self):
-... return self.name
-...
-... class Meta:
-... app_label = 'msm'
-
->>> class PB(models.Model):
-... name = models.CharField(maxlength=20)
-... a = models.ForeignKey(PA)
-...
-... def __str__(self):
-... return self.name
-...
-... class Meta:
-... app_label = 'msm'
-
->>> class PC(models.Model):
-... name = models.CharField(maxlength=20)
-... b = models.ForeignKey(PB)
-...
-... def __str__(self):
-... return self.name
-...
-... class Meta:
-... app_label = 'msm'
-
-# connection django_test_db_b
->>> class QA(models.Model):
-... name = models.CharField(maxlength=20)
-...
-... def __str__(self):
-... return self.name
-...
-... class Meta:
-... app_label = 'msm'
-
->>> class QB(models.Model):
-... name = models.CharField(maxlength=20)
-... a = models.ForeignKey(QA)
-...
-... def __str__(self):
-... return self.name
-...
-... class Meta:
-... app_label = 'msm'
-
-# many-many
->>> class QC(models.Model):
-... name = models.CharField(maxlength=20)
-...
-... def __str__(self):
-... return self.name
-...
-... class Meta:
-... app_label = 'msm'
-
->>> class QD(models.Model):
-... name = models.CharField(maxlength=20)
-... qcs = models.ManyToManyField(QC)
-...
-... def __str__(self):
-... return self.name
-...
-... class Meta:
-... app_label = 'msm'
-
-# Using the manager, models can be installed individually, whether they
-# use the default connection or a named connection.
-
->>> DA.objects.install()
-{}
->>> QA.objects.install()
-{}
->>> QB.objects.install()
-{}
->>> DA.objects.all()
-[]
->>> list(QA.objects.all())
-[]
->>> list(QB.objects.all())
-[]
->>> QA(name="something").save()
->>> QA.objects.all()
-[<QA: something>]
-
-# The `install()` method returns a tuple, the first element of which is a
-# list of statements that were executed, and the second, pending
-# statements that could not be executed because (for instance) they are
-# meant to establish foreign key relationships to tables that don't
-# exist. These are bound to the model's connection and should
-# be executed after all models in the app have been installed. The pending
-# statments are returned as a dict keyed by the model which must be installed
-# before the pending statements can be installed.
-
-# NOTE: pretend db supports constraints for this test
->>> real_cnst = PA._default_manager.db.backend.supports_constraints
->>> PA._default_manager.db.backend.supports_constraints = True
->>> result = PA.objects.install()
->>> result
-{<class 'othertests.manager_schema_manipulation.PC'>: [BoundStatement('ALTER TABLE "msm_pa" ADD CONSTRAINT "c_id_referencing_msm_pc_id" FOREIGN KEY ("c_id") REFERENCES "msm_pc" ("id");')]}
-
-# NOTE: restore real constraint flag
->>> PA._default_manager.db.backend.supports_constraints = real_cnst
-
-# Models with many-many relationships may also have pending statement
-# lists. Like other pending statements, these should be executed after
-# all models in the app have been installed. If the related table's model
-# has already been created, then there will be no pending list.
-
->>> QC.objects.install()
-{}
->>> QD.objects.install()
-{}
-
-# Finally, restore the original settings
->>> settings.OTHER_DATABASES = odb
-"""
diff --git a/tests/othertests/markup.py b/tests/othertests/markup.py
deleted file mode 100644
index 2b00a8c7a5..0000000000
--- a/tests/othertests/markup.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# Quick tests for the markup templatetags (django.contrib.markup)
-
-from django.template import Template, Context, add_to_builtins
-import re
-
-add_to_builtins('django.contrib.markup.templatetags.markup')
-
-# find out if markup modules are installed and tailor the test appropriately
-try:
- import textile
-except ImportError:
- textile = None
-
-try:
- import markdown
-except ImportError:
- markdown = None
-
-try:
- import docutils
-except ImportError:
- docutils = None
-
-# simple examples 'cause this isn't actually testing the markup, just
-# that the filters work as advertised
-
-### test textile
-
-textile_content = """Paragraph 1
-
-Paragraph 2 with "quotes" and @code@"""
-
-t = Template("{{ textile_content|textile }}")
-rendered = t.render(Context(locals())).strip()
-if textile:
- assert rendered == """<p>Paragraph 1</p>
-
-<p>Paragraph 2 with &#8220;quotes&#8221; and <code>code</code></p>"""
-else:
- assert rendered == textile_content
-
-### test markdown
-
-markdown_content = """Paragraph 1
-
-## An h2"""
-
-t = Template("{{ markdown_content|markdown }}")
-rendered = t.render(Context(locals())).strip()
-if markdown:
- pattern = re.compile("""<p>Paragraph 1\s*</p>\s*<h2>\s*An h2</h2>""")
- assert pattern.match(rendered)
-else:
- assert rendered == markdown_content
-
-### test rest
-
-rest_content = """Paragraph 1
-
-Paragraph 2 with a link_
-
-.. _link: http://www.example.com/"""
-
-t = Template("{{ rest_content|restructuredtext }}")
-rendered = t.render(Context(locals())).strip()
-if docutils:
- assert rendered =="""<p>Paragraph 1</p>
-<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>"""
-else:
- assert rendered == rest_content
diff --git a/tests/othertests/request_isolation.py b/tests/othertests/request_isolation.py
deleted file mode 100644
index 6c29306c4e..0000000000
--- a/tests/othertests/request_isolation.py
+++ /dev/null
@@ -1,140 +0,0 @@
-# tests that db settings can change between requests
-import copy
-import os
-from django.conf import settings, UserSettingsHolder
-from django.core.handlers.wsgi import WSGIHandler
-from django.db import models, model_connection_name, _default, connection
-from django.http import HttpResponse
-
-# state holder
-S = {}
-
-# models
-class MX(models.Model):
- val = models.CharField(maxlength=10)
- class Meta:
- app_label = 'ri'
-
-
-class MY(models.Model):
- val = models.CharField(maxlength=10)
- class Meta:
- app_label = 'ri'
-
-
-# tests
-def test_one(path, request):
- """Start out with settings as originally configured"""
- assert model_connection_name(MX) == 'django_test_db_a'
- assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']
- assert model_connection_name(MY) == 'django_test_db_b'
- assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'], \
- "%s != %s" % \
- (MY._default_manager.db.connection.settings.DATABASE_NAME,
- settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'])
-
-
-def test_two(path, request):
- """Between the first and second requests, settings change to assign
- model MY to a different connection
- """
- assert model_connection_name(MX) == 'django_test_db_a'
- assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']
- assert model_connection_name(MY) == _default
- assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.DATABASE_NAME, "%s != %s" % \
- (MY._default_manager.db.connection.settings.DATABASE_NAME,
- settings.DATABASE_NAME)
-
-
-def test_three(path, request):
- """Between the 2nd and 3rd requests, the settings at the names in
- OTHER_DATABASES have changed.
- """
- assert model_connection_name(MX) == 'django_test_db_b'
- assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME']
- assert model_connection_name(MY) == 'django_test_db_a'
- assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'], \
- "%s != %s" % \
- (MY._default_manager.db.connection.settings.DATABASE_NAME,
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'])
-
-
-# helpers
-class MockHandler(WSGIHandler):
-
- def __init__(self, test):
- self.test = test
- super(MockHandler, self).__init__()
-
- def get_response(self, path, request):
- # debug("mock handler answering %s, %s", path, request)
- return HttpResponse(self.test(path, request))
-
-
-def pr(*arg):
- if S['verbosity'] >= 1:
- msg, arg = arg[0], arg[1:]
- print msg % arg
-
-
-def debug(*arg):
- if S['verbosity'] >= 2:
- msg, arg = arg[0], arg[1:]
- print msg % arg
-
-
-def setup():
- debug("setup")
- S['settings'] = settings._target
- settings._target = UserSettingsHolder(copy.deepcopy(settings._target))
- settings.OTHER_DATABASES['django_test_db_a']['MODELS'] = ['ri.MX']
- settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = ['ri.MY']
-
-
-def teardown():
- debug("teardown")
- settings._target = S['settings']
-
-
-def start_response(code, headers):
- debug("start response: %s %s", code, headers)
- pass
-
-
-def main():
- debug("running tests")
-
- env = os.environ.copy()
- env['PATH_INFO'] = '/'
- env['REQUEST_METHOD'] = 'GET'
-
- MockHandler(test_one)(env, start_response)
-
- settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = []
- MockHandler(test_two)(env, start_response)
-
- settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = ['ri.MY']
- settings.OTHER_DATABASES['django_test_db_b'], \
- settings.OTHER_DATABASES['django_test_db_a'] = \
- settings.OTHER_DATABASES['django_test_db_a'], \
- settings.OTHER_DATABASES['django_test_db_b']
- MockHandler(test_three)(env, start_response)
-
-
-def run_tests(verbosity=0):
- S['verbosity'] = verbosity
- setup()
- try:
- main()
- finally:
- teardown()
-
-
-if __name__ == '__main__':
- run_tests(2)
diff --git a/tests/othertests/sql/car.sql b/tests/othertests/sql/car.sql
deleted file mode 100644
index 8a377aabfb..0000000000
--- a/tests/othertests/sql/car.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-insert into ansi_sql_car (make, model, year, condition)
- values ("Chevy", "Impala", 1966, "mint"); \ No newline at end of file
diff --git a/tests/othertests/templates.py b/tests/othertests/templates.py
deleted file mode 100644
index 9975f3b05c..0000000000
--- a/tests/othertests/templates.py
+++ /dev/null
@@ -1,634 +0,0 @@
-from django.conf import settings
-
-if __name__ == '__main__':
- # When running this file in isolation, we need to set up the configuration
- # before importing 'template'.
- settings.configure()
-
-from django import template
-from django.template import loader
-from django.utils.translation import activate, deactivate, install
-from django.utils.tzinfo import LocalTimezone
-from datetime import datetime, timedelta
-import traceback
-
-#################################
-# Custom template tag for tests #
-#################################
-
-register = template.Library()
-
-class EchoNode(template.Node):
- def __init__(self, contents):
- self.contents = contents
-
- def render(self, context):
- return " ".join(self.contents)
-
-def do_echo(parser, token):
- return EchoNode(token.contents.split()[1:])
-
-register.tag("echo", do_echo)
-
-template.libraries['django.templatetags.testtags'] = register
-
-#####################################
-# Helper objects for template tests #
-#####################################
-
-class SomeException(Exception):
- silent_variable_failure = True
-
-class SomeOtherException(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
-
-class OtherClass:
- def method(self):
- return "OtherClass.method"
-
-# NOW and NOW_tz are used by timesince tag tests.
-NOW = datetime.now()
-NOW_tz = datetime.now(LocalTimezone(datetime.now()))
-
-# SYNTAX --
-# 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class)
-TEMPLATE_TESTS = {
-
- ### BASIC SYNTAX ##########################################################
-
- # Plain text should go through the template parser untouched
- 'basic-syntax01': ("something cool", {}, "something cool"),
-
- # Variables should be replaced with their value in the current context
- 'basic-syntax02': ("{{ headline }}", {'headline':'Success'}, "Success"),
-
- # More than one replacement variable is allowed in a template
- 'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"),
-
- # Fail silently when a variable is not found in the current context
- 'basic-syntax04': ("as{{ missing }}df", {}, "asINVALIDdf"),
-
- # A variable may not contain more than one word
- 'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for empty variable tags
- 'basic-syntax07': ("{{ }}", {}, template.TemplateSyntaxError),
- 'basic-syntax08': ("{{ }}", {}, template.TemplateSyntaxError),
-
- # Attribute syntax allows a template to call an object's attribute
- 'basic-syntax09': ("{{ var.method }}", {"var": SomeClass()}, "SomeClass.method"),
-
- # Multiple levels of attribute access are allowed
- 'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"),
-
- # Fail silently when a variable's attribute isn't found
- 'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, "INVALID"),
-
- # Raise TemplateSyntaxError when trying to access a variable beginning with an underscore
- 'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError when trying to access a variable containing an illegal character
- 'basic-syntax13': ("{{ va>r }}", {}, template.TemplateSyntaxError),
- 'basic-syntax14': ("{{ (var.r) }}", {}, template.TemplateSyntaxError),
- 'basic-syntax15': ("{{ sp%am }}", {}, template.TemplateSyntaxError),
- 'basic-syntax16': ("{{ eggs! }}", {}, template.TemplateSyntaxError),
- 'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError),
-
- # Attribute syntax allows a template to call a dictionary key's value
- 'basic-syntax18': ("{{ foo.bar }}", {"foo" : {"bar" : "baz"}}, "baz"),
-
- # Fail silently when a variable's dictionary key isn't found
- 'basic-syntax19': ("{{ foo.spam }}", {"foo" : {"bar" : "baz"}}, "INVALID"),
-
- # Fail silently when accessing a non-simple method
- 'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, "INVALID"),
-
- # Basic filter usage
- 'basic-syntax21': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
-
- # Chained filters
- 'basic-syntax22': ("{{ var|upper|lower }}", {"var": "Django is the greatest!"}, "django is the greatest!"),
-
- # Raise TemplateSyntaxError for space between a variable and filter pipe
- 'basic-syntax23': ("{{ var |upper }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for space after a filter pipe
- 'basic-syntax24': ("{{ var| upper }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for a nonexistent filter
- 'basic-syntax25': ("{{ var|does_not_exist }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError when trying to access a filter containing an illegal character
- 'basic-syntax26': ("{{ var|fil(ter) }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for invalid block tags
- 'basic-syntax27': ("{% nothing_to_see_here %}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for empty block tags
- 'basic-syntax28': ("{% %}", {}, template.TemplateSyntaxError),
-
- # Chained filters, with an argument to the first one
- 'basic-syntax29': ('{{ var|removetags:"b i"|upper|lower }}', {"var": "<b><i>Yes</i></b>"}, "yes"),
-
- # Escaped string as argument
- 'basic-syntax30': (r'{{ var|default_if_none:" endquote\" hah" }}', {"var": None}, ' endquote" hah'),
-
- # Variable as argument
- 'basic-syntax31': (r'{{ var|default_if_none:var2 }}', {"var": None, "var2": "happy"}, 'happy'),
-
- # Default argument testing
- 'basic-syntax32': (r'{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}', {"var": True}, 'yup yes'),
-
- # Fail silently for methods that raise an exception with a "silent_variable_failure" attribute
- 'basic-syntax33': (r'1{{ var.method3 }}2', {"var": SomeClass()}, "1INVALID2"),
-
- # In methods that raise an exception without a "silent_variable_attribute" set to True,
- # the exception propogates
- 'basic-syntax34': (r'1{{ var.method4 }}2', {"var": SomeClass()}, SomeOtherException),
-
- # Escaped backslash in argument
- 'basic-syntax35': (r'{{ var|default_if_none:"foo\bar" }}', {"var": None}, r'foo\bar'),
-
- # Escaped backslash using known escape char
- 'basic-syntax35': (r'{{ var|default_if_none:"foo\now" }}', {"var": None}, r'foo\now'),
-
- ### COMMENT TAG ###########################################################
- 'comment-tag01': ("{% comment %}this is hidden{% endcomment %}hello", {}, "hello"),
- 'comment-tag02': ("{% comment %}this is hidden{% endcomment %}hello{% comment %}foo{% endcomment %}", {}, "hello"),
-
- # Comment tag can contain invalid stuff.
- 'comment-tag03': ("foo{% comment %} {% if %} {% endcomment %}", {}, "foo"),
- 'comment-tag04': ("foo{% comment %} {% endblock %} {% endcomment %}", {}, "foo"),
- 'comment-tag05': ("foo{% comment %} {% somerandomtag %} {% endcomment %}", {}, "foo"),
-
- ### CYCLE TAG #############################################################
- 'cycle01': ('{% cycle a %}', {}, template.TemplateSyntaxError),
- 'cycle02': ('{% cycle a,b,c as abc %}{% cycle abc %}', {}, 'ab'),
- 'cycle03': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}', {}, 'abc'),
- 'cycle04': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}', {}, 'abca'),
- 'cycle05': ('{% cycle %}', {}, template.TemplateSyntaxError),
- 'cycle06': ('{% cycle a %}', {}, template.TemplateSyntaxError),
- 'cycle07': ('{% cycle a,b,c as foo %}{% cycle bar %}', {}, template.TemplateSyntaxError),
-
- ### EXCEPTIONS ############################################################
-
- # Raise exception for invalid template name
- 'exception01': ("{% extends 'nonexistent' %}", {}, template.TemplateSyntaxError),
-
- # Raise exception for invalid template name (in variable)
- 'exception02': ("{% extends nonexistent %}", {}, template.TemplateSyntaxError),
-
- # Raise exception for extra {% extends %} tags
- 'exception03': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% extends 'inheritance16' %}", {}, template.TemplateSyntaxError),
-
- # Raise exception for custom tags used in child with {% load %} tag in parent, not in child
- 'exception04': ("{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}", {}, template.TemplateSyntaxError),
-
- ### FILTER TAG ############################################################
- 'filter01': ('{% filter upper %}{% endfilter %}', {}, ''),
- 'filter02': ('{% filter upper %}django{% endfilter %}', {}, 'DJANGO'),
- 'filter03': ('{% filter upper|lower %}django{% endfilter %}', {}, 'django'),
-
- ### FIRSTOF TAG ###########################################################
- 'firstof01': ('{% firstof a b c %}', {'a':0,'b':0,'c':0}, ''),
- 'firstof02': ('{% firstof a b c %}', {'a':1,'b':0,'c':0}, '1'),
- 'firstof03': ('{% firstof a b c %}', {'a':0,'b':2,'c':0}, '2'),
- 'firstof04': ('{% firstof a b c %}', {'a':0,'b':0,'c':3}, '3'),
- 'firstof05': ('{% firstof a b c %}', {'a':1,'b':2,'c':3}, '1'),
- 'firstof06': ('{% firstof %}', {}, template.TemplateSyntaxError),
-
- ### FOR TAG ###############################################################
- 'for-tag01': ("{% for val in values %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "123"),
- 'for-tag02': ("{% for val in values reversed %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "321"),
- 'for-tag-vars01': ("{% for val in values %}{{ forloop.counter }}{% endfor %}", {"values": [6, 6, 6]}, "123"),
- 'for-tag-vars02': ("{% for val in values %}{{ forloop.counter0 }}{% endfor %}", {"values": [6, 6, 6]}, "012"),
- 'for-tag-vars03': ("{% for val in values %}{{ forloop.revcounter }}{% endfor %}", {"values": [6, 6, 6]}, "321"),
- 'for-tag-vars04': ("{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}", {"values": [6, 6, 6]}, "210"),
-
- ### IF TAG ################################################################
- 'if-tag01': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": True}, "yes"),
- 'if-tag02': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": False}, "no"),
- 'if-tag03': ("{% if foo %}yes{% else %}no{% endif %}", {}, "no"),
-
- # AND
- 'if-tag-and01': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-and02': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-and03': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-and04': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
- 'if-tag-and05': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
- 'if-tag-and06': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
- 'if-tag-and07': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True}, 'no'),
- 'if-tag-and08': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': True}, 'no'),
-
- # OR
- 'if-tag-or01': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-or02': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-or03': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-or04': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
- 'if-tag-or05': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
- 'if-tag-or06': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
- 'if-tag-or07': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True}, 'yes'),
- 'if-tag-or08': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': True}, 'yes'),
-
- # TODO: multiple ORs
-
- # NOT
- 'if-tag-not01': ("{% if not foo %}no{% else %}yes{% endif %}", {'foo': True}, 'yes'),
- 'if-tag-not02': ("{% if not %}yes{% else %}no{% endif %}", {'foo': True}, 'no'),
- 'if-tag-not03': ("{% if not %}yes{% else %}no{% endif %}", {'not': True}, 'yes'),
- 'if-tag-not04': ("{% if not not %}no{% else %}yes{% endif %}", {'not': True}, 'yes'),
- 'if-tag-not05': ("{% if not not %}no{% else %}yes{% endif %}", {}, 'no'),
-
- 'if-tag-not06': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {}, 'no'),
- 'if-tag-not07': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not08': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-not09': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-not10': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
-
- 'if-tag-not11': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {}, 'no'),
- 'if-tag-not12': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not13': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-not14': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-not15': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
-
- 'if-tag-not16': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not17': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-not18': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-not19': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-not20': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- 'if-tag-not21': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not22': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-not23': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-not24': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-not25': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- 'if-tag-not26': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not27': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not28': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-not29': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-not30': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- 'if-tag-not31': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not32': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not33': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-not34': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-not35': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- # AND and OR raises a TemplateSyntaxError
- 'if-tag-error01': ("{% if foo or bar and baz %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, template.TemplateSyntaxError),
- 'if-tag-error02': ("{% if foo and %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
- 'if-tag-error03': ("{% if foo or %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
- 'if-tag-error04': ("{% if not foo and %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
- 'if-tag-error05': ("{% if not foo or %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
-
- ### IFCHANGED TAG #########################################################
- 'ifchanged01': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,2,3) }, '123'),
- 'ifchanged02': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,1,3) }, '13'),
- 'ifchanged03': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,1,1) }, '1'),
-
- ### IFEQUAL TAG ###########################################################
- 'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""),
- 'ifequal02': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 1}, "yes"),
- 'ifequal03': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 2}, "no"),
- 'ifequal04': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 1}, "yes"),
- 'ifequal05': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "test"}, "yes"),
- 'ifequal06': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "no"}, "no"),
- 'ifequal07': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "test"}, "yes"),
- 'ifequal08': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "no"}, "no"),
- 'ifequal09': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {}, "no"),
- 'ifequal10': ('{% ifequal a b %}yes{% else %}no{% endifequal %}', {}, "yes"),
-
- # SMART SPLITTING
- 'ifequal-split01': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {}, "no"),
- 'ifequal-split02': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'foo'}, "no"),
- 'ifequal-split03': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'test man'}, "yes"),
- 'ifequal-split04': ("{% ifequal a 'test man' %}yes{% else %}no{% endifequal %}", {'a': 'test man'}, "yes"),
- 'ifequal-split05': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': ''}, "no"),
- 'ifequal-split06': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i "love" you'}, "yes"),
- 'ifequal-split07': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i love you'}, "no"),
- 'ifequal-split08': (r"{% ifequal a 'I\'m happy' %}yes{% else %}no{% endifequal %}", {'a': "I'm happy"}, "yes"),
- 'ifequal-split09': (r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r"slash\man"}, "yes"),
- 'ifequal-split10': (r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r"slashman"}, "no"),
-
- ### IFNOTEQUAL TAG ########################################################
- 'ifnotequal01': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
- 'ifnotequal02': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 1}, ""),
- 'ifnotequal03': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
- 'ifnotequal04': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 1}, "no"),
-
- ### INCLUDE TAG ###########################################################
- 'include01': ('{% include "basic-syntax01" %}', {}, "something cool"),
- 'include02': ('{% include "basic-syntax02" %}', {'headline': 'Included'}, "Included"),
- 'include03': ('{% include template_name %}', {'template_name': 'basic-syntax02', 'headline': 'Included'}, "Included"),
- 'include04': ('a{% include "nonexistent" %}b', {}, "ab"),
-
- ### INHERITANCE ###########################################################
-
- # Standard template with no inheritance
- 'inheritance01': ("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}", {}, '1_3_'),
-
- # Standard two-level inheritance
- 'inheritance02': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
-
- # Three-level with no redefinitions on third level
- 'inheritance03': ("{% extends 'inheritance02' %}", {}, '1234'),
-
- # Two-level with no redefinitions on second level
- 'inheritance04': ("{% extends 'inheritance01' %}", {}, '1_3_'),
-
- # Two-level with double quotes instead of single quotes
- 'inheritance05': ('{% extends "inheritance02" %}', {}, '1234'),
-
- # Three-level with variable parent-template name
- 'inheritance06': ("{% extends foo %}", {'foo': 'inheritance02'}, '1234'),
-
- # Two-level with one block defined, one block not defined
- 'inheritance07': ("{% extends 'inheritance01' %}{% block second %}5{% endblock %}", {}, '1_35'),
-
- # Three-level with one block defined on this level, two blocks defined next level
- 'inheritance08': ("{% extends 'inheritance02' %}{% block second %}5{% endblock %}", {}, '1235'),
-
- # Three-level with second and third levels blank
- 'inheritance09': ("{% extends 'inheritance04' %}", {}, '1_3_'),
-
- # Three-level with space NOT in a block -- should be ignored
- 'inheritance10': ("{% extends 'inheritance04' %} ", {}, '1_3_'),
-
- # Three-level with both blocks defined on this level, but none on second level
- 'inheritance11': ("{% extends 'inheritance04' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
-
- # Three-level with this level providing one and second level providing the other
- 'inheritance12': ("{% extends 'inheritance07' %}{% block first %}2{% endblock %}", {}, '1235'),
-
- # Three-level with this level overriding second level
- 'inheritance13': ("{% extends 'inheritance02' %}{% block first %}a{% endblock %}{% block second %}b{% endblock %}", {}, '1a3b'),
-
- # A block defined only in a child template shouldn't be displayed
- 'inheritance14': ("{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}", {}, '1_3_'),
-
- # A block within another block
- 'inheritance15': ("{% extends 'inheritance01' %}{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}", {}, '12inner3_'),
-
- # A block within another block (level 2)
- 'inheritance16': ("{% extends 'inheritance15' %}{% block inner %}out{% endblock %}", {}, '12out3_'),
-
- # {% load %} tag (parent -- setup for exception04)
- 'inheritance17': ("{% load testtags %}{% block first %}1234{% endblock %}", {}, '1234'),
-
- # {% load %} tag (standard usage, without inheritance)
- 'inheritance18': ("{% load testtags %}{% echo this that theother %}5678", {}, 'this that theother5678'),
-
- # {% load %} tag (within a child template)
- 'inheritance19': ("{% extends 'inheritance01' %}{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", {}, '140056783_'),
-
- # Two-level inheritance with {{ block.super }}
- 'inheritance20': ("{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
-
- # Three-level inheritance with {{ block.super }} from parent
- 'inheritance21': ("{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '12a34'),
-
- # Three-level inheritance with {{ block.super }} from grandparent
- 'inheritance22': ("{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
-
- # Three-level inheritance with {{ block.super }} from parent and grandparent
- 'inheritance23': ("{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}", {}, '1_ab3_'),
-
- # Inheritance from local context without use of template loader
- 'inheritance24': ("{% extends context_template %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {'context_template': template.Template("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}")}, '1234'),
-
- # Inheritance from local context with variable parent template
- 'inheritance25': ("{% extends context_template.1 %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {'context_template': [template.Template("Wrong"), template.Template("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}")]}, '1234'),
-
- ### I18N ##################################################################
-
- # {% spaceless %} tag
- 'spaceless01': ("{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}", {}, "<b> <i> text </i> </b>"),
- 'spaceless02': ("{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}", {}, "<b> <i> text </i> </b>"),
- 'spaceless03': ("{% spaceless %}<b><i>text</i></b>{% endspaceless %}", {}, "<b><i>text</i></b>"),
-
- # simple translation of a string delimited by '
- 'i18n01': ("{% load i18n %}{% trans 'xxxyyyxxx' %}", {}, "xxxyyyxxx"),
-
- # simple translation of a string delimited by "
- 'i18n02': ('{% load i18n %}{% trans "xxxyyyxxx" %}', {}, "xxxyyyxxx"),
-
- # simple translation of a variable
- 'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': 'xxxyyyxxx'}, "xxxyyyxxx"),
-
- # simple translation of a variable and filter
- 'i18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'XXXYYYXXX'}, "xxxyyyxxx"),
-
- # simple translation of a string with interpolation
- 'i18n05': ('{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}', {'anton': 'yyy'}, "xxxyyyxxx"),
-
- # simple translation of a string to german
- 'i18n06': ('{% load i18n %}{% trans "Page not found" %}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
-
- # translation of singular form
- 'i18n07': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 1}, "singular"),
-
- # translation of plural form
- 'i18n08': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 2}, "plural"),
-
- # simple non-translation (only marking) of a string to german
- 'i18n09': ('{% load i18n %}{% trans "Page not found" noop %}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
-
- # translation of a variable with a translated filter
- 'i18n10': ('{{ bool|yesno:_("ja,nein") }}', {'bool': True}, 'ja'),
-
- # translation of a variable with a non-translated filter
- 'i18n11': ('{{ bool|yesno:"ja,nein" }}', {'bool': True}, 'ja'),
-
- # usage of the get_available_languages tag
- 'i18n12': ('{% load i18n %}{% get_available_languages as langs %}{% for lang in langs %}{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}', {}, 'de'),
-
- # translation of a constant string
- 'i18n13': ('{{ _("Page not found") }}', {'LANGUAGE_CODE': 'de'}, 'Seite nicht gefunden'),
-
- ### MULTILINE #############################################################
-
- 'multiline01': ("""
- Hello,
- boys.
- How
- are
- you
- gentlemen.
- """,
- {},
- """
- Hello,
- boys.
- How
- are
- you
- gentlemen.
- """),
-
- ### REGROUP TAG ###########################################################
- 'regroup01': ('{% regroup data by bar as grouped %}' + \
- '{% for group in grouped %}' + \
- '{{ group.grouper }}:' + \
- '{% for item in group.list %}' + \
- '{{ item.foo }}' + \
- '{% endfor %},' + \
- '{% endfor %}',
- {'data': [ {'foo':'c', 'bar':1},
- {'foo':'d', 'bar':1},
- {'foo':'a', 'bar':2},
- {'foo':'b', 'bar':2},
- {'foo':'x', 'bar':3} ]},
- '1:cd,2:ab,3:x,'),
-
- # Test for silent failure when target variable isn't found
- 'regroup02': ('{% regroup data by bar as grouped %}' + \
- '{% for group in grouped %}' + \
- '{{ group.grouper }}:' + \
- '{% for item in group.list %}' + \
- '{{ item.foo }}' + \
- '{% endfor %},' + \
- '{% endfor %}',
- {}, 'INVALID:INVALIDINVALIDINVALIDINVALIDINVALIDINVALIDINVALID,'),
-
- ### TEMPLATETAG TAG #######################################################
- 'templatetag01': ('{% templatetag openblock %}', {}, '{%'),
- 'templatetag02': ('{% templatetag closeblock %}', {}, '%}'),
- 'templatetag03': ('{% templatetag openvariable %}', {}, '{{'),
- 'templatetag04': ('{% templatetag closevariable %}', {}, '}}'),
- 'templatetag05': ('{% templatetag %}', {}, template.TemplateSyntaxError),
- 'templatetag06': ('{% templatetag foo %}', {}, template.TemplateSyntaxError),
- 'templatetag07': ('{% templatetag openbrace %}', {}, '{'),
- 'templatetag08': ('{% templatetag closebrace %}', {}, '}'),
- 'templatetag09': ('{% templatetag openbrace %}{% templatetag openbrace %}', {}, '{{'),
- 'templatetag10': ('{% templatetag closebrace %}{% templatetag closebrace %}', {}, '}}'),
-
- ### WIDTHRATIO TAG ########################################################
- 'widthratio01': ('{% widthratio a b 0 %}', {'a':50,'b':100}, '0'),
- 'widthratio02': ('{% widthratio a b 100 %}', {'a':0,'b':0}, ''),
- 'widthratio03': ('{% widthratio a b 100 %}', {'a':0,'b':100}, '0'),
- 'widthratio04': ('{% widthratio a b 100 %}', {'a':50,'b':100}, '50'),
- 'widthratio05': ('{% widthratio a b 100 %}', {'a':100,'b':100}, '100'),
-
- # 62.5 should round to 63
- 'widthratio06': ('{% widthratio a b 100 %}', {'a':50,'b':80}, '63'),
-
- # 71.4 should round to 71
- 'widthratio07': ('{% widthratio a b 100 %}', {'a':50,'b':70}, '71'),
-
- # Raise exception if we don't have 3 args, last one an integer
- 'widthratio08': ('{% widthratio %}', {}, template.TemplateSyntaxError),
- 'widthratio09': ('{% widthratio a b %}', {'a':50,'b':100}, template.TemplateSyntaxError),
- 'widthratio10': ('{% widthratio a b 100.0 %}', {'a':50,'b':100}, template.TemplateSyntaxError),
-
- ### NOW TAG ########################################################
- # Simple case
- 'now01' : ('{% now "j n Y"%}', {}, str(datetime.now().day) + ' ' + str(datetime.now().month) + ' ' + str(datetime.now().year)),
-
- # Check parsing of escaped and special characters
- 'now02' : ('{% now "j "n" Y"%}', {}, template.TemplateSyntaxError),
-# 'now03' : ('{% now "j \"n\" Y"%}', {}, str(datetime.now().day) + '"' + str(datetime.now().month) + '"' + str(datetime.now().year)),
-# 'now04' : ('{% now "j \nn\n Y"%}', {}, str(datetime.now().day) + '\n' + str(datetime.now().month) + '\n' + str(datetime.now().year))
-
- ### TIMESINCE TAG ##################################################
- # Default compare with datetime.now()
- 'timesince01' : ('{{ a|timesince }}', {'a':datetime.now() + timedelta(minutes=-1, seconds = -10)}, '1 minute'),
- 'timesince02' : ('{{ a|timesince }}', {'a':(datetime.now() - timedelta(days=1, minutes = 1))}, '1 day'),
- 'timesince03' : ('{{ a|timesince }}', {'a':(datetime.now() -
- timedelta(hours=1, minutes=25, seconds = 10))}, '1 hour, 25 minutes'),
-
- # Compare to a given parameter
- 'timesince04' : ('{{ a|timesince:b }}', {'a':NOW + timedelta(days=2), 'b':NOW + timedelta(days=1)}, '1 day'),
- 'timesince05' : ('{{ a|timesince:b }}', {'a':NOW + timedelta(days=2, minutes=1), 'b':NOW + timedelta(days=2)}, '1 minute'),
-
- # Check that timezone is respected
- 'timesince06' : ('{{ a|timesince:b }}', {'a':NOW_tz + timedelta(hours=8), 'b':NOW_tz}, '8 hours'),
-
- ### TIMEUNTIL TAG ##################################################
- # Default compare with datetime.now()
- 'timeuntil01' : ('{{ a|timeuntil }}', {'a':datetime.now() + timedelta(minutes=2, seconds = 10)}, '2 minutes'),
- 'timeuntil02' : ('{{ a|timeuntil }}', {'a':(datetime.now() + timedelta(days=1, seconds = 10))}, '1 day'),
- 'timeuntil03' : ('{{ a|timeuntil }}', {'a':(datetime.now() + timedelta(hours=8, minutes=10, seconds = 10))}, '8 hours, 10 minutes'),
-
- # Compare to a given parameter
- 'timeuntil04' : ('{{ a|timeuntil:b }}', {'a':NOW - timedelta(days=1), 'b':NOW - timedelta(days=2)}, '1 day'),
- 'timeuntil05' : ('{{ a|timeuntil:b }}', {'a':NOW - timedelta(days=2), 'b':NOW - timedelta(days=2, minutes=1)}, '1 minute'),
-}
-
-def test_template_loader(template_name, template_dirs=None):
- "A custom template loader that loads the unit-test templates."
- try:
- return (TEMPLATE_TESTS[template_name][0] , "test:%s" % template_name)
- except KeyError:
- raise template.TemplateDoesNotExist, template_name
-
-def run_tests(verbosity=0, standalone=False):
- # Register our custom template loader.
- old_template_loaders = loader.template_source_loaders
- loader.template_source_loaders = [test_template_loader]
-
- failed_tests = []
- tests = TEMPLATE_TESTS.items()
- tests.sort()
-
- # Turn TEMPLATE_DEBUG off, because tests assume that.
- old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, False
- # Set TEMPLATE_STRING_IF_INVALID to a known string
- old_invalid, settings.TEMPLATE_STRING_IF_INVALID = settings.TEMPLATE_STRING_IF_INVALID, 'INVALID'
-
- for name, vals in tests:
- install()
- if 'LANGUAGE_CODE' in vals[1]:
- activate(vals[1]['LANGUAGE_CODE'])
- else:
- activate('en-us')
- try:
- output = loader.get_template(name).render(template.Context(vals[1]))
- except Exception, e:
- if e.__class__ == vals[2]:
- if verbosity:
- print "Template test: %s -- Passed" % name
- else:
- if verbosity:
- traceback.print_exc()
- print "Template test: %s -- FAILED. Got %s, exception: %s" % (name, e.__class__, e)
- failed_tests.append(name)
- continue
- if 'LANGUAGE_CODE' in vals[1]:
- deactivate()
- if output == vals[2]:
- if verbosity:
- print "Template test: %s -- Passed" % name
- else:
- if verbosity:
- print "Template test: %s -- FAILED. Expected %r, got %r" % (name, vals[2], output)
- failed_tests.append(name)
- loader.template_source_loaders = old_template_loaders
- deactivate()
- settings.TEMPLATE_DEBUG = old_td
- settings.TEMPLATE_STRING_IF_INVALID = old_invalid
-
- if failed_tests and not standalone:
- msg = "Template tests %s failed." % failed_tests
- if not verbosity:
- msg += " Re-run tests with -v1 to see actual failures"
- raise Exception, msg
-
-if __name__ == "__main__":
- run_tests(1, True)
diff --git a/tests/othertests/thread_isolation.py b/tests/othertests/thread_isolation.py
deleted file mode 100644
index f1d1f9129b..0000000000
--- a/tests/othertests/thread_isolation.py
+++ /dev/null
@@ -1,300 +0,0 @@
-# tests that db settings can be different in different threads
-#
-#
-# What's going on here:
-#
-# Simulating multiple web requests in a threaded environment, one in
-# which settings are different for each request. So we replace
-# django.conf.settings with a thread local, with different
-# configurations in each thread, and then fire off three
-# simultaneous requests (using a condition to sync them up), and
-# test that each thread sees its own settings and the models in each
-# thread attempt to connect to the correct database as per their
-# settings.
-#
-
-
-import copy
-import os
-import sys
-import threading
-from thread import get_ident
-
-from django.conf import settings, UserSettingsHolder
-from django.core.handlers.wsgi import WSGIHandler
-from django.db import models, model_connection_name, _default, connection, \
- connections
-from django.http import HttpResponse
-
-try:
- # Only exists in Python 2.4+
- from threading import local
-except ImportError:
- # Import copy of _thread_local.py from Python 2.4
- from django.utils._threading_local import local
-
-# state holder
-S = {}
-
-# models
-class MQ(models.Model):
- val = models.CharField(maxlength=10)
- class Meta:
- app_label = 'ti'
-
-
-class MX(models.Model):
- val = models.CharField(maxlength=10)
- class Meta:
- app_label = 'ti'
-
-
-class MY(models.Model):
- val = models.CharField(maxlength=10)
- class Meta:
- app_label = 'ti'
-
-# eventused to synchronize threads so we can be sure they are running
-# together
-ev = threading.Event()
-
-
-def test_one(path, request):
- """Start out with settings as originally configured"""
- from django.conf import settings
- debug("test_one: %s", settings.OTHER_DATABASES)
-
- assert model_connection_name(MQ) == _default
- assert model_connection_name(MX) == 'django_test_db_a', \
- "%s != 'django_test_db_a'" % model_connection_name(MX)
- assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']
- assert model_connection_name(MY) == 'django_test_db_b'
- assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'], \
- "%s != %s" % \
- (MY._default_manager.db.connection.settings.DATABASE_NAME,
- settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'])
- assert MQ._default_manager.db.connection is \
- connections[_default].connection
- assert MQ._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.DATABASE_NAME
- assert connection.settings.DATABASE_NAME == settings.DATABASE_NAME
-
-
-def test_two(path, request):
- """Between the first and second requests, settings change to assign
- model MY to a different connection
- """
- # from django.conf import settings
- debug("test_two: %s", settings.OTHER_DATABASES)
-
- try:
- assert model_connection_name(MQ) == _default
- assert model_connection_name(MX) == 'django_test_db_a'
- assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']
- assert model_connection_name(MY) == _default
- assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.DATABASE_NAME, "%s != %s" % \
- (MY._default_manager.db.connection.settings.DATABASE_NAME,
- settings.DATABASE_NAME)
- assert MQ._default_manager.db.connection is \
- connections[_default].connection
- assert MQ._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.DATABASE_NAME
- assert connection.settings.DATABASE_NAME == settings.DATABASE_NAME
- except:
- S.setdefault('errors',[]).append(sys.exc_info())
-
-
-def test_three(path, request):
- """Between the 2nd and 3rd requests, the settings at the names in
- OTHER_DATABASES have changed.
- """
- # from django.conf import settings
- debug("3 %s: %s", get_ident(), settings.OTHER_DATABASES)
- debug("3 %s: default: %s", get_ident(), settings.DATABASE_NAME)
- debug("3 %s: conn: %s", get_ident(), connection.settings.DATABASE_NAME)
-
- try:
- assert model_connection_name(MQ) == _default
- assert model_connection_name(MX) == 'django_test_db_b'
- assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'],\
- "%s != %s" % \
- (MX._default_manager.db.connection.settings.DATABASE_NAME,
- settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'])
- assert model_connection_name(MY) == 'django_test_db_a'
- assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'],\
- "%s != %s" % \
- (MY._default_manager.db.connection.settings.DATABASE_NAME,
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'])
- assert MQ._default_manager.db.connection is \
- connections[_default].connection
- assert connection.settings.DATABASE_NAME == \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'],\
- "%s != %s" % \
- (connection.settings.DATABASE_NAME,
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'])
- except:
- S.setdefault('errors',[]).append(sys.exc_info())
-
-
-
-# helpers
-def thread_two(func, *arg):
- def start():
- # from django.conf import settings
- settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = []
-
- debug("t2 ODB: %s", settings.OTHER_DATABASES)
- debug("t2 waiting")
- ev.wait(2.0)
- func(*arg)
- debug("t2 complete")
- t2 = threading.Thread(target=start)
- t2.start()
- return t2
-
-
-def thread_three(func, *arg):
- def start():
- # from django.conf import settings
- settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = ['ti.MY']
- settings.OTHER_DATABASES['django_test_db_b'], \
- settings.OTHER_DATABASES['django_test_db_a'] = \
- settings.OTHER_DATABASES['django_test_db_a'], \
- settings.OTHER_DATABASES['django_test_db_b']
-
- settings.DATABASE_NAME = \
- settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']
-
- debug("t3 ODB: %s", settings.OTHER_DATABASES)
- debug("3 %s: start: default: %s", get_ident(), settings.DATABASE_NAME)
- debug("3 %s: start: conn: %s", get_ident(),
- connection.settings.DATABASE_NAME)
-
- debug("t3 waiting")
- ev.wait(2.0)
- func(*arg)
- debug("t3 complete")
- t3 = threading.Thread(target=start)
- t3.start()
- return t3
-
-# helpers
-class LocalSettings:
- """Settings holder that allows thread-local overrides of defaults.
- """
- def __init__(self, defaults):
- self._defaults = defaults
- self._local = local()
-
- def __getattr__(self, attr):
- if attr in ('_defaults', '_local'):
- return self.__dict__[attr]
- _local = self.__dict__['_local']
- _defaults = self.__dict__['_defaults']
- debug("LS get %s (%s)", attr, hasattr(_local, attr))
- if not hasattr(_local, attr):
- # Make sure everything we return is the local version; this
- # avoids sets to deep datastructures overwriting the defaults
- setattr(_local, attr, copy.deepcopy(getattr(_defaults, attr)))
- return getattr(_local, attr)
-
- def __setattr__(self, attr, val):
- if attr in ('_defaults', '_local'):
- self.__dict__[attr] = val
- else:
- debug("LS set local %s = %s", attr, val)
- setattr(self.__dict__['_local'], attr, val)
-
-class MockHandler(WSGIHandler):
-
- def __init__(self, test):
- self.test = test
- super(MockHandler, self).__init__()
-
- def get_response(self, path, request):
- # debug("mock handler answering %s, %s", path, request)
- return HttpResponse(self.test(path, request))
-
-
-def pr(*arg):
- if S['verbosity'] >= 1:
- msg, arg = arg[0], arg[1:]
- print msg % arg
-
-
-def debug(*arg):
- if S['verbosity'] >= 2:
- msg, arg = arg[0], arg[1:]
- print msg % arg
-
-
-def setup():
- debug("setup")
- S['settings'] = settings._target
- settings._target = UserSettingsHolder(copy.deepcopy(settings._target))
- settings.OTHER_DATABASES['django_test_db_a']['MODELS'] = ['ti.MX']
- settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = ['ti.MY']
-
- # normal settings holders aren't thread-safe, so we need to substitute
- # one that is (and so allows per-thread settings)
- holder = settings._target
- settings._target = LocalSettings(holder)
-
-
-def teardown():
- debug("teardown")
- settings._target = S['settings']
-
-
-def start_response(code, headers):
- debug("start response: %s %s", code, headers)
- pass
-
-
-def main():
- debug("running tests")
-
- env = os.environ.copy()
- env['PATH_INFO'] = '/'
- env['REQUEST_METHOD'] = 'GET'
-
- t2 = thread_two(MockHandler(test_two), env, start_response)
- t3 = thread_three(MockHandler(test_three), env, start_response)
-
- try:
- ev.set()
- MockHandler(test_one)(env, start_response)
- finally:
- t2.join()
- t3.join()
- err = S.get('errors', [])
- if err:
- import traceback
- for e in err:
- traceback.print_exception(*e)
- raise AssertionError("%s thread%s failed" %
- (len(err), len(err) > 1 and 's' or ''))
-
-def run_tests(verbosity=0):
- S['verbosity'] = verbosity
-
- setup()
- try:
- main()
- finally:
- teardown()
-
-
-if __name__ == '__main__':
- from django.conf import settings
-
- settings.DATABASE_NAME = ':memory:'
- print "MAIN start! ", connection.settings.DATABASE_NAME
- connection.cursor()
- run_tests(2)
diff --git a/tests/othertests/urlpatterns_reverse.py b/tests/othertests/urlpatterns_reverse.py
deleted file mode 100644
index 236944d49f..0000000000
--- a/tests/othertests/urlpatterns_reverse.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"Unit tests for reverse URL lookup"
-
-from django.core.urlresolvers import reverse_helper, NoReverseMatch
-import re
-
-test_data = (
- ('^places/(\d+)/$', 'places/3/', [3], {}),
- ('^places/(\d+)/$', 'places/3/', ['3'], {}),
- ('^places/(\d+)/$', NoReverseMatch, ['a'], {}),
- ('^places/(\d+)/$', NoReverseMatch, [], {}),
- ('^places/(?P<id>\d+)/$', 'places/3/', [], {'id': 3}),
- ('^people/(?P<name>\w+)/$', 'people/adrian/', ['adrian'], {}),
- ('^people/(?P<name>\w+)/$', 'people/adrian/', [], {'name': 'adrian'}),
- ('^people/(?P<name>\w+)/$', NoReverseMatch, ['name with spaces'], {}),
- ('^people/(?P<name>\w+)/$', NoReverseMatch, [], {'name': 'name with spaces'}),
- ('^people/(?P<name>\w+)/$', NoReverseMatch, [], {}),
- ('^hardcoded/$', 'hardcoded/', [], {}),
- ('^hardcoded/$', 'hardcoded/', ['any arg'], {}),
- ('^hardcoded/$', 'hardcoded/', [], {'kwarg': 'foo'}),
- ('^people/(?P<state>\w\w)/(?P<name>\w+)/$', 'people/il/adrian/', [], {'state': 'il', 'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(?P<name>\d)/$', NoReverseMatch, [], {'state': 'il', 'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(?P<name>\w+)/$', NoReverseMatch, [], {'state': 'il'}),
- ('^people/(?P<state>\w\w)/(?P<name>\w+)/$', NoReverseMatch, [], {'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(\w+)/$', NoReverseMatch, ['il'], {'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(\w+)/$', 'people/il/adrian/', ['adrian'], {'state': 'il'}),
-)
-
-def run_tests(verbosity=0):
- for regex, expected, args, kwargs in test_data:
- passed = True
- try:
- got = reverse_helper(re.compile(regex), *args, **kwargs)
- except NoReverseMatch, e:
- if expected != NoReverseMatch:
- passed, got = False, str(e)
- else:
- if got != expected:
- passed, got = False, got
- if passed and verbosity:
- print "Passed: %s" % regex
- elif not passed:
- print "REVERSE LOOKUP FAILED: %s" % regex
- print " Got: %s" % got
- print " Expected: %r" % expected
-
-if __name__ == "__main__":
- run_tests(1)