Skip to content

Commit

Permalink
add a Response.PyQuery method
Browse files Browse the repository at this point in the history
  • Loading branch information
gawel committed Jul 5, 2024
1 parent 576de9b commit dae8351
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 9 additions & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -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('/')
Expand Down
21 changes: 19 additions & 2 deletions webtest/response.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import re
from json import loads

from webtest import forms
from webtest import utils
Expand Down Expand Up @@ -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(
Expand All @@ -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):
Expand Down

0 comments on commit dae8351

Please sign in to comment.