Debian Codegraph @

Cheetah/Tests/Template.py

raw symbols SCIP
1 import os
2 import os.path
3 import sys
4 import shutil
5 import tempfile
6 import unittest
7
8 from Cheetah.Template import Template
9 from Cheetah.compat import unicode
10
11
12 class TemplateTest(unittest.TestCase):
13 pass
14
15
16 class ClassMethods_compile(TemplateTest):
17 """I am using the same Cheetah source for each test to root out clashes
18 caused by the compile caching in Template.compile().
19 """
20
21 def test_basicUsage(self):
22 klass = Template.compile(source='$foo')
23 t = klass(namespaces={'foo': 1234})
24 assert str(t) == '1234'
25
26 def test_baseclassArg(self):
27 klass = Template.compile(source='$foo', baseclass=dict)
28 t = klass({'foo': 1234})
29 assert str(t) == '1234'
30
31 klass2 = Template.compile(source='$foo', baseclass=klass)
32 t = klass2({'foo': 1234})
33 assert str(t) == '1234'
34
35 klass3 = Template.compile(source='#implements dummy\n$bar',
36 baseclass=klass2)
37 t = klass3({'foo': 1234})
38 assert str(t) == '1234'
39
40 klass4 = Template.compile(source='$foo', baseclass='dict')
41 t = klass4({'foo': 1234})
42 assert str(t) == '1234'
43
44 def test_moduleFileCaching(self):
45 tmpDir = tempfile.mkdtemp()
46 try:
47 # print tmpDir
48 assert os.path.exists(tmpDir)
49 klass = Template.compile(source='$foo',
50 cacheModuleFilesForTracebacks=True,
51 cacheDirForModuleFiles=tmpDir)
52 mod = sys.modules[klass.__module__]
53 # print mod.__file__
54 assert os.path.exists(mod.__file__)
55 assert os.path.dirname(mod.__file__) == tmpDir
56 finally:
57 shutil.rmtree(tmpDir, True)
58
59 def test_classNameArg(self):
60 klass = Template.compile(source='$foo', className='foo123')
61 assert klass.__name__ == 'foo123'
62 t = klass(namespaces={'foo': 1234})
63 assert str(t) == '1234'
64
65 def test_moduleNameArg(self):
66 klass = Template.compile(source='$foo', moduleName='foo99')
67 assert klass.__name__ == 'foo99'
68 t = klass(namespaces={'foo': 1234})
69 assert str(t) == '1234'
70
71 klass = Template.compile(source='$foo',
72 moduleName='foo1',
73 className='foo2')
74 assert klass.__name__ == 'foo2'
75 t = klass(namespaces={'foo': 1234})
76 assert str(t) == '1234'
77
78 def test_mainMethodNameArg(self):
79 klass = Template.compile(source='$foo',
80 className='foo123',
81 mainMethodName='testMeth')
82 assert klass.__name__ == 'foo123'
83 t = klass(namespaces={'foo': 1234})
84 # print t.generatedClassCode()
85 assert str(t) == '1234'
86 assert t.testMeth() == '1234'
87
88 klass = Template.compile(source='$foo',
89 moduleName='fooXXX',
90 className='foo123',
91 mainMethodName='testMeth',
92 baseclass=dict)
93 assert klass.__name__ == 'foo123'
94 t = klass({'foo': 1234})
95 # print t.generatedClassCode()
96 assert str(t) == '1234'
97 assert t.testMeth() == '1234'
98
99 def test_moduleGlobalsArg(self):
100 klass = Template.compile(source='$foo',
101 moduleGlobals={'foo': 1234})
102 t = klass()
103 assert str(t) == '1234'
104
105 klass2 = Template.compile(source='$foo', baseclass='Test1',
106 moduleGlobals={'Test1': dict})
107 t = klass2({'foo': 1234})
108 assert str(t) == '1234'
109
110 klass3 = Template.compile(source='$foo', baseclass='Test1',
111 moduleGlobals={'Test1': dict, 'foo': 1234})
112 t = klass3()
113 assert str(t) == '1234'
114
115 def test_keepRefToGeneratedCodeArg(self):
116 klass = Template.compile(source='$foo',
117 className='unique58',
118 cacheCompilationResults=False,
119 keepRefToGeneratedCode=False)
120 t = klass(namespaces={'foo': 1234})
121 assert str(t) == '1234'
122 assert not t.generatedModuleCode()
123
124 klass2 = Template.compile(source='$foo',
125 className='unique58',
126 keepRefToGeneratedCode=True)
127 t = klass2(namespaces={'foo': 1234})
128 assert str(t) == '1234'
129 assert t.generatedModuleCode()
130
131 klass3 = Template.compile(source='$foo',
132 className='unique58',
133 keepRefToGeneratedCode=False)
134 t = klass3(namespaces={'foo': 1234})
135 assert str(t) == '1234'
136 # still there as this class came from the cache
137 assert t.generatedModuleCode()
138
139 def test_compilationCache(self):
140 klass = Template.compile(source='$foo',
141 className='unique111',
142 cacheCompilationResults=False)
143 t = klass(namespaces={'foo': 1234})
144 assert str(t) == '1234'
145 assert not klass._CHEETAH_isInCompilationCache
146
147 # this time it will place it in the cache
148 klass = Template.compile(source='$foo',
149 className='unique111',
150 cacheCompilationResults=True)
151 t = klass(namespaces={'foo': 1234})
152 assert str(t) == '1234'
153 assert klass._CHEETAH_isInCompilationCache
154
155 # by default it will be in the cache
156 klass = Template.compile(source='$foo',
157 className='unique999099')
158 t = klass(namespaces={'foo': 1234})
159 assert str(t) == '1234'
160 assert klass._CHEETAH_isInCompilationCache
161
162
163 class OpenFileTest(TemplateTest):
164 def setUp(self):
165 self.template_file = \
166 tempfile.NamedTemporaryFile(mode='w', delete=False)
167 self.template_file.write("<h1>Test open file</h1>")
168 self.template_file.close()
169
170 def tearDown(self):
171 os.remove(self.template_file.name)
172
173 def test_compileFile(self):
174 tmpl_file = open(self.template_file.name)
175 try:
176 Template.compile(file=tmpl_file)
177 finally:
178 tmpl_file.close()
179
180
181 class ClassMethods_subclass(TemplateTest):
182
183 def test_basicUsage(self):
184 klass = Template.compile(source='$foo', baseclass=dict)
185 t = klass({'foo': 1234})
186 assert str(t) == '1234'
187
188 klass2 = klass.subclass(source='$foo')
189 t = klass2({'foo': 1234})
190 assert str(t) == '1234'
191
192 klass3 = klass2.subclass(source='#implements dummy\n$bar')
193 t = klass3({'foo': 1234})
194 assert str(t) == '1234'
195
196
197 class Preprocessors(TemplateTest):
198
199 def test_basicUsage1(self):
200 src = '''\
201 %set foo = @a
202 $(@foo*10)
203 @a'''
204 src = '\n'.join([ln.strip() for ln in src.splitlines()])
205 preprocessors = {'tokens': '@ %',
206 'namespaces': {'a': 99}
207 }
208 klass = Template.compile(src, preprocessors=preprocessors)
209 assert str(klass()) == '990\n99'
210
211 def test_normalizePreprocessorArgVariants(self):
212 src = '%set foo = 12\n%%comment\n$(@foo*10)'
213
214 class Settings1:
215 tokens = '@ %'
216 Settings1 = Settings1()
217
218 from Cheetah.Template import TemplatePreprocessor
219 settings = Template._normalizePreprocessorSettings(Settings1)
220 preprocObj = TemplatePreprocessor(settings)
221
222 def preprocFunc(source, file):
223 return '$(12*10)', None
224
225 class TemplateSubclass(Template):
226 pass
227
228 compilerSettings = {'cheetahVarStartToken': '@',
229 'directiveStartToken': '%',
230 'commentStartToken': '%%',
231 }
232
233 for arg in ['@ %',
234 {'tokens': '@ %'},
235 {'compilerSettings': compilerSettings},
236 {'compilerSettings': compilerSettings,
237 'templateInitArgs': {}},
238 {'tokens': '@ %',
239 'templateAPIClass': TemplateSubclass},
240 Settings1,
241 preprocObj,
242 preprocFunc,
243 ]:
244
245 klass = Template.compile(src, preprocessors=arg)
246 assert str(klass()) == '120'
247
248 def test_complexUsage(self):
249 src = '''\
250 %set foo = @a
251 %def func1: #def func(arg): $arg("***")
252 %% comment
253 $(@foo*10)
254 @func1
255 $func(lambda x:c"--$x--@a")'''
256 src = '\n'.join([ln.strip() for ln in src.splitlines()])
257
258 for arg in [{'tokens': '@ %', 'namespaces': {'a': 99}},
259 {'tokens': '@ %', 'namespaces': {'a': 99}},
260 ]:
261 klass = Template.compile(src, preprocessors=arg)
262 t = klass()
263 assert str(t) == '990\n--***--99'
264
265 def test_i18n(self):
266 src = '''\
267 %i18n: This is a $string that needs translation
268 %i18n id="foo", domain="root": This is a $string that needs translation
269 '''
270 src = '\n'.join([ln.strip() for ln in src.splitlines()])
271 klass = Template.compile(src, preprocessors='@ %', baseclass=dict)
272 t = klass({'string': 'bit of text'})
273 # print str(t), repr(str(t))
274 assert str(t) == (
275 'This is a bit of text that needs translation\n'*2)[:-1] # noqa: E226,E501 missing whitespace around operator
276
277
278 class TryExceptImportTest(TemplateTest):
279 def test_FailCase(self):
280 """
281 Test situation where an inline #import statement will get relocated
282 """
283 source = '''
284 #def myFunction()
285 Ahoy!
286 #try
287 #import sys
288 #except ImportError
289 $print "This will never happen!"
290 #end try
291 #end def
292 '''
293 # This should raise an IndentationError (if the bug exists)
294 klass = Template.compile(
295 source=source, compilerSettings={'useLegacyImportMode': False})
296 t = klass(namespaces={'foo': 1234}) # noqa: F841
297
298
299 class ClassMethodSupport(TemplateTest):
300 def test_BasicDecorator(self):
301 template = '''
302 #@classmethod
303 #def myClassMethod()
304 #return '$foo = %s' % $foo
305 #end def
306 '''
307 template = Template.compile(source=template)
308 try:
309 rc = template.myClassMethod(foo='bar')
310 assert rc == '$foo = bar', \
311 (rc, 'Template class method didn\'t return what I expected')
312 except AttributeError as ex:
313 self.fail(ex)
314
315
316 class StaticMethodSupport(TemplateTest):
317 def test_BasicDecorator(self):
318 template = '''
319 #@staticmethod
320 #def myStaticMethod()
321 #return '$foo = %s' % $foo
322 #end def
323 '''
324 template = Template.compile(source=template)
325 try:
326 rc = template.myStaticMethod(foo='bar')
327 assert rc == '$foo = bar', \
328 (rc, 'Template class method didn\'t return what I expected')
329 except AttributeError as ex:
330 self.fail(ex)
331
332
333 class MultipleInheritanceSupport(TemplateTest):
334 def runTest(self):
335 template = '''
336 #extends Cheetah.Tests.Boinker, Cheetah.Tests.Pinger
337 #def foo()
338 #return [4,5] + $boink()
339 #end def
340 '''
341
342 template = Template.compile(template)
343 template = template()
344 result = template.foo()
345 assert result == [4, 5, 1, 2, 3], (result, 'Unexpected result')
346
347
348 class SubclassSearchListTest(TemplateTest):
349 '''
350 Verify that if we subclass Template, we can still
351 use attributes on that subclass in the searchList
352 '''
353 def runTest(self):
354 class Sub(Template):
355 greeting = 'Hola'
356 tmpl = Sub('''When we meet, I say "${greeting}"''')
357 self.assertEqual(unicode(tmpl), 'When we meet, I say "Hola"')