aboutsummaryrefslogtreecommitdiff
path: root/test/normalize.py
blob: 5b4803bc135088f0832e9360c1d6340ba54494f4 (plain)
  1. # -*- coding: utf-8 -*-
  2. from HTMLParser import HTMLParser, HTMLParseError
  3. from htmlentitydefs import name2codepoint
  4. import sys
  5. import re
  6. import cgi
  7. # Normalization code, adapted from
  8. # https://github.com/karlcow/markdown-testsuite/
  9. significant_attrs = ["alt", "href", "src", "title"]
  10. whitespace_re = re.compile('\s+')
  11. class MyHTMLParser(HTMLParser):
  12. def __init__(self):
  13. HTMLParser.__init__(self)
  14. self.last = "starttag"
  15. self.in_pre = False
  16. self.output = u""
  17. self.last_tag = ""
  18. def handle_data(self, data):
  19. after_tag = self.last == "endtag" or self.last == "starttag"
  20. after_block_tag = after_tag and self.is_block_tag(self.last_tag)
  21. if after_tag and self.last_tag == "br":
  22. data = data.lstrip('\n')
  23. data = whitespace_re.sub(' ', data)
  24. if after_block_tag and not self.in_pre:
  25. if self.last == "starttag":
  26. data = data.lstrip()
  27. elif self.last == "endtag":
  28. data = data.strip()
  29. self.output += data
  30. self.last = "data"
  31. def handle_endtag(self, tag):
  32. if tag == "pre":
  33. self.in_pre = False
  34. if self.is_block_tag(tag):
  35. self.output = self.output.rstrip()
  36. self.output += "</" + tag + ">"
  37. self.last_tag = tag
  38. self.last = "endtag"
  39. def handle_starttag(self, tag, attrs):
  40. if tag == "pre":
  41. self.in_pre = True
  42. self.output += "<" + tag
  43. # For now we don't strip out 'extra' attributes, because of
  44. # raw HTML test cases.
  45. # attrs = filter(lambda attr: attr[0] in significant_attrs, attrs)
  46. if attrs:
  47. attrs.sort()
  48. for (k,v) in attrs:
  49. self.output += " " + k
  50. if v != None:
  51. self.output += ("=" + '"' + cgi.escape(v,quote=True) + '"')
  52. self.output += ">"
  53. self.last_tag = tag
  54. self.last = "starttag"
  55. def handle_startendtag(self, tag, attrs):
  56. """Ignore closing tag for self-closing """
  57. self.handle_starttag(tag, attrs)
  58. self.last_tag = tag
  59. self.last = "endtag"
  60. def handle_comment(self, data):
  61. self.output += '<!--' + data + '-->'
  62. self.last = "comment"
  63. def handle_decl(self, data):
  64. self.output += '<!' + data + '>'
  65. self.last = "decl"
  66. def unknown_decl(self, data):
  67. self.output += '<!' + data + '>'
  68. self.last = "decl"
  69. def handle_pi(self,data):
  70. self.output += '<?' + data + '>'
  71. self.last = "pi"
  72. def handle_entityref(self, name):
  73. try:
  74. c = unichr(name2codepoint[name])
  75. except KeyError:
  76. c = None
  77. self.output_char(c, '&' + name + ';')
  78. self.last = "ref"
  79. def handle_charref(self, name):
  80. try:
  81. if name.startswith("x"):
  82. c = unichr(int(name[1:], 16))
  83. else:
  84. c = unichr(int(name))
  85. except ValueError:
  86. c = None
  87. self.output_char(c, '&' + name + ';')
  88. self.last = "ref"
  89. # Helpers.
  90. def output_char(self, c, fallback):
  91. if c == u'<':
  92. self.output += "&lt;"
  93. elif c == u'>':
  94. self.output += "&gt;"
  95. elif c == u'&':
  96. self.output += "&amp;"
  97. elif c == u'"':
  98. self.output += "&quot;"
  99. elif c == None:
  100. self.output += fallback
  101. else:
  102. self.output += c
  103. def is_block_tag(self,tag):
  104. return (tag in ['article', 'header', 'aside', 'hgroup', 'blockquote',
  105. 'hr', 'iframe', 'body', 'li', 'map', 'button', 'object', 'canvas',
  106. 'ol', 'caption', 'output', 'col', 'p', 'colgroup', 'pre', 'dd',
  107. 'progress', 'div', 'section', 'dl', 'table', 'td', 'dt',
  108. 'tbody', 'embed', 'textarea', 'fieldset', 'tfoot', 'figcaption',
  109. 'th', 'figure', 'thead', 'footer', 'tr', 'form', 'ul',
  110. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'video', 'script', 'style'])
  111. def normalize_html(html):
  112. r"""
  113. Return normalized form of HTML which ignores insignificant output
  114. differences:
  115. Multiple inner whitespaces are collapsed to a single space (except
  116. in pre tags):
  117. >>> normalize_html("<p>a \t b</p>")
  118. u'<p>a b</p>'
  119. >>> normalize_html("<p>a \t\nb</p>")
  120. u'<p>a b</p>'
  121. * Outer whitespace (outside block-level tags) is removed.
  122. >>> normalize_html("<p>a b</p> ")
  123. u'<p>a b</p>'
  124. * Self-closing tags are converted to open tags.
  125. >>> normalize_html("<br />")
  126. u'<br>'
  127. * Attributes are sorted and lowercased.
  128. >>> normalize_html('<a title="bar" HREF="foo">x</a>')
  129. u'<a href="foo" title="bar">x</a>'
  130. * References are converted to unicode, except that '<', '>', '&', and
  131. '"' are rendered using entities.
  132. >>> normalize_html("&forall;&amp;&gt;&lt;&quot;")
  133. u'\u2200&amp;&gt;&lt;&quot;'
  134. """
  135. html_chunk_re = re.compile("(\<!\[CDATA\[.*?\]\]\>|\<[^>]*\>|[^<]+)")
  136. try:
  137. parser = MyHTMLParser()
  138. # We work around HTMLParser's limitations parsing CDATA
  139. # by breaking the input into chunks and passing CDATA chunks
  140. # through verbatim.
  141. for chunk in re.finditer(html_chunk_re, html):
  142. if chunk.group(0)[:8] == "<![CDATA":
  143. parser.output += chunk.group(0)
  144. else:
  145. parser.feed(chunk.group(0).decode(encoding='UTF-8'))
  146. parser.close()
  147. return parser.output
  148. except HTMLParseError as e:
  149. sys.stderr.write("Normalization error: " + e.msg + "\n")
  150. return html # on error, return unnormalized HTML