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):