"""
HTML parser test cases for etree
"""


import unittest
import tempfile, os, os.path, sys
from io import BytesIO

from .common_imports import etree, html, fileInTestDir
from .common_imports import SillyFileLike, HelperTestCase, write_to_file, needs_libxml


class HtmlParserTestCase(HelperTestCase):
    """HTML parser test cases
    """
    etree = etree

    html_str = b"<html><head><title>test</title></head><body><h1>page title</h1></body></html>"
    html_str_pretty = b"""\
<html>
<head><title>test</title></head>
<body><h1>page title</h1></body>
</html>
"""
    broken_html_str = (
        b"<html><head><title>test</title>"
        b"<body><h1>page title</h3></p></html>")
    uhtml_str = (
        "<html><head><title>test Ã¡</title></head>"
        "<body><h1>page Ã¡ title</h1></body></html>"
    )

    def tearDown(self):
        super().tearDown()
        self.etree.set_default_parser()

    def test_module_HTML(self):
        element = self.etree.HTML(self.html_str)
        self.assertEqual(self.etree.tostring(element, method="html"),
                         self.html_str)

    def test_module_HTML_unicode(self):
        element = self.etree.HTML(self.uhtml_str)
        self.assertEqual(
            self.etree.tostring(element, method="html", encoding='unicode'),
            self.uhtml_str)
        self.assertEqual(element.findtext('.//h1'),
                         "page Ã¡ title")

    @needs_libxml(2, 9, 5)  # not sure, at least 2.9.4 fails
    def test_wide_unicode_html(self):
        if sys.maxunicode < 1114111:
            return  # skip test
        element = self.etree.HTML('<html><body><p>\U00026007</p></body></html>')
        p_text = element.findtext('.//p')
        self.assertEqual(1, len(p_text))
        self.assertEqual('\U00026007',
                         p_text)

    def test_html_ids(self):
        parser = self.etree.HTMLParser(recover=False)
        fromstring = self.etree.fromstring
        html = fromstring('''
            <html><body id="bodyID"><p id="pID"></p></body></html>
        ''', parser=parser)
        self.assertEqual(len(html.xpath('//p[@id="pID"]')), 1)
        self.assertEqual(len(html.findall('.//p[@id="pID"]')), 1)

    def test_html_ids_no_collect_ids(self):
        parser = self.etree.HTMLParser(recover=False, collect_ids=False)
        fromstring = self.etree.fromstring
        html = fromstring('''
            <html><body id="bodyID"><p id="pID"></p></body></html>
        ''', parser=parser)
        self.assertEqual(len(html.xpath('//p[@id="pID"]')), 1)
        self.assertEqual(len(html.findall('.//p[@id="pID"]')), 1)

    def test_module_HTML_pretty_print(self):
        element = self.etree.HTML(self.html_str)
        self.assertEqual(self.etree.tostring(element, method="html", pretty_print=True),
                         self.html_str_pretty)

    def test_module_parse_html_error(self):
        parser = self.etree.HTMLParser(recover=False)
        parse = self.etree.parse
        f = BytesIO(b"<html></body>")
        self.assertRaises(self.etree.XMLSyntaxError,
                          parse, f, parser)

    def test_html_element_name_empty(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement

        el = Element('name')
        self.assertRaises(ValueError, Element, '{}')
        self.assertRaises(ValueError, setattr, el, 'tag', '{}')

        self.assertRaises(ValueError, Element, '{test}')
        self.assertRaises(ValueError, setattr, el, 'tag', '{test}')

    def test_html_element_name_colon(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement

        pname = Element('p:name')
        self.assertEqual(pname.tag, 'p:name')

        pname = Element('{test}p:name')
        self.assertEqual(pname.tag, '{test}p:name')

        pname = Element('name')
        pname.tag = 'p:name'
        self.assertEqual(pname.tag, 'p:name')

    def test_html_element_name_quote(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement

        self.assertRaises(ValueError, Element, 'p"name')
        self.assertRaises(ValueError, Element, "na'me")
        self.assertRaises(ValueError, Element, '{test}"name')
        self.assertRaises(ValueError, Element, "{test}name'")

        el = Element('name')
        self.assertRaises(ValueError, setattr, el, 'tag', "pname'")
        self.assertRaises(ValueError, setattr, el, 'tag', '"pname')
        self.assertEqual(el.tag, "name")

    def test_html_element_name_space(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement

        self.assertRaises(ValueError, Element, ' name ')
        self.assertRaises(ValueError, Element, 'na me')
        self.assertRaises(ValueError, Element, '{test} name')

        el = Element('name')
        self.assertRaises(ValueError, setattr, el, 'tag', ' name ')
        self.assertEqual(el.tag, "name")

    def test_html_subelement_name_empty(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement

        SubElement = self.etree.SubElement

        el = Element('name')
        self.assertRaises(ValueError, SubElement, el, '{}')
        self.assertRaises(ValueError, SubElement, el, '{test}')

    def test_html_subelement_name_colon(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement
        SubElement = self.etree.SubElement

        el = Element('name')
        pname = SubElement(el, 'p:name')
        self.assertEqual(pname.tag, 'p:name')

        pname = SubElement(el, '{test}p:name')
        self.assertEqual(pname.tag, '{test}p:name')

    def test_html_subelement_name_quote(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement
        SubElement = self.etree.SubElement

        el = Element('name')
        self.assertRaises(ValueError, SubElement, el, "name'")
        self.assertRaises(ValueError, SubElement, el, 'na"me')
        self.assertRaises(ValueError, SubElement, el, "{test}na'me")
        self.assertRaises(ValueError, SubElement, el, '{test}"name')

    def test_html_subelement_name_space(self):
        parser = self.etree.HTMLParser()
        Element = parser.makeelement
        SubElement = self.etree.SubElement

        el = Element('name')
        self.assertRaises(ValueError, SubElement, el, ' name ')
        self.assertRaises(ValueError, SubElement, el, 'na me')
        self.assertRaises(ValueError, SubElement, el, '{test} name')

    def test_module_parse_html_norecover(self):
        parser = self.etree.HTMLParser(recover=False)
        parse = self.etree.parse
        f = BytesIO(self.broken_html_str)
        self.assertRaises(self.etree.XMLSyntaxError,
                          parse, f, parser)

    def test_module_parse_html_default_doctype(self):
        parser = self.etree.HTMLParser(default_doctype=False)
        d = html.fromstring('<!DOCTYPE html><h1>S</h1></html>', parser=parser)
        self.assertEqual(d.getroottree().docinfo.doctype, '<!DOCTYPE html>')

        d = html.fromstring('<html><h1>S</h1></html>', parser=parser)
        self.assertEqual(d.getroottree().docinfo.doctype, '')

    def test_parse_encoding_8bit_explicit(self):
        text = 'Søk på nettet'
        html_latin1 = ('<p>%s</p>' % text).encode('iso-8859-1')

        tree = self.etree.parse(
            BytesIO(html_latin1),
            self.etree.HTMLParser(encoding="iso-8859-1"))
        p = tree.find(".//p")
        self.assertEqual(p.text, text)

    def test_parse_encoding_8bit_override(self):
        text = 'Søk på nettet'
        wrong_head = '''
        <head>
          <meta http-equiv="Content-Type"
                content="text/html; charset=UTF-8" />
        </head>'''
        html_latin1 = ('<html>%s<body><p>%s</p></body></html>' % (wrong_head,
                                                                        text)
                      ).encode('iso-8859-1')

        self.assertRaises(self.etree.ParseError,
                          self.etree.parse,
                          BytesIO(html_latin1))

        tree = self.etree.parse(
            BytesIO(html_latin1),
            self.etree.HTMLParser(encoding="iso-8859-1"))
        p = tree.find(".//p")
        self.assertEqual(p.text, text)

    def test_module_HTML_broken(self):
        element = self.etree.HTML(self.broken_html_str)
        self.assertEqual(self.etree.tostring(element, method="html"),
                         self.html_str)

    def test_module_HTML_script(self):
        # by default, libxml2 generates CDATA nodes for <script> content
        html = b'<html><head><style>foo</style><script>too</script></head></html>'
        element = self.etree.HTML(html)
        self.assertEqual(element[0][0].tag, "style")
        self.assertEqual(element[0][0].text, "foo")

        self.assertEqual(element[0][1].tag, "script")
        self.assertEqual(element[0][1].text, "too")

    @needs_libxml(2, 10, 0)
    def test_module_HTML_cdata_ignored(self):
        # libxml2 discards CDATA "content" since HTML does not know them.
        import warnings
        html = b'<html><body><!CDATA[[foo]]></head></html>'
        element = self.etree.HTML(html)
        self.assertEqual(element[0].tag, "body")
        self.assertFalse(element[0].text)

        with warnings.catch_warnings(record=True) as warnings_seen:
            warnings.simplefilter("always")
            parser = self.etree.HTMLParser(strip_cdata=True)
        self.assertTrue(warnings_seen)

        element = self.etree.HTML(html, parser)
        self.assertEqual(element[0].tag, "body")
        self.assertFalse(element[0].text)

        with warnings.catch_warnings(record=True) as warnings_seen:
            warnings.simplefilter("always")
            parser = self.etree.HTMLParser(strip_cdata=False)
        self.assertTrue(warnings_seen)

        element = self.etree.HTML(html, parser)
        self.assertEqual(element[0].tag, "body")
        self.assertFalse(element[0].text)

    def test_module_HTML_access(self):
        element = self.etree.HTML(self.html_str)
        self.assertEqual(element[0][0].tag, 'title')

    def test_module_parse_html(self):
        parser = self.etree.HTMLParser()
        filename = tempfile.mktemp(suffix=".html")
        write_to_file(filename, self.html_str, 'wb')
        try:
            with open(filename, 'rb') as f:
                tree = self.etree.parse(f, parser)
            self.assertEqual(self.etree.tostring(tree.getroot(), method="html"),
                             self.html_str)
        finally:
            os.remove(filename)

    def test_module_parse_html_filelike(self):
        parser = self.etree.HTMLParser()
        f = SillyFileLike(self.html_str)
        tree = self.etree.parse(f, parser)
        html = self.etree.tostring(tree.getroot(),
                                   method="html", encoding='UTF-8')
        self.assertEqual(html, self.html_str)

##     def test_module_parse_html_filelike_unicode(self):
##         parser = self.etree.HTMLParser()
##         f = SillyFileLike(self.uhtml_str)
##         tree = self.etree.parse(f, parser)
##         html = self.etree.tostring(tree.getroot(), encoding='UTF-8')
##         self.assertEqual(unicode(html, 'UTF-8'), self.uhtml_str)

    def test_html_file_error(self):
        parser = self.etree.HTMLParser()
        parse = self.etree.parse
        self.assertRaises(IOError,
                          parse, "__some_hopefully_nonexisting_file__.html",
                          parser)

    def test_default_parser_HTML_broken(self):
        self.assertRaises(self.etree.XMLSyntaxError,
                          self.etree.parse, BytesIO(self.broken_html_str))

        self.etree.set_default_parser( self.etree.HTMLParser() )

        tree = self.etree.parse(BytesIO(self.broken_html_str))
        self.assertEqual(self.etree.tostring(tree.getroot(), method="html"),
                         self.html_str)

        self.etree.set_default_parser()

        self.assertRaises(self.etree.XMLSyntaxError,
                          self.etree.parse, BytesIO(self.broken_html_str))

    def test_html_iterparse(self):
        iterparse = self.etree.iterparse
        f = BytesIO(b'<html><head><title>TITLE</title><body><p>P</p></body></html>')

        iterator = iterparse(f, html=True)
        self.assertEqual(None, iterator.root)

        events = list(iterator)
        root = iterator.root
        self.assertTrue(root is not None)
        self.assertEqual(
            [('end', root[0][0]), ('end', root[0]), ('end', root[1][0]),
             ('end', root[1]), ('end', root)],
            events)

    def test_html_iterparse_tag(self):
        iterparse = self.etree.iterparse
        f = BytesIO(b'<html><head><title>TITLE</title><body><p>P</p></body></html>')

        iterator = iterparse(f, html=True, tag=["p", "title"])
        self.assertEqual(None, iterator.root)

        events = list(iterator)
        root = iterator.root
        self.assertTrue(root is not None)
        self.assertEqual(
            [('end', root[0][0]), ('end', root[1][0])],
            events)

    def test_html_iterparse_stop_short(self):
        iterparse = self.etree.iterparse
        f = BytesIO(b'<html><head><title>TITLE</title><body><p>P</p></body></html>')

        iterator = iterparse(f, html=True)
        self.assertEqual(None, iterator.root)

        event, element = next(iterator)
        self.assertEqual('end', event)
        self.assertEqual('title', element.tag)
        self.assertEqual(None, iterator.root)
        del element

        event, element = next(iterator)
        self.assertEqual('end', event)
        self.assertEqual('head', element.tag)
        self.assertEqual(None, iterator.root)
        del element
        del iterator

    def test_html_iterparse_broken(self):
        iterparse = self.etree.iterparse
        f = BytesIO(b'<head><title>TEST></title></head><p>P<br></div>')

        iterator = iterparse(f, html=True)
        self.assertEqual(None, iterator.root)

        events = list(iterator)
        root = iterator.root
        self.assertTrue(root is not None)
        self.assertEqual('html', root.tag)
        self.assertEqual('head', root[0].tag)
        self.assertEqual('body', root[1].tag)
        self.assertEqual('p', root[1][0].tag)
        self.assertEqual('br', root[1][0][0].tag)
        self.assertEqual(
            [('end', root[0][0]), ('end', root[0]), ('end', root[1][0][0]),
             ('end', root[1][0]), ('end', root[1]), ('end', root)],
            events)

    def test_html_iterparse_broken_meta(self):
        # Broken HTML with a misplaced tag before the real html tag.
        body = '''
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <html>
            <head></head>
            <body>
            </body>
        </html>
        '''
        PARSE_TAGS = {'meta', 'html', 'body'}

        iterator = etree.iterparse(
            BytesIO(body.encode()), events=('start', 'end'), html=True, recover=True, tag=PARSE_TAGS)
        parse_events = list(iterator)

    def test_html_iterparse_broken_no_recover(self):
        iterparse = self.etree.iterparse
        f = BytesIO(b'<p>P<br></div>')
        iterator = iterparse(f, html=True, recover=False)
        self.assertRaises(self.etree.XMLSyntaxError, list, iterator)

    def test_html_iterparse_file(self):
        iterparse = self.etree.iterparse
        iterator = iterparse(fileInTestDir("shakespeare.html"),
                             html=True)

        self.assertEqual(None, iterator.root)
        events = list(iterator)
        root = iterator.root
        self.assertTrue(root is not None)
        self.assertEqual(249, len(events))
        self.assertFalse(
            [event for (event, element) in events if event != 'end'])

    def test_html_iterparse_start(self):
        iterparse = self.etree.iterparse
        f = BytesIO(b'<html><head><title>TITLE</title><body><p>P</p></body></html>')

        iterator = iterparse(f, html=True, events=('start',))
        self.assertEqual(None, iterator.root)

        events = list(iterator)
        root = iterator.root
        self.assertNotEqual(None, root)
        self.assertEqual(
            [('start', root), ('start', root[0]), ('start', root[0][0]),
                ('start', root[1]), ('start', root[1][0])],
            events)

    def test_html_iterparse_cdata(self):
        import warnings

        iterparse = self.etree.iterparse
        f = BytesIO(b'<html><body><![CDATA[ foo ]]></body></html>')

        with warnings.catch_warnings(record=True) as warned_novalue:
            warnings.simplefilter("always")
            iterator = iterparse(f, html=True, events=('start', ))
        self.assertFalse(warned_novalue)

        events = list(iterator)
        root = iterator.root
        self.assertNotEqual(None, root)
        self.assertEqual(('start', root), events[0])

        f.seek(0)
        with warnings.catch_warnings(record=True) as warned_true:
            warnings.simplefilter("always")
            iterator = iterparse(
                f, html=True, events=('start', ), strip_cdata=True)
        self.assertFalse(warned_true)

        events = list(iterator)
        root = iterator.root
        self.assertNotEqual(None, root)
        self.assertEqual(('start', root), events[0])

        f.seek(0)
        with warnings.catch_warnings(record=True) as warned_false:
            warnings.simplefilter("always")
            iterator = iterparse(
                f, html=True, events=('start', ), strip_cdata=False)
        self.assertFalse(warned_false)

        events = list(iterator)
        root = iterator.root
        self.assertNotEqual(None, root)
        self.assertEqual(('start', root), events[0])

    def test_html_feed_parser(self):
        parser = self.etree.HTMLParser()
        parser.feed("<html><body></")
        parser.feed("body></html>")
        root = parser.close()

        self.assertEqual('html', root.tag)
        # test that we find all names in the parser dict
        self.assertEqual([root], list(root.iter('html')))
        self.assertEqual([root[0]], list(root.iter('body')))

    def test_html_feed_parser_chunky(self):
        parser = self.etree.HTMLParser()
        parser.feed("<htm")
        parser.feed("l><body")
        parser.feed("><")
        parser.feed("p><")
        parser.feed("strong")
        parser.feed(">some ")
        parser.feed("text</strong></p><")
        parser.feed("/body></html>")
        root = parser.close()

        self.assertEqual('html', root.tag)
        # test that we find all names in the parser dict
        self.assertEqual([root], list(root.iter('html')))
        self.assertEqual([root[0]], list(root.iter('body')))
        self.assertEqual([root[0][0]], list(root.iter('p')))
        self.assertEqual([root[0][0][0]], list(root.iter('strong')))

    def test_html_feed_parser_more_tags(self):
        parser = self.etree.HTMLParser()
        parser.feed('<html><head>')
        parser.feed('<title>TITLE</title><body><p>P</p></body><')
        parser.feed("/html>")
        root = parser.close()

        self.assertEqual('html', root.tag)
        # test that we find all names in the parser dict
        self.assertEqual([root], list(root.iter('html')))
        self.assertEqual([root[0]], list(root.iter('head')))
        self.assertEqual([root[0][0]], list(root.iter('title')))
        self.assertEqual([root[1]], list(root.iter('body')))
        self.assertEqual([root[1][0]], list(root.iter('p')))

    def test_html_pull_parser_chunky(self):
        # See https://bugs.launchpad.net/lxml/+bug/2058828
        if self.etree.LIBXML_VERSION < (2, 11):
            return
        parser = self.etree.HTMLPullParser()
        parser.feed(b'<html><body><a href="2011-03-13_')
        parser.feed(b'135411/">2011-03-13_135411/</a></body></html>')

        events = parser.read_events()
        self.assertEqual(
            ['a', 'body', 'html'],
            [el.tag for _, el in events])
        root = parser.close()

        self.assertEqual('html', root.tag)
        self.assertEqual('body', root[0].tag)
        self.assertEqual('a', root[0][0].tag)
        self.assertEqual('2011-03-13_135411/', root[0][0].get("href"))

    def test_html_parser_target_tag(self):
        assertFalse  = self.assertFalse
        events = []
        class Target:
            def start(self, tag, attrib):
                events.append(("start", tag))
                assertFalse(attrib)
            def end(self, tag):
                events.append(("end", tag))
            def close(self):
                return "DONE"

        parser = self.etree.HTMLParser(target=Target())

        parser.feed("<html><body></body></html>")
        done = parser.close()

        self.assertEqual("DONE", done)
        self.assertEqual([
            ("start", "html"), ("start", "body"),
            ("end", "body"), ("end", "html")], events)

    def test_html_parser_target_doctype_empty(self):
        assertFalse  = self.assertFalse
        events = []
        class Target:
            def start(self, tag, attrib):
                events.append(("start", tag))
                assertFalse(attrib)
            def end(self, tag):
                events.append(("end", tag))
            def doctype(self, *args):
                events.append(("doctype", args))
            def close(self):
                return "DONE"

        parser = self.etree.HTMLParser(target=Target())
        parser.feed("<!DOCTYPE><html><body></body></html>")
        done = parser.close()

        self.assertEqual("DONE", done)
        self.assertEqual([
            ("doctype", (None, None, None)),
            ("start", "html"), ("start", "body"),
            ("end", "body"), ("end", "html")], events)

    def test_html_parser_target_doctype_html(self):
        assertFalse  = self.assertFalse
        events = []
        class Target:
            def start(self, tag, attrib):
                events.append(("start", tag))
                assertFalse(attrib)
            def end(self, tag):
                events.append(("end", tag))
            def doctype(self, *args):
                events.append(("doctype", args))
            def close(self):
                return "DONE"

        parser = self.etree.HTMLParser(target=Target())
        parser.feed("<!DOCTYPE html><html><body></body></html>")
        done = parser.close()

        self.assertEqual("DONE", done)
        self.assertEqual([
            ("doctype", ("html", None, None)),
            ("start", "html"), ("start", "body"),
            ("end", "body"), ("end", "html")], events)

    def test_html_parser_target_doctype_html_full(self):
        assertFalse  = self.assertFalse
        events = []
        class Target:
            def start(self, tag, attrib):
                events.append(("start", tag))
                assertFalse(attrib)
            def end(self, tag):
                events.append(("end", tag))
            def doctype(self, *args):
                events.append(("doctype", args))
            def close(self):
                return "DONE"

        parser = self.etree.HTMLParser(target=Target())
        parser.feed('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "sys.dtd">'
                    '<html><body></body></html>')
        done = parser.close()

        self.assertEqual("DONE", done)
        self.assertEqual([
            ("doctype", ("html", "-//W3C//DTD HTML 4.01//EN", "sys.dtd")),
            ("start", "html"), ("start", "body"),
            ("end", "body"), ("end", "html")], events)

    def test_html_parser_target_exceptions(self):
        events = []
        class Target:
            def start(self, tag, attrib):
                events.append(("start", tag))
                raise ValueError("START")
            def end(self, tag):
                events.append(("end", tag))
                raise TypeError("END")
            def close(self):
                return "DONE"

        parser = self.etree.HTMLParser(target=Target())
        try:
            parser.feed('<html><body>')
            parser.feed('</body></html>')
        except ValueError as exc:
            assert "START" in str(exc)
        except TypeError as exc:
            assert "END" in str(exc)
            self.assertTrue(False, "wrong exception raised")
        else:
            self.assertTrue(False, "no exception raised")

        self.assertTrue(("start", "html") in events, events)
        self.assertTrue(("end", "html") not in events, events)

    def test_html_fromstring_target_exceptions(self):
        events = []
        class Target:
            def start(self, tag, attrib):
                events.append(("start", tag))
                raise ValueError("START")
            def end(self, tag):
                events.append(("end", tag))
                raise TypeError("END")
            def close(self):
                return "DONE"

        parser = self.etree.HTMLParser(target=Target())
        try:
            self.etree.fromstring('<html><body></body></html>', parser)
        except ValueError as exc:
            assert "START" in str(exc), str(exc)
        except TypeError as exc:
            assert "END" in str(exc), str(exc)
            self.assertTrue(False, "wrong exception raised")
        else:
            self.assertTrue(False, "no exception raised")

        self.assertTrue(("start", "html") in events, events)
        self.assertTrue(("end", "html") not in events, events)

    def test_set_decl_html(self):
        doc = html.Element('html').getroottree()
        doc.docinfo.public_id = "-//W3C//DTD XHTML 1.0 Strict//EN"
        doc.docinfo.system_url = \
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
        self.assertEqual(doc.docinfo.doctype,
                         '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
        self.assertEqual(self.etree.tostring(doc),
                         b'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"></html>''')

    def test_html5_doctype(self):
        # document type declaration with neither public if nor system url
        doc = html.Element('html').getroottree()
        doc.docinfo.public_id = None
        doc.docinfo.system_url = None
        self.assertEqual(doc.docinfo.doctype,
                         '<!DOCTYPE html>')
        self.assertTrue(doc.docinfo.public_id is None)
        self.assertEqual(self.etree.tostring(doc),
                         b'<!DOCTYPE html>\n<html/>')

    def test_ietf_decl(self):
        # legacy declaration with public id, no system url
        doc = html.Element('html').getroottree()
        doc.docinfo.public_id = '-//IETF//DTD HTML//EN'
        doc.docinfo.system_url = None
        self.assertEqual(doc.docinfo.doctype,
                         '<!DOCTYPE html PUBLIC "-//IETF//DTD HTML//EN">')
        self.assertEqual(self.etree.tostring(doc),
                         b'<!DOCTYPE html PUBLIC "-//IETF//DTD HTML//EN">\n<html/>')

    def test_boolean_attribute(self):
        # ability to serialize boolean attribute by setting value to None
        form = html.Element('form')
        form.set('novalidate', None)
        self.assertEqual(html.tostring(form),
                         b'<form novalidate></form>')
        form.set('custom')
        self.assertEqual(html.tostring(form),
                         b'<form novalidate custom></form>')

    def test_boolean_attribute_round_trip(self):
        # ability to pass boolean attributes unmodified
        fragment = '<tag attribute></tag>'
        self.assertEqual(html.tostring(html.fragment_fromstring(fragment)),
                         fragment.encode('utf-8'))

    def test_boolean_attribute_xml_adds_empty_string(self):
        # html serialized as xml converts boolean attributes to empty strings
        fragment = '<tag attribute></tag>'
        self.assertEqual(self.etree.tostring(html.fragment_fromstring(fragment)),
                         b'<tag attribute=""/>')

    def test_xhtml_as_html_as_xml(self):
        # parse XHTML as HTML, serialise as XML
        # See https://bugs.launchpad.net/lxml/+bug/1965070
        xhtml = (
            b'<?xml version="1.0" encoding="UTF-8"?>'
            b'<html xmlns="http://www.w3.org/1999/xhtml"></html>'
        )
        root = html.fromstring(xhtml)
        result = etree.tostring(root)
        self.assertEqual(result, b'<html xmlns="http://www.w3.org/1999/xhtml"/>')

        # Adding an XHTML doctype makes libxml2 add the namespace, which wasn't parsed as such by the HTML parser.
        """
        xhtml = (
            b'<?xml version="1.0" encoding="UTF-8"?>'
            b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
            b'<html xmlns="http://www.w3.org/1999/xhtml"></html>'
        )
        root = html.fromstring(xhtml)
        result = etree.tostring(root)
        self.assertEqual(result, b'<html xmlns="http://www.w3.org/1999/xhtml"/>')
        """


def test_suite():
    suite = unittest.TestSuite()
    suite.addTests([unittest.defaultTestLoader.loadTestsFromTestCase(HtmlParserTestCase)])
    return suite


if __name__ == '__main__':
    print('to test use test.py %s' % __file__)
