Webob needs body to calc Content-Length (bug 1016171)
- Refactored render_response() and added relevant tests Change-Id: I121e8cc641fe11a036106cbfd206f0aa1f6da560
This commit is contained in:
parent
a7d73d2c4b
commit
4b97716e4a
@ -490,17 +490,22 @@ class ExtensionRouter(Router):
|
||||
return _factory
|
||||
|
||||
|
||||
def render_response(body=None, status=(200, 'OK'), headers=None):
|
||||
def render_response(body=None, status=None, headers=None):
|
||||
"""Forms a WSGI response."""
|
||||
resp = webob.Response()
|
||||
resp.status = '%s %s' % status
|
||||
resp.headerlist = headers or [('Content-Type', 'application/json'),
|
||||
('Vary', 'X-Auth-Token')]
|
||||
headers = headers or []
|
||||
headers.append(('Vary', 'X-Auth-Token'))
|
||||
|
||||
if body is not None:
|
||||
resp.body = jsonutils.dumps(body, cls=utils.SmarterEncoder)
|
||||
if body is None:
|
||||
body = ''
|
||||
status = status or (204, 'No Content')
|
||||
else:
|
||||
body = jsonutils.dumps(body, cls=utils.SmarterEncoder)
|
||||
headers.append(('Content-Type', 'application/json'))
|
||||
status = status or (200, 'OK')
|
||||
|
||||
return resp
|
||||
return webob.Response(body=body,
|
||||
status='%s %s' % status,
|
||||
headerlist=headers)
|
||||
|
||||
|
||||
def render_exception(error):
|
||||
|
@ -47,3 +47,32 @@ class ApplicationTest(test.TestCase):
|
||||
req = self._make_request(url='/?1=2')
|
||||
resp = req.get_response(app)
|
||||
self.assertEqual(jsonutils.loads(resp.body), {'1': '2'})
|
||||
|
||||
def test_render_response(self):
|
||||
data = {'attribute': 'value'}
|
||||
body = '{"attribute": "value"}'
|
||||
|
||||
resp = wsgi.render_response(body=data)
|
||||
self.assertEqual(resp.status, '200 OK')
|
||||
self.assertEqual(resp.status_int, 200)
|
||||
self.assertEqual(resp.body, body)
|
||||
self.assertEqual(resp.headers.get('Vary'), 'X-Auth-Token')
|
||||
self.assertEqual(resp.headers.get('Content-Length'), str(len(body)))
|
||||
|
||||
def test_render_response_custom_status(self):
|
||||
resp = wsgi.render_response(status=(501, 'Not Implemented'))
|
||||
self.assertEqual(resp.status, '501 Not Implemented')
|
||||
self.assertEqual(resp.status_int, 501)
|
||||
|
||||
def test_render_response_custom_headers(self):
|
||||
resp = wsgi.render_response(headers=[('Custom-Header', 'Some-Value')])
|
||||
self.assertEqual(resp.headers.get('Custom-Header'), 'Some-Value')
|
||||
self.assertEqual(resp.headers.get('Vary'), 'X-Auth-Token')
|
||||
|
||||
def test_render_response_no_body(self):
|
||||
resp = wsgi.render_response()
|
||||
self.assertEqual(resp.status, '204 No Content')
|
||||
self.assertEqual(resp.status_int, 204)
|
||||
self.assertEqual(resp.body, '')
|
||||
self.assertEqual(resp.headers.get('Content-Length'), '0')
|
||||
self.assertEqual(resp.headers.get('Content-Type'), None)
|
||||
|
Loading…
x
Reference in New Issue
Block a user