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