summaryrefslogtreecommitdiff
path: root/bs4/tests/test_formatter.py
diff options
context:
space:
mode:
authorLeonard Richardson <leonardr@segfault.org>2021-12-21 12:57:04 -0500
committerLeonard Richardson <leonardr@segfault.org>2021-12-21 12:57:04 -0500
commit3ac8524a1263f170ae0a9096d255d3e28aa76340 (patch)
treee6aab155135f553f3043a425dcf8e61884091919 /bs4/tests/test_formatter.py
parent792a9e485e1b110534345a4f96fd65099879421e (diff)
It's now possible to customize the way output is indented by
providing a value for the 'indent' argument to the Formatter constructor. The 'indent' argument works very similarly to the argument of the same name in the Python standard library's json.dump() method. [bug=1955497]
Diffstat (limited to 'bs4/tests/test_formatter.py')
-rw-r--r--bs4/tests/test_formatter.py38
1 files changed, 38 insertions, 0 deletions
diff --git a/bs4/tests/test_formatter.py b/bs4/tests/test_formatter.py
index 12327ef..84d4e3b 100644
--- a/bs4/tests/test_formatter.py
+++ b/bs4/tests/test_formatter.py
@@ -1,3 +1,5 @@
+import pytest
+
from bs4.element import Tag
from bs4.formatter import (
Formatter,
@@ -24,6 +26,8 @@ class TestFormatter(SoupTest):
# normally happen.
tag.attrs = None
assert [] == formatter.attributes(tag)
+
+ assert ' ' == formatter.indent
def test_sort_attributes(self):
# Test the ability to override Formatter.attributes() to,
@@ -73,3 +77,37 @@ class TestFormatter(SoupTest):
assert b'<option selected=""></option>' == soup.option.encode(formatter='html')
assert b'<option selected></option>' == soup.option.encode(formatter='html5')
+ @pytest.mark.parametrize(
+ "indent,expect",
+ [
+ (None, '<a>\n<b>\ntext\n</b>\n</a>'),
+ (-1, '<a>\n<b>\ntext\n</b>\n</a>'),
+ (0, '<a>\n<b>\ntext\n</b>\n</a>'),
+ ("", '<a>\n<b>\ntext\n</b>\n</a>'),
+
+ (1, '<a>\n <b>\n text\n </b>\n</a>'),
+ (2, '<a>\n <b>\n text\n </b>\n</a>'),
+
+ ("\t", '<a>\n\t<b>\n\t\ttext\n\t</b>\n</a>'),
+ ('abc', '<a>\nabc<b>\nabcabctext\nabc</b>\n</a>'),
+
+ # Some invalid inputs -- the default behavior is used.
+ (object(), '<a>\n <b>\n text\n </b>\n</a>'),
+ (b'bytes', '<a>\n <b>\n text\n </b>\n</a>'),
+ ]
+ )
+ def test_indent(self, indent, expect):
+ # Pretty-print a tree with a Formatter set to
+ # indent in a certain way and verify the results.
+ soup = self.soup("<a><b>text</b></a>")
+ formatter = Formatter(indent=indent)
+ assert soup.prettify(formatter=formatter) == expect
+
+ # Pretty-printing only happens with prettify(), not
+ # encode().
+ assert soup.encode(formatter=formatter) != expect
+
+ def test_default_indent_value(self):
+ formatter = Formatter()
+ assert formatter.indent == ' '
+