def testUnicode(self): a = ustr(u'hello') assert a=='hello', `a` a = ustr(force_str(u'hello')) assert a=='hello', `a` a = ustr(unichr(200)) assert a==unichr(200), `a` a = ustr(force_str(unichr(200))) assert a==unichr(200), `a`
def render_blocks(blocks, md): rendered = [] append=rendered.append for section in blocks: if type(section) is TupleType: l=len(section) if l==1: # Simple var section=section[0] if type(section) is StringType: section=md[section] else: section=section(md) section=ustr(section) else: # if cache={} md._push(cache) try: i=0 m=l-1 while i < m: cond=section[i] if type(cond) is StringType: n=cond try: cond=md[cond] cache[n]=cond except KeyError, v: v=str(v) if n != v: raise KeyError, v, sys.exc_traceback cond=None else: cond=cond(md) if cond: section=section[i+1] if section: section=render_blocks(section,md) else: section='' m=0 break i=i+2 if m: if i==m: section=render_blocks(section[i],md) else: section='' finally: md._pop() elif type(section) is not StringType and type(section) is not UnicodeType: section=section(md)
def testPlain(self): a = ustr('hello') assert a=='hello', `a` a = ustr(force_str('hello')) assert a=='hello', `a` a = ustr(chr(200)) assert a==chr(200), `a` a = ustr(force_str(chr(200))) assert a==chr(200), `a` a = ustr(22) assert a=='22', `a` a = ustr([1,2,3]) assert a=='[1, 2, 3]', `a`
def raise_standardErrorMessage( self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=re.compile(r'[a-zA-Z]>').search, error_log_url=''): try: if error_type is None: error_type =sys.exc_info()[0] if error_value is None: error_value=sys.exc_info()[1] # allow for a few different traceback options if tb is None and error_tb is None: tb=sys.exc_info()[2] if type(tb) is not type('') and (error_tb is None): error_tb = pretty_tb(error_type, error_value, tb) elif type(tb) is type('') and not error_tb: error_tb = tb if hasattr(self, '_v_eek'): # Stop if there is recursion. raise error_type, error_value, tb self._v_eek = 1 if hasattr(error_type, '__name__'): error_name = error_type.__name__ else: error_name = 'Unknown' if not error_message: try: s = ustr(error_value) except: s = error_value try: match = tagSearch(s) except TypeError: match = None if match is not None: error_message=error_value if client is None: client = self if not REQUEST: REQUEST = aq_acquire(self, 'REQUEST') try: s = aq_acquire(client, 'standard_error_message') # For backward compatibility, we pass 'error_name' as # 'error_type' here as historically this has always # been a string. kwargs = {'error_type': error_name, 'error_value': error_value, 'error_tb': error_tb, 'error_traceback': error_tb, 'error_message': error_message, 'error_log_url': error_log_url} if getattr(aq_base(s), 'isDocTemp', 0): v = s(client, REQUEST, **kwargs) elif callable(s): v = s(**kwargs) else: v = HTML.__call__(s, client, REQUEST, **kwargs) except: logger.error( 'Exception while rendering an error message', exc_info=True ) try: strv = repr(error_value) # quotes tainted strings except: strv = ('<unprintable %s object>' % str(type(error_value).__name__)) v = strv + ( (" (Also, the following error occurred while attempting " "to render the standard error message, please see the " "event log for full details: %s)")%( html_quote(sys.exc_info()[1]), )) # If we've been asked to handle errors, just return the rendered # exception and let the ZPublisher Exception Hook deal with it. return error_type, v, tb finally: if hasattr(self, '_v_eek'): del self._v_eek tb = None
def raise_standardErrorMessage(self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=re.compile(r'[a-zA-Z]>').search, error_log_url=''): try: if error_type is None: error_type = sys.exc_info()[0] if error_value is None: error_value = sys.exc_info()[1] # allow for a few different traceback options if tb is None and error_tb is None: tb = sys.exc_info()[2] if type(tb) is not str and (error_tb is None): error_tb = pretty_tb(error_type, error_value, tb) elif type(tb) is str and not error_tb: error_tb = tb if hasattr(self, '_v_eek'): # Stop if there is recursion. raise error_type, error_value, tb self._v_eek = 1 if hasattr(error_type, '__name__'): error_name = error_type.__name__ else: error_name = 'Unknown' if not error_message: try: s = ustr(error_value) except: s = error_value try: match = tagSearch(s) except TypeError: match = None if match is not None: error_message = error_value if client is None: client = self if not REQUEST: REQUEST = aq_acquire(self, 'REQUEST') try: s = aq_acquire(client, 'standard_error_message') # For backward compatibility, we pass 'error_name' as # 'error_type' here as historically this has always # been a string. kwargs = { 'error_type': error_name, 'error_value': error_value, 'error_tb': error_tb, 'error_traceback': error_tb, 'error_message': xml_escape(str(error_message)), 'error_log_url': error_log_url } if getattr(aq_base(s), 'isDocTemp', 0): v = s(client, REQUEST, **kwargs) elif callable(s): v = s(**kwargs) else: v = HTML.__call__(s, client, REQUEST, **kwargs) except: logger.error('Exception while rendering an error message', exc_info=True) try: strv = repr(error_value) # quotes tainted strings except: strv = ('<unprintable %s object>' % str(type(error_value).__name__)) v = strv + ( (" (Also, the following error occurred while attempting " "to render the standard error message, please see the " "event log for full details: %s)") % (html_quote(sys.exc_info()[1]), )) # If we've been asked to handle errors, just return the rendered # exception and let the ZPublisher Exception Hook deal with it. return error_type, v, tb finally: if hasattr(self, '_v_eek'): del self._v_eek tb = None
def test_with_int(self): from DocumentTemplate.ustr import ustr a = ustr(22) self.assertEqual(a, '22')
def html_quote(v, name='(Unknown name)', md={}): return escape(ustr(v), 1)
def test_with_force_str(self): from DocumentTemplate.ustr import ustr a = ustr(force_str('hello')) self.assertEqual(a, 'hello')
def testCustomStrings(self): a = ustr(Foo('foo')) self.failUnlessEqual(type(a), Foo) a = ustr(Bar('bar')) self.failUnlessEqual(type(a), Bar)
def render_blocks_(blocks, rendered, md, encoding): for block in blocks: append = True if (isinstance(block, tuple) and len(block) > 1 and isinstance(block[0], six.string_types)): first_char = block[0][0] if first_char == 'v': # var t = block[1] if isinstance(t, six.string_types): t = md[t] else: t = t(md) skip_html_quote = 0 if not isinstance(t, (six.string_types, six.binary_type)): # This might be a TaintedString object untaintmethod = getattr(t, '__untaint__', None) if untaintmethod is not None: # Quote it t = untaintmethod() skip_html_quote = 1 if not isinstance(t, (six.string_types, six.binary_type)): t = ustr(t) if (skip_html_quote == 0 and len(block) == 3): # html_quote if isinstance(t, str): if ('&' in t or '<' in t or '>' in t or '"' in t): # string includes html problem characters, # so we cant skip the quoting process skip_html_quote = 0 else: skip_html_quote = 1 else: # never skip the quoting for unicode strings skip_html_quote = 0 if not skip_html_quote: t = html_quote(t, encoding=encoding) block = t elif first_char == 'i': # if bs = len(block) - 1 # subtract code cache = {} md._push(cache) try: append = False m = bs - 1 icond = 0 while icond < m: cond = block[icond + 1] if isinstance(cond, str): # We have to be careful to handle key errors here n = cond try: cond = md[cond] except KeyError as t: if n != t.args[0]: raise cond = None else: cache[n] = cond else: cond = cond(md) if cond: block = block[icond + 2] if block: render_blocks_(block, rendered, md, encoding) m = -1 break icond += 2 if icond == m: block = block[icond + 1] if block: render_blocks_(block, rendered, md, encoding) finally: md._pop() else: raise ValueError('Invalid DTML command code, %s', block[0]) elif not isinstance(block, (six.string_types, six.binary_type)): block = block(md) if append and block: rendered.append(block)
def test_w_unichr_in_exception(self): from DocumentTemplate.ustr import ustr a = ustr(ValueError(unichr(200))) self.assertEqual(a, unichr(200))
def testCustomStrings(self): from DocumentTemplate.ustr import ustr a = ustr(Foo('foo')) self.assertEqual(type(a), Foo) a = ustr(Bar('bar')) self.assertEqual(type(a), Bar)
def test_w_force_str_unichr(self): from DocumentTemplate.ustr import ustr a = ustr(force_str(unichr(200))) self.assertEqual(a, unichr(200))
def test_w_force_str_unicode_literal(self): from DocumentTemplate.ustr import ustr a = ustr(force_str(u'hello')) self.assertEqual(a, 'hello')
def test_with_list(self): from DocumentTemplate.ustr import ustr a = ustr([1,2,3]) self.assertEqual(a, '[1, 2, 3]')
def html_quote(v, name="(Unknown name)", md={}): return escape(ustr(v), 1)
def render_blocks_(blocks, rendered, md, encoding): for block in blocks: append = True if (isinstance(block, tuple) and len(block) > 1 and isinstance(block[0], six.string_types)): first_char = block[0][0] if first_char == 'v': # var t = block[1] if isinstance(t, six.string_types): t = md[t] else: t = t(md) skip_html_quote = 0 if not isinstance(t, (six.string_types, six.binary_type)): # This might be a TaintedString object untaintmethod = getattr(t, '__untaint__', None) if untaintmethod is not None: # Quote it t = untaintmethod() skip_html_quote = 1 if not isinstance(t, (six.string_types, six.binary_type)): t = ustr(t) if (skip_html_quote == 0 and len(block) == 3): # html_quote if isinstance(t, str): if ('&' in t or '<' in t or '>' in t or '"' in t): # string includes html problem characters, # so we cant skip the quoting process skip_html_quote = 0 else: skip_html_quote = 1 else: # never skip the quoting for unicode strings skip_html_quote = 0 if not skip_html_quote: t = html_quote(t, encoding=encoding) block = t elif first_char == 'i': # if bs = len(block) - 1 # subtract code cache = {} md._push(cache) try: append = False m = bs - 1 icond = 0 while icond < m: cond = block[icond + 1] if isinstance(cond, str): # We have to be careful to handle key errors here n = cond try: cond = md[cond] except KeyError as t: if n != t.args[0]: raise cond = None else: cache[n] = cond else: cond = cond(md) if cond: block = block[icond + 2] if block: render_blocks_(block, rendered, md, encoding) m = -1 break icond += 2 if icond == m: block = block[icond + 1] if block: render_blocks_(block, rendered, md, encoding) finally: md._pop() else: raise ValueError( 'Invalid DTML command code, %s', block[0]) elif not isinstance(block, (six.string_types, six.binary_type)): block = block(md) if append and block: rendered.append(block)
def test_bare_string_literall(self): from DocumentTemplate.ustr import ustr a = ustr('hello') self.assertEqual(a, 'hello')
def test_with_force_str_non_ascii_char(self): from DocumentTemplate.ustr import ustr a = ustr(force_str(chr(200))) self.assertEqual(a, chr(200))
def test_with_list(self): from DocumentTemplate.ustr import ustr a = ustr([1, 2, 3]) self.assertEqual(a, '[1, 2, 3]')
def html_quote(v, name='(Unknown name)', md={}, encoding=None): v = ustr(v) if six.PY3 and isinstance(v, six.binary_type): # decode using the old default if no encoding is passed v = v.decode(encoding or 'Latin-1') return escape(v, 1)
def testExceptions(self): a = ustr(ValueError(unichr(200))) assert a==unichr(200), `a`
def raise_standardErrorMessage(self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=re.compile(r'[a-zA-Z]>').search, error_log_url=''): try: if error_type is None: error_type = sys.exc_info()[0] if error_value is None: error_value = sys.exc_info()[1] # allow for a few different traceback options if tb is None and error_tb is None: tb = sys.exc_info()[2] if type(tb) is not type('') and (error_tb is None): error_tb = pretty_tb(error_type, error_value, tb) elif type(tb) is type('') and not error_tb: error_tb = tb # turn error_type into a string if hasattr(error_type, '__name__'): error_type = error_type.__name__ if hasattr(self, '_v_eek'): # Stop if there is recursion. raise error_type, error_value, tb self._v_eek = 1 if str(error_type).lower() in ('redirect', ): raise error_type, error_value, tb if not error_message: try: s = ustr(error_value) except: s = error_value try: match = tagSearch(s) except TypeError: match = None if match is not None: error_message = error_value if client is None: client = self if not REQUEST: REQUEST = self.aq_acquire('REQUEST') try: if hasattr(client, 'standard_error_message'): s = getattr(client, 'standard_error_message') else: client = client.aq_parent s = getattr(client, 'standard_error_message') kwargs = { 'error_type': error_type, 'error_value': error_value, 'error_tb': error_tb, 'error_traceback': error_tb, 'error_message': error_message, 'error_log_url': error_log_url } if getattr(aq_base(s), 'isDocTemp', 0): v = s(client, REQUEST, **kwargs) elif callable(s): v = s(**kwargs) else: v = HTML.__call__(s, client, REQUEST, **kwargs) except: logger.error('Exception while rendering an error message', exc_info=True) try: strv = str(error_value) except: strv = ('<unprintable %s object>' % str(type(error_value).__name__)) v = strv + ( (" (Also, the following error occurred while attempting " "to render the standard error message, please see the " "event log for full details: %s)") % (html_quote(sys.exc_info()[1]), )) raise error_type, v, tb finally: if hasattr(self, '_v_eek'): del self._v_eek tb = None
def test_w_chr(self): from DocumentTemplate.ustr import ustr a = ustr(chr(200)) self.assertEqual(a, chr(200))
def raise_standardErrorMessage( self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=re.compile(r'[a-zA-Z]>').search, error_log_url=''): try: if error_type is None: error_type =sys.exc_info()[0] if error_value is None: error_value=sys.exc_info()[1] # allow for a few different traceback options if tb is None and error_tb is None: tb=sys.exc_info()[2] if type(tb) is not type('') and (error_tb is None): error_tb = pretty_tb(error_type, error_value, tb) elif type(tb) is type('') and not error_tb: error_tb = tb # turn error_type into a string if hasattr(error_type, '__name__'): error_type=error_type.__name__ if hasattr(self, '_v_eek'): # Stop if there is recursion. raise error_type, error_value, tb self._v_eek=1 if str(error_type).lower() in ('redirect',): raise error_type, error_value, tb if not error_message: try: s = ustr(error_value) except: s = error_value try: match = tagSearch(s) except TypeError: match = None if match is not None: error_message=error_value if client is None: client=self if not REQUEST: REQUEST=self.aq_acquire('REQUEST') try: if hasattr(client, 'standard_error_message'): s=getattr(client, 'standard_error_message') else: client = client.aq_parent s=getattr(client, 'standard_error_message') kwargs = {'error_type': error_type, 'error_value': error_value, 'error_tb': error_tb, 'error_traceback': error_tb, 'error_message': error_message, 'error_log_url': error_log_url} if isinstance(s, HTML): v = s(client, REQUEST, **kwargs) elif callable(s): v = s(**kwargs) else: v = HTML.__call__(s, client, REQUEST, **kwargs) except: LOG('OFS', BLATHER, 'Exception while rendering an error message', error=sys.exc_info()) try: strv = str(error_value) except: strv = ('<unprintable %s object>' % str(type(error_value).__name__)) v = strv + ( " (Also, an error occurred while attempting " "to render the standard error message.)") raise error_type, v, tb finally: if hasattr(self, '_v_eek'): del self._v_eek tb=None
def test_RequestLike(self): from DocumentTemplate.ustr import ustr self.assertEqual(ustr(RequestLike()), "RequestLike")