html5lib_adapter_test.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # Copyright 2012 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. """Tests for the Gumbo => Html5lib adapter."""
  16. import codecs
  17. import collections
  18. import glob
  19. import os
  20. import re
  21. import StringIO
  22. import unittest
  23. import warnings
  24. from html5lib import treebuilders
  25. import html5lib_adapter
  26. TREEBUILDER = treebuilders.getTreeBuilder('dom')
  27. TESTDATA_BASE_PATH = os.path.join(
  28. os.path.split(__file__)[0], '..', '..')
  29. # Copied from html5lib.tests/test_parser.py
  30. def convertTreeDump(data):
  31. return "\n".join(convertExpected(data, 3).split("\n")[1:])
  32. # Copied/adapted/simplified from html5lib.tests/support.py
  33. def html5lib_test_files():
  34. return glob.glob(os.path.join(
  35. TESTDATA_BASE_PATH, 'testdata', 'tree-construction', '*.dat'))
  36. class TestData(object):
  37. def __init__(self, filename):
  38. self.f = codecs.open(filename, encoding="utf8")
  39. def __iter__(self):
  40. data = collections.defaultdict(lambda: None)
  41. key=None
  42. for line in self.f:
  43. heading = self.isSectionHeading(line)
  44. if heading:
  45. if data and heading == 'data':
  46. #Remove trailing newline
  47. data[key] = data[key][:-1]
  48. yield self.normaliseOutput(data)
  49. data = collections.defaultdict(lambda: None)
  50. key = heading
  51. data[key] = ''
  52. elif key is not None:
  53. data[key] += line
  54. if data:
  55. yield self.normaliseOutput(data)
  56. def isSectionHeading(self, line):
  57. """If the current heading is a test section heading return the heading,
  58. otherwise return False"""
  59. if line.startswith("#"):
  60. return line[1:].strip()
  61. else:
  62. return False
  63. def normaliseOutput(self, data):
  64. # Remove trailing newlines
  65. for key, value in data.iteritems():
  66. if value.endswith("\n"):
  67. data[key] = value[:-1]
  68. return data
  69. def convertExpected(data, stripChars):
  70. """convert the output of str(document) to the format used in the testcases"""
  71. data = data.split("\n")
  72. rv = []
  73. for line in data:
  74. if line.startswith("|"):
  75. rv.append(line[stripChars:])
  76. else:
  77. rv.append(line)
  78. return "\n".join(rv)
  79. def reformatTemplateContents(expected):
  80. lines = expected.split('\n')
  81. retval = []
  82. template_indents = []
  83. for line in lines:
  84. line_stripped = line.strip()
  85. indent = len(line) - len(line_stripped)
  86. if line_stripped == 'content':
  87. template_indents.append(indent)
  88. continue
  89. while template_indents and indent <= template_indents[-1]:
  90. template_indents.pop()
  91. if template_indents:
  92. line = line[2 * len(template_indents):]
  93. retval.append(line)
  94. return '\n'.join(retval)
  95. class Html5libAdapterTest(unittest.TestCase):
  96. """Adapter between Gumbo and the html5lib tests.
  97. This works through a bit of magic. It's an empty class at first, but then
  98. buildTestCases runs through the test files in html5lib, and adds a
  99. method to this class for each one. That method acts like
  100. test_parser.TestCase.runParserTest, running a parse, serializing the tree, and
  101. comparing it to the expected output.
  102. The vague name is so nosetests doesn't try to run it as a test.
  103. """
  104. def impl(self, inner_html, input, expected, errors):
  105. p = html5lib_adapter.HTMLParser(
  106. tree=TREEBUILDER(namespaceHTMLElements=True))
  107. if inner_html:
  108. document = p.parseFragment(
  109. StringIO.StringIO(input), inner_html.replace('math ', 'mathml '))
  110. else:
  111. document = p.parse(StringIO.StringIO(input))
  112. with warnings.catch_warnings():
  113. # Etree serializer in html5lib uses a deprecated getchildren() API.
  114. warnings.filterwarnings('ignore', category=DeprecationWarning)
  115. output = convertTreeDump(p.tree.testSerializer(document))
  116. expected = re.compile(r'^(\s*)<(\S+)>', re.M).sub(
  117. r'\1<html \2>', convertExpected(expected, 2))
  118. # html5lib doesn't yet support the template tag, but it appears in the
  119. # tests with the expectation that the template contents will be under the
  120. # word 'contents', so we need to reformat that string a bit.
  121. expected = reformatTemplateContents(expected)
  122. error_msg = '\n'.join(['\n\nInput:', input, '\nExpected:', expected,
  123. '\nReceived:', output])
  124. self.assertEquals(expected, output,
  125. error_msg.encode('ascii', 'xmlcharrefreplace') + '\n')
  126. # TODO(jdtang): Check error messages, when there's full error support.
  127. def BuildTestCases(cls):
  128. for filename in html5lib_test_files():
  129. test_name = os.path.basename(filename).replace('.dat', '')
  130. for i, test in enumerate(TestData(filename)):
  131. # html5lib parses <noscript> tags as if the scripting-enabled flag is
  132. # set, while we parse as if the scripting-disabled flag is set (since we
  133. # don't really support scripting and the resulting parse tree is often
  134. # more useful for toolsmiths). That means our output will differ by
  135. # design from html5lib's, so we disable any of their tests that involve
  136. # <noscript>
  137. if '<noscript>' in test['data']:
  138. continue
  139. # <command> has been renamed to <menuitem> in recent versions of the spec.
  140. # html5lib 0.95 does not include this yet, and so we disable tests that
  141. # include the old tag.
  142. if '<command>' in test['data']:
  143. continue
  144. def test_func(
  145. self,
  146. inner_html=test['document-fragment'],
  147. input=test['data'],
  148. expected=test['document'],
  149. errors=test.get('errors', '').split('\n')):
  150. return self.impl(inner_html, input, expected, errors)
  151. test_func.__name__ = 'test_%s_%d' % (test_name, i + 1)
  152. setattr(cls, test_func.__name__, test_func)
  153. if __name__ == '__main__':
  154. BuildTestCases(Html5libAdapterTest)
  155. unittest.main()