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