]> khamidou — GitHub mirrors - vcrpy.git/commitdiff
Compositional HeaderDict insensitive-headers
authorIvan Malison <imalison@uber.com>
Fri, 28 Aug 2015 21:41:35 +0000 (14:41 -0700)
committerIvan Malison <imalison@uber.com>
Fri, 28 Aug 2015 21:51:03 +0000 (14:51 -0700)
tests/unit/test_request.py
tox.ini
vcr/request.py
vcr/serialize.py
vcr/stubs/__init__.py
vcr/util.py

index a89e15afa9ff422f3c55b6dd10a824f8e55790cb..890bb5fefece5f5b8892231749e0821f63229b13 100644 (file)
@@ -1,6 +1,7 @@
 import pytest
 
-from vcr.request import Request, HeadersDict
+from vcr.request import Request
+from vcr.util import HeadersDict
 
 
 def test_str():
@@ -29,7 +30,7 @@ def test_add_header_deprecated():
     ('https://go.com/', 443),
     ('https://go.com:443/', 443),
     ('https://go.com:3000/', 3000),
-    ])
+])
 def test_port(uri, expected_port):
     req = Request('GET', uri,  '', {})
     assert req.port == expected_port
diff --git a/tox.ini b/tox.ini
index 5e1a0dd656410c88ff1cb902647dcae2aea770e1..1be63fcbe50e4b282b7a6171b0397fa990194a37 100644 (file)
--- a/tox.ini
+++ b/tox.ini
@@ -15,6 +15,7 @@ deps =
     pytest
     pytest-localserver
     PyYAML
+    ipdb
     requests1: requests==1.2.3
     requests27: requests==2.7.0
     requests26: requests==2.6.0
index 63e451e584c6202d154e630c1fe0e40e68ff915a..24023dd6c55dd12ed0b26e5dce324de5b950b0d7 100644 (file)
@@ -1,13 +1,11 @@
 import warnings
 from six import BytesIO, text_type
 from six.moves.urllib.parse import urlparse, parse_qsl
-from .util import CaseInsensitiveDict
+from .util import HeadersDict
 
 
 class Request(object):
-    """
-    VCR's representation of a request.
-    """
+    """Represent an HTTP request in vcrpy."""
 
     def __init__(self, method, uri, body, headers):
         self.method = method
@@ -91,41 +89,9 @@ class Request(object):
             'method': self.method,
             'uri': self.uri,
             'body': self.body,
-            'headers': dict(((k, [v]) for k, v in self.headers.items())),
+            'headers': self.headers.serialize,
         }
 
     @classmethod
     def _from_dict(cls, dct):
         return Request(**dct)
-
-
-class HeadersDict(CaseInsensitiveDict):
-    """
-    There is a weird quirk in HTTP.  You can send the same header twice.  For
-    this reason, headers are represented by a dict, with lists as the values.
-    However, it appears that HTTPlib is completely incapable of sending the
-    same header twice.  This puts me in a weird position: I want to be able to
-    accurately represent HTTP headers in cassettes, but I don't want the extra
-    step of always having to do [0] in the general case, i.e.
-    request.headers['key'][0]
-
-    In addition, some servers sometimes send the same header more than once,
-    and httplib *can* deal with this situation.
-
-    Futhermore, I wanted to keep the request and response cassette format as
-    similar as possible.
-
-    For this reason, in cassettes I keep a dict with lists as keys, but once
-    deserialized into VCR, I keep them as plain, naked dicts.
-    """
-
-    def __setitem__(self, key, value):
-        if isinstance(value, (tuple, list)):
-            value = value[0]
-
-        # Preserve the case from the first time this key was set.
-        old = self._store.get(key.lower())
-        if old:
-            key = old[0]
-
-        super(HeadersDict, self).__setitem__(key, value)
index bf669116e59bae4d85287505c59f1a51e14afe69..2dab5e459ae6e7f7b540dbde4dd8f600083c7229 100644 (file)
@@ -36,7 +36,7 @@ def deserialize(cassette_string, serializer):
         data = serializer.deserialize(cassette_string)
     # Old cassettes used to use yaml object thingy so I have to
     # check for some fairly stupid exceptions here
-    except (ImportError, yaml.constructor.ConstructorError):
+    except (ImportError, yaml.constructor.ConstructorError) as er:
         _warn_about_old_cassette_format()
     if _looks_like_an_old_cassette(data):
         _warn_about_old_cassette_format()
index 19d57f1ef79d6b581ec1db077015bd9fbb118d28..f0ee23f4ba65565e5cb573d5ed2e172ae3cd5b1c 100644 (file)
@@ -252,7 +252,7 @@ class VCRConnection(object):
                     method=self._vcr_request.method,
                     url=self._url(self._vcr_request.uri),
                     body=self._vcr_request.body,
-                    headers=self._vcr_request.headers,
+                    headers=self._vcr_request.headers.single_valued,
                 )
 
             # get the response
index e1261970226a48f474740b1ee08239c02f7b701f..0958900c66e968fd07dff775d899dbd6a05e017c 100644 (file)
 import collections
 import types
 
+import six
 
-# Shamelessly stolen from https://github.com/kennethreitz/requests/blob/master/requests/structures.py
-class CaseInsensitiveDict(collections.MutableMapping):
-    """
-    A case-insensitive ``dict``-like object.
-    Implements all methods and operations of
-    ``collections.MutableMapping`` as well as dict's ``copy``. Also
-    provides ``lower_items``.
-    All keys are expected to be strings. The structure remembers the
-    case of the last key to be set, and ``iter(instance)``,
-    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
-    will contain case-sensitive keys. However, querying and contains
-    testing is case insensitive::
-        cid = CaseInsensitiveDict()
-        cid['Accept'] = 'application/json'
-        cid['aCCEPT'] == 'application/json'  # True
-        list(cid) == ['Accept']  # True
-    For example, ``headers['content-encoding']`` will return the
-    value of a ``'Content-Encoding'`` response header, regardless
-    of how the header name was originally stored.
-    If the constructor, ``.update``, or equality comparison
-    operations are given keys that have equal ``.lower()``s, the
-    behavior is undefined.
-    """
-    def __init__(self, data=None, **kwargs):
-        self._store = dict()
+
+class DictDecorator(collections.MutableMapping):
+
+    def __init__(self, data=None, store_type=dict):
+        self._store_type = store_type
+        self._store = self._store_type()
         if data is None:
             data = {}
-        self.update(data, **kwargs)
+        self.update(data)
 
     def __setitem__(self, key, value):
-        # Use the lowercased key for lookups, but store the actual
-        # key alongside the value.
-        self._store[key.lower()] = (key, value)
+        self._store[key] = value
 
     def __getitem__(self, key):
-        return self._store[key.lower()][1]
+        return self._store[key]
 
     def __delitem__(self, key):
-        del self._store[key.lower()]
+        del self._store[key]
 
     def __iter__(self):
-        return (casedkey for casedkey, mappedvalue in self._store.values())
+        return iter(self._store)
 
     def __len__(self):
         return len(self._store)
 
-    def lower_items(self):
-        """Like iteritems(), but with all lowercase keys."""
-        return (
-            (lowerkey, keyval[1])
-            for (lowerkey, keyval)
-            in self._store.items()
-        )
+    def __getattr__(self, attr):
+        return getattr(self._store, attr)
 
-    def __eq__(self, other):
-        if isinstance(other, collections.Mapping):
-            other = CaseInsensitiveDict(other)
-        else:
-            return NotImplemented
-        # Compare insensitively
-        return dict(self.lower_items()) == dict(other.lower_items())
+    def __contains__(self, key):
+        return key in self._store
+
+    def setdefault(self, key, default=None):
+        return self._store.setdefault(key, default)
 
-    # Copy is required
     def copy(self):
-        return CaseInsensitiveDict(self._store.values())
+        return type(self)(data=self._store, store_type=self._store_type)
+
+    @property
+    def underlying_store(self):
+        return (self._store.underlying_store
+                if hasattr(self._store, 'underlying_store')
+                else self._store)
+
+
+KVPair = collections.namedtuple('KVPair', ['key', 'value'])
+
+
+# Adapted from:
+# https://github.com/kennethreitz/requests/blob/master/requests/structures.py
+class CaseInsensitiveDict(DictDecorator):
+
+    def __setitem__(self, key, value):
+        # Use the lowercased key for lookups, but store the actual
+        # key alongside the value.
+        self._store[key.lower()] = KVPair(key, value)
+
+    def __getitem__(self, key):
+        return self._store[key.lower()]
+
+    def __delitem__(self, key):
+        del self._store[key.lower()]
+
+    def __len__(self):
+        return len(self._store)
+
+    def __contains__(self, key):
+        return key.lower() in self._store
 
     def __repr__(self):
         return str(dict(self.items()))
 
+
+class MultiValueDict(DictDecorator):
+
+    _no_set_iterables = six.string_types + (KVPair,)
+
+    def __setitem__(self, key, value):
+        if (not isinstance(value, self._no_set_iterables) and
+                isinstance(value, collections.Iterable)):
+            self._store[key] = collections.deque(value)
+            return
+        if key not in self._store:
+            self._store[key] = collections.deque()
+        self._store[key].appendleft(value)
+
+
+class HeadersDict(CaseInsensitiveDict):
+    """A dictionary object that is adapted to the specific case of
+    representing HTTP requests.
+
+    The HTTP spec has a strange quirk where it allows the submission
+    of a single header twice. For this reason, HeadersDict instances
+    map each case insensitive header string to a list of values that
+    were provided for that header. However, since httplib is incapable
+    of sending the same header twice, HeadersDict provides the
+    property `single_valued`, which returns a version of the headers
+    dict where each header key is mapped to the single value at index
+    0 for that key in the HeadersDict store.
+    """
+
+    def __init__(self, data=None, store_type=None):
+        super(HeadersDict, self).__init__(data, store_type=MultiValueDict)
+
+    @property
+    def single_valued(self):
+        return dict(
+            key_value_pairs[0]
+            for key_value_pairs in self.values()
+        )
+
+    @property
+    def serialize(self):
+        return dict(
+            (lower_key, [(key, value) for key, value in value_pairs])
+            for lower_key, value_pairs in self.items()
+        )
+
+
 def partition_dict(predicate, dictionary):
     true_dict = {}
     false_dict = {}
@@ -89,6 +139,7 @@ def compose(*functions):
         return res
     return composed
 
+
 def read_body(request):
     if hasattr(request.body, 'read'):
         return request.body.read()