Path: blob/master/venv/Lib/site-packages/bs4/testing.py
811 views
# encoding: utf-81"""Helper classes for tests."""23# Use of this source code is governed by the MIT license.4__license__ = "MIT"56import pickle7import copy8import functools9import unittest10from unittest import TestCase11from bs4 import BeautifulSoup12from bs4.element import (13CharsetMetaAttributeValue,14Comment,15ContentMetaAttributeValue,16Doctype,17PYTHON_SPECIFIC_ENCODINGS,18SoupStrainer,19Script,20Stylesheet,21Tag22)2324from bs4.builder import HTMLParserTreeBuilder25default_builder = HTMLParserTreeBuilder2627BAD_DOCUMENT = """A bare string28<!DOCTYPE xsl:stylesheet SYSTEM "htmlent.dtd">29<!DOCTYPE xsl:stylesheet PUBLIC "htmlent.dtd">30<div><![CDATA[A CDATA section where it doesn't belong]]></div>31<div><svg><![CDATA[HTML5 does allow CDATA sections in SVG]]></svg></div>32<div>A <meta> tag</div>33<div>A <br> tag that supposedly has contents.</br></div>34<div>AT&T</div>35<div><textarea>Within a textarea, markup like <b> tags and <&<& should be treated as literal</textarea></div>36<div><script>if (i < 2) { alert("<b>Markup within script tags should be treated as literal.</b>"); }</script></div>37<div>This numeric entity is missing the final semicolon: <x t="piñata"></div>38<div><a href="http://example.com/</a> that attribute value never got closed</div>39<div><a href="foo</a>, </a><a href="bar">that attribute value was closed by the subsequent tag</a></div>40<! This document starts with a bogus declaration ><div>a</div>41<div>This document contains <!an incomplete declaration <div>(do you see it?)</div>42<div>This document ends with <!an incomplete declaration43<div><a style={height:21px;}>That attribute value was bogus</a></div>44<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">The doctype is invalid because it contains extra whitespace45<div><table><td nowrap>That boolean attribute had no value</td></table></div>46<div>Here's a nonexistent entity: &#foo; (do you see it?)</div>47<div>This document ends before the entity finishes: >48<div><p>Paragraphs shouldn't contain block display elements, but this one does: <dl><dt>you see?</dt></p>49<b b="20" a="1" b="10" a="2" a="3" a="4">Multiple values for the same attribute.</b>50<div><table><tr><td>Here's a table</td></tr></table></div>51<div><table id="1"><tr><td>Here's a nested table:<table id="2"><tr><td>foo</td></tr></table></td></div>52<div>This tag contains nothing but whitespace: <b> </b></div>53<div><blockquote><p><b>This p tag is cut off by</blockquote></p>the end of the blockquote tag</div>54<div><table><div>This table contains bare markup</div></table></div>55<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>56<div>This document contains a <!DOCTYPE surprise>surprise doctype</div>57<div><a><B><Cd><EFG>Mixed case tags are folded to lowercase</efg></CD></b></A></div>58<div><our\u2603>Tag name contains Unicode characters</our\u2603></div>59<div><a \u2603="snowman">Attribute name contains Unicode characters</a></div>60<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">61"""626364class SoupTest(unittest.TestCase):6566@property67def default_builder(self):68return default_builder6970def soup(self, markup, **kwargs):71"""Build a Beautiful Soup object from markup."""72builder = kwargs.pop('builder', self.default_builder)73return BeautifulSoup(markup, builder=builder, **kwargs)7475def document_for(self, markup, **kwargs):76"""Turn an HTML fragment into a document.7778The details depend on the builder.79"""80return self.default_builder(**kwargs).test_fragment_to_document(markup)8182def assertSoupEquals(self, to_parse, compare_parsed_to=None):83builder = self.default_builder84obj = BeautifulSoup(to_parse, builder=builder)85if compare_parsed_to is None:86compare_parsed_to = to_parse8788self.assertEqual(obj.decode(), self.document_for(compare_parsed_to))8990def assertConnectedness(self, element):91"""Ensure that next_element and previous_element are properly92set for all descendants of the given element.93"""94earlier = None95for e in element.descendants:96if earlier:97self.assertEqual(e, earlier.next_element)98self.assertEqual(earlier, e.previous_element)99earlier = e100101def linkage_validator(self, el, _recursive_call=False):102"""Ensure proper linkage throughout the document."""103descendant = None104# Document element should have no previous element or previous sibling.105# It also shouldn't have a next sibling.106if el.parent is None:107assert el.previous_element is None,\108"Bad previous_element\nNODE: {}\nPREV: {}\nEXPECTED: {}".format(109el, el.previous_element, None110)111assert el.previous_sibling is None,\112"Bad previous_sibling\nNODE: {}\nPREV: {}\nEXPECTED: {}".format(113el, el.previous_sibling, None114)115assert el.next_sibling is None,\116"Bad next_sibling\nNODE: {}\nNEXT: {}\nEXPECTED: {}".format(117el, el.next_sibling, None118)119120idx = 0121child = None122last_child = None123last_idx = len(el.contents) - 1124for child in el.contents:125descendant = None126127# Parent should link next element to their first child128# That child should have no previous sibling129if idx == 0:130if el.parent is not None:131assert el.next_element is child,\132"Bad next_element\nNODE: {}\nNEXT: {}\nEXPECTED: {}".format(133el, el.next_element, child134)135assert child.previous_element is el,\136"Bad previous_element\nNODE: {}\nPREV: {}\nEXPECTED: {}".format(137child, child.previous_element, el138)139assert child.previous_sibling is None,\140"Bad previous_sibling\nNODE: {}\nPREV {}\nEXPECTED: {}".format(141child, child.previous_sibling, None142)143144# If not the first child, previous index should link as sibling to this index145# Previous element should match the last index or the last bubbled up descendant146else:147assert child.previous_sibling is el.contents[idx - 1],\148"Bad previous_sibling\nNODE: {}\nPREV {}\nEXPECTED {}".format(149child, child.previous_sibling, el.contents[idx - 1]150)151assert el.contents[idx - 1].next_sibling is child,\152"Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format(153el.contents[idx - 1], el.contents[idx - 1].next_sibling, child154)155156if last_child is not None:157assert child.previous_element is last_child,\158"Bad previous_element\nNODE: {}\nPREV {}\nEXPECTED {}\nCONTENTS {}".format(159child, child.previous_element, last_child, child.parent.contents160)161assert last_child.next_element is child,\162"Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format(163last_child, last_child.next_element, child164)165166if isinstance(child, Tag) and child.contents:167descendant = self.linkage_validator(child, True)168# A bubbled up descendant should have no next siblings169assert descendant.next_sibling is None,\170"Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format(171descendant, descendant.next_sibling, None172)173174# Mark last child as either the bubbled up descendant or the current child175if descendant is not None:176last_child = descendant177else:178last_child = child179180# If last child, there are non next siblings181if idx == last_idx:182assert child.next_sibling is None,\183"Bad next_sibling\nNODE: {}\nNEXT {}\nEXPECTED {}".format(184child, child.next_sibling, None185)186idx += 1187188child = descendant if descendant is not None else child189if child is None:190child = el191192if not _recursive_call and child is not None:193target = el194while True:195if target is None:196assert child.next_element is None, \197"Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format(198child, child.next_element, None199)200break201elif target.next_sibling is not None:202assert child.next_element is target.next_sibling, \203"Bad next_element\nNODE: {}\nNEXT {}\nEXPECTED {}".format(204child, child.next_element, target.next_sibling205)206break207target = target.parent208209# We are done, so nothing to return210return None211else:212# Return the child to the recursive caller213return child214215216class HTMLTreeBuilderSmokeTest(object):217218"""A basic test of a treebuilder's competence.219220Any HTML treebuilder, present or future, should be able to pass221these tests. With invalid markup, there's room for interpretation,222and different parsers can handle it differently. But with the223markup in these tests, there's not much room for interpretation.224"""225226def test_empty_element_tags(self):227"""Verify that all HTML4 and HTML5 empty element (aka void element) tags228are handled correctly.229"""230for name in [231'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr',232'spacer', 'frame'233]:234soup = self.soup("")235new_tag = soup.new_tag(name)236self.assertEqual(True, new_tag.is_empty_element)237238def test_special_string_containers(self):239soup = self.soup(240"<style>Some CSS</style><script>Some Javascript</script>"241)242assert isinstance(soup.style.string, Stylesheet)243assert isinstance(soup.script.string, Script)244245soup = self.soup(246"<style><!--Some CSS--></style>"247)248assert isinstance(soup.style.string, Stylesheet)249# The contents of the style tag resemble an HTML comment, but250# it's not treated as a comment.251self.assertEqual("<!--Some CSS-->", soup.style.string)252assert isinstance(soup.style.string, Stylesheet)253254def test_pickle_and_unpickle_identity(self):255# Pickling a tree, then unpickling it, yields a tree identical256# to the original.257tree = self.soup("<a><b>foo</a>")258dumped = pickle.dumps(tree, 2)259loaded = pickle.loads(dumped)260self.assertEqual(loaded.__class__, BeautifulSoup)261self.assertEqual(loaded.decode(), tree.decode())262263def assertDoctypeHandled(self, doctype_fragment):264"""Assert that a given doctype string is handled correctly."""265doctype_str, soup = self._document_with_doctype(doctype_fragment)266267# Make sure a Doctype object was created.268doctype = soup.contents[0]269self.assertEqual(doctype.__class__, Doctype)270self.assertEqual(doctype, doctype_fragment)271self.assertEqual(272soup.encode("utf8")[:len(doctype_str)],273doctype_str274)275276# Make sure that the doctype was correctly associated with the277# parse tree and that the rest of the document parsed.278self.assertEqual(soup.p.contents[0], 'foo')279280def _document_with_doctype(self, doctype_fragment, doctype_string="DOCTYPE"):281"""Generate and parse a document with the given doctype."""282doctype = '<!%s %s>' % (doctype_string, doctype_fragment)283markup = doctype + '\n<p>foo</p>'284soup = self.soup(markup)285return doctype.encode("utf8"), soup286287def test_normal_doctypes(self):288"""Make sure normal, everyday HTML doctypes are handled correctly."""289self.assertDoctypeHandled("html")290self.assertDoctypeHandled(291'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"')292293def test_empty_doctype(self):294soup = self.soup("<!DOCTYPE>")295doctype = soup.contents[0]296self.assertEqual("", doctype.strip())297298def test_mixed_case_doctype(self):299# A lowercase or mixed-case doctype becomes a Doctype.300for doctype_fragment in ("doctype", "DocType"):301doctype_str, soup = self._document_with_doctype(302"html", doctype_fragment303)304305# Make sure a Doctype object was created and that the DOCTYPE306# is uppercase.307doctype = soup.contents[0]308self.assertEqual(doctype.__class__, Doctype)309self.assertEqual(doctype, "html")310self.assertEqual(311soup.encode("utf8")[:len(doctype_str)],312b"<!DOCTYPE html>"313)314315# Make sure that the doctype was correctly associated with the316# parse tree and that the rest of the document parsed.317self.assertEqual(soup.p.contents[0], 'foo')318319def test_public_doctype_with_url(self):320doctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"'321self.assertDoctypeHandled(doctype)322323def test_system_doctype(self):324self.assertDoctypeHandled('foo SYSTEM "http://www.example.com/"')325326def test_namespaced_system_doctype(self):327# We can handle a namespaced doctype with a system ID.328self.assertDoctypeHandled('xsl:stylesheet SYSTEM "htmlent.dtd"')329330def test_namespaced_public_doctype(self):331# Test a namespaced doctype with a public id.332self.assertDoctypeHandled('xsl:stylesheet PUBLIC "htmlent.dtd"')333334def test_real_xhtml_document(self):335"""A real XHTML document should come out more or less the same as it went in."""336markup = b"""<?xml version="1.0" encoding="utf-8"?>337<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">338<html xmlns="http://www.w3.org/1999/xhtml">339<head><title>Hello.</title></head>340<body>Goodbye.</body>341</html>"""342soup = self.soup(markup)343self.assertEqual(344soup.encode("utf-8").replace(b"\n", b""),345markup.replace(b"\n", b""))346347def test_namespaced_html(self):348"""When a namespaced XML document is parsed as HTML it should349be treated as HTML with weird tag names.350"""351markup = b"""<ns1:foo>content</ns1:foo><ns1:foo/><ns2:foo/>"""352soup = self.soup(markup)353self.assertEqual(2, len(soup.find_all("ns1:foo")))354355def test_processing_instruction(self):356# We test both Unicode and bytestring to verify that357# process_markup correctly sets processing_instruction_class358# even when the markup is already Unicode and there is no359# need to process anything.360markup = """<?PITarget PIContent?>"""361soup = self.soup(markup)362self.assertEqual(markup, soup.decode())363364markup = b"""<?PITarget PIContent?>"""365soup = self.soup(markup)366self.assertEqual(markup, soup.encode("utf8"))367368def test_deepcopy(self):369"""Make sure you can copy the tree builder.370371This is important because the builder is part of a372BeautifulSoup object, and we want to be able to copy that.373"""374copy.deepcopy(self.default_builder)375376def test_p_tag_is_never_empty_element(self):377"""A <p> tag is never designated as an empty-element tag.378379Even if the markup shows it as an empty-element tag, it380shouldn't be presented that way.381"""382soup = self.soup("<p/>")383self.assertFalse(soup.p.is_empty_element)384self.assertEqual(str(soup.p), "<p></p>")385386def test_unclosed_tags_get_closed(self):387"""A tag that's not closed by the end of the document should be closed.388389This applies to all tags except empty-element tags.390"""391self.assertSoupEquals("<p>", "<p></p>")392self.assertSoupEquals("<b>", "<b></b>")393394self.assertSoupEquals("<br>", "<br/>")395396def test_br_is_always_empty_element_tag(self):397"""A <br> tag is designated as an empty-element tag.398399Some parsers treat <br></br> as one <br/> tag, some parsers as400two tags, but it should always be an empty-element tag.401"""402soup = self.soup("<br></br>")403self.assertTrue(soup.br.is_empty_element)404self.assertEqual(str(soup.br), "<br/>")405406def test_nested_formatting_elements(self):407self.assertSoupEquals("<em><em></em></em>")408409def test_double_head(self):410html = '''<!DOCTYPE html>411<html>412<head>413<title>Ordinary HEAD element test</title>414</head>415<script type="text/javascript">416alert("Help!");417</script>418<body>419Hello, world!420</body>421</html>422'''423soup = self.soup(html)424self.assertEqual("text/javascript", soup.find('script')['type'])425426def test_comment(self):427# Comments are represented as Comment objects.428markup = "<p>foo<!--foobar-->baz</p>"429self.assertSoupEquals(markup)430431soup = self.soup(markup)432comment = soup.find(text="foobar")433self.assertEqual(comment.__class__, Comment)434435# The comment is properly integrated into the tree.436foo = soup.find(text="foo")437self.assertEqual(comment, foo.next_element)438baz = soup.find(text="baz")439self.assertEqual(comment, baz.previous_element)440441def test_preserved_whitespace_in_pre_and_textarea(self):442"""Whitespace must be preserved in <pre> and <textarea> tags,443even if that would mean not prettifying the markup.444"""445pre_markup = "<pre> </pre>"446textarea_markup = "<textarea> woo\nwoo </textarea>"447self.assertSoupEquals(pre_markup)448self.assertSoupEquals(textarea_markup)449450soup = self.soup(pre_markup)451self.assertEqual(soup.pre.prettify(), pre_markup)452453soup = self.soup(textarea_markup)454self.assertEqual(soup.textarea.prettify(), textarea_markup)455456soup = self.soup("<textarea></textarea>")457self.assertEqual(soup.textarea.prettify(), "<textarea></textarea>")458459def test_nested_inline_elements(self):460"""Inline elements can be nested indefinitely."""461b_tag = "<b>Inside a B tag</b>"462self.assertSoupEquals(b_tag)463464nested_b_tag = "<p>A <i>nested <b>tag</b></i></p>"465self.assertSoupEquals(nested_b_tag)466467double_nested_b_tag = "<p>A <a>doubly <i>nested <b>tag</b></i></a></p>"468self.assertSoupEquals(nested_b_tag)469470def test_nested_block_level_elements(self):471"""Block elements can be nested."""472soup = self.soup('<blockquote><p><b>Foo</b></p></blockquote>')473blockquote = soup.blockquote474self.assertEqual(blockquote.p.b.string, 'Foo')475self.assertEqual(blockquote.b.string, 'Foo')476477def test_correctly_nested_tables(self):478"""One table can go inside another one."""479markup = ('<table id="1">'480'<tr>'481"<td>Here's another table:"482'<table id="2">'483'<tr><td>foo</td></tr>'484'</table></td>')485486self.assertSoupEquals(487markup,488'<table id="1"><tr><td>Here\'s another table:'489'<table id="2"><tr><td>foo</td></tr></table>'490'</td></tr></table>')491492self.assertSoupEquals(493"<table><thead><tr><td>Foo</td></tr></thead>"494"<tbody><tr><td>Bar</td></tr></tbody>"495"<tfoot><tr><td>Baz</td></tr></tfoot></table>")496497def test_multivalued_attribute_with_whitespace(self):498# Whitespace separating the values of a multi-valued attribute499# should be ignored.500501markup = '<div class=" foo bar "></a>'502soup = self.soup(markup)503self.assertEqual(['foo', 'bar'], soup.div['class'])504505# If you search by the literal name of the class it's like the whitespace506# wasn't there.507self.assertEqual(soup.div, soup.find('div', class_="foo bar"))508509def test_deeply_nested_multivalued_attribute(self):510# html5lib can set the attributes of the same tag many times511# as it rearranges the tree. This has caused problems with512# multivalued attributes.513markup = '<table><div><div class="css"></div></div></table>'514soup = self.soup(markup)515self.assertEqual(["css"], soup.div.div['class'])516517def test_multivalued_attribute_on_html(self):518# html5lib uses a different API to set the attributes ot the519# <html> tag. This has caused problems with multivalued520# attributes.521markup = '<html class="a b"></html>'522soup = self.soup(markup)523self.assertEqual(["a", "b"], soup.html['class'])524525def test_angle_brackets_in_attribute_values_are_escaped(self):526self.assertSoupEquals('<a b="<a>"></a>', '<a b="<a>"></a>')527528def test_strings_resembling_character_entity_references(self):529# "&T" and "&p" look like incomplete character entities, but they are530# not.531self.assertSoupEquals(532"<p>• AT&T is in the s&p 500</p>",533"<p>\u2022 AT&T is in the s&p 500</p>"534)535536def test_apos_entity(self):537self.assertSoupEquals(538"<p>Bob's Bar</p>",539"<p>Bob's Bar</p>",540)541542def test_entities_in_foreign_document_encoding(self):543# “ and ” are invalid numeric entities referencing544# Windows-1252 characters. - references a character common545# to Windows-1252 and Unicode, and ☃ references a546# character only found in Unicode.547#548# All of these entities should be converted to Unicode549# characters.550markup = "<p>“Hello” -☃</p>"551soup = self.soup(markup)552self.assertEqual("“Hello” -☃", soup.p.string)553554def test_entities_in_attributes_converted_to_unicode(self):555expect = '<p id="pi\N{LATIN SMALL LETTER N WITH TILDE}ata"></p>'556self.assertSoupEquals('<p id="piñata"></p>', expect)557self.assertSoupEquals('<p id="piñata"></p>', expect)558self.assertSoupEquals('<p id="piñata"></p>', expect)559self.assertSoupEquals('<p id="piñata"></p>', expect)560561def test_entities_in_text_converted_to_unicode(self):562expect = '<p>pi\N{LATIN SMALL LETTER N WITH TILDE}ata</p>'563self.assertSoupEquals("<p>piñata</p>", expect)564self.assertSoupEquals("<p>piñata</p>", expect)565self.assertSoupEquals("<p>piñata</p>", expect)566self.assertSoupEquals("<p>piñata</p>", expect)567568def test_quot_entity_converted_to_quotation_mark(self):569self.assertSoupEquals("<p>I said "good day!"</p>",570'<p>I said "good day!"</p>')571572def test_out_of_range_entity(self):573expect = "\N{REPLACEMENT CHARACTER}"574self.assertSoupEquals("�", expect)575self.assertSoupEquals("�", expect)576self.assertSoupEquals("�", expect)577578def test_multipart_strings(self):579"Mostly to prevent a recurrence of a bug in the html5lib treebuilder."580soup = self.soup("<html><h2>\nfoo</h2><p></p></html>")581self.assertEqual("p", soup.h2.string.next_element.name)582self.assertEqual("p", soup.p.name)583self.assertConnectedness(soup)584585def test_empty_element_tags(self):586"""Verify consistent handling of empty-element tags,587no matter how they come in through the markup.588"""589self.assertSoupEquals('<br/><br/><br/>', "<br/><br/><br/>")590self.assertSoupEquals('<br /><br /><br />', "<br/><br/><br/>")591592def test_head_tag_between_head_and_body(self):593"Prevent recurrence of a bug in the html5lib treebuilder."594content = """<html><head></head>595<link></link>596<body>foo</body>597</html>598"""599soup = self.soup(content)600self.assertNotEqual(None, soup.html.body)601self.assertConnectedness(soup)602603def test_multiple_copies_of_a_tag(self):604"Prevent recurrence of a bug in the html5lib treebuilder."605content = """<!DOCTYPE html>606<html>607<body>608<article id="a" >609<div><a href="1"></div>610<footer>611<a href="2"></a>612</footer>613</article>614</body>615</html>616"""617soup = self.soup(content)618self.assertConnectedness(soup.article)619620def test_basic_namespaces(self):621"""Parsers don't need to *understand* namespaces, but at the622very least they should not choke on namespaces or lose623data."""624625markup = 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>'626soup = self.soup(markup)627self.assertEqual(markup, soup.encode())628html = soup.html629self.assertEqual('http://www.w3.org/1999/xhtml', soup.html['xmlns'])630self.assertEqual(631'http://www.w3.org/1998/Math/MathML', soup.html['xmlns:mathml'])632self.assertEqual(633'http://www.w3.org/2000/svg', soup.html['xmlns:svg'])634635def test_multivalued_attribute_value_becomes_list(self):636markup = b'<a class="foo bar">'637soup = self.soup(markup)638self.assertEqual(['foo', 'bar'], soup.a['class'])639640#641# Generally speaking, tests below this point are more tests of642# Beautiful Soup than tests of the tree builders. But parsers are643# weird, so we run these tests separately for every tree builder644# to detect any differences between them.645#646647def test_can_parse_unicode_document(self):648# A seemingly innocuous document... but it's in Unicode! And649# it contains characters that can't be represented in the650# encoding found in the declaration! The horror!651markup = '<html><head><meta encoding="euc-jp"></head><body>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</body>'652soup = self.soup(markup)653self.assertEqual('Sacr\xe9 bleu!', soup.body.string)654655def test_soupstrainer(self):656"""Parsers should be able to work with SoupStrainers."""657strainer = SoupStrainer("b")658soup = self.soup("A <b>bold</b> <meta/> <i>statement</i>",659parse_only=strainer)660self.assertEqual(soup.decode(), "<b>bold</b>")661662def test_single_quote_attribute_values_become_double_quotes(self):663self.assertSoupEquals("<foo attr='bar'></foo>",664'<foo attr="bar"></foo>')665666def test_attribute_values_with_nested_quotes_are_left_alone(self):667text = """<foo attr='bar "brawls" happen'>a</foo>"""668self.assertSoupEquals(text)669670def test_attribute_values_with_double_nested_quotes_get_quoted(self):671text = """<foo attr='bar "brawls" happen'>a</foo>"""672soup = self.soup(text)673soup.foo['attr'] = 'Brawls happen at "Bob\'s Bar"'674self.assertSoupEquals(675soup.foo.decode(),676"""<foo attr="Brawls happen at "Bob\'s Bar"">a</foo>""")677678def test_ampersand_in_attribute_value_gets_escaped(self):679self.assertSoupEquals('<this is="really messed up & stuff"></this>',680'<this is="really messed up & stuff"></this>')681682self.assertSoupEquals(683'<a href="http://example.org?a=1&b=2;3">foo</a>',684'<a href="http://example.org?a=1&b=2;3">foo</a>')685686def test_escaped_ampersand_in_attribute_value_is_left_alone(self):687self.assertSoupEquals('<a href="http://example.org?a=1&b=2;3"></a>')688689def test_entities_in_strings_converted_during_parsing(self):690# Both XML and HTML entities are converted to Unicode characters691# during parsing.692text = "<p><<sacré bleu!>></p>"693expected = "<p><<sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></p>"694self.assertSoupEquals(text, expected)695696def test_smart_quotes_converted_on_the_way_in(self):697# Microsoft smart quotes are converted to Unicode characters during698# parsing.699quote = b"<p>\x91Foo\x92</p>"700soup = self.soup(quote)701self.assertEqual(702soup.p.string,703"\N{LEFT SINGLE QUOTATION MARK}Foo\N{RIGHT SINGLE QUOTATION MARK}")704705def test_non_breaking_spaces_converted_on_the_way_in(self):706soup = self.soup("<a> </a>")707self.assertEqual(soup.a.string, "\N{NO-BREAK SPACE}" * 2)708709def test_entities_converted_on_the_way_out(self):710text = "<p><<sacré bleu!>></p>"711expected = "<p><<sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></p>".encode("utf-8")712soup = self.soup(text)713self.assertEqual(soup.p.encode("utf-8"), expected)714715def test_real_iso_latin_document(self):716# Smoke test of interrelated functionality, using an717# easy-to-understand document.718719# Here it is in Unicode. Note that it claims to be in ISO-Latin-1.720unicode_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>'721722# That's because we're going to encode it into ISO-Latin-1, and use723# that to test.724iso_latin_html = unicode_html.encode("iso-8859-1")725726# Parse the ISO-Latin-1 HTML.727soup = self.soup(iso_latin_html)728# Encode it to UTF-8.729result = soup.encode("utf-8")730731# What do we expect the result to look like? Well, it would732# look like unicode_html, except that the META tag would say733# UTF-8 instead of ISO-Latin-1.734expected = unicode_html.replace("ISO-Latin-1", "utf-8")735736# And, of course, it would be in UTF-8, not Unicode.737expected = expected.encode("utf-8")738739# Ta-da!740self.assertEqual(result, expected)741742def test_real_shift_jis_document(self):743# Smoke test to make sure the parser can handle a document in744# Shift-JIS encoding, without choking.745shift_jis_html = (746b'<html><head></head><body><pre>'747b'\x82\xb1\x82\xea\x82\xcdShift-JIS\x82\xc5\x83R\x81[\x83f'748b'\x83B\x83\x93\x83O\x82\xb3\x82\xea\x82\xbd\x93\xfa\x96{\x8c'749b'\xea\x82\xcc\x83t\x83@\x83C\x83\x8b\x82\xc5\x82\xb7\x81B'750b'</pre></body></html>')751unicode_html = shift_jis_html.decode("shift-jis")752soup = self.soup(unicode_html)753754# Make sure the parse tree is correctly encoded to various755# encodings.756self.assertEqual(soup.encode("utf-8"), unicode_html.encode("utf-8"))757self.assertEqual(soup.encode("euc_jp"), unicode_html.encode("euc_jp"))758759def test_real_hebrew_document(self):760# A real-world test to make sure we can convert ISO-8859-9 (a761# Hebrew encoding) to UTF-8.762hebrew_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>'763soup = self.soup(764hebrew_document, from_encoding="iso8859-8")765# Some tree builders call it iso8859-8, others call it iso-8859-9.766# That's not a difference we really care about.767assert soup.original_encoding in ('iso8859-8', 'iso-8859-8')768self.assertEqual(769soup.encode('utf-8'),770hebrew_document.decode("iso8859-8").encode("utf-8"))771772def test_meta_tag_reflects_current_encoding(self):773# Here's the <meta> tag saying that a document is774# encoded in Shift-JIS.775meta_tag = ('<meta content="text/html; charset=x-sjis" '776'http-equiv="Content-type"/>')777778# Here's a document incorporating that meta tag.779shift_jis_html = (780'<html><head>\n%s\n'781'<meta http-equiv="Content-language" content="ja"/>'782'</head><body>Shift-JIS markup goes here.') % meta_tag783soup = self.soup(shift_jis_html)784785# Parse the document, and the charset is seemingly unaffected.786parsed_meta = soup.find('meta', {'http-equiv': 'Content-type'})787content = parsed_meta['content']788self.assertEqual('text/html; charset=x-sjis', content)789790# But that value is actually a ContentMetaAttributeValue object.791self.assertTrue(isinstance(content, ContentMetaAttributeValue))792793# And it will take on a value that reflects its current794# encoding.795self.assertEqual('text/html; charset=utf8', content.encode("utf8"))796797# For the rest of the story, see TestSubstitutions in798# test_tree.py.799800def test_html5_style_meta_tag_reflects_current_encoding(self):801# Here's the <meta> tag saying that a document is802# encoded in Shift-JIS.803meta_tag = ('<meta id="encoding" charset="x-sjis" />')804805# Here's a document incorporating that meta tag.806shift_jis_html = (807'<html><head>\n%s\n'808'<meta http-equiv="Content-language" content="ja"/>'809'</head><body>Shift-JIS markup goes here.') % meta_tag810soup = self.soup(shift_jis_html)811812# Parse the document, and the charset is seemingly unaffected.813parsed_meta = soup.find('meta', id="encoding")814charset = parsed_meta['charset']815self.assertEqual('x-sjis', charset)816817# But that value is actually a CharsetMetaAttributeValue object.818self.assertTrue(isinstance(charset, CharsetMetaAttributeValue))819820# And it will take on a value that reflects its current821# encoding.822self.assertEqual('utf8', charset.encode("utf8"))823824def test_python_specific_encodings_not_used_in_charset(self):825# You can encode an HTML document using a Python-specific826# encoding, but that encoding won't be mentioned _inside_ the827# resulting document. Instead, the document will appear to828# have no encoding.829for markup in [830b'<meta charset="utf8"></head>'831b'<meta id="encoding" charset="utf-8" />'832]:833soup = self.soup(markup)834for encoding in PYTHON_SPECIFIC_ENCODINGS:835if encoding in (836'idna', 'mbcs', 'oem', 'undefined',837'string_escape', 'string-escape'838):839# For one reason or another, these will raise an840# exception if we actually try to use them, so don't841# bother.842continue843encoded = soup.encode(encoding)844assert b'meta charset=""' in encoded845assert encoding.encode("ascii") not in encoded846847def test_tag_with_no_attributes_can_have_attributes_added(self):848data = self.soup("<a>text</a>")849data.a['foo'] = 'bar'850self.assertEqual('<a foo="bar">text</a>', data.a.decode())851852def test_worst_case(self):853"""Test the worst case (currently) for linking issues."""854855soup = self.soup(BAD_DOCUMENT)856self.linkage_validator(soup)857858859class XMLTreeBuilderSmokeTest(object):860861def test_pickle_and_unpickle_identity(self):862# Pickling a tree, then unpickling it, yields a tree identical863# to the original.864tree = self.soup("<a><b>foo</a>")865dumped = pickle.dumps(tree, 2)866loaded = pickle.loads(dumped)867self.assertEqual(loaded.__class__, BeautifulSoup)868self.assertEqual(loaded.decode(), tree.decode())869870def test_docstring_generated(self):871soup = self.soup("<root/>")872self.assertEqual(873soup.encode(), b'<?xml version="1.0" encoding="utf-8"?>\n<root/>')874875def test_xml_declaration(self):876markup = b"""<?xml version="1.0" encoding="utf8"?>\n<foo/>"""877soup = self.soup(markup)878self.assertEqual(markup, soup.encode("utf8"))879880def test_python_specific_encodings_not_used_in_xml_declaration(self):881# You can encode an XML document using a Python-specific882# encoding, but that encoding won't be mentioned _inside_ the883# resulting document.884markup = b"""<?xml version="1.0"?>\n<foo/>"""885soup = self.soup(markup)886for encoding in PYTHON_SPECIFIC_ENCODINGS:887if encoding in (888'idna', 'mbcs', 'oem', 'undefined',889'string_escape', 'string-escape'890):891# For one reason or another, these will raise an892# exception if we actually try to use them, so don't893# bother.894continue895encoded = soup.encode(encoding)896assert b'<?xml version="1.0"?>' in encoded897assert encoding.encode("ascii") not in encoded898899def test_processing_instruction(self):900markup = b"""<?xml version="1.0" encoding="utf8"?>\n<?PITarget PIContent?>"""901soup = self.soup(markup)902self.assertEqual(markup, soup.encode("utf8"))903904def test_real_xhtml_document(self):905"""A real XHTML document should come out *exactly* the same as it went in."""906markup = b"""<?xml version="1.0" encoding="utf-8"?>907<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">908<html xmlns="http://www.w3.org/1999/xhtml">909<head><title>Hello.</title></head>910<body>Goodbye.</body>911</html>"""912soup = self.soup(markup)913self.assertEqual(914soup.encode("utf-8"), markup)915916def test_nested_namespaces(self):917doc = b"""<?xml version="1.0" encoding="utf-8"?>918<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">919<parent xmlns="http://ns1/">920<child xmlns="http://ns2/" xmlns:ns3="http://ns3/">921<grandchild ns3:attr="value" xmlns="http://ns4/"/>922</child>923</parent>"""924soup = self.soup(doc)925self.assertEqual(doc, soup.encode())926927def test_formatter_processes_script_tag_for_xml_documents(self):928doc = """929<script type="text/javascript">930</script>931"""932soup = BeautifulSoup(doc, "lxml-xml")933# lxml would have stripped this while parsing, but we can add934# it later.935soup.script.string = 'console.log("< < hey > > ");'936encoded = soup.encode()937self.assertTrue(b"< < hey > >" in encoded)938939def test_can_parse_unicode_document(self):940markup = '<?xml version="1.0" encoding="euc-jp"><root>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</root>'941soup = self.soup(markup)942self.assertEqual('Sacr\xe9 bleu!', soup.root.string)943944def test_popping_namespaced_tag(self):945markup = '<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>'946soup = self.soup(markup)947self.assertEqual(948str(soup.rss), markup)949950def test_docstring_includes_correct_encoding(self):951soup = self.soup("<root/>")952self.assertEqual(953soup.encode("latin1"),954b'<?xml version="1.0" encoding="latin1"?>\n<root/>')955956def test_large_xml_document(self):957"""A large XML document should come out the same as it went in."""958markup = (b'<?xml version="1.0" encoding="utf-8"?>\n<root>'959+ b'0' * (2**12)960+ b'</root>')961soup = self.soup(markup)962self.assertEqual(soup.encode("utf-8"), markup)963964965def test_tags_are_empty_element_if_and_only_if_they_are_empty(self):966self.assertSoupEquals("<p>", "<p/>")967self.assertSoupEquals("<p>foo</p>")968969def test_namespaces_are_preserved(self):970markup = '<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>'971soup = self.soup(markup)972root = soup.root973self.assertEqual("http://example.com/", root['xmlns:a'])974self.assertEqual("http://example.net/", root['xmlns:b'])975976def test_closing_namespaced_tag(self):977markup = '<p xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:date>20010504</dc:date></p>'978soup = self.soup(markup)979self.assertEqual(str(soup.p), markup)980981def test_namespaced_attributes(self):982markup = '<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><bar xsi:schemaLocation="http://www.example.com"/></foo>'983soup = self.soup(markup)984self.assertEqual(str(soup.foo), markup)985986def test_namespaced_attributes_xml_namespace(self):987markup = '<foo xml:lang="fr">bar</foo>'988soup = self.soup(markup)989self.assertEqual(str(soup.foo), markup)990991def test_find_by_prefixed_name(self):992doc = """<?xml version="1.0" encoding="utf-8"?>993<Document xmlns="http://example.com/ns0"994xmlns:ns1="http://example.com/ns1"995xmlns:ns2="http://example.com/ns2"996<ns1:tag>foo</ns1:tag>997<ns1:tag>bar</ns1:tag>998<ns2:tag key="value">baz</ns2:tag>999</Document>1000"""1001soup = self.soup(doc)10021003# There are three <tag> tags.1004self.assertEqual(3, len(soup.find_all('tag')))10051006# But two of them are ns1:tag and one of them is ns2:tag.1007self.assertEqual(2, len(soup.find_all('ns1:tag')))1008self.assertEqual(1, len(soup.find_all('ns2:tag')))10091010self.assertEqual(1, len(soup.find_all('ns2:tag', key='value')))1011self.assertEqual(3, len(soup.find_all(['ns1:tag', 'ns2:tag'])))10121013def test_copy_tag_preserves_namespace(self):1014xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>1015<w:document xmlns:w="http://example.com/ns0"/>"""10161017soup = self.soup(xml)1018tag = soup.document1019duplicate = copy.copy(tag)10201021# The two tags have the same namespace prefix.1022self.assertEqual(tag.prefix, duplicate.prefix)10231024def test_worst_case(self):1025"""Test the worst case (currently) for linking issues."""10261027soup = self.soup(BAD_DOCUMENT)1028self.linkage_validator(soup)102910301031class HTML5TreeBuilderSmokeTest(HTMLTreeBuilderSmokeTest):1032"""Smoke test for a tree builder that supports HTML5."""10331034def test_real_xhtml_document(self):1035# Since XHTML is not HTML5, HTML5 parsers are not tested to handle1036# XHTML documents in any particular way.1037pass10381039def test_html_tags_have_namespace(self):1040markup = "<a>"1041soup = self.soup(markup)1042self.assertEqual("http://www.w3.org/1999/xhtml", soup.a.namespace)10431044def test_svg_tags_have_namespace(self):1045markup = '<svg><circle/></svg>'1046soup = self.soup(markup)1047namespace = "http://www.w3.org/2000/svg"1048self.assertEqual(namespace, soup.svg.namespace)1049self.assertEqual(namespace, soup.circle.namespace)105010511052def test_mathml_tags_have_namespace(self):1053markup = '<math><msqrt>5</msqrt></math>'1054soup = self.soup(markup)1055namespace = 'http://www.w3.org/1998/Math/MathML'1056self.assertEqual(namespace, soup.math.namespace)1057self.assertEqual(namespace, soup.msqrt.namespace)10581059def test_xml_declaration_becomes_comment(self):1060markup = '<?xml version="1.0" encoding="utf-8"?><html></html>'1061soup = self.soup(markup)1062self.assertTrue(isinstance(soup.contents[0], Comment))1063self.assertEqual(soup.contents[0], '?xml version="1.0" encoding="utf-8"?')1064self.assertEqual("html", soup.contents[0].next_element.name)10651066def skipIf(condition, reason):1067def nothing(test, *args, **kwargs):1068return None10691070def decorator(test_item):1071if condition:1072return nothing1073else:1074return test_item10751076return decorator107710781079