summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG4
-rw-r--r--bs4/testing.py306
-rw-r--r--bs4/tests/test_builder_registry.py73
-rw-r--r--bs4/tests/test_dammit.py112
-rw-r--r--bs4/tests/test_docs.py2
-rw-r--r--bs4/tests/test_formatter.py26
-rw-r--r--bs4/tests/test_html5lib.py51
-rw-r--r--bs4/tests/test_htmlparser.py36
-rw-r--r--bs4/tests/test_lxml.py21
-rw-r--r--bs4/tests/test_navigablestring.py59
-rw-r--r--bs4/tests/test_soup.py193
-rw-r--r--bs4/tests/test_tree.py1160
-rw-r--r--setup.py3
13 files changed, 981 insertions, 1065 deletions
diff --git a/CHANGELOG b/CHANGELOG
index 596f4da..200c7e5 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -3,6 +3,10 @@ Beautiful Soup's official support for Python 2 ended on December 31st,
4.9.3. In the Launchpad Bazaar repository, the final revision to support
Python 2 was revision 605.
+= 4.11.0 (Unreleased)
+
+* Ported unit tests to use pytest.
+
= 4.10.0 (20210907)
* This is the first release of Beautiful Soup to only support Python
diff --git a/bs4/testing.py b/bs4/testing.py
index 2f9046a..97914c0 100644
--- a/bs4/testing.py
+++ b/bs4/testing.py
@@ -7,9 +7,8 @@ __license__ = "MIT"
import pickle
import copy
import functools
-import unittest
import warnings
-from unittest import TestCase
+import pytest
from bs4 import BeautifulSoup
from bs4.element import (
CharsetMetaAttributeValue,
@@ -63,7 +62,7 @@ BAD_DOCUMENT = """A bare string
"""
-class SoupTest(unittest.TestCase):
+class SoupTest(object):
@property
def default_builder(self):
@@ -80,15 +79,18 @@ class SoupTest(unittest.TestCase):
The details depend on the builder.
"""
return self.default_builder(**kwargs).test_fragment_to_document(markup)
-
- def assertSoupEquals(self, to_parse, compare_parsed_to=None):
+
+ def assert_soup(self, to_parse, compare_parsed_to=None):
+ """Parse some markup using Beautiful Soup and verify that
+ the output markup is as expected.
+ """
builder = self.default_builder
obj = BeautifulSoup(to_parse, builder=builder)
if compare_parsed_to is None:
compare_parsed_to = to_parse
# Verify that the documents come out the same.
- self.assertEqual(obj.decode(), self.document_for(compare_parsed_to))
+ assert obj.decode() == self.document_for(compare_parsed_to)
# Also run some checks on the BeautifulSoup object itself:
@@ -99,9 +101,9 @@ class SoupTest(unittest.TestCase):
# The only tag in the tag stack is the one for the root
# document.
- self.assertEqual(
- [obj.ROOT_TAG_NAME], [x.name for x in obj.tagStack]
- )
+ assert [obj.ROOT_TAG_NAME] == [x.name for x in obj.tagStack]
+
+ assertSoupEquals = assert_soup
def assertConnectedness(self, element):
"""Ensure that next_element and previous_element are properly
@@ -110,8 +112,8 @@ class SoupTest(unittest.TestCase):
earlier = None
for e in element.descendants:
if earlier:
- self.assertEqual(e, earlier.next_element)
- self.assertEqual(earlier, e.previous_element)
+ assert e == earlier.next_element
+ assert earlier == e.previous_element
earlier = e
def linkage_validator(self, el, _recursive_call=False):
@@ -283,7 +285,7 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
]:
soup = self.soup("")
new_tag = soup.new_tag(name)
- self.assertEqual(True, new_tag.is_empty_element)
+ assert new_tag.is_empty_element == True
def test_special_string_containers(self):
soup = self.soup(
@@ -298,7 +300,7 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
assert isinstance(soup.style.string, Stylesheet)
# The contents of the style tag resemble an HTML comment, but
# it's not treated as a comment.
- self.assertEqual("<!--Some CSS-->", soup.style.string)
+ assert soup.style.string == "<!--Some CSS-->"
assert isinstance(soup.style.string, Stylesheet)
def test_pickle_and_unpickle_identity(self):
@@ -307,8 +309,8 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
tree = self.soup("<a><b>foo</a>")
dumped = pickle.dumps(tree, 2)
loaded = pickle.loads(dumped)
- self.assertEqual(loaded.__class__, BeautifulSoup)
- self.assertEqual(loaded.decode(), tree.decode())
+ assert loaded.__class__ == BeautifulSoup
+ assert loaded.decode() == tree.decode()
def assertDoctypeHandled(self, doctype_fragment):
"""Assert that a given doctype string is handled correctly."""
@@ -316,16 +318,13 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
# Make sure a Doctype object was created.
doctype = soup.contents[0]
- self.assertEqual(doctype.__class__, Doctype)
- self.assertEqual(doctype, doctype_fragment)
- self.assertEqual(
- soup.encode("utf8")[:len(doctype_str)],
- doctype_str
- )
+ assert doctype.__class__ == Doctype
+ assert doctype == doctype_fragment
+ assert soup.encode("utf8")[:len(doctype_str)] == doctype_str
# Make sure that the doctype was correctly associated with the
# parse tree and that the rest of the document parsed.
- self.assertEqual(soup.p.contents[0], 'foo')
+ assert soup.p.contents[0] == 'foo'
def _document_with_doctype(self, doctype_fragment, doctype_string="DOCTYPE"):
"""Generate and parse a document with the given doctype."""
@@ -343,7 +342,7 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
def test_empty_doctype(self):
soup = self.soup("<!DOCTYPE>")
doctype = soup.contents[0]
- self.assertEqual("", doctype.strip())
+ assert "" == doctype.strip()
def test_mixed_case_doctype(self):
# A lowercase or mixed-case doctype becomes a Doctype.
@@ -355,16 +354,13 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
# Make sure a Doctype object was created and that the DOCTYPE
# is uppercase.
doctype = soup.contents[0]
- self.assertEqual(doctype.__class__, Doctype)
- self.assertEqual(doctype, "html")
- self.assertEqual(
- soup.encode("utf8")[:len(doctype_str)],
- b"<!DOCTYPE html>"
- )
+ assert doctype.__class__ == Doctype
+ assert doctype == "html"
+ assert soup.encode("utf8")[:len(doctype_str)] == b"<!DOCTYPE html>"
# Make sure that the doctype was correctly associated with the
# parse tree and that the rest of the document parsed.
- self.assertEqual(soup.p.contents[0], 'foo')
+ assert soup.p.contents[0] == 'foo'
def test_public_doctype_with_url(self):
doctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"'
@@ -390,9 +386,7 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
<body>Goodbye.</body>
</html>"""
soup = self.soup(markup)
- self.assertEqual(
- soup.encode("utf-8").replace(b"\n", b""),
- markup.replace(b"\n", b""))
+ assert soup.encode("utf-8").replace(b"\n", b"") == markup.replace(b"\n", b"")
def test_namespaced_html(self):
"""When a namespaced XML document is parsed as HTML it should
@@ -400,7 +394,7 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
"""
markup = b"""<ns1:foo>content</ns1:foo><ns1:foo/><ns2:foo/>"""
soup = self.soup(markup)
- self.assertEqual(2, len(soup.find_all("ns1:foo")))
+ assert 2 == len(soup.find_all("ns1:foo"))
def test_processing_instruction(self):
# We test both Unicode and bytestring to verify that
@@ -409,11 +403,11 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
# need to process anything.
markup = """<?PITarget PIContent?>"""
soup = self.soup(markup)
- self.assertEqual(markup, soup.decode())
+ assert markup == soup.decode()
markup = b"""<?PITarget PIContent?>"""
soup = self.soup(markup)
- self.assertEqual(markup, soup.encode("utf8"))
+ assert markup == soup.encode("utf8")
def test_deepcopy(self):
"""Make sure you can copy the tree builder.
@@ -430,18 +424,18 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
shouldn't be presented that way.
"""
soup = self.soup("<p/>")
- self.assertFalse(soup.p.is_empty_element)
- self.assertEqual(str(soup.p), "<p></p>")
+ assert not soup.p.is_empty_element
+ assert str(soup.p) == "<p></p>"
def test_unclosed_tags_get_closed(self):
"""A tag that's not closed by the end of the document should be closed.
This applies to all tags except empty-element tags.
"""
- self.assertSoupEquals("<p>", "<p></p>")
- self.assertSoupEquals("<b>", "<b></b>")
+ self.assert_soup("<p>", "<p></p>")
+ self.assert_soup("<b>", "<b></b>")
- self.assertSoupEquals("<br>", "<br/>")
+ self.assert_soup("<br>", "<br/>")
def test_br_is_always_empty_element_tag(self):
"""A <br> tag is designated as an empty-element tag.
@@ -450,11 +444,11 @@ class HTMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
two tags, but it should always be an empty-element tag.
"""
soup = self.soup("<br></br>")
- self.assertTrue(soup.br.is_empty_element)
- self.assertEqual(str(soup.br), "<br/>")
+ assert soup.br.is_empty_element
+ assert str(soup.br) == "<br/>"
def test_nested_formatting_elements(self):
- self.assertSoupEquals("<em><em></em></em>")
+ self.assert_soup("<em><em></em></em>")
def test_double_head(self):
html = '''<!DOCTYPE html>
@@ -471,22 +465,22 @@ Hello, world!
</html>
'''
soup = self.soup(html)
- self.assertEqual("text/javascript", soup.find('script')['type'])
+ assert "text/javascript" == soup.find('script')['type']
def test_comment(self):
# Comments are represented as Comment objects.
markup = "<p>foo<!--foobar-->baz</p>"
- self.assertSoupEquals(markup)
+ self.assert_soup(markup)
soup = self.soup(markup)
comment = soup.find(text="foobar")
- self.assertEqual(comment.__class__, Comment)
+ assert comment.__class__ == Comment
# The comment is properly integrated into the tree.
foo = soup.find(text="foo")
- self.assertEqual(comment, foo.next_element)
+ assert comment == foo.next_element
baz = soup.find(text="baz")
- self.assertEqual(comment, baz.previous_element)
+ assert comment == baz.previous_element
def test_preserved_whitespace_in_pre_and_textarea(self):
"""Whitespace must be preserved in <pre> and <textarea> tags,
@@ -494,35 +488,35 @@ Hello, world!
"""
pre_markup = "<pre> </pre>"
textarea_markup = "<textarea> woo\nwoo </textarea>"
- self.assertSoupEquals(pre_markup)
- self.assertSoupEquals(textarea_markup)
+ self.assert_soup(pre_markup)
+ self.assert_soup(textarea_markup)
soup = self.soup(pre_markup)
- self.assertEqual(soup.pre.prettify(), pre_markup)
+ assert soup.pre.prettify() == pre_markup
soup = self.soup(textarea_markup)
- self.assertEqual(soup.textarea.prettify(), textarea_markup)
+ assert soup.textarea.prettify() == textarea_markup
soup = self.soup("<textarea></textarea>")
- self.assertEqual(soup.textarea.prettify(), "<textarea></textarea>")
+ assert soup.textarea.prettify() == "<textarea></textarea>"
def test_nested_inline_elements(self):
"""Inline elements can be nested indefinitely."""
b_tag = "<b>Inside a B tag</b>"
- self.assertSoupEquals(b_tag)
+ self.assert_soup(b_tag)
nested_b_tag = "<p>A <i>nested <b>tag</b></i></p>"
- self.assertSoupEquals(nested_b_tag)
+ self.assert_soup(nested_b_tag)
double_nested_b_tag = "<p>A <a>doubly <i>nested <b>tag</b></i></a></p>"
- self.assertSoupEquals(nested_b_tag)
+ self.assert_soup(nested_b_tag)
def test_nested_block_level_elements(self):
"""Block elements can be nested."""
soup = self.soup('<blockquote><p><b>Foo</b></p></blockquote>')
blockquote = soup.blockquote
- self.assertEqual(blockquote.p.b.string, 'Foo')
- self.assertEqual(blockquote.b.string, 'Foo')
+ assert blockquote.p.b.string == 'Foo'
+ assert blockquote.b.string == 'Foo'
def test_correctly_nested_tables(self):
"""One table can go inside another one."""
@@ -533,13 +527,13 @@ Hello, world!
'<tr><td>foo</td></tr>'
'</table></td>')
- self.assertSoupEquals(
+ self.assert_soup(
markup,
'<table id="1"><tr><td>Here\'s another table:'
'<table id="2"><tr><td>foo</td></tr></table>'
'</td></tr></table>')
- self.assertSoupEquals(
+ self.assert_soup(
"<table><thead><tr><td>Foo</td></tr></thead>"
"<tbody><tr><td>Bar</td></tr></tbody>"
"<tfoot><tr><td>Baz</td></tr></tfoot></table>")
@@ -550,11 +544,11 @@ Hello, world!
markup = '<div class=" foo bar "></a>'
soup = self.soup(markup)
- self.assertEqual(['foo', 'bar'], soup.div['class'])
+ assert ['foo', 'bar'] == soup.div['class']
# If you search by the literal name of the class it's like the whitespace
# wasn't there.
- self.assertEqual(soup.div, soup.find('div', class_="foo bar"))
+ assert soup.div == soup.find('div', class_="foo bar")
def test_deeply_nested_multivalued_attribute(self):
# html5lib can set the attributes of the same tag many times
@@ -562,7 +556,7 @@ Hello, world!
# multivalued attributes.
markup = '<table><div><div class="css"></div></div></table>'
soup = self.soup(markup)
- self.assertEqual(["css"], soup.div.div['class'])
+ assert ["css"] == soup.div.div['class']
def test_multivalued_attribute_on_html(self):
# html5lib uses a different API to set the attributes ot the
@@ -570,21 +564,21 @@ Hello, world!
# attributes.
markup = '<html class="a b"></html>'
soup = self.soup(markup)
- self.assertEqual(["a", "b"], soup.html['class'])
+ assert ["a", "b"] == soup.html['class']
def test_angle_brackets_in_attribute_values_are_escaped(self):
- self.assertSoupEquals('<a b="<a>"></a>', '<a b="&lt;a&gt;"></a>')
+ self.assert_soup('<a b="<a>"></a>', '<a b="&lt;a&gt;"></a>')
def test_strings_resembling_character_entity_references(self):
# "&T" and "&p" look like incomplete character entities, but they are
# not.
- self.assertSoupEquals(
+ self.assert_soup(
"<p>&bull; AT&T is in the s&p 500</p>",
"<p>\u2022 AT&amp;T is in the s&amp;p 500</p>"
)
def test_apos_entity(self):
- self.assertSoupEquals(
+ self.assert_soup(
"<p>Bob&apos;s Bar</p>",
"<p>Bob's Bar</p>",
)
@@ -599,45 +593,45 @@ Hello, world!
# characters.
markup = "<p>&#147;Hello&#148; &#45;&#9731;</p>"
soup = self.soup(markup)
- self.assertEqual("“Hello” -☃", soup.p.string)
+ assert "“Hello” -☃" == soup.p.string
def test_entities_in_attributes_converted_to_unicode(self):
expect = '<p id="pi\N{LATIN SMALL LETTER N WITH TILDE}ata"></p>'
- self.assertSoupEquals('<p id="pi&#241;ata"></p>', expect)
- self.assertSoupEquals('<p id="pi&#xf1;ata"></p>', expect)
- self.assertSoupEquals('<p id="pi&#Xf1;ata"></p>', expect)
- self.assertSoupEquals('<p id="pi&ntilde;ata"></p>', expect)
+ self.assert_soup('<p id="pi&#241;ata"></p>', expect)
+ self.assert_soup('<p id="pi&#xf1;ata"></p>', expect)
+ self.assert_soup('<p id="pi&#Xf1;ata"></p>', expect)
+ self.assert_soup('<p id="pi&ntilde;ata"></p>', expect)
def test_entities_in_text_converted_to_unicode(self):
expect = '<p>pi\N{LATIN SMALL LETTER N WITH TILDE}ata</p>'
- self.assertSoupEquals("<p>pi&#241;ata</p>", expect)
- self.assertSoupEquals("<p>pi&#xf1;ata</p>", expect)
- self.assertSoupEquals("<p>pi&#Xf1;ata</p>", expect)
- self.assertSoupEquals("<p>pi&ntilde;ata</p>", expect)
+ self.assert_soup("<p>pi&#241;ata</p>", expect)
+ self.assert_soup("<p>pi&#xf1;ata</p>", expect)
+ self.assert_soup("<p>pi&#Xf1;ata</p>", expect)
+ self.assert_soup("<p>pi&ntilde;ata</p>", expect)
def test_quot_entity_converted_to_quotation_mark(self):
- self.assertSoupEquals("<p>I said &quot;good day!&quot;</p>",
+ self.assert_soup("<p>I said &quot;good day!&quot;</p>",
'<p>I said "good day!"</p>')
def test_out_of_range_entity(self):
expect = "\N{REPLACEMENT CHARACTER}"
- self.assertSoupEquals("&#10000000000000;", expect)
- self.assertSoupEquals("&#x10000000000000;", expect)
- self.assertSoupEquals("&#1000000000;", expect)
+ self.assert_soup("&#10000000000000;", expect)
+ self.assert_soup("&#x10000000000000;", expect)
+ self.assert_soup("&#1000000000;", expect)
def test_multipart_strings(self):
"Mostly to prevent a recurrence of a bug in the html5lib treebuilder."
soup = self.soup("<html><h2>\nfoo</h2><p></p></html>")
- self.assertEqual("p", soup.h2.string.next_element.name)
- self.assertEqual("p", soup.p.name)
+ assert "p" == soup.h2.string.next_element.name
+ assert "p" == soup.p.name
self.assertConnectedness(soup)
def test_empty_element_tags(self):
"""Verify consistent handling of empty-element tags,
no matter how they come in through the markup.
"""
- self.assertSoupEquals('<br/><br/><br/>', "<br/><br/><br/>")
- self.assertSoupEquals('<br /><br /><br />', "<br/><br/><br/>")
+ self.assert_soup('<br/><br/><br/>', "<br/><br/><br/>")
+ self.assert_soup('<br /><br /><br />', "<br/><br/><br/>")
def test_head_tag_between_head_and_body(self):
"Prevent recurrence of a bug in the html5lib treebuilder."
@@ -647,7 +641,7 @@ Hello, world!
</html>
"""
soup = self.soup(content)
- self.assertNotEqual(None, soup.html.body)
+ assert soup.html.body is not None
self.assertConnectedness(soup)
def test_multiple_copies_of_a_tag(self):
@@ -674,18 +668,16 @@ Hello, world!
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>'
soup = self.soup(markup)
- self.assertEqual(markup, soup.encode())
+ assert markup == soup.encode()
html = soup.html
- self.assertEqual('http://www.w3.org/1999/xhtml', soup.html['xmlns'])
- self.assertEqual(
- 'http://www.w3.org/1998/Math/MathML', soup.html['xmlns:mathml'])
- self.assertEqual(
- 'http://www.w3.org/2000/svg', soup.html['xmlns:svg'])
+ assert 'http://www.w3.org/1999/xhtml' == soup.html['xmlns']
+ assert 'http://www.w3.org/1998/Math/MathML' == soup.html['xmlns:mathml']
+ assert 'http://www.w3.org/2000/svg' == soup.html['xmlns:svg']
def test_multivalued_attribute_value_becomes_list(self):
markup = b'<a class="foo bar">'
soup = self.soup(markup)
- self.assertEqual(['foo', 'bar'], soup.a['class'])
+ assert ['foo', 'bar'] == soup.a['class']
#
# Generally speaking, tests below this point are more tests of
@@ -700,67 +692,65 @@ Hello, world!
# encoding found in the declaration! The horror!
markup = '<html><head><meta encoding="euc-jp"></head><body>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</body>'
soup = self.soup(markup)
- self.assertEqual('Sacr\xe9 bleu!', soup.body.string)
+ assert 'Sacr\xe9 bleu!' == soup.body.string
def test_soupstrainer(self):
"""Parsers should be able to work with SoupStrainers."""
strainer = SoupStrainer("b")
soup = self.soup("A <b>bold</b> <meta/> <i>statement</i>",
parse_only=strainer)
- self.assertEqual(soup.decode(), "<b>bold</b>")
+ assert soup.decode() == "<b>bold</b>"
def test_single_quote_attribute_values_become_double_quotes(self):
- self.assertSoupEquals("<foo attr='bar'></foo>",
+ self.assert_soup("<foo attr='bar'></foo>",
'<foo attr="bar"></foo>')
def test_attribute_values_with_nested_quotes_are_left_alone(self):
text = """<foo attr='bar "brawls" happen'>a</foo>"""
- self.assertSoupEquals(text)
+ self.assert_soup(text)
def test_attribute_values_with_double_nested_quotes_get_quoted(self):
text = """<foo attr='bar "brawls" happen'>a</foo>"""
soup = self.soup(text)
soup.foo['attr'] = 'Brawls happen at "Bob\'s Bar"'
- self.assertSoupEquals(
+ self.assert_soup(
soup.foo.decode(),
"""<foo attr="Brawls happen at &quot;Bob\'s Bar&quot;">a</foo>""")
def test_ampersand_in_attribute_value_gets_escaped(self):
- self.assertSoupEquals('<this is="really messed up & stuff"></this>',
+ self.assert_soup('<this is="really messed up & stuff"></this>',
'<this is="really messed up &amp; stuff"></this>')
- self.assertSoupEquals(
+ self.assert_soup(
'<a href="http://example.org?a=1&b=2;3">foo</a>',
'<a href="http://example.org?a=1&amp;b=2;3">foo</a>')
def test_escaped_ampersand_in_attribute_value_is_left_alone(self):
- self.assertSoupEquals('<a href="http://example.org?a=1&amp;b=2;3"></a>')
+ self.assert_soup('<a href="http://example.org?a=1&amp;b=2;3"></a>')
def test_entities_in_strings_converted_during_parsing(self):
# Both XML and HTML entities are converted to Unicode characters
# during parsing.
text = "<p>&lt;&lt;sacr&eacute;&#32;bleu!&gt;&gt;</p>"
expected = "<p>&lt;&lt;sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</p>"
- self.assertSoupEquals(text, expected)
+ self.assert_soup(text, expected)
def test_smart_quotes_converted_on_the_way_in(self):
# Microsoft smart quotes are converted to Unicode characters during
# parsing.
quote = b"<p>\x91Foo\x92</p>"
soup = self.soup(quote)
- self.assertEqual(
- soup.p.string,
- "\N{LEFT SINGLE QUOTATION MARK}Foo\N{RIGHT SINGLE QUOTATION MARK}")
+ assert soup.p.string == "\N{LEFT SINGLE QUOTATION MARK}Foo\N{RIGHT SINGLE QUOTATION MARK}"
def test_non_breaking_spaces_converted_on_the_way_in(self):
soup = self.soup("<a>&nbsp;&nbsp;</a>")
- self.assertEqual(soup.a.string, "\N{NO-BREAK SPACE}" * 2)
+ assert soup.a.string == "\N{NO-BREAK SPACE}" * 2
def test_entities_converted_on_the_way_out(self):
text = "<p>&lt;&lt;sacr&eacute;&#32;bleu!&gt;&gt;</p>"
expected = "<p>&lt;&lt;sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</p>".encode("utf-8")
soup = self.soup(text)
- self.assertEqual(soup.p.encode("utf-8"), expected)
+ assert soup.p.encode("utf-8") == expected
def test_real_iso_latin_document(self):
# Smoke test of interrelated functionality, using an
@@ -787,7 +777,7 @@ Hello, world!
expected = expected.encode("utf-8")
# Ta-da!
- self.assertEqual(result, expected)
+ assert result == expected
def test_real_shift_jis_document(self):
# Smoke test to make sure the parser can handle a document in
@@ -803,8 +793,8 @@ Hello, world!
# Make sure the parse tree is correctly encoded to various
# encodings.
- self.assertEqual(soup.encode("utf-8"), unicode_html.encode("utf-8"))
- self.assertEqual(soup.encode("euc_jp"), unicode_html.encode("euc_jp"))
+ assert soup.encode("utf-8") == unicode_html.encode("utf-8")
+ assert soup.encode("euc_jp") == unicode_html.encode("euc_jp")
def test_real_hebrew_document(self):
# A real-world test to make sure we can convert ISO-8859-9 (a
@@ -815,9 +805,9 @@ Hello, world!
# Some tree builders call it iso8859-8, others call it iso-8859-9.
# That's not a difference we really care about.
assert soup.original_encoding in ('iso8859-8', 'iso-8859-8')
- self.assertEqual(
- soup.encode('utf-8'),
- hebrew_document.decode("iso8859-8").encode("utf-8"))
+ assert soup.encode('utf-8') == (
+ hebrew_document.decode("iso8859-8").encode("utf-8")
+ )
def test_meta_tag_reflects_current_encoding(self):
# Here's the <meta> tag saying that a document is
@@ -835,14 +825,14 @@ Hello, world!
# Parse the document, and the charset is seemingly unaffected.
parsed_meta = soup.find('meta', {'http-equiv': 'Content-type'})
content = parsed_meta['content']
- self.assertEqual('text/html; charset=x-sjis', content)
+ assert 'text/html; charset=x-sjis' == content
# But that value is actually a ContentMetaAttributeValue object.
- self.assertTrue(isinstance(content, ContentMetaAttributeValue))
+ assert isinstance(content, ContentMetaAttributeValue)
# And it will take on a value that reflects its current
# encoding.
- self.assertEqual('text/html; charset=utf8', content.encode("utf8"))
+ assert 'text/html; charset=utf8' == content.encode("utf8")
# For the rest of the story, see TestSubstitutions in
# test_tree.py.
@@ -862,14 +852,14 @@ Hello, world!
# Parse the document, and the charset is seemingly unaffected.
parsed_meta = soup.find('meta', id="encoding")
charset = parsed_meta['charset']
- self.assertEqual('x-sjis', charset)
+ assert 'x-sjis' == charset
# But that value is actually a CharsetMetaAttributeValue object.
- self.assertTrue(isinstance(charset, CharsetMetaAttributeValue))
+ assert isinstance(charset, CharsetMetaAttributeValue)
# And it will take on a value that reflects its current
# encoding.
- self.assertEqual('utf8', charset.encode("utf8"))
+ assert 'utf8' == charset.encode("utf8")
def test_python_specific_encodings_not_used_in_charset(self):
# You can encode an HTML document using a Python-specific
@@ -897,7 +887,7 @@ Hello, world!
def test_tag_with_no_attributes_can_have_attributes_added(self):
data = self.soup("<a>text</a>")
data.a['foo'] = 'bar'
- self.assertEqual('<a foo="bar">text</a>', data.a.decode())
+ assert '<a foo="bar">text</a>' == data.a.decode()
def test_closing_tag_with_no_opening_tag(self):
# Without BeautifulSoup.open_tag_counter, the </span> tag will
@@ -905,9 +895,7 @@ Hello, world!
# for a <span> tag that wasn't there. The result is that 'text2'
# will show up outside the body of the document.
soup = self.soup("<body><div><p>text1</p></span>text2</div></body>")
- self.assertEqual(
- "<body><div><p>text1</p>text2</div></body>", soup.body.decode()
- )
+ assert "<body><div><p>text1</p>text2</div></body>" == soup.body.decode()
def test_worst_case(self):
"""Test the worst case (currently) for linking issues."""
@@ -924,18 +912,17 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
tree = self.soup("<a><b>foo</a>")
dumped = pickle.dumps(tree, 2)
loaded = pickle.loads(dumped)
- self.assertEqual(loaded.__class__, BeautifulSoup)
- self.assertEqual(loaded.decode(), tree.decode())
+ assert loaded.__class__ == BeautifulSoup
+ assert loaded.decode() == tree.decode()
def test_docstring_generated(self):
soup = self.soup("<root/>")
- self.assertEqual(
- soup.encode(), b'<?xml version="1.0" encoding="utf-8"?>\n<root/>')
+ assert soup.encode() == b'<?xml version="1.0" encoding="utf-8"?>\n<root/>'
def test_xml_declaration(self):
markup = b"""<?xml version="1.0" encoding="utf8"?>\n<foo/>"""
soup = self.soup(markup)
- self.assertEqual(markup, soup.encode("utf8"))
+ assert markup == soup.encode("utf8")
def test_python_specific_encodings_not_used_in_xml_declaration(self):
# You can encode an XML document using a Python-specific
@@ -959,7 +946,7 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
def test_processing_instruction(self):
markup = b"""<?xml version="1.0" encoding="utf8"?>\n<?PITarget PIContent?>"""
soup = self.soup(markup)
- self.assertEqual(markup, soup.encode("utf8"))
+ assert markup == soup.encode("utf8")
def test_real_xhtml_document(self):
"""A real XHTML document should come out *exactly* the same as it went in."""
@@ -970,8 +957,7 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
<body>Goodbye.</body>
</html>"""
soup = self.soup(markup)
- self.assertEqual(
- soup.encode("utf-8"), markup)
+ assert soup.encode("utf-8") == markup
def test_nested_namespaces(self):
doc = b"""<?xml version="1.0" encoding="utf-8"?>
@@ -982,7 +968,7 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
</child>
</parent>"""
soup = self.soup(doc)
- self.assertEqual(doc, soup.encode())
+ assert doc == soup.encode()
def test_formatter_processes_script_tag_for_xml_documents(self):
doc = """
@@ -994,24 +980,21 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
# it later.
soup.script.string = 'console.log("< < hey > > ");'
encoded = soup.encode()
- self.assertTrue(b"&lt; &lt; hey &gt; &gt;" in encoded)
+ assert b"&lt; &lt; hey &gt; &gt;" in encoded
def test_can_parse_unicode_document(self):
markup = '<?xml version="1.0" encoding="euc-jp"><root>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</root>'
soup = self.soup(markup)
- self.assertEqual('Sacr\xe9 bleu!', soup.root.string)
+ assert 'Sacr\xe9 bleu!' == soup.root.string
def test_popping_namespaced_tag(self):
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>'
soup = self.soup(markup)
- self.assertEqual(
- str(soup.rss), markup)
+ assert str(soup.rss) == markup
def test_docstring_includes_correct_encoding(self):
soup = self.soup("<root/>")
- self.assertEqual(
- soup.encode("latin1"),
- b'<?xml version="1.0" encoding="latin1"?>\n<root/>')
+ assert soup.encode("latin1") == b'<?xml version="1.0" encoding="latin1"?>\n<root/>'
def test_large_xml_document(self):
"""A large XML document should come out the same as it went in."""
@@ -1019,34 +1002,33 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
+ b'0' * (2**12)
+ b'</root>')
soup = self.soup(markup)
- self.assertEqual(soup.encode("utf-8"), markup)
-
+ assert soup.encode("utf-8") == markup
def test_tags_are_empty_element_if_and_only_if_they_are_empty(self):
- self.assertSoupEquals("<p>", "<p/>")
- self.assertSoupEquals("<p>foo</p>")
+ self.assert_soup("<p>", "<p/>")
+ self.assert_soup("<p>foo</p>")
def test_namespaces_are_preserved(self):
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>'
soup = self.soup(markup)
root = soup.root
- self.assertEqual("http://example.com/", root['xmlns:a'])
- self.assertEqual("http://example.net/", root['xmlns:b'])
+ assert "http://example.com/" == root['xmlns:a']
+ assert "http://example.net/" == root['xmlns:b']
def test_closing_namespaced_tag(self):
markup = '<p xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:date>20010504</dc:date></p>'
soup = self.soup(markup)
- self.assertEqual(str(soup.p), markup)
+ assert str(soup.p) == markup
def test_namespaced_attributes(self):
markup = '<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><bar xsi:schemaLocation="http://www.example.com"/></foo>'
soup = self.soup(markup)
- self.assertEqual(str(soup.foo), markup)
+ assert str(soup.foo) == markup
def test_namespaced_attributes_xml_namespace(self):
markup = '<foo xml:lang="fr">bar</foo>'
soup = self.soup(markup)
- self.assertEqual(str(soup.foo), markup)
+ assert str(soup.foo) == markup
def test_find_by_prefixed_name(self):
doc = """<?xml version="1.0" encoding="utf-8"?>
@@ -1061,14 +1043,14 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
soup = self.soup(doc)
# There are three <tag> tags.
- self.assertEqual(3, len(soup.find_all('tag')))
+ assert 3 == len(soup.find_all('tag'))
# But two of them are ns1:tag and one of them is ns2:tag.
- self.assertEqual(2, len(soup.find_all('ns1:tag')))
- self.assertEqual(1, len(soup.find_all('ns2:tag')))
+ assert 2 == len(soup.find_all('ns1:tag'))
+ assert 1 == len(soup.find_all('ns2:tag'))
- self.assertEqual(1, len(soup.find_all('ns2:tag', key='value')))
- self.assertEqual(3, len(soup.find_all(['ns1:tag', 'ns2:tag'])))
+ assert 1, len(soup.find_all('ns2:tag', key='value'))
+ assert 3, len(soup.find_all(['ns1:tag', 'ns2:tag']))
def test_copy_tag_preserves_namespace(self):
xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
@@ -1079,7 +1061,7 @@ class XMLTreeBuilderSmokeTest(TreeBuilderSmokeTest):
duplicate = copy.copy(tag)
# The two tags have the same namespace prefix.
- self.assertEqual(tag.prefix, duplicate.prefix)
+ assert tag.prefix == duplicate.prefix
def test_worst_case(self):
"""Test the worst case (currently) for linking issues."""
@@ -1099,29 +1081,29 @@ class HTML5TreeBuilderSmokeTest(HTMLTreeBuilderSmokeTest):
def test_html_tags_have_namespace(self):
markup = "<a>"
soup = self.soup(markup)
- self.assertEqual("http://www.w3.org/1999/xhtml", soup.a.namespace)
+ assert "http://www.w3.org/1999/xhtml" == soup.a.namespace
def test_svg_tags_have_namespace(self):
markup = '<svg><circle/></svg>'
soup = self.soup(markup)
namespace = "http://www.w3.org/2000/svg"
- self.assertEqual(namespace, soup.svg.namespace)
- self.assertEqual(namespace, soup.circle.namespace)
+ assert namespace == soup.svg.namespace
+ assert namespace == soup.circle.namespace
def test_mathml_tags_have_namespace(self):
markup = '<math><msqrt>5</msqrt></math>'
soup = self.soup(markup)
namespace = 'http://www.w3.org/1998/Math/MathML'
- self.assertEqual(namespace, soup.math.namespace)
- self.assertEqual(namespace, soup.msqrt.namespace)
+ assert namespace == soup.math.namespace
+ assert namespace == soup.msqrt.namespace
def test_xml_declaration_becomes_comment(self):
markup = '<?xml version="1.0" encoding="utf-8"?><html></html>'
soup = self.soup(markup)
- self.assertTrue(isinstance(soup.contents[0], Comment))
- self.assertEqual(soup.contents[0], '?xml version="1.0" encoding="utf-8"?')
- self.assertEqual("html", soup.contents[0].next_element.name)
+ assert isinstance(soup.contents[0], Comment)
+ assert soup.contents[0] == '?xml version="1.0" encoding="utf-8"?'
+ assert "html" == soup.contents[0].next_element.name
def skipIf(condition, reason):
def nothing(test, *args, **kwargs):
diff --git a/bs4/tests/test_builder_registry.py b/bs4/tests/test_builder_registry.py
index 90cad82..5fa874c 100644
--- a/bs4/tests/test_builder_registry.py
+++ b/bs4/tests/test_builder_registry.py
@@ -1,6 +1,6 @@
"""Tests of the builder registry."""
-import unittest
+import pytest
import warnings
from bs4 import BeautifulSoup
@@ -26,46 +26,36 @@ except ImportError:
LXML_PRESENT = False
-class BuiltInRegistryTest(unittest.TestCase):
+class TestBuiltInRegistry(object):
"""Test the built-in registry with the default builders registered."""
def test_combination(self):
+ assert registry.lookup('strict', 'html') == HTMLParserTreeBuilder
if LXML_PRESENT:
- self.assertEqual(registry.lookup('fast', 'html'),
- LXMLTreeBuilder)
-
- if LXML_PRESENT:
- self.assertEqual(registry.lookup('permissive', 'xml'),
- LXMLTreeBuilderForXML)
- self.assertEqual(registry.lookup('strict', 'html'),
- HTMLParserTreeBuilder)
+ assert registry.lookup('fast', 'html') == LXMLTreeBuilder
+ assert registry.lookup('permissive', 'xml') == LXMLTreeBuilderForXML
if HTML5LIB_PRESENT:
- self.assertEqual(registry.lookup('html5lib', 'html'),
- HTML5TreeBuilder)
+ assert registry.lookup('html5lib', 'html') == HTML5TreeBuilder
def test_lookup_by_markup_type(self):
if LXML_PRESENT:
- self.assertEqual(registry.lookup('html'), LXMLTreeBuilder)
- self.assertEqual(registry.lookup('xml'), LXMLTreeBuilderForXML)
+ assert registry.lookup('html') == LXMLTreeBuilder
+ assert registry.lookup('xml') == LXMLTreeBuilderForXML
else:
- self.assertEqual(registry.lookup('xml'), None)
+ assert registry.lookup('xml') == None
if HTML5LIB_PRESENT:
- self.assertEqual(registry.lookup('html'), HTML5TreeBuilder)
+ assert registry.lookup('html') == HTML5TreeBuilder
else:
- self.assertEqual(registry.lookup('html'), HTMLParserTreeBuilder)
+ assert registry.lookup('html') == HTMLParserTreeBuilder
def test_named_library(self):
if LXML_PRESENT:
- self.assertEqual(registry.lookup('lxml', 'xml'),
- LXMLTreeBuilderForXML)
- self.assertEqual(registry.lookup('lxml', 'html'),
- LXMLTreeBuilder)
+ assert registry.lookup('lxml', 'xml') == LXMLTreeBuilderForXML
+ assert registry.lookup('lxml', 'html') == LXMLTreeBuilder
if HTML5LIB_PRESENT:
- self.assertEqual(registry.lookup('html5lib'),
- HTML5TreeBuilder)
+ assert registry.lookup('html5lib') == HTML5TreeBuilder
- self.assertEqual(registry.lookup('html.parser'),
- HTMLParserTreeBuilder)
+ assert registry.lookup('html.parser') == HTMLParserTreeBuilder
def test_beautifulsoup_constructor_does_lookup(self):
@@ -77,16 +67,17 @@ class BuiltInRegistryTest(unittest.TestCase):
BeautifulSoup("", features="html")
# Or a list of strings.
BeautifulSoup("", features=["html", "fast"])
-
+ pass
+
# You'll get an exception if BS can't find an appropriate
# builder.
- self.assertRaises(ValueError, BeautifulSoup,
- "", features="no-such-feature")
+ with pytest.raises(ValueError):
+ BeautifulSoup("", features="no-such-feature")
-class RegistryTest(unittest.TestCase):
+class TestRegistry(object):
"""Test the TreeBuilderRegistry class in general."""
- def setUp(self):
+ def setup_method(self):
self.registry = TreeBuilderRegistry()
def builder_for_features(self, *feature_list):
@@ -101,28 +92,28 @@ class RegistryTest(unittest.TestCase):
# Since the builder advertises no features, you can't find it
# by looking up features.
- self.assertEqual(self.registry.lookup('foo'), None)
+ assert self.registry.lookup('foo') is None
# But you can find it by doing a lookup with no features, if
# this happens to be the only registered builder.
- self.assertEqual(self.registry.lookup(), builder)
+ assert self.registry.lookup() == builder
def test_register_with_features_makes_lookup_succeed(self):
builder = self.builder_for_features('foo', 'bar')
- self.assertEqual(self.registry.lookup('foo'), builder)
- self.assertEqual(self.registry.lookup('bar'), builder)
+ assert self.registry.lookup('foo') is builder
+ assert self.registry.lookup('bar') is builder
def test_lookup_fails_when_no_builder_implements_feature(self):
builder = self.builder_for_features('foo', 'bar')
- self.assertEqual(self.registry.lookup('baz'), None)
+ assert self.registry.lookup('baz') is None
def test_lookup_gets_most_recent_registration_when_no_feature_specified(self):
builder1 = self.builder_for_features('foo')
builder2 = self.builder_for_features('bar')
- self.assertEqual(self.registry.lookup(), builder2)
+ assert self.registry.lookup() == builder2
def test_lookup_fails_when_no_tree_builders_registered(self):
- self.assertEqual(self.registry.lookup(), None)
+ assert self.registry.lookup() is None
def test_lookup_gets_most_recent_builder_supporting_all_features(self):
has_one = self.builder_for_features('foo')
@@ -134,14 +125,12 @@ class RegistryTest(unittest.TestCase):
# There are two builders featuring 'foo' and 'bar', but
# the one that also features 'quux' was registered later.
- self.assertEqual(self.registry.lookup('foo', 'bar'),
- has_both_late)
+ assert self.registry.lookup('foo', 'bar') == has_both_late
# There is only one builder featuring 'foo', 'bar', and 'baz'.
- self.assertEqual(self.registry.lookup('foo', 'bar', 'baz'),
- has_both_early)
+ assert self.registry.lookup('foo', 'bar', 'baz') == has_both_early
def test_lookup_fails_when_cannot_reconcile_requested_features(self):
builder1 = self.builder_for_features('foo', 'bar')
builder2 = self.builder_for_features('foo', 'baz')
- self.assertEqual(self.registry.lookup('bar', 'baz'), None)
+ assert self.registry.lookup('bar', 'baz') is None
diff --git a/bs4/tests/test_dammit.py b/bs4/tests/test_dammit.py
index 5177503..348c600 100644
--- a/bs4/tests/test_dammit.py
+++ b/bs4/tests/test_dammit.py
@@ -1,6 +1,6 @@
# encoding: utf-8
+import pytest
import logging
-import unittest
import bs4
from bs4 import BeautifulSoup
from bs4.dammit import (
@@ -8,67 +8,62 @@ from bs4.dammit import (
UnicodeDammit,
)
-class TestUnicodeDammit(unittest.TestCase):
+class TestUnicodeDammit(object):
"""Standalone tests of UnicodeDammit."""
def test_unicode_input(self):
markup = "I'm already Unicode! \N{SNOWMAN}"
dammit = UnicodeDammit(markup)
- self.assertEqual(dammit.unicode_markup, markup)
+ assert dammit.unicode_markup == markup
def test_smart_quotes_to_unicode(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup)
- self.assertEqual(
- dammit.unicode_markup, "<foo>\u2018\u2019\u201c\u201d</foo>")
+ assert dammit.unicode_markup == "<foo>\u2018\u2019\u201c\u201d</foo>"
def test_smart_quotes_to_xml_entities(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup, smart_quotes_to="xml")
- self.assertEqual(
- dammit.unicode_markup, "<foo>&#x2018;&#x2019;&#x201C;&#x201D;</foo>")
+ assert dammit.unicode_markup == "<foo>&#x2018;&#x2019;&#x201C;&#x201D;</foo>"
def test_smart_quotes_to_html_entities(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup, smart_quotes_to="html")
- self.assertEqual(
- dammit.unicode_markup, "<foo>&lsquo;&rsquo;&ldquo;&rdquo;</foo>")
+ assert dammit.unicode_markup == "<foo>&lsquo;&rsquo;&ldquo;&rdquo;</foo>"
def test_smart_quotes_to_ascii(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup, smart_quotes_to="ascii")
- self.assertEqual(
- dammit.unicode_markup, """<foo>''""</foo>""")
+ assert dammit.unicode_markup == """<foo>''""</foo>"""
def test_detect_utf8(self):
utf8 = b"Sacr\xc3\xa9 bleu! \xe2\x98\x83"
dammit = UnicodeDammit(utf8)
- self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
- self.assertEqual(dammit.unicode_markup, 'Sacr\xe9 bleu! \N{SNOWMAN}')
-
+ assert dammit.original_encoding.lower() == 'utf-8'
+ assert dammit.unicode_markup == 'Sacr\xe9 bleu! \N{SNOWMAN}'
def test_convert_hebrew(self):
hebrew = b"\xed\xe5\xec\xf9"
dammit = UnicodeDammit(hebrew, ["iso-8859-8"])
- self.assertEqual(dammit.original_encoding.lower(), 'iso-8859-8')
- self.assertEqual(dammit.unicode_markup, '\u05dd\u05d5\u05dc\u05e9')
+ assert dammit.original_encoding.lower() == 'iso-8859-8'
+ assert dammit.unicode_markup == '\u05dd\u05d5\u05dc\u05e9'
def test_dont_see_smart_quotes_where_there_are_none(self):
utf_8 = b"\343\202\261\343\203\274\343\202\277\343\202\244 Watch"
dammit = UnicodeDammit(utf_8)
- self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
- self.assertEqual(dammit.unicode_markup.encode("utf-8"), utf_8)
+ assert dammit.original_encoding.lower() == 'utf-8'
+ assert dammit.unicode_markup.encode("utf-8") == utf_8
def test_ignore_inappropriate_codecs(self):
utf8_data = "Räksmörgås".encode("utf-8")
dammit = UnicodeDammit(utf8_data, ["iso-8859-8"])
- self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
+ assert dammit.original_encoding.lower() == 'utf-8'
def test_ignore_invalid_codecs(self):
utf8_data = "Räksmörgås".encode("utf-8")
for bad_encoding in ['.utf8', '...', 'utF---16.!']:
dammit = UnicodeDammit(utf8_data, [bad_encoding])
- self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
+ assert dammit.original_encoding.lower() == 'utf-8'
def test_exclude_encodings(self):
# This is UTF-8.
@@ -77,14 +72,14 @@ class TestUnicodeDammit(unittest.TestCase):
# But if we exclude UTF-8 from consideration, the guess is
# Windows-1252.
dammit = UnicodeDammit(utf8_data, exclude_encodings=["utf-8"])
- self.assertEqual(dammit.original_encoding.lower(), 'windows-1252')
+ assert dammit.original_encoding.lower() == 'windows-1252'
# And if we exclude that, there is no valid guess at all.
dammit = UnicodeDammit(
utf8_data, exclude_encodings=["utf-8", "windows-1252"])
- self.assertEqual(dammit.original_encoding, None)
+ assert dammit.original_encoding == None
-class TestEncodingDetector(unittest.TestCase):
+class TestEncodingDetector(object):
def test_encoding_detector_replaces_junk_in_encoding_name_with_replacement_character(self):
detected = EncodingDetector(
@@ -100,8 +95,7 @@ class TestEncodingDetector(unittest.TestCase):
b"<html><meta charset=euc-jp /></html>",
b"<html><meta charset=euc-jp/></html>"):
dammit = UnicodeDammit(data, is_html=True)
- self.assertEqual(
- "euc-jp", dammit.original_encoding)
+ assert "euc-jp" == dammit.original_encoding
def test_last_ditch_entity_replacement(self):
# This is a UTF-8 document that contains bytestrings
@@ -129,11 +123,11 @@ class TestEncodingDetector(unittest.TestCase):
return None
bs4.dammit.chardet_dammit = noop
dammit = UnicodeDammit(doc)
- self.assertEqual(True, dammit.contains_replacement_characters)
- self.assertTrue("\ufffd" in dammit.unicode_markup)
+ assert True == dammit.contains_replacement_characters
+ assert "\ufffd" in dammit.unicode_markup
soup = BeautifulSoup(doc, "html.parser")
- self.assertTrue(soup.contains_replacement_characters)
+ assert soup.contains_replacement_characters
finally:
logging.disable(logging.NOTSET)
bs4.dammit.chardet_dammit = chardet
@@ -142,8 +136,8 @@ class TestEncodingDetector(unittest.TestCase):
# A document written in UTF-16LE will have its byte order marker stripped.
data = b'\xff\xfe<\x00a\x00>\x00\xe1\x00\xe9\x00<\x00/\x00a\x00>\x00'
dammit = UnicodeDammit(data)
- self.assertEqual("<a>áé</a>", dammit.unicode_markup)
- self.assertEqual("utf-16le", dammit.original_encoding)
+ assert "<a>áé</a>" == dammit.unicode_markup
+ assert "utf-16le" == dammit.original_encoding
def test_known_definite_versus_user_encodings(self):
# The known_definite_encodings are used before sniffing the
@@ -156,16 +150,14 @@ class TestEncodingDetector(unittest.TestCase):
# We can process it as UTF-16 by passing it in as a known
# definite encoding.
before = UnicodeDammit(data, known_definite_encodings=["utf-16"])
- self.assertEqual("utf-16", before.original_encoding)
+ assert "utf-16" == before.original_encoding
# If we pass UTF-18 as a user encoding, it's not even
# tried--the encoding sniffed from the byte-order mark takes
# precedence.
after = UnicodeDammit(data, user_encodings=["utf-8"])
- self.assertEqual("utf-16le", after.original_encoding)
- self.assertEqual(
- ["utf-16le"], [x[0] for x in dammit.tried_encodings]
- )
+ assert "utf-16le" == after.original_encoding
+ assert ["utf-16le"] == [x[0] for x in dammit.tried_encodings]
# Here's a document in ISO-8859-8.
hebrew = b"\xed\xe5\xec\xf9"
@@ -175,10 +167,8 @@ class TestEncodingDetector(unittest.TestCase):
# The known_definite_encodings don't work, BOM sniffing does
# nothing (it only works for a few UTF encodings), but one of
# the user_encodings does work.
- self.assertEqual("iso-8859-8", dammit.original_encoding)
- self.assertEqual(
- ["utf-8", "iso-8859-8"], [x[0] for x in dammit.tried_encodings]
- )
+ assert "iso-8859-8" == dammit.original_encoding
+ assert ["utf-8", "iso-8859-8"] == [x[0] for x in dammit.tried_encodings]
def test_deprecated_override_encodings(self):
# override_encodings is a deprecated alias for
@@ -190,12 +180,11 @@ class TestEncodingDetector(unittest.TestCase):
override_encodings=["utf-8"],
user_encodings=["iso-8859-8"],
)
- self.assertEqual("iso-8859-8", dammit.original_encoding)
+ assert "iso-8859-8" == dammit.original_encoding
# known_definite_encodings and override_encodings were tried
# before user_encodings.
- self.assertEqual(
- ["shift-jis", "utf-8", "iso-8859-8"],
+ assert ["shift-jis", "utf-8", "iso-8859-8"] == (
[x[0] for x in dammit.tried_encodings]
)
@@ -212,16 +201,15 @@ class TestEncodingDetector(unittest.TestCase):
doc = utf8 + windows_1252 + utf8
# The document can't be turned into UTF-8:
- self.assertRaises(UnicodeDecodeError, doc.decode, "utf8")
+ with pytest.raises(UnicodeDecodeError):
+ doc.decode("utf8")
# Unicode, Dammit thinks the whole document is Windows-1252,
# and decodes it into "☃☃☃“Hi, I like Windows!”☃☃☃"
# But if we run it through fix_embedded_windows_1252, it's fixed:
-
fixed = UnicodeDammit.detwingle(doc)
- self.assertEqual(
- "☃☃☃“Hi, I like Windows!”☃☃☃", fixed.decode("utf8"))
+ assert "☃☃☃“Hi, I like Windows!”☃☃☃" == fixed.decode("utf8")
def test_detwingle_ignores_multibyte_characters(self):
# Each of these characters has a UTF-8 representation ending
@@ -234,9 +222,9 @@ class TestEncodingDetector(unittest.TestCase):
"\xf0\x90\x90\x93", # This is a CJK character, not sure which one.
):
input = tricky_unicode_char.encode("utf8")
- self.assertTrue(input.endswith(b'\x93'))
+ assert input.endswith(b'\x93')
output = UnicodeDammit.detwingle(input)
- self.assertEqual(output, input)
+ assert output == input
def test_find_declared_encoding(self):
# Test our ability to find a declared encoding inside an
@@ -253,34 +241,30 @@ class TestEncodingDetector(unittest.TestCase):
xml_bytes = xml_unicode.encode("ascii")
m = EncodingDetector.find_declared_encoding
- self.assertEqual(None, m(html_unicode, is_html=False))
- self.assertEqual("utf-8", m(html_unicode, is_html=True))
- self.assertEqual("utf-8", m(html_bytes, is_html=True))
+ assert m(html_unicode, is_html=False) is None
+ assert "utf-8" == m(html_unicode, is_html=True)
+ assert "utf-8" == m(html_bytes, is_html=True)
- self.assertEqual("iso-8859-1", m(xml_unicode))
- self.assertEqual("iso-8859-1", m(xml_bytes))
+ assert "iso-8859-1" == m(xml_unicode)
+ assert "iso-8859-1" == m(xml_bytes)
# Normally, only the first few kilobytes of a document are checked for
# an encoding.
spacer = b' ' * 5000
- self.assertEqual(None, m(spacer + html_bytes))
- self.assertEqual(None, m(spacer + xml_bytes))
+ assert m(spacer + html_bytes) is None
+ assert m(spacer + xml_bytes) is None
# But you can tell find_declared_encoding to search an entire
# HTML document.
- self.assertEqual(
- "utf-8",
+ assert (
m(spacer + html_bytes, is_html=True, search_entire_document=True)
+ == "utf-8"
)
# The XML encoding declaration has to be the very first thing
# in the document. We'll allow whitespace before the document
# starts, but nothing else.
- self.assertEqual(
- "iso-8859-1",
- m(xml_bytes, search_entire_document=True)
- )
- self.assertEqual(
- None, m(b'a' + xml_bytes, search_entire_document=True)
- )
+ assert m(xml_bytes, search_entire_document=True) == "iso-8859-1"
+ assert m(b' ' + xml_bytes, search_entire_document=True) == "iso-8859-1"
+ assert m(b'a' + xml_bytes, search_entire_document=True) is None
diff --git a/bs4/tests/test_docs.py b/bs4/tests/test_docs.py
index 5b9f677..0194d69 100644
--- a/bs4/tests/test_docs.py
+++ b/bs4/tests/test_docs.py
@@ -1,5 +1,7 @@
"Test harness for doctests."
+# TODO: Pretty sure this isn't used and should be deleted.
+
# pylint: disable-msg=E0611,W0142
__metaclass__ = type
diff --git a/bs4/tests/test_formatter.py b/bs4/tests/test_formatter.py
index c188e18..e944759 100644
--- a/bs4/tests/test_formatter.py
+++ b/bs4/tests/test_formatter.py
@@ -18,12 +18,12 @@ class TestFormatter(SoupTest):
# Attributes come out sorted by name. In Python 3, attributes
# normally come out of a dictionary in the order they were
# added.
- self.assertEqual([('a', 2), ('b', 1)], formatter.attributes(tag))
+ assert [('a', 2), ('b', 1)] == formatter.attributes(tag)
# This works even if Tag.attrs is None, though this shouldn't
# normally happen.
tag.attrs = None
- self.assertEqual([], formatter.attributes(tag))
+ assert [] == formatter.attributes(tag)
def test_sort_attributes(self):
# Test the ability to override Formatter.attributes() to,
@@ -42,8 +42,8 @@ class TestFormatter(SoupTest):
# attributes() was called on the <p> tag. It filtered out one
# attribute and sorted the other two.
- self.assertEqual(formatter.called_with, soup.p)
- self.assertEqual('<p aval="2" cval="1"></p>', decoded)
+ assert formatter.called_with == soup.p
+ assert '<p aval="2" cval="1"></p>' == decoded
def test_empty_attributes_are_booleans(self):
# Test the behavior of empty_attributes_are_booleans as well
@@ -51,17 +51,17 @@ class TestFormatter(SoupTest):
for name in ('html', 'minimal', None):
formatter = HTMLFormatter.REGISTRY[name]
- self.assertEqual(False, formatter.empty_attributes_are_booleans)
+ assert False == formatter.empty_attributes_are_booleans
formatter = XMLFormatter.REGISTRY[None]
- self.assertEqual(False, formatter.empty_attributes_are_booleans)
+ assert False == formatter.empty_attributes_are_booleans
formatter = HTMLFormatter.REGISTRY['html5']
- self.assertEqual(True, formatter.empty_attributes_are_booleans)
+ assert True == formatter.empty_attributes_are_booleans
# Verify that the constructor sets the value.
formatter = Formatter(empty_attributes_are_booleans=True)
- self.assertEqual(True, formatter.empty_attributes_are_booleans)
+ assert True == formatter.empty_attributes_are_booleans
# Now demonstrate what it does to markup.
for markup in (
@@ -70,12 +70,6 @@ class TestFormatter(SoupTest):
):
soup = self.soup(markup)
for formatter in ('html', 'minimal', 'xml', None):
- self.assertEqual(
- b'<option selected=""></option>',
- soup.option.encode(formatter='html')
- )
- self.assertEqual(
- b'<option selected></option>',
- soup.option.encode(formatter='html5')
- )
+ assert b'<option selected=""></option>' == soup.option.encode(formatter='html')
+ assert b'<option selected></option>' == soup.option.encode(formatter='html5')
diff --git a/bs4/tests/test_html5lib.py b/bs4/tests/test_html5lib.py
index f8902ad..9ac6ccc 100644
--- a/bs4/tests/test_html5lib.py
+++ b/bs4/tests/test_html5lib.py
@@ -17,7 +17,7 @@ from bs4.testing import (
@skipIf(
not HTML5LIB_PRESENT,
"html5lib seems not to be present, not testing its tree builder.")
-class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
+class TestHTML5LibBuilder(SoupTest, HTML5TreeBuilderSmokeTest):
"""See ``HTML5TreeBuilderSmokeTest``."""
@property
@@ -30,12 +30,9 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
markup = "<p>A <b>bold</b> statement.</p>"
with warnings.catch_warnings(record=True) as w:
soup = self.soup(markup, parse_only=strainer)
- self.assertEqual(
- soup.decode(), self.document_for(markup))
+ assert soup.decode() == self.document_for(markup)
- self.assertTrue(
- "the html5lib tree builder doesn't support parse_only" in
- str(w[0].message))
+ assert "the html5lib tree builder doesn't support parse_only" in str(w[0].message)
def test_correctly_nested_tables(self):
"""html5lib inserts <tbody> tags where other parsers don't."""
@@ -46,13 +43,13 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
'<tr><td>foo</td></tr>'
'</table></td>')
- self.assertSoupEquals(
+ self.assert_soup(
markup,
'<table id="1"><tbody><tr><td>Here\'s another table:'
'<table id="2"><tbody><tr><td>foo</td></tr></tbody></table>'
'</td></tr></tbody></table>')
- self.assertSoupEquals(
+ self.assert_soup(
"<table><thead><tr><td>Foo</td></tr></thead>"
"<tbody><tr><td>Bar</td></tr></tbody>"
"<tfoot><tr><td>Baz</td></tr></tfoot></table>")
@@ -69,20 +66,20 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
</html>'''
soup = self.soup(markup)
# Verify that we can reach the <p> tag; this means the tree is connected.
- self.assertEqual(b"<p>foo</p>", soup.p.encode())
+ assert b"<p>foo</p>" == soup.p.encode()
def test_reparented_markup(self):
markup = '<p><em>foo</p>\n<p>bar<a></a></em></p>'
soup = self.soup(markup)
- self.assertEqual("<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p></body>", soup.body.decode())
- self.assertEqual(2, len(soup.find_all('p')))
+ assert "<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p></body>" == soup.body.decode()
+ assert 2 == len(soup.find_all('p'))
def test_reparented_markup_ends_with_whitespace(self):
markup = '<p><em>foo</p>\n<p>bar<a></a></em></p>\n'
soup = self.soup(markup)
- self.assertEqual("<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p>\n</body>", soup.body.decode())
- self.assertEqual(2, len(soup.find_all('p')))
+ assert "<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p>\n</body>" == soup.body.decode()
+ assert 2 == len(soup.find_all('p'))
def test_reparented_markup_containing_identical_whitespace_nodes(self):
"""Verify that we keep the two whitespace nodes in this
@@ -99,7 +96,7 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
markup = '<div><a>aftermath<p><noscript>target</noscript>aftermath</a></p></div>'
soup = self.soup(markup)
noscript = soup.noscript
- self.assertEqual("target", noscript.next_element)
+ assert "target" == noscript.next_element
target = soup.find(string='target')
# The 'aftermath' string was duplicated; we want the second one.
@@ -108,8 +105,8 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
# The <noscript> tag was moved beneath a copy of the <a> tag,
# but the 'target' string within is still connected to the
# (second) 'aftermath' string.
- self.assertEqual(final_aftermath, target.next_element)
- self.assertEqual(target, final_aftermath.previous_element)
+ assert final_aftermath == target.next_element
+ assert target == final_aftermath.previous_element
def test_processing_instruction(self):
"""Processing instructions become comments."""
@@ -121,13 +118,13 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
markup = b"""<a class="my_class"><p></a>"""
soup = self.soup(markup)
a1, a2 = soup.find_all('a')
- self.assertEqual(a1, a2)
+ assert a1 == a2
assert a1 is not a2
def test_foster_parenting(self):
markup = b"""<table><td></tbody>A"""
soup = self.soup(markup)
- self.assertEqual("<body>A<table><tbody><tr><td></td></tr></tbody></table></body>", soup.body.decode())
+ assert "<body>A<table><tbody><tr><td></td></tr></tbody></table></body>" == soup.body.decode()
def test_extraction(self):
"""
@@ -145,7 +142,7 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
[s.extract() for s in soup('script')]
[s.extract() for s in soup('style')]
- self.assertEqual(len(soup.find_all("p")), 1)
+ assert len(soup.find_all("p")) == 1
def test_empty_comment(self):
"""
@@ -167,21 +164,21 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
inputs = []
for form in soup.find_all('form'):
inputs.extend(form.find_all('input'))
- self.assertEqual(len(inputs), 1)
+ assert len(inputs) == 1
def test_tracking_line_numbers(self):
# The html.parser TreeBuilder keeps track of line number and
# position of each element.
markup = "\n <p>\n\n<sourceline>\n<b>text</b></sourceline><sourcepos></p>"
soup = self.soup(markup)
- self.assertEqual(2, soup.p.sourceline)
- self.assertEqual(5, soup.p.sourcepos)
- self.assertEqual("sourceline", soup.p.find('sourceline').name)
+ assert 2 == soup.p.sourceline
+ assert 5 == soup.p.sourcepos
+ assert "sourceline" == soup.p.find('sourceline').name
# You can deactivate this behavior.
soup = self.soup(markup, store_line_numbers=False)
- self.assertEqual("sourceline", soup.p.sourceline.name)
- self.assertEqual("sourcepos", soup.p.sourcepos.name)
+ assert "sourceline" == soup.p.sourceline.name
+ assert "sourcepos" == soup.p.sourcepos.name
def test_special_string_containers(self):
# The html5lib tree builder doesn't support this standard feature,
@@ -219,8 +216,8 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
div = self.soup(markup).div
without_element = div.encode()
expect = b"<div>%s</div>" % output_unicode.encode("utf8")
- self.assertEqual(without_element, expect)
+ assert without_element == expect
with_element = div.encode(formatter="html")
expect = b"<div>%s</div>" % output_element
- self.assertEqual(with_element, expect)
+ assert with_element == expect
diff --git a/bs4/tests/test_htmlparser.py b/bs4/tests/test_htmlparser.py
index 0d8161e..640cb1f 100644
--- a/bs4/tests/test_htmlparser.py
+++ b/bs4/tests/test_htmlparser.py
@@ -8,7 +8,7 @@ from bs4.testing import SoupTest, HTMLTreeBuilderSmokeTest
from bs4.builder import HTMLParserTreeBuilder
from bs4.builder._htmlparser import BeautifulSoupHTMLParser
-class HTMLParserTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
+class TestHTMLParserTreeBuilder(SoupTest, HTMLTreeBuilderSmokeTest):
default_builder = HTMLParserTreeBuilder
@@ -27,30 +27,30 @@ class HTMLParserTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
tree = self.soup("<a><b>foo</a>")
dumped = pickle.dumps(tree, 2)
loaded = pickle.loads(dumped)
- self.assertTrue(isinstance(loaded.builder, type(tree.builder)))
+ assert isinstance(loaded.builder, type(tree.builder))
def test_redundant_empty_element_closing_tags(self):
- self.assertSoupEquals('<br></br><br></br><br></br>', "<br/><br/><br/>")
- self.assertSoupEquals('</br></br></br>', "")
+ self.assert_soup('<br></br><br></br><br></br>', "<br/><br/><br/>")
+ self.assert_soup('</br></br></br>', "")
def test_empty_element(self):
# This verifies that any buffered data present when the parser
# finishes working is handled.
- self.assertSoupEquals("foo &# bar", "foo &amp;# bar")
+ self.assert_soup("foo &# bar", "foo &amp;# bar")
def test_tracking_line_numbers(self):
# The html.parser TreeBuilder keeps track of line number and
# position of each element.
markup = "\n <p>\n\n<sourceline>\n<b>text</b></sourceline><sourcepos></p>"
soup = self.soup(markup)
- self.assertEqual(2, soup.p.sourceline)
- self.assertEqual(3, soup.p.sourcepos)
- self.assertEqual("sourceline", soup.p.find('sourceline').name)
+ assert 2 == soup.p.sourceline
+ assert 3 == soup.p.sourcepos
+ assert "sourceline" == soup.p.find('sourceline').name
# You can deactivate this behavior.
soup = self.soup(markup, store_line_numbers=False)
- self.assertEqual("sourceline", soup.p.sourceline.name)
- self.assertEqual("sourcepos", soup.p.sourcepos.name)
+ assert "sourceline" == soup.p.sourceline.name
+ assert "sourcepos" == soup.p.sourcepos.name
def test_on_duplicate_attribute(self):
# The html.parser tree builder has a variety of ways of
@@ -61,20 +61,20 @@ class HTMLParserTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
# If you don't provide any particular value for
# on_duplicate_attribute, later values replace earlier values.
soup = self.soup(markup)
- self.assertEqual("url3", soup.a['href'])
- self.assertEqual(["cls"], soup.a['class'])
- self.assertEqual("id", soup.a['id'])
+ assert "url3" == soup.a['href']
+ assert ["cls"] == soup.a['class']
+ assert "id" == soup.a['id']
# You can also get this behavior explicitly.
def assert_attribute(on_duplicate_attribute, expected):
soup = self.soup(
markup, on_duplicate_attribute=on_duplicate_attribute
)
- self.assertEqual(expected, soup.a['href'])
+ assert expected == soup.a['href']
# Verify that non-duplicate attributes are treated normally.
- self.assertEqual(["cls"], soup.a['class'])
- self.assertEqual("id", soup.a['id'])
+ assert ["cls"] == soup.a['class']
+ assert "id" == soup.a['id']
assert_attribute(None, "url3")
assert_attribute(BeautifulSoupHTMLParser.REPLACE, "url3")
@@ -114,11 +114,11 @@ class HTMLParserTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
div = self.soup(markup).div
without_element = div.encode()
expect = b"<div>%s</div>" % output_unicode.encode("utf8")
- self.assertEqual(without_element, expect)
+ assert without_element == expect
with_element = div.encode(formatter="html")
expect = b"<div>%s</div>" % output_element
- self.assertEqual(with_element, expect)
+ assert with_element == expect
class TestHTMLParserSubclass(SoupTest):
diff --git a/bs4/tests/test_lxml.py b/bs4/tests/test_lxml.py
index 71931ff..0e505d9 100644
--- a/bs4/tests/test_lxml.py
+++ b/bs4/tests/test_lxml.py
@@ -31,7 +31,7 @@ from bs4.testing import (
@skipIf(
not LXML_PRESENT,
"lxml seems not to be present, not testing its tree builder.")
-class LXMLTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
+class TestLXMLTreeBuilder(SoupTest, HTMLTreeBuilderSmokeTest):
"""See ``HTMLTreeBuilderSmokeTest``."""
@property
@@ -39,11 +39,11 @@ class LXMLTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
return LXMLTreeBuilder
def test_out_of_range_entity(self):
- self.assertSoupEquals(
+ self.assert_soup(
"<p>foo&#10000000000000;bar</p>", "<p>foobar</p>")
- self.assertSoupEquals(
+ self.assert_soup(
"<p>foo&#x10000000000000;bar</p>", "<p>foobar</p>")
- self.assertSoupEquals(
+ self.assert_soup(
"<p>foo&#1000000000;bar</p>", "<p>foobar</p>")
def test_entities_in_foreign_document_encoding(self):
@@ -61,15 +61,15 @@ class LXMLTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
def test_empty_doctype(self):
soup = self.soup("<!DOCTYPE>")
doctype = soup.contents[0]
- self.assertEqual("", doctype.strip())
+ assert "" == doctype.strip()
def test_beautifulstonesoup_is_xml_parser(self):
# Make sure that the deprecated BSS class uses an xml builder
# if one is installed.
with warnings.catch_warnings(record=True) as w:
soup = BeautifulStoneSoup("<b />")
- self.assertEqual("<b/>", str(soup.b))
- self.assertTrue("BeautifulStoneSoup class is deprecated" in str(w[0].message))
+ assert "<b/>" == str(soup.b)
+ assert "BeautifulStoneSoup class is deprecated" in str(w[0].message)
def test_tracking_line_numbers(self):
# The lxml TreeBuilder cannot keep track of line numbers from
@@ -83,8 +83,8 @@ class LXMLTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
"\n <p>\n\n<sourceline>\n<b>text</b></sourceline><sourcepos></p>",
store_line_numbers=True
)
- self.assertEqual("sourceline", soup.p.sourceline.name)
- self.assertEqual("sourcepos", soup.p.sourcepos.name)
+ assert "sourceline" == soup.p.sourceline.name
+ assert "sourcepos" == soup.p.sourcepos.name
@skipIf(
not LXML_PRESENT,
@@ -109,7 +109,6 @@ class LXMLXMLTreeBuilderSmokeTest(SoupTest, XMLTreeBuilderSmokeTest):
'<prefix:tag xmlns:prefix="http://prefixed-namespace.com">content</tag>'
'</root>'
)
- self.assertEqual(
- soup._namespaces,
+ assert soup._namespaces == (
{'xml': 'http://www.w3.org/XML/1998/namespace', 'prefix': 'http://prefixed-namespace.com'}
)
diff --git a/bs4/tests/test_navigablestring.py b/bs4/tests/test_navigablestring.py
index 89e92b7..6cd57f7 100644
--- a/bs4/tests/test_navigablestring.py
+++ b/bs4/tests/test_navigablestring.py
@@ -15,34 +15,33 @@ class TestNavigableString(SoupTest):
def test_text_acquisition_methods(self):
# These methods are intended for use against Tag, but they
# work on NavigableString as well,
- eq_ = self.assertEqual
s = NavigableString("fee ")
cdata = CData("fie ")
comment = Comment("foe ")
- eq_("fee ", s.get_text())
- eq_("fee", s.get_text(strip=True))
- eq_(["fee "], list(s.strings))
- eq_(["fee"], list(s.stripped_strings))
- eq_(["fee "], list(s._all_strings()))
-
- eq_("fie ", cdata.get_text())
- eq_("fie", cdata.get_text(strip=True))
- eq_(["fie "], list(cdata.strings))
- eq_(["fie"], list(cdata.stripped_strings))
- eq_(["fie "], list(cdata._all_strings()))
+ assert "fee " == s.get_text()
+ assert "fee" == s.get_text(strip=True)
+ assert ["fee "] == list(s.strings)
+ assert ["fee"] == list(s.stripped_strings)
+ assert ["fee "] == list(s._all_strings())
+
+ assert "fie " == cdata.get_text()
+ assert "fie" == cdata.get_text(strip=True)
+ assert ["fie "] == list(cdata.strings)
+ assert ["fie"] == list(cdata.stripped_strings)
+ assert ["fie "] == list(cdata._all_strings())
# Since a Comment isn't normally considered 'text',
# these methods generally do nothing.
- eq_("", comment.get_text())
- eq_([], list(comment.strings))
- eq_([], list(comment.stripped_strings))
- eq_([], list(comment._all_strings()))
+ assert "" == comment.get_text()
+ assert [] == list(comment.strings)
+ assert [] == list(comment.stripped_strings)
+ assert [] == list(comment._all_strings())
# Unless you specifically say that comments are okay.
- eq_("foe", comment.get_text(strip=True, types=Comment))
- eq_("foe ", comment.get_text(types=(Comment, NavigableString)))
+ assert "foe" == comment.get_text(strip=True, types=Comment)
+ assert "foe " == comment.get_text(types=(Comment, NavigableString))
class TestNavigableStringSubclasses(SoupTest):
@@ -52,9 +51,9 @@ class TestNavigableStringSubclasses(SoupTest):
soup = self.soup("")
cdata = CData("foo")
soup.insert(1, cdata)
- self.assertEqual(str(soup), "<![CDATA[foo]]>")
- self.assertEqual(soup.find(text="foo"), "foo")
- self.assertEqual(soup.contents[0], "foo")
+ assert str(soup) == "<![CDATA[foo]]>"
+ assert soup.find(text="foo") == "foo"
+ assert soup.contents[0] == "foo"
def test_cdata_is_never_formatted(self):
"""Text inside a CData object is passed into the formatter.
@@ -70,9 +69,8 @@ class TestNavigableStringSubclasses(SoupTest):
soup = self.soup("")
cdata = CData("<><><>")
soup.insert(1, cdata)
- self.assertEqual(
- b"<![CDATA[<><><>]]>", soup.encode(formatter=increment))
- self.assertEqual(1, self.count)
+ assert b"<![CDATA[<><><>]]>" == soup.encode(formatter=increment)
+ assert 1 == self.count
def test_doctype_ends_in_newline(self):
# Unlike other NavigableString subclasses, a DOCTYPE always ends
@@ -80,11 +78,11 @@ class TestNavigableStringSubclasses(SoupTest):
doctype = Doctype("foo")
soup = self.soup("")
soup.insert(1, doctype)
- self.assertEqual(soup.encode(), b"<!DOCTYPE foo>\n")
+ assert soup.encode() == b"<!DOCTYPE foo>\n"
def test_declaration(self):
d = Declaration("foo")
- self.assertEqual("<?foo?>", d.output_ready())
+ assert "<?foo?>" == d.output_ready()
def test_default_string_containers(self):
# In some cases, we use different NavigableString subclasses for
@@ -92,10 +90,9 @@ class TestNavigableStringSubclasses(SoupTest):
soup = self.soup(
"<div>text</div><script>text</script><style>text</style>"
)
- self.assertEqual(
- [NavigableString, Script, Stylesheet],
- [x.__class__ for x in soup.find_all(text=True)]
- )
+ assert [NavigableString, Script, Stylesheet] == [
+ x.__class__ for x in soup.find_all(text=True)
+ ]
# The TemplateString is a little unusual because it's generally found
# _inside_ children of a <template> element, not a direct child of the
@@ -119,5 +116,5 @@ class TestNavigableStringSubclasses(SoupTest):
# Comment.
markup = b"<template>Some text<p>In a tag</p><!--with a comment--></template>"
soup = self.soup(markup)
- self.assertEqual(markup, soup.template.encode("utf8"))
+ assert markup == soup.template.encode("utf8")
diff --git a/bs4/tests/test_soup.py b/bs4/tests/test_soup.py
index 4d00845..f73086a 100644
--- a/bs4/tests/test_soup.py
+++ b/bs4/tests/test_soup.py
@@ -4,7 +4,7 @@
from pdb import set_trace
import logging
import os
-import unittest
+import pytest
import sys
import tempfile
@@ -53,17 +53,17 @@ class TestConstructor(SoupTest):
def test_short_unicode_input(self):
data = "<h1>éé</h1>"
soup = self.soup(data)
- self.assertEqual("éé", soup.h1.string)
+ assert "éé" == soup.h1.string
def test_embedded_null(self):
data = "<h1>foo\0bar</h1>"
soup = self.soup(data)
- self.assertEqual("foo\0bar", soup.h1.string)
+ assert "foo\0bar" == soup.h1.string
def test_exclude_encodings(self):
utf8_data = "Räksmörgås".encode("utf-8")
soup = self.soup(utf8_data, exclude_encodings=["utf-8"])
- self.assertEqual("windows-1252", soup.original_encoding)
+ assert "windows-1252" == soup.original_encoding
def test_custom_builder_class(self):
# Verify that you can pass in a custom Builder class and
@@ -97,8 +97,8 @@ class TestConstructor(SoupTest):
with warnings.catch_warnings(record=True):
soup = BeautifulSoup('', builder=Mock, **kwargs)
assert isinstance(soup.builder, Mock)
- self.assertEqual(dict(var="value"), soup.builder.called_with)
- self.assertEqual("prepared markup", soup.builder.fed)
+ assert dict(var="value") == soup.builder.called_with
+ assert "prepared markup" == soup.builder.fed
# You can also instantiate the TreeBuilder yourself. In this
# case, that specific object is used and any keyword arguments
@@ -110,8 +110,8 @@ class TestConstructor(SoupTest):
)
msg = str(w[0].message)
assert msg.startswith("Keyword arguments to the BeautifulSoup constructor will be ignored.")
- self.assertEqual(builder, soup.builder)
- self.assertEqual(kwargs, builder.called_with)
+ assert builder == soup.builder
+ assert kwargs == builder.called_with
def test_parser_markup_rejection(self):
# If markup is completely rejected by the parser, an
@@ -126,12 +126,11 @@ class TestConstructor(SoupTest):
yield markup, None, None, False
yield markup, None, None, False
+
import re
- self.assertRaisesRegex(
- ParserRejectedMarkup,
- "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help.",
- BeautifulSoup, '', builder=Mock,
- )
+ with pytest.raises(ParserRejectedMarkup) as exc_info:
+ BeautifulSoup('', builder=Mock)
+ assert "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help." in str(exc_info.value)
def test_cdata_list_attributes(self):
# Most attribute values are represented as scalars, but the
@@ -142,14 +141,14 @@ class TestConstructor(SoupTest):
# Note that the spaces are stripped for 'class' but not for 'id'.
a = soup.a
- self.assertEqual(" an id ", a['id'])
- self.assertEqual(["a", "class"], a['class'])
+ assert " an id " == a['id']
+ assert ["a", "class"] == a['class']
# TreeBuilder takes an argument called 'mutli_valued_attributes' which lets
# you customize or disable this. As always, you can customize the TreeBuilder
# by passing in a keyword argument to the BeautifulSoup constructor.
soup = self.soup(markup, builder=default_builder, multi_valued_attributes=None)
- self.assertEqual(" a class ", soup.a['class'])
+ assert " a class " == soup.a['class']
# Here are two ways of saying that `id` is a multi-valued
# attribute in this context, but 'class' is not.
@@ -159,8 +158,8 @@ class TestConstructor(SoupTest):
# specifying a parser, but we'll ignore it.
soup = self.soup(markup, builder=None, multi_valued_attributes=switcheroo)
a = soup.a
- self.assertEqual(["an", "id"], a['id'])
- self.assertEqual(" a class ", a['class'])
+ assert ["an", "id"] == a['id']
+ assert " a class " == a['class']
def test_replacement_classes(self):
# Test the ability to pass in replacements for element classes
@@ -221,7 +220,7 @@ class TestConstructor(SoupTest):
# Now that parsing was complete, the string_container_stack
# (where this information was kept) has been cleared out.
- self.assertEqual([], soup.string_container_stack)
+ assert [] == soup.string_container_stack
class TestWarnings(SoupTest):
@@ -235,9 +234,7 @@ class TestWarnings(SoupTest):
def _assert_no_parser_specified(self, w):
warning = self._assert_warning(w, GuessedAtParserWarning)
message = str(warning.message)
- self.assertTrue(
- message.startswith(BeautifulSoup.NO_PARSER_SPECIFIED_WARNING[:60])
- )
+ assert message.startswith(BeautifulSoup.NO_PARSER_SPECIFIED_WARNING[:60])
def test_warning_if_no_parser_specified(self):
with warnings.catch_warnings(record=True) as w:
@@ -252,28 +249,28 @@ class TestWarnings(SoupTest):
def test_no_warning_if_explicit_parser_specified(self):
with warnings.catch_warnings(record=True) as w:
soup = BeautifulSoup("<a><b></b></a>", "html.parser")
- self.assertEqual([], w)
+ assert [] == w
def test_parseOnlyThese_renamed_to_parse_only(self):
with warnings.catch_warnings(record=True) as w:
soup = self.soup("<a><b></b></a>", parseOnlyThese=SoupStrainer("b"))
msg = str(w[0].message)
- self.assertTrue("parseOnlyThese" in msg)
- self.assertTrue("parse_only" in msg)
- self.assertEqual(b"<b></b>", soup.encode())
+ assert "parseOnlyThese" in msg
+ assert "parse_only" in msg
+ assert b"<b></b>" == soup.encode()
def test_fromEncoding_renamed_to_from_encoding(self):
with warnings.catch_warnings(record=True) as w:
utf8 = b"\xc3\xa9"
soup = self.soup(utf8, fromEncoding="utf8")
msg = str(w[0].message)
- self.assertTrue("fromEncoding" in msg)
- self.assertTrue("from_encoding" in msg)
- self.assertEqual("utf8", soup.original_encoding)
+ assert "fromEncoding" in msg
+ assert "from_encoding" in msg
+ assert "utf8" == soup.original_encoding
def test_unrecognized_keyword_argument(self):
- self.assertRaises(
- TypeError, self.soup, "<a>", no_such_argument=True)
+ with pytest.raises(TypeError):
+ self.soup("<a>", no_such_argument=True)
def test_disk_file_warning(self):
filehandle = tempfile.NamedTemporaryFile()
@@ -282,14 +279,14 @@ class TestWarnings(SoupTest):
with warnings.catch_warnings(record=True) as w:
soup = self.soup(filename)
warning = self._assert_warning(w, MarkupResemblesLocatorWarning)
- self.assertTrue("looks like a filename" in str(warning.message))
+ assert "looks like a filename" in str(warning.message)
finally:
filehandle.close()
# The file no longer exists, so Beautiful Soup will no longer issue the warning.
with warnings.catch_warnings(record=True) as w:
soup = self.soup(filename)
- self.assertEqual([], w)
+ assert [] == w
def test_directory_warning(self):
try:
@@ -297,14 +294,14 @@ class TestWarnings(SoupTest):
with warnings.catch_warnings(record=True) as w:
soup = self.soup(filename)
warning = self._assert_warning(w, MarkupResemblesLocatorWarning)
- self.assertTrue("looks like a directory" in str(warning.message))
+ assert "looks like a directory" in str(warning.message)
finally:
os.rmdir(filename)
# The directory no longer exists, so Beautiful Soup will no longer issue the warning.
with warnings.catch_warnings(record=True) as w:
soup = self.soup(filename)
- self.assertEqual([], w)
+ assert [] == w
def test_url_warning_with_bytes_url(self):
with warnings.catch_warnings(record=True) as warning_list:
@@ -312,7 +309,7 @@ class TestWarnings(SoupTest):
warning = self._assert_warning(
warning_list, MarkupResemblesLocatorWarning
)
- self.assertTrue("looks like a URL" in str(warning.message))
+ assert "looks like a URL" in str(warning.message)
def test_url_warning_with_unicode_url(self):
with warnings.catch_warnings(record=True) as warning_list:
@@ -322,21 +319,21 @@ class TestWarnings(SoupTest):
warning = self._assert_warning(
warning_list, MarkupResemblesLocatorWarning
)
- self.assertTrue("looks like a URL" in str(warning.message))
+ assert "looks like a URL" in str(warning.message)
def test_url_warning_with_bytes_and_space(self):
# Here the markup contains something besides a URL, so no warning
# is issued.
with warnings.catch_warnings(record=True) as warning_list:
soup = self.soup(b"http://www.crummybytes.com/ is great")
- self.assertFalse(any("looks like a URL" in str(w.message)
- for w in warning_list))
+ assert not any("looks like a URL" in str(w.message)
+ for w in warning_list)
def test_url_warning_with_unicode_and_space(self):
with warnings.catch_warnings(record=True) as warning_list:
- soup = self.soup("http://www.crummyuncode.com/ is great")
- self.assertFalse(any("looks like a URL" in str(w.message)
- for w in warning_list))
+ soup = self.soup("http://www.crummyunicode.com/ is great")
+ assert not any("looks like a URL" in str(w.message)
+ for w in warning_list)
class TestSelectiveParsing(SoupTest):
@@ -345,28 +342,26 @@ class TestSelectiveParsing(SoupTest):
markup = "No<b>Yes</b><a>No<b>Yes <c>Yes</c></b>"
strainer = SoupStrainer("b")
soup = self.soup(markup, parse_only=strainer)
- self.assertEqual(soup.encode(), b"<b>Yes</b><b>Yes <c>Yes</c></b>")
+ assert soup.encode() == b"<b>Yes</b><b>Yes <c>Yes</c></b>"
-class TestEntitySubstitution(unittest.TestCase):
+class TestEntitySubstitution(object):
"""Standalone tests of the EntitySubstitution class."""
- def setUp(self):
+ def setup_method(self):
self.sub = EntitySubstitution
def test_simple_html_substitution(self):
# Unicode characters corresponding to named HTML entites
# are substituted, and no others.
s = "foo\u2200\N{SNOWMAN}\u00f5bar"
- self.assertEqual(self.sub.substitute_html(s),
- "foo&forall;\N{SNOWMAN}&otilde;bar")
+ assert self.sub.substitute_html(s) == "foo&forall;\N{SNOWMAN}&otilde;bar"
def test_smart_quote_substitution(self):
# MS smart quotes are a common source of frustration, so we
# give them a special test.
quotes = b"\x91\x92foo\x93\x94"
dammit = UnicodeDammit(quotes)
- self.assertEqual(self.sub.substitute_html(dammit.markup),
- "&lsquo;&rsquo;foo&ldquo;&rdquo;")
+ assert self.sub.substitute_html(dammit.markup) == "&lsquo;&rsquo;foo&ldquo;&rdquo;"
def test_html5_entity(self):
# Some HTML5 entities correspond to single- or multi-character
@@ -399,7 +394,7 @@ class TestEntitySubstitution(unittest.TestCase):
template = '3 %s 4'
raw = template % u
with_entities = template % entity
- self.assertEqual(self.sub.substitute_html(raw), with_entities)
+ assert self.sub.substitute_html(raw) == with_entities
def test_html5_entity_with_variation_selector(self):
# Some HTML5 entities correspond either to a single-character
@@ -407,73 +402,59 @@ class TestEntitySubstitution(unittest.TestCase):
# VARIATION SELECTOR 1. We can handle this.
data = "fjords \u2294 penguins"
markup = "fjords &sqcup; penguins"
- self.assertEqual(self.sub.substitute_html(data), markup)
+ assert self.sub.substitute_html(data) == markup
data = "fjords \u2294\ufe00 penguins"
markup = "fjords &sqcups; penguins"
- self.assertEqual(self.sub.substitute_html(data), markup)
+ assert self.sub.substitute_html(data) == markup
def test_xml_converstion_includes_no_quotes_if_make_quoted_attribute_is_false(self):
s = 'Welcome to "my bar"'
- self.assertEqual(self.sub.substitute_xml(s, False), s)
+ assert self.sub.substitute_xml(s, False) == s
def test_xml_attribute_quoting_normally_uses_double_quotes(self):
- self.assertEqual(self.sub.substitute_xml("Welcome", True),
- '"Welcome"')
- self.assertEqual(self.sub.substitute_xml("Bob's Bar", True),
- '"Bob\'s Bar"')
+ assert self.sub.substitute_xml("Welcome", True) == '"Welcome"'
+ assert self.sub.substitute_xml("Bob's Bar", True) == '"Bob\'s Bar"'
def test_xml_attribute_quoting_uses_single_quotes_when_value_contains_double_quotes(self):
s = 'Welcome to "my bar"'
- self.assertEqual(self.sub.substitute_xml(s, True),
- "'Welcome to \"my bar\"'")
+ assert self.sub.substitute_xml(s, True) == "'Welcome to \"my bar\"'"
def test_xml_attribute_quoting_escapes_single_quotes_when_value_contains_both_single_and_double_quotes(self):
s = 'Welcome to "Bob\'s Bar"'
- self.assertEqual(
- self.sub.substitute_xml(s, True),
- '"Welcome to &quot;Bob\'s Bar&quot;"')
+ assert self.sub.substitute_xml(s, True) == '"Welcome to &quot;Bob\'s Bar&quot;"'
def test_xml_quotes_arent_escaped_when_value_is_not_being_quoted(self):
quoted = 'Welcome to "Bob\'s Bar"'
- self.assertEqual(self.sub.substitute_xml(quoted), quoted)
+ assert self.sub.substitute_xml(quoted) == quoted
def test_xml_quoting_handles_angle_brackets(self):
- self.assertEqual(
- self.sub.substitute_xml("foo<bar>"),
- "foo&lt;bar&gt;")
+ assert self.sub.substitute_xml("foo<bar>") == "foo&lt;bar&gt;"
def test_xml_quoting_handles_ampersands(self):
- self.assertEqual(self.sub.substitute_xml("AT&T"), "AT&amp;T")
+ assert self.sub.substitute_xml("AT&T") == "AT&amp;T"
def test_xml_quoting_including_ampersands_when_they_are_part_of_an_entity(self):
- self.assertEqual(
- self.sub.substitute_xml("&Aacute;T&T"),
- "&amp;Aacute;T&amp;T")
+ assert self.sub.substitute_xml("&Aacute;T&T") == "&amp;Aacute;T&amp;T"
def test_xml_quoting_ignoring_ampersands_when_they_are_part_of_an_entity(self):
- self.assertEqual(
- self.sub.substitute_xml_containing_entities("&Aacute;T&T"),
- "&Aacute;T&amp;T")
+ assert self.sub.substitute_xml_containing_entities("&Aacute;T&T") == "&Aacute;T&amp;T"
def test_quotes_not_html_substituted(self):
"""There's no need to do this except inside attribute values."""
text = 'Bob\'s "bar"'
- self.assertEqual(self.sub.substitute_html(text), text)
+ assert self.sub.substitute_html(text) == text
class TestEncodingConversion(SoupTest):
# Test Beautiful Soup's ability to decode and encode from various
# encodings.
- def setUp(self):
- super(TestEncodingConversion, self).setUp()
+ def setup_method(self):
self.unicode_data = '<html><head><meta charset="utf-8"/></head><body><foo>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</foo></body></html>'
self.utf8_data = self.unicode_data.encode("utf-8")
# Just so you know what it looks like.
- self.assertEqual(
- self.utf8_data,
- b'<html><head><meta charset="utf-8"/></head><body><foo>Sacr\xc3\xa9 bleu!</foo></body></html>')
+ assert self.utf8_data == b'<html><head><meta charset="utf-8"/></head><body><foo>Sacr\xc3\xa9 bleu!</foo></body></html>'
def test_ascii_in_unicode_out(self):
# ASCII input is converted to Unicode. The original_encoding
@@ -488,9 +469,9 @@ class TestEncodingConversion(SoupTest):
ascii = b"<foo>a</foo>"
soup_from_ascii = self.soup(ascii)
unicode_output = soup_from_ascii.decode()
- self.assertTrue(isinstance(unicode_output, str))
- self.assertEqual(unicode_output, self.document_for(ascii.decode()))
- self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8")
+ assert isinstance(unicode_output, str)
+ assert unicode_output == self.document_for(ascii.decode())
+ assert soup_from_ascii.original_encoding.lower() == "utf-8"
finally:
logging.disable(logging.NOTSET)
bs4.dammit.chardet_dammit = chardet
@@ -499,81 +480,81 @@ class TestEncodingConversion(SoupTest):
# Unicode input is left alone. The original_encoding attribute
# is not set.
soup_from_unicode = self.soup(self.unicode_data)
- self.assertEqual(soup_from_unicode.decode(), self.unicode_data)
- self.assertEqual(soup_from_unicode.foo.string, 'Sacr\xe9 bleu!')
- self.assertEqual(soup_from_unicode.original_encoding, None)
+ assert soup_from_unicode.decode() == self.unicode_data
+ assert soup_from_unicode.foo.string == 'Sacr\xe9 bleu!'
+ assert soup_from_unicode.original_encoding == None
def test_utf8_in_unicode_out(self):
# UTF-8 input is converted to Unicode. The original_encoding
# attribute is set.
soup_from_utf8 = self.soup(self.utf8_data)
- self.assertEqual(soup_from_utf8.decode(), self.unicode_data)
- self.assertEqual(soup_from_utf8.foo.string, 'Sacr\xe9 bleu!')
+ assert soup_from_utf8.decode() == self.unicode_data
+ assert soup_from_utf8.foo.string == 'Sacr\xe9 bleu!'
def test_utf8_out(self):
# The internal data structures can be encoded as UTF-8.
soup_from_unicode = self.soup(self.unicode_data)
- self.assertEqual(soup_from_unicode.encode('utf-8'), self.utf8_data)
+ assert soup_from_unicode.encode('utf-8') == self.utf8_data
@skipIf(
PYTHON_3_PRE_3_2,
"Bad HTMLParser detected; skipping test of non-ASCII characters in attribute name.")
def test_attribute_name_containing_unicode_characters(self):
markup = '<div><a \N{SNOWMAN}="snowman"></a></div>'
- self.assertEqual(self.soup(markup).div.encode("utf8"), markup.encode("utf8"))
+ assert self.soup(markup).div.encode("utf8") == markup.encode("utf8")
class TestNamedspacedAttribute(SoupTest):
def test_name_may_be_none_or_missing(self):
a = NamespacedAttribute("xmlns", None)
- self.assertEqual(a, "xmlns")
+ assert a == "xmlns"
a = NamespacedAttribute("xmlns", "")
- self.assertEqual(a, "xmlns")
+ assert a == "xmlns"
a = NamespacedAttribute("xmlns")
- self.assertEqual(a, "xmlns")
+ assert a == "xmlns"
def test_namespace_may_be_none_or_missing(self):
a = NamespacedAttribute(None, "tag")
- self.assertEqual(a, "tag")
+ assert a == "tag"
a = NamespacedAttribute("", "tag")
- self.assertEqual(a, "tag")
+ assert a == "tag"
def test_attribute_is_equivalent_to_colon_separated_string(self):
a = NamespacedAttribute("a", "b")
- self.assertEqual("a:b", a)
+ assert "a:b" == a
def test_attributes_are_equivalent_if_prefix_and_name_identical(self):
a = NamespacedAttribute("a", "b", "c")
b = NamespacedAttribute("a", "b", "c")
- self.assertEqual(a, b)
+ assert a == b
# The actual namespace is not considered.
c = NamespacedAttribute("a", "b", None)
- self.assertEqual(a, c)
+ assert a == c
# But name and prefix are important.
d = NamespacedAttribute("a", "z", "c")
- self.assertNotEqual(a, d)
+ assert a != d
e = NamespacedAttribute("z", "b", "c")
- self.assertNotEqual(a, e)
+ assert a != e
-class TestAttributeValueWithCharsetSubstitution(unittest.TestCase):
+class TestAttributeValueWithCharsetSubstitution(object):
def test_content_meta_attribute_value(self):
value = CharsetMetaAttributeValue("euc-jp")
- self.assertEqual("euc-jp", value)
- self.assertEqual("euc-jp", value.original_value)
- self.assertEqual("utf8", value.encode("utf8"))
+ assert "euc-jp" == value
+ assert "euc-jp" == value.original_value
+ assert "utf8" == value.encode("utf8")
def test_content_meta_attribute_value(self):
value = ContentMetaAttributeValue("text/html; charset=euc-jp")
- self.assertEqual("text/html; charset=euc-jp", value)
- self.assertEqual("text/html; charset=euc-jp", value.original_value)
- self.assertEqual("text/html; charset=utf8", value.encode("utf8"))
+ assert "text/html; charset=euc-jp" == value
+ assert "text/html; charset=euc-jp" == value.original_value
+ assert "text/html; charset=utf8" == value.encode("utf8")
diff --git a/bs4/tests/test_tree.py b/bs4/tests/test_tree.py
index 59b51d0..aab773f 100644
--- a/bs4/tests/test_tree.py
+++ b/bs4/tests/test_tree.py
@@ -12,6 +12,7 @@ methods tested here.
from pdb import set_trace
import copy
import pickle
+import pytest
import re
import warnings
from bs4 import BeautifulSoup
@@ -44,23 +45,23 @@ LXML_PRESENT = (builder_registry.lookup("lxml") is not None)
class TreeTest(SoupTest):
- def assertSelects(self, tags, should_match):
+ def assert_selects(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)
+ assert [tag.string for tag in tags] == should_match
- def assertSelectsIDs(self, tags, should_match):
+ def assert_selects_ids(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)
+ assert [tag['id'] for tag in tags] == should_match
class TestFind(TreeTest):
@@ -72,27 +73,27 @@ class TestFind(TreeTest):
def test_find_tag(self):
soup = self.soup("<a>1</a><b>2</b><a>3</a><b>4</b>")
- self.assertEqual(soup.find("b").string, "2")
+ assert soup.find("b").string == "2"
def test_unicode_text_find(self):
soup = self.soup('<h1>Räksmörgås</h1>')
- self.assertEqual(soup.find(string='Räksmörgås'), 'Räksmörgås')
+ assert soup.find(string='Räksmörgås') == 'Räksmörgås'
def test_unicode_attribute_find(self):
soup = self.soup('<h1 id="Räksmörgås">here it is</h1>')
str(soup)
- self.assertEqual("here it is", soup.find(id='Räksmörgås').text)
+ assert "here it is" == soup.find(id='Räksmörgås').text
def test_find_everything(self):
"""Test an optimization that finds all tags."""
soup = self.soup("<a>foo</a><b>bar</b>")
- self.assertEqual(2, len(soup.find_all()))
+ assert 2 == len(soup.find_all())
def test_find_everything_with_name(self):
"""Test an optimization that finds all tags with a given name."""
soup = self.soup("<a>foo</a><b>bar</b><a>baz</a>")
- self.assertEqual(2, len(soup.find_all('a')))
+ assert 2 == len(soup.find_all('a'))
class TestFindAll(TreeTest):
"""Basic tests of the find_all() method."""
@@ -101,34 +102,31 @@ class TestFindAll(TreeTest):
"""You can search the tree for text nodes."""
soup = self.soup("<html>Foo<b>bar</b>\xbb</html>")
# Exact match.
- self.assertEqual(soup.find_all(string="bar"), ["bar"])
- self.assertEqual(soup.find_all(text="bar"), ["bar"])
+ assert soup.find_all(string="bar") == ["bar"]
+ assert soup.find_all(text="bar") == ["bar"]
# Match any of a number of strings.
- self.assertEqual(
- soup.find_all(text=["Foo", "bar"]), ["Foo", "bar"])
+ assert soup.find_all(text=["Foo", "bar"]) == ["Foo", "bar"]
# Match a regular expression.
- self.assertEqual(soup.find_all(text=re.compile('.*')),
- ["Foo", "bar", '\xbb'])
+ assert soup.find_all(text=re.compile('.*')) == ["Foo", "bar", '\xbb']
# Match anything.
- self.assertEqual(soup.find_all(text=True),
- ["Foo", "bar", '\xbb'])
+ assert soup.find_all(text=True) == ["Foo", "bar", '\xbb']
def test_find_all_limit(self):
"""You can limit the number of items returned by find_all."""
soup = self.soup("<a>1</a><a>2</a><a>3</a><a>4</a><a>5</a>")
- self.assertSelects(soup.find_all('a', limit=3), ["1", "2", "3"])
- self.assertSelects(soup.find_all('a', limit=1), ["1"])
- self.assertSelects(
+ self.assert_selects(soup.find_all('a', limit=3), ["1", "2", "3"])
+ self.assert_selects(soup.find_all('a', limit=1), ["1"])
+ self.assert_selects(
soup.find_all('a', limit=10), ["1", "2", "3", "4", "5"])
# A limit of 0 means no limit.
- self.assertSelects(
+ self.assert_selects(
soup.find_all('a', limit=0), ["1", "2", "3", "4", "5"])
def test_calling_a_tag_is_calling_findall(self):
soup = self.soup("<a>1</a><b>2<a id='foo'>3</a></b>")
- self.assertSelects(soup('a', limit=1), ["1"])
- self.assertSelects(soup.b(id="foo"), ["3"])
+ self.assert_selects(soup('a', limit=1), ["1"])
+ self.assert_selects(soup.b(id="foo"), ["3"])
def test_find_all_with_self_referential_data_structure_does_not_cause_infinite_recursion(self):
soup = self.soup("<a></a>")
@@ -138,79 +136,78 @@ class TestFindAll(TreeTest):
# Without special code in _normalize_search_value, this would cause infinite
# recursion.
- self.assertEqual([], soup.find_all(l))
+ assert [] == soup.find_all(l)
def test_find_all_resultset(self):
"""All find_all calls return a ResultSet"""
soup = self.soup("<a></a>")
result = soup.find_all("a")
- self.assertTrue(hasattr(result, "source"))
+ assert hasattr(result, "source")
result = soup.find_all(True)
- self.assertTrue(hasattr(result, "source"))
+ assert hasattr(result, "source")
result = soup.find_all(text="foo")
- self.assertTrue(hasattr(result, "source"))
+ assert hasattr(result, "source")
class TestFindAllBasicNamespaces(TreeTest):
def test_find_by_namespaced_name(self):
soup = self.soup('<mathml:msqrt>4</mathml:msqrt><a svg:fill="red">')
- self.assertEqual("4", soup.find("mathml:msqrt").string)
- self.assertEqual("a", soup.find(attrs= { "svg:fill" : "red" }).name)
+ assert "4" == soup.find("mathml:msqrt").string
+ assert "a" == soup.find(attrs= { "svg:fill" : "red" }).name
class TestFindAllByName(TreeTest):
"""Test ways of finding tags by tag name."""
- def setUp(self):
- super(TreeTest, self).setUp()
+ def setup_method(self):
self.tree = self.soup("""<a>First tag.</a>
<b>Second tag.</b>
<c>Third <a>Nested tag.</a> tag.</c>""")
def test_find_all_by_tag_name(self):
# Find all the <a> tags.
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all('a'), ['First tag.', 'Nested tag.'])
def test_find_all_by_name_and_text(self):
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all('a', text='First tag.'), ['First tag.'])
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all('a', text=True), ['First tag.', 'Nested tag.'])
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all('a', text=re.compile("tag")),
['First tag.', 'Nested tag.'])
def test_find_all_on_non_root_element(self):
# You can call find_all on any node, not just the root.
- self.assertSelects(self.tree.c.find_all('a'), ['Nested tag.'])
+ self.assert_selects(self.tree.c.find_all('a'), ['Nested tag.'])
def test_calling_element_invokes_find_all(self):
- self.assertSelects(self.tree('a'), ['First tag.', 'Nested tag.'])
+ self.assert_selects(self.tree('a'), ['First tag.', 'Nested tag.'])
def test_find_all_by_tag_strainer(self):
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all(SoupStrainer('a')),
['First tag.', 'Nested tag.'])
def test_find_all_by_tag_names(self):
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all(['a', 'b']),
['First tag.', 'Second tag.', 'Nested tag.'])
def test_find_all_by_tag_dict(self):
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all({'a' : True, 'b' : True}),
['First tag.', 'Second tag.', 'Nested tag.'])
def test_find_all_by_tag_re(self):
- self.assertSelects(
+ self.assert_selects(
self.tree.find_all(re.compile('^[ab]$')),
['First tag.', 'Second tag.', 'Nested tag.'])
@@ -224,7 +221,7 @@ class TestFindAllByName(TreeTest):
<a id="1">Does not match.</a>
<b id="b">Match 2.</a>""")
- self.assertSelects(
+ self.assert_selects(
tree.find_all(id_matches_name), ["Match 1.", "Match 2."])
def test_find_with_multi_valued_attribute(self):
@@ -234,10 +231,10 @@ class TestFindAllByName(TreeTest):
r1 = soup.find('div', 'a d');
r2 = soup.find('div', re.compile(r'a d'));
r3, r4 = soup.find_all('div', ['a b', 'a d']);
- self.assertEqual('3', r1.string)
- self.assertEqual('3', r2.string)
- self.assertEqual('1', r3.string)
- self.assertEqual('3', r4.string)
+ assert '3' == r1.string
+ assert '3' == r2.string
+ assert '1' == r3.string
+ assert '3' == r4.string
class TestFindAllByAttribute(TreeTest):
@@ -250,16 +247,16 @@ class TestFindAllByAttribute(TreeTest):
<a id="second">
Non-matching <b id="first">Matching b.</b>a.
</a>""")
- self.assertSelects(tree.find_all(id='first'),
+ self.assert_selects(tree.find_all(id='first'),
["Matching a.", "Matching b."])
def test_find_all_by_utf8_attribute_value(self):
peace = "םולש".encode("utf8")
data = '<a title="םולש"></a>'.encode("utf8")
soup = self.soup(data)
- self.assertEqual([soup.a], soup.find_all(title=peace))
- self.assertEqual([soup.a], soup.find_all(title=peace.decode("utf8")))
- self.assertEqual([soup.a], soup.find_all(title=[peace, "something else"]))
+ assert [soup.a] == soup.find_all(title=peace)
+ assert [soup.a] == soup.find_all(title=peace.decode("utf8"))
+ assert [soup.a], soup.find_all(title=[peace, "something else"])
def test_find_all_by_attribute_dict(self):
# You can pass in a dictionary as the argument 'attrs'. This
@@ -273,13 +270,13 @@ class TestFindAllByAttribute(TreeTest):
""")
# This doesn't do what you want.
- self.assertSelects(tree.find_all(name='name1'),
+ self.assert_selects(tree.find_all(name='name1'),
["A tag called 'name1'."])
# This does what you want.
- self.assertSelects(tree.find_all(attrs={'name' : 'name1'}),
+ self.assert_selects(tree.find_all(attrs={'name' : 'name1'}),
["Name match."])
- self.assertSelects(tree.find_all(attrs={'class' : 'class2'}),
+ self.assert_selects(tree.find_all(attrs={'class' : 'class2'}),
["Class match."])
def test_find_all_by_class(self):
@@ -292,57 +289,57 @@ class TestFindAllByAttribute(TreeTest):
# Passing in the class_ keyword argument will search against
# the 'class' attribute.
- self.assertSelects(tree.find_all('a', class_='1'), ['Class 1.'])
- self.assertSelects(tree.find_all('c', class_='3'), ['Class 3 and 4.'])
- self.assertSelects(tree.find_all('c', class_='4'), ['Class 3 and 4.'])
+ self.assert_selects(tree.find_all('a', class_='1'), ['Class 1.'])
+ self.assert_selects(tree.find_all('c', class_='3'), ['Class 3 and 4.'])
+ self.assert_selects(tree.find_all('c', class_='4'), ['Class 3 and 4.'])
# Passing in a string to 'attrs' will also search the CSS class.
- self.assertSelects(tree.find_all('a', '1'), ['Class 1.'])
- self.assertSelects(tree.find_all(attrs='1'), ['Class 1.', 'Class 1.'])
- self.assertSelects(tree.find_all('c', '3'), ['Class 3 and 4.'])
- self.assertSelects(tree.find_all('c', '4'), ['Class 3 and 4.'])
+ self.assert_selects(tree.find_all('a', '1'), ['Class 1.'])
+ self.assert_selects(tree.find_all(attrs='1'), ['Class 1.', 'Class 1.'])
+ self.assert_selects(tree.find_all('c', '3'), ['Class 3 and 4.'])
+ self.assert_selects(tree.find_all('c', '4'), ['Class 3 and 4.'])
def test_find_by_class_when_multiple_classes_present(self):
tree = self.soup("<gar class='foo bar'>Found it</gar>")
f = tree.find_all("gar", class_=re.compile("o"))
- self.assertSelects(f, ["Found it"])
+ self.assert_selects(f, ["Found it"])
f = tree.find_all("gar", class_=re.compile("a"))
- self.assertSelects(f, ["Found it"])
+ self.assert_selects(f, ["Found it"])
# If the search fails to match the individual strings "foo" and "bar",
# it will be tried against the combined string "foo bar".
f = tree.find_all("gar", class_=re.compile("o b"))
- self.assertSelects(f, ["Found it"])
+ self.assert_selects(f, ["Found it"])
def test_find_all_with_non_dictionary_for_attrs_finds_by_class(self):
soup = self.soup("<a class='bar'>Found it</a>")
- self.assertSelects(soup.find_all("a", re.compile("ba")), ["Found it"])
+ self.assert_selects(soup.find_all("a", re.compile("ba")), ["Found it"])
def big_attribute_value(value):
return len(value) > 3
- self.assertSelects(soup.find_all("a", big_attribute_value), [])
+ self.assert_selects(soup.find_all("a", big_attribute_value), [])
def small_attribute_value(value):
return len(value) <= 3
- self.assertSelects(
+ self.assert_selects(
soup.find_all("a", small_attribute_value), ["Found it"])
def test_find_all_with_string_for_attrs_finds_multiple_classes(self):
soup = self.soup('<a class="foo bar"></a><a class="foo"></a>')
a, a2 = soup.find_all("a")
- self.assertEqual([a, a2], soup.find_all("a", "foo"))
- self.assertEqual([a], soup.find_all("a", "bar"))
+ assert [a, a2], soup.find_all("a", "foo")
+ assert [a], soup.find_all("a", "bar")
# If you specify the class as a string that contains a
# space, only that specific value will be found.
- self.assertEqual([a], soup.find_all("a", class_="foo bar"))
- self.assertEqual([a], soup.find_all("a", "foo bar"))
- self.assertEqual([], soup.find_all("a", "bar foo"))
+ assert [a] == soup.find_all("a", class_="foo bar")
+ assert [a] == soup.find_all("a", "foo bar")
+ assert [] == soup.find_all("a", "bar foo")
def test_find_all_by_attribute_soupstrainer(self):
tree = self.soup("""
@@ -350,7 +347,7 @@ class TestFindAllByAttribute(TreeTest):
<a id="second">Non-match.</a>""")
strainer = SoupStrainer(attrs={'id' : 'first'})
- self.assertSelects(tree.find_all(strainer), ['Match.'])
+ self.assert_selects(tree.find_all(strainer), ['Match.'])
def test_find_all_with_missing_attribute(self):
# You can pass in None as the value of an attribute to find_all.
@@ -358,7 +355,7 @@ class TestFindAllByAttribute(TreeTest):
tree = self.soup("""<a id="1">ID present.</a>
<a>No ID present.</a>
<a id="">ID is empty.</a>""")
- self.assertSelects(tree.find_all('a', id=None), ["No ID present."])
+ self.assert_selects(tree.find_all('a', id=None), ["No ID present."])
def test_find_all_with_defined_attribute(self):
# You can pass in None as the value of an attribute to find_all.
@@ -366,7 +363,7 @@ class TestFindAllByAttribute(TreeTest):
tree = self.soup("""<a id="1">ID present.</a>
<a>No ID present.</a>
<a id="">ID is empty.</a>""")
- self.assertSelects(
+ self.assert_selects(
tree.find_all(id=True), ["ID present.", "ID is empty."])
def test_find_all_with_numeric_attribute(self):
@@ -375,8 +372,8 @@ class TestFindAllByAttribute(TreeTest):
<a id="1">Quoted attribute.</a>""")
expected = ["Unquoted attribute.", "Quoted attribute."]
- self.assertSelects(tree.find_all(id=1), expected)
- self.assertSelects(tree.find_all(id="1"), expected)
+ self.assert_selects(tree.find_all(id=1), expected)
+ self.assert_selects(tree.find_all(id="1"), expected)
def test_find_all_with_list_attribute_values(self):
# You can pass a list of attribute values instead of just one,
@@ -385,7 +382,7 @@ class TestFindAllByAttribute(TreeTest):
<a id="2">2</a>
<a id="3">3</a>
<a>No ID.</a>""")
- self.assertSelects(tree.find_all(id=["1", "3", "4"]),
+ self.assert_selects(tree.find_all(id=["1", "3", "4"]),
["1", "3"])
def test_find_all_with_regular_expression_attribute_value(self):
@@ -398,27 +395,26 @@ class TestFindAllByAttribute(TreeTest):
<a id="b">One b.</a>
<a>No ID.</a>""")
- self.assertSelects(tree.find_all(id=re.compile("^a+$")),
+ self.assert_selects(tree.find_all(id=re.compile("^a+$")),
["One a.", "Two as."])
def test_find_by_name_and_containing_string(self):
soup = self.soup("<b>foo</b><b>bar</b><a>foo</a>")
a = soup.a
- self.assertEqual([a], soup.find_all("a", text="foo"))
- self.assertEqual([], soup.find_all("a", text="bar"))
- self.assertEqual([], soup.find_all("a", text="bar"))
+ assert [a] == soup.find_all("a", text="foo")
+ assert [] == soup.find_all("a", text="bar")
def test_find_by_name_and_containing_string_when_string_is_buried(self):
soup = self.soup("<a>foo</a><a><b><c>foo</c></b></a>")
- self.assertEqual(soup.find_all("a"), soup.find_all("a", text="foo"))
+ assert soup.find_all("a") == soup.find_all("a", text="foo")
def test_find_by_attribute_and_containing_string(self):
soup = self.soup('<b id="1">foo</b><a id="2">foo</a>')
a = soup.a
- self.assertEqual([a], soup.find_all(id=2, text="foo"))
- self.assertEqual([], soup.find_all(id=1, text="bar"))
+ assert [a] == soup.find_all(id=2, text="foo")
+ assert [] == soup.find_all(id=1, text="bar")
class TestSmooth(TreeTest):
@@ -444,25 +440,25 @@ class TestSmooth(TreeTest):
# output.
# Since the <span> tag has two children, its .string is None.
- self.assertEqual(None, div.span.string)
+ assert None == div.span.string
- self.assertEqual(7, len(div.contents))
+ assert 7 == len(div.contents)
div.smooth()
- self.assertEqual(5, len(div.contents))
+ assert 5 == len(div.contents)
# The three strings at the beginning of div.contents have been
# merged into on string.
#
- self.assertEqual('abc', div.contents[0])
+ assert 'abc' == div.contents[0]
# The call is recursive -- the <span> tag was also smoothed.
- self.assertEqual('12', div.span.string)
+ assert '12' == div.span.string
# The two comments have _not_ been merged, even though
# comments are strings. Merging comments would change the
# meaning of the HTML.
- self.assertEqual('Comment 1', div.contents[1])
- self.assertEqual('Comment 2', div.contents[2])
+ assert 'Comment 1' == div.contents[1]
+ assert 'Comment 2' == div.contents[2]
class TestIndex(TreeTest):
@@ -479,15 +475,15 @@ class TestIndex(TreeTest):
</div>""")
div = tree.div
for i, element in enumerate(div.contents):
- self.assertEqual(i, div.index(element))
- self.assertRaises(ValueError, tree.index, 1)
+ assert i == div.index(element)
+ with pytest.raises(ValueError):
+ tree.index(1)
class TestParentOperations(TreeTest):
"""Test navigation and searching through an element's parents."""
- def setUp(self):
- super(TestParentOperations, self).setUp()
+ def setup_method(self):
self.tree = self.soup('''<ul id="empty"></ul>
<ul id="top">
<ul id="middle">
@@ -499,125 +495,124 @@ class TestParentOperations(TreeTest):
def test_parent(self):
- self.assertEqual(self.start.parent['id'], 'bottom')
- self.assertEqual(self.start.parent.parent['id'], 'middle')
- self.assertEqual(self.start.parent.parent.parent['id'], 'top')
+ assert self.start.parent['id'] == 'bottom'
+ assert self.start.parent.parent['id'] == 'middle'
+ assert self.start.parent.parent.parent['id'] == 'top'
def test_parent_of_top_tag_is_soup_object(self):
top_tag = self.tree.contents[0]
- self.assertEqual(top_tag.parent, self.tree)
+ assert top_tag.parent == self.tree
def test_soup_object_has_no_parent(self):
- self.assertEqual(None, self.tree.parent)
+ assert None == self.tree.parent
def test_find_parents(self):
- self.assertSelectsIDs(
+ self.assert_selects_ids(
self.start.find_parents('ul'), ['bottom', 'middle', 'top'])
- self.assertSelectsIDs(
+ self.assert_selects_ids(
self.start.find_parents('ul', id="middle"), ['middle'])
def test_find_parent(self):
- self.assertEqual(self.start.find_parent('ul')['id'], 'bottom')
- self.assertEqual(self.start.find_parent('ul', id='top')['id'], 'top')
+ assert self.start.find_parent('ul')['id'] == 'bottom'
+ assert self.start.find_parent('ul', id='top')['id'] == 'top'
def test_parent_of_text_element(self):
text = self.tree.find(text="Start here")
- self.assertEqual(text.parent.name, 'b')
+ assert text.parent.name == 'b'
def test_text_element_find_parent(self):
text = self.tree.find(text="Start here")
- self.assertEqual(text.find_parent('ul')['id'], 'bottom')
+ assert 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 'id' in parent.attrs]
- self.assertEqual(parents, ['bottom', 'middle', 'top'])
+ assert parents, ['bottom', 'middle' == 'top']
class ProximityTest(TreeTest):
- def setUp(self):
- super(TreeTest, self).setUp()
+ def setup_method(self):
self.tree = self.soup(
'<html id="start"><head></head><body><b id="1">One</b><b id="2">Two</b><b id="3">Three</b></body></html>')
class TestNextOperations(ProximityTest):
- def setUp(self):
- super(TestNextOperations, self).setUp()
+ def setup_method(self):
+ super(TestNextOperations, self).setup_method()
self.start = self.tree.b
def test_next(self):
- self.assertEqual(self.start.next_element, "One")
- self.assertEqual(self.start.next_element.next_element['id'], "2")
+ assert self.start.next_element == "One"
+ assert self.start.next_element.next_element['id'] == "2"
def test_next_of_last_item_is_none(self):
last = self.tree.find(text="Three")
- self.assertEqual(last.next_element, None)
+ assert last.next_element == None
def test_next_of_root_is_none(self):
# The document root is outside the next/previous chain.
- self.assertEqual(self.tree.next_element, None)
+ assert self.tree.next_element == None
def test_find_all_next(self):
- self.assertSelects(self.start.find_all_next('b'), ["Two", "Three"])
+ self.assert_selects(self.start.find_all_next('b'), ["Two", "Three"])
self.start.find_all_next(id=3)
- self.assertSelects(self.start.find_all_next(id=3), ["Three"])
+ self.assert_selects(self.start.find_all_next(id=3), ["Three"])
def test_find_next(self):
- self.assertEqual(self.start.find_next('b')['id'], '2')
- self.assertEqual(self.start.find_next(text="Three"), "Three")
+ assert self.start.find_next('b')['id'] == '2'
+ assert self.start.find_next(text="Three") == "Three"
def test_find_next_for_text_element(self):
text = self.tree.find(text="One")
- self.assertEqual(text.find_next("b").string, "Two")
- self.assertSelects(text.find_all_next("b"), ["Two", "Three"])
+ assert text.find_next("b").string == "Two"
+ self.assert_selects(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 <b> tag and its text contents.
tag, contents = successors
- self.assertEqual(tag['id'], '3')
- self.assertEqual(contents, "Three")
+ assert tag['id'] == '3'
+ assert contents == "Three"
class TestPreviousOperations(ProximityTest):
- def setUp(self):
- super(TestPreviousOperations, self).setUp()
+ def setup_method(self):
+ super(TestPreviousOperations, self).setup_method()
self.end = self.tree.find(text="Three")
def test_previous(self):
- self.assertEqual(self.end.previous_element['id'], "3")
- self.assertEqual(self.end.previous_element.previous_element, "Two")
+ assert self.end.previous_element['id'] == "3"
+ assert self.end.previous_element.previous_element == "Two"
def test_previous_of_first_item_is_none(self):
first = self.tree.find('html')
- self.assertEqual(first.previous_element, None)
+ assert first.previous_element == None
def test_previous_of_root_is_none(self):
# The document root is outside the next/previous chain.
# XXX This is broken!
- #self.assertEqual(self.tree.previous_element, None)
+ #assert self.tree.previous_element == None
pass
def test_find_all_previous(self):
# The <b> tag containing the "Three" node is the predecessor
# of the "Three" node itself, which is why "Three" shows up
# here.
- self.assertSelects(
+ self.assert_selects(
self.end.find_all_previous('b'), ["Three", "Two", "One"])
- self.assertSelects(self.end.find_all_previous(id=1), ["One"])
+ self.assert_selects(self.end.find_all_previous(id=1), ["One"])
def test_find_previous(self):
- self.assertEqual(self.end.find_previous('b')['id'], '3')
- self.assertEqual(self.end.find_previous(text="One"), "One")
+ assert self.end.find_previous('b')['id'] == '3'
+ assert self.end.find_previous(text="One") == "One"
def test_find_previous_for_text_element(self):
text = self.tree.find(text="Three")
- self.assertEqual(text.find_previous("b").string, "Three")
- self.assertSelects(
+ assert text.find_previous("b").string == "Three"
+ self.assert_selects(
text.find_all_previous("b"), ["Three", "Two", "One"])
def test_previous_generator(self):
@@ -627,16 +622,15 @@ class TestPreviousOperations(ProximityTest):
# There are four predecessors: the <b> tag containing "One"
# the <body> tag, the <head> tag, and the <html> tag.
b, body, head, html = predecessors
- self.assertEqual(b['id'], '1')
- self.assertEqual(body.name, "body")
- self.assertEqual(head.name, "head")
- self.assertEqual(html.name, "html")
+ assert b['id'] == '1'
+ assert body.name == "body"
+ assert head.name == "head"
+ assert html.name == "html"
class SiblingTest(TreeTest):
- def setUp(self):
- super(SiblingTest, self).setUp()
+ def setup_method(self):
markup = '''<html>
<span id="1">
<span id="1.1"></span>
@@ -657,92 +651,92 @@ class SiblingTest(TreeTest):
class TestNextSibling(SiblingTest):
- def setUp(self):
- super(TestNextSibling, self).setUp()
+ def setup_method(self):
+ super(TestNextSibling, self).setup_method()
self.start = self.tree.find(id="1")
def test_next_sibling_of_root_is_none(self):
- self.assertEqual(self.tree.next_sibling, None)
+ assert self.tree.next_sibling == None
def test_next_sibling(self):
- self.assertEqual(self.start.next_sibling['id'], '2')
- self.assertEqual(self.start.next_sibling.next_sibling['id'], '3')
+ assert self.start.next_sibling['id'] == '2'
+ assert self.start.next_sibling.next_sibling['id'] == '3'
# Note the difference between next_sibling and next_element.
- self.assertEqual(self.start.next_element['id'], '1.1')
+ assert self.start.next_element['id'] == '1.1'
def test_next_sibling_may_not_exist(self):
- self.assertEqual(self.tree.html.next_sibling, None)
+ assert self.tree.html.next_sibling == None
nested_span = self.tree.find(id="1.1")
- self.assertEqual(nested_span.next_sibling, None)
+ assert nested_span.next_sibling == None
last_span = self.tree.find(id="4")
- self.assertEqual(last_span.next_sibling, None)
+ assert last_span.next_sibling == None
def test_find_next_sibling(self):
- self.assertEqual(self.start.find_next_sibling('span')['id'], '2')
+ assert self.start.find_next_sibling('span')['id'] == '2'
def test_next_siblings(self):
- self.assertSelectsIDs(self.start.find_next_siblings("span"),
+ self.assert_selects_ids(self.start.find_next_siblings("span"),
['2', '3', '4'])
- self.assertSelectsIDs(self.start.find_next_siblings(id='3'), ['3'])
+ self.assert_selects_ids(self.start.find_next_siblings(id='3'), ['3'])
def test_next_sibling_for_text_element(self):
soup = self.soup("Foo<b>bar</b>baz")
start = soup.find(text="Foo")
- self.assertEqual(start.next_sibling.name, 'b')
- self.assertEqual(start.next_sibling.next_sibling, 'baz')
+ assert start.next_sibling.name == 'b'
+ assert start.next_sibling.next_sibling == 'baz'
- self.assertSelects(start.find_next_siblings('b'), ['bar'])
- self.assertEqual(start.find_next_sibling(text="baz"), "baz")
- self.assertEqual(start.find_next_sibling(text="nonesuch"), None)
+ self.assert_selects(start.find_next_siblings('b'), ['bar'])
+ assert start.find_next_sibling(text="baz") == "baz"
+ assert start.find_next_sibling(text="nonesuch") == None
class TestPreviousSibling(SiblingTest):
- def setUp(self):
- super(TestPreviousSibling, self).setUp()
+ def setup_method(self):
+ super(TestPreviousSibling, self).setup_method()
self.end = self.tree.find(id="4")
def test_previous_sibling_of_root_is_none(self):
- self.assertEqual(self.tree.previous_sibling, None)
+ assert self.tree.previous_sibling == None
def test_previous_sibling(self):
- self.assertEqual(self.end.previous_sibling['id'], '3')
- self.assertEqual(self.end.previous_sibling.previous_sibling['id'], '2')
+ assert self.end.previous_sibling['id'] == '3'
+ assert self.end.previous_sibling.previous_sibling['id'] == '2'
# Note the difference between previous_sibling and previous_element.
- self.assertEqual(self.end.previous_element['id'], '3.1')
+ assert self.end.previous_element['id'] == '3.1'
def test_previous_sibling_may_not_exist(self):
- self.assertEqual(self.tree.html.previous_sibling, None)
+ assert self.tree.html.previous_sibling == None
nested_span = self.tree.find(id="1.1")
- self.assertEqual(nested_span.previous_sibling, None)
+ assert nested_span.previous_sibling == None
first_span = self.tree.find(id="1")
- self.assertEqual(first_span.previous_sibling, None)
+ assert first_span.previous_sibling == None
def test_find_previous_sibling(self):
- self.assertEqual(self.end.find_previous_sibling('span')['id'], '3')
+ assert self.end.find_previous_sibling('span')['id'] == '3'
def test_previous_siblings(self):
- self.assertSelectsIDs(self.end.find_previous_siblings("span"),
+ self.assert_selects_ids(self.end.find_previous_siblings("span"),
['3', '2', '1'])
- self.assertSelectsIDs(self.end.find_previous_siblings(id='1'), ['1'])
+ self.assert_selects_ids(self.end.find_previous_siblings(id='1'), ['1'])
def test_previous_sibling_for_text_element(self):
soup = self.soup("Foo<b>bar</b>baz")
start = soup.find(text="baz")
- self.assertEqual(start.previous_sibling.name, 'b')
- self.assertEqual(start.previous_sibling.previous_sibling, 'Foo')
+ assert start.previous_sibling.name == 'b'
+ assert start.previous_sibling.previous_sibling == 'Foo'
- self.assertSelects(start.find_previous_siblings('b'), ['bar'])
- self.assertEqual(start.find_previous_sibling(text="Foo"), "Foo")
- self.assertEqual(start.find_previous_sibling(text="nonesuch"), None)
+ self.assert_selects(start.find_previous_siblings('b'), ['bar'])
+ assert start.find_previous_sibling(text="Foo") == "Foo"
+ assert start.find_previous_sibling(text="nonesuch") == None
class TestTag(SoupTest):
@@ -755,18 +749,18 @@ class TestTag(SoupTest):
# No list of whitespace-preserving tags -> pretty-print
tag._preserve_whitespace_tags = None
- self.assertEqual(True, tag._should_pretty_print(0))
+ assert True == tag._should_pretty_print(0)
# List exists but tag is not on the list -> pretty-print
tag.preserve_whitespace_tags = ["some_other_tag"]
- self.assertEqual(True, tag._should_pretty_print(1))
+ assert True == tag._should_pretty_print(1)
# Indent level is None -> don't pretty-print
- self.assertEqual(False, tag._should_pretty_print(None))
+ assert False == tag._should_pretty_print(None)
# Tag is on the whitespace-preserving list -> don't pretty-print
tag.preserve_whitespace_tags = ["some_other_tag", "a_tag"]
- self.assertEqual(False, tag._should_pretty_print(1))
+ assert False == tag._should_pretty_print(1)
class TestTagCreation(SoupTest):
@@ -774,10 +768,10 @@ class TestTagCreation(SoupTest):
def test_new_tag(self):
soup = self.soup("")
new_tag = soup.new_tag("foo", bar="baz", attrs={"name": "a name"})
- self.assertTrue(isinstance(new_tag, Tag))
- self.assertEqual("foo", new_tag.name)
- self.assertEqual(dict(bar="baz", name="a name"), new_tag.attrs)
- self.assertEqual(None, new_tag.parent)
+ assert isinstance(new_tag, Tag)
+ assert "foo" == new_tag.name
+ assert dict(bar="baz", name="a name") == new_tag.attrs
+ assert None == new_tag.parent
def test_tag_inherits_self_closing_rules_from_builder(self):
if XML_BUILDER_PRESENT:
@@ -787,8 +781,8 @@ class TestTagCreation(SoupTest):
# Both the <br> and <p> tag are empty-element, just because
# they have no contents.
- self.assertEqual(b"<br/>", xml_br.encode())
- self.assertEqual(b"<p/>", xml_p.encode())
+ assert b"<br/>" == xml_br.encode()
+ assert b"<p/>" == xml_p.encode()
html_soup = BeautifulSoup("", "html.parser")
html_br = html_soup.new_tag("br")
@@ -796,31 +790,31 @@ class TestTagCreation(SoupTest):
# The HTML builder users HTML's rules about which tags are
# empty-element tags, and the new tags reflect these rules.
- self.assertEqual(b"<br/>", html_br.encode())
- self.assertEqual(b"<p></p>", html_p.encode())
+ assert b"<br/>" == html_br.encode()
+ assert b"<p></p>" == html_p.encode()
def test_new_string_creates_navigablestring(self):
soup = self.soup("")
s = soup.new_string("foo")
- self.assertEqual("foo", s)
- self.assertTrue(isinstance(s, NavigableString))
+ assert "foo" == s
+ assert isinstance(s, NavigableString)
def test_new_string_can_create_navigablestring_subclass(self):
soup = self.soup("")
s = soup.new_string("foo", Comment)
- self.assertEqual("foo", s)
- self.assertTrue(isinstance(s, Comment))
+ assert "foo" == s
+ assert isinstance(s, Comment)
class TestTreeModification(SoupTest):
def test_attribute_modification(self):
soup = self.soup('<a id="1"></a>')
soup.a['id'] = 2
- self.assertEqual(soup.decode(), self.document_for('<a id="2"></a>'))
+ assert soup.decode() == self.document_for('<a id="2"></a>')
del(soup.a['id'])
- self.assertEqual(soup.decode(), self.document_for('<a></a>'))
+ assert soup.decode() == self.document_for('<a></a>')
soup.a['id2'] = 'foo'
- self.assertEqual(soup.decode(), self.document_for('<a id2="foo"></a>'))
+ assert soup.decode() == self.document_for('<a id2="foo"></a>')
def test_new_tag_creation(self):
builder = builder_registry.lookup('html')()
@@ -830,9 +824,7 @@ class TestTreeModification(SoupTest):
a['href'] = 'http://foo.com/'
soup.body.insert(0, a)
soup.body.insert(1, ol)
- self.assertEqual(
- soup.body.encode(),
- b'<body><a href="http://foo.com/"></a><ol></ol></body>')
+ assert soup.body.encode() == b'<body><a href="http://foo.com/"></a><ol></ol></body>'
def test_append_to_contents_moves_tag(self):
doc = """<p id="1">Don't leave me <b>here</b>.</p>
@@ -845,51 +837,55 @@ class TestTreeModification(SoupTest):
soup.find(id='2').append(soup.b)
# The <b> tag is now a child of the second paragraph.
- self.assertEqual(bold.parent, second_para)
+ assert bold.parent == second_para
- self.assertEqual(
- soup.decode(), self.document_for(
+ assert soup.decode() == self.document_for(
'<p id="1">Don\'t leave me .</p>\n'
- '<p id="2">Don\'t leave!<b>here</b></p>'))
+ '<p id="2">Don\'t leave!<b>here</b></p>'
+ )
def test_replace_with_returns_thing_that_was_replaced(self):
text = "<a></a><b><c></c></b>"
soup = self.soup(text)
a = soup.a
new_a = a.replace_with(soup.c)
- self.assertEqual(a, new_a)
+ assert a == new_a
def test_unwrap_returns_thing_that_was_replaced(self):
text = "<a><b></b><c></c></a>"
soup = self.soup(text)
a = soup.a
new_a = a.unwrap()
- self.assertEqual(a, new_a)
+ assert a == new_a
def test_replace_with_and_unwrap_give_useful_exception_when_tag_has_no_parent(self):
soup = self.soup("<a><b>Foo</b></a><c>Bar</c>")
a = soup.a
a.extract()
- self.assertEqual(None, a.parent)
- self.assertRaises(ValueError, a.unwrap)
- self.assertRaises(ValueError, a.replace_with, soup.c)
+ assert None == a.parent
+ with pytest.raises(ValueError):
+ a.unwrap()
+ with pytest.raises(ValueError):
+ a.replace_with(soup.c)
def test_replace_tag_with_itself(self):
text = "<a><b></b><c>Foo<d></d></c></a><a><e></e></a>"
soup = self.soup(text)
c = soup.c
soup.c.replace_with(c)
- self.assertEqual(soup.decode(), self.document_for(text))
+ assert soup.decode() == self.document_for(text)
def test_replace_tag_with_its_parent_raises_exception(self):
text = "<a><b></b></a>"
soup = self.soup(text)
- self.assertRaises(ValueError, soup.b.replace_with, soup.a)
+ with pytest.raises(ValueError):
+ soup.b.replace_with(soup.a)
def test_insert_tag_into_itself_raises_exception(self):
text = "<a><b></b></a>"
soup = self.soup(text)
- self.assertRaises(ValueError, soup.a.insert, 0, soup.a)
+ with pytest.raises(ValueError):
+ soup.a.insert(0, soup.a)
def test_insert_beautifulsoup_object_inserts_children(self):
"""Inserting one BeautifulSoup object into another actually inserts all
@@ -905,10 +901,10 @@ class TestTreeModification(SoupTest):
assert not isinstance(i, BeautifulSoup)
p1, p2, p3, p4 = list(soup.children)
- self.assertEqual("And now, a word:", p1.string)
- self.assertEqual("p2", p2.string)
- self.assertEqual("p3", p3.string)
- self.assertEqual("And we're back.", p4.string)
+ assert "And now, a word:" == p1.string
+ assert "p2" == p2.string
+ assert "p3" == p3.string
+ assert "And we're back." == p4.string
def test_replace_with_maintains_next_element_throughout(self):
@@ -924,17 +920,17 @@ class TestTreeModification(SoupTest):
right.replaceWith('')
# The <b> tag is still connected to the tree.
- self.assertEqual("three", soup.b.string)
+ assert "three" == soup.b.string
def test_replace_final_node(self):
soup = self.soup("<b>Argh!</b>")
soup.find(text="Argh!").replace_with("Hooray!")
new_text = soup.find(text="Hooray!")
b = soup.b
- self.assertEqual(new_text.previous_element, b)
- self.assertEqual(new_text.parent, b)
- self.assertEqual(new_text.previous_element.next_element, new_text)
- self.assertEqual(new_text.next_element, None)
+ assert new_text.previous_element == b
+ assert new_text.parent == b
+ assert new_text.previous_element.next_element == new_text
+ assert new_text.next_element == None
def test_consecutive_text_nodes(self):
# A builder should never create two consecutive text nodes,
@@ -943,28 +939,28 @@ class TestTreeModification(SoupTest):
soup = self.soup("<a><b>Argh!</b><c></c></a>")
soup.b.insert(1, "Hooray!")
- self.assertEqual(
- soup.decode(), self.document_for(
- "<a><b>Argh!Hooray!</b><c></c></a>"))
+ assert soup.decode() == self.document_for(
+ "<a><b>Argh!Hooray!</b><c></c></a>"
+ )
new_text = soup.find(text="Hooray!")
- self.assertEqual(new_text.previous_element, "Argh!")
- self.assertEqual(new_text.previous_element.next_element, new_text)
+ assert new_text.previous_element == "Argh!"
+ assert new_text.previous_element.next_element == new_text
- self.assertEqual(new_text.previous_sibling, "Argh!")
- self.assertEqual(new_text.previous_sibling.next_sibling, new_text)
+ assert new_text.previous_sibling == "Argh!"
+ assert new_text.previous_sibling.next_sibling == new_text
- self.assertEqual(new_text.next_sibling, None)
- self.assertEqual(new_text.next_element, soup.c)
+ assert new_text.next_sibling == None
+ assert new_text.next_element == soup.c
def test_insert_string(self):
soup = self.soup("<a></a>")
soup.a.insert(0, "bar")
soup.a.insert(0, "foo")
# The string were added to the tag.
- self.assertEqual(["foo", "bar"], soup.a.contents)
+ assert ["foo", "bar"] == soup.a.contents
# And they were converted to NavigableStrings.
- self.assertEqual(soup.a.contents[0].next_element, "bar")
+ assert soup.a.contents[0].next_element == "bar"
def test_insert_tag(self):
builder = self.default_builder()
@@ -974,40 +970,40 @@ class TestTreeModification(SoupTest):
magic_tag.insert(0, "the")
soup.a.insert(1, magic_tag)
- self.assertEqual(
- soup.decode(), self.document_for(
- "<a><b>Find</b><magictag>the</magictag><c>lady!</c><d></d></a>"))
+ assert soup.decode() == self.document_for(
+ "<a><b>Find</b><magictag>the</magictag><c>lady!</c><d></d></a>"
+ )
# Make sure all the relationships are hooked up correctly.
b_tag = soup.b
- self.assertEqual(b_tag.next_sibling, magic_tag)
- self.assertEqual(magic_tag.previous_sibling, b_tag)
+ assert b_tag.next_sibling == magic_tag
+ assert magic_tag.previous_sibling == b_tag
find = b_tag.find(text="Find")
- self.assertEqual(find.next_element, magic_tag)
- self.assertEqual(magic_tag.previous_element, find)
+ assert find.next_element == magic_tag
+ assert magic_tag.previous_element == find
c_tag = soup.c
- self.assertEqual(magic_tag.next_sibling, c_tag)
- self.assertEqual(c_tag.previous_sibling, magic_tag)
+ assert magic_tag.next_sibling == c_tag
+ assert c_tag.previous_sibling == magic_tag
the = magic_tag.find(text="the")
- self.assertEqual(the.parent, magic_tag)
- self.assertEqual(the.next_element, c_tag)
- self.assertEqual(c_tag.previous_element, the)
+ assert the.parent == magic_tag
+ assert the.next_element == c_tag
+ assert c_tag.previous_element == the
def test_append_child_thats_already_at_the_end(self):
data = "<a><b></b></a>"
soup = self.soup(data)
soup.a.append(soup.b)
- self.assertEqual(data, soup.decode())
+ assert data == soup.decode()
def test_extend(self):
data = "<a><b><c><d><e><f><g></g></f></e></d></c></b></a>"
soup = self.soup(data)
l = [soup.g, soup.f, soup.e, soup.d, soup.c, soup.b]
soup.a.extend(l)
- self.assertEqual("<a><g></g><f></f><e></e><d></d><c></c><b></b></a>", soup.decode())
+ assert "<a><g></g><f></f><e></e><d></d><c></c><b></b></a>" == soup.decode()
def test_extend_with_another_tags_contents(self):
data = '<body><div id="d1"><a>1</a><a>2</a><a>3</a><a>4</a></div><div id="d2"></div></body>'
@@ -1015,14 +1011,14 @@ class TestTreeModification(SoupTest):
d1 = soup.find('div', id='d1')
d2 = soup.find('div', id='d2')
d2.extend(d1)
- self.assertEqual('<div id="d1"></div>', d1.decode())
- self.assertEqual('<div id="d2"><a>1</a><a>2</a><a>3</a><a>4</a></div>', d2.decode())
+ assert '<div id="d1"></div>' == d1.decode()
+ assert '<div id="d2"><a>1</a><a>2</a><a>3</a><a>4</a></div>' == d2.decode()
def test_move_tag_to_beginning_of_parent(self):
data = "<a><b></b><c></c><d></d></a>"
soup = self.soup(data)
soup.a.insert(0, soup.d)
- self.assertEqual("<a><d></d><b></b><c></c></a>", soup.decode())
+ assert "<a><d></d><b></b><c></c></a>" == soup.decode()
def test_insert_works_on_empty_element_tag(self):
# This is a little strange, since most HTML parsers don't allow
@@ -1031,117 +1027,136 @@ class TestTreeModification(SoupTest):
# I'm letting this succeed for now.
soup = self.soup("<br/>")
soup.br.insert(1, "Contents")
- self.assertEqual(str(soup.br), "<br>Contents</br>")
+ assert str(soup.br) == "<br>Contents</br>"
def test_insert_before(self):
soup = self.soup("<a>foo</a><b>bar</b>")
soup.b.insert_before("BAZ")
soup.a.insert_before("QUUX")
- self.assertEqual(
- soup.decode(), self.document_for("QUUX<a>foo</a>BAZ<b>bar</b>"))
+ assert soup.decode() == self.document_for(
+ "QUUX<a>foo</a>BAZ<b>bar</b>"
+ )
soup.a.insert_before(soup.b)
- self.assertEqual(
- soup.decode(), self.document_for("QUUX<b>bar</b><a>foo</a>BAZ"))
+ assert soup.decode() == self.document_for("QUUX<b>bar</b><a>foo</a>BAZ")
# Can't insert an element before itself.
b = soup.b
- self.assertRaises(ValueError, b.insert_before, b)
+ with pytest.raises(ValueError):
+ b.insert_before(b)
# Can't insert before if an element has no parent.
b.extract()
- self.assertRaises(ValueError, b.insert_before, "nope")
+ with pytest.raises(ValueError):
+ b.insert_before("nope")
# Can insert an identical element
soup = self.soup("<a>")
soup.a.insert_before(soup.new_tag("a"))
+
+ # TODO: OK but what happens?
def test_insert_multiple_before(self):
soup = self.soup("<a>foo</a><b>bar</b>")
soup.b.insert_before("BAZ", " ", "QUUX")
soup.a.insert_before("QUUX", " ", "BAZ")
- self.assertEqual(
- soup.decode(), self.document_for("QUUX BAZ<a>foo</a>BAZ QUUX<b>bar</b>"))
+ assert soup.decode() == self.document_for(
+ "QUUX BAZ<a>foo</a>BAZ QUUX<b>bar</b>"
+ )
soup.a.insert_before(soup.b, "FOO")
- self.assertEqual(
- soup.decode(), self.document_for("QUUX BAZ<b>bar</b>FOO<a>foo</a>BAZ QUUX"))
+ assert soup.decode() == self.document_for(
+ "QUUX BAZ<b>bar</b>FOO<a>foo</a>BAZ QUUX"
+ )
def test_insert_after(self):
soup = self.soup("<a>foo</a><b>bar</b>")
soup.b.insert_after("BAZ")
soup.a.insert_after("QUUX")
- self.assertEqual(
- soup.decode(), self.document_for("<a>foo</a>QUUX<b>bar</b>BAZ"))
+ assert soup.decode() == self.document_for(
+ "<a>foo</a>QUUX<b>bar</b>BAZ"
+ )
soup.b.insert_after(soup.a)
- self.assertEqual(
- soup.decode(), self.document_for("QUUX<b>bar</b><a>foo</a>BAZ"))
+ assert soup.decode() == self.document_for("QUUX<b>bar</b><a>foo</a>BAZ")
# Can't insert an element after itself.
b = soup.b
- self.assertRaises(ValueError, b.insert_after, b)
+ with pytest.raises(ValueError):
+ b.insert_after(b)
# Can't insert after if an element has no parent.
b.extract()
- self.assertRaises(ValueError, b.insert_after, "nope")
+ with pytest.raises(ValueError):
+ b.insert_after("nope")
# Can insert an identical element
soup = self.soup("<a>")
soup.a.insert_before(soup.new_tag("a"))
+
+ # TODO: OK but what does it look like?
def test_insert_multiple_after(self):
soup = self.soup("<a>foo</a><b>bar</b>")
soup.b.insert_after("BAZ", " ", "QUUX")
soup.a.insert_after("QUUX", " ", "BAZ")
- self.assertEqual(
- soup.decode(), self.document_for("<a>foo</a>QUUX BAZ<b>bar</b>BAZ QUUX"))
+ assert soup.decode() == self.document_for(
+ "<a>foo</a>QUUX BAZ<b>bar</b>BAZ QUUX"
+ )
soup.b.insert_after(soup.a, "FOO ")
- self.assertEqual(
- soup.decode(), self.document_for("QUUX BAZ<b>bar</b><a>foo</a>FOO BAZ QUUX"))
+ assert soup.decode() == self.document_for(
+ "QUUX BAZ<b>bar</b><a>foo</a>FOO BAZ QUUX"
+ )
def test_insert_after_raises_exception_if_after_has_no_meaning(self):
soup = self.soup("")
tag = soup.new_tag("a")
string = soup.new_string("")
- self.assertRaises(ValueError, string.insert_after, tag)
- self.assertRaises(NotImplementedError, soup.insert_after, tag)
- self.assertRaises(ValueError, tag.insert_after, tag)
+ with pytest.raises(ValueError):
+ string.insert_after(tag)
+ with pytest.raises(NotImplementedError):
+ soup.insert_after(tag)
+ with pytest.raises(ValueError):
+ tag.insert_after(tag)
def test_insert_before_raises_notimplementederror_if_before_has_no_meaning(self):
soup = self.soup("")
tag = soup.new_tag("a")
string = soup.new_string("")
- self.assertRaises(ValueError, string.insert_before, tag)
- self.assertRaises(NotImplementedError, soup.insert_before, tag)
- self.assertRaises(ValueError, tag.insert_before, tag)
+ with pytest.raises(ValueError):
+ string.insert_before(tag)
+ with pytest.raises(NotImplementedError):
+ soup.insert_before(tag)
+ with pytest.raises(ValueError):
+ tag.insert_before(tag)
def test_replace_with(self):
soup = self.soup(
"<p>There's <b>no</b> business like <b>show</b> business</p>")
no, show = soup.find_all('b')
show.replace_with(no)
- self.assertEqual(
- soup.decode(),
- self.document_for(
- "<p>There's business like <b>no</b> business</p>"))
+ assert soup.decode() == self.document_for(
+ "<p>There's business like <b>no</b> business</p>"
+ )
- self.assertEqual(show.parent, None)
- self.assertEqual(no.parent, soup.p)
- self.assertEqual(no.next_element, "no")
- self.assertEqual(no.next_sibling, " business")
+ assert show.parent == None
+ assert no.parent == soup.p
+ assert no.next_element == "no"
+ assert no.next_sibling == " business"
def test_replace_with_errors(self):
# Can't replace a tag that's not part of a tree.
a_tag = Tag(name="a")
- self.assertRaises(ValueError, a_tag.replace_with, "won't work")
+ with pytest.raises(ValueError):
+ a_tag.replace_with("won't work")
# Can't replace a tag with its parent.
a_tag = self.soup("<a><b></b></a>").a
- self.assertRaises(ValueError, a_tag.b.replace_with, a_tag)
+ with pytest.raises(ValueError):
+ a_tag.b.replace_with(a_tag)
# Or with a list that includes its parent.
- self.assertRaises(ValueError, a_tag.b.replace_with,
- "string1", a_tag, "string2")
+ with pytest.raises(ValueError):
+ a_tag.b.replace_with("string1", a_tag, "string2")
def test_replace_with_multiple(self):
data = "<a><b></b><c></c></a>"
@@ -1152,10 +1167,7 @@ class TestTreeModification(SoupTest):
f_tag = soup.new_tag("f")
a_string = "Random Text"
soup.c.replace_with(d_tag, e_tag, a_string, f_tag)
- self.assertEqual(
- "<a><b></b><d>Text In D Tag</d><e></e>Random Text<f></f></a>",
- soup.decode()
- )
+ assert soup.decode() == "<a><b></b><d>Text In D Tag</d><e></e>Random Text<f></f></a>"
assert soup.b.next_element == d_tag
assert d_tag.string.next_element==e_tag
assert e_tag.next_element.string == a_string
@@ -1165,13 +1177,13 @@ class TestTreeModification(SoupTest):
data = "<a><b></b><c></c></a>"
soup = self.soup(data)
soup.b.replace_with(soup.c)
- self.assertEqual("<a><c></c></a>", soup.decode())
+ assert "<a><c></c></a>" == soup.decode()
def test_replace_last_child(self):
data = "<a><b></b><c></c></a>"
soup = self.soup(data)
soup.c.replace_with(soup.b)
- self.assertEqual("<a><b></b></a>", soup.decode())
+ assert "<a><b></b></a>" == soup.decode()
def test_nested_tag_replace_with(self):
soup = self.soup(
@@ -1183,85 +1195,82 @@ class TestTreeModification(SoupTest):
move_tag = soup.f
remove_tag.replace_with(move_tag)
- self.assertEqual(
- soup.decode(), self.document_for(
- "<a>We<f>refuse</f></a><e>to<g>service</g></e>"))
+ assert soup.decode() == self.document_for(
+ "<a>We<f>refuse</f></a><e>to<g>service</g></e>"
+ )
# The <b> tag is now an orphan.
- self.assertEqual(remove_tag.parent, None)
- self.assertEqual(remove_tag.find(text="right").next_element, None)
- self.assertEqual(remove_tag.previous_element, None)
- self.assertEqual(remove_tag.next_sibling, None)
- self.assertEqual(remove_tag.previous_sibling, None)
+ assert remove_tag.parent == None
+ assert remove_tag.find(text="right").next_element == None
+ assert remove_tag.previous_element == None
+ assert remove_tag.next_sibling == None
+ assert remove_tag.previous_sibling == None
# The <f> tag is now connected to the <a> tag.
- self.assertEqual(move_tag.parent, soup.a)
- self.assertEqual(move_tag.previous_element, "We")
- self.assertEqual(move_tag.next_element.next_element, soup.e)
- self.assertEqual(move_tag.next_sibling, None)
+ assert move_tag.parent == soup.a
+ assert move_tag.previous_element == "We"
+ assert move_tag.next_element.next_element == soup.e
+ assert move_tag.next_sibling == None
# The gap where the <f> tag used to be has been mended, and
# the word "to" is now connected to the <g> tag.
to_text = soup.find(text="to")
g_tag = soup.g
- self.assertEqual(to_text.next_element, g_tag)
- self.assertEqual(to_text.next_sibling, g_tag)
- self.assertEqual(g_tag.previous_element, to_text)
- self.assertEqual(g_tag.previous_sibling, to_text)
+ assert to_text.next_element == g_tag
+ assert to_text.next_sibling == g_tag
+ assert g_tag.previous_element == to_text
+ assert g_tag.previous_sibling == to_text
def test_unwrap(self):
tree = self.soup("""
<p>Unneeded <em>formatting</em> is unneeded</p>
""")
tree.em.unwrap()
- self.assertEqual(tree.em, None)
- self.assertEqual(tree.p.text, "Unneeded formatting is unneeded")
+ assert tree.em == None
+ assert tree.p.text == "Unneeded formatting is unneeded"
def test_wrap(self):
soup = self.soup("I wish I was bold.")
value = soup.string.wrap(soup.new_tag("b"))
- self.assertEqual(value.decode(), "<b>I wish I was bold.</b>")
- self.assertEqual(
- soup.decode(), self.document_for("<b>I wish I was bold.</b>"))
+ assert value.decode() == "<b>I wish I was bold.</b>"
+ assert soup.decode() == self.document_for("<b>I wish I was bold.</b>")
def test_wrap_extracts_tag_from_elsewhere(self):
soup = self.soup("<b></b>I wish I was bold.")
soup.b.next_sibling.wrap(soup.b)
- self.assertEqual(
- soup.decode(), self.document_for("<b>I wish I was bold.</b>"))
+ assert soup.decode() == self.document_for("<b>I wish I was bold.</b>")
def test_wrap_puts_new_contents_at_the_end(self):
soup = self.soup("<b>I like being bold.</b>I wish I was bold.")
soup.b.next_sibling.wrap(soup.b)
- self.assertEqual(2, len(soup.b.contents))
- self.assertEqual(
- soup.decode(), self.document_for(
- "<b>I like being bold.I wish I was bold.</b>"))
+ assert 2 == len(soup.b.contents)
+ assert soup.decode() == self.document_for(
+ "<b>I like being bold.I wish I was bold.</b>"
+ )
def test_extract(self):
soup = self.soup(
'<html><body>Some content. <div id="nav">Nav crap</div> More content.</body></html>')
- self.assertEqual(len(soup.body.contents), 3)
+ assert len(soup.body.contents) == 3
extracted = soup.find(id="nav").extract()
- self.assertEqual(
- soup.decode(), "<html><body>Some content. More content.</body></html>")
- self.assertEqual(extracted.decode(), '<div id="nav">Nav crap</div>')
+ assert soup.decode() == "<html><body>Some content. More content.</body></html>"
+ assert extracted.decode() == '<div id="nav">Nav crap</div>'
# The extracted tag is now an orphan.
- self.assertEqual(len(soup.body.contents), 2)
- self.assertEqual(extracted.parent, None)
- self.assertEqual(extracted.previous_element, None)
- self.assertEqual(extracted.next_element.next_element, None)
+ assert len(soup.body.contents) == 2
+ assert extracted.parent == None
+ assert extracted.previous_element == None
+ assert extracted.next_element.next_element == None
# The gap where the extracted tag used to be has been mended.
content_1 = soup.find(text="Some content. ")
content_2 = soup.find(text=" More content.")
- self.assertEqual(content_1.next_element, content_2)
- self.assertEqual(content_1.next_sibling, content_2)
- self.assertEqual(content_2.previous_element, content_1)
- self.assertEqual(content_2.previous_sibling, content_1)
+ assert content_1.next_element == content_2
+ assert content_1.next_sibling == content_2
+ assert content_2.previous_element == content_1
+ assert content_2.previous_sibling == content_1
def test_extract_distinguishes_between_identical_strings(self):
soup = self.soup("<a>foo</a><b>bar</b>")
@@ -1277,8 +1286,8 @@ class TestTreeModification(SoupTest):
# "bar".
foo_1.extract()
bar_2.extract()
- self.assertEqual(foo_2, soup.a.string)
- self.assertEqual(bar_2, soup.b.string)
+ assert foo_2 == soup.a.string
+ assert bar_2 == soup.b.string
def test_extract_multiples_of_same_tag(self):
soup = self.soup("""
@@ -1293,7 +1302,7 @@ class TestTreeModification(SoupTest):
<script>baz</script>
</html>""")
[soup.script.extract() for i in soup.find_all("script")]
- self.assertEqual("<body>\n\n<a></a>\n</body>", str(soup.body))
+ assert "<body>\n\n<a></a>\n</body>" == str(soup.body)
def test_extract_works_when_element_is_surrounded_by_identical_strings(self):
@@ -1302,7 +1311,7 @@ class TestTreeModification(SoupTest):
'<body>hi</body>\n'
'</html>')
soup.find('body').extract()
- self.assertEqual(None, soup.find('body'))
+ assert None == soup.find('body')
def test_clear(self):
@@ -1311,13 +1320,13 @@ class TestTreeModification(SoupTest):
# clear using extract()
a = soup.a
soup.p.clear()
- self.assertEqual(len(soup.p.contents), 0)
- self.assertTrue(hasattr(a, "contents"))
+ assert len(soup.p.contents) == 0
+ assert hasattr(a, "contents")
# clear using decompose()
em = a.em
a.clear(decompose=True)
- self.assertEqual(0, len(em.contents))
+ assert 0 == len(em.contents)
def test_decompose(self):
@@ -1327,33 +1336,33 @@ class TestTreeModification(SoupTest):
a = p1.a
text = p1.em.string
for i in [p1, p2, a, text]:
- self.assertEqual(False, i.decomposed)
+ assert False == i.decomposed
# This sets p1 and everything beneath it to decomposed.
p1.decompose()
for i in [p1, a, text]:
- self.assertEqual(True, i.decomposed)
+ assert True == i.decomposed
# p2 is unaffected.
- self.assertEqual(False, p2.decomposed)
+ assert False == p2.decomposed
def test_string_set(self):
"""Tag.string = 'string'"""
soup = self.soup("<a></a> <b><c></c></b>")
soup.a.string = "foo"
- self.assertEqual(soup.a.contents, ["foo"])
+ assert soup.a.contents == ["foo"]
soup.b.string = "bar"
- self.assertEqual(soup.b.contents, ["bar"])
+ assert soup.b.contents == ["bar"]
def test_string_set_does_not_affect_original_string(self):
soup = self.soup("<a><b>foo</b><c>bar</c>")
soup.b.string = soup.c.string
- self.assertEqual(soup.a.encode(), b"<a><b>bar</b><c>bar</c></a>")
+ assert soup.a.encode() == b"<a><b>bar</b><c>bar</c></a>"
def test_set_string_preserves_class_of_string(self):
soup = self.soup("<a></a>")
cdata = CData("foo")
soup.a.string = cdata
- self.assertTrue(isinstance(soup.a.string, CData))
+ assert isinstance(soup.a.string, CData)
class TestElementObjects(SoupTest):
"""Test various features of element objects."""
@@ -1364,29 +1373,27 @@ class TestElementObjects(SoupTest):
# The BeautifulSoup object itself contains one element: the
# <top> tag.
- self.assertEqual(len(soup.contents), 1)
- self.assertEqual(len(soup), 1)
+ assert len(soup.contents) == 1
+ assert len(soup) == 1
# The <top> tag contains three elements: the text node "1", the
# <b> tag, and the text node "3".
- self.assertEqual(len(soup.top), 3)
- self.assertEqual(len(soup.top.contents), 3)
+ assert len(soup.top) == 3
+ assert len(soup.top.contents) == 3
def test_member_access_invokes_find(self):
"""Accessing a Python member .foo invokes find('foo')"""
soup = self.soup('<b><i></i></b>')
- self.assertEqual(soup.b, soup.find('b'))
- self.assertEqual(soup.b.i, soup.find('b').find('i'))
- self.assertEqual(soup.a, None)
+ assert soup.b == soup.find('b')
+ assert soup.b.i == soup.find('b').find('i')
+ assert soup.a == None
def test_deprecated_member_access(self):
soup = self.soup('<b><i></i></b>')
with warnings.catch_warnings(record=True) as w:
tag = soup.bTag
- self.assertEqual(soup.b, tag)
- self.assertEqual(
- '.bTag is deprecated, use .find("b") instead. If you really were looking for a tag called bTag, use .find("bTag")',
- str(w[0].message))
+ assert soup.b == tag
+ assert '.bTag is deprecated, use .find("b") instead. If you really were looking for a tag called bTag, use .find("bTag")' == str(w[0].message)
def test_has_attr(self):
"""has_attr() checks for the presence of an attribute.
@@ -1396,8 +1403,8 @@ class TestElementObjects(SoupTest):
checks the tag's chidlren.
"""
soup = self.soup("<foo attr='bar'>")
- self.assertTrue(soup.foo.has_attr('attr'))
- self.assertFalse(soup.foo.has_attr('attr2'))
+ assert soup.foo.has_attr('attr')
+ assert not soup.foo.has_attr('attr2')
def test_attributes_come_out_in_alphabetical_order(self):
@@ -1408,68 +1415,66 @@ class TestElementObjects(SoupTest):
# A tag that contains only a text node makes that node
# available as .string.
soup = self.soup("<b>foo</b>")
- self.assertEqual(soup.b.string, 'foo')
+ assert soup.b.string == 'foo'
def test_empty_tag_has_no_string(self):
# A tag with no children has no .stirng.
soup = self.soup("<b></b>")
- self.assertEqual(soup.b.string, None)
+ assert soup.b.string == None
def test_tag_with_multiple_children_has_no_string(self):
# A tag with no children has no .string.
soup = self.soup("<a>foo<b></b><b></b></b>")
- self.assertEqual(soup.b.string, None)
+ assert soup.b.string == None
soup = self.soup("<a>foo<b></b>bar</b>")
- self.assertEqual(soup.b.string, None)
+ assert soup.b.string == None
# Even if all the children are strings, due to trickery,
# it won't work--but this would be a good optimization.
soup = self.soup("<a>foo</b>")
soup.a.insert(1, "bar")
- self.assertEqual(soup.a.string, None)
+ assert soup.a.string == None
def test_tag_with_recursive_string_has_string(self):
# A tag with a single child which has a .string inherits that
# .string.
soup = self.soup("<a><b>foo</b></a>")
- self.assertEqual(soup.a.string, "foo")
- self.assertEqual(soup.string, "foo")
+ assert soup.a.string == "foo"
+ assert soup.string == "foo"
def test_lack_of_string(self):
"""Only a tag containing a single text node has a .string."""
soup = self.soup("<b>f<i>e</i>o</b>")
- self.assertFalse(soup.b.string)
+ assert soup.b.string is None
soup = self.soup("<b></b>")
- self.assertFalse(soup.b.string)
+ assert soup.b.string is None
def test_all_text(self):
"""Tag.text and Tag.get_text(sep=u"") -> all child text, concatenated"""
soup = self.soup("<a>a<b>r</b> <r> t </r></a>")
- self.assertEqual(soup.a.text, "ar t ")
- self.assertEqual(soup.a.get_text(strip=True), "art")
- self.assertEqual(soup.a.get_text(","), "a,r, , t ")
- self.assertEqual(soup.a.get_text(",", strip=True), "a,r,t")
+ assert soup.a.text == "ar t "
+ assert soup.a.get_text(strip=True) == "art"
+ assert soup.a.get_text(",") == "a,r, , t "
+ assert soup.a.get_text(",", strip=True) == "a,r,t"
def test_get_text_ignores_special_string_containers(self):
soup = self.soup("foo<!--IGNORE-->bar")
- self.assertEqual(soup.get_text(), "foobar")
+ assert soup.get_text() == "foobar"
- self.assertEqual(
- soup.get_text(types=(NavigableString, Comment)), "fooIGNOREbar")
- self.assertEqual(
- soup.get_text(types=None), "fooIGNOREbar")
+ assert soup.get_text(types=(NavigableString, Comment)) == "fooIGNOREbar"
+ assert soup.get_text(types=None) == "fooIGNOREbar"
soup = self.soup("foo<style>CSS</style><script>Javascript</script>bar")
- self.assertEqual(soup.get_text(), "foobar")
+ assert soup.get_text() == "foobar"
def test_all_strings_ignores_special_string_containers(self):
soup = self.soup("foo<!--IGNORE-->bar")
- self.assertEqual(['foo', 'bar'], list(soup.strings))
+ assert ['foo', 'bar'] == list(soup.strings)
soup = self.soup("foo<style>CSS</style><script>Javascript</script>bar")
- self.assertEqual(['foo', 'bar'], list(soup.strings))
+ assert ['foo', 'bar'] == list(soup.strings)
def test_string_methods_inside_special_string_container_tags(self):
# Strings inside tags like <script> are generally ignored by
@@ -1482,29 +1487,25 @@ class TestElementObjects(SoupTest):
template = self.soup("<div>a<template><p>Templated <b>text</b>.</p><!--With a comment.--></template></div>")
script = self.soup("<div>a<script><!--a comment-->Some text</script></div>")
- self.assertEqual(style.div.get_text(), "a")
- self.assertEqual(list(style.div.strings), ["a"])
- self.assertEqual(style.div.style.get_text(), "Some CSS")
- self.assertEqual(list(style.div.style.strings),
- ['Some CSS'])
+ assert style.div.get_text() == "a"
+ assert list(style.div.strings) == ["a"]
+ assert style.div.style.get_text() == "Some CSS"
+ assert list(style.div.style.strings) == ['Some CSS']
# The comment is not picked up here. That's because it was
# parsed into a Comment object, which is not considered
# interesting by template.strings.
- self.assertEqual(template.div.get_text(), "a")
- self.assertEqual(list(template.div.strings), ["a"])
- self.assertEqual(template.div.template.get_text(), "Templated text.")
- self.assertEqual(list(template.div.template.strings),
- ["Templated ", "text", "."])
+ assert template.div.get_text() == "a"
+ assert list(template.div.strings) == ["a"]
+ assert template.div.template.get_text() == "Templated text."
+ assert list(template.div.template.strings) == ["Templated ", "text", "."]
# The comment is included here, because it didn't get parsed
# into a Comment object--it's part of the Script string.
- self.assertEqual(script.div.get_text(), "a")
- self.assertEqual(list(script.div.strings), ["a"])
- self.assertEqual(script.div.script.get_text(),
- "<!--a comment-->Some text")
- self.assertEqual(list(script.div.script.strings),
- ['<!--a comment-->Some text'])
+ assert script.div.get_text() == "a"
+ assert list(script.div.strings) == ["a"]
+ assert script.div.script.get_text() == "<!--a comment-->Some text"
+ assert list(script.div.script.strings) == ['<!--a comment-->Some text']
class TestCDAtaListAttributes(SoupTest):
@@ -1512,27 +1513,27 @@ class TestCDAtaListAttributes(SoupTest):
"""
def test_single_value_becomes_list(self):
soup = self.soup("<a class='foo'>")
- self.assertEqual(["foo"],soup.a['class'])
+ assert ["foo"] ==soup.a['class']
def test_multiple_values_becomes_list(self):
soup = self.soup("<a class='foo bar'>")
- self.assertEqual(["foo", "bar"], soup.a['class'])
+ assert ["foo", "bar"] == soup.a['class']
def test_multiple_values_separated_by_weird_whitespace(self):
soup = self.soup("<a class='foo\tbar\nbaz'>")
- self.assertEqual(["foo", "bar", "baz"],soup.a['class'])
+ assert ["foo", "bar", "baz"] ==soup.a['class']
def test_attributes_joined_into_string_on_output(self):
soup = self.soup("<a class='foo\tbar'>")
- self.assertEqual(b'<a class="foo bar"></a>', soup.a.encode())
+ assert b'<a class="foo bar"></a>' == soup.a.encode()
def test_get_attribute_list(self):
soup = self.soup("<a id='abc def'>")
- self.assertEqual(['abc def'], soup.a.get_attribute_list('id'))
+ assert ['abc def'] == soup.a.get_attribute_list('id')
def test_accept_charset(self):
soup = self.soup('<form accept-charset="ISO-8859-1 UTF-8">')
- self.assertEqual(['ISO-8859-1', 'UTF-8'], soup.form['accept-charset'])
+ assert ['ISO-8859-1', 'UTF-8'] == soup.form['accept-charset']
def test_cdata_attribute_applying_only_to_one_tag(self):
data = '<a accept-charset="ISO-8859-1 UTF-8"></a>'
@@ -1540,20 +1541,18 @@ class TestCDAtaListAttributes(SoupTest):
# We saw in another test that accept-charset is a cdata-list
# attribute for the <form> tag. But it's not a cdata-list
# attribute for any other tag.
- self.assertEqual('ISO-8859-1 UTF-8', soup.a['accept-charset'])
+ assert 'ISO-8859-1 UTF-8' == soup.a['accept-charset']
def test_string_has_immutable_name_property(self):
string = self.soup("s").string
- self.assertEqual(None, string.name)
- def t():
+ assert None == string.name
+ with pytest.raises(AttributeError):
string.name = 'foo'
- self.assertRaises(AttributeError, t)
class TestPersistence(SoupTest):
"Testing features like pickle and deepcopy."
- def setUp(self):
- super(TestPersistence, self).setUp()
+ def setup_method(self):
self.page = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/transitional.dtd">
<html>
@@ -1577,20 +1576,20 @@ class TestPersistence(SoupTest):
# to the original.
dumped = pickle.dumps(self.tree, 2)
loaded = pickle.loads(dumped)
- self.assertEqual(loaded.__class__, BeautifulSoup)
- self.assertEqual(loaded.decode(), self.tree.decode())
+ assert loaded.__class__ == BeautifulSoup
+ assert loaded.decode() == self.tree.decode()
def test_deepcopy_identity(self):
# Making a deepcopy of a tree yields an identical tree.
copied = copy.deepcopy(self.tree)
- self.assertEqual(copied.decode(), self.tree.decode())
+ assert copied.decode() == self.tree.decode()
def test_copy_preserves_encoding(self):
soup = BeautifulSoup(b'<p>&nbsp;</p>', 'html.parser')
encoding = soup.original_encoding
copy = soup.__copy__()
- self.assertEqual("<p> </p>", str(copy))
- self.assertEqual(encoding, copy.original_encoding)
+ assert "<p> </p>" == str(copy)
+ assert encoding == copy.original_encoding
def test_copy_preserves_builder_information(self):
@@ -1604,18 +1603,11 @@ class TestPersistence(SoupTest):
# The TreeBuilder object is no longer availble, but information
# obtained from it gets copied over to the new Tag object.
- self.assertEqual(tag.sourceline, copied.sourceline)
- self.assertEqual(tag.sourcepos, copied.sourcepos)
- self.assertEqual(
- tag.can_be_empty_element, copied.can_be_empty_element
- )
- self.assertEqual(
- tag.cdata_list_attributes, copied.cdata_list_attributes
- )
- self.assertEqual(
- tag.preserve_whitespace_tags, copied.preserve_whitespace_tags
- )
-
+ assert tag.sourceline == copied.sourceline
+ assert tag.sourcepos == copied.sourcepos
+ assert tag.can_be_empty_element == copied.can_be_empty_element
+ assert tag.cdata_list_attributes == copied.cdata_list_attributes
+ assert tag.preserve_whitespace_tags == copied.preserve_whitespace_tags
def test_unicode_pickle(self):
# A tree containing Unicode characters can be pickled.
@@ -1623,33 +1615,33 @@ class TestPersistence(SoupTest):
soup = self.soup(html)
dumped = pickle.dumps(soup, pickle.HIGHEST_PROTOCOL)
loaded = pickle.loads(dumped)
- self.assertEqual(loaded.decode(), soup.decode())
+ assert loaded.decode() == soup.decode()
def test_copy_navigablestring_is_not_attached_to_tree(self):
html = "<b>Foo<a></a></b><b>Bar</b>"
soup = self.soup(html)
s1 = soup.find(string="Foo")
s2 = copy.copy(s1)
- self.assertEqual(s1, s2)
- self.assertEqual(None, s2.parent)
- self.assertEqual(None, s2.next_element)
- self.assertNotEqual(None, s1.next_sibling)
- self.assertEqual(None, s2.next_sibling)
- self.assertEqual(None, s2.previous_element)
+ assert s1 == s2
+ assert None == s2.parent
+ assert None == s2.next_element
+ assert None != s1.next_sibling
+ assert None == s2.next_sibling
+ assert None == s2.previous_element
def test_copy_navigablestring_subclass_has_same_type(self):
html = "<b><!--Foo--></b>"
soup = self.soup(html)
s1 = soup.string
s2 = copy.copy(s1)
- self.assertEqual(s1, s2)
- self.assertTrue(isinstance(s2, Comment))
+ assert s1 == s2
+ assert isinstance(s2, Comment)
def test_copy_entire_soup(self):
html = "<div><b>Foo<a></a></b><b>Bar</b></div>end"
soup = self.soup(html)
soup_copy = copy.copy(soup)
- self.assertEqual(soup, soup_copy)
+ assert soup == soup_copy
def test_copy_tag_copies_contents(self):
html = "<div><b>Foo<a></a></b><b>Bar</b></div>end"
@@ -1658,18 +1650,18 @@ class TestPersistence(SoupTest):
div_copy = copy.copy(div)
# The two tags look the same, and evaluate to equal.
- self.assertEqual(str(div), str(div_copy))
- self.assertEqual(div, div_copy)
+ assert str(div) == str(div_copy)
+ assert div == div_copy
# But they're not the same object.
- self.assertFalse(div is div_copy)
+ assert div is not div_copy
# And they don't have the same relation to the parse tree. The
# copy is not associated with a parse tree at all.
- self.assertEqual(None, div_copy.parent)
- self.assertEqual(None, div_copy.previous_element)
- self.assertEqual(None, div_copy.find(string='Bar').next_element)
- self.assertNotEqual(None, div.find(string='Bar').next_element)
+ assert None == div_copy.parent
+ assert None == div_copy.previous_element
+ assert None == div_copy.find(string='Bar').next_element
+ assert None != div.find(string='Bar').next_element
class TestSubstitutions(SoupTest):
@@ -1678,36 +1670,34 @@ class TestSubstitutions(SoupTest):
soup = self.soup(markup)
decoded = soup.decode(formatter="minimal")
# The < is converted back into &lt; but the e-with-acute is left alone.
- self.assertEqual(
- decoded,
- self.document_for(
- "<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"))
+ assert decoded == self.document_for(
+ "<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"
+ )
def test_formatter_html(self):
markup = "<br><b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"
soup = self.soup(markup)
decoded = soup.decode(formatter="html")
- self.assertEqual(
- decoded,
- self.document_for("<br/><b>&lt;&lt;Sacr&eacute; bleu!&gt;&gt;</b>"))
+ assert decoded == self.document_for(
+ "<br/><b>&lt;&lt;Sacr&eacute; bleu!&gt;&gt;</b>"
+ )
def test_formatter_html5(self):
markup = "<br><b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"
soup = self.soup(markup)
decoded = soup.decode(formatter="html5")
- self.assertEqual(
- decoded,
- self.document_for("<br><b>&lt;&lt;Sacr&eacute; bleu!&gt;&gt;</b>"))
+ assert decoded == self.document_for(
+ "<br><b>&lt;&lt;Sacr&eacute; bleu!&gt;&gt;</b>"
+ )
def test_formatter_minimal(self):
markup = "<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"
soup = self.soup(markup)
decoded = soup.decode(formatter="minimal")
# The < is converted back into &lt; but the e-with-acute is left alone.
- self.assertEqual(
- decoded,
- self.document_for(
- "<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"))
+ assert decoded == self.document_for(
+ "<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"
+ )
def test_formatter_null(self):
markup = "<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>"
@@ -1715,8 +1705,9 @@ class TestSubstitutions(SoupTest):
decoded = soup.decode(formatter=None)
# Neither the angle brackets nor the e-with-acute are converted.
# This is not valid HTML, but it's what the user wanted.
- self.assertEqual(decoded,
- self.document_for("<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"))
+ assert decoded == self.document_for(
+ "<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"
+ )
def test_formatter_custom(self):
markup = "<b>&lt;foo&gt;</b><b>bar</b><br/>"
@@ -1724,9 +1715,7 @@ class TestSubstitutions(SoupTest):
decoded = soup.decode(formatter = lambda x: x.upper())
# Instead of normal entity conversion code, the custom
# callable is called on every string.
- self.assertEqual(
- decoded,
- self.document_for("<b><FOO></b><b>BAR</b><br/>"))
+ assert decoded == self.document_for("<b><FOO></b><b>BAR</b><br/>")
def test_formatter_is_run_on_attribute_values(self):
markup = '<a href="http://a.com?a=b&c=é">e</a>'
@@ -1735,15 +1724,15 @@ class TestSubstitutions(SoupTest):
expect_minimal = '<a href="http://a.com?a=b&amp;c=é">e</a>'
- self.assertEqual(expect_minimal, a.decode())
- self.assertEqual(expect_minimal, a.decode(formatter="minimal"))
+ assert expect_minimal == a.decode()
+ assert expect_minimal == a.decode(formatter="minimal")
expect_html = '<a href="http://a.com?a=b&amp;c=&eacute;">e</a>'
- self.assertEqual(expect_html, a.decode(formatter="html"))
+ assert expect_html == a.decode(formatter="html")
- self.assertEqual(markup, a.decode(formatter=None))
+ assert markup == a.decode(formatter=None)
expect_upper = '<a href="HTTP://A.COM?A=B&C=É">E</a>'
- self.assertEqual(expect_upper, a.decode(formatter=lambda x: x.upper()))
+ assert expect_upper == a.decode(formatter=lambda x: x.upper())
def test_formatter_skips_script_tag_for_html_documents(self):
doc = """
@@ -1752,7 +1741,7 @@ class TestSubstitutions(SoupTest):
</script>
"""
encoded = BeautifulSoup(doc, 'html.parser').encode()
- self.assertTrue(b"< < hey > >" in encoded)
+ assert b"< < hey > >" in encoded
def test_formatter_skips_style_tag_for_html_documents(self):
doc = """
@@ -1761,34 +1750,32 @@ class TestSubstitutions(SoupTest):
</style>
"""
encoded = BeautifulSoup(doc, 'html.parser').encode()
- self.assertTrue(b"< < hey > >" in encoded)
+ assert b"< < hey > >" in encoded
def test_prettify_leaves_preformatted_text_alone(self):
soup = self.soup("<div> foo <pre> \tbar\n \n </pre> baz <textarea> eee\nfff\t</textarea></div>")
# Everything outside the <pre> tag is reformatted, but everything
# inside is left alone.
- self.assertEqual(
- '<div>\n foo\n <pre> \tbar\n \n </pre>\n baz\n <textarea> eee\nfff\t</textarea>\n</div>',
- soup.div.prettify())
+ assert '<div>\n foo\n <pre> \tbar\n \n </pre>\n baz\n <textarea> eee\nfff\t</textarea>\n</div>' == soup.div.prettify()
def test_prettify_accepts_formatter_function(self):
soup = BeautifulSoup("<html><body>foo</body></html>", 'html.parser')
pretty = soup.prettify(formatter = lambda x: x.upper())
- self.assertTrue("FOO" in pretty)
+ assert "FOO" in pretty
def test_prettify_outputs_unicode_by_default(self):
soup = self.soup("<a></a>")
- self.assertEqual(str, type(soup.prettify()))
+ assert str == type(soup.prettify())
def test_prettify_can_encode_data(self):
soup = self.soup("<a></a>")
- self.assertEqual(bytes, type(soup.prettify("utf-8")))
+ assert bytes == type(soup.prettify("utf-8"))
def test_html_entity_substitution_off_by_default(self):
markup = "<b>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</b>"
soup = self.soup(markup)
encoded = soup.b.encode("utf-8")
- self.assertEqual(encoded, markup.encode('utf-8'))
+ assert encoded == markup.encode('utf-8')
def test_encoding_substitution(self):
# Here's the <meta> tag saying that a document is
@@ -1798,21 +1785,21 @@ class TestSubstitutions(SoupTest):
soup = self.soup(meta_tag)
# Parse the document, and the charset apprears unchanged.
- self.assertEqual(soup.meta['content'], 'text/html; charset=x-sjis')
+ assert soup.meta['content'] == 'text/html; charset=x-sjis'
# Encode the document into some encoding, and the encoding is
# substituted into the meta tag.
utf_8 = soup.encode("utf-8")
- self.assertTrue(b"charset=utf-8" in utf_8)
+ assert b"charset=utf-8" in utf_8
euc_jp = soup.encode("euc_jp")
- self.assertTrue(b"charset=euc_jp" in euc_jp)
+ assert b"charset=euc_jp" in euc_jp
shift_jis = soup.encode("shift-jis")
- self.assertTrue(b"charset=shift-jis" in shift_jis)
+ assert b"charset=shift-jis" in shift_jis
utf_16_u = soup.encode("utf-16").decode("utf-16")
- self.assertTrue("charset=utf-16" in utf_16_u)
+ assert "charset=utf-16" in utf_16_u
def test_encoding_substitution_doesnt_happen_if_tag_is_strained(self):
markup = ('<head><meta content="text/html; charset=x-sjis" '
@@ -1823,7 +1810,7 @@ class TestSubstitutions(SoupTest):
# sure that doesn't happen.
strainer = SoupStrainer('pre')
soup = self.soup(markup, parse_only=strainer)
- self.assertEqual(soup.contents[0].name, 'pre')
+ assert soup.contents[0].name == 'pre'
class TestEncoding(SoupTest):
"""Test the ability to encode objects into strings."""
@@ -1831,51 +1818,48 @@ class TestEncoding(SoupTest):
def test_unicode_string_can_be_encoded(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
- self.assertEqual(soup.b.string.encode("utf-8"),
- "\N{SNOWMAN}".encode("utf-8"))
+ assert soup.b.string.encode("utf-8") == "\N{SNOWMAN}".encode("utf-8")
def test_tag_containing_unicode_string_can_be_encoded(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
- self.assertEqual(
- soup.b.encode("utf-8"), html.encode("utf-8"))
+ assert soup.b.encode("utf-8") == html.encode("utf-8")
def test_encoding_substitutes_unrecognized_characters_by_default(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
- self.assertEqual(soup.b.encode("ascii"), b"<b>&#9731;</b>")
+ assert soup.b.encode("ascii") == b"<b>&#9731;</b>"
def test_encoding_can_be_made_strict(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
- self.assertRaises(
- UnicodeEncodeError, soup.encode, "ascii", errors="strict")
+ with pytest.raises(UnicodeEncodeError):
+ soup.encode("ascii", errors="strict")
def test_decode_contents(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
- self.assertEqual("\N{SNOWMAN}", soup.b.decode_contents())
+ assert "\N{SNOWMAN}" == soup.b.decode_contents()
def test_encode_contents(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
- self.assertEqual(
- "\N{SNOWMAN}".encode("utf8"), soup.b.encode_contents(
- encoding="utf8"))
+ assert "\N{SNOWMAN}".encode("utf8") == soup.b.encode_contents(
+ encoding="utf8"
+ )
def test_deprecated_renderContents(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
- self.assertEqual(
- "\N{SNOWMAN}".encode("utf8"), soup.b.renderContents())
+ assert "\N{SNOWMAN}".encode("utf8") == soup.b.renderContents()
def test_repr(self):
html = "<b>\N{SNOWMAN}</b>"
soup = self.soup(html)
if PY3K:
- self.assertEqual(html, repr(soup))
+ assert html == repr(soup)
else:
- self.assertEqual(b'<b>\\u2603</b>', repr(soup))
+ assert b'<b>\\u2603</b>' == repr(soup)
class TestSoupSelector(TreeTest):
@@ -1929,82 +1913,81 @@ class TestSoupSelector(TreeTest):
</div>
"""
- def setUp(self):
+ def setup_method(self):
self.soup = BeautifulSoup(self.HTML, 'html.parser')
- def assertSelects(self, selector, expected_ids, **kwargs):
+ def assert_selects(self, selector, expected_ids, **kwargs):
el_ids = [el['id'] for el in self.soup.select(selector, **kwargs)]
el_ids.sort()
expected_ids.sort()
- self.assertEqual(expected_ids, el_ids,
- "Selector %s, expected [%s], got [%s]" % (
+ assert expected_ids == el_ids, "Selector %s, expected [%s], got [%s]" % (
selector, ', '.join(expected_ids), ', '.join(el_ids)
- )
)
- assertSelect = assertSelects
+ assertSelect = assert_selects
- def assertSelectMultiple(self, *tests):
+ def assert_select_multiple(self, *tests):
for selector, expected_ids in tests:
- self.assertSelect(selector, expected_ids)
+ self.assert_selects(selector, expected_ids)
def test_one_tag_one(self):
els = self.soup.select('title')
- self.assertEqual(len(els), 1)
- self.assertEqual(els[0].name, 'title')
- self.assertEqual(els[0].contents, ['The title'])
+ assert len(els) == 1
+ assert els[0].name == 'title'
+ assert els[0].contents == ['The title']
def test_one_tag_many(self):
els = self.soup.select('div')
- self.assertEqual(len(els), 4)
+ assert len(els) == 4
for div in els:
- self.assertEqual(div.name, 'div')
+ assert div.name == 'div'
el = self.soup.select_one('div')
- self.assertEqual('main', el['id'])
+ assert 'main' == el['id']
def test_select_one_returns_none_if_no_match(self):
match = self.soup.select_one('nonexistenttag')
- self.assertEqual(None, match)
+ assert None == match
def test_tag_in_tag_one(self):
els = self.soup.select('div div')
- self.assertSelects('div div', ['inner', 'data1'])
+ self.assert_selects('div div', ['inner', 'data1'])
def test_tag_in_tag_many(self):
for selector in ('html div', 'html body div', 'body div'):
- self.assertSelects(selector, ['data1', 'main', 'inner', 'footer'])
+ self.assert_selects(selector, ['data1', 'main', 'inner', 'footer'])
def test_limit(self):
- self.assertSelects('html div', ['main'], limit=1)
- self.assertSelects('html body div', ['inner', 'main'], limit=2)
- self.assertSelects('body div', ['data1', 'main', 'inner', 'footer'],
+ self.assert_selects('html div', ['main'], limit=1)
+ self.assert_selects('html body div', ['inner', 'main'], limit=2)
+ self.assert_selects('body div', ['data1', 'main', 'inner', 'footer'],
limit=10)
def test_tag_no_match(self):
- self.assertEqual(len(self.soup.select('del')), 0)
+ assert len(self.soup.select('del')) == 0
def test_invalid_tag(self):
- self.assertRaises(SelectorSyntaxError, self.soup.select, 'tag%t')
+ with pytest.raises(SelectorSyntaxError):
+ self.soup.select('tag%t')
def test_select_dashed_tag_ids(self):
- self.assertSelects('custom-dashed-tag', ['dash1', 'dash2'])
+ self.assert_selects('custom-dashed-tag', ['dash1', 'dash2'])
def test_select_dashed_by_id(self):
dashed = self.soup.select('custom-dashed-tag[id=\"dash2\"]')
- self.assertEqual(dashed[0].name, 'custom-dashed-tag')
- self.assertEqual(dashed[0]['id'], 'dash2')
+ assert dashed[0].name == 'custom-dashed-tag'
+ assert dashed[0]['id'] == 'dash2'
def test_dashed_tag_text(self):
- self.assertEqual(self.soup.select('body > custom-dashed-tag')[0].text, 'Hello there.')
+ assert self.soup.select('body > custom-dashed-tag')[0].text == 'Hello there.'
def test_select_dashed_matches_find_all(self):
- self.assertEqual(self.soup.select('custom-dashed-tag'), self.soup.find_all('custom-dashed-tag'))
+ assert self.soup.select('custom-dashed-tag') == self.soup.find_all('custom-dashed-tag')
def test_header_tags(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
('h1', ['header1']),
('h2', ['header2', 'header3']),
)
@@ -2012,53 +1995,53 @@ class TestSoupSelector(TreeTest):
def test_class_one(self):
for selector in ('.onep', 'p.onep', 'html p.onep'):
els = self.soup.select(selector)
- self.assertEqual(len(els), 1)
- self.assertEqual(els[0].name, 'p')
- self.assertEqual(els[0]['class'], ['onep'])
+ assert len(els) == 1
+ assert els[0].name == 'p'
+ assert els[0]['class'] == ['onep']
def test_class_mismatched_tag(self):
els = self.soup.select('div.onep')
- self.assertEqual(len(els), 0)
+ assert len(els) == 0
def test_one_id(self):
for selector in ('div#inner', '#inner', 'div div#inner'):
- self.assertSelects(selector, ['inner'])
+ self.assert_selects(selector, ['inner'])
def test_bad_id(self):
els = self.soup.select('#doesnotexist')
- self.assertEqual(len(els), 0)
+ assert len(els) == 0
def test_items_in_id(self):
els = self.soup.select('div#inner p')
- self.assertEqual(len(els), 3)
+ assert len(els) == 3
for el in els:
- self.assertEqual(el.name, 'p')
- self.assertEqual(els[1]['class'], ['onep'])
- self.assertFalse(els[0].has_attr('class'))
+ assert el.name == 'p'
+ assert els[1]['class'] == ['onep']
+ assert not els[0].has_attr('class')
def test_a_bunch_of_emptys(self):
for selector in ('div#main del', 'div#main div.oops', 'div div#main'):
- self.assertEqual(len(self.soup.select(selector)), 0)
+ assert len(self.soup.select(selector)) == 0
def test_multi_class_support(self):
for selector in ('.class1', 'p.class1', '.class2', 'p.class2',
'.class3', 'p.class3', 'html p.class2', 'div#inner .class2'):
- self.assertSelects(selector, ['pmulti'])
+ self.assert_selects(selector, ['pmulti'])
def test_multi_class_selection(self):
for selector in ('.class1.class3', '.class3.class2',
'.class1.class2.class3'):
- self.assertSelects(selector, ['pmulti'])
+ self.assert_selects(selector, ['pmulti'])
def test_child_selector(self):
- self.assertSelects('.s1 > a', ['s1a1', 's1a2'])
- self.assertSelects('.s1 > a span', ['s1a2s1'])
+ self.assert_selects('.s1 > a', ['s1a1', 's1a2'])
+ self.assert_selects('.s1 > a span', ['s1a2s1'])
def test_child_selector_id(self):
- self.assertSelects('.s1 > a#s1a2 span', ['s1a2s1'])
+ self.assert_selects('.s1 > a#s1a2 span', ['s1a2s1'])
def test_attribute_equals(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
('p[class="onep"]', ['p1']),
('p[id="p1"]', ['p1']),
('[class="onep"]', ['p1']),
@@ -2076,7 +2059,7 @@ class TestSoupSelector(TreeTest):
)
def test_attribute_tilde(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
('p[class~="class1"]', ['pmulti']),
('p[class~="class2"]', ['pmulti']),
('p[class~="class3"]', ['pmulti']),
@@ -2090,7 +2073,7 @@ class TestSoupSelector(TreeTest):
)
def test_attribute_startswith(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
('[rel^="style"]', ['l1']),
('link[rel^="style"]', ['l1']),
('notlink[rel^="notstyle"]', []),
@@ -2107,7 +2090,7 @@ class TestSoupSelector(TreeTest):
)
def test_attribute_endswith(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
('[href$=".css"]', ['l1']),
('link[href$=".css"]', ['l1']),
('link[id$="1"]', ['l1']),
@@ -2117,7 +2100,7 @@ class TestSoupSelector(TreeTest):
)
def test_attribute_contains(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
# From test_attribute_startswith
('[rel*="style"]', ['l1']),
('link[rel*="style"]', ['l1']),
@@ -2146,7 +2129,7 @@ class TestSoupSelector(TreeTest):
)
def test_attribute_exact_or_hypen(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
('p[lang|="en"]', ['lang-en', 'lang-en-gb', 'lang-en-us']),
('[lang|="en"]', ['lang-en', 'lang-en-gb', 'lang-en-us']),
('p[lang|="fr"]', ['lang-fr']),
@@ -2154,7 +2137,7 @@ class TestSoupSelector(TreeTest):
)
def test_attribute_exists(self):
- self.assertSelectMultiple(
+ self.assert_select_multiple(
('[rel]', ['l1', 'bob', 'me']),
('link[rel]', ['l1']),
('a[rel]', ['bob', 'me']),
@@ -2171,41 +2154,41 @@ class TestSoupSelector(TreeTest):
"""
soup = BeautifulSoup(html, 'html.parser')
[chosen] = soup.select('div[style="display: right"]')
- self.assertEqual("yes", chosen.string)
+ assert "yes" == chosen.string
def test_unsupported_pseudoclass(self):
- self.assertRaises(
- NotImplementedError, self.soup.select, "a:no-such-pseudoclass")
+ with pytest.raises(NotImplementedError):
+ self.soup.select("a:no-such-pseudoclass")
- self.assertRaises(
- SelectorSyntaxError, self.soup.select, "a:nth-of-type(a)")
+ with pytest.raises(SelectorSyntaxError):
+ self.soup.select("a:nth-of-type(a)")
def test_nth_of_type(self):
# Try to select first paragraph
els = self.soup.select('div#inner p:nth-of-type(1)')
- self.assertEqual(len(els), 1)
- self.assertEqual(els[0].string, 'Some text')
+ assert len(els) == 1
+ assert els[0].string == 'Some text'
# Try to select third paragraph
els = self.soup.select('div#inner p:nth-of-type(3)')
- self.assertEqual(len(els), 1)
- self.assertEqual(els[0].string, 'Another')
+ assert len(els) == 1
+ assert els[0].string == 'Another'
# Try to select (non-existent!) fourth paragraph
els = self.soup.select('div#inner p:nth-of-type(4)')
- self.assertEqual(len(els), 0)
+ assert len(els) == 0
# Zero will select no tags.
els = self.soup.select('div p:nth-of-type(0)')
- self.assertEqual(len(els), 0)
+ assert len(els) == 0
def test_nth_of_type_direct_descendant(self):
els = self.soup.select('div#inner > p:nth-of-type(1)')
- self.assertEqual(len(els), 1)
- self.assertEqual(els[0].string, 'Some text')
+ assert len(els) == 1
+ assert els[0].string == 'Some text'
def test_id_child_selector_nth_of_type(self):
- self.assertSelects('#inner > p:nth-of-type(2)', ['p1'])
+ self.assert_selects('#inner > p:nth-of-type(2)', ['p1'])
def test_select_on_element(self):
# Other tests operate on the tree; this operates on an element
@@ -2214,68 +2197,71 @@ class TestSoupSelector(TreeTest):
selected = inner.select("div")
# The <div id="inner"> tag was selected. The <div id="footer">
# tag was not.
- self.assertSelectsIDs(selected, ['inner', 'data1'])
+ self.assert_selects_ids(selected, ['inner', 'data1'])
def test_overspecified_child_id(self):
- self.assertSelects(".fancy #inner", ['inner'])
- self.assertSelects(".normal #inner", [])
+ self.assert_selects(".fancy #inner", ['inner'])
+ self.assert_selects(".normal #inner", [])
def test_adjacent_sibling_selector(self):
- self.assertSelects('#p1 + h2', ['header2'])
- self.assertSelects('#p1 + h2 + p', ['pmulti'])
- self.assertSelects('#p1 + #header2 + .class1', ['pmulti'])
- self.assertEqual([], self.soup.select('#p1 + p'))
+ self.assert_selects('#p1 + h2', ['header2'])
+ self.assert_selects('#p1 + h2 + p', ['pmulti'])
+ self.assert_selects('#p1 + #header2 + .class1', ['pmulti'])
+ assert [] == self.soup.select('#p1 + p')
def test_general_sibling_selector(self):
- self.assertSelects('#p1 ~ h2', ['header2', 'header3'])
- self.assertSelects('#p1 ~ #header2', ['header2'])
- self.assertSelects('#p1 ~ h2 + a', ['me'])
- self.assertSelects('#p1 ~ h2 + [rel="me"]', ['me'])
- self.assertEqual([], self.soup.select('#inner ~ h2'))
+ self.assert_selects('#p1 ~ h2', ['header2', 'header3'])
+ self.assert_selects('#p1 ~ #header2', ['header2'])
+ self.assert_selects('#p1 ~ h2 + a', ['me'])
+ self.assert_selects('#p1 ~ h2 + [rel="me"]', ['me'])
+ assert [] == self.soup.select('#inner ~ h2')
def test_dangling_combinator(self):
- self.assertRaises(SelectorSyntaxError, self.soup.select, 'h1 >')
+ with pytest.raises(SelectorSyntaxError):
+ self.soup.select('h1 >')
def test_sibling_combinator_wont_select_same_tag_twice(self):
- self.assertSelects('p[lang] ~ p', ['lang-en-gb', 'lang-en-us', 'lang-fr'])
+ self.assert_selects('p[lang] ~ p', ['lang-en-gb', 'lang-en-us', 'lang-fr'])
# Test the selector grouping operator (the comma)
def test_multiple_select(self):
- self.assertSelects('x, y', ['xid', 'yid'])
+ self.assert_selects('x, y', ['xid', 'yid'])
def test_multiple_select_with_no_space(self):
- self.assertSelects('x,y', ['xid', 'yid'])
+ self.assert_selects('x,y', ['xid', 'yid'])
def test_multiple_select_with_more_space(self):
- self.assertSelects('x, y', ['xid', 'yid'])
+ self.assert_selects('x, y', ['xid', 'yid'])
def test_multiple_select_duplicated(self):
- self.assertSelects('x, x', ['xid'])
+ self.assert_selects('x, x', ['xid'])
def test_multiple_select_sibling(self):
- self.assertSelects('x, y ~ p[lang=fr]', ['xid', 'lang-fr'])
+ self.assert_selects('x, y ~ p[lang=fr]', ['xid', 'lang-fr'])
def test_multiple_select_tag_and_direct_descendant(self):
- self.assertSelects('x, y > z', ['xid', 'zidb'])
+ self.assert_selects('x, y > z', ['xid', 'zidb'])
def test_multiple_select_direct_descendant_and_tags(self):
- self.assertSelects('div > x, y, z', ['xid', 'yid', 'zida', 'zidb', 'zidab', 'zidac'])
+ self.assert_selects('div > x, y, z', ['xid', 'yid', 'zida', 'zidb', 'zidab', 'zidac'])
def test_multiple_select_indirect_descendant(self):
- self.assertSelects('div x,y, z', ['xid', 'yid', 'zida', 'zidb', 'zidab', 'zidac'])
+ self.assert_selects('div x,y, z', ['xid', 'yid', 'zida', 'zidb', 'zidab', 'zidac'])
def test_invalid_multiple_select(self):
- self.assertRaises(SelectorSyntaxError, self.soup.select, ',x, y')
- self.assertRaises(SelectorSyntaxError, self.soup.select, 'x,,y')
+ with pytest.raises(SelectorSyntaxError):
+ self.soup.select(',x, y')
+ with pytest.raises(SelectorSyntaxError):
+ self.soup.select('x,,y')
def test_multiple_select_attrs(self):
- self.assertSelects('p[lang=en], p[lang=en-gb]', ['lang-en', 'lang-en-gb'])
+ self.assert_selects('p[lang=en], p[lang=en-gb]', ['lang-en', 'lang-en-gb'])
def test_multiple_select_ids(self):
- self.assertSelects('x, y > z[id=zida], z[id=zidab], z[id=zidb]', ['xid', 'zidb', 'zidab'])
+ self.assert_selects('x, y > z[id=zida], z[id=zidab], z[id=zidb]', ['xid', 'zidb', 'zidab'])
def test_multiple_select_nested(self):
- self.assertSelects('body > div > x, y > z', ['xid', 'zidb'])
+ self.assert_selects('body > div > x, y > z', ['xid', 'zidb'])
def test_select_duplicate_elements(self):
# When markup contains duplicate elements, a multiple select
@@ -2283,7 +2269,7 @@ class TestSoupSelector(TreeTest):
markup = '<div class="c1"/><div class="c2"/><div class="c1"/>'
soup = BeautifulSoup(markup, 'html.parser')
selected = soup.select(".c1, .c2")
- self.assertEqual(3, len(selected))
+ assert 3 == len(selected)
# Verify that find_all finds the same elements, though because
# of an implementation detail it finds them in a different
diff --git a/setup.py b/setup.py
index 0bb17eb..04ca112 100644
--- a/setup.py
+++ b/setup.py
@@ -17,10 +17,11 @@ setup(
url="http://www.crummy.com/software/BeautifulSoup/bs4/",
download_url = "http://www.crummy.com/software/BeautifulSoup/bs4/download/",
description="Screen-scraping library",
- python_requires='>3.0.0',
+ python_requires='>=3.6.0',
install_requires=[
"soupsieve >1.2",
],
+ tests_require=['pytest'],
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",