From c742576c105f40fc8b754fcae56fee4aa35840a3 Mon Sep 17 00:00:00 2001
From: Stefan Behnel <stefan_ml@behnel.de>
Date: Tue, 19 Jul 2022 08:25:20 +0200
Subject: [PATCH] Work around libxml2 bug in affected versions that failed to
 reset the namespace count in the parser context.

See https://gitlab.gnome.org/GNOME/libxml2/-/issues/378
---
 src/lxml/includes/xmlparser.pxd | 1 +
 src/lxml/parser.pxi             | 3 +++
 src/lxml/tests/test_etree.py    | 3 +--
 3 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/lxml/includes/xmlparser.pxd b/src/lxml/includes/xmlparser.pxd
index a196e34..45acfc8 100644
--- a/src/lxml/includes/xmlparser.pxd
+++ b/src/lxml/includes/xmlparser.pxd
@@ -144,6 +144,7 @@ cdef extern from "libxml/parser.h":
         void* userData
         int* spaceTab
         int spaceMax
+        int nsNr
         bint html
         bint progressive
         int inSubset
diff --git a/src/lxml/parser.pxi b/src/lxml/parser.pxi
index f5baf29..f0c8c6b 100644
--- a/src/lxml/parser.pxi
+++ b/src/lxml/parser.pxi
@@ -569,6 +569,9 @@ cdef class _ParserContext(_ResolverContext):
                 self._c_ctxt.disableSAX = 0 # work around bug in libxml2
             else:
                 xmlparser.xmlClearParserCtxt(self._c_ctxt)
+                # work around bug in libxml2 [2.9.10 .. 2.9.14]:
+                # https://gitlab.gnome.org/GNOME/libxml2/-/issues/378
+                self._c_ctxt.nsNr = 0
 
     cdef int prepare(self, bint set_document_loader=True) except -1:
         cdef int result
diff --git a/src/lxml/tests/test_etree.py b/src/lxml/tests/test_etree.py
index 8bf82c0..0339796 100644
--- a/src/lxml/tests/test_etree.py
+++ b/src/lxml/tests/test_etree.py
@@ -1491,8 +1491,7 @@ class ETreeOnlyTestCase(HelperTestCase):
             # This would be the expected result, because there was no namespace
             pass
         else:
-            # This is a bug in libxml2
-            assert not ns, repr(ns)
+            assert False, "Found unexpected namespace '%s'" % ns
 
     def test_itertext_comment_pi(self):
         # https://bugs.launchpad.net/lxml/+bug/1844674
-- 
1.8.3.1

