Skip to content

Commit

Permalink
Merge pull request #145 from JayH5/issue-144--hasheaders-values
Browse files Browse the repository at this point in the history
Encode header values in treq.testing.HasHeaders
  • Loading branch information
glyph committed Nov 8, 2016
2 parents e0b3ad8 + dcf98d1 commit a852b5f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
9 changes: 9 additions & 0 deletions treq/test/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,15 @@ def test_case_sensitive_values(self):
"""
self.assertNotEqual(HasHeaders({b'a': [b'a']}), {b'a': [b'A']})

def test_bytes_encoded_forms(self):
"""
The :obj:`HasHeaders` equality function compares the bytes-encoded
forms of both sets of headers.
"""
self.assertEqual(HasHeaders({b'a': [b'a']}), {u'a': [u'a']})

self.assertEqual(HasHeaders({u'b': [u'b']}), {b'b': [b'b']})

def test_repr(self):
"""
:obj:`HasHeaders` returns a nice string repr.
Expand Down
15 changes: 11 additions & 4 deletions treq/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,12 @@ def _maybeEncode(someStr):
return someStr


def _maybeEncodeHeaders(headers):
""" Convert a headers mapping to its bytes-encoded form. """
return {_maybeEncode(k).lower(): [_maybeEncode(v) for v in vs]
for k, vs in headers.items()}


class HasHeaders(object):
"""
Since Twisted adds headers to a request, such as the host and the content
Expand All @@ -298,17 +304,18 @@ class HasHeaders(object):
This wraps a set of headers, and can be used in an equality test against
a superset if the provided headers. The headers keys are lowercased, and
keys and values are compared in their bytes-encoded forms.
Headers should be provided as a mapping from strings or bytes to a list of
strings or bytes.
"""
def __init__(self, headers):
self._headers = dict([(_maybeEncode(k).lower(), _maybeEncode(v))
for k, v in headers.items()])
self._headers = _maybeEncodeHeaders(headers)

def __repr__(self):
return "HasHeaders({0})".format(repr(self._headers))

def __eq__(self, other_headers):
compare_to = dict([(_maybeEncode(k).lower(), _maybeEncode(v))
for k, v in other_headers.items()])
compare_to = _maybeEncodeHeaders(other_headers)

return (set(self._headers.keys()).issubset(set(compare_to.keys())) and
all([set(v).issubset(set(compare_to[k]))
Expand Down

0 comments on commit a852b5f

Please sign in to comment.