• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python vcr.VCR类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: my_vcr

def my_vcr(gocd_docker):
    return VCR(
        path_transformer=VCR.ensure_suffix('.yaml'),
        cassette_library_dir=os.path.join(root_cassette_library_dir, gocd_docker),
    )
开发者ID:grundic,项目名称:yagocd,代码行数:5,代码来源:conftest.py


示例17: serialize

    def serialize(cassette_dict):
        for i in cassette_dict['interactions']:
            # Remove request headers
            i['request']['headers'] = {}
            # Filter some unimportant response headers
            response_headers = i['response']['headers']
            response_headers.pop('connection', None)
            response_headers.pop('date', None)
            response_headers.pop('server', None)
            filter_x_headers(response_headers)
        return yamlserializer.serialize(cassette_dict)

    @staticmethod
    def deserialize(cassette_str):
        return yamlserializer.deserialize(cassette_str)


vcr = VCR(
    cassette_library_dir=FIXTURES_ROOT,
    record_mode='once',
    match_on=['url', 'method'],
)
vcr.register_serializer('custom', CustomSerializer)


def use_cassette(name):
    return vcr.use_cassette(
        '{}.yml'.format(name),
        serializer='custom',
    )
开发者ID:fracolo,项目名称:liberapay.com,代码行数:30,代码来源:vcr.py


示例18: VCR

    - customer:key are replaced with 'X:Y'
    """
    body = request.body
    if helpers.PY3:
        body = request.body.decode('utf-8')

    payload = json.loads(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
)

if helpers.PY3:
    my_vcr.register_serializer('json', JSONSerializer)


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


class BaseCase(unittest.TestCase):
    pass
开发者ID:camptocamp,项目名称:AIS.py,代码行数:31,代码来源:common.py


示例19: session_fixture

    session.server_url = 'http://example.com'
    return session


@pytest.fixture()
def session_fixture():
    options = copy.deepcopy(Yagocd.DEFAULT_OPTIONS)
    options['server'] = 'http://local.docker:8153/'
    return Session(
        auth=('admin', '12345'),
        options=options
    )


my_vcr_object = VCR(
    path_transformer=VCR.ensure_suffix('.yaml'),
    cassette_library_dir=os.path.join(tests_dir(), 'fixtures/cassettes'),
)


@pytest.fixture()
def my_vcr():
    return my_vcr_object


CONTAINER_NAME = 'yagocd-server'
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))


def pytest_addoption(parser):
    parser.addoption(
开发者ID:barrowkwan,项目名称:yagocd,代码行数:31,代码来源:conftest.py


示例20: Fayuan

class Fayuan(object):
    def __str__(self):
        return 'Fayuan Zhixing Enging.'

    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

    def get_code(self):
        code_url = "http://zhixing.court.gov.cn/search/security/jcaptcha.jpg?" + str(random.randint(1, 99))
        code_response = self.s.get(code_url)  # 获取验证码图片和cookies (必须)
        with open('code.jpg', 'wb') as f:
            f.write(code_response.content)
        # self.j_captcha = raw_input("Input Code: ")
        self.j_captcha = self.vcr.recognize(os.path.join(os.getcwd(), 'code.jpg'))

    def get_page(self, name, page=1):
        self.get_code()  # 获取验证码
        data = {'searchCourtName': u'全国法院(包含地方各级法院)',
                'selectCourtId': 1,
                'selectCourtArrange': 1,
                'pname': name,
                'cardNum': '',
                'currentPage': page,
                'j_captcha': self.j_captcha
                }
        self.s.headers.update({'Origin': 'http://zhixing.court.gov.cn',
                          'Referer': 'http://zhixing.court.gov.cn/search/',
                          'Upgrade-Insecure-Requests': '1'})

        response = self.s.post('http://zhixing.court.gov.cn/search/newsearch', data=data)
        tried = 0
        while u"验证码出现错误,请重新输入" in response.text:  # 验证码出错
            tried += 1
            if tried >= 3:  # try 3 times
                return False
            self.get_code()  # 获取验证码
            data['j_captcha'] = self.j_captcha
            response = self.s.post('http://zhixing.court.gov.cn/search/newsearch', data=data)
        self.total_pages = int(re.search(u' .+页 \d+/(.+) 共.+', response.text).group(1))

        soup = BeautifulSoup(response.text, 'lxml')
        rows = soup.find('tbody').find_all('tr')[1:]
        for row in rows:
            case_id = row.find_all('td')[4].find('a')['id']
            self.case_ids.add(case_id)
        return True

    def get_basic_info(self, name):
        self.get_page(name, 1)
        if self.total_pages > 1:
            for i in range(2, min(self.total_pages+1, self.MAX_PAGES+1)):
                self.get_page(name, i)

    def get_detail(self):
        for case_id in self.case_ids:
            self.get_code()  # 获取验证码
            detail_url = "http://zhixing.court.gov.cn/search/newdetail?id=" + str(case_id) + "&j_captcha=" + str(self.j_captcha)
            detail_response = self.s.get(detail_url)
            tried = 0
            while detail_response.text == '{}':   # 验证码出错
                tried += 1
                if tried >= 3:  # try 3 times
                    return False
                self.get_code()  # 获取验证码
                detail_url = "http://zhixing.court.gov.cn/search/newdetail?id=" + str(case_id) + "&j_captcha=" + str(self.j_captcha)
                detail_response = self.s.get(detail_url)
            self.detail_info.append(json.loads(detail_response.text))
        return True

    def search(self, name='英孚'):
        # 初始化
        self.s = requests.Session()
        self.total_pages = 1
        self.case_ids = set()
        self.detail_info = []

        # 开始查询
        self.s.get("http://zhixing.court.gov.cn/search/", headers=self.headers)  # 第一次访问(必需)
        # s.get("http://zhixing.court.gov.cn/search/explain.html?v=20130408", headers=headers)   # 获取下方文字(非查询必须)
        self.get_basic_info(name)
        self.get_detail()
        return self.detail_info
开发者ID:ExtraYin,项目名称:Credit_Report,代码行数:93,代码来源:fayuan_zhixing.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python cassette.Cassette类代码示例发布时间:2022-05-26
下一篇:
Python vcr.use_cassette函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap