mirror of
https://github.com/kevin1024/vcrpy.git
synced 2025-12-09 01:03:24 +00:00
Fix pyflakes and pep8 errors
Use extra asserts to use previously unused variables in tests, such as `cass` and `response`. Fix only pyflakes errors in docs/conf.py
This commit is contained in:
@@ -6,6 +6,7 @@ env:
|
|||||||
- secure: AifoKzwhjV94cmcQZrdQmqRu/9rkZZvWpwBv1daeAQpLOKFPGsOm3D+x2cSw9+iCfkgDZDfqQVv1kCaFVxTll8v8jTq5SJdqEY0NmGWbj/UkNtShh609oRDsuzLxAEwtVKYjf/h8K2BRea+bl1tGkwZ2vtmYS6dxNlAijjWOfds=
|
- secure: AifoKzwhjV94cmcQZrdQmqRu/9rkZZvWpwBv1daeAQpLOKFPGsOm3D+x2cSw9+iCfkgDZDfqQVv1kCaFVxTll8v8jTq5SJdqEY0NmGWbj/UkNtShh609oRDsuzLxAEwtVKYjf/h8K2BRea+bl1tGkwZ2vtmYS6dxNlAijjWOfds=
|
||||||
- secure: LBSEg/gMj4u4Hrpo3zs6Y/1mTpd2RtcN49mZIFgTdbJ9IhpiNPqcEt647Lz94F9Eses2x2WbNuKqZKZZReY7QLbEzU1m0nN5jlaKrjcG5NR5clNABfFFyhgc0jBikyS4abAG8jc2efeaTrFuQwdoF4sE8YiVrkiVj2X5Xoi6sBk=
|
- secure: LBSEg/gMj4u4Hrpo3zs6Y/1mTpd2RtcN49mZIFgTdbJ9IhpiNPqcEt647Lz94F9Eses2x2WbNuKqZKZZReY7QLbEzU1m0nN5jlaKrjcG5NR5clNABfFFyhgc0jBikyS4abAG8jc2efeaTrFuQwdoF4sE8YiVrkiVj2X5Xoi6sBk=
|
||||||
matrix:
|
matrix:
|
||||||
|
- TOX_SUFFIX="flakes"
|
||||||
- TOX_SUFFIX="requests22"
|
- TOX_SUFFIX="requests22"
|
||||||
- TOX_SUFFIX="requests23"
|
- TOX_SUFFIX="requests23"
|
||||||
- TOX_SUFFIX="requests24"
|
- TOX_SUFFIX="requests24"
|
||||||
@@ -37,7 +38,7 @@ python:
|
|||||||
- pypy
|
- pypy
|
||||||
install:
|
install:
|
||||||
- pip install tox
|
- pip install tox
|
||||||
- python setup.py install
|
- if [[ $TOX_SUFFIX != flakes ]]; then python setup.py install ; fi
|
||||||
script:
|
script:
|
||||||
- v=$TRAVIS_PYTHON_VERSION
|
- v=$TRAVIS_PYTHON_VERSION
|
||||||
- if [[ ${v%py} != $v ]]; then TOXPY=$v; else TOXPY=py"${v/./}"; fi
|
- if [[ ${v%py} != $v ]]; then TOXPY=$v; else TOXPY=py"${v/./}"; fi
|
||||||
|
|||||||
@@ -12,9 +12,7 @@
|
|||||||
# All configuration values have a default; values that are commented out
|
# All configuration values have a default; values that are commented out
|
||||||
# serve to show the default.
|
# serve to show the default.
|
||||||
|
|
||||||
import sys
|
|
||||||
import os
|
import os
|
||||||
import shlex
|
|
||||||
|
|
||||||
# If extensions (or modules to document with autodoc) are in another directory,
|
# If extensions (or modules to document with autodoc) are in another directory,
|
||||||
# add these directories to sys.path here. If the directory is relative to the
|
# add these directories to sys.path here. If the directory is relative to the
|
||||||
|
|||||||
@@ -31,26 +31,26 @@ def test_boto_without_vcr():
|
|||||||
def test_boto_medium_difficulty(tmpdir):
|
def test_boto_medium_difficulty(tmpdir):
|
||||||
s3_conn = S3Connection()
|
s3_conn = S3Connection()
|
||||||
s3_bucket = s3_conn.get_bucket('boto-demo-1394171994') # a bucket you can access
|
s3_bucket = s3_conn.get_bucket('boto-demo-1394171994') # a bucket you can access
|
||||||
with vcr.use_cassette(str(tmpdir.join('boto-medium.yml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('boto-medium.yml'))):
|
||||||
k = Key(s3_bucket)
|
k = Key(s3_bucket)
|
||||||
k.key = 'test.txt'
|
k.key = 'test.txt'
|
||||||
k.set_contents_from_string('hello world i am a string')
|
k.set_contents_from_string('hello world i am a string')
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('boto-medium.yml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('boto-medium.yml'))):
|
||||||
k = Key(s3_bucket)
|
k = Key(s3_bucket)
|
||||||
k.key = 'test.txt'
|
k.key = 'test.txt'
|
||||||
k.set_contents_from_string('hello world i am a string')
|
k.set_contents_from_string('hello world i am a string')
|
||||||
|
|
||||||
|
|
||||||
def test_boto_hardcore_mode(tmpdir):
|
def test_boto_hardcore_mode(tmpdir):
|
||||||
with vcr.use_cassette(str(tmpdir.join('boto-hardcore.yml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('boto-hardcore.yml'))):
|
||||||
s3_conn = S3Connection()
|
s3_conn = S3Connection()
|
||||||
s3_bucket = s3_conn.get_bucket('boto-demo-1394171994') # a bucket you can access
|
s3_bucket = s3_conn.get_bucket('boto-demo-1394171994') # a bucket you can access
|
||||||
k = Key(s3_bucket)
|
k = Key(s3_bucket)
|
||||||
k.key = 'test.txt'
|
k.key = 'test.txt'
|
||||||
k.set_contents_from_string('hello world i am a string')
|
k.set_contents_from_string('hello world i am a string')
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('boto-hardcore.yml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('boto-hardcore.yml'))):
|
||||||
s3_conn = S3Connection()
|
s3_conn = S3Connection()
|
||||||
s3_bucket = s3_conn.get_bucket('boto-demo-1394171994') # a bucket you can access
|
s3_bucket = s3_conn.get_bucket('boto-demo-1394171994') # a bucket you can access
|
||||||
k = Key(s3_bucket)
|
k = Key(s3_bucket)
|
||||||
@@ -68,10 +68,10 @@ def test_boto_iam(tmpdir):
|
|||||||
# Ensure that boto uses CertValidatingHTTPSConnection
|
# Ensure that boto uses CertValidatingHTTPSConnection
|
||||||
boto.config.set('Boto', 'https_validate_certificates', 'true')
|
boto.config.set('Boto', 'https_validate_certificates', 'true')
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('boto-iam.yml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('boto-iam.yml'))):
|
||||||
iam_conn = boto.iam.connect_to_region('universal')
|
iam_conn = boto.iam.connect_to_region('universal')
|
||||||
iam_conn.get_all_users()
|
iam_conn.get_all_users()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('boto-iam.yml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('boto-iam.yml'))):
|
||||||
iam_conn = boto.iam.connect_to_region('universal')
|
iam_conn = boto.iam.connect_to_region('universal')
|
||||||
iam_conn.get_all_users()
|
iam_conn.get_all_users()
|
||||||
|
|||||||
@@ -78,9 +78,11 @@ def test_filter_json_post_data(tmpdir):
|
|||||||
def test_filter_callback(tmpdir):
|
def test_filter_callback(tmpdir):
|
||||||
url = 'http://httpbin.org/get'
|
url = 'http://httpbin.org/get'
|
||||||
cass_file = str(tmpdir.join('basic_auth_filter.yaml'))
|
cass_file = str(tmpdir.join('basic_auth_filter.yaml'))
|
||||||
|
|
||||||
def before_record_cb(request):
|
def before_record_cb(request):
|
||||||
if request.path != '/get':
|
if request.path != '/get':
|
||||||
return request
|
return request
|
||||||
|
|
||||||
# Test the legacy keyword.
|
# Test the legacy keyword.
|
||||||
my_vcr = vcr.VCR(before_record=before_record_cb)
|
my_vcr = vcr.VCR(before_record=before_record_cb)
|
||||||
with my_vcr.use_cassette(cass_file, filter_headers=['authorization']) as cass:
|
with my_vcr.use_cassette(cass_file, filter_headers=['authorization']) as cass:
|
||||||
|
|||||||
@@ -24,11 +24,11 @@ def scheme(request):
|
|||||||
def test_response_code(scheme, tmpdir):
|
def test_response_code(scheme, tmpdir):
|
||||||
'''Ensure we can read a response code from a fetch'''
|
'''Ensure we can read a response code from a fetch'''
|
||||||
url = scheme + '://httpbin.org/'
|
url = scheme + '://httpbin.org/'
|
||||||
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))):
|
||||||
resp, _ = httplib2.Http().request(url)
|
resp, _ = httplib2.Http().request(url)
|
||||||
code = resp.status
|
code = resp.status
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))):
|
||||||
resp, _ = httplib2.Http().request(url)
|
resp, _ = httplib2.Http().request(url)
|
||||||
assert code == resp.status
|
assert code == resp.status
|
||||||
|
|
||||||
@@ -36,11 +36,11 @@ def test_response_code(scheme, tmpdir):
|
|||||||
def test_random_body(scheme, tmpdir):
|
def test_random_body(scheme, tmpdir):
|
||||||
'''Ensure we can read the content, and that it's served from cache'''
|
'''Ensure we can read the content, and that it's served from cache'''
|
||||||
url = scheme + '://httpbin.org/bytes/1024'
|
url = scheme + '://httpbin.org/bytes/1024'
|
||||||
with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('body.yaml'))):
|
||||||
_, content = httplib2.Http().request(url)
|
_, content = httplib2.Http().request(url)
|
||||||
body = content
|
body = content
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('body.yaml'))):
|
||||||
_, content = httplib2.Http().request(url)
|
_, content = httplib2.Http().request(url)
|
||||||
assert body == content
|
assert body == content
|
||||||
|
|
||||||
@@ -48,26 +48,28 @@ def test_random_body(scheme, tmpdir):
|
|||||||
def test_response_headers(scheme, tmpdir):
|
def test_response_headers(scheme, tmpdir):
|
||||||
'''Ensure we can get information from the response'''
|
'''Ensure we can get information from the response'''
|
||||||
url = scheme + '://httpbin.org/'
|
url = scheme + '://httpbin.org/'
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
resp, _ = httplib2.Http().request(url)
|
resp, _ = httplib2.Http().request(url)
|
||||||
headers = resp.items()
|
headers = resp.items()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
resp, _ = httplib2.Http().request(url)
|
resp, _ = httplib2.Http().request(url)
|
||||||
assert set(headers) == set(resp.items())
|
assert set(headers) == set(resp.items())
|
||||||
|
|
||||||
|
|
||||||
def test_effective_url(scheme, tmpdir):
|
def test_effective_url(scheme, tmpdir):
|
||||||
'''Ensure that the effective_url is captured'''
|
'''Ensure that the effective_url is captured'''
|
||||||
url = scheme + '://httpbin.org/redirect-to?url=/html'
|
url = scheme + '://httpbin.org/redirect-to?url=/html'
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
resp, _ = httplib2.Http().request(url)
|
resp, _ = httplib2.Http().request(url)
|
||||||
effective_url = resp['content-location']
|
effective_url = resp['content-location']
|
||||||
assert effective_url == scheme + '://httpbin.org/html'
|
assert effective_url == scheme + '://httpbin.org/html'
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
resp, _ = httplib2.Http().request(url)
|
resp, _ = httplib2.Http().request(url)
|
||||||
assert effective_url == resp['content-location']
|
assert effective_url == resp['content-location']
|
||||||
|
|
||||||
|
|
||||||
def test_multiple_requests(scheme, tmpdir):
|
def test_multiple_requests(scheme, tmpdir):
|
||||||
'''Ensure that we can cache multiple requests'''
|
'''Ensure that we can cache multiple requests'''
|
||||||
urls = [
|
urls = [
|
||||||
@@ -85,10 +87,10 @@ def test_get_data(scheme, tmpdir):
|
|||||||
'''Ensure that it works with query data'''
|
'''Ensure that it works with query data'''
|
||||||
data = urlencode({'some': 1, 'data': 'here'})
|
data = urlencode({'some': 1, 'data': 'here'})
|
||||||
url = scheme + '://httpbin.org/get?' + data
|
url = scheme + '://httpbin.org/get?' + data
|
||||||
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))):
|
||||||
_, res1 = httplib2.Http().request(url)
|
_, res1 = httplib2.Http().request(url)
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))):
|
||||||
_, res2 = httplib2.Http().request(url)
|
_, res2 = httplib2.Http().request(url)
|
||||||
|
|
||||||
assert res1 == res2
|
assert res1 == res2
|
||||||
@@ -98,7 +100,7 @@ def test_post_data(scheme, tmpdir):
|
|||||||
'''Ensure that it works when posting data'''
|
'''Ensure that it works when posting data'''
|
||||||
data = urlencode({'some': 1, 'data': 'here'})
|
data = urlencode({'some': 1, 'data': 'here'})
|
||||||
url = scheme + '://httpbin.org/post'
|
url = scheme + '://httpbin.org/post'
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))):
|
||||||
_, res1 = httplib2.Http().request(url, "POST", data)
|
_, res1 = httplib2.Http().request(url, "POST", data)
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
||||||
@@ -112,7 +114,7 @@ def test_post_unicode_data(scheme, tmpdir):
|
|||||||
'''Ensure that it works when posting unicode data'''
|
'''Ensure that it works when posting unicode data'''
|
||||||
data = urlencode({'snowman': u'☃'.encode('utf-8')})
|
data = urlencode({'snowman': u'☃'.encode('utf-8')})
|
||||||
url = scheme + '://httpbin.org/post'
|
url = scheme + '://httpbin.org/post'
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))):
|
||||||
_, res1 = httplib2.Http().request(url, "POST", data)
|
_, res1 = httplib2.Http().request(url, "POST", data)
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import base64
|
from six.moves.urllib.request import urlopen
|
||||||
import pytest
|
|
||||||
from six.moves.urllib.request import urlopen, Request
|
|
||||||
from six.moves.urllib.error import HTTPError
|
|
||||||
import vcr
|
import vcr
|
||||||
|
|
||||||
|
|
||||||
@@ -40,6 +38,7 @@ def test_ignore_localhost_and_httpbin(tmpdir, httpserver):
|
|||||||
urlopen(httpserver.url)
|
urlopen(httpserver.url)
|
||||||
assert len(cass) == 0
|
assert len(cass) == 0
|
||||||
|
|
||||||
|
|
||||||
def test_ignore_localhost_twice(tmpdir, httpserver):
|
def test_ignore_localhost_twice(tmpdir, httpserver):
|
||||||
httpserver.serve_content('Hello!')
|
httpserver.serve_content('Hello!')
|
||||||
cass_file = str(tmpdir.join('filter_qs.yaml'))
|
cass_file = str(tmpdir.join('filter_qs.yaml'))
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ def cassette(tmpdir):
|
|||||||
('query',
|
('query',
|
||||||
'https://google.com/get?p2=q2&p1=q1',
|
'https://google.com/get?p2=q2&p1=q1',
|
||||||
'http://httpbin.org/get?p1=q1&a=b')
|
'http://httpbin.org/get?p1=q1&a=b')
|
||||||
])
|
])
|
||||||
def test_matchers(cassette, matcher, matching_uri, not_matching_uri):
|
def test_matchers(cassette, matcher, matching_uri, not_matching_uri):
|
||||||
# play cassette with default uri
|
# play cassette with default uri
|
||||||
with vcr.use_cassette(cassette, match_on=[matcher]) as cass:
|
with vcr.use_cassette(cassette, match_on=[matcher]) as cass:
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import os
|
|
||||||
import pytest
|
import pytest
|
||||||
import vcr
|
import vcr
|
||||||
from six.moves.urllib.request import urlopen
|
from six.moves.urllib.request import urlopen
|
||||||
@@ -8,39 +7,39 @@ def test_once_record_mode(tmpdir):
|
|||||||
testfile = str(tmpdir.join('recordmode.yml'))
|
testfile = str(tmpdir.join('recordmode.yml'))
|
||||||
with vcr.use_cassette(testfile, record_mode="once"):
|
with vcr.use_cassette(testfile, record_mode="once"):
|
||||||
# cassette file doesn't exist, so create.
|
# cassette file doesn't exist, so create.
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
with vcr.use_cassette(testfile, record_mode="once") as cass:
|
with vcr.use_cassette(testfile, record_mode="once"):
|
||||||
# make the same request again
|
# make the same request again
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
# the first time, it's played from the cassette.
|
# the first time, it's played from the cassette.
|
||||||
# but, try to access something else from the same cassette, and an
|
# but, try to access something else from the same cassette, and an
|
||||||
# exception is raised.
|
# exception is raised.
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(Exception):
|
||||||
response = urlopen('http://httpbin.org/get').read()
|
urlopen('http://httpbin.org/get').read()
|
||||||
|
|
||||||
|
|
||||||
def test_once_record_mode_two_times(tmpdir):
|
def test_once_record_mode_two_times(tmpdir):
|
||||||
testfile = str(tmpdir.join('recordmode.yml'))
|
testfile = str(tmpdir.join('recordmode.yml'))
|
||||||
with vcr.use_cassette(testfile, record_mode="once"):
|
with vcr.use_cassette(testfile, record_mode="once"):
|
||||||
# get two of the same file
|
# get two of the same file
|
||||||
response1 = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
response2 = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
with vcr.use_cassette(testfile, record_mode="once") as cass:
|
with vcr.use_cassette(testfile, record_mode="once"):
|
||||||
# do it again
|
# do it again
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
|
|
||||||
def test_once_mode_three_times(tmpdir):
|
def test_once_mode_three_times(tmpdir):
|
||||||
testfile = str(tmpdir.join('recordmode.yml'))
|
testfile = str(tmpdir.join('recordmode.yml'))
|
||||||
with vcr.use_cassette(testfile, record_mode="once"):
|
with vcr.use_cassette(testfile, record_mode="once"):
|
||||||
# get three of the same file
|
# get three of the same file
|
||||||
response1 = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
response2 = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
response2 = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
|
|
||||||
def test_new_episodes_record_mode(tmpdir):
|
def test_new_episodes_record_mode(tmpdir):
|
||||||
@@ -48,18 +47,18 @@ def test_new_episodes_record_mode(tmpdir):
|
|||||||
|
|
||||||
with vcr.use_cassette(testfile, record_mode="new_episodes"):
|
with vcr.use_cassette(testfile, record_mode="new_episodes"):
|
||||||
# cassette file doesn't exist, so create.
|
# cassette file doesn't exist, so create.
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
with vcr.use_cassette(testfile, record_mode="new_episodes") as cass:
|
with vcr.use_cassette(testfile, record_mode="new_episodes") as cass:
|
||||||
# make the same request again
|
# make the same request again
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
# all responses have been played
|
# all responses have been played
|
||||||
assert cass.all_played
|
assert cass.all_played
|
||||||
|
|
||||||
# in the "new_episodes" record mode, we can add more requests to
|
# in the "new_episodes" record mode, we can add more requests to
|
||||||
# a cassette without repurcussions.
|
# a cassette without repurcussions.
|
||||||
response = urlopen('http://httpbin.org/get').read()
|
urlopen('http://httpbin.org/get').read()
|
||||||
|
|
||||||
# one of the responses has been played
|
# one of the responses has been played
|
||||||
assert cass.play_count == 1
|
assert cass.play_count == 1
|
||||||
@@ -102,15 +101,15 @@ def test_all_record_mode(tmpdir):
|
|||||||
|
|
||||||
with vcr.use_cassette(testfile, record_mode="all"):
|
with vcr.use_cassette(testfile, record_mode="all"):
|
||||||
# cassette file doesn't exist, so create.
|
# cassette file doesn't exist, so create.
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
with vcr.use_cassette(testfile, record_mode="all") as cass:
|
with vcr.use_cassette(testfile, record_mode="all") as cass:
|
||||||
# make the same request again
|
# make the same request again
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
# in the "all" record mode, we can add more requests to
|
# in the "all" record mode, we can add more requests to
|
||||||
# a cassette without repurcussions.
|
# a cassette without repurcussions.
|
||||||
response = urlopen('http://httpbin.org/get').read()
|
urlopen('http://httpbin.org/get').read()
|
||||||
|
|
||||||
# The cassette was never actually played, even though it existed.
|
# The cassette was never actually played, even though it existed.
|
||||||
# that's because, in "all" mode, the requests all go directly to
|
# that's because, in "all" mode, the requests all go directly to
|
||||||
@@ -124,7 +123,7 @@ def test_none_record_mode(tmpdir):
|
|||||||
testfile = str(tmpdir.join('recordmode.yml'))
|
testfile = str(tmpdir.join('recordmode.yml'))
|
||||||
with vcr.use_cassette(testfile, record_mode="none"):
|
with vcr.use_cassette(testfile, record_mode="none"):
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(Exception):
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
|
|
||||||
def test_none_record_mode_with_existing_cassette(tmpdir):
|
def test_none_record_mode_with_existing_cassette(tmpdir):
|
||||||
@@ -132,12 +131,12 @@ def test_none_record_mode_with_existing_cassette(tmpdir):
|
|||||||
testfile = str(tmpdir.join('recordmode.yml'))
|
testfile = str(tmpdir.join('recordmode.yml'))
|
||||||
|
|
||||||
with vcr.use_cassette(testfile, record_mode="all"):
|
with vcr.use_cassette(testfile, record_mode="all"):
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
|
|
||||||
# play from cassette file
|
# play from cassette file
|
||||||
with vcr.use_cassette(testfile, record_mode="none") as cass:
|
with vcr.use_cassette(testfile, record_mode="none") as cass:
|
||||||
response = urlopen('http://httpbin.org/').read()
|
urlopen('http://httpbin.org/').read()
|
||||||
assert cass.play_count == 1
|
assert cass.play_count == 1
|
||||||
# but if I try to hit the net, raise an exception.
|
# but if I try to hit the net, raise an exception.
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(Exception):
|
||||||
response = urlopen('http://httpbin.org/get').read()
|
urlopen('http://httpbin.org/get').read()
|
||||||
|
|||||||
@@ -14,12 +14,12 @@ def test_registered_true_matcher(tmpdir):
|
|||||||
my_vcr = vcr.VCR()
|
my_vcr = vcr.VCR()
|
||||||
my_vcr.register_matcher('true', true_matcher)
|
my_vcr.register_matcher('true', true_matcher)
|
||||||
testfile = str(tmpdir.join('test.yml'))
|
testfile = str(tmpdir.join('test.yml'))
|
||||||
with my_vcr.use_cassette(testfile, match_on=['true']) as cass:
|
with my_vcr.use_cassette(testfile, match_on=['true']):
|
||||||
# These 2 different urls are stored as the same request
|
# These 2 different urls are stored as the same request
|
||||||
urlopen('http://httpbin.org/')
|
urlopen('http://httpbin.org/')
|
||||||
urlopen('https://httpbin.org/get')
|
urlopen('https://httpbin.org/get')
|
||||||
|
|
||||||
with my_vcr.use_cassette(testfile, match_on=['true']) as cass:
|
with my_vcr.use_cassette(testfile, match_on=['true']):
|
||||||
# I can get the response twice even though I only asked for it once
|
# I can get the response twice even though I only asked for it once
|
||||||
urlopen('http://httpbin.org/get')
|
urlopen('http://httpbin.org/get')
|
||||||
urlopen('https://httpbin.org/get')
|
urlopen('https://httpbin.org/get')
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ class MockSerializer(object):
|
|||||||
def deserialize(self, cassette_string):
|
def deserialize(self, cassette_string):
|
||||||
self.serialize_count += 1
|
self.serialize_count += 1
|
||||||
self.cassette_string = cassette_string
|
self.cassette_string = cassette_string
|
||||||
return {'interactions':[]}
|
return {'interactions': []}
|
||||||
|
|
||||||
def serialize(self, cassette_dict):
|
def serialize(self, cassette_dict):
|
||||||
self.deserialize_count += 1
|
self.deserialize_count += 1
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ def test_body(tmpdir, scheme):
|
|||||||
with vcr.use_cassette(str(tmpdir.join('body.yaml'))):
|
with vcr.use_cassette(str(tmpdir.join('body.yaml'))):
|
||||||
assert content == requests.get(url).content
|
assert content == requests.get(url).content
|
||||||
|
|
||||||
|
|
||||||
def test_effective_url(scheme, tmpdir):
|
def test_effective_url(scheme, tmpdir):
|
||||||
'''Ensure that the effective_url is captured'''
|
'''Ensure that the effective_url is captured'''
|
||||||
url = scheme + '://httpbin.org/redirect-to?url=/html'
|
url = scheme + '://httpbin.org/redirect-to?url=/html'
|
||||||
@@ -54,6 +55,7 @@ def test_effective_url(scheme, tmpdir):
|
|||||||
with vcr.use_cassette(str(tmpdir.join('url.yaml'))):
|
with vcr.use_cassette(str(tmpdir.join('url.yaml'))):
|
||||||
assert effective_url == requests.get(url).url
|
assert effective_url == requests.get(url).url
|
||||||
|
|
||||||
|
|
||||||
def test_auth(tmpdir, scheme):
|
def test_auth(tmpdir, scheme):
|
||||||
'''Ensure that we can handle basic auth'''
|
'''Ensure that we can handle basic auth'''
|
||||||
auth = ('user', 'passwd')
|
auth = ('user', 'passwd')
|
||||||
@@ -242,4 +244,3 @@ def test_filter_post_params(tmpdir, scheme):
|
|||||||
requests.post(url, data={'key': 'value'})
|
requests.post(url, data={'key': 'value'})
|
||||||
with vcr.use_cassette(cass_loc, filter_post_data_parameters=['key']) as cass:
|
with vcr.use_cassette(cass_loc, filter_post_data_parameters=['key']) as cass:
|
||||||
assert b'key=value' not in cass.requests[0].body
|
assert b'key=value' not in cass.requests[0].body
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import vcr
|
import vcr
|
||||||
import six.moves.http_client as httplib
|
import six.moves.http_client as httplib
|
||||||
|
|
||||||
|
|
||||||
def _headers_are_case_insensitive():
|
def _headers_are_case_insensitive():
|
||||||
conn = httplib.HTTPConnection('httpbin.org')
|
conn = httplib.HTTPConnection('httpbin.org')
|
||||||
conn.request('GET', "/cookies/set?k1=v1")
|
conn.request('GET', "/cookies/set?k1=v1")
|
||||||
@@ -12,6 +13,7 @@ def _headers_are_case_insensitive():
|
|||||||
cookie_data2 = r2.getheader('Set-Cookie')
|
cookie_data2 = r2.getheader('Set-Cookie')
|
||||||
return cookie_data1 == cookie_data2
|
return cookie_data1 == cookie_data2
|
||||||
|
|
||||||
|
|
||||||
def test_case_insensitivity(tmpdir):
|
def test_case_insensitivity(tmpdir):
|
||||||
testfile = str(tmpdir.join('case_insensitivity.yml'))
|
testfile = str(tmpdir.join('case_insensitivity.yml'))
|
||||||
# check if headers are case insensitive outside of vcrpy
|
# check if headers are case insensitive outside of vcrpy
|
||||||
@@ -25,12 +27,14 @@ def test_case_insensitivity(tmpdir):
|
|||||||
# behavior should be the same both inside and outside
|
# behavior should be the same both inside and outside
|
||||||
assert outside == inside == inside2
|
assert outside == inside == inside2
|
||||||
|
|
||||||
|
|
||||||
def _multiple_header_value(httpserver):
|
def _multiple_header_value(httpserver):
|
||||||
conn = httplib.HTTPConnection('%s:%s' % httpserver.server_address)
|
conn = httplib.HTTPConnection('%s:%s' % httpserver.server_address)
|
||||||
conn.request('GET', "/")
|
conn.request('GET', "/")
|
||||||
r = conn.getresponse()
|
r = conn.getresponse()
|
||||||
return r.getheader('foo')
|
return r.getheader('foo')
|
||||||
|
|
||||||
|
|
||||||
def test_multiple_headers(tmpdir, httpserver):
|
def test_multiple_headers(tmpdir, httpserver):
|
||||||
testfile = str(tmpdir.join('multiple_headers.yaml'))
|
testfile = str(tmpdir.join('multiple_headers.yaml'))
|
||||||
httpserver.serve_content('Hello!', headers=[('foo', 'bar'), ('foo', 'baz')])
|
httpserver.serve_content('Hello!', headers=[('foo', 'bar'), ('foo', 'baz')])
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ def test_body(get_client, tmpdir, scheme):
|
|||||||
assert content == (yield get(get_client(), url)).body
|
assert content == (yield get(get_client(), url)).body
|
||||||
assert 1 == cass.play_count
|
assert 1 == cass.play_count
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.gen_test
|
@pytest.mark.gen_test
|
||||||
def test_effective_url(get_client, scheme, tmpdir):
|
def test_effective_url(get_client, scheme, tmpdir):
|
||||||
'''Ensure that the effective_url is captured'''
|
'''Ensure that the effective_url is captured'''
|
||||||
@@ -93,6 +94,7 @@ def test_effective_url(get_client, scheme, tmpdir):
|
|||||||
assert effective_url == (yield get(get_client(), url)).effective_url
|
assert effective_url == (yield get(get_client(), url)).effective_url
|
||||||
assert 1 == cass.play_count
|
assert 1 == cass.play_count
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.gen_test
|
@pytest.mark.gen_test
|
||||||
def test_auth(get_client, tmpdir, scheme):
|
def test_auth(get_client, tmpdir, scheme):
|
||||||
'''Ensure that we can handle basic auth'''
|
'''Ensure that we can handle basic auth'''
|
||||||
|
|||||||
@@ -22,43 +22,46 @@ def scheme(request):
|
|||||||
def test_response_code(scheme, tmpdir):
|
def test_response_code(scheme, tmpdir):
|
||||||
'''Ensure we can read a response code from a fetch'''
|
'''Ensure we can read a response code from a fetch'''
|
||||||
url = scheme + '://httpbin.org/'
|
url = scheme + '://httpbin.org/'
|
||||||
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))):
|
||||||
code = urlopen(url).getcode()
|
code = urlopen(url).getcode()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('atts.yaml'))):
|
||||||
assert code == urlopen(url).getcode()
|
assert code == urlopen(url).getcode()
|
||||||
|
|
||||||
|
|
||||||
def test_random_body(scheme, tmpdir):
|
def test_random_body(scheme, tmpdir):
|
||||||
'''Ensure we can read the content, and that it's served from cache'''
|
'''Ensure we can read the content, and that it's served from cache'''
|
||||||
url = scheme + '://httpbin.org/bytes/1024'
|
url = scheme + '://httpbin.org/bytes/1024'
|
||||||
with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('body.yaml'))):
|
||||||
body = urlopen(url).read()
|
body = urlopen(url).read()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('body.yaml'))):
|
||||||
assert body == urlopen(url).read()
|
assert body == urlopen(url).read()
|
||||||
|
|
||||||
|
|
||||||
def test_response_headers(scheme, tmpdir):
|
def test_response_headers(scheme, tmpdir):
|
||||||
'''Ensure we can get information from the response'''
|
'''Ensure we can get information from the response'''
|
||||||
url = scheme + '://httpbin.org/'
|
url = scheme + '://httpbin.org/'
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
open1 = urlopen(url).info().items()
|
open1 = urlopen(url).info().items()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
open2 = urlopen(url).info().items()
|
open2 = urlopen(url).info().items()
|
||||||
|
|
||||||
assert sorted(open1) == sorted(open2)
|
assert sorted(open1) == sorted(open2)
|
||||||
|
|
||||||
|
|
||||||
def test_effective_url(scheme, tmpdir):
|
def test_effective_url(scheme, tmpdir):
|
||||||
'''Ensure that the effective_url is captured'''
|
'''Ensure that the effective_url is captured'''
|
||||||
url = scheme + '://httpbin.org/redirect-to?url=/html'
|
url = scheme + '://httpbin.org/redirect-to?url=/html'
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
effective_url = urlopen(url).geturl()
|
effective_url = urlopen(url).geturl()
|
||||||
assert effective_url == scheme + '://httpbin.org/html'
|
assert effective_url == scheme + '://httpbin.org/html'
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('headers.yaml'))):
|
||||||
assert effective_url == urlopen(url).geturl()
|
assert effective_url == urlopen(url).geturl()
|
||||||
|
|
||||||
|
|
||||||
def test_multiple_requests(scheme, tmpdir):
|
def test_multiple_requests(scheme, tmpdir):
|
||||||
'''Ensure that we can cache multiple requests'''
|
'''Ensure that we can cache multiple requests'''
|
||||||
urls = [
|
urls = [
|
||||||
@@ -76,10 +79,10 @@ def test_get_data(scheme, tmpdir):
|
|||||||
'''Ensure that it works with query data'''
|
'''Ensure that it works with query data'''
|
||||||
data = urlencode({'some': 1, 'data': 'here'})
|
data = urlencode({'some': 1, 'data': 'here'})
|
||||||
url = scheme + '://httpbin.org/get?' + data
|
url = scheme + '://httpbin.org/get?' + data
|
||||||
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))):
|
||||||
res1 = urlopen(url).read()
|
res1 = urlopen(url).read()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('get_data.yaml'))):
|
||||||
res2 = urlopen(url).read()
|
res2 = urlopen(url).read()
|
||||||
|
|
||||||
assert res1 == res2
|
assert res1 == res2
|
||||||
@@ -89,11 +92,12 @@ def test_post_data(scheme, tmpdir):
|
|||||||
'''Ensure that it works when posting data'''
|
'''Ensure that it works when posting data'''
|
||||||
data = urlencode({'some': 1, 'data': 'here'}).encode('utf-8')
|
data = urlencode({'some': 1, 'data': 'here'}).encode('utf-8')
|
||||||
url = scheme + '://httpbin.org/post'
|
url = scheme + '://httpbin.org/post'
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))):
|
||||||
res1 = urlopen(url, data).read()
|
res1 = urlopen(url, data).read()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
||||||
res2 = urlopen(url, data).read()
|
res2 = urlopen(url, data).read()
|
||||||
|
assert len(cass) == 1
|
||||||
|
|
||||||
assert res1 == res2
|
assert res1 == res2
|
||||||
assert_cassette_has_one_response(cass)
|
assert_cassette_has_one_response(cass)
|
||||||
@@ -103,10 +107,13 @@ def test_post_unicode_data(scheme, tmpdir):
|
|||||||
'''Ensure that it works when posting unicode data'''
|
'''Ensure that it works when posting unicode data'''
|
||||||
data = urlencode({'snowman': u'☃'.encode('utf-8')}).encode('utf-8')
|
data = urlencode({'snowman': u'☃'.encode('utf-8')}).encode('utf-8')
|
||||||
url = scheme + '://httpbin.org/post'
|
url = scheme + '://httpbin.org/post'
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))):
|
||||||
res1 = urlopen(url, data).read()
|
res1 = urlopen(url, data).read()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
with vcr.use_cassette(str(tmpdir.join('post_data.yaml'))) as cass:
|
||||||
res2 = urlopen(url, data).read()
|
res2 = urlopen(url, data).read()
|
||||||
|
assert len(cass) == 1
|
||||||
|
|
||||||
assert res1 == res2
|
assert res1 == res2
|
||||||
assert_cassette_has_one_response(cass)
|
assert_cassette_has_one_response(cass)
|
||||||
|
|
||||||
@@ -122,6 +129,7 @@ def test_cross_scheme(tmpdir):
|
|||||||
assert len(cass) == 2
|
assert len(cass) == 2
|
||||||
assert cass.play_count == 0
|
assert cass.play_count == 0
|
||||||
|
|
||||||
|
|
||||||
def test_decorator(scheme, tmpdir):
|
def test_decorator(scheme, tmpdir):
|
||||||
'''Test the decorator version of VCR.py'''
|
'''Test the decorator version of VCR.py'''
|
||||||
url = scheme + '://httpbin.org/'
|
url = scheme + '://httpbin.org/'
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ def scheme(request):
|
|||||||
@pytest.fixture(scope='module')
|
@pytest.fixture(scope='module')
|
||||||
def verify_pool_mgr():
|
def verify_pool_mgr():
|
||||||
return urllib3.PoolManager(
|
return urllib3.PoolManager(
|
||||||
cert_reqs='CERT_REQUIRED', # Force certificate check.
|
cert_reqs='CERT_REQUIRED', # Force certificate check.
|
||||||
ca_certs=certifi.where()
|
ca_certs=certifi.where()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ def test_flickr_multipart_upload():
|
|||||||
data = r.read()
|
data = r.read()
|
||||||
h.close()
|
h.close()
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
with vcr.use_cassette('fixtures/vcr_cassettes/flickr.yaml') as cass:
|
with vcr.use_cassette('fixtures/vcr_cassettes/flickr.yaml') as cass:
|
||||||
_pretend_to_be_flickr_library()
|
_pretend_to_be_flickr_library()
|
||||||
assert len(cass) == 1
|
assert len(cass) == 1
|
||||||
@@ -63,7 +65,8 @@ def test_cookies(tmpdir):
|
|||||||
testfile = str(tmpdir.join('cookies.yml'))
|
testfile = str(tmpdir.join('cookies.yml'))
|
||||||
with vcr.use_cassette(testfile):
|
with vcr.use_cassette(testfile):
|
||||||
s = requests.Session()
|
s = requests.Session()
|
||||||
r1 = s.get("http://httpbin.org/cookies/set?k1=v1&k2=v2")
|
s.get("http://httpbin.org/cookies/set?k1=v1&k2=v2")
|
||||||
|
|
||||||
r2 = s.get("http://httpbin.org/cookies")
|
r2 = s.get("http://httpbin.org/cookies")
|
||||||
assert len(r2.json()['cookies']) == 2
|
assert len(r2.json()['cookies']) == 2
|
||||||
|
|
||||||
@@ -81,9 +84,8 @@ def test_xmlrpclib(tmpdir):
|
|||||||
roundup_server = xmlrpc_client.ServerProxy('http://bugs.python.org/xmlrpc', allow_none=True)
|
roundup_server = xmlrpc_client.ServerProxy('http://bugs.python.org/xmlrpc', allow_none=True)
|
||||||
original_schema = roundup_server.schema()
|
original_schema = roundup_server.schema()
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join('xmlrpcvideo.yaml'))) as cassette:
|
with vcr.use_cassette(str(tmpdir.join('xmlrpcvideo.yaml'))):
|
||||||
roundup_server = xmlrpc_client.ServerProxy('http://bugs.python.org/xmlrpc', allow_none=True)
|
roundup_server = xmlrpc_client.ServerProxy('http://bugs.python.org/xmlrpc', allow_none=True)
|
||||||
second_schema = roundup_server.schema()
|
second_schema = roundup_server.schema()
|
||||||
|
|
||||||
assert original_schema == second_schema
|
assert original_schema == second_schema
|
||||||
|
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ def make_get_request():
|
|||||||
def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times(*args):
|
def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times(*args):
|
||||||
decorated_function = Cassette.use(path='test')(make_get_request)
|
decorated_function = Cassette.use(path='test')(make_get_request)
|
||||||
for i in range(4):
|
for i in range(4):
|
||||||
decorated_function()
|
decorated_function()
|
||||||
|
|
||||||
|
|
||||||
def test_arg_getter_functionality():
|
def test_arg_getter_functionality():
|
||||||
@@ -160,7 +160,7 @@ def test_nesting_cassette_context_managers(*args):
|
|||||||
with contextlib.ExitStack() as exit_stack:
|
with contextlib.ExitStack() as exit_stack:
|
||||||
first_cassette = exit_stack.enter_context(Cassette.use(path='test'))
|
first_cassette = exit_stack.enter_context(Cassette.use(path='test'))
|
||||||
exit_stack.enter_context(mock.patch.object(first_cassette, 'play_response',
|
exit_stack.enter_context(mock.patch.object(first_cassette, 'play_response',
|
||||||
return_value=first_response))
|
return_value=first_response))
|
||||||
assert_get_response_body_is('first_response')
|
assert_get_response_body_is('first_response')
|
||||||
|
|
||||||
# Make sure a second cassette can supercede the first
|
# Make sure a second cassette can supercede the first
|
||||||
@@ -200,16 +200,17 @@ def test_custom_patchers():
|
|||||||
custom_patches=((Test, 'attribute', VCRHTTPSConnection),)):
|
custom_patches=((Test, 'attribute', VCRHTTPSConnection),)):
|
||||||
assert issubclass(Test.attribute, VCRHTTPSConnection)
|
assert issubclass(Test.attribute, VCRHTTPSConnection)
|
||||||
assert VCRHTTPSConnection is not Test.attribute
|
assert VCRHTTPSConnection is not Test.attribute
|
||||||
assert Test.attribute is not old_attribute
|
assert Test.attribute is not old_attribute
|
||||||
|
|
||||||
assert issubclass(Test.attribute, VCRHTTPSConnection)
|
assert issubclass(Test.attribute, VCRHTTPSConnection)
|
||||||
assert VCRHTTPSConnection is not Test.attribute
|
assert VCRHTTPSConnection is not Test.attribute
|
||||||
assert Test.attribute is old_attribute
|
assert Test.attribute is old_attribute
|
||||||
|
|
||||||
|
|
||||||
def test_decorated_functions_are_reentrant():
|
def test_decorated_functions_are_reentrant():
|
||||||
info = {"second": False}
|
info = {"second": False}
|
||||||
original_conn = httplib.HTTPConnection
|
original_conn = httplib.HTTPConnection
|
||||||
|
|
||||||
@Cassette.use(path='whatever', inject=True)
|
@Cassette.use(path='whatever', inject=True)
|
||||||
def test_function(cassette):
|
def test_function(cassette):
|
||||||
if info['second']:
|
if info['second']:
|
||||||
@@ -219,6 +220,7 @@ def test_decorated_functions_are_reentrant():
|
|||||||
info['second'] = True
|
info['second'] = True
|
||||||
test_function()
|
test_function()
|
||||||
assert httplib.HTTPConnection is info['first_conn']
|
assert httplib.HTTPConnection is info['first_conn']
|
||||||
|
|
||||||
test_function()
|
test_function()
|
||||||
assert httplib.HTTPConnection is original_conn
|
assert httplib.HTTPConnection is original_conn
|
||||||
|
|
||||||
@@ -232,9 +234,11 @@ def test_cassette_use_called_without_path_uses_function_to_generate_path():
|
|||||||
|
|
||||||
def test_path_transformer_with_function_path():
|
def test_path_transformer_with_function_path():
|
||||||
path_transformer = lambda path: os.path.join('a', path)
|
path_transformer = lambda path: os.path.join('a', path)
|
||||||
|
|
||||||
@Cassette.use(inject=True, path_transformer=path_transformer)
|
@Cassette.use(inject=True, path_transformer=path_transformer)
|
||||||
def function_name(cassette):
|
def function_name(cassette):
|
||||||
assert cassette._path == os.path.join('a', 'function_name')
|
assert cassette._path == os.path.join('a', 'function_name')
|
||||||
|
|
||||||
function_name()
|
function_name()
|
||||||
|
|
||||||
|
|
||||||
@@ -255,15 +259,18 @@ def test_path_transformer_None():
|
|||||||
def test_func_path_generator():
|
def test_func_path_generator():
|
||||||
def generator(function):
|
def generator(function):
|
||||||
return os.path.join(os.path.dirname(inspect.getfile(function)),
|
return os.path.join(os.path.dirname(inspect.getfile(function)),
|
||||||
function.__name__)
|
function.__name__)
|
||||||
|
|
||||||
@Cassette.use(inject=True, func_path_generator=generator)
|
@Cassette.use(inject=True, func_path_generator=generator)
|
||||||
def function_name(cassette):
|
def function_name(cassette):
|
||||||
assert cassette._path == os.path.join(os.path.dirname(__file__), 'function_name')
|
assert cassette._path == os.path.join(os.path.dirname(__file__), 'function_name')
|
||||||
|
|
||||||
function_name()
|
function_name()
|
||||||
|
|
||||||
|
|
||||||
def test_use_as_decorator_on_coroutine():
|
def test_use_as_decorator_on_coroutine():
|
||||||
original_http_connetion = httplib.HTTPConnection
|
original_http_connetion = httplib.HTTPConnection
|
||||||
|
|
||||||
@Cassette.use(inject=True)
|
@Cassette.use(inject=True)
|
||||||
def test_function(cassette):
|
def test_function(cassette):
|
||||||
assert httplib.HTTPConnection.cassette is cassette
|
assert httplib.HTTPConnection.cassette is cassette
|
||||||
@@ -274,6 +281,7 @@ def test_use_as_decorator_on_coroutine():
|
|||||||
assert httplib.HTTPConnection is not original_http_connetion
|
assert httplib.HTTPConnection is not original_http_connetion
|
||||||
value = yield 2
|
value = yield 2
|
||||||
assert value == 2
|
assert value == 2
|
||||||
|
|
||||||
coroutine = test_function()
|
coroutine = test_function()
|
||||||
value = next(coroutine)
|
value = next(coroutine)
|
||||||
while True:
|
while True:
|
||||||
@@ -285,6 +293,7 @@ def test_use_as_decorator_on_coroutine():
|
|||||||
|
|
||||||
def test_use_as_decorator_on_generator():
|
def test_use_as_decorator_on_generator():
|
||||||
original_http_connetion = httplib.HTTPConnection
|
original_http_connetion = httplib.HTTPConnection
|
||||||
|
|
||||||
@Cassette.use(inject=True)
|
@Cassette.use(inject=True)
|
||||||
def test_function(cassette):
|
def test_function(cassette):
|
||||||
assert httplib.HTTPConnection.cassette is cassette
|
assert httplib.HTTPConnection.cassette is cassette
|
||||||
@@ -293,4 +302,5 @@ def test_use_as_decorator_on_generator():
|
|||||||
assert httplib.HTTPConnection.cassette is cassette
|
assert httplib.HTTPConnection.cassette is cassette
|
||||||
assert httplib.HTTPConnection is not original_http_connetion
|
assert httplib.HTTPConnection is not original_http_connetion
|
||||||
yield 2
|
yield 2
|
||||||
|
|
||||||
assert list(test_function()) == [1, 2]
|
assert list(test_function()) == [1, 2]
|
||||||
|
|||||||
@@ -29,9 +29,9 @@ def test_add_header_deprecated():
|
|||||||
('https://go.com/', 443),
|
('https://go.com/', 443),
|
||||||
('https://go.com:443/', 443),
|
('https://go.com:443/', 443),
|
||||||
('https://go.com:3000/', 3000),
|
('https://go.com:3000/', 3000),
|
||||||
])
|
])
|
||||||
def test_port(uri, expected_port):
|
def test_port(uri, expected_port):
|
||||||
req = Request('GET', uri, '', {})
|
req = Request('GET', uri, '', {})
|
||||||
assert req.port == expected_port
|
assert req.port == expected_port
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
from vcr.stubs import VCRHTTPSConnection
|
from vcr.stubs import VCRHTTPSConnection
|
||||||
|
|
||||||
|
|
||||||
class TestVCRConnection(object):
|
class TestVCRConnection(object):
|
||||||
|
|
||||||
def test_setting_of_attributes_get_propogated_to_real_connection(self):
|
def test_setting_of_attributes_get_propogated_to_real_connection(self):
|
||||||
vcr_connection = VCRHTTPSConnection('www.examplehost.com')
|
vcr_connection = VCRHTTPSConnection('www.examplehost.com')
|
||||||
vcr_connection.ssl_version = 'example_ssl_version'
|
vcr_connection.ssl_version = 'example_ssl_version'
|
||||||
|
|||||||
16
tox.ini
16
tox.ini
@@ -1,15 +1,22 @@
|
|||||||
[tox]
|
[tox]
|
||||||
envlist = {py26,py27,py33,py34,pypy}-{requests27,requests26,requests25,requests24,requests23,requests22,requests1,httplib2,urllib317,urllib319,urllib3110,tornado,boto}
|
envlist = py34-flakes,{py26,py27,py33,py34,pypy}-{requests27,requests26,requests25,requests24,requests23,requests22,requests1,httplib2,urllib317,urllib319,urllib3110,tornado,boto}
|
||||||
|
|
||||||
|
[testenv:py34-flakes]
|
||||||
|
skipsdist = True
|
||||||
|
commands =
|
||||||
|
flake8 --exclude="./docs/conf.py"
|
||||||
|
pyflakes ./docs/conf.py
|
||||||
|
deps = flake8
|
||||||
|
|
||||||
[testenv]
|
[testenv]
|
||||||
commands =
|
|
||||||
py.test {posargs}
|
|
||||||
basepython =
|
basepython =
|
||||||
py26: python2.6
|
py26: python2.6
|
||||||
py27: python2.7
|
py27: python2.7
|
||||||
py33: python3.3
|
py33: python3.3
|
||||||
py34: python3.4
|
py34: python3.4
|
||||||
pypy: pypy
|
pypy: pypy
|
||||||
|
commands =
|
||||||
|
py.test {posargs}
|
||||||
deps =
|
deps =
|
||||||
mock
|
mock
|
||||||
pytest
|
pytest
|
||||||
@@ -30,3 +37,6 @@ deps =
|
|||||||
{py26,py27,py33,py34,pypy}-tornado: pytest-tornado
|
{py26,py27,py33,py34,pypy}-tornado: pytest-tornado
|
||||||
{py26,py27,py33,py34}-tornado: pycurl
|
{py26,py27,py33,py34}-tornado: pycurl
|
||||||
boto: boto
|
boto: boto
|
||||||
|
|
||||||
|
[flake8]
|
||||||
|
max_line_length = 110
|
||||||
|
|||||||
@@ -67,7 +67,8 @@ def _identity(x):
|
|||||||
|
|
||||||
def _get_transformer(request):
|
def _get_transformer(request):
|
||||||
for checker, transformer in _checker_transformer_pairs:
|
for checker, transformer in _checker_transformer_pairs:
|
||||||
if checker(request.headers): return transformer
|
if checker(request.headers):
|
||||||
|
return transformer
|
||||||
else:
|
else:
|
||||||
return _identity
|
return _identity
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import sys
|
|||||||
import tempfile
|
import tempfile
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
from .serializers import compat, yamlserializer, jsonserializer
|
from .serializers import yamlserializer, jsonserializer
|
||||||
from .serialize import serialize
|
from .serialize import serialize
|
||||||
from . import request
|
from . import request
|
||||||
from .stubs.compat import get_httpmessage
|
from .stubs.compat import get_httpmessage
|
||||||
|
|||||||
25
vcr/patch.py
25
vcr/patch.py
@@ -59,7 +59,7 @@ except ImportError: # pragma: no cover
|
|||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
_SimpleAsyncHTTPClient_fetch_impl = \
|
_SimpleAsyncHTTPClient_fetch_impl = \
|
||||||
tornado.simple_httpclient.SimpleAsyncHTTPClient.fetch_impl
|
tornado.simple_httpclient.SimpleAsyncHTTPClient.fetch_impl
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -68,7 +68,7 @@ except ImportError: # pragma: no cover
|
|||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
_CurlAsyncHTTPClient_fetch_impl = \
|
_CurlAsyncHTTPClient_fetch_impl = \
|
||||||
tornado.curl_httpclient.CurlAsyncHTTPClient.fetch_impl
|
tornado.curl_httpclient.CurlAsyncHTTPClient.fetch_impl
|
||||||
|
|
||||||
|
|
||||||
class CassettePatcherBuilder(object):
|
class CassettePatcherBuilder(object):
|
||||||
@@ -127,13 +127,13 @@ class CassettePatcherBuilder(object):
|
|||||||
described in the previous paragraph.
|
described in the previous paragraph.
|
||||||
"""
|
"""
|
||||||
if isinstance(replacement_dict_or_obj, dict):
|
if isinstance(replacement_dict_or_obj, dict):
|
||||||
for key, replacement_obj in replacement_dict_or_obj.items():
|
for key, replacement_obj in replacement_dict_or_obj.items():
|
||||||
replacement_obj = self._recursively_apply_get_cassette_subclass(
|
replacement_obj = self._recursively_apply_get_cassette_subclass(
|
||||||
replacement_obj)
|
replacement_obj)
|
||||||
replacement_dict_or_obj[key] = replacement_obj
|
replacement_dict_or_obj[key] = replacement_obj
|
||||||
return replacement_dict_or_obj
|
return replacement_dict_or_obj
|
||||||
if hasattr(replacement_dict_or_obj, 'cassette'):
|
if hasattr(replacement_dict_or_obj, 'cassette'):
|
||||||
replacement_dict_or_obj = self._get_cassette_subclass(
|
replacement_dict_or_obj = self._get_cassette_subclass(
|
||||||
replacement_dict_or_obj)
|
replacement_dict_or_obj)
|
||||||
return replacement_dict_or_obj
|
return replacement_dict_or_obj
|
||||||
|
|
||||||
@@ -147,7 +147,7 @@ class CassettePatcherBuilder(object):
|
|||||||
|
|
||||||
def _build_cassette_subclass(self, base_class):
|
def _build_cassette_subclass(self, base_class):
|
||||||
bases = (base_class,)
|
bases = (base_class,)
|
||||||
if not issubclass(base_class, object): # Check for old style class
|
if not issubclass(base_class, object): # Check for old style class
|
||||||
bases += (object,)
|
bases += (object,)
|
||||||
return type('{0}{1}'.format(base_class.__name__, self._cassette._path),
|
return type('{0}{1}'.format(base_class.__name__, self._cassette._path),
|
||||||
bases, dict(cassette=self._cassette))
|
bases, dict(cassette=self._cassette))
|
||||||
@@ -167,11 +167,13 @@ class CassettePatcherBuilder(object):
|
|||||||
|
|
||||||
def _patched_get_conn(self, connection_pool_class, connection_class_getter):
|
def _patched_get_conn(self, connection_pool_class, connection_class_getter):
|
||||||
get_conn = connection_pool_class._get_conn
|
get_conn = connection_pool_class._get_conn
|
||||||
|
|
||||||
@functools.wraps(get_conn)
|
@functools.wraps(get_conn)
|
||||||
def patched_get_conn(pool, timeout=None):
|
def patched_get_conn(pool, timeout=None):
|
||||||
connection = get_conn(pool, timeout)
|
connection = get_conn(pool, timeout)
|
||||||
connection_class = pool.ConnectionCls if hasattr(pool, 'ConnectionCls') \
|
connection_class = (
|
||||||
else connection_class_getter()
|
pool.ConnectionCls if hasattr(pool, 'ConnectionCls')
|
||||||
|
else connection_class_getter())
|
||||||
# We need to make sure that we are actually providing a
|
# We need to make sure that we are actually providing a
|
||||||
# patched version of the connection class. This might not
|
# patched version of the connection class. This might not
|
||||||
# always be the case because the pool keeps previously
|
# always be the case because the pool keeps previously
|
||||||
@@ -181,15 +183,18 @@ class CassettePatcherBuilder(object):
|
|||||||
while not isinstance(connection, connection_class):
|
while not isinstance(connection, connection_class):
|
||||||
connection = get_conn(pool, timeout)
|
connection = get_conn(pool, timeout)
|
||||||
return connection
|
return connection
|
||||||
|
|
||||||
return patched_get_conn
|
return patched_get_conn
|
||||||
|
|
||||||
def _patched_new_conn(self, connection_pool_class, connection_remover):
|
def _patched_new_conn(self, connection_pool_class, connection_remover):
|
||||||
new_conn = connection_pool_class._new_conn
|
new_conn = connection_pool_class._new_conn
|
||||||
|
|
||||||
@functools.wraps(new_conn)
|
@functools.wraps(new_conn)
|
||||||
def patched_new_conn(pool):
|
def patched_new_conn(pool):
|
||||||
new_connection = new_conn(pool)
|
new_connection = new_conn(pool)
|
||||||
connection_remover.add_connection_to_pool_entry(pool, new_connection)
|
connection_remover.add_connection_to_pool_entry(pool, new_connection)
|
||||||
return new_connection
|
return new_connection
|
||||||
|
|
||||||
return patched_new_conn
|
return patched_new_conn
|
||||||
|
|
||||||
def _urllib3(self):
|
def _urllib3(self):
|
||||||
@@ -270,10 +275,10 @@ class CassettePatcherBuilder(object):
|
|||||||
# connections of the appropriate type.
|
# connections of the appropriate type.
|
||||||
mock_triples += ((cpool.HTTPConnectionPool, '_get_conn',
|
mock_triples += ((cpool.HTTPConnectionPool, '_get_conn',
|
||||||
self._patched_get_conn(cpool.HTTPConnectionPool,
|
self._patched_get_conn(cpool.HTTPConnectionPool,
|
||||||
lambda : cpool.HTTPConnection)),
|
lambda: cpool.HTTPConnection)),
|
||||||
(cpool.HTTPSConnectionPool, '_get_conn',
|
(cpool.HTTPSConnectionPool, '_get_conn',
|
||||||
self._patched_get_conn(cpool.HTTPSConnectionPool,
|
self._patched_get_conn(cpool.HTTPSConnectionPool,
|
||||||
lambda : cpool.HTTPSConnection)),
|
lambda: cpool.HTTPSConnection)),
|
||||||
(cpool.HTTPConnectionPool, '_new_conn',
|
(cpool.HTTPConnectionPool, '_new_conn',
|
||||||
self._patched_new_conn(cpool.HTTPConnectionPool,
|
self._patched_new_conn(cpool.HTTPConnectionPool,
|
||||||
http_connection_remover)),
|
http_connection_remover)),
|
||||||
@@ -382,7 +387,7 @@ def reset_patchers():
|
|||||||
else:
|
else:
|
||||||
yield mock.patch.object(
|
yield mock.patch.object(
|
||||||
curl.CurlAsyncHTTPClient,
|
curl.CurlAsyncHTTPClient,
|
||||||
'fetch_impl',
|
'fetch_impl',
|
||||||
_CurlAsyncHTTPClient_fetch_impl,
|
_CurlAsyncHTTPClient_fetch_impl,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
'''Stubs for patching HTTP and HTTPS requests'''
|
'''Stubs for patching HTTP and HTTPS requests'''
|
||||||
|
|
||||||
try:
|
|
||||||
import http.client
|
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
import logging
|
import logging
|
||||||
import six
|
import six
|
||||||
from six.moves.http_client import (
|
from six.moves.http_client import (
|
||||||
@@ -329,8 +325,8 @@ class VCRConnection(object):
|
|||||||
try:
|
try:
|
||||||
setattr(self.real_connection, name, value)
|
setattr(self.real_connection, name, value)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
# raised if real_connection has not been set yet, such as when
|
# raised if real_connection has not been set yet, such as when
|
||||||
# we're setting the real_connection itself for the first time
|
# we're setting the real_connection itself for the first time
|
||||||
pass
|
pass
|
||||||
|
|
||||||
super(VCRConnection, self).__setattr__(name, value)
|
super(VCRConnection, self).__setattr__(name, value)
|
||||||
|
|||||||
@@ -10,8 +10,10 @@ from ..stubs import VCRHTTPConnection, VCRHTTPSConnection
|
|||||||
# urllib3 defines its own HTTPConnection classes, which requests goes ahead and assumes
|
# urllib3 defines its own HTTPConnection classes, which requests goes ahead and assumes
|
||||||
# you're using. It includes some polyfills for newer features missing in older pythons.
|
# you're using. It includes some polyfills for newer features missing in older pythons.
|
||||||
|
|
||||||
|
|
||||||
class VCRRequestsHTTPConnection(VCRHTTPConnection, HTTPConnection):
|
class VCRRequestsHTTPConnection(VCRHTTPConnection, HTTPConnection):
|
||||||
_baseclass = HTTPConnection
|
_baseclass = HTTPConnection
|
||||||
|
|
||||||
|
|
||||||
class VCRRequestsHTTPSConnection(VCRHTTPSConnection, VerifiedHTTPSConnection):
|
class VCRRequestsHTTPSConnection(VCRHTTPSConnection, VerifiedHTTPSConnection):
|
||||||
_baseclass = VerifiedHTTPSConnection
|
_baseclass = VerifiedHTTPSConnection
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ from ..stubs import VCRHTTPConnection, VCRHTTPSConnection
|
|||||||
# urllib3 defines its own HTTPConnection classes. It includes some polyfills
|
# urllib3 defines its own HTTPConnection classes. It includes some polyfills
|
||||||
# for newer features missing in older pythons.
|
# for newer features missing in older pythons.
|
||||||
|
|
||||||
|
|
||||||
class VCRRequestsHTTPConnection(VCRHTTPConnection, HTTPConnection):
|
class VCRRequestsHTTPConnection(VCRHTTPConnection, HTTPConnection):
|
||||||
_baseclass = HTTPConnection
|
_baseclass = HTTPConnection
|
||||||
|
|
||||||
|
|
||||||
class VCRRequestsHTTPSConnection(VCRHTTPSConnection, VerifiedHTTPSConnection):
|
class VCRRequestsHTTPSConnection(VCRHTTPSConnection, VerifiedHTTPSConnection):
|
||||||
_baseclass = VerifiedHTTPSConnection
|
_baseclass = VerifiedHTTPSConnection
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ class CaseInsensitiveDict(collections.MutableMapping):
|
|||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return str(dict(self.items()))
|
return str(dict(self.items()))
|
||||||
|
|
||||||
|
|
||||||
def partition_dict(predicate, dictionary):
|
def partition_dict(predicate, dictionary):
|
||||||
true_dict = {}
|
true_dict = {}
|
||||||
false_dict = {}
|
false_dict = {}
|
||||||
@@ -89,6 +90,7 @@ def compose(*functions):
|
|||||||
return res
|
return res
|
||||||
return composed
|
return composed
|
||||||
|
|
||||||
|
|
||||||
def read_body(request):
|
def read_body(request):
|
||||||
if hasattr(request.body, 'read'):
|
if hasattr(request.body, 'read'):
|
||||||
return request.body.read()
|
return request.body.read()
|
||||||
|
|||||||
Reference in New Issue
Block a user