root/galaxy-central/eggs/Cheetah-2.2.2-py2.6-macosx-10.6-universal-ucs2.egg/Cheetah/Tests/Template.py @ 3

リビジョン 3, 11.8 KB (コミッタ: kohda, 14 年 前)

Install Unix tools  http://hannonlab.cshl.edu/galaxy_unix_tools/galaxy.html

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