From dae835149088a728bbfc491cf3ecfa7260cb77d6 Mon Sep 17 00:00:00 2001 From: Gael Pasgrimaud Date: Fri, 5 Jul 2024 15:23:20 +0200 Subject: [PATCH] add a Response.PyQuery method --- CHANGELOG.rst | 4 +++- tests/test_response.py | 9 +++++++++ webtest/response.py | 21 +++++++++++++++++++-- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2e2cd9e..5b09f7c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,7 +10,9 @@ News - Allows the TestResponse to follow customised onclick buttons -- PyQuery object now use the html parser +- Response.pyquery object now use the html parser. + +- You can use the Response.PyQuery method to customize pyquery init. - Various docs / testing improvments diff --git a/tests/test_response.py b/tests/test_response.py index 5504173..5ad1583 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -304,6 +304,15 @@ def test_lxml_attribute_with_encoding_declaration(self): print(resp.body) print(resp.lxml) + def test_pyquery(self): + app = webtest.TestApp(svg_application) + resp = app.get('/') + self.assertRaises(ValueError, lambda: resp.pyquery) + pq = resp.PyQuery(parser='xml', remove_namespaces=True) + assert len(pq('svg')) == 1 + pq = resp.PyQuery(parser='xml') + assert len(pq('svg')) == 0 + def test_html_attribute(self): app = webtest.TestApp(links_app) res = app.post('/') diff --git a/webtest/response.py b/webtest/response.py index c69cad7..8498339 100644 --- a/webtest/response.py +++ b/webtest/response.py @@ -1,5 +1,4 @@ import re -from json import loads from webtest import forms from webtest import utils @@ -494,6 +493,16 @@ def pyquery(self): Only works with HTML and XML responses; other content-types raise AttributeError. + """ + return self.PyQuery(parser='html') + + def PyQuery(self, **kwargs): + """ + Same as `pyquery` but allow to pass arguments to initialize the + `PyQuery` instance:: + + pq = resp.PyQuery(parser='xml', remove_namespaces=True) + """ if 'html' not in self.content_type and 'xml' not in self.content_type: raise AttributeError( @@ -504,7 +513,15 @@ def pyquery(self): except ImportError: # pragma: no cover raise ImportError( "You must have PyQuery installed to use response.pyquery") - d = PyQuery(self.testbody, parser='html') + remove_namespaces = kwargs.pop('remove_namespaces', False) + parser = kwargs.get('parser', 'html') + if parser == 'xml': + body = self.body + else: + body = self.testbody + d = PyQuery(body, **kwargs) + if remove_namespaces: + d.remove_namespaces() return d def showbrowser(self):