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