2 from lxml.tests.common_imports import make_doctest
5 from lxml.html.clean import Cleaner, clean_html
8 class CleanerTest(unittest.TestCase):
9 def test_allow_tags(self):
18 <td>hello</td><td>world</td>
21 <td>hello</td><td>world</td>
29 html_root = lxml.html.document_fromstring(html)
31 remove_unknown_tags = False,
32 allow_tags = ['table', 'tr', 'td'])
33 result = cleaner.clean_html(html_root)
35 self.assertEqual(12-5+1, len(list(result.iter())))
37 def test_safe_attrs_included(self):
38 html = """<p><span style="color: #00ffff;">Cyan</span></p>"""
40 safe_attrs=set(lxml.html.defs.safe_attrs)
41 safe_attrs.add('style')
45 safe_attrs=safe_attrs)
46 result = cleaner.clean_html(html)
48 self.assertEqual(html, result)
50 def test_safe_attrs_excluded(self):
51 html = """<p><span style="color: #00ffff;">Cyan</span></p>"""
52 expected = """<p><span>Cyan</span></p>"""
58 safe_attrs=safe_attrs)
59 result = cleaner.clean_html(html)
61 self.assertEqual(expected, result)
63 def test_clean_invalid_root_tag(self):
64 # only testing that cleaning with invalid root tags works at all
65 s = lxml.html.fromstring('parent <invalid tag>child</another>')
66 self.assertEqual('parent child', clean_html(s).text_content())
68 s = lxml.html.fromstring('<invalid tag>child</another>')
69 self.assertEqual('child', clean_html(s).text_content())
73 suite = unittest.TestSuite()
74 suite.addTests([make_doctest('test_clean.txt')])
75 suite.addTests([make_doctest('test_clean_embed.txt')])
76 suite.addTests(unittest.makeSuite(CleanerTest))