Commits

Ralph Bean committed 730bf97

First pass with python-modernize.

Comments (0)

Files changed (10)

       package_data={'strainer': ['dtds/*']},
       zip_safe=True,
       install_requires=[
-          # -*- Extra requirements: -*-
+          'six',
       ],
       tests_require=[
           'nose',
                             break
                     else:
                         raise AttributeError('%s not found on %s' % (
-                            func.__name__, func.im_class.__name__))
+                            func.__name__, func.__self__.__class__.__name__))
                     superfunc = getattr(super(klass, self), func.__name__)
                     #superfunc is bound, so "self" is implied
                     #Args and KW needed?
                         superfunc(klass.__base__)
                     else:
                         superfunc()
-                except Exception, e:
+                except Exception as e:
                     if delay:
                         append_delayed_and_print_traceback(e)
                     else:
             #During
             try:
                 ret = func(self)
-            except Exception, e:
+            except Exception as e:
                 if delay:
                     append_delayed_and_print_traceback(e)
                 else:
     raised so that args can be checked'''
     try:
         ret = method(*args, **kwargs)
-    except exc, e:
+    except exc as e:
         return e
     else:
         raise AssertionError(

strainer/middleware.py

 """Provides WSGI middleware for validating and tidying HTML output."""
 import re
-import xhtmlify
+from . import xhtmlify
 import logging
 try:
     from cStringIO import StringIO
         return response
 
 try:
-    from validate import validate_xhtml, XHTMLSyntaxError
+    from .validate import validate_xhtml, XHTMLSyntaxError
 
     class XHTMLValidatorMiddleware(BufferingMiddleware):
         def __init__(self, app, doctype='', record_error=LOG.error):
             if content_type in ('text/html', 'application/xml+html'):
                 try:
                     validate_xhtml(response, doctype=self.doctype)
-                except XHTMLSyntaxError, e:
+                except XHTMLSyntaxError as e:
                     self.record_error(str(e))
             return response
 except ImportError:
         return response
 
 
-from wellformed import is_wellformed_xhtml, is_wellformed_xml
+from .wellformed import is_wellformed_xhtml, is_wellformed_xml
 
 
 class WellformednessCheckerMiddleware(BufferingMiddleware):
             is_wellformed_xml(response, record_error=self.record_error)
         return response
 
-from validate import validate_json, JSONSyntaxError
+from .validate import validate_json, JSONSyntaxError
 
 
 class JSONValidatorMiddleware(BufferingMiddleware):
         if content_type == 'text/json':
             try:
                 validate_json(response)
-            except JSONSyntaxError, e:
+            except JSONSyntaxError as e:
                 self.record_error(str(e))
         return response

strainer/operators.py

-from xhtmlify import xhtmlify, XMLParsingError, ValidationError
+from .xhtmlify import xhtmlify, XMLParsingError, ValidationError
 from xml.etree import ElementTree as etree
 from xml.parsers.expat import ExpatError
 import copy
 import re
 from pprint import pformat, pprint
+import six
 try:
     from simplejson import loads
 except ImportError:
     from json import loads
 
 from nose.tools import *
-from almostequal import approx_equal
+from .almostequal import approx_equal
 import strainer.log as log
 
 log = log.log
 
 def replace_escape_chars(needle):
     needle = needle.replace(' ', ' ')
-    needle = needle.replace(u'\xa0', ' ')
+    needle = needle.replace(six.u('\xa0'), ' ')
     return needle
 
 
     needle = xhtmlify(needle)
     try:
         needle_node = etree.fromstring(needle)
-    except ExpatError, e:
+    except ExpatError as e:
         raise XMLParsingError(
             'Could not parse %s into xml. %s' % (needle, e.args[0]))
     needle_node = remove_whitespace_nodes(needle_node)
 def in_xhtml(needle, haystack):
     try:
         needle_s = normalize_to_xhtml(needle)
-    except ValidationError, e:
+    except ValidationError as e:
         raise XMLParsingError(
             'Could not parse needle: %s into xml. %s' %
             (needle, e.message))
     try:
         haystack_s = normalize_to_xhtml(haystack)
-    except ValidationError, e:
+    except ValidationError as e:
         raise XMLParsingError(
             'Could not parse haystack: %s into xml. %s' %
             (haystack, e.message))
         haystack = '<div id="wrapper">%s</div>'
     try:
         needle_s = normalize_to_xhtml(needle)
-    except ValidationError, e:
+    except ValidationError as e:
         raise XMLParsingError(
             'Could not parse needle: %s into xml. %s' %
             (needle, e.message))
     try:
         haystack_s = normalize_to_xhtml(haystack)
-    except ValidationError, e:
+    except ValidationError as e:
         raise XMLParsingError(
             'Could not parse haystack: %s into xml. %s' %
             (haystack, e.message))
 def assert_raises(exc, method, *args, **kw):
     try:
         method(*args, **kw)
-    except exc, e:
+    except exc as e:
         return e
     else:
         raise AssertionError(

strainer/validate.py

         import lxml.etree
     try:
         lxml.etree.fromstring(doctype + xhtml, parser=_get_parser())
-    except lxml.etree.XMLSyntaxError, e:
+    except lxml.etree.XMLSyntaxError as e:
         # Try to fix up the error message so line numbers are
         # relative to xhtml.
         tline = doctype.count('\n')
     xhtml = doctype + (template % xhtml_fragment)
     try:
         lxml.etree.fromstring(xhtml, parser=_get_parser())
-    except lxml.etree.XMLSyntaxError, e:
+    except lxml.etree.XMLSyntaxError as e:
         # Try to fix up the error message so line numbers are
         # relative to the fragment.
         message = re.sub(r'line (\d+)',
     """Validates that json is a valid JSON string (by loading it)."""
     try:
         json.loads(jsonstr)
-    except ValueError, e:
+    except ValueError as e:
         raise JSONSyntaxError(str(e))

strainer/wellformed.py

         parser.feed(doc)
         parser.close()
         return True
-    except SAXParseException, e:
+    except SAXParseException as e:
         # catches our exception and other parse errors
         if record_error is not None:
             line, column = e.getLineNumber(), e.getColumnNumber()

strainer/xhtmlify.py

 #!/usr/bin/env python
 """An HTML to XHTML converter."""
+from __future__ import print_function
 import re
 import htmlentitydefs
 import codecs
 import encodings.aliases
+import six
 
 
 __all__ = [
     EOS = r'\Z'  # end of string regexp
     starts_utf16_re = re.compile('utf[_-]?16', re.IGNORECASE)
     bomless_utf16_re = re.compile('utf[_-]?16[_-]?[bl]e\Z', re.IGNORECASE)
-    unicode_input = isinstance(xml, unicode)
+    unicode_input = isinstance(xml, six.text_type)
     if not re.match(r'1\.[0-9]+' + EOS, default_version):
         raise ValueError("Bad default XML declaration version")
     if encoding is not None:
                 xml.startswith(codecs.BOM_UTF16_LE) or
                 xml.startswith(codecs.BOM_UTF16_BE)):
 
-                xml = u'\ufeff'.encode(encoding) + xml
+                xml = six.u('\ufeff').encode(encoding) + xml
             elif unicode_input and bomless_utf16_re.match(encoding):
-                xml = u'\ufeff' + xml
+                xml = six.u('\ufeff') + xml
             # "else: pass"; Python adds the BOM when encoding unicode as UTF-16
     if unicode_input:
         if encoding:
     if bomless_utf16_re.match(enc):
         # These need a BOM prefix according to the spec but the default
         # Python encodings of that name don't provide one.
-        prefix = encode(u'\ufeff')
+        prefix = encode(six.u('\ufeff'))
     else:
         prefix = encode('')
     chars_we_need = ('''abcdefghijklmnopqrstuvwxyz'''
     any = lambda *args: '(?:%s)*' % '|'.join(args)
     some = lambda *args: '(?:%s)+' % '|'.join(args)
     named = lambda name, regexp: '(?P<%s>%s)' % (name, regexp)
-    NameStartChar = (u'[:A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D'
-                     u'\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF'
-                     u'\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]')
-    if len(u'\U00010000') == 1:
-        NameStartChar = NameStartChar[:-1] + u'\U00010000-\U000EFFFF]'
-    NameChar = NameStartChar[:-1] + u"0-9\xB7\u0300-\u036F\u203F-\u2040\-]"
+    NameStartChar = (
+        six.u('[:A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D') +
+        six.u('\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF') +
+        six.u('\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]'))
+    if len(six.u('\U00010000')) == 1:
+        NameStartChar = NameStartChar[:-1] + six.u('\U00010000-\U000EFFFF]')
+    NameChar = NameStartChar[:-1] + six.u("0-9\xB7\u0300-\u036F\u203F-\u2040\-]")
     Name = NameStartChar + any(NameChar)
     Nmtoken = some(NameChar)
     quoted = oneof('"[^<>"]*"', "'[^<>']*'")
     html = fix_xmldecl(html, encoding=encoding, add_encoding=False)
     if not encoding:
         encoding = sniff_encoding(html)
-    unicode_input = isinstance(html, unicode)
+    unicode_input = isinstance(html, six.text_type)
     if unicode_input:
         html = html.encode(encoding, 'strict')
     if not isinstance(html, str):
         raise TypeError("Expected string, got %s" % type(html))
     html = html.decode(encoding, 'replace')
     # "in HTML, the Formfeed character (U+000C) is treated as white space"
-    html = html.replace(u'\u000C', u' ')
+    html = html.replace(six.u('\u000C'), six.u(' '))
     # Replace disallowed characters with U+FFFD (unicode replacement char)
-    if len(u'\U00010000') == 1:
+    if len(six.u('\U00010000')) == 1:
         html = re.sub(  # XML 1.0 section 2.2, "Char" production
-            u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD'
-              u'\U00010000-\U0010FFFF]',  # <-- 32 bit characters
-            u'\N{replacement character}', html)
+            six.u('[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD') +
+              six.u('\U00010000-\U0010FFFF]'),  # <-- 32 bit characters
+            six.u('\N{replacement character}'), html)
     else:
         # Replace 32-bit characters, this Python build doesn't support them
         html = re.sub(  # XML 1.0 section 2.2, "Char" production
-            u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]',
-            u'\N{replacement character}', html)
+            six.u('[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]'),
+            six.u('\N{replacement character}'), html)
 
     def ERROR(message, charpos=None):
         if charpos is None:
     # Output the XML declaration and doctype, if they exist.
     doctype, lastpos = fix_doctype(html)
     output(doctype)
-    if html.startswith('<?xml') or html.startswith(u'\ufeff<?xml'):
+    if html.startswith('<?xml') or html.startswith(six.u('\ufeff<?xml')):
         pos = html.find('>') + 1
         if not doctype:
             output(html[:pos])
     try:
         assert xhtml == xhtmlify(xhtml)
     except ValidationError:
-        print xhtml
+        print(xhtml)
         raise
     xmlparse(re.sub('(?s)<!(?!\[).*?>', '', xhtml))  # ET can't handle <!...>
     if len(sys.argv) == 2:
     from xml.etree import ElementTree as ET
     if wrap is None:
         wrap = (not snippet.startswith('<?xml') and
-                not snippet.startswith(u'\ufeff<?xml'))
+                not snippet.startswith(six.u('\ufeff<?xml')))
     try:
         if encoding:
             try:
             input = '<document>\n%s\n</document>' % snippet
         else:
             input = snippet
-        if isinstance(snippet, unicode):
+        if isinstance(snippet, six.text_type):
             if not encoding:
                 encoding = sniff_encoding(snippet)
             input = input.encode(encoding)
         parser.feed(input)
         parser.close()
-    except xml.parsers.expat.ExpatError, e:
+    except xml.parsers.expat.ExpatError as e:
         lineno, offset = e.lineno, e.offset
         lineno -= 1
         if lineno == input.count('\n'):  # last line => </document>
     encode = codecs.lookup(enc).incrementalencoder().encode
     prefix = encode('')  # any header such as a UTF-8 BOM
     if enc in ('utf_16_le', 'utf_16_be'):
-        prefix = u'\ufeff'.encode(enc)  # the standard approach fails
+        prefix = six.u('\ufeff').encode(enc)  # the standard approach fails
     L = lambda s: re.escape(encode(s))  # encoded form of literal s
     optional = lambda s: '(?:%s)?' % s
     oneof = lambda opts: '(?:%s)' % '|'.join(opts)

tests/test_case.py

+from __future__ import print_function
 import sys
 from strainer.case import call_super, STestCase, DelayedException
 from nose.tools import eq_, raises
         self.capture_stdout()
 
     def _call(self, name):
-        print name
+        print(name)
     
     def foo(self):
         """There is no superclass here"""
     def testBrokeBar(self):
         try:
             self.broke_bar()
-        except DelayedException, e:
+        except DelayedException as e:
             eq_(self.output.getvalue(), 'broke_bar1\nbroke_bar0\n')
         else:
             self.fail('broke_bar should have raised a DelayedException')

tests/test_validate.py

 def test_validate_invalid_xhtml():
     try:
         validate_xhtml('<html/>', doctype=DOCTYPE_XHTML1_STRICT)
-    except XHTMLSyntaxError, e:
+    except XHTMLSyntaxError as e:
         assert 'line 1, column 8' in e.message, e.message
         assert 'Element html content does not follow the DTD' in e.message
         assert 'expecting (head, body)' in e.message.replace(' ,', ',')
 def test_validate_invalid_xhtml_fragment():
     try:
         validate_xhtml_fragment('</p>')
-    except XHTMLSyntaxError, e:
+    except XHTMLSyntaxError as e:
         assert e.message==('Opening and ending tag mismatch: '
                            'div line 0 and p, line 1, column 5'), e.message

tests/test_xhtmlify.py

 from strainer.xhtmlify import xhtmlify as _xhtmlify, xmlparse, ValidationError
 from strainer.xhtmlify import sniff_encoding, fix_xmldecl
 from strainer.doctypes import DOCTYPE_XHTML1_STRICT
+import six
 
 
 def xhtmlify(html, *args, **kwargs):
         # ET can't handle <!...>
         stripped_xhtml = re.sub(r'(?s)<!(?!\[).*?>', '', xhtml)
         xmlparse(stripped_xhtml, wrap=_wrap)
-    except Exception, e:
+    except Exception as e:
         assert False, (stripped_xhtml, str(e))
     assert xhtml == _xhtmlify(xhtml, *args, **kwargs), xhtml
     return xhtml
     e = '<p><b><i>test</i></b></p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<p></p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<!-- test -->'  # TODO: what to do about < and > in comments?
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
          '''content =\n"text/html;charset=utf-8" />''')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, repr(r)
     e = '''<p id="a" class="b"><br id="d/" /></p>'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, repr(r)
     e_exc = "Malformed tag contents at line 1, column 10 (char 10)"
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e = '''<a\tb="&quot;b">c'\t&gt;</a>'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, repr(r)
     e = '<p/>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, repr(r)
     e_exc = "Unexpected closing tag </p> at line 1, column 11 (char 11)"
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e = '<p id="foo" class=\'bar\'><input value="TesT" /></p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'''<img alt='"' /><img alt='&quot;' />'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'''<img alt="'" /><img alt='&apos;' />'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'''<img alt="&quot;" />'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'''<img alt="'" />'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'''<img alt="&lt;"/>'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'''<img alt='&lt;'/>'''
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<br /><input value="test" /><input id="x" value="test"  />'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<p></p><p></p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<p><div></div></p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<h1><p></p></h1>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<ul><li></li></ul>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<ol><li></li></ol>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<tr><td></td></tr>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<tr><th></th></tr>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<p title="&amp;">&amp;</p><p>&amp;</p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e_exc = 'Unescaped "<" or unfinished tag at line 1, column 1 (char 1)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e_exc = 'Unescaped "<" or unfinished tag at line 1, column 4 (char 4)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e = '&gt;'  # '>' would strictly be ok too...
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = "<p>'</p><p>&apos;</p>"
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<p>"</p><p>&quot;</p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<p>&#x20ac;</p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<p>&amp;nosuch;</p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = ']]&gt;'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     # would break our rule of only making changes where necessary.
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e_exc = 'Unescaped "<" or unfinished tag at line 1, column 4 (char 4)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e = '<script>/* test */</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script> 1 /*<![CDATA[*/ < /*]]>*/ 2 </script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script> 1 /*<![CDATA[*/ > /*]]>*/ 2 </script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script> 1 /*<![CDATA[*/ & /*]]>*/ 2 </script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>var amp=2; amp += 3 /*<![CDATA[*/ & /*]]>*/amp;</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>/* <![CDATA[<]]> */</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>/* <![CDATA[>]]> */</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>/* <![CDATA[&]]> */</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>// /*<![CDATA[*/ < /*]]>*/ </script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>// /*<![CDATA[*/ > /*]]>*/ </script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>// /*<![CDATA[*/ & /*]]>*/ </script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>/* <![CDATA[x]]> ]]<![CDATA[>]]> */</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = '<script>// <![CDATA[x]]> ]]/*<![CDATA[*/ > /*]]>*/ </script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script> " \"\x%02x " </script>' % ord('<')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script> " \"\x%02x " </script>' % ord('>')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script> " \"\x%02x " </script>' % ord('&')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script> " \x%02x " </script>' % ord('<')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script> " \x%02x " </script>' % ord('>')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script> ' \'\x%02x ' </script>" % ord('<')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script> ' \'\x%02x ' </script>" % ord('>')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script> ' \'\x%02x ' </script>" % ord('&')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script> <![CDATA['x ]]>\x%02x ' </script>" % ord('&')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script> ' \x%02x ' </script>" % ord('<')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script> ' \x%02x ' </script>" % ord('>')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script><![CDATA[</script>]]></script>"
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script>"\x%02x]]\x%02x"</script>' % (ord('<'), ord('>'))
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script>/*<![CDATA[*/ < /*]]>*/evil/*<![CDATA[*/ > /*]]>*/</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script>document.write("\x3cb\x3e");</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script>document.write('\x3cb\x3e');</script>"
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r"<script>/* <![CDATA[<]]>evil<![CDATA[>]]> */</script>"
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<script>/*<![CDATA[*/ < /*]]>*/evil/*<![CDATA[*/ > /*]]>*/</script>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e_exc = 'Malformed tag at line 1, column 1 (char 1)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e_exc = 'Malformed tag at line 1, column 4 (char 4)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e = r'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<p>&amp;#7;</p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e_exc = 'Repeated attribute "style" at line 1, column 38 (char 38)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e = r'<option selected="selected"></option>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<p x=":;&quot;/"><img /></p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<py:test xmlns:py="..."/>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e_exc = r'Malformed tag at line 1, column 1 (char 1)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     e = r'this<p>is<a href="..">a test</a></p>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e = r'<html xmlns="http://www.w3.org/1999/xhtml"><body>Test</body></html>'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert False, exc
     else:
         assert r==e, r
     e_exc = r'Malformed tag at line 1, column 1 (char 1)'
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
     for i, (s, e) in enumerate(tests):
         try:
             r = sniff_encoding(s)
-        except ValidationError, exc:
+        except ValidationError as exc:
             assert False, (exc, i)
         else:
             assert r==e, (r, i)
 
 def test_sniffer_exc():
-    s = u'<?xml version="1.0" encoding="Cp037" ?>'.encode('utf-8-sig')
+    s = six.u('<?xml version="1.0" encoding="Cp037" ?>').encode('utf-8-sig')
     e_exc = r'Multiply-specified encoding (BOM: utf_8_sig, XML decl: Cp037) at line 1, column 1 (char 1)'
     try:
         r = sniff_encoding(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc)==e_exc, exc
     else:
         assert False, r
             ''.encode(encoding)
         except LookupError:  # not trying to handle unknown encodings yet
             continue
-        xmldecl = fix_xmldecl(u'  <?xml>', encoding, add_encoding=True)
+        xmldecl = fix_xmldecl(six.u('  <?xml>'), encoding, add_encoding=True)
         if encoding.lower().startswith('utf'):
             if '16' in encoding:
                 if 'le' in encoding.lower():
                     assert xmldecl.startswith(codecs.BOM_UTF16_BE)
         sniffed = sniff_encoding(xmldecl)
         assert sniffed==encoding, (xmldecl, encoding, sniffed)
-        xmldecl = fix_xmldecl(u'  <?xml>'.encode(encoding), encoding,
+        xmldecl = fix_xmldecl(six.u('  <?xml>').encode(encoding), encoding,
                               add_encoding=True)
         if encoding.lower().startswith('utf'):
             if '16' in encoding:
         '''<?xml version="1.0"  standalone='no'  ?>'''), xmldecl
 
 def test_xhtmlify_handles_utf8_xmldecl():
-    result = xhtmlify(u'<?xml><html>', 'utf-8', _wrap=False)
-    assert result.decode('utf-8')==u'<?xml version=\'1.0\'?><html xmlns="http://www.w3.org/1999/xhtml"></html>'
+    result = xhtmlify(six.u('<?xml><html>'), 'utf-8', _wrap=False)
+    assert result.decode('utf-8')==six.u('<?xml version=\'1.0\'?><html xmlns="http://www.w3.org/1999/xhtml"></html>')
 
 def test_xhtmlify_handles_utf16_xmldecl():
-    result = xhtmlify(u'<?xml><html>', 'utf_16_be', _wrap=False)
-    assert result.decode('utf16')==u'<?xml version=\'1.0\'?><html xmlns="http://www.w3.org/1999/xhtml"></html>'
+    result = xhtmlify(six.u('<?xml><html>'), 'utf_16_be', _wrap=False)
+    assert result.decode('utf16')==six.u('<?xml version=\'1.0\'?><html xmlns="http://www.w3.org/1999/xhtml"></html>')
 
 def test_doctype():
     s = r'''<?xml version="1.0" encoding="ISO-8859-1"?>
     assert s[110:].startswith('<!DOCTYPE ')
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc).startswith(
             'Malformed tag at line 2, column 1 (char 111)'), exc
     else:
     assert s[122:].startswith('<!DOCTYPE '), s[122:]
     try:
         r = xhtmlify(s)
-    except ValidationError, exc:
+    except ValidationError as exc:
         assert str(exc).startswith(
             'Malformed tag at line 2, column 13 (char 123)'), exc
     else:
             e_exc %= (parent, child)
             try:
                 r = xhtmlify(s)
-            except ValidationError, e:
+            except ValidationError as e:
                 assert str(e).startswith(e_exc + ' at line 1'), (s, e)
             else:
                 assert False, (s, r)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.