当前位置: 首页>>代码示例>>Python>>正文


Python vcr.VCR类代码示例

本文整理汇总了Python中vcr.VCR的典型用法代码示例。如果您正苦于以下问题:Python VCR类的具体用法?Python VCR怎么用?Python VCR使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了VCR类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_vcr_use_cassette

def test_vcr_use_cassette():
    record_mode = mock.Mock()
    test_vcr = VCR(record_mode=record_mode)
    with mock.patch(
        'vcr.cassette.Cassette.load',
        return_value=mock.MagicMock(inject=False)
    ) as mock_cassette_load:
        @test_vcr.use_cassette('test')
        def function():
            pass
        assert mock_cassette_load.call_count == 0
        function()
        assert mock_cassette_load.call_args[1]['record_mode'] is record_mode

        # Make sure that calls to function now use cassettes with the
        # new filter_header_settings
        test_vcr.record_mode = mock.Mock()
        function()
        assert mock_cassette_load.call_args[1]['record_mode'] == test_vcr.record_mode

        # Ensure that explicitly provided arguments still supercede
        # those on the vcr.
        new_record_mode = mock.Mock()

    with test_vcr.use_cassette('test', record_mode=new_record_mode) as cassette:
        assert cassette.record_mode == new_record_mode
开发者ID:MrJohz,项目名称:vcrpy,代码行数:26,代码来源:test_vcr.py

示例2: vcr

def vcr(request):

    def auth_matcher(r1, r2):
        return (r1.headers.get('authorization') ==
                r2.headers.get('authorization'))

    def uri_with_query_matcher(r1, r2):
        "URI matcher that allows query params to appear in any order"
        p1,  p2 = urlparse(r1.uri), urlparse(r2.uri)
        return (p1[:3] == p2[:3] and
                parse_qs(p1.query, True) == parse_qs(p2.query, True))

    # Use `none` to use the recorded requests, and `once` to delete existing
    # cassettes and re-record.
    record_mode = request.config.option.record_mode
    assert record_mode in ('once', 'none')

    cassette_dir = os.path.join(os.path.dirname(__file__), 'cassettes')
    if not os.path.exists(cassette_dir):
        os.makedirs(cassette_dir)

    # https://github.com/kevin1024/vcrpy/pull/196
    vcr = VCR(
        record_mode=request.config.option.record_mode,
        filter_headers=[('Authorization', '**********')],
        filter_post_data_parameters=[('refresh_token', '**********')],
        match_on=['method', 'uri_with_query', 'auth', 'body'],
        cassette_library_dir=cassette_dir)
    vcr.register_matcher('auth', auth_matcher)
    vcr.register_matcher('uri_with_query', uri_with_query_matcher)
    return vcr
开发者ID:5225225,项目名称:rtv,代码行数:31,代码来源:conftest.py

示例3: test_vcr_before_record_request_params

def test_vcr_before_record_request_params():
    base_path = 'http://httpbin.org/'
    def before_record_cb(request):
        if request.path != '/get':
            return request
    test_vcr = VCR(filter_headers=('cookie',), before_record_request=before_record_cb,
                   ignore_hosts=('www.test.com',), ignore_localhost=True,
                   filter_query_parameters=('foo',))

    with test_vcr.use_cassette('test') as cassette:
        assert cassette.filter_request(Request('GET', base_path + 'get', '', {})) is None
        assert cassette.filter_request(Request('GET', base_path + 'get2', '', {})) is not None

        assert cassette.filter_request(Request('GET', base_path + '?foo=bar', '', {})).query == []
        assert cassette.filter_request(
            Request('GET', base_path + '?foo=bar', '',
                    {'cookie': 'test', 'other': 'fun'})).headers == {'other': 'fun'}
        assert cassette.filter_request(Request('GET', base_path + '?foo=bar', '',
                                               {'cookie': 'test', 'other': 'fun'})).headers == {'other': 'fun'}

        assert cassette.filter_request(Request('GET', 'http://www.test.com' + '?foo=bar', '',
                                               {'cookie': 'test', 'other': 'fun'})) is None

    with test_vcr.use_cassette('test', before_record_request=None) as cassette:
        # Test that before_record can be overwritten with
        assert cassette.filter_request(Request('GET', base_path + 'get', '', {})) is not None
开发者ID:gazpachoking,项目名称:vcrpy,代码行数:26,代码来源:test_vcr.py

示例4: test_before_record_response_as_filter

def test_before_record_response_as_filter():
    request = Request('GET', '/', '', {})
    response = object()  # just can't be None

    # Prevent actually saving the cassette
    with mock.patch('vcr.cassette.FilesystemPersister.save_cassette'):

        filter_all = mock.Mock(return_value=None)
        vcr = VCR(before_record_response=filter_all)
        with vcr.use_cassette('test') as cassette:
            cassette.append(request, response)
            assert cassette.data == []
            assert not cassette.dirty
开发者ID:adamchainz,项目名称:vcrpy,代码行数:13,代码来源:test_vcr.py

示例5: test_custom_patchers

def test_custom_patchers():
    class Test(object):
        attribute = None
        attribute2 = None
    test_vcr = VCR(custom_patches=((Test, 'attribute', VCRHTTPSConnection),))
    with test_vcr.use_cassette('custom_patches'):
        assert issubclass(Test.attribute, VCRHTTPSConnection)
        assert VCRHTTPSConnection is not Test.attribute

    with test_vcr.use_cassette('custom_patches', custom_patches=((Test, 'attribute2', VCRHTTPSConnection),)):
        assert issubclass(Test.attribute, VCRHTTPSConnection)
        assert VCRHTTPSConnection is not Test.attribute
        assert Test.attribute is Test.attribute2
开发者ID:addgene,项目名称:vcrpy,代码行数:13,代码来源:test_vcr.py

示例6: vcr

def vcr(vcr):
    def scrub_request(request):
        for header in ("Authorization", "Set-Cookie", "Cookie"):
            if header in request.headers:
                del request.headers[header]
        return request

    def scrub_response(response):
        for header in ("Authorization", "Set-Cookie", "Cookie", "Date", "Expires", "Transfer-Encoding"):
            if header in response["headers"]:
                del response["headers"][header]
        return response

    def range_header_matcher(r1, r2):
        return r1.headers.get('Range', '') == r2.headers.get('Range', '')

    vcr.cassette_library_dir = CASSETTE_DIR
    vcr.path_transformer = VCR.ensure_suffix('.yaml')
    vcr.filter_headers = ['Set-Cookie']
    vcr.before_record_request = scrub_request
    vcr.before_record_response = scrub_response
    vcr.decode_compressed_response = True
    vcr.register_serializer('custom', BinaryContentSerializer(CASSETTE_DIR))
    vcr.serializer = 'custom'
    vcr.register_matcher('range_header', range_header_matcher)
    vcr.match_on = ['uri', 'method', 'body', 'range_header']
    return vcr
开发者ID:valgur,项目名称:sentinelsat,代码行数:27,代码来源:conftest.py

示例7: test_ensure_suffix

def test_ensure_suffix():
    vcr = VCR(inject_cassette=True, path_transformer=VCR.ensure_suffix('.yaml'))
    @vcr.use_cassette
    def function_name(cassette):
        assert cassette._path == os.path.join(os.path.dirname(__file__),
                                              'function_name.yaml')
    function_name()
开发者ID:MrJohz,项目名称:vcrpy,代码行数:7,代码来源:test_vcr.py

示例8: test_vcr_before_record_request_params

def test_vcr_before_record_request_params():
    base_path = 'http://httpbin.org/'

    def before_record_cb(request):
        if request.path != '/get':
            return request

    test_vcr = VCR(filter_headers=('cookie', ('bert', 'ernie')),
                   before_record_request=before_record_cb,
                   ignore_hosts=('www.test.com',), ignore_localhost=True,
                   filter_query_parameters=('foo', ('tom', 'jerry')),
                   filter_post_data_parameters=('posted', ('no', 'trespassing')))

    with test_vcr.use_cassette('test') as cassette:
        # Test explicit before_record_cb
        request_get = Request('GET', base_path + 'get', '', {})
        assert cassette.filter_request(request_get) is None
        request = Request('GET', base_path + 'get2', '', {})
        assert cassette.filter_request(request) is not None

        # Test filter_query_parameters
        request = Request('GET', base_path + '?foo=bar', '', {})
        assert cassette.filter_request(request).query == []
        request = Request('GET', base_path + '?tom=nobody', '', {})
        assert cassette.filter_request(request).query == [('tom', 'jerry')]

        # Test filter_headers
        request = Request('GET', base_path + '?foo=bar', '',
                          {'cookie': 'test', 'other': 'fun', 'bert': 'nobody'})
        assert (cassette.filter_request(request).headers ==
                {'other': 'fun', 'bert': 'ernie'})

        # Test ignore_hosts
        request = Request('GET', 'http://www.test.com' + '?foo=bar', '',
                          {'cookie': 'test', 'other': 'fun'})
        assert cassette.filter_request(request) is None

        # Test ignore_localhost
        request = Request('GET', 'http://localhost:8000' + '?foo=bar', '',
                          {'cookie': 'test', 'other': 'fun'})
        assert cassette.filter_request(request) is None

    with test_vcr.use_cassette('test', before_record_request=None) as cassette:
        # Test that before_record can be overwritten in context manager.
        assert cassette.filter_request(request_get) is not None
开发者ID:adamchainz,项目名称:vcrpy,代码行数:45,代码来源:test_vcr.py

示例9: test_with_current_defaults

def test_with_current_defaults():
    vcr = VCR(inject_cassette=True, record_mode='once')
    @vcr.use_cassette('test', with_current_defaults=False)
    def changing_defaults(cassette, checks):
        checks(cassette)
    @vcr.use_cassette('test', with_current_defaults=True)
    def current_defaults(cassette, checks):
        checks(cassette)

    def assert_record_mode_once(cassette):
        assert cassette.record_mode == 'once'

    def assert_record_mode_all(cassette):
        assert cassette.record_mode == 'all'

    changing_defaults(assert_record_mode_once)
    current_defaults(assert_record_mode_once)

    vcr.record_mode = 'all'
    changing_defaults(assert_record_mode_all)
    current_defaults(assert_record_mode_once)
开发者ID:addgene,项目名称:vcrpy,代码行数:21,代码来源:test_vcr.py

示例10: __init__

 def __init__(self, max_pages=5):
     self.headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                     'Host': 'zhixing.court.gov.cn',
                     'Upgrade-Insecure-Requests': '1',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
                     }
     self.j_captcha = '0000'  # 验证码
     self.s = None  # session
     self.total_pages = 1
     self.case_ids = set()
     self.detail_info = []
     self.vcr = VCR()
     self.MAX_PAGES = max_pages
开发者ID:ExtraYin,项目名称:Credit_Report,代码行数:13,代码来源:fayuan_zhixing.py

示例11: test_vcr_before_record_request_params

def test_vcr_before_record_request_params():
    base_path = "http://httpbin.org/"

    def before_record_cb(request):
        if request.path != "/get":
            return request

    test_vcr = VCR(
        filter_headers=("cookie",),
        before_record_request=before_record_cb,
        ignore_hosts=("www.test.com",),
        ignore_localhost=True,
        filter_query_parameters=("foo",),
    )

    with test_vcr.use_cassette("test") as cassette:
        assert cassette.filter_request(Request("GET", base_path + "get", "", {})) is None
        assert cassette.filter_request(Request("GET", base_path + "get2", "", {})) is not None

        assert cassette.filter_request(Request("GET", base_path + "?foo=bar", "", {})).query == []
        assert cassette.filter_request(
            Request("GET", base_path + "?foo=bar", "", {"cookie": "test", "other": "fun"})
        ).headers == {"other": "fun"}
        assert cassette.filter_request(
            Request("GET", base_path + "?foo=bar", "", {"cookie": "test", "other": "fun"})
        ).headers == {"other": "fun"}

        assert (
            cassette.filter_request(
                Request("GET", "http://www.test.com" + "?foo=bar", "", {"cookie": "test", "other": "fun"})
            )
            is None
        )

    with test_vcr.use_cassette("test", before_record_request=None) as cassette:
        # Test that before_record can be overwritten with
        assert cassette.filter_request(Request("GET", base_path + "get", "", {})) is not None
开发者ID:gwillem,项目名称:vcrpy,代码行数:37,代码来源:test_vcr.py

示例12: test_vcr_before_record_response_iterable

def test_vcr_before_record_response_iterable():
    # Regression test for #191

    request = Request('GET', '/', '', {})
    response = object()  # just can't be None

    # Prevent actually saving the cassette
    with mock.patch('vcr.cassette.save_cassette'):

        # Baseline: non-iterable before_record_response should work
        mock_filter = mock.Mock()
        vcr = VCR(before_record_response=mock_filter)
        with vcr.use_cassette('test') as cassette:
            assert mock_filter.call_count == 0
            cassette.append(request, response)
            assert mock_filter.call_count == 1

        # Regression test: iterable before_record_response should work too
        mock_filter = mock.Mock()
        vcr = VCR(before_record_response=(mock_filter,))
        with vcr.use_cassette('test') as cassette:
            assert mock_filter.call_count == 0
            cassette.append(request, response)
            assert mock_filter.call_count == 1
开发者ID:bcen,项目名称:vcrpy,代码行数:24,代码来源:test_vcr.py

示例13: test_vcr_path_transformer

def test_vcr_path_transformer():
    # Regression test for #199

    # Prevent actually saving the cassette
    with mock.patch('vcr.cassette.save_cassette'):

        # Baseline: path should be unchanged
        vcr = VCR()
        with vcr.use_cassette('test') as cassette:
            assert cassette._path == 'test'

        # Regression test: path_transformer=None should do the same.
        vcr = VCR(path_transformer=None)
        with vcr.use_cassette('test') as cassette:
            assert cassette._path == 'test'

        # and it should still work with cassette_library_dir
        vcr = VCR(cassette_library_dir='/foo')
        with vcr.use_cassette('test') as cassette:
            assert cassette._path == '/foo/test'
开发者ID:bcen,项目名称:vcrpy,代码行数:20,代码来源:test_vcr.py

示例14: VCR

    """Replace confidential information in the recorded cassettes.

    - customer:key are replaced with 'X:Y'

    """
    payload = json.loads(request.body)
    payload['SignRequest']['OptionalInputs']['ClaimedIdentity']['Name'] = 'X:Y'
    request.body = json.dumps(payload)
    return request


my_vcr = VCR(
    serializer='json',
    record_mode='once',
    cassette_library_dir=join(dirname(__file__), 'cassettes'),
    path_transformer=VCR.ensure_suffix('.json'),
    before_record=before_record_callback
)


def fixture_path(filename):
    """Build the full path of a fixture file."""
    return join(dirname(__file__), 'fixtures', filename)


class TestAIS(unittest.TestCase):
    """Generic tests of the AIS client."""

    def test_constructor(self):
        """The constructor builds a client instance."""
        alice_instance = AIS(customer='alice', key_static='alice_secret',
开发者ID:lepistone,项目名称:AIS.py,代码行数:31,代码来源:test_ais.py

示例15: VCR

# -*- coding: utf-8 -*-

import bot_mock
from pyfibot.modules import module_urltitle

from utils import check_re
import pytest

from vcr import VCR

my_vcr = VCR(
    path_transformer=VCR.ensure_suffix(".yaml"),
    cassette_library_dir="tests/cassettes/",
    record_mode=pytest.config.getoption("--vcrmode"),
)


@pytest.fixture
def botmock():
    bot = bot_mock.BotMock()
    module_urltitle.init(bot)
    return bot


length_str_regex = u"\d+(h|m|s)(\d+(m))?(\d+s)?"
views_str_regex = u"\d+(\.\d+)?(k|M|Billion|Trillion)?"
age_str_regex = u"(FRESH|(\d+(\.\d+)?(y|d) (ago|from now)))"


@my_vcr.use_cassette
def test_areena_radio(botmock):
开发者ID:lepinkainen,项目名称:pyfibot,代码行数:31,代码来源:test_areena.py


注:本文中的vcr.VCR类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。