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