Change parsing of headers to accept 'True', 'on', 1 for boolean truth values.

This commit is contained in:
jaypipes@gmail.com 2011-04-11 20:44:06 -04:00
parent 74e8627738
commit 788296100d
2 changed files with 43 additions and 2 deletions

View File

@ -91,12 +91,27 @@ def get_image_meta_from_headers(response):
if 'size' in result:
result['size'] = int(result['size'])
if 'is_public' in result:
result['is_public'] = (result['is_public'] == 'True')
result['is_public'] = bool_from_header_value(result['is_public'])
if 'deleted' in result:
result['deleted'] = (result['deleted'] == 'True')
result['deleted'] = bool_from_header_value(result['deleted'])
return result
def bool_from_header_value(value):
"""
Returns True if value is any of ('True', 'On', '1'),
case-insensitive
"""
if type(value) == type(bool):
return value
elif isinstance(value, (basestring, unicode)):
if str(value).lower() in ('true', 'on', '1'):
return True
elif type(value) == type(int):
return bool(value)
return False
def has_body(req):
"""
Returns whether a Webob.Request object will possess an entity body.

View File

@ -65,3 +65,29 @@ class TestUtils(unittest.TestCase):
result = utils.get_image_meta_from_headers(response)
for k, v in fixture.iteritems():
self.assertEqual(v, result[k])
def test_boolean_header_values(self):
"""
Tests that boolean headers like is_public can be set
to True if any of ('True', 'On', 1) is provided, case-insensitive
"""
fixtures = [{'is_public': True},
{'is_public': 'True'},
{'is_public': 'true'},
{'is_public': 'On'},
{'is_public': 1},
{'is_public': '1'}]
expected = {'is_public': True}
class FakeResponse():
pass
for fixture in fixtures:
headers = utils.image_meta_to_http_headers(fixture)
response = FakeResponse()
response.headers = headers
result = utils.get_image_meta_from_headers(response)
for k, v in expected.items():
self.assertEqual(v, result[k])