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