__init__.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. # encoding: utf-8
  2. """Helper classes for tests."""
  3. # Use of this source code is governed by the MIT license.
  4. __license__ = "MIT"
  5. import pickle
  6. import copy
  7. import functools
  8. import warnings
  9. import pytest
  10. from bs4 import BeautifulSoup
  11. from bs4.element import (
  12. CharsetMetaAttributeValue,
  13. Comment,
  14. ContentMetaAttributeValue,
  15. Doctype,
  16. PYTHON_SPECIFIC_ENCODINGS,
  17. SoupStrainer,
  18. Script,
  19. Stylesheet,
  20. Tag
  21. )
  22. from bs4.builder import (
  23. DetectsXMLParsedAsHTML,
  24. HTMLParserTreeBuilder,
  25. XMLParsedAsHTMLWarning,
  26. )
  27. default_builder = HTMLParserTreeBuilder
  28. BAD_DOCUMENT = """A bare string
  29. <!DOCTYPE xsl:stylesheet SYSTEM "htmlent.dtd">
  30. <!DOCTYPE xsl:stylesheet PUBLIC "htmlent.dtd">
  31. <div><![CDATA[A CDATA section where it doesn't belong]]></div>
  32. <div><svg><![CDATA[HTML5 does allow CDATA sections in SVG]]></svg></div>
  33. <div>A <meta> tag</div>
  34. <div>A <br> tag that supposedly has contents.</br></div>
  35. <div>AT&T</div>
  36. <div><textarea>Within a textarea, markup like <b> tags and <&<&amp; should be treated as literal</textarea></div>
  37. <div><script>if (i < 2) { alert("<b>Markup within script tags should be treated as literal.</b>"); }</script></div>
  38. <div>This numeric entity is missing the final semicolon: <x t="pi&#241ata"></div>
  39. <div><a href="http://example.com/</a> that attribute value never got closed</div>
  40. <div><a href="foo</a>, </a><a href="bar">that attribute value was closed by the subsequent tag</a></div>
  41. <! This document starts with a bogus declaration ><div>a</div>
  42. <div>This document contains <!an incomplete declaration <div>(do you see it?)</div>
  43. <div>This document ends with <!an incomplete declaration
  44. <div><a style={height:21px;}>That attribute value was bogus</a></div>
  45. <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">The doctype is invalid because it contains extra whitespace
  46. <div><table><td nowrap>That boolean attribute had no value</td></table></div>
  47. <div>Here's a nonexistent entity: &#foo; (do you see it?)</div>
  48. <div>This document ends before the entity finishes: &gt
  49. <div><p>Paragraphs shouldn't contain block display elements, but this one does: <dl><dt>you see?</dt></p>
  50. <b b="20" a="1" b="10" a="2" a="3" a="4">Multiple values for the same attribute.</b>
  51. <div><table><tr><td>Here's a table</td></tr></table></div>
  52. <div><table id="1"><tr><td>Here's a nested table:<table id="2"><tr><td>foo</td></tr></table></td></div>
  53. <div>This tag contains nothing but whitespace: <b> </b></div>
  54. <div><blockquote><p><b>This p tag is cut off by</blockquote></p>the end of the blockquote tag</div>
  55. <div><table><div>This table contains bare markup</div></table></div>
  56. <div><div id="1">\n <a href="link1">This link is never closed.\n</div>\n<div id="2">\n <div id="3">\n <a href="link2">This link is closed.</a>\n </div>\n</div></div>
  57. <div>This document contains a <!DOCTYPE surprise>surprise doctype</div>
  58. <div><a><B><Cd><EFG>Mixed case tags are folded to lowercase</efg></CD></b></A></div>
  59. <div><our\u2603>Tag name contains Unicode characters</our\u2603></div>
  60. <div><a \u2603="snowman">Attribute name contains Unicode characters</a></div>
  61. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  62. """
  63. class SoupTest(object):
  64. @property
  65. def default_builder(self):
  66. return default_builder
  67. def soup(self, markup, **kwargs):
  68. """Build a Beautiful Soup object from markup."""
  69. builder = kwargs.pop('builder', self.default_builder)
  70. return BeautifulSoup(markup, builder=builder, **kwargs)
  71. def document_for(self, markup, **kwargs):
  72. """Turn an HTML fragment into a document.
  73. The details depend on the builder.
  74. """
  75. return self.default_builder(**kwargs).test_fragment_to_document(markup)
  76. def assert_soup(self, to_parse, compare_parsed_to=None):
  77. """Parse some markup using Beautiful Soup and verify that
  78. the output markup is as expected.
  79. """
  80. builder = self.default_builder
  81. obj = BeautifulSoup(to_parse, builder=builder)
  82. if compare_parsed_to is None:
  83. compare_parsed_to = to_parse
  84. # Verify that the documents come out the same.
  85. assert obj.decode() == self.document_for(compare_parsed_to)
  86. # Also run some checks on the BeautifulSoup object itself:
  87. # Verify that every tag that was opened was eventually closed.
  88. # There are no tags in the open tag counter.
  89. assert all(v==0 for v in list(obj.open_tag_counter.values()))
  90. # The only tag in the tag stack is the one for the root
  91. # document.
  92. assert [obj.ROOT_TAG_NAME] == [x.name for x in obj.tagStack]
  93. assertSoupEquals = assert_soup
  94. def assertConnectedness(self, element):
  95. """Ensure that next_element and previous_element are properly
  96. set for all descendants of the given element.
  97. """
  98. earlier = None
  99. for e in element.descendants:
  100. if earlier:
  101. assert e == earlier.next_element
  102. assert earlier == e.previous_element
  103. earlier = e
  104. def linkage_validator(self, el, _recursive_call=False):
  105. """Ensure proper linkage throughout the document."""
  106. descendant = None
  107. # Document element should have no previous element or previous sibling.
  108. # It also shouldn't have a next sibling.
  109. if el.parent is None:
  110. assert el.previous_element is None,\
  111. "Bad previous_element\nNODE: {}\nPREV: {}\nEXPECTED: {}".format(
  112. el, el.previous_element, None
  113. )
  114. assert el.previous_sibling is None,\
  115. "Bad previous_sibling\nNODE: {}\nPREV: {}\nEXPECTED: {}".format(
  116. el, el.previous_sibling, None
  117. )
  118. assert el.next_sibling is None,\
  119. "Bad next_sibling\nNODE: {}\nNEXT: {}\nEXPECTED: {}".format(
  120. el, el.next_sibling, None
  121. )
  122. idx = 0
  123. child = None
  124. last_child = None
  125. last_idx = len(el.contents) - 1
  126. for child in el.contents:
  127. descendant = None
  128. # Parent should link next element to their first child
  129. # That child should have no previous sibling
  130. if idx == 0:
  131. if el.parent is not None:
  132. assert el.next_element is child,\
  133. "Bad next_element\nNODE: {}\nNEXT: {}\nEXPECTED: {}".format(
  134. el, el.next_element, child
  135. )
  136. assert child.previous_element is el,\
  137. "Bad previous_element\nNODE: {}\nPREV: {}\nEXPECTED: {}".format(
  138. child, child.previous_element, el
  139. )
  140. assert child.previous_sibling is None,\
  141. "Bad previous_sibling\nNODE: {}\nPREV {}\nEXPECTED: {}".format(
  142. child, child.previous_sibling, None
  143. )
  144. # If not the first child, previous index should link as sibling to this index
  145. # Previous element should match the last index or the last bubbled up descendant
  146. else:
  147. assert child.previous_sibling is el.contents[idx - 1],\
  148. "Bad previous_sibling\nNODE: {}\nPREV {}\nEXPECTED {}".format(
  149. child, child.previous_sibling, el.contents[idx - 1]
  150. )
  151. assert el.contents[idx - 1].next_sibling is child,\
  152. "Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format(
  153. el.contents[idx - 1], el.contents[idx - 1].next_sibling, child
  154. )
  155. if last_child is not None:
  156. assert child.previous_element is last_child,\
  157. "Bad previous_element\nNODE: {}\nPREV {}\nEXPECTED {}\nCONTENTS {}".format(
  158. child, child.previous_element, last_child, child.parent.contents
  159. )
  160. assert last_child.next_element is child,\
  161. "Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format(
  162. last_child, last_child.next_element, child
  163. )
  164. if isinstance(child, Tag) and child.contents:
  165. descendant = self.linkage_validator(child, True)
  166. # A bubbled up descendant should have no next siblings
  167. assert descendant.next_sibling is None,\
  168. "Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format(
  169. descendant, descendant.next_sibling, None
  170. )
  171. # Mark last child as either the bubbled up descendant or the current child
  172. if descendant is not None:
  173. last_child = descendant
  174. else:
  175. last_child = child
  176. # If last child, there are non next siblings
  177. if idx == last_idx:
  178. assert child.next_sibling is None,\
  179. "Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format(
  180. child, child.next_sibling, None
  181. )
  182. idx += 1
  183. child = descendant if descendant is not None else child
  184. if child is None:
  185. child = el
  186. if not _recursive_call and child is not None:
  187. target = el
  188. while True:
  189. if target is None:
  190. assert child.next_element is None, \
  191. "Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format(
  192. child, child.next_element, None
  193. )
  194. break
  195. elif target.next_sibling is not None:
  196. assert child.next_element is target.next_sibling, \
  197. "Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format(
  198. child, child.next_element, target.next_sibling
  199. )
  200. break
  201. target = target.parent
  202. # We are done, so nothing to return
  203. return None
  204. else:
  205. # Return the child to the recursive caller
  206. return child
  207. def assert_selects(self, tags, should_match):
  208. """Make sure that the given tags have the correct text.
  209. This is used in tests that define a bunch of tags, each
  210. containing a single string, and then select certain strings by
  211. some mechanism.
  212. """
  213. assert [tag.string for tag in tags] == should_match
  214. def assert_selects_ids(self, tags, should_match):
  215. """Make sure that the given tags have the correct IDs.
  216. This is used in tests that define a bunch of tags, each
  217. containing a single string, and then select certain strings by
  218. some mechanism.
  219. """
  220. assert [tag['id'] for tag in tags] == should_match
  221. class TreeBuilderSmokeTest(object):
  222. # Tests that are common to HTML and XML tree builders.
  223. @pytest.mark.parametrize(
  224. "multi_valued_attributes",
  225. [None, dict(b=['class']), {'*': ['notclass']}]
  226. )
  227. def test_attribute_not_multi_valued(self, multi_valued_attributes):
  228. markup = '<a class="a b c">'
  229. soup = self.soup(markup, multi_valued_attributes=multi_valued_attributes)
  230. assert soup.a['class'] == 'a b c'
  231. @pytest.mark.parametrize(
  232. "multi_valued_attributes", [dict(a=['class']), {'*': ['class']}]
  233. )
  234. def test_attribute_multi_valued(self, multi_valued_attributes):
  235. markup = '<a class="a b c">'
  236. soup = self.soup(
  237. markup, multi_valued_attributes=multi_valued_attributes
  238. )
  239. assert soup.a['class'] == ['a', 'b', 'c']
  240. def test_fuzzed_input(self):
  241. # This test centralizes in one place the various fuzz tests
  242. # for Beautiful Soup created by the oss-fuzz project.
  243. # These strings superficially resemble markup, but they
  244. # generally can't be parsed into anything. The best we can
  245. # hope for is that parsing these strings won't crash the
  246. # parser.
  247. #
  248. # n.b. This markup is commented out because these fuzz tests
  249. # _do_ crash the parser. However the crashes are due to bugs
  250. # in html.parser, not Beautiful Soup -- otherwise I'd fix the
  251. # bugs!
  252. bad_markup = [
  253. # https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28873
  254. # https://github.com/guidovranken/python-library-fuzzers/blob/master/corp-html/519e5b4269a01185a0d5e76295251921da2f0700
  255. # https://bugs.python.org/issue37747
  256. #
  257. #b'\n<![\xff\xfe\xfe\xcd\x00',
  258. #https://github.com/guidovranken/python-library-fuzzers/blob/master/corp-html/de32aa55785be29bbc72a1a8e06b00611fb3d9f8
  259. # https://bugs.python.org/issue34480
  260. #
  261. #b'<![n\x00'
  262. ]
  263. for markup in bad_markup:
  264. with warnings.catch_warnings(record=False):
  265. soup = self.soup(markup)
  266. class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
  267. """A basic test of a treebuilder's competence.
  268. Any HTML treebuilder, present or future, should be able to pass
  269. these tests. With invalid markup, there's room for interpretation,
  270. and different parsers can handle it differently. But with the
  271. markup in these tests, there's not much room for interpretation.
  272. """
  273. def test_empty_element_tags(self):
  274. """Verify that all HTML4 and HTML5 empty element (aka void element) tags
  275. are handled correctly.
  276. """
  277. for name in [
  278. 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr',
  279. 'spacer', 'frame'
  280. ]:
  281. soup = self.soup("")
  282. new_tag = soup.new_tag(name)
  283. assert new_tag.is_empty_element == True
  284. def test_special_string_containers(self):
  285. soup = self.soup(
  286. "<style>Some CSS</style><script>Some Javascript</script>"
  287. )
  288. assert isinstance(soup.style.string, Stylesheet)
  289. assert isinstance(soup.script.string, Script)
  290. soup = self.soup(
  291. "<style><!--Some CSS--></style>"
  292. )
  293. assert isinstance(soup.style.string, Stylesheet)
  294. # The contents of the style tag resemble an HTML comment, but
  295. # it's not treated as a comment.
  296. assert soup.style.string == "<!--Some CSS-->"
  297. assert isinstance(soup.style.string, Stylesheet)
  298. def test_pickle_and_unpickle_identity(self):
  299. # Pickling a tree, then unpickling it, yields a tree identical
  300. # to the original.
  301. tree = self.soup("<a><b>foo</a>")
  302. dumped = pickle.dumps(tree, 2)
  303. loaded = pickle.loads(dumped)
  304. assert loaded.__class__ == BeautifulSoup
  305. assert loaded.decode() == tree.decode()
  306. def assertDoctypeHandled(self, doctype_fragment):
  307. """Assert that a given doctype string is handled correctly."""
  308. doctype_str, soup = self._document_with_doctype(doctype_fragment)
  309. # Make sure a Doctype object was created.
  310. doctype = soup.contents[0]
  311. assert doctype.__class__ == Doctype
  312. assert doctype == doctype_fragment
  313. assert soup.encode("utf8")[:len(doctype_str)] == doctype_str
  314. # Make sure that the doctype was correctly associated with the
  315. # parse tree and that the rest of the document parsed.
  316. assert soup.p.contents[0] == 'foo'
  317. def _document_with_doctype(self, doctype_fragment, doctype_string="DOCTYPE"):
  318. """Generate and parse a document with the given doctype."""
  319. doctype = '<!%s %s>' % (doctype_string, doctype_fragment)
  320. markup = doctype + '\n<p>foo</p>'
  321. soup = self.soup(markup)
  322. return doctype.encode("utf8"), soup
  323. def test_normal_doctypes(self):
  324. """Make sure normal, everyday HTML doctypes are handled correctly."""
  325. self.assertDoctypeHandled("html")
  326. self.assertDoctypeHandled(
  327. 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"')
  328. def test_empty_doctype(self):
  329. soup = self.soup("<!DOCTYPE>")
  330. doctype = soup.contents[0]
  331. assert "" == doctype.strip()
  332. def test_mixed_case_doctype(self):
  333. # A lowercase or mixed-case doctype becomes a Doctype.
  334. for doctype_fragment in ("doctype", "DocType"):
  335. doctype_str, soup = self._document_with_doctype(
  336. "html", doctype_fragment
  337. )
  338. # Make sure a Doctype object was created and that the DOCTYPE
  339. # is uppercase.
  340. doctype = soup.contents[0]
  341. assert doctype.__class__ == Doctype
  342. assert doctype == "html"
  343. assert soup.encode("utf8")[:len(doctype_str)] == b"<!DOCTYPE html>"
  344. # Make sure that the doctype was correctly associated with the
  345. # parse tree and that the rest of the document parsed.
  346. assert soup.p.contents[0] == 'foo'
  347. def test_public_doctype_with_url(self):
  348. doctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"'
  349. self.assertDoctypeHandled(doctype)
  350. def test_system_doctype(self):
  351. self.assertDoctypeHandled('foo SYSTEM "http://www.example.com/"')
  352. def test_namespaced_system_doctype(self):
  353. # We can handle a namespaced doctype with a system ID.
  354. self.assertDoctypeHandled('xsl:stylesheet SYSTEM "htmlent.dtd"')
  355. def test_namespaced_public_doctype(self):
  356. # Test a namespaced doctype with a public id.
  357. self.assertDoctypeHandled('xsl:stylesheet PUBLIC "htmlent.dtd"')
  358. def test_real_xhtml_document(self):
  359. """A real XHTML document should come out more or less the same as it went in."""
  360. markup = b"""<?xml version="1.0" encoding="utf-8"?>
  361. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
  362. <html xmlns="http://www.w3.org/1999/xhtml">
  363. <head><title>Hello.</title></head>
  364. <body>Goodbye.</body>
  365. </html>"""
  366. with warnings.catch_warnings(record=True) as w:
  367. soup = self.soup(markup)
  368. assert soup.encode("utf-8").replace(b"\n", b"") == markup.replace(b"\n", b"")
  369. # No warning was issued about parsing an XML document as HTML,
  370. # because XHTML is both.
  371. assert w == []
  372. def test_namespaced_html(self):
  373. # When a namespaced XML document is parsed as HTML it should
  374. # be treated as HTML with weird tag names.
  375. markup = b"""<ns1:foo>content</ns1:foo><ns1:foo/><ns2:foo/>"""
  376. with warnings.catch_warnings(record=True) as w:
  377. soup = self.soup(markup)
  378. assert 2 == len(soup.find_all("ns1:foo"))
  379. # n.b. no "you're parsing XML as HTML" warning was given
  380. # because there was no XML declaration.
  381. assert [] == w
  382. def test_detect_xml_parsed_as_html(self):
  383. # A warning is issued when parsing an XML document as HTML,
  384. # but basic stuff should still work.
  385. markup = b"""<?xml version="1.0" encoding="utf-8"?><tag>string</tag>"""
  386. with warnings.catch_warnings(record=True) as w:
  387. soup = self.soup(markup)
  388. assert soup.tag.string == 'string'
  389. [warning] = w
  390. assert isinstance(warning.message, XMLParsedAsHTMLWarning)
  391. assert str(warning.message) == XMLParsedAsHTMLWarning.MESSAGE
  392. # NOTE: the warning is not issued if the document appears to
  393. # be XHTML (tested with test_real_xhtml_document in the
  394. # superclass) or if there is no XML declaration (tested with
  395. # test_namespaced_html in the superclass).
  396. def test_processing_instruction(self):
  397. # We test both Unicode and bytestring to verify that
  398. # process_markup correctly sets processing_instruction_class
  399. # even when the markup is already Unicode and there is no
  400. # need to process anything.
  401. markup = """<?PITarget PIContent?>"""
  402. soup = self.soup(markup)
  403. assert markup == soup.decode()
  404. markup = b"""<?PITarget PIContent?>"""
  405. soup = self.soup(markup)
  406. assert markup == soup.encode("utf8")
  407. def test_deepcopy(self):
  408. """Make sure you can copy the tree builder.
  409. This is important because the builder is part of a
  410. BeautifulSoup object, and we want to be able to copy that.
  411. """
  412. copy.deepcopy(self.default_builder)
  413. def test_p_tag_is_never_empty_element(self):
  414. """A <p> tag is never designated as an empty-element tag.
  415. Even if the markup shows it as an empty-element tag, it
  416. shouldn't be presented that way.
  417. """
  418. soup = self.soup("<p/>")
  419. assert not soup.p.is_empty_element
  420. assert str(soup.p) == "<p></p>"
  421. def test_unclosed_tags_get_closed(self):
  422. """A tag that's not closed by the end of the document should be closed.
  423. This applies to all tags except empty-element tags.
  424. """
  425. self.assert_soup("<p>", "<p></p>")
  426. self.assert_soup("<b>", "<b></b>")
  427. self.assert_soup("<br>", "<br/>")
  428. def test_br_is_always_empty_element_tag(self):
  429. """A <br> tag is designated as an empty-element tag.
  430. Some parsers treat <br></br> as one <br/> tag, some parsers as
  431. two tags, but it should always be an empty-element tag.
  432. """
  433. soup = self.soup("<br></br>")
  434. assert soup.br.is_empty_element
  435. assert str(soup.br) == "<br/>"
  436. def test_nested_formatting_elements(self):
  437. self.assert_soup("<em><em></em></em>")
  438. def test_double_head(self):
  439. html = '''<!DOCTYPE html>
  440. <html>
  441. <head>
  442. <title>Ordinary HEAD element test</title>
  443. </head>
  444. <script type="text/javascript">
  445. alert("Help!");
  446. </script>
  447. <body>
  448. Hello, world!
  449. </body>
  450. </html>
  451. '''
  452. soup = self.soup(html)
  453. assert "text/javascript" == soup.find('script')['type']
  454. def test_comment(self):
  455. # Comments are represented as Comment objects.
  456. markup = "<p>foo<!--foobar-->baz</p>"
  457. self.assert_soup(markup)
  458. soup = self.soup(markup)
  459. comment = soup.find(string="foobar")
  460. assert comment.__class__ == Comment
  461. # The comment is properly integrated into the tree.
  462. foo = soup.find(string="foo")
  463. assert comment == foo.next_element
  464. baz = soup.find(string="baz")
  465. assert comment == baz.previous_element
  466. def test_preserved_whitespace_in_pre_and_textarea(self):
  467. """Whitespace must be preserved in <pre> and <textarea> tags,
  468. even if that would mean not prettifying the markup.
  469. """
  470. pre_markup = "<pre> </pre>"
  471. textarea_markup = "<textarea> woo\nwoo </textarea>"
  472. self.assert_soup(pre_markup)
  473. self.assert_soup(textarea_markup)
  474. soup = self.soup(pre_markup)
  475. assert soup.pre.prettify() == pre_markup
  476. soup = self.soup(textarea_markup)
  477. assert soup.textarea.prettify() == textarea_markup
  478. soup = self.soup("<textarea></textarea>")
  479. assert soup.textarea.prettify() == "<textarea></textarea>"
  480. def test_nested_inline_elements(self):
  481. """Inline elements can be nested indefinitely."""
  482. b_tag = "<b>Inside a B tag</b>"
  483. self.assert_soup(b_tag)
  484. nested_b_tag = "<p>A <i>nested <b>tag</b></i></p>"
  485. self.assert_soup(nested_b_tag)
  486. double_nested_b_tag = "<p>A <a>doubly <i>nested <b>tag</b></i></a></p>"
  487. self.assert_soup(nested_b_tag)
  488. def test_nested_block_level_elements(self):
  489. """Block elements can be nested."""
  490. soup = self.soup('<blockquote><p><b>Foo</b></p></blockquote>')
  491. blockquote = soup.blockquote
  492. assert blockquote.p.b.string == 'Foo'
  493. assert blockquote.b.string == 'Foo'
  494. def test_correctly_nested_tables(self):
  495. """One table can go inside another one."""
  496. markup = ('<table id="1">'
  497. '<tr>'
  498. "<td>Here's another table:"
  499. '<table id="2">'
  500. '<tr><td>foo</td></tr>'
  501. '</table></td>')
  502. self.assert_soup(
  503. markup,
  504. '<table id="1"><tr><td>Here\'s another table:'
  505. '<table id="2"><tr><td>foo</td></tr></table>'
  506. '</td></tr></table>')
  507. self.assert_soup(
  508. "<table><thead><tr><td>Foo</td></tr></thead>"
  509. "<tbody><tr><td>Bar</td></tr></tbody>"
  510. "<tfoot><tr><td>Baz</td></tr></tfoot></table>")
  511. def test_multivalued_attribute_with_whitespace(self):
  512. # Whitespace separating the values of a multi-valued attribute
  513. # should be ignored.
  514. markup = '<div class=" foo bar "></a>'
  515. soup = self.soup(markup)
  516. assert ['foo', 'bar'] == soup.div['class']
  517. # If you search by the literal name of the class it's like the whitespace
  518. # wasn't there.
  519. assert soup.div == soup.find('div', class_="foo bar")
  520. def test_deeply_nested_multivalued_attribute(self):
  521. # html5lib can set the attributes of the same tag many times
  522. # as it rearranges the tree. This has caused problems with
  523. # multivalued attributes.
  524. markup = '<table><div><div class="css"></div></div></table>'
  525. soup = self.soup(markup)
  526. assert ["css"] == soup.div.div['class']
  527. def test_multivalued_attribute_on_html(self):
  528. # html5lib uses a different API to set the attributes ot the
  529. # <html> tag. This has caused problems with multivalued
  530. # attributes.
  531. markup = '<html class="a b"></html>'
  532. soup = self.soup(markup)
  533. assert ["a", "b"] == soup.html['class']
  534. def test_angle_brackets_in_attribute_values_are_escaped(self):
  535. self.assert_soup('<a b="<a>"></a>', '<a b="&lt;a&gt;"></a>')
  536. def test_strings_resembling_character_entity_references(self):
  537. # "&T" and "&p" look like incomplete character entities, but they are
  538. # not.
  539. self.assert_soup(
  540. "<p>&bull; AT&T is in the s&p 500</p>",
  541. "<p>\u2022 AT&amp;T is in the s&amp;p 500</p>"
  542. )
  543. def test_apos_entity(self):
  544. self.assert_soup(
  545. "<p>Bob&apos;s Bar</p>",
  546. "<p>Bob's Bar</p>",
  547. )
  548. def test_entities_in_foreign_document_encoding(self):
  549. # &#147; and &#148; are invalid numeric entities referencing
  550. # Windows-1252 characters. &#45; references a character common
  551. # to Windows-1252 and Unicode, and &#9731; references a
  552. # character only found in Unicode.
  553. #
  554. # All of these entities should be converted to Unicode
  555. # characters.
  556. markup = "<p>&#147;Hello&#148; &#45;&#9731;</p>"
  557. soup = self.soup(markup)
  558. assert "“Hello” -☃" == soup.p.string
  559. def test_entities_in_attributes_converted_to_unicode(self):
  560. expect = '<p id="pi\N{LATIN SMALL LETTER N WITH TILDE}ata"></p>'
  561. self.assert_soup('<p id="pi&#241;ata"></p>', expect)
  562. self.assert_soup('<p id="pi&#xf1;ata"></p>', expect)
  563. self.assert_soup('<p id="pi&#Xf1;ata"></p>', expect)
  564. self.assert_soup('<p id="pi&ntilde;ata"></p>', expect)
  565. def test_entities_in_text_converted_to_unicode(self):
  566. expect = '<p>pi\N{LATIN SMALL LETTER N WITH TILDE}ata</p>'
  567. self.assert_soup("<p>pi&#241;ata</p>", expect)
  568. self.assert_soup("<p>pi&#xf1;ata</p>", expect)
  569. self.assert_soup("<p>pi&#Xf1;ata</p>", expect)
  570. self.assert_soup("<p>pi&ntilde;ata</p>", expect)
  571. def test_quot_entity_converted_to_quotation_mark(self):
  572. self.assert_soup("<p>I said &quot;good day!&quot;</p>",
  573. '<p>I said "good day!"</p>')
  574. def test_out_of_range_entity(self):
  575. expect = "\N{REPLACEMENT CHARACTER}"
  576. self.assert_soup("&#10000000000000;", expect)
  577. self.assert_soup("&#x10000000000000;", expect)
  578. self.assert_soup("&#1000000000;", expect)
  579. def test_multipart_strings(self):
  580. "Mostly to prevent a recurrence of a bug in the html5lib treebuilder."
  581. soup = self.soup("<html><h2>\nfoo</h2><p></p></html>")
  582. assert "p" == soup.h2.string.next_element.name
  583. assert "p" == soup.p.name
  584. self.assertConnectedness(soup)
  585. def test_empty_element_tags(self):
  586. """Verify consistent handling of empty-element tags,
  587. no matter how they come in through the markup.
  588. """
  589. self.assert_soup('<br/><br/><br/>', "<br/><br/><br/>")
  590. self.assert_soup('<br /><br /><br />', "<br/><br/><br/>")
  591. def test_head_tag_between_head_and_body(self):
  592. "Prevent recurrence of a bug in the html5lib treebuilder."
  593. content = """<html><head></head>
  594. <link></link>
  595. <body>foo</body>
  596. </html>
  597. """
  598. soup = self.soup(content)
  599. assert soup.html.body is not None
  600. self.assertConnectedness(soup)
  601. def test_multiple_copies_of_a_tag(self):
  602. "Prevent recurrence of a bug in the html5lib treebuilder."
  603. content = """<!DOCTYPE html>
  604. <html>
  605. <body>
  606. <article id="a" >
  607. <div><a href="1"></div>
  608. <footer>
  609. <a href="2"></a>
  610. </footer>
  611. </article>
  612. </body>
  613. </html>
  614. """
  615. soup = self.soup(content)
  616. self.assertConnectedness(soup.article)
  617. def test_basic_namespaces(self):
  618. """Parsers don't need to *understand* namespaces, but at the
  619. very least they should not choke on namespaces or lose
  620. data."""
  621. 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>'
  622. soup = self.soup(markup)
  623. assert markup == soup.encode()
  624. html = soup.html
  625. assert 'http://www.w3.org/1999/xhtml' == soup.html['xmlns']
  626. assert 'http://www.w3.org/1998/Math/MathML' == soup.html['xmlns:mathml']
  627. assert 'http://www.w3.org/2000/svg' == soup.html['xmlns:svg']
  628. def test_multivalued_attribute_value_becomes_list(self):
  629. markup = b'<a class="foo bar">'
  630. soup = self.soup(markup)
  631. assert ['foo', 'bar'] == soup.a['class']
  632. #
  633. # Generally speaking, tests below this point are more tests of
  634. # Beautiful Soup than tests of the tree builders. But parsers are
  635. # weird, so we run these tests separately for every tree builder
  636. # to detect any differences between them.
  637. #
  638. def test_can_parse_unicode_document(self):
  639. # A seemingly innocuous document... but it's in Unicode! And
  640. # it contains characters that can't be represented in the
  641. # encoding found in the declaration! The horror!
  642. markup = '<html><head><meta encoding="euc-jp"></head><body>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</body>'
  643. soup = self.soup(markup)
  644. assert 'Sacr\xe9 bleu!' == soup.body.string
  645. def test_soupstrainer(self):
  646. """Parsers should be able to work with SoupStrainers."""
  647. strainer = SoupStrainer("b")
  648. soup = self.soup("A <b>bold</b> <meta/> <i>statement</i>",
  649. parse_only=strainer)
  650. assert soup.decode() == "<b>bold</b>"
  651. def test_single_quote_attribute_values_become_double_quotes(self):
  652. self.assert_soup("<foo attr='bar'></foo>",
  653. '<foo attr="bar"></foo>')
  654. def test_attribute_values_with_nested_quotes_are_left_alone(self):
  655. text = """<foo attr='bar "brawls" happen'>a</foo>"""
  656. self.assert_soup(text)
  657. def test_attribute_values_with_double_nested_quotes_get_quoted(self):
  658. text = """<foo attr='bar "brawls" happen'>a</foo>"""
  659. soup = self.soup(text)
  660. soup.foo['attr'] = 'Brawls happen at "Bob\'s Bar"'
  661. self.assert_soup(
  662. soup.foo.decode(),
  663. """<foo attr="Brawls happen at &quot;Bob\'s Bar&quot;">a</foo>""")
  664. def test_ampersand_in_attribute_value_gets_escaped(self):
  665. self.assert_soup('<this is="really messed up & stuff"></this>',
  666. '<this is="really messed up &amp; stuff"></this>')
  667. self.assert_soup(
  668. '<a href="http://example.org?a=1&b=2;3">foo</a>',
  669. '<a href="http://example.org?a=1&amp;b=2;3">foo</a>')
  670. def test_escaped_ampersand_in_attribute_value_is_left_alone(self):
  671. self.assert_soup('<a href="http://example.org?a=1&amp;b=2;3"></a>')
  672. def test_entities_in_strings_converted_during_parsing(self):
  673. # Both XML and HTML entities are converted to Unicode characters
  674. # during parsing.
  675. text = "<p>&lt;&lt;sacr&eacute;&#32;bleu!&gt;&gt;</p>"
  676. expected = "<p>&lt;&lt;sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</p>"
  677. self.assert_soup(text, expected)
  678. def test_smart_quotes_converted_on_the_way_in(self):
  679. # Microsoft smart quotes are converted to Unicode characters during
  680. # parsing.
  681. quote = b"<p>\x91Foo\x92</p>"
  682. soup = self.soup(quote)
  683. assert soup.p.string == "\N{LEFT SINGLE QUOTATION MARK}Foo\N{RIGHT SINGLE QUOTATION MARK}"
  684. def test_non_breaking_spaces_converted_on_the_way_in(self):
  685. soup = self.soup("<a>&nbsp;&nbsp;</a>")
  686. assert soup.a.string == "\N{NO-BREAK SPACE}" * 2
  687. def test_entities_converted_on_the_way_out(self):
  688. text = "<p>&lt;&lt;sacr&eacute;&#32;bleu!&gt;&gt;</p>"
  689. expected = "<p>&lt;&lt;sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</p>".encode("utf-8")
  690. soup = self.soup(text)
  691. assert soup.p.encode("utf-8") == expected
  692. def test_real_iso_latin_document(self):
  693. # Smoke test of interrelated functionality, using an
  694. # easy-to-understand document.
  695. # Here it is in Unicode. Note that it claims to be in ISO-Latin-1.
  696. unicode_html = '<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>'
  697. # That's because we're going to encode it into ISO-Latin-1, and use
  698. # that to test.
  699. iso_latin_html = unicode_html.encode("iso-8859-1")
  700. # Parse the ISO-Latin-1 HTML.
  701. soup = self.soup(iso_latin_html)
  702. # Encode it to UTF-8.
  703. result = soup.encode("utf-8")
  704. # What do we expect the result to look like? Well, it would
  705. # look like unicode_html, except that the META tag would say
  706. # UTF-8 instead of ISO-Latin-1.
  707. expected = unicode_html.replace("ISO-Latin-1", "utf-8")
  708. # And, of course, it would be in UTF-8, not Unicode.
  709. expected = expected.encode("utf-8")
  710. # Ta-da!
  711. assert result == expected
  712. def test_real_shift_jis_document(self):
  713. # Smoke test to make sure the parser can handle a document in
  714. # Shift-JIS encoding, without choking.
  715. shift_jis_html = (
  716. b'<html><head></head><body><pre>'
  717. b'\x82\xb1\x82\xea\x82\xcdShift-JIS\x82\xc5\x83R\x81[\x83f'
  718. b'\x83B\x83\x93\x83O\x82\xb3\x82\xea\x82\xbd\x93\xfa\x96{\x8c'
  719. b'\xea\x82\xcc\x83t\x83@\x83C\x83\x8b\x82\xc5\x82\xb7\x81B'
  720. b'</pre></body></html>')
  721. unicode_html = shift_jis_html.decode("shift-jis")
  722. soup = self.soup(unicode_html)
  723. # Make sure the parse tree is correctly encoded to various
  724. # encodings.
  725. assert soup.encode("utf-8") == unicode_html.encode("utf-8")
  726. assert soup.encode("euc_jp") == unicode_html.encode("euc_jp")
  727. def test_real_hebrew_document(self):
  728. # A real-world test to make sure we can convert ISO-8859-9 (a
  729. # Hebrew encoding) to UTF-8.
  730. 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>'
  731. soup = self.soup(
  732. hebrew_document, from_encoding="iso8859-8")
  733. # Some tree builders call it iso8859-8, others call it iso-8859-9.
  734. # That's not a difference we really care about.
  735. assert soup.original_encoding in ('iso8859-8', 'iso-8859-8')
  736. assert soup.encode('utf-8') == (
  737. hebrew_document.decode("iso8859-8").encode("utf-8")
  738. )
  739. def test_meta_tag_reflects_current_encoding(self):
  740. # Here's the <meta> tag saying that a document is
  741. # encoded in Shift-JIS.
  742. meta_tag = ('<meta content="text/html; charset=x-sjis" '
  743. 'http-equiv="Content-type"/>')
  744. # Here's a document incorporating that meta tag.
  745. shift_jis_html = (
  746. '<html><head>\n%s\n'
  747. '<meta http-equiv="Content-language" content="ja"/>'
  748. '</head><body>Shift-JIS markup goes here.') % meta_tag
  749. soup = self.soup(shift_jis_html)
  750. # Parse the document, and the charset is seemingly unaffected.
  751. parsed_meta = soup.find('meta', {'http-equiv': 'Content-type'})
  752. content = parsed_meta['content']
  753. assert 'text/html; charset=x-sjis' == content
  754. # But that value is actually a ContentMetaAttributeValue object.
  755. assert isinstance(content, ContentMetaAttributeValue)
  756. # And it will take on a value that reflects its current
  757. # encoding.
  758. assert 'text/html; charset=utf8' == content.encode("utf8")
  759. # For the rest of the story, see TestSubstitutions in
  760. # test_tree.py.
  761. def test_html5_style_meta_tag_reflects_current_encoding(self):
  762. # Here's the <meta> tag saying that a document is
  763. # encoded in Shift-JIS.
  764. meta_tag = ('<meta id="encoding" charset="x-sjis" />')
  765. # Here's a document incorporating that meta tag.
  766. shift_jis_html = (
  767. '<html><head>\n%s\n'
  768. '<meta http-equiv="Content-language" content="ja"/>'
  769. '</head><body>Shift-JIS markup goes here.') % meta_tag
  770. soup = self.soup(shift_jis_html)
  771. # Parse the document, and the charset is seemingly unaffected.
  772. parsed_meta = soup.find('meta', id="encoding")
  773. charset = parsed_meta['charset']
  774. assert 'x-sjis' == charset
  775. # But that value is actually a CharsetMetaAttributeValue object.
  776. assert isinstance(charset, CharsetMetaAttributeValue)
  777. # And it will take on a value that reflects its current
  778. # encoding.
  779. assert 'utf8' == charset.encode("utf8")
  780. def test_python_specific_encodings_not_used_in_charset(self):
  781. # You can encode an HTML document using a Python-specific
  782. # encoding, but that encoding won't be mentioned _inside_ the
  783. # resulting document. Instead, the document will appear to
  784. # have no encoding.
  785. for markup in [
  786. b'<meta charset="utf8"></head>'
  787. b'<meta id="encoding" charset="utf-8" />'
  788. ]:
  789. soup = self.soup(markup)
  790. for encoding in PYTHON_SPECIFIC_ENCODINGS:
  791. if encoding in (
  792. 'idna', 'mbcs', 'oem', 'undefined',
  793. 'string_escape', 'string-escape'
  794. ):
  795. # For one reason or another, these will raise an
  796. # exception if we actually try to use them, so don't
  797. # bother.
  798. continue
  799. encoded = soup.encode(encoding)
  800. assert b'meta charset=""' in encoded
  801. assert encoding.encode("ascii") not in encoded
  802. def test_tag_with_no_attributes_can_have_attributes_added(self):
  803. data = self.soup("<a>text</a>")
  804. data.a['foo'] = 'bar'
  805. assert '<a foo="bar">text</a>' == data.a.decode()
  806. def test_closing_tag_with_no_opening_tag(self):
  807. # Without BeautifulSoup.open_tag_counter, the </span> tag will
  808. # cause _popToTag to be called over and over again as we look
  809. # for a <span> tag that wasn't there. The result is that 'text2'
  810. # will show up outside the body of the document.
  811. soup = self.soup("<body><div><p>text1</p></span>text2</div></body>")
  812. assert "<body><div><p>text1</p>text2</div></body>" == soup.body.decode()
  813. def test_worst_case(self):
  814. """Test the worst case (currently) for linking issues."""
  815. soup = self.soup(BAD_DOCUMENT)
  816. self.linkage_validator(soup)
  817. class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
  818. def test_pickle_and_unpickle_identity(self):
  819. # Pickling a tree, then unpickling it, yields a tree identical
  820. # to the original.
  821. tree = self.soup("<a><b>foo</a>")
  822. dumped = pickle.dumps(tree, 2)
  823. loaded = pickle.loads(dumped)
  824. assert loaded.__class__ == BeautifulSoup
  825. assert loaded.decode() == tree.decode()
  826. def test_docstring_generated(self):
  827. soup = self.soup("<root/>")
  828. assert soup.encode() == b'<?xml version="1.0" encoding="utf-8"?>\n<root/>'
  829. def test_xml_declaration(self):
  830. markup = b"""<?xml version="1.0" encoding="utf8"?>\n<foo/>"""
  831. soup = self.soup(markup)
  832. assert markup == soup.encode("utf8")
  833. def test_python_specific_encodings_not_used_in_xml_declaration(self):
  834. # You can encode an XML document using a Python-specific
  835. # encoding, but that encoding won't be mentioned _inside_ the
  836. # resulting document.
  837. markup = b"""<?xml version="1.0"?>\n<foo/>"""
  838. soup = self.soup(markup)
  839. for encoding in PYTHON_SPECIFIC_ENCODINGS:
  840. if encoding in (
  841. 'idna', 'mbcs', 'oem', 'undefined',
  842. 'string_escape', 'string-escape'
  843. ):
  844. # For one reason or another, these will raise an
  845. # exception if we actually try to use them, so don't
  846. # bother.
  847. continue
  848. encoded = soup.encode(encoding)
  849. assert b'<?xml version="1.0"?>' in encoded
  850. assert encoding.encode("ascii") not in encoded
  851. def test_processing_instruction(self):
  852. markup = b"""<?xml version="1.0" encoding="utf8"?>\n<?PITarget PIContent?>"""
  853. soup = self.soup(markup)
  854. assert markup == soup.encode("utf8")
  855. def test_real_xhtml_document(self):
  856. """A real XHTML document should come out *exactly* the same as it went in."""
  857. markup = b"""<?xml version="1.0" encoding="utf-8"?>
  858. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
  859. <html xmlns="http://www.w3.org/1999/xhtml">
  860. <head><title>Hello.</title></head>
  861. <body>Goodbye.</body>
  862. </html>"""
  863. soup = self.soup(markup)
  864. assert soup.encode("utf-8") == markup
  865. def test_nested_namespaces(self):
  866. doc = b"""<?xml version="1.0" encoding="utf-8"?>
  867. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  868. <parent xmlns="http://ns1/">
  869. <child xmlns="http://ns2/" xmlns:ns3="http://ns3/">
  870. <grandchild ns3:attr="value" xmlns="http://ns4/"/>
  871. </child>
  872. </parent>"""
  873. soup = self.soup(doc)
  874. assert doc == soup.encode()
  875. def test_formatter_processes_script_tag_for_xml_documents(self):
  876. doc = """
  877. <script type="text/javascript">
  878. </script>
  879. """
  880. soup = BeautifulSoup(doc, "lxml-xml")
  881. # lxml would have stripped this while parsing, but we can add
  882. # it later.
  883. soup.script.string = 'console.log("< < hey > > ");'
  884. encoded = soup.encode()
  885. assert b"&lt; &lt; hey &gt; &gt;" in encoded
  886. def test_can_parse_unicode_document(self):
  887. markup = '<?xml version="1.0" encoding="euc-jp"><root>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</root>'
  888. soup = self.soup(markup)
  889. assert 'Sacr\xe9 bleu!' == soup.root.string
  890. def test_can_parse_unicode_document_begining_with_bom(self):
  891. markup = '\N{BYTE ORDER MARK}<?xml version="1.0" encoding="euc-jp"><root>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</root>'
  892. soup = self.soup(markup)
  893. assert 'Sacr\xe9 bleu!' == soup.root.string
  894. def test_popping_namespaced_tag(self):
  895. 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>'
  896. soup = self.soup(markup)
  897. assert str(soup.rss) == markup
  898. def test_docstring_includes_correct_encoding(self):
  899. soup = self.soup("<root/>")
  900. assert soup.encode("latin1") == b'<?xml version="1.0" encoding="latin1"?>\n<root/>'
  901. def test_large_xml_document(self):
  902. """A large XML document should come out the same as it went in."""
  903. markup = (b'<?xml version="1.0" encoding="utf-8"?>\n<root>'
  904. + b'0' * (2**12)
  905. + b'</root>')
  906. soup = self.soup(markup)
  907. assert soup.encode("utf-8") == markup
  908. def test_tags_are_empty_element_if_and_only_if_they_are_empty(self):
  909. self.assert_soup("<p>", "<p/>")
  910. self.assert_soup("<p>foo</p>")
  911. def test_namespaces_are_preserved(self):
  912. 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>'
  913. soup = self.soup(markup)
  914. root = soup.root
  915. assert "http://example.com/" == root['xmlns:a']
  916. assert "http://example.net/" == root['xmlns:b']
  917. def test_closing_namespaced_tag(self):
  918. markup = '<p xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:date>20010504</dc:date></p>'
  919. soup = self.soup(markup)
  920. assert str(soup.p) == markup
  921. def test_namespaced_attributes(self):
  922. markup = '<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><bar xsi:schemaLocation="http://www.example.com"/></foo>'
  923. soup = self.soup(markup)
  924. assert str(soup.foo) == markup
  925. def test_namespaced_attributes_xml_namespace(self):
  926. markup = '<foo xml:lang="fr">bar</foo>'
  927. soup = self.soup(markup)
  928. assert str(soup.foo) == markup
  929. def test_find_by_prefixed_name(self):
  930. doc = """<?xml version="1.0" encoding="utf-8"?>
  931. <Document xmlns="http://example.com/ns0"
  932. xmlns:ns1="http://example.com/ns1"
  933. xmlns:ns2="http://example.com/ns2"
  934. <ns1:tag>foo</ns1:tag>
  935. <ns1:tag>bar</ns1:tag>
  936. <ns2:tag key="value">baz</ns2:tag>
  937. </Document>
  938. """
  939. soup = self.soup(doc)
  940. # There are three <tag> tags.
  941. assert 3 == len(soup.find_all('tag'))
  942. # But two of them are ns1:tag and one of them is ns2:tag.
  943. assert 2 == len(soup.find_all('ns1:tag'))
  944. assert 1 == len(soup.find_all('ns2:tag'))
  945. assert 1, len(soup.find_all('ns2:tag', key='value'))
  946. assert 3, len(soup.find_all(['ns1:tag', 'ns2:tag']))
  947. def test_copy_tag_preserves_namespace(self):
  948. xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  949. <w:document xmlns:w="http://example.com/ns0"/>"""
  950. soup = self.soup(xml)
  951. tag = soup.document
  952. duplicate = copy.copy(tag)
  953. # The two tags have the same namespace prefix.
  954. assert tag.prefix == duplicate.prefix
  955. def test_worst_case(self):
  956. """Test the worst case (currently) for linking issues."""
  957. soup = self.soup(BAD_DOCUMENT)
  958. self.linkage_validator(soup)
  959. class HTML5TreeBuilderSmokeTest(HTMLTreeBuilderSmokeTest):
  960. """Smoke test for a tree builder that supports HTML5."""
  961. def test_real_xhtml_document(self):
  962. # Since XHTML is not HTML5, HTML5 parsers are not tested to handle
  963. # XHTML documents in any particular way.
  964. pass
  965. def test_html_tags_have_namespace(self):
  966. markup = "<a>"
  967. soup = self.soup(markup)
  968. assert "http://www.w3.org/1999/xhtml" == soup.a.namespace
  969. def test_svg_tags_have_namespace(self):
  970. markup = '<svg><circle/></svg>'
  971. soup = self.soup(markup)
  972. namespace = "http://www.w3.org/2000/svg"
  973. assert namespace == soup.svg.namespace
  974. assert namespace == soup.circle.namespace
  975. def test_mathml_tags_have_namespace(self):
  976. markup = '<math><msqrt>5</msqrt></math>'
  977. soup = self.soup(markup)
  978. namespace = 'http://www.w3.org/1998/Math/MathML'
  979. assert namespace == soup.math.namespace
  980. assert namespace == soup.msqrt.namespace
  981. def test_xml_declaration_becomes_comment(self):
  982. markup = '<?xml version="1.0" encoding="utf-8"?><html></html>'
  983. soup = self.soup(markup)
  984. assert isinstance(soup.contents[0], Comment)
  985. assert soup.contents[0] == '?xml version="1.0" encoding="utf-8"?'
  986. assert "html" == soup.contents[0].next_element.name
  987. def skipIf(condition, reason):
  988. def nothing(test, *args, **kwargs):
  989. return None
  990. def decorator(test_item):
  991. if condition:
  992. return nothing
  993. else:
  994. return test_item
  995. return decorator