def test_normalizePreprocessorArgVariants(self): src='%set foo = 12\n%%comment\n$(@foo*10)' class Settings1: tokens = '@ %' Settings1 = Settings1() from modules.Cheetah.Template import TemplatePreprocessor settings = Template._normalizePreprocessorSettings(Settings1) preprocObj = TemplatePreprocessor(settings) def preprocFunc(source, file): return '$(12*10)', None class TemplateSubclass(Template): pass compilerSettings = {'cheetahVarStartToken': '@', 'directiveStartToken': '%', 'commentStartToken': '%%', } for arg in ['@ %', {'tokens':'@ %'}, {'compilerSettings':compilerSettings}, {'compilerSettings':compilerSettings, 'templateInitArgs':{}}, {'tokens':'@ %', 'templateAPIClass':TemplateSubclass}, Settings1, preprocObj, preprocFunc, ]: klass = Template.compile(src, preprocessors=arg) assert str(klass())=='120'
def test_int(self): from modules.Cheetah.Template import Template t = Template(''' #def intify(val) #return $int(val) #end def''', compilerSettings={'useStackFrames' : False}) self.assertEquals(5, t.intify('5'))
def test_int(self): from modules.Cheetah.Template import Template t = Template(''' #def intify(val) #return $int(val) #end def''', compilerSettings={'useStackFrames': False}) self.assertEquals(5, t.intify('5'))
def runTest(self): t = Template("""Foo ${var}""", filter='EncodeUnicode') t.var = u"Text with some non-ascii characters: åäö" rc = t.respond() assert isinstance(rc, unicode), ('Template.respond() should return unicode', rc) rc = str(t) assert isinstance(rc, str), ('Template.__str__() should return a UTF-8 encoded string', rc)
def runTest(self): t = Template.compile(source="""Main file with |$v| $other""") otherT = Template.compile(source="Other template with |$v|") other = otherT() t.other = other t.v = u'Unicode String with eacute é' t.other.v = u'Unicode String and an eacute é' assert unicode(t())
def runTest(self): t = Template("""Foo ${var}""", filter='EncodeUnicode') t.var = u"Text with some non-ascii characters: åäö" rc = t.respond() assert isinstance( rc, unicode), ('Template.respond() should return unicode', rc) rc = str(t) assert isinstance( rc, str), ('Template.__str__() should return a UTF-8 encoded string', rc)
def test_moduleNameArg(self): klass = Template.compile(source='$foo', moduleName='foo99') mod = sys.modules['foo99'] assert klass.__name__=='foo99' t = klass(namespaces={'foo':1234}) assert str(t)=='1234' klass = Template.compile(source='$foo', moduleName='foo1', className='foo2') mod = sys.modules['foo1'] assert klass.__name__=='foo2' t = klass(namespaces={'foo':1234}) assert str(t)=='1234'
def test_moduleGlobalsArg(self): klass = Template.compile(source='$foo', moduleGlobals={'foo':1234}) t = klass() assert str(t)=='1234' klass2 = Template.compile(source='$foo', baseclass='Test1', moduleGlobals={'Test1':dict}) t = klass2({'foo':1234}) assert str(t)=='1234' klass3 = Template.compile(source='$foo', baseclass='Test1', moduleGlobals={'Test1':dict, 'foo':1234}) t = klass3() assert str(t)=='1234'
def test_baseclassArg(self): klass = Template.compile(source='$foo', baseclass=dict) t = klass({'foo':1234}) assert str(t)=='1234' klass2 = Template.compile(source='$foo', baseclass=klass) t = klass2({'foo':1234}) assert str(t)=='1234' klass3 = Template.compile(source='#implements dummy\n$bar', baseclass=klass2) t = klass3({'foo':1234}) assert str(t)=='1234' klass4 = Template.compile(source='$foo', baseclass='dict') t = klass4({'foo':1234}) assert str(t)=='1234'
def get_torrent_info(self, torrent_id, html=None ): c = time.localtime(self.RT.getCreationDate(torrent_id)) created = time.strftime("%d/%m/%Y %H:%M:%S", c) size = self.RT.getSizeBytes(torrent_id) completed_bytes = self.RT.getCompletedBytes(torrent_id) if completed_bytes >= size: completed = True else: completed = False peers = self.RT.getPeers(torrent_id) jsonObject = { "name" : self.RT.getNameByID(torrent_id), "uploaded" : self.handler.humanSize(self.RT.getUploadBytes(torrent_id)), "downloaded" : self.handler.humanSize(self.RT.getDownloadBytes(torrent_id)), "peers" : len(peers), "torrent_id" : torrent_id, "created" : created, "size" : self.handler.humanSize(size), "ratio" : "%.02f" % (float(self.RT.getRatio(torrent_id))/1000), "percentage" : "%i" % ((float(self.RT.getCompletedBytes(torrent_id)) / size) * 100), "completed" : completed, "trackers" : [x.__dict__ for x in self.RT.getTrackers(torrent_id)], "peer_details" : [self._peerProcess(x) for x in peers], "file_tree" : self.handler.fileTreeHTML(self.RT.getFiles(torrent_id), self.RT.getRootDir()), } if not html: return json.dumps(jsonObject) else: return Template(file="htdocs/dropDownHTML.tmpl", searchList=jsonObject).respond()
def get(self): searchList = [{ "ROOT_DIR": self.application._pyrtRT.getGlobalRootPath() }] HTML = Template(file="htdocs/createHTML.tmpl", searchList=searchList).respond() self.write(HTML)
def runTest(self): t = Template.compile(source="""#encoding utf-8 Main file with |$v| and eacute in the template é""") t.v = u'Unicode String' assert unicode(t())
def runTest(self): source = """#encoding utf-8 #set $someUnicodeString = u"Bébé" Main file with |$v| and eacute in the template é""" t = Template.compile(source=source) t.v = u'Unicode String' assert unicode(t())
def __init__(self, *args, **KWs): Template.__init__(self, *args, **KWs) self._metaTags = {'HTTP-EQUIV':{'keywords': 'Cheetah', 'Content-Type': 'text/html; charset=iso-8859-1', }, 'NAME':{'generator':'Cheetah: The Python-Powered Template Engine'} } # metaTags = {'HTTP_EQUIV':{'test':1234}, 'NAME':{'test':1234,'test2':1234} } self._stylesheets = {} # stylesheets = {'.cssClassName':'stylesheetCode'} self._stylesheetsOrder = [] # stylesheetsOrder = ['.cssClassName',] self._stylesheetLibs = {} # stylesheetLibs = {'libName':'libSrcPath'} self._javascriptLibs = {} self._javascriptTags = {} # self._javascriptLibs = {'libName':'libSrcPath'} self._bodyTagAttribs = {}
def testDynamicCompile(self): source = """#encoding utf-8 #set $someUnicodeString = u"Bébé" $someUnicodeString""" template = Template(source=source) a = unicode(template).encode("utf-8") self.assertEquals("Bébé", a)
def test_i18n(self): src='''\ %i18n: This is a $string that needs translation %i18n id="foo", domain="root": This is a $string that needs translation ''' src = '\n'.join([ln.strip() for ln in src.splitlines()]) klass = Template.compile(src, preprocessors='@ %', baseclass=dict) t = klass({'string':'bit of text'}) #print str(t), repr(str(t)) assert str(t)==('This is a bit of text that needs translation\n'*2)[:-1]
def test_mainMethodNameArg(self): klass = Template.compile(source='$foo', className='foo123', mainMethodName='testMeth') assert klass.__name__=='foo123' t = klass(namespaces={'foo':1234}) #print t.generatedClassCode() assert str(t)=='1234' assert t.testMeth()=='1234' klass = Template.compile(source='$foo', moduleName='fooXXX', className='foo123', mainMethodName='testMeth', baseclass=dict) assert klass.__name__=='foo123' t = klass({'foo':1234}) #print t.generatedClassCode() assert str(t)=='1234' assert t.testMeth()=='1234'
def test_success(self): """ Test a template with a proper #encoding tag """ template = '#encoding utf-8\n%s' % self.template template = Template(template, searchList=[{ 'header': '', 'nombre': '', 'numpedidos_bodega': '', 'numpedidos_noconf': '' }]) self.assertTrue(unicode(template))
def test_basicUsage1(self): src='''\ %set foo = @a $(@foo*10) @a''' src = '\n'.join([ln.strip() for ln in src.splitlines()]) preprocessors = {'tokens':'@ %', 'namespaces':{'a':99} } klass = Template.compile(src, preprocessors=preprocessors) assert str(klass())=='990\n99'
def test_basicUsage(self): klass = Template.compile(source='$foo', baseclass=dict) t = klass({'foo':1234}) assert str(t)=='1234' klass2 = klass.subclass(source='$foo') t = klass2({'foo':1234}) assert str(t)=='1234' klass3 = klass2.subclass(source='#implements dummy\n$bar') t = klass3({'foo':1234}) assert str(t)=='1234'
def __init__(self, *args, **KWs): Template.__init__(self, *args, **KWs) self._metaTags = { 'HTTP-EQUIV': { 'keywords': 'Cheetah', 'Content-Type': 'text/html; charset=iso-8859-1', }, 'NAME': { 'generator': 'Cheetah: The Python-Powered Template Engine' } } # metaTags = {'HTTP_EQUIV':{'test':1234}, 'NAME':{'test':1234,'test2':1234} } self._stylesheets = {} # stylesheets = {'.cssClassName':'stylesheetCode'} self._stylesheetsOrder = [] # stylesheetsOrder = ['.cssClassName',] self._stylesheetLibs = {} # stylesheetLibs = {'libName':'libSrcPath'} self._javascriptLibs = {} self._javascriptTags = {} # self._javascriptLibs = {'libName':'libSrcPath'} self._bodyTagAttribs = {}
def runTest(self): template = ''' #extends Template, Useless #def foo() #return [4,5] + $boink() #end def ''' template = Template.compile(template, moduleGlobals={'Useless' : Useless}, compilerSettings={'autoImportForExtendsDirective' : False}) template = template() result = template.foo() assert result == [4, 5, 1, 2, 3], (result, 'Unexpected result')
def test_compilationCache(self): klass = Template.compile(source='$foo', className='unique111', cacheCompilationResults=False) t = klass(namespaces={'foo':1234}) assert str(t)=='1234' assert not klass._CHEETAH_isInCompilationCache # this time it will place it in the cache klass = Template.compile(source='$foo', className='unique111', cacheCompilationResults=True) t = klass(namespaces={'foo':1234}) assert str(t)=='1234' assert klass._CHEETAH_isInCompilationCache # by default it will be in the cache klass = Template.compile(source='$foo', className='unique999099') t = klass(namespaces={'foo':1234}) assert str(t)=='1234' assert klass._CHEETAH_isInCompilationCache
def test_keepRefToGeneratedCodeArg(self): klass = Template.compile(source='$foo', className='unique58', cacheCompilationResults=False, keepRefToGeneratedCode=False) t = klass(namespaces={'foo':1234}) assert str(t)=='1234' assert not t.generatedModuleCode() klass2 = Template.compile(source='$foo', className='unique58', keepRefToGeneratedCode=True) t = klass2(namespaces={'foo':1234}) assert str(t)=='1234' assert t.generatedModuleCode() klass3 = Template.compile(source='$foo', className='unique58', keepRefToGeneratedCode=False) t = klass3(namespaces={'foo':1234}) assert str(t)=='1234' # still there as this class came from the cache assert t.generatedModuleCode()
def test_FailCase(self): ''' Test situation where an inline #import statement will get relocated ''' source = ''' #def myFunction() Ahoy! #try #import sys #except ImportError $print "This will never happen!" #end try #end def ''' # This should raise an IndentationError (if the bug exists) klass = Template.compile(source=source, compilerSettings={'useLegacyImportMode' : False}) t = klass(namespaces={'foo' : 1234})
def get(self): chk = _check.web(self) if not chk[0]: self.write(self.application._pyrtL.loginHTML(chk[1])) return elif chk[0] and chk[1]: self.set_cookie( "sess_id", self.application._pyrtL.sendCookie(self.request.remote_ip)) searchList = [{ "ROOT_DIR": self.application._pyrtRT.getGlobalRootPath() }] HTML = Template(file="htdocs/createHTML.tmpl", searchList=searchList).respond() self.write(HTML)
def test_moduleFileCaching(self): if versionTuple < (2, 3): return tmpDir = tempfile.mkdtemp() try: #print tmpDir assert os.path.exists(tmpDir) klass = Template.compile(source='$foo', cacheModuleFilesForTracebacks=True, cacheDirForModuleFiles=tmpDir) mod = sys.modules[klass.__module__] #print mod.__file__ assert os.path.exists(mod.__file__) assert os.path.dirname(mod.__file__)==tmpDir finally: shutil.rmtree(tmpDir, True)
def test_BasicDecorator(self): if sys.version_info[0] == 2 and sys.version_info[1] == 3: print('This version of Python doesn\'t support decorators, skipping tests') return template = ''' #@staticmethod #def myStaticMethod() #return '$foo = %s' % $foo #end def ''' template = Template.compile(source=template) try: rc = template.myStaticMethod(foo='bar') assert rc == '$foo = bar', (rc, 'Template class method didn\'t return what I expected') except AttributeError, ex: self.fail(ex)
def test_complexUsage(self): src='''\ %set foo = @a %def func1: #def func(arg): $arg("***") %% comment $(@foo*10) @func1 $func(lambda x:c"--$x--@a")''' src = '\n'.join([ln.strip() for ln in src.splitlines()]) for arg in [{'tokens':'@ %', 'namespaces':{'a':99} }, {'tokens':'@ %', 'namespaces':{'a':99} }, ]: klass = Template.compile(src, preprocessors=arg) t = klass() assert str(t)=='990\n--***--99'
def torrentHTML(self, torrentList, sort, view, reverse=None): """ Sorts a list of torrent_ids with default information Arguments: torrentList = list : rtorrent.Torrent objects sort = str : value to sort on reverse = boolean : reverse or not Sort Options: name, size, ratio, uprate, uptotal, downrate, downtotal, leechs, leechs_connected, leechs_total, seeds, seeds_connected, seeds_total, peers, peers_connected, peers_total, priority, status, tracker, created leechs, seeds, and peers are shorthand for leechs_connected, seeds_connected and peers_connected respectively """ torrentList = self.sortTorrents(torrentList, sort, reverse) updated_torrentList = [] for t in torrentList: t.t_size = self.humanSize(t.size) t.t_uploaded = self.humanSize(t.up_total) t.t_downloaded = self.humanSize(t.down_total) t.t_ratio = "%.02f" % (float(t.ratio) / 1000) t.t_uprate = self.humanSize(t.up_rate) t.t_downrate = self.humanSize(t.down_rate) t.t_percentage = int((float(t.completed_bytes) / t.size) * 100) updated_torrentList += [t] searchList = [{ "global": system.get_global(), "torrent_list": updated_torrentList, "this_view": view, "this_sort": sort, "this_reverse": reverse, "self": self, }] HTML = Template(file="htdocs/torrentHTML.tmpl", searchList=searchList).respond() return HTML
def test_classNameArg(self): klass = Template.compile(source='$foo', className='foo123') assert klass.__name__=='foo123' t = klass(namespaces={'foo':1234}) assert str(t)=='1234'
def test_basicUsage(self): klass = Template.compile(source='$foo') t = klass(namespaces={'foo':1234}) assert str(t)=='1234'
def index(self): # PyRT: # change password # change port # (change theme) # rTorrent # global upload throttle # global download throttle portrange = self.RT.getGlobalPortRange() aliases = self.ALIASES.STORE maxpeers = self.RT.getGlobalMaxPeers() maxpeersseed = self.RT.getGlobalMaxPeersSeed() if maxpeersseed == -1: maxpeersseed = maxpeers try: performancereadahead = int(float(self.RT.getGlobalHashReadAhead())) except: performancereadahead = None gmc_bool, gmc_value = self.RT.getGlobalMoveTo() gmc_enabled = gmc_bool and "checked" or "" if gmc_bool: gmc_hidden = "" else: gmc_hidden = "hidden" gmc_value = gmc_value and gmc_value or "" definitions = { "config": self.C.CONFIG, "throttleup": int(float(self.RT.getGlobalUpThrottle()) / 1024), "throttledown": int(float(self.RT.getGlobalDownThrottle()) / 1024), "generaldir": self.RT.getGlobalRootPath(), "generalmovecheckbool": gmc_enabled, "generalmovecheckvalue": gmc_value, "generalmovecheckhidden": gmc_hidden, "networkportfrom": portrange.split("-")[0], "networkportto": portrange.split("-")[1], "aliases": aliases, "performancemaxmemory": int(float(self.RT.getGlobalMaxMemoryUsage()) / 1024 / 1024), "performancereceivebuffer": int(float(self.RT.getGlobalReceiveBufferSize()) / 1024), "performancesendbuffer": int(float(self.RT.getGlobalSendBufferSize()) / 1024), "performancemaxopenfiles": self.RT.getGlobalMaxOpenFiles(), "performancemaxfilesize": int(float(self.RT.getGlobalMaxFileSize()) / 1024 / 1024), "performancereadahead": performancereadahead, "networksimuluploads": self.RT.getGlobalMaxUploads(), "networksimuldownloads": self.RT.getGlobalMaxDownloads(), "networkmaxpeers": maxpeers, "networkmaxpeersseed": maxpeersseed, "networkmaxopensockets": self.RT.getGlobalMaxOpenSockets(), "networkmaxopenhttp": self.RT.getGlobalMaxOpenHttp(), } HTML = Template(file="htdocs/optionsHTML.tmpl", searchList=definitions).respond() return HTML