PageRenderTime 40ms CodeModel.GetById 5ms RepoModel.GetById 0ms app.codeStats 0ms

/web/lib/bs4/testing.py

https://gitlab.com/adam.lukaitis/muzei
Python | 592 lines | 505 code | 41 blank | 46 comment | 4 complexity | 24a0a90ea82dd7bf3a73ee09c36c0b85 MD5 | raw file
  1. """Helper classes for tests."""
  2. import copy
  3. import functools
  4. import unittest
  5. from unittest import TestCase
  6. from bs4 import BeautifulSoup
  7. from bs4.element import (
  8. CharsetMetaAttributeValue,
  9. Comment,
  10. ContentMetaAttributeValue,
  11. Doctype,
  12. SoupStrainer,
  13. )
  14. from bs4.builder import HTMLParserTreeBuilder
  15. default_builder = HTMLParserTreeBuilder
  16. class SoupTest(unittest.TestCase):
  17. @property
  18. def default_builder(self):
  19. return default_builder()
  20. def soup(self, markup, **kwargs):
  21. """Build a Beautiful Soup object from markup."""
  22. builder = kwargs.pop('builder', self.default_builder)
  23. return BeautifulSoup(markup, builder=builder, **kwargs)
  24. def document_for(self, markup):
  25. """Turn an HTML fragment into a document.
  26. The details depend on the builder.
  27. """
  28. return self.default_builder.test_fragment_to_document(markup)
  29. def assertSoupEquals(self, to_parse, compare_parsed_to=None):
  30. builder = self.default_builder
  31. obj = BeautifulSoup(to_parse, builder=builder)
  32. if compare_parsed_to is None:
  33. compare_parsed_to = to_parse
  34. self.assertEqual(obj.decode(), self.document_for(compare_parsed_to))
  35. class HTMLTreeBuilderSmokeTest(object):
  36. """A basic test of a treebuilder's competence.
  37. Any HTML treebuilder, present or future, should be able to pass
  38. these tests. With invalid markup, there's room for interpretation,
  39. and different parsers can handle it differently. But with the
  40. markup in these tests, there's not much room for interpretation.
  41. """
  42. def assertDoctypeHandled(self, doctype_fragment):
  43. """Assert that a given doctype string is handled correctly."""
  44. doctype_str, soup = self._document_with_doctype(doctype_fragment)
  45. # Make sure a Doctype object was created.
  46. doctype = soup.contents[0]
  47. self.assertEqual(doctype.__class__, Doctype)
  48. self.assertEqual(doctype, doctype_fragment)
  49. self.assertEqual(str(soup)[:len(doctype_str)], doctype_str)
  50. # Make sure that the doctype was correctly associated with the
  51. # parse tree and that the rest of the document parsed.
  52. self.assertEqual(soup.p.contents[0], 'foo')
  53. def _document_with_doctype(self, doctype_fragment):
  54. """Generate and parse a document with the given doctype."""
  55. doctype = '<!DOCTYPE %s>' % doctype_fragment
  56. markup = doctype + '\n<p>foo</p>'
  57. soup = self.soup(markup)
  58. return doctype, soup
  59. def test_normal_doctypes(self):
  60. """Make sure normal, everyday HTML doctypes are handled correctly."""
  61. self.assertDoctypeHandled("html")
  62. self.assertDoctypeHandled(
  63. 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"')
  64. def test_empty_doctype(self):
  65. soup = self.soup("<!DOCTYPE>")
  66. doctype = soup.contents[0]
  67. self.assertEqual("", doctype.strip())
  68. def test_public_doctype_with_url(self):
  69. doctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"'
  70. self.assertDoctypeHandled(doctype)
  71. def test_system_doctype(self):
  72. self.assertDoctypeHandled('foo SYSTEM "http://www.example.com/"')
  73. def test_namespaced_system_doctype(self):
  74. # We can handle a namespaced doctype with a system ID.
  75. self.assertDoctypeHandled('xsl:stylesheet SYSTEM "htmlent.dtd"')
  76. def test_namespaced_public_doctype(self):
  77. # Test a namespaced doctype with a public id.
  78. self.assertDoctypeHandled('xsl:stylesheet PUBLIC "htmlent.dtd"')
  79. def test_real_xhtml_document(self):
  80. """A real XHTML document should come out more or less the same as it went in."""
  81. markup = b"""<?xml version="1.0" encoding="utf-8"?>
  82. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
  83. <html xmlns="http://www.w3.org/1999/xhtml">
  84. <head><title>Hello.</title></head>
  85. <body>Goodbye.</body>
  86. </html>"""
  87. soup = self.soup(markup)
  88. self.assertEqual(
  89. soup.encode("utf-8").replace(b"\n", b""),
  90. markup.replace(b"\n", b""))
  91. def test_deepcopy(self):
  92. """Make sure you can copy the tree builder.
  93. This is important because the builder is part of a
  94. BeautifulSoup object, and we want to be able to copy that.
  95. """
  96. copy.deepcopy(self.default_builder)
  97. def test_p_tag_is_never_empty_element(self):
  98. """A <p> tag is never designated as an empty-element tag.
  99. Even if the markup shows it as an empty-element tag, it
  100. shouldn't be presented that way.
  101. """
  102. soup = self.soup("<p/>")
  103. self.assertFalse(soup.p.is_empty_element)
  104. self.assertEqual(str(soup.p), "<p></p>")
  105. def test_unclosed_tags_get_closed(self):
  106. """A tag that's not closed by the end of the document should be closed.
  107. This applies to all tags except empty-element tags.
  108. """
  109. self.assertSoupEquals("<p>", "<p></p>")
  110. self.assertSoupEquals("<b>", "<b></b>")
  111. self.assertSoupEquals("<br>", "<br/>")
  112. def test_br_is_always_empty_element_tag(self):
  113. """A <br> tag is designated as an empty-element tag.
  114. Some parsers treat <br></br> as one <br/> tag, some parsers as
  115. two tags, but it should always be an empty-element tag.
  116. """
  117. soup = self.soup("<br></br>")
  118. self.assertTrue(soup.br.is_empty_element)
  119. self.assertEqual(str(soup.br), "<br/>")
  120. def test_nested_formatting_elements(self):
  121. self.assertSoupEquals("<em><em></em></em>")
  122. def test_comment(self):
  123. # Comments are represented as Comment objects.
  124. markup = "<p>foo<!--foobar-->baz</p>"
  125. self.assertSoupEquals(markup)
  126. soup = self.soup(markup)
  127. comment = soup.find(text="foobar")
  128. self.assertEqual(comment.__class__, Comment)
  129. # The comment is properly integrated into the tree.
  130. foo = soup.find(text="foo")
  131. self.assertEqual(comment, foo.next_element)
  132. baz = soup.find(text="baz")
  133. self.assertEqual(comment, baz.previous_element)
  134. def test_preserved_whitespace_in_pre_and_textarea(self):
  135. """Whitespace must be preserved in <pre> and <textarea> tags."""
  136. self.assertSoupEquals("<pre> </pre>")
  137. self.assertSoupEquals("<textarea> woo </textarea>")
  138. def test_nested_inline_elements(self):
  139. """Inline elements can be nested indefinitely."""
  140. b_tag = "<b>Inside a B tag</b>"
  141. self.assertSoupEquals(b_tag)
  142. nested_b_tag = "<p>A <i>nested <b>tag</b></i></p>"
  143. self.assertSoupEquals(nested_b_tag)
  144. double_nested_b_tag = "<p>A <a>doubly <i>nested <b>tag</b></i></a></p>"
  145. self.assertSoupEquals(nested_b_tag)
  146. def test_nested_block_level_elements(self):
  147. """Block elements can be nested."""
  148. soup = self.soup('<blockquote><p><b>Foo</b></p></blockquote>')
  149. blockquote = soup.blockquote
  150. self.assertEqual(blockquote.p.b.string, 'Foo')
  151. self.assertEqual(blockquote.b.string, 'Foo')
  152. def test_correctly_nested_tables(self):
  153. """One table can go inside another one."""
  154. markup = ('<table id="1">'
  155. '<tr>'
  156. "<td>Here's another table:"
  157. '<table id="2">'
  158. '<tr><td>foo</td></tr>'
  159. '</table></td>')
  160. self.assertSoupEquals(
  161. markup,
  162. '<table id="1"><tr><td>Here\'s another table:'
  163. '<table id="2"><tr><td>foo</td></tr></table>'
  164. '</td></tr></table>')
  165. self.assertSoupEquals(
  166. "<table><thead><tr><td>Foo</td></tr></thead>"
  167. "<tbody><tr><td>Bar</td></tr></tbody>"
  168. "<tfoot><tr><td>Baz</td></tr></tfoot></table>")
  169. def test_deeply_nested_multivalued_attribute(self):
  170. # html5lib can set the attributes of the same tag many times
  171. # as it rearranges the tree. This has caused problems with
  172. # multivalued attributes.
  173. markup = '<table><div><div class="css"></div></div></table>'
  174. soup = self.soup(markup)
  175. self.assertEqual(["css"], soup.div.div['class'])
  176. def test_angle_brackets_in_attribute_values_are_escaped(self):
  177. self.assertSoupEquals('<a b="<a>"></a>', '<a b="&lt;a&gt;"></a>')
  178. def test_entities_in_attributes_converted_to_unicode(self):
  179. expect = u'<p id="pi\N{LATIN SMALL LETTER N WITH TILDE}ata"></p>'
  180. self.assertSoupEquals('<p id="pi&#241;ata"></p>', expect)
  181. self.assertSoupEquals('<p id="pi&#xf1;ata"></p>', expect)
  182. self.assertSoupEquals('<p id="pi&#Xf1;ata"></p>', expect)
  183. self.assertSoupEquals('<p id="pi&ntilde;ata"></p>', expect)
  184. def test_entities_in_text_converted_to_unicode(self):
  185. expect = u'<p>pi\N{LATIN SMALL LETTER N WITH TILDE}ata</p>'
  186. self.assertSoupEquals("<p>pi&#241;ata</p>", expect)
  187. self.assertSoupEquals("<p>pi&#xf1;ata</p>", expect)
  188. self.assertSoupEquals("<p>pi&#Xf1;ata</p>", expect)
  189. self.assertSoupEquals("<p>pi&ntilde;ata</p>", expect)
  190. def test_quot_entity_converted_to_quotation_mark(self):
  191. self.assertSoupEquals("<p>I said &quot;good day!&quot;</p>",
  192. '<p>I said "good day!"</p>')
  193. def test_out_of_range_entity(self):
  194. expect = u"\N{REPLACEMENT CHARACTER}"
  195. self.assertSoupEquals("&#10000000000000;", expect)
  196. self.assertSoupEquals("&#x10000000000000;", expect)
  197. self.assertSoupEquals("&#1000000000;", expect)
  198. def test_multipart_strings(self):
  199. "Mostly to prevent a recurrence of a bug in the html5lib treebuilder."
  200. soup = self.soup("<html><h2>\nfoo</h2><p></p></html>")
  201. self.assertEqual("p", soup.h2.string.next_element.name)
  202. self.assertEqual("p", soup.p.name)
  203. def test_basic_namespaces(self):
  204. """Parsers don't need to *understand* namespaces, but at the
  205. very least they should not choke on namespaces or lose
  206. data."""
  207. markup = b'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:mathml="http://www.w3.org/1998/Math/MathML" xmlns:svg="http://www.w3.org/2000/svg"><head></head><body><mathml:msqrt>4</mathml:msqrt><b svg:fill="red"></b></body></html>'
  208. soup = self.soup(markup)
  209. self.assertEqual(markup, soup.encode())
  210. html = soup.html
  211. self.assertEqual('http://www.w3.org/1999/xhtml', soup.html['xmlns'])
  212. self.assertEqual(
  213. 'http://www.w3.org/1998/Math/MathML', soup.html['xmlns:mathml'])
  214. self.assertEqual(
  215. 'http://www.w3.org/2000/svg', soup.html['xmlns:svg'])
  216. def test_multivalued_attribute_value_becomes_list(self):
  217. markup = b'<a class="foo bar">'
  218. soup = self.soup(markup)
  219. self.assertEqual(['foo', 'bar'], soup.a['class'])
  220. #
  221. # Generally speaking, tests below this point are more tests of
  222. # Beautiful Soup than tests of the tree builders. But parsers are
  223. # weird, so we run these tests separately for every tree builder
  224. # to detect any differences between them.
  225. #
  226. def test_can_parse_unicode_document(self):
  227. # A seemingly innocuous document... but it's in Unicode! And
  228. # it contains characters that can't be represented in the
  229. # encoding found in the declaration! The horror!
  230. markup = u'<html><head><meta encoding="euc-jp"></head><body>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</body>'
  231. soup = self.soup(markup)
  232. self.assertEqual(u'Sacr\xe9 bleu!', soup.body.string)
  233. def test_soupstrainer(self):
  234. """Parsers should be able to work with SoupStrainers."""
  235. strainer = SoupStrainer("b")
  236. soup = self.soup("A <b>bold</b> <meta/> <i>statement</i>",
  237. parse_only=strainer)
  238. self.assertEqual(soup.decode(), "<b>bold</b>")
  239. def test_single_quote_attribute_values_become_double_quotes(self):
  240. self.assertSoupEquals("<foo attr='bar'></foo>",
  241. '<foo attr="bar"></foo>')
  242. def test_attribute_values_with_nested_quotes_are_left_alone(self):
  243. text = """<foo attr='bar "brawls" happen'>a</foo>"""
  244. self.assertSoupEquals(text)
  245. def test_attribute_values_with_double_nested_quotes_get_quoted(self):
  246. text = """<foo attr='bar "brawls" happen'>a</foo>"""
  247. soup = self.soup(text)
  248. soup.foo['attr'] = 'Brawls happen at "Bob\'s Bar"'
  249. self.assertSoupEquals(
  250. soup.foo.decode(),
  251. """<foo attr="Brawls happen at &quot;Bob\'s Bar&quot;">a</foo>""")
  252. def test_ampersand_in_attribute_value_gets_escaped(self):
  253. self.assertSoupEquals('<this is="really messed up & stuff"></this>',
  254. '<this is="really messed up &amp; stuff"></this>')
  255. self.assertSoupEquals(
  256. '<a href="http://example.org?a=1&b=2;3">foo</a>',
  257. '<a href="http://example.org?a=1&amp;b=2;3">foo</a>')
  258. def test_escaped_ampersand_in_attribute_value_is_left_alone(self):
  259. self.assertSoupEquals('<a href="http://example.org?a=1&amp;b=2;3"></a>')
  260. def test_entities_in_strings_converted_during_parsing(self):
  261. # Both XML and HTML entities are converted to Unicode characters
  262. # during parsing.
  263. text = "<p>&lt;&lt;sacr&eacute;&#32;bleu!&gt;&gt;</p>"
  264. expected = u"<p>&lt;&lt;sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</p>"
  265. self.assertSoupEquals(text, expected)
  266. def test_smart_quotes_converted_on_the_way_in(self):
  267. # Microsoft smart quotes are converted to Unicode characters during
  268. # parsing.
  269. quote = b"<p>\x91Foo\x92</p>"
  270. soup = self.soup(quote)
  271. self.assertEqual(
  272. soup.p.string,
  273. u"\N{LEFT SINGLE QUOTATION MARK}Foo\N{RIGHT SINGLE QUOTATION MARK}")
  274. def test_non_breaking_spaces_converted_on_the_way_in(self):
  275. soup = self.soup("<a>&nbsp;&nbsp;</a>")
  276. self.assertEqual(soup.a.string, u"\N{NO-BREAK SPACE}" * 2)
  277. def test_entities_converted_on_the_way_out(self):
  278. text = "<p>&lt;&lt;sacr&eacute;&#32;bleu!&gt;&gt;</p>"
  279. expected = u"<p>&lt;&lt;sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</p>".encode("utf-8")
  280. soup = self.soup(text)
  281. self.assertEqual(soup.p.encode("utf-8"), expected)
  282. def test_real_iso_latin_document(self):
  283. # Smoke test of interrelated functionality, using an
  284. # easy-to-understand document.
  285. # Here it is in Unicode. Note that it claims to be in ISO-Latin-1.
  286. unicode_html = u'<html><head><meta content="text/html; charset=ISO-Latin-1" http-equiv="Content-type"/></head><body><p>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</p></body></html>'
  287. # That's because we're going to encode it into ISO-Latin-1, and use
  288. # that to test.
  289. iso_latin_html = unicode_html.encode("iso-8859-1")
  290. # Parse the ISO-Latin-1 HTML.
  291. soup = self.soup(iso_latin_html)
  292. # Encode it to UTF-8.
  293. result = soup.encode("utf-8")
  294. # What do we expect the result to look like? Well, it would
  295. # look like unicode_html, except that the META tag would say
  296. # UTF-8 instead of ISO-Latin-1.
  297. expected = unicode_html.replace("ISO-Latin-1", "utf-8")
  298. # And, of course, it would be in UTF-8, not Unicode.
  299. expected = expected.encode("utf-8")
  300. # Ta-da!
  301. self.assertEqual(result, expected)
  302. def test_real_shift_jis_document(self):
  303. # Smoke test to make sure the parser can handle a document in
  304. # Shift-JIS encoding, without choking.
  305. shift_jis_html = (
  306. b'<html><head></head><body><pre>'
  307. b'\x82\xb1\x82\xea\x82\xcdShift-JIS\x82\xc5\x83R\x81[\x83f'
  308. b'\x83B\x83\x93\x83O\x82\xb3\x82\xea\x82\xbd\x93\xfa\x96{\x8c'
  309. b'\xea\x82\xcc\x83t\x83@\x83C\x83\x8b\x82\xc5\x82\xb7\x81B'
  310. b'</pre></body></html>')
  311. unicode_html = shift_jis_html.decode("shift-jis")
  312. soup = self.soup(unicode_html)
  313. # Make sure the parse tree is correctly encoded to various
  314. # encodings.
  315. self.assertEqual(soup.encode("utf-8"), unicode_html.encode("utf-8"))
  316. self.assertEqual(soup.encode("euc_jp"), unicode_html.encode("euc_jp"))
  317. def test_real_hebrew_document(self):
  318. # A real-world test to make sure we can convert ISO-8859-9 (a
  319. # Hebrew encoding) to UTF-8.
  320. hebrew_document = b'<html><head><title>Hebrew (ISO 8859-8) in Visual Directionality</title></head><body><h1>Hebrew (ISO 8859-8) in Visual Directionality</h1>\xed\xe5\xec\xf9</body></html>'
  321. soup = self.soup(
  322. hebrew_document, from_encoding="iso8859-8")
  323. self.assertEqual(soup.original_encoding, 'iso8859-8')
  324. self.assertEqual(
  325. soup.encode('utf-8'),
  326. hebrew_document.decode("iso8859-8").encode("utf-8"))
  327. def test_meta_tag_reflects_current_encoding(self):
  328. # Here's the <meta> tag saying that a document is
  329. # encoded in Shift-JIS.
  330. meta_tag = ('<meta content="text/html; charset=x-sjis" '
  331. 'http-equiv="Content-type"/>')
  332. # Here's a document incorporating that meta tag.
  333. shift_jis_html = (
  334. '<html><head>\n%s\n'
  335. '<meta http-equiv="Content-language" content="ja"/>'
  336. '</head><body>Shift-JIS markup goes here.') % meta_tag
  337. soup = self.soup(shift_jis_html)
  338. # Parse the document, and the charset is seemingly unaffected.
  339. parsed_meta = soup.find('meta', {'http-equiv': 'Content-type'})
  340. content = parsed_meta['content']
  341. self.assertEqual('text/html; charset=x-sjis', content)
  342. # But that value is actually a ContentMetaAttributeValue object.
  343. self.assertTrue(isinstance(content, ContentMetaAttributeValue))
  344. # And it will take on a value that reflects its current
  345. # encoding.
  346. self.assertEqual('text/html; charset=utf8', content.encode("utf8"))
  347. # For the rest of the story, see TestSubstitutions in
  348. # test_tree.py.
  349. def test_html5_style_meta_tag_reflects_current_encoding(self):
  350. # Here's the <meta> tag saying that a document is
  351. # encoded in Shift-JIS.
  352. meta_tag = ('<meta id="encoding" charset="x-sjis" />')
  353. # Here's a document incorporating that meta tag.
  354. shift_jis_html = (
  355. '<html><head>\n%s\n'
  356. '<meta http-equiv="Content-language" content="ja"/>'
  357. '</head><body>Shift-JIS markup goes here.') % meta_tag
  358. soup = self.soup(shift_jis_html)
  359. # Parse the document, and the charset is seemingly unaffected.
  360. parsed_meta = soup.find('meta', id="encoding")
  361. charset = parsed_meta['charset']
  362. self.assertEqual('x-sjis', charset)
  363. # But that value is actually a CharsetMetaAttributeValue object.
  364. self.assertTrue(isinstance(charset, CharsetMetaAttributeValue))
  365. # And it will take on a value that reflects its current
  366. # encoding.
  367. self.assertEqual('utf8', charset.encode("utf8"))
  368. def test_tag_with_no_attributes_can_have_attributes_added(self):
  369. data = self.soup("<a>text</a>")
  370. data.a['foo'] = 'bar'
  371. self.assertEqual('<a foo="bar">text</a>', data.a.decode())
  372. class XMLTreeBuilderSmokeTest(object):
  373. def test_docstring_generated(self):
  374. soup = self.soup("<root/>")
  375. self.assertEqual(
  376. soup.encode(), b'<?xml version="1.0" encoding="utf-8"?>\n<root/>')
  377. def test_real_xhtml_document(self):
  378. """A real XHTML document should come out *exactly* the same as it went in."""
  379. markup = b"""<?xml version="1.0" encoding="utf-8"?>
  380. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
  381. <html xmlns="http://www.w3.org/1999/xhtml">
  382. <head><title>Hello.</title></head>
  383. <body>Goodbye.</body>
  384. </html>"""
  385. soup = self.soup(markup)
  386. self.assertEqual(
  387. soup.encode("utf-8"), markup)
  388. def test_formatter_processes_script_tag_for_xml_documents(self):
  389. doc = """
  390. <script type="text/javascript">
  391. </script>
  392. """
  393. soup = BeautifulSoup(doc, "xml")
  394. # lxml would have stripped this while parsing, but we can add
  395. # it later.
  396. soup.script.string = 'console.log("< < hey > > ");'
  397. encoded = soup.encode()
  398. self.assertTrue(b"&lt; &lt; hey &gt; &gt;" in encoded)
  399. def test_can_parse_unicode_document(self):
  400. markup = u'<?xml version="1.0" encoding="euc-jp"><root>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</root>'
  401. soup = self.soup(markup)
  402. self.assertEqual(u'Sacr\xe9 bleu!', soup.root.string)
  403. def test_popping_namespaced_tag(self):
  404. markup = '<rss xmlns:dc="foo"><dc:creator>b</dc:creator><dc:date>2012-07-02T20:33:42Z</dc:date><dc:rights>c</dc:rights><image>d</image></rss>'
  405. soup = self.soup(markup)
  406. self.assertEqual(
  407. unicode(soup.rss), markup)
  408. def test_docstring_includes_correct_encoding(self):
  409. soup = self.soup("<root/>")
  410. self.assertEqual(
  411. soup.encode("latin1"),
  412. b'<?xml version="1.0" encoding="latin1"?>\n<root/>')
  413. def test_large_xml_document(self):
  414. """A large XML document should come out the same as it went in."""
  415. markup = (b'<?xml version="1.0" encoding="utf-8"?>\n<root>'
  416. + b'0' * (2**12)
  417. + b'</root>')
  418. soup = self.soup(markup)
  419. self.assertEqual(soup.encode("utf-8"), markup)
  420. def test_tags_are_empty_element_if_and_only_if_they_are_empty(self):
  421. self.assertSoupEquals("<p>", "<p/>")
  422. self.assertSoupEquals("<p>foo</p>")
  423. def test_namespaces_are_preserved(self):
  424. markup = '<root xmlns:a="http://example.com/" xmlns:b="http://example.net/"><a:foo>This tag is in the a namespace</a:foo><b:foo>This tag is in the b namespace</b:foo></root>'
  425. soup = self.soup(markup)
  426. root = soup.root
  427. self.assertEqual("http://example.com/", root['xmlns:a'])
  428. self.assertEqual("http://example.net/", root['xmlns:b'])
  429. def test_closing_namespaced_tag(self):
  430. markup = '<p xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:date>20010504</dc:date></p>'
  431. soup = self.soup(markup)
  432. self.assertEqual(unicode(soup.p), markup)
  433. def test_namespaced_attributes(self):
  434. markup = '<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><bar xsi:schemaLocation="http://www.example.com"/></foo>'
  435. soup = self.soup(markup)
  436. self.assertEqual(unicode(soup.foo), markup)
  437. def test_namespaced_attributes_xml_namespace(self):
  438. markup = '<foo xml:lang="fr">bar</foo>'
  439. soup = self.soup(markup)
  440. self.assertEqual(unicode(soup.foo), markup)
  441. class HTML5TreeBuilderSmokeTest(HTMLTreeBuilderSmokeTest):
  442. """Smoke test for a tree builder that supports HTML5."""
  443. def test_real_xhtml_document(self):
  444. # Since XHTML is not HTML5, HTML5 parsers are not tested to handle
  445. # XHTML documents in any particular way.
  446. pass
  447. def test_html_tags_have_namespace(self):
  448. markup = "<a>"
  449. soup = self.soup(markup)
  450. self.assertEqual("http://www.w3.org/1999/xhtml", soup.a.namespace)
  451. def test_svg_tags_have_namespace(self):
  452. markup = '<svg><circle/></svg>'
  453. soup = self.soup(markup)
  454. namespace = "http://www.w3.org/2000/svg"
  455. self.assertEqual(namespace, soup.svg.namespace)
  456. self.assertEqual(namespace, soup.circle.namespace)
  457. def test_mathml_tags_have_namespace(self):
  458. markup = '<math><msqrt>5</msqrt></math>'
  459. soup = self.soup(markup)
  460. namespace = 'http://www.w3.org/1998/Math/MathML'
  461. self.assertEqual(namespace, soup.math.namespace)
  462. self.assertEqual(namespace, soup.msqrt.namespace)
  463. def test_xml_declaration_becomes_comment(self):
  464. markup = '<?xml version="1.0" encoding="utf-8"?><html></html>'
  465. soup = self.soup(markup)
  466. self.assertTrue(isinstance(soup.contents[0], Comment))
  467. self.assertEqual(soup.contents[0], '?xml version="1.0" encoding="utf-8"?')
  468. self.assertEqual("html", soup.contents[0].next_element.name)
  469. def skipIf(condition, reason):
  470. def nothing(test, *args, **kwargs):
  471. return None
  472. def decorator(test_item):
  473. if condition:
  474. return nothing
  475. else:
  476. return test_item
  477. return decorator