Skip to content

Commit

Permalink
Webob needs body to calc Content-Length (bug 1016171)
Browse files Browse the repository at this point in the history
- Refactored render_response() and added relevant tests

Change-Id: I121e8cc641fe11a036106cbfd206f0aa1f6da560
  • Loading branch information
dolph committed Jul 13, 2012
1 parent a7d73d2 commit 4b97716
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 10 deletions.
25 changes: 15 additions & 10 deletions keystone/common/wsgi.py
Expand Up @@ -490,17 +490,22 @@ def _factory(app):
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')]

if body is not None:
resp.body = jsonutils.dumps(body, cls=utils.SmarterEncoder)

return resp
headers = headers or []
headers.append(('Vary', 'X-Auth-Token'))

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 webob.Response(body=body,
status='%s %s' % status,
headerlist=headers)


def render_exception(error):
Expand Down
29 changes: 29 additions & 0 deletions tests/test_wsgi.py
Expand Up @@ -47,3 +47,32 @@ def index(self, context):
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)

0 comments on commit 4b97716

Please sign in to comment.