Use the same rounding for width as for height in platform sections -- covers ticket...
[pyTivo.git] / Cheetah / Tests / Template.py
blobb97cf5d146b258da2a2114426a1edc9199a858e2
1 #!/usr/bin/env python
2 # $Id: Template.py,v 1.16 2006/02/03 21:05:50 tavis_rudd Exp $
3 """Tests of the Template class API
5 Meta-Data
6 ================================================================================
7 Author: Tavis Rudd <tavis@damnsimple.com>,
8 Version: $Revision: 1.16 $
9 Start Date: 2001/10/01
10 Last Revision Date: $Date: 2006/02/03 21:05:50 $
11 """
12 __author__ = "Tavis Rudd <tavis@damnsimple.com>"
13 __revision__ = "$Revision: 1.16 $"[11:-2]
16 ##################################################
17 ## DEPENDENCIES ##
19 import sys
20 import types
21 import os
22 import os.path
23 import tempfile
24 import shutil
25 import unittest_local_copy as unittest
26 from Cheetah.Template import Template
28 ##################################################
29 ## CONSTANTS & GLOBALS ##
31 majorVer, minorVer = sys.version_info[0], sys.version_info[1]
32 versionTuple = (majorVer, minorVer)
34 try:
35 True,False
36 except NameError:
37 True, False = (1==1),(1==0)
39 ##################################################
40 ## TEST DATA FOR USE IN THE TEMPLATES ##
42 ##################################################
43 ## TEST BASE CLASSES
45 class TemplateTest(unittest.TestCase):
46 pass
48 ##################################################
49 ## TEST CASE CLASSES
51 class ClassMethods_compile(TemplateTest):
52 """I am using the same Cheetah source for each test to root out clashes
53 caused by the compile caching in Template.compile().
54 """
56 def test_basicUsage(self):
57 klass = Template.compile(source='$foo')
58 t = klass(namespaces={'foo':1234})
59 assert str(t)=='1234'
61 def test_baseclassArg(self):
62 klass = Template.compile(source='$foo', baseclass=dict)
63 t = klass({'foo':1234})
64 assert str(t)=='1234'
66 klass2 = Template.compile(source='$foo', baseclass=klass)
67 t = klass2({'foo':1234})
68 assert str(t)=='1234'
70 klass3 = Template.compile(source='#implements dummy\n$bar', baseclass=klass2)
71 t = klass3({'foo':1234})
72 assert str(t)=='1234'
74 klass4 = Template.compile(source='$foo', baseclass='dict')
75 t = klass4({'foo':1234})
76 assert str(t)=='1234'
78 def test_moduleFileCaching(self):
79 if versionTuple < (2,3):
80 return
81 tmpDir = tempfile.mkdtemp()
82 try:
83 #print tmpDir
84 assert os.path.exists(tmpDir)
85 klass = Template.compile(source='$foo',
86 cacheModuleFilesForTracebacks=True,
87 cacheDirForModuleFiles=tmpDir)
88 mod = sys.modules[klass.__module__]
89 #print mod.__file__
90 assert os.path.exists(mod.__file__)
91 assert os.path.dirname(mod.__file__)==tmpDir
92 finally:
93 shutil.rmtree(tmpDir, True)
95 def test_classNameArg(self):
96 klass = Template.compile(source='$foo', className='foo123')
97 assert klass.__name__=='foo123'
98 t = klass(namespaces={'foo':1234})
99 assert str(t)=='1234'
101 def test_moduleNameArg(self):
102 klass = Template.compile(source='$foo', moduleName='foo99')
103 mod = sys.modules['foo99']
104 assert klass.__name__=='foo99'
105 t = klass(namespaces={'foo':1234})
106 assert str(t)=='1234'
109 klass = Template.compile(source='$foo',
110 moduleName='foo1',
111 className='foo2')
112 mod = sys.modules['foo1']
113 assert klass.__name__=='foo2'
114 t = klass(namespaces={'foo':1234})
115 assert str(t)=='1234'
118 def test_mainMethodNameArg(self):
119 klass = Template.compile(source='$foo',
120 className='foo123',
121 mainMethodName='testMeth')
122 assert klass.__name__=='foo123'
123 t = klass(namespaces={'foo':1234})
124 #print t.generatedClassCode()
125 assert str(t)=='1234'
126 assert t.testMeth()=='1234'
128 klass = Template.compile(source='$foo',
129 moduleName='fooXXX',
130 className='foo123',
131 mainMethodName='testMeth',
132 baseclass=dict)
133 assert klass.__name__=='foo123'
134 t = klass({'foo':1234})
135 #print t.generatedClassCode()
136 assert str(t)=='1234'
137 assert t.testMeth()=='1234'
141 def test_moduleGlobalsArg(self):
142 klass = Template.compile(source='$foo',
143 moduleGlobals={'foo':1234})
144 t = klass()
145 assert str(t)=='1234'
147 klass2 = Template.compile(source='$foo', baseclass='Test1',
148 moduleGlobals={'Test1':dict})
149 t = klass2({'foo':1234})
150 assert str(t)=='1234'
152 klass3 = Template.compile(source='$foo', baseclass='Test1',
153 moduleGlobals={'Test1':dict, 'foo':1234})
154 t = klass3()
155 assert str(t)=='1234'
158 def test_keepRefToGeneratedCodeArg(self):
159 klass = Template.compile(source='$foo',
160 className='unique58',
161 cacheCompilationResults=False,
162 keepRefToGeneratedCode=False)
163 t = klass(namespaces={'foo':1234})
164 assert str(t)=='1234'
165 assert not t.generatedModuleCode()
168 klass2 = Template.compile(source='$foo',
169 className='unique58',
170 keepRefToGeneratedCode=True)
171 t = klass2(namespaces={'foo':1234})
172 assert str(t)=='1234'
173 assert t.generatedModuleCode()
175 klass3 = Template.compile(source='$foo',
176 className='unique58',
177 keepRefToGeneratedCode=False)
178 t = klass3(namespaces={'foo':1234})
179 assert str(t)=='1234'
180 # still there as this class came from the cache
181 assert t.generatedModuleCode()
184 def test_compilationCache(self):
185 klass = Template.compile(source='$foo',
186 className='unique111',
187 cacheCompilationResults=False)
188 t = klass(namespaces={'foo':1234})
189 assert str(t)=='1234'
190 assert not klass._CHEETAH_isInCompilationCache
193 # this time it will place it in the cache
194 klass = Template.compile(source='$foo',
195 className='unique111',
196 cacheCompilationResults=True)
197 t = klass(namespaces={'foo':1234})
198 assert str(t)=='1234'
199 assert klass._CHEETAH_isInCompilationCache
201 # by default it will be in the cache
202 klass = Template.compile(source='$foo',
203 className='unique999099')
204 t = klass(namespaces={'foo':1234})
205 assert str(t)=='1234'
206 assert klass._CHEETAH_isInCompilationCache
209 class ClassMethods_subclass(TemplateTest):
211 def test_basicUsage(self):
212 klass = Template.compile(source='$foo', baseclass=dict)
213 t = klass({'foo':1234})
214 assert str(t)=='1234'
216 klass2 = klass.subclass(source='$foo')
217 t = klass2({'foo':1234})
218 assert str(t)=='1234'
220 klass3 = klass2.subclass(source='#implements dummy\n$bar')
221 t = klass3({'foo':1234})
222 assert str(t)=='1234'
225 class Preprocessors(TemplateTest):
227 def test_basicUsage1(self):
228 src='''\
229 %set foo = @a
230 $(@foo*10)
231 @a'''
232 src = '\n'.join([ln.strip() for ln in src.splitlines()])
233 preprocessors = {'tokens':'@ %',
234 'namespaces':{'a':99}
236 klass = Template.compile(src, preprocessors=preprocessors)
237 assert str(klass())=='990\n99'
239 def test_normalizePreprocessorArgVariants(self):
240 src='%set foo = 12\n%%comment\n$(@foo*10)'
242 class Settings1: tokens = '@ %'
243 Settings1 = Settings1()
245 from Cheetah.Template import TemplatePreprocessor
246 settings = Template._normalizePreprocessorSettings(Settings1)
247 preprocObj = TemplatePreprocessor(settings)
249 def preprocFunc(source, file):
250 return '$(12*10)', None
252 class TemplateSubclass(Template):
253 pass
255 compilerSettings = {'cheetahVarStartToken':'@',
256 'directiveStartToken':'%',
257 'commentStartToken':'%%',
260 for arg in ['@ %',
261 {'tokens':'@ %'},
262 {'compilerSettings':compilerSettings},
263 {'compilerSettings':compilerSettings,
264 'templateInitArgs':{}},
265 {'tokens':'@ %',
266 'templateAPIClass':TemplateSubclass},
267 Settings1,
268 preprocObj,
269 preprocFunc,
272 klass = Template.compile(src, preprocessors=arg)
273 assert str(klass())=='120'
276 def test_complexUsage(self):
277 src='''\
278 %set foo = @a
279 %def func1: #def func(arg): $arg("***")
280 %% comment
281 $(@foo*10)
282 @func1
283 $func(lambda x:c"--$x--@a")'''
284 src = '\n'.join([ln.strip() for ln in src.splitlines()])
287 for arg in [{'tokens':'@ %', 'namespaces':{'a':99} },
288 {'tokens':'@ %', 'namespaces':{'a':99} },
290 klass = Template.compile(src, preprocessors=arg)
291 t = klass()
292 assert str(t)=='990\n--***--99'
296 def test_i18n(self):
297 src='''\
298 %i18n: This is a $string that needs translation
299 %i18n id="foo", domain="root": This is a $string that needs translation
301 src = '\n'.join([ln.strip() for ln in src.splitlines()])
302 klass = Template.compile(src, preprocessors='@ %', baseclass=dict)
303 t = klass({'string':'bit of text'})
304 #print str(t), repr(str(t))
305 assert str(t)==('This is a bit of text that needs translation\n'*2)[:-1]
308 ##################################################
309 ## if run from the command line ##
311 if __name__ == '__main__':
312 unittest.main()