]> khamidou — GitHub mirrors - vcrpy.git/commitdiff
Add support for posting files through requests. closes #121. Possibly #134.
authorIvan Malison <IvanMalison@gmail.com>
Tue, 24 Mar 2015 20:27:23 +0000 (13:27 -0700)
committerIvan Malison <IvanMalison@gmail.com>
Tue, 24 Mar 2015 21:11:16 +0000 (14:11 -0700)
tests/integration/test_requests.py
vcr/matchers.py
vcr/request.py

index 30cf774a8353eb4047982451a36047292624056d..da40239e6e32ab78cb4da99abc27de9d12d566a8 100644 (file)
@@ -199,3 +199,18 @@ def test_nested_cassettes_with_session_created_before_nesting(scheme, tmpdir):
     # Make sure that the session can now get content normally.
     session.get('http://www.reddit.com')
 
+
+def test_post_file(tmpdir, scheme):
+    '''Ensure that we handle posting a file.'''
+    url = scheme + '://httpbin.org/post'
+    with vcr.use_cassette(str(tmpdir.join('post_file.yaml'))) as cass, open('tox.ini') as f:
+        original_response = requests.post(url, f).content
+
+    # This also tests that we do the right thing with matching the body when they are files.
+    with vcr.use_cassette(str(tmpdir.join('post_file.yaml')),
+                          match_on=('method', 'scheme', 'host', 'port', 'path', 'query', 'body')) as cass, open('tox.ini') as f:
+        tox_content = f.read()
+        assert cass.requests[0].body.read() == tox_content
+        with open('tox.ini') as f:
+            new_response = requests.post(url, f).content
+        assert original_response == new_response
index d24875cd398fc45853d965d7afca7a53f3910691..91bce1117d9d78467865a5cd160bab02f142c782 100644 (file)
@@ -31,6 +31,8 @@ def query(r1, r2):
 
 
 def body(r1, r2):
+    if hasattr(r1.body, 'read') and hasattr(r2.body, 'read'):
+        return r1.body.read() == r2.body.read()
     return r1.body == r2.body
 
 
index 052573292f70af068a5575102e980cbb2d747f3e..26ba917250886aaa300fd0de34cb1a440d4cd3cb 100644 (file)
@@ -1,3 +1,4 @@
+import StringIO
 from six.moves.urllib.parse import urlparse, parse_qsl
 
 
@@ -26,11 +27,16 @@ class Request(object):
     def __init__(self, method, uri, body, headers):
         self.method = method
         self.uri = uri
-        self.body = body
+        self._was_file = hasattr(body, 'read')
+        self._body = body.read() if self._was_file else body
         self.headers = {}
         for key in headers:
             self.add_header(key, headers[key])
 
+    @property
+    def body(self):
+        return StringIO.StringIO(self._body) if self._was_file else self._body
+
     def add_header(self, key, value):
         # see class docstring for an explanation
         if isinstance(value, (tuple, list)):