# -*- coding: utf-8 -*-
"""Tests for Beautiful Soup's tree traversal methods.
The tree traversal methods are the main advantage of using Beautiful
Soup over other parsers.
Different parsers will build different Beautiful Soup trees given the
same markup, but all Beautiful Soup trees can be traversed with the
methods tested here.
"""
import copy
import cPickle as pickle
import re
from bs4 import BeautifulSoup
from bs4.builder import builder_registry
from bs4.element import CData, SoupStrainer, Tag
from bs4.testing import SoupTest
class TreeTest(SoupTest):
def assertSelects(self, tags, should_match):
"""Make sure that the given tags have the correct text.
This is used in tests that define a bunch of tags, each
containing a single string, and then select certain strings by
some mechanism.
"""
self.assertEqual([tag.string for tag in tags], should_match)
def assertSelectsIDs(self, tags, should_match):
"""Make sure that the given tags have the correct IDs.
This is used in tests that define a bunch of tags, each
containing a single string, and then select certain strings by
some mechanism.
"""
self.assertEqual([tag['id'] for tag in tags], should_match)
class TestFind(TreeTest):
"""Basic tests of the find() method.
find() just calls find_all() with limit=1, so it's not tested all
that thouroughly here.
"""
def test_find_tag(self):
soup = self.soup("1234")
self.assertEqual(soup.find("b").string, "2")
def test_unicode_text_find(self):
soup = self.soup(u'
''')
self.start = self.tree.b
def test_parent(self):
self.assertEquals(self.start.parent['id'], 'bottom')
self.assertEquals(self.start.parent.parent['id'], 'middle')
self.assertEquals(self.start.parent.parent.parent['id'], 'top')
def test_parent_of_top_tag_is_soup_object(self):
top_tag = self.tree.contents[0]
self.assertEquals(top_tag.parent, self.tree)
def test_soup_object_has_no_parent(self):
self.assertEquals(None, self.tree.parent)
def test_find_parents(self):
self.assertSelectsIDs(
self.start.find_parents('ul'), ['bottom', 'middle', 'top'])
self.assertSelectsIDs(
self.start.find_parents('ul', id="middle"), ['middle'])
def test_find_parent(self):
self.assertEquals(self.start.find_parent('ul')['id'], 'bottom')
def test_parent_of_text_element(self):
text = self.tree.find(text="Start here")
self.assertEquals(text.parent.name, 'b')
def test_text_element_find_parent(self):
text = self.tree.find(text="Start here")
self.assertEquals(text.find_parent('ul')['id'], 'bottom')
def test_parent_generator(self):
parents = [parent['id'] for parent in self.start.parents
if parent is not None and parent.has_key('id')]
self.assertEquals(parents, ['bottom', 'middle', 'top'])
class ProximityTest(TreeTest):
def setUp(self):
super(TreeTest, self).setUp()
self.tree = self.soup(
'OneTwoThree')
class TestNextOperations(ProximityTest):
def setUp(self):
super(TestNextOperations, self).setUp()
self.start = self.tree.b
def test_next(self):
self.assertEquals(self.start.next, "One")
self.assertEquals(self.start.next.next['id'], "2")
def test_next_of_last_item_is_none(self):
last = self.tree.find(text="Three")
self.assertEquals(last.next, None)
def test_next_of_root_is_none(self):
# The document root is outside the next/previous chain.
self.assertEquals(self.tree.next, None)
def test_find_all_next(self):
self.assertSelects(self.start.find_all_next('b'), ["Two", "Three"])
self.assertSelects(self.start.find_all_next(id=3), ["Three"])
def test_find_next(self):
self.assertEquals(self.start.find_next('b')['id'], '2')
self.assertEquals(self.start.find_next(text="Three"), "Three")
def test_find_next_for_text_element(self):
text = self.tree.find(text="One")
self.assertEquals(text.find_next("b").string, "Two")
self.assertSelects(text.find_all_next("b"), ["Two", "Three"])
def test_next_generator(self):
start = self.tree.find(text="Two")
successors = [node for node in start.next_elements]
# There are two successors: the final tag and its text contents.
# Then we go off the end.
tag, contents, none = successors
self.assertEquals(tag['id'], '3')
self.assertEquals(contents, "Three")
self.assertEquals(none, None)
# XXX Should next_elements really return None? Seems like it
# should just stop.
class TestPreviousOperations(ProximityTest):
def setUp(self):
super(TestPreviousOperations, self).setUp()
self.end = self.tree.find(text="Three")
def test_previous(self):
self.assertEquals(self.end.previous['id'], "3")
self.assertEquals(self.end.previous.previous, "Two")
def test_previous_of_first_item_is_none(self):
first = self.tree.find('html')
self.assertEquals(first.previous, None)
def test_previous_of_root_is_none(self):
# The document root is outside the next/previous chain.
# XXX This is broken!
#self.assertEquals(self.tree.previous, None)
pass
def test_find_all_previous(self):
# The tag containing the "Three" node is the predecessor
# of the "Three" node itself, which is why "Three" shows up
# here.
self.assertSelects(
self.end.find_all_previous('b'), ["Three", "Two", "One"])
self.assertSelects(self.end.find_all_previous(id=1), ["One"])
def test_find_previous(self):
self.assertEquals(self.end.find_previous('b')['id'], '3')
self.assertEquals(self.end.find_previous(text="One"), "One")
def test_find_previous_for_text_element(self):
text = self.tree.find(text="Three")
self.assertEquals(text.find_previous("b").string, "Three")
self.assertSelects(
text.find_all_previous("b"), ["Three", "Two", "One"])
def test_previous_generator(self):
start = self.tree.find(text="One")
predecessors = [node for node in start.previous_elements]
# There are four predecessors: the tag containing "One"
# the tag, the tag, and the tag. Then we
# go off the end.
b, body, head, html, none = predecessors
self.assertEquals(b['id'], '1')
self.assertEquals(body.name, "body")
self.assertEquals(head.name, "head")
self.assertEquals(html.name, "html")
self.assertEquals(none, None)
# Again, we shouldn't be returning None.
class SiblingTest(TreeTest):
def setUp(self):
super(SiblingTest, self).setUp()
markup = '''
'''
# All that whitespace looks good but makes the tests more
# difficult. Get rid of it.
markup = re.compile("\n\s*").sub("", markup)
self.tree = self.soup(markup)
class TestNextSibling(SiblingTest):
def setUp(self):
super(TestNextSibling, self).setUp()
self.start = self.tree.find(id="1")
def test_next_sibling_of_root_is_none(self):
self.assertEquals(self.tree.nextSibling, None)
def test_next_sibling(self):
self.assertEquals(self.start.nextSibling['id'], '2')
self.assertEquals(self.start.nextSibling.nextSibling['id'], '3')
# Note the difference between nextSibling and next.
self.assertEquals(self.start.next['id'], '1.1')
def test_next_sibling_may_not_exist(self):
self.assertEquals(self.tree.html.nextSibling, None)
nested_span = self.tree.find(id="1.1")
self.assertEquals(nested_span.nextSibling, None)
last_span = self.tree.find(id="4")
self.assertEquals(last_span.nextSibling, None)
def test_find_next_sibling(self):
self.assertEquals(self.start.find_next_sibling('span')['id'], '2')
def test_next_siblings(self):
self.assertSelectsIDs(self.start.find_next_siblings("span"),
['2', '3', '4'])
self.assertSelectsIDs(self.start.find_next_siblings(id='3'), ['3'])
def test_next_sibling_for_text_element(self):
soup = self.soup("Foobarbaz")
start = soup.find(text="Foo")
self.assertEquals(start.nextSibling.name, 'b')
self.assertEquals(start.nextSibling.nextSibling, 'baz')
self.assertSelects(start.find_next_siblings('b'), ['bar'])
self.assertEquals(start.find_next_sibling(text="baz"), "baz")
self.assertEquals(start.find_next_sibling(text="nonesuch"), None)
class TestPreviousSibling(SiblingTest):
def setUp(self):
super(TestPreviousSibling, self).setUp()
self.end = self.tree.find(id="4")
def test_previous_sibling_of_root_is_none(self):
self.assertEquals(self.tree.previousSibling, None)
def test_previous_sibling(self):
self.assertEquals(self.end.previousSibling['id'], '3')
self.assertEquals(self.end.previousSibling.previousSibling['id'], '2')
# Note the difference between previousSibling and previous.
self.assertEquals(self.end.previous['id'], '3.1')
def test_previous_sibling_may_not_exist(self):
self.assertEquals(self.tree.html.previousSibling, None)
nested_span = self.tree.find(id="1.1")
self.assertEquals(nested_span.previousSibling, None)
first_span = self.tree.find(id="1")
self.assertEquals(first_span.previousSibling, None)
def test_find_previous_sibling(self):
self.assertEquals(self.end.find_previous_sibling('span')['id'], '3')
def test_previous_siblings(self):
self.assertSelectsIDs(self.end.find_previous_siblings("span"),
['3', '2', '1'])
self.assertSelectsIDs(self.end.find_previous_siblings(id='1'), ['1'])
def test_previous_sibling_for_text_element(self):
soup = self.soup("Foobarbaz")
start = soup.find(text="baz")
self.assertEquals(start.previousSibling.name, 'b')
self.assertEquals(start.previousSibling.previousSibling, 'Foo')
self.assertSelects(start.find_previous_siblings('b'), ['bar'])
self.assertEquals(start.find_previous_sibling(text="Foo"), "Foo")
self.assertEquals(start.find_previous_sibling(text="nonesuch"), None)
class TestTreeModification(SoupTest):
def test_attribute_modification(self):
soup = self.soup('')
soup.a['id'] = 2
self.assertEqual(soup.decode(), self.document_for(''))
del(soup.a['id'])
self.assertEqual(soup.decode(), self.document_for(''))
soup.a['id2'] = 'foo'
self.assertEqual(soup.decode(), self.document_for(''))
def test_new_tag_creation(self):
builder = builder_registry.lookup('html5lib')()
soup = self.soup("", builder=builder)
a = Tag(soup, builder, 'a')
ol = Tag(soup, builder, 'ol')
a['href'] = 'http://foo.com/'
soup.body.insert(0, a)
soup.body.insert(1, ol)
self.assertEqual(
soup.body.encode(),
'')
def test_append_to_contents_moves_tag(self):
doc = """
Don't leave me here.
Don\'t leave!
"""
soup = self.soup(doc)
second_para = soup.find(id='2')
bold = soup.b
# Move the tag to the end of the second paragraph.
soup.find(id='2').append(soup.b)
# The tag is now a child of the second paragraph.
self.assertEqual(bold.parent, second_para)
self.assertEqual(
soup.decode(), self.document_for(
'
Don\'t leave me .
\n'
'
Don\'t leave!here
'))
def test_replace_tag_with_itself(self):
text = "Foo"
soup = self.soup(text)
c = soup.c
soup.c.replaceWith(c)
self.assertEquals(soup.decode(), self.document_for(text))
def test_replace_final_node(self):
soup = self.soup("Argh!")
soup.find(text="Argh!").replaceWith("Hooray!")
new_text = soup.find(text="Hooray!")
b = soup.b
self.assertEqual(new_text.previous, b)
self.assertEqual(new_text.parent, b)
self.assertEqual(new_text.previous.next, new_text)
self.assertEqual(new_text.next, None)
def test_consecutive_text_nodes(self):
# A builder should never create two consecutive text nodes,
# but if you insert one next to another, Beautiful Soup will
# handle it correctly.
soup = self.soup("Argh!")
soup.b.insert(1, "Hooray!")
self.assertEqual(
soup.decode(), self.document_for(
"Argh!Hooray!"))
new_text = soup.find(text="Hooray!")
self.assertEqual(new_text.previous, "Argh!")
self.assertEqual(new_text.previous.next, new_text)
self.assertEqual(new_text.previousSibling, "Argh!")
self.assertEqual(new_text.previousSibling.nextSibling, new_text)
self.assertEqual(new_text.nextSibling, None)
self.assertEqual(new_text.next, soup.c)
def test_insert_tag(self):
builder = self.default_builder
soup = self.soup(
"Findlady!", builder=builder)
magic_tag = Tag(soup, builder, 'magictag')
magic_tag.insert(0, "the")
soup.a.insert(1, magic_tag)
self.assertEqual(
soup.decode(), self.document_for(
"Findthelady!"))
# Make sure all the relationships are hooked up correctly.
b_tag = soup.b
self.assertEqual(b_tag.nextSibling, magic_tag)
self.assertEqual(magic_tag.previousSibling, b_tag)
find = b_tag.find(text="Find")
self.assertEqual(find.next, magic_tag)
self.assertEqual(magic_tag.previous, find)
c_tag = soup.c
self.assertEqual(magic_tag.nextSibling, c_tag)
self.assertEqual(c_tag.previousSibling, magic_tag)
the = magic_tag.find(text="the")
self.assertEqual(the.parent, magic_tag)
self.assertEqual(the.next, c_tag)
self.assertEqual(c_tag.previous, the)
def test_insert_works_on_empty_element_tag(self):
# This is a little strange, since most HTML parsers don't allow
# markup like this to come through. But in general, we don't
# know what the parser would or wouldn't have allowed, so
# I'm letting this succeed for now.
soup = self.soup(" ")
soup.br.insert(1, "Contents")
self.assertEquals(str(soup.br), " Contents")
def test_replace_with(self):
soup = self.soup(
"
There's no business like show business
")
no, show = soup.find_all('b')
show.replaceWith(no)
self.assertEquals(
soup.decode(),
self.document_for(
"
')
# Beautiful Soup used to try to rewrite the meta tag even if the
# meta tag got filtered out by the strainer. This test makes
# sure that doesn't happen.
strainer = SoupStrainer('pre')
soup = self.soup(markup, parse_only=strainer)
self.assertEquals(soup.contents[0].name, 'pre')
class TestEncoding(SoupTest):
"""Test the ability to encode objects into strings."""
def test_unicode_string_can_be_encoded(self):
html = u"\N{SNOWMAN}"
soup = self.soup(html)
self.assertEquals(soup.b.string.encode("utf-8"),
u"\N{SNOWMAN}".encode("utf-8"))
def test_tag_containing_unicode_string_can_be_encoded(self):
html = u"\N{SNOWMAN}"
soup = self.soup(html)
self.assertEquals(
soup.b.encode("utf-8"), html.encode("utf-8"))
class TestNavigableStringSubclasses(SoupTest):
def test_cdata(self):
# None of the current builders turn CDATA sections into CData
# objects, but you can create them manually.
soup = self.soup("")
cdata = CData("foo")
soup.insert(1, cdata)
self.assertEquals(str(soup), "")
self.assertEquals(soup.find(text="foo"), "foo")
self.assertEquals(soup.contents[0], "foo")