Merge lp:~cjwatson/lazr.restful/py3-response-wrapper into lp:lazr.restful

Proposed by Colin Watson
Status: Merged
Merged at revision: 270
Proposed branch: lp:~cjwatson/lazr.restful/py3-response-wrapper
Merge into: lp:lazr.restful
Diff against target: 50 lines (+18/-6)
1 file modified
src/lazr/restful/testing/webservice.py (+18/-6)
To merge this branch: bzr merge lp:~cjwatson/lazr.restful/py3-response-wrapper
Reviewer Review Type Date Requested Status
Ioana Lasc (community) Approve
Review via email: mp+390377@code.launchpad.net

Commit message

Fix WebServiceResponseWrapper for Python 3.

Description of the change

The reimplementation of http.client.HTTPMessage using email.message.Message in 3.0 removed the headers attribute, so we need to go to some effort to deal with that.

Sorting list responses in the jsonBody method doesn't make sense, so stop doing that.

To post a comment you must log in.
Revision history for this message
Ioana Lasc (ilasc) wrote :

makes sense to me, looks good.

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'src/lazr/restful/testing/webservice.py'
2--- src/lazr/restful/testing/webservice.py 2020-09-02 21:58:55 +0000
3+++ src/lazr/restful/testing/webservice.py 2020-09-07 16:54:40 +0000
4@@ -410,6 +410,7 @@
5 return (config.path_override + '/' + default_version)
6
7
8+@six.python_2_unicode_compatible
9 class WebServiceResponseWrapper(ProxyBase):
10 """A response from the web service with easy access to the JSON body."""
11
12@@ -421,21 +422,32 @@
13 return self.getheader(key, default)
14
15 def __str__(self):
16+ if sys.version_info[0] >= 3:
17+ # Reconstructing the original list of headers seems to involve a
18+ # bit more effort on Python 3.
19+ def normalize(key):
20+ """Normalize an HTTP header name to title case."""
21+ return '-'.join(s.title() for s in key.split('-'))
22+
23+ headers = [
24+ '%s: %s\n' % (normalize(key), value)
25+ for key, value in self.msg.items()]
26+ else:
27+ headers = self.msg.headers
28+ body = self.body.decode('UTF-8')
29 return 'HTTP/1.1 %s %s\n%s\n%s' % (
30- self.status, self.reason, ''.join(self.msg.headers), self.body)
31+ self.status, self.reason, ''.join(headers), body)
32
33 def jsonBody(self):
34 """Return the body of the web service request as a JSON document."""
35+ body = six.ensure_text(self.body)
36 try:
37- json = simplejson.loads(six.ensure_text(self.body))
38- if isinstance(json, list):
39- json = sorted(json)
40- return json
41+ return simplejson.loads(body)
42 except ValueError:
43 # Return a useful ValueError that displays the problematic
44 # string, instead of one that just says the string wasn't
45 # JSON.
46- raise ValueError(self.body)
47+ raise ValueError(body)
48
49
50 @implementer(IWebServiceConfiguration)

Subscribers

People subscribed via source and target branches