Corrected philo tests and removed all use of penfield models in those tests - resolve...
[philo.git] / philo / tests.py
1 import sys
2 import traceback
3
4 from django import template
5 from django.conf import settings
6 from django.db import connection, models
7 from django.template import loader
8 from django.template.loaders import cached
9 from django.test import TestCase
10 from django.test.utils import setup_test_template_loader, restore_template_loaders
11
12 from philo.exceptions import AncestorDoesNotExist
13 from philo.models import Node, Page, Template, Tag
14
15
16 class TemplateTestCase(TestCase):
17         fixtures = ['test_fixtures.json']
18         
19         def test_templates(self):
20                 "Tests to make sure that embed behaves with complex includes and extends"
21                 template_tests = self.get_template_tests()
22                 
23                 # Register our custom template loader. Shamelessly cribbed from django/tests/regressiontests/templates/tests.py:384.
24                 cache_loader = setup_test_template_loader(
25                         dict([(name, t[0]) for name, t in template_tests.iteritems()]),
26                         use_cached_loader=True,
27                 )
28                 
29                 failures = []
30                 tests = template_tests.items()
31                 tests.sort()
32                 
33                 # Turn TEMPLATE_DEBUG off, because tests assume that.
34                 old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, False
35                 
36                 # Set TEMPLATE_STRING_IF_INVALID to a known string.
37                 old_invalid = settings.TEMPLATE_STRING_IF_INVALID
38                 expected_invalid_str = 'INVALID'
39                 
40                 # Run tests
41                 for name, vals in tests:
42                         xx, context, result = vals
43                         try:
44                                 test_template = loader.get_template(name)
45                                 output = test_template.render(template.Context(context))
46                         except Exception:
47                                 exc_type, exc_value, exc_tb = sys.exc_info()
48                                 if exc_type != result:
49                                         tb = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_tb))
50                                         failures.append("Template test %s -- FAILED. Got %s, exception: %s\n%s" % (name, exc_type, exc_value, tb))
51                                 continue
52                         if output != result:
53                                 failures.append("Template test %s -- FAILED. Expected %r, got %r" % (name, result, output))
54                 
55                 # Cleanup
56                 settings.TEMPLATE_DEBUG = old_td
57                 settings.TEMPLATE_STRING_IF_INVALID = old_invalid
58                 restore_template_loaders()
59                 
60                 self.assertEqual(failures, [], "Tests failed:\n%s\n%s" % ('-'*70, ("\n%s\n" % ('-'*70)).join(failures)))
61         
62         
63         def get_template_tests(self):
64                 # SYNTAX --
65                 # 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class)
66                 embedded = Tag.objects.get(pk=1)
67                 return {
68                         # EMBED INCLUSION HANDLING
69                         
70                         'embed01': ('{{ embedded.name|safe }}', {'embedded': embedded}, embedded.name),
71                         'embed02': ('{{ embedded.name|safe }}{{ var1 }}{{ var2 }}', {'embedded': embedded}, embedded.name),
72                         'embed03': ('{{ embedded.name|safe }} is a lie!', {'embedded': embedded}, '%s is a lie!' % embedded.name),
73                         
74                         # Simple template structure with embed
75                         'simple01': ('{% embed philo.tag with "embed01" %}{% embed philo.tag 1 %}Simple{% block one %}{% endblock %}', {'embedded': embedded}, '%sSimple' % embedded.name),
76                         'simple02': ('{% extends "simple01" %}', {}, '%sSimple' % embedded.name),
77                         'simple03': ('{% embed philo.tag with "embed000" %}', {}, settings.TEMPLATE_STRING_IF_INVALID),
78                         'simple04': ('{% embed philo.tag 1 %}', {}, settings.TEMPLATE_STRING_IF_INVALID),
79                         'simple05': ('{% embed philo.tag with "embed01" %}{% embed embedded %}', {'embedded': embedded}, embedded.name),
80                         
81                         # Kwargs
82                         'kwargs01': ('{% embed philo.tag with "embed02" %}{% embed philo.tag 1 var1="hi" var2=lo %}', {'lo': 'lo'}, '%shilo' % embedded.name),
83                         
84                         # Filters/variables
85                         'filters01': ('{% embed philo.tag with "embed02" %}{% embed philo.tag 1 var1=hi|first var2=lo|slice:"3" %}', {'hi': ["These", "words"], 'lo': 'lower'}, '%sTheselow' % embedded.name),
86                         'filters02': ('{% embed philo.tag with "embed01" %}{% embed philo.tag entry %}', {'entry': 1}, embedded.name),
87                         
88                         # Blocky structure
89                         'block01': ('{% block one %}Hello{% endblock %}', {}, 'Hello'),
90                         'block02': ('{% extends "simple01" %}{% block one %}{% embed philo.tag 1 %}{% endblock %}', {}, "%sSimple%s" % (embedded.name, embedded.name)),
91                         'block03': ('{% extends "simple01" %}{% embed philo.tag with "embed03" %}{% block one %}{% embed philo.tag 1 %}{% endblock %}', {}, "%sSimple%s is a lie!" % (embedded.name, embedded.name)),
92                         
93                         # Blocks and includes
94                         'block-include01': ('{% extends "simple01" %}{% embed philo.tag with "embed03" %}{% block one %}{% include "simple01" %}{% embed philo.tag 1 %}{% endblock %}', {}, "%sSimple%sSimple%s is a lie!" % (embedded.name, embedded.name, embedded.name)),
95                         'block-include02': ('{% extends "simple01" %}{% block one %}{% include "simple04" %}{% embed philo.tag with "embed03" %}{% include "simple04" %}{% embed philo.tag 1 %}{% endblock %}', {}, "%sSimple%s%s is a lie!%s is a lie!" % (embedded.name, embedded.name, embedded.name, embedded.name)),
96                         
97                         # Tests for more complex situations...
98                         'complex01': ('{% block one %}{% endblock %}complex{% block two %}{% endblock %}', {}, 'complex'),
99                         'complex02': ('{% extends "complex01" %}', {}, 'complex'),
100                         'complex03': ('{% extends "complex02" %}{% embed philo.tag with "embed01" %}', {}, 'complex'),
101                         'complex04': ('{% extends "complex03" %}{% block one %}{% embed philo.tag 1 %}{% endblock %}', {}, '%scomplex' % embedded.name),
102                         'complex05': ('{% extends "complex03" %}{% block one %}{% include "simple04" %}{% endblock %}', {}, '%scomplex' % embedded.name),
103                 }
104
105
106 class NodeURLTestCase(TestCase):
107         """Tests the features of the node_url template tag."""
108         urls = 'philo.urls'
109         fixtures = ['test_fixtures.json']
110         
111         def setUp(self):
112                 self.templates = [
113                                 ("{% node_url %}", "/root/second"),
114                                 ("{% node_url for node2 %}", "/root/second2"),
115                                 ("{% node_url as hello %}<p>{{ hello|slice:'1:' }}</p>", "<p>root/second</p>"),
116                                 ("{% node_url for nodes|first %}", "/root"),
117                 ]
118                 
119                 nodes = Node.objects.all()
120                 
121                 self.context = template.Context({
122                         'node': nodes.get(slug='second'),
123                         'node2': nodes.get(slug='second2'),
124                         'nodes': nodes,
125                 })
126         
127         def test_nodeurl(self):
128                 for string, result in self.templates:
129                         self.assertEqual(template.Template(string).render(self.context), result)
130
131 class TreePathTestCase(TestCase):
132         urls = 'philo.urls'
133         fixtures = ['test_fixtures.json']
134         
135         def assertQueryLimit(self, max, expected_result, *args, **kwargs):
136                 # As a rough measure of efficiency, limit the number of queries required for a given operation.
137                 settings.DEBUG = True
138                 call = kwargs.pop('callable', Node.objects.get_with_path)
139                 try:
140                         queries = len(connection.queries)
141                         if isinstance(expected_result, type) and issubclass(expected_result, Exception):
142                                 self.assertRaises(expected_result, call, *args, **kwargs)
143                         else:
144                                 self.assertEqual(call(*args, **kwargs), expected_result)
145                         queries = len(connection.queries) - queries
146                         if queries > max:
147                                 raise AssertionError('"%d" unexpectedly not less than or equal to "%s"' % (queries, max))
148                 finally:
149                         settings.DEBUG = False
150         
151         def test_get_with_path(self):
152                 root = Node.objects.get(slug='root')
153                 third = Node.objects.get(slug='third')
154                 second2 = Node.objects.get(slug='second2')
155                 fifth = Node.objects.get(slug='fifth')
156                 e = Node.DoesNotExist
157                 
158                 # Empty segments
159                 self.assertQueryLimit(0, root, '', root=root)
160                 self.assertQueryLimit(0, e, '')
161                 self.assertQueryLimit(0, (root, None), '', root=root, absolute_result=False)
162                 
163                 # Absolute result
164                 self.assertQueryLimit(1, third, 'root/second/third')
165                 self.assertQueryLimit(1, third, 'second/third', root=root)
166                 self.assertQueryLimit(1, third, 'root//////second/third///')
167                 
168                 self.assertQueryLimit(1, e, 'root/secont/third')
169                 self.assertQueryLimit(1, e, 'second/third')
170                 
171                 # Non-absolute result (binary search)
172                 self.assertQueryLimit(2, (second2, 'sub/path/tail'), 'root/second2/sub/path/tail', absolute_result=False)
173                 self.assertQueryLimit(3, (second2, 'sub'), 'root/second2/sub/', absolute_result=False)
174                 self.assertQueryLimit(2, e, 'invalid/path/1/2/3/4/5/6/7/8/9/1/2/3/4/5/6/7/8/9/0', absolute_result=False)
175                 self.assertQueryLimit(1, (root, None), 'root', absolute_result=False)
176                 self.assertQueryLimit(2, (second2, None), 'root/second2', absolute_result=False)
177                 self.assertQueryLimit(3, (third, None), 'root/second/third', absolute_result=False)
178                 
179                 # with root != None
180                 self.assertQueryLimit(1, (second2, None), 'second2', root=root, absolute_result=False)
181                 self.assertQueryLimit(2, (third, None), 'second/third', root=root, absolute_result=False)
182                 
183                 # Eliminate trailing slash
184                 self.assertQueryLimit(2, (second2, 'sub/path/tail'), 'root/second2/sub/path/tail/', absolute_result=False)
185                 
186                 # Speed increase for leaf nodes - should this be tested?
187                 self.assertQueryLimit(1, (fifth, 'sub/path/tail/len/five'), 'root/second/third/fourth/fifth/sub/path/tail/len/five', absolute_result=False)
188         
189         def test_get_path(self):
190                 root = Node.objects.get(slug='root')
191                 root2 = Node.objects.get(slug='root')
192                 third = Node.objects.get(slug='third')
193                 second2 = Node.objects.get(slug='second2')
194                 fifth = Node.objects.get(slug='fifth')
195                 e = AncestorDoesNotExist
196                 
197                 self.assertQueryLimit(0, 'root', callable=root.get_path)
198                 self.assertQueryLimit(0, '', root2, callable=root.get_path)
199                 self.assertQueryLimit(1, 'root/second/third', callable=third.get_path)
200                 self.assertQueryLimit(1, 'second/third', root, callable=third.get_path)
201                 self.assertQueryLimit(1, e, third, callable=second2.get_path)
202                 self.assertQueryLimit(1, '? - ?', root, ' - ', 'title', callable=third.get_path)