Beispiel #1
0
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
 def randomize(self, randoSettings, graphSettings):
     self.restrictions = Restrictions(randoSettings)
     graphBuilder = GraphBuilder(graphSettings)
     container = None
     i = 0
     attempts = 500 if graphSettings.areaRando else 1
     while container is None and i < attempts:
         self.areaGraph = graphBuilder.createGraph()
         services = RandoServices(self.areaGraph, self.restrictions)
         setup = RandoSetup(graphSettings, graphLocations, services)
         container = setup.createItemLocContainer()
         if container is None:
             sys.stdout.write('*')
             sys.stdout.flush()
             i += 1
     if container is None:
         if graphSettings.areaRando:
             self.errorMsg = "Could not find an area layout with these settings"
         else:
             self.errorMsg = "Unable to process settings"
         return (True, [], [])
     graphBuilder.escapeGraph(container, self.areaGraph,
                              randoSettings.maxDiff)
     self.areaGraph.printGraph()
     filler = self.createFiller(randoSettings, graphSettings, container)
     vcr = VCR(self.seedName, 'rando') if self.vcr == True else None
     ret = filler.generateItems(vcr=vcr)
     self.errorMsg = filler.errorMsg
     return ret
Beispiel #3
0
def make_vcr(pytestconfig, cassette_library_dir):
    mode = pytestconfig.getoption('--vcr-mode')
    api_key = pytestconfig.getoption('--whispir-api-key')
    username = pytestconfig.getoption('--whispir-username')
    gcm_api_key = pytestconfig.getoption('--whispir-gcm-api-key')
    scrubber = scrub_patterns(
        ((api_key, TEST_API_KEY), (username, TEST_USERNAME),
         (gcm_api_key, TEST_GCM_API_KEY)))
    options = {
        'record_mode':
        mode,
        'filter_headers': [('authorization', replace_auth),
                           ('set-cookie', None), ('cookie', None),
                           ('User-Agent', None), ('x-api-key', TEST_API_KEY)],
        'before_record_response':
        scrubber,
        'before_record_request':
        scrubber,
        'path_transformer':
        VCR.ensure_suffix('.yaml'),
        'decode_compressed_response':
        True,
        'cassette_library_dir':
        cassette_library_dir,
        'match_on':
        ('method', 'scheme', 'host', 'port', 'path', 'query', 'headers'),
        'serializer':
        'pretty-yaml'
    }
    vcr = VCR(**options)
    vcr.register_serializer('pretty-yaml', prettyserializer)
    return vcr
def use_cassette(*args, **kwargs):
    return VCR(
        cassette_library_dir=os.path.join(os.path.dirname(__file__),
                                          'cassettes', 'api_client'),
        match_on=['url', 'method', 'headers', 'body'],
        record_mode='none',
    ).use_cassette(*args, **kwargs)
Beispiel #5
0
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
Beispiel #6
0
def custom_vcr(request, custom_cassette_dir):
    return VCR(
        cassette_library_dir=str(custom_cassette_dir),
        decode_compressed_response=True,
        filter_headers=[("authorization", "[REDACTED]")],
        record_mode=request.config.getoption("--record-mode"),
    )
Beispiel #7
0
def initialize_vcr():

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

    def uri_with_query_matcher(r1, r2):
        p1,  p2 = urlparse(r1.uri), urlparse(r2.uri)
        return (p1[:3] == p2[:3] and
                parse_qs(p1.query, True) == parse_qs(p2.query, True))

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

    filename = os.path.join(cassette_dir, 'demo_theme.yaml')
    if os.path.exists(filename):
        record_mode = 'none'
    else:
        record_mode = 'once'
    vcr = VCR(
        record_mode=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
Beispiel #8
0
def http_recorder(vcr_mode, cassette_dir):
    """Creates a VCR object in vcr_mode mode.

    Args:
        vcr_mode (string): the parameter for record_mode.
        cassette_dir (string): path to the cassettes.

    Returns:
        VCR: a VCR object.
    """
    my_vcr = VCR(cassette_library_dir=cassette_dir,
                 record_mode=vcr_mode,
                 match_on=[
                     'method', 'scheme', 'host', 'port', 'path',
                     'unordered_query'
                 ],
                 filter_headers=['x-qx-client-application', 'User-Agent'],
                 filter_query_parameters=[('access_token',
                                           'dummyapiusersloginWithTokenid01')],
                 filter_post_data_parameters=[('apiToken', 'apiToken_dummy')],
                 decode_compressed_response=True,
                 before_record_response=_purge_headers_cb([
                     'Date', ('Set-Cookie', 'dummy_cookie'),
                     'X-Global-Transaction-ID', 'Etag',
                     'Content-Security-Policy', 'X-Content-Security-Policy',
                     'X-Webkit-Csp', 'content-length'
                 ]))
    my_vcr.register_matcher('unordered_query', _unordered_query_matcher)
    my_vcr.register_persister(IdRemoverPersister)
    return my_vcr
def use_sso_cassette(*args, **kwargs):
    return VCR(
        cassette_library_dir=os.path.join(os.path.dirname(__file__),
                                          'cassettes', 'sso'),
        match_on=['method', 'scheme', 'host', 'port', 'path', 'query'],
        record_mode='none',
    ).use_cassette(*args, **kwargs)
Beispiel #10
0
def use_cassette(vcr=VCR(), path='fixtures/vcr_cassettes/', **kwargs):
    """
    Usage:
       @use_cassette()  # the default path will be fixtures/vcr_cassettes/foo.yaml
       def foo(self):
           ...

       @use_cassette(path='fixtures/vcr_cassettes/synopsis.yaml', record_mode='one')
       def foo(self):
           ...
    """
    def decorator(func):
        @wraps(func)
        def inner_func(*args, **kw):
            if os.path.isabs(path):
                file_path = path
            else:
                fun_path, fun_filename = os.path.split(
                    func.__code__.co_filename)
                file_path = os.path.join(fun_path, path,
                                         os.path.splitext(fun_filename)[0])

            if not os.path.splitext(file_path)[1]:
                serializer = kwargs.get('serializer', vcr.serializer)
                file_path = os.path.join(
                    file_path, '{0}.{1}'.format(func.__name__.lower(),
                                                serializer))

            with vcr.use_cassette(file_path, **kwargs):
                return func(*args, **kw)

        return inner_func

    return decorator
Beispiel #11
0
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
Beispiel #12
0
def test_use_cassette_with_no_extra_invocation():
    vcr = VCR(inject_cassette=True, cassette_library_dir='/')

    @vcr.use_cassette
    def function_name(cassette):
        assert cassette._path == os.path.join('/', 'function_name')

    function_name()
Beispiel #13
0
def test_cassette_name_generator_defaults_to_using_module_function_defined_in():
    vcr = VCR(inject_cassette=True)

    @vcr.use_cassette
    def function_name(cassette):
        assert cassette._path == os.path.join(os.path.dirname(__file__),
                                              'function_name')
    function_name()
Beispiel #14
0
 def _get_vcr(self):
     testdir = os.path.dirname(inspect.getfile(self.__class__))
     cassettes_dir = os.path.join(testdir, 'cassettes')
     return VCR(record_mode=self.vcrpy_record_mode,
                cassette_library_dir=cassettes_dir,
                match_on=['method', 'scheme', 'host', 'port', 'path'],
                filter_query_parameters=FILTER_QUERY_PARAMS,
                filter_post_data_parameters=FILTER_QUERY_PARAMS,
                before_record_response=RecordedTestCase.remove_link_headers)
Beispiel #15
0
def test_decoration_should_respect_function_return_value():
    vcr = VCR()
    ret = "a-return-value"

    @vcr.use_cassette
    def function_with_return():
        return ret

    assert ret == function_with_return()
Beispiel #16
0
def test_cassette_library_dir_with_decoration_and_explicit_path():
    library_dir = "/library_dir"
    vcr = VCR(inject_cassette=True, cassette_library_dir=library_dir)

    @vcr.use_cassette(path="custom_name")
    def function_name(cassette):
        assert cassette._path == os.path.join(library_dir, "custom_name")

    function_name()
Beispiel #17
0
def vcr():
    return VCR(
        cassette_library_dir=str(
            Path(__file__).parent.joinpath("fixtures/cassettes")),
        decode_compressed_response=True,
        path_transformer=VCR.ensure_suffix(".yaml"),
        record_mode="once",
        filter_headers=["authorization"],
    )
Beispiel #18
0
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()
Beispiel #19
0
def test_path_transformer():
    vcr = VCR(inject_cassette=True, cassette_library_dir='/',
              path_transformer=lambda x: x + '_test')

    @vcr.use_cassette
    def function_name(cassette):
        assert cassette._path == os.path.join('/', 'function_name_test')

    function_name()
Beispiel #20
0
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
Beispiel #21
0
def test_cassette_library_dir_with_decoration_and_super_explicit_path():
    library_dir = '/libary_dir'
    vcr = VCR(inject_cassette=True, cassette_library_dir=library_dir)

    @vcr.use_cassette(path=os.path.join(library_dir, 'custom_name'))
    def function_name(cassette):
        assert cassette._path == os.path.join(library_dir, 'custom_name')

    function_name()
Beispiel #22
0
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
Beispiel #23
0
def custom_vcr():
    dirname = os.path.dirname(__file__)
    return VCR(decode_compressed_response=True,
               cassette_library_dir=os.path.join(dirname,
                                                 'fixtures/cassettes'),
               path_transformer=VCR.ensure_suffix('.yml'),
               filter_query_parameters=bad_fields,
               before_record_response=filter_payload,
               filter_post_data_parameters=bad_fields,
               match_on=['path', 'method'])
Beispiel #24
0
def test_cassette_library_dir_with_path_transformer():
    library_dir = '/libary_dir'
    vcr = VCR(inject_cassette=True, cassette_library_dir=library_dir,
              path_transformer=lambda path: path + '.json')

    @vcr.use_cassette()
    def function_name(cassette):
        assert cassette._path == os.path.join(library_dir, 'function_name.json')

    function_name()
Beispiel #25
0
def authenticated_transport(app_uuid, client_uuid, credentials, record_mode,
                            vcr_cassette_dir, vcr_config):
    user_name, password = credentials
    transport = LuxMedTransport(user_name=user_name,
                                password=password,
                                app_uuid=app_uuid,
                                client_uuid=client_uuid)
    with VCR(cassette_library_dir=vcr_cassette_dir, record_mode=record_mode).\
            use_cassette('authenticated.yaml', **vcr_config):
        transport.authenticate()
    yield transport
Beispiel #26
0
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'
Beispiel #27
0
def get_recorder(**kw):
    defaults = dict(
        record_mode='once',
        cassette_library_dir=join(dirname(__file__), 'fixtures/cassettes'),
        path_transformer=VCR.ensure_suffix('.yaml'),
        match_on=['method', 'path', 'query'],
        filter_headers=['Authorization'],
        decode_compressed_response=True,
    )
    defaults.update(kw)
    return VCR(**defaults)
Beispiel #28
0
def test_inject_cassette():
    vcr = VCR(inject_cassette=True)
    @vcr.use_cassette('test', record_mode='once')
    def with_cassette_injected(cassette):
        assert cassette.record_mode == 'once'

    @vcr.use_cassette('test', record_mode='once', inject_cassette=False)
    def without_cassette_injected():
        pass

    with_cassette_injected()
    without_cassette_injected()
Beispiel #29
0
def use_cassette(vcr_cassette_dir, record_mode, markers, config):
    """Create a VCR instance and return an appropriate context manager for the given cassette configuration."""
    merged_config = merge_kwargs(config, markers)
    path_transformer = get_path_transformer(merged_config)
    vcr = VCR(path_transformer=path_transformer,
              cassette_library_dir=vcr_cassette_dir,
              record_mode=record_mode)
    # flatten the paths
    extra_paths = chain(*(marker[0] for marker in markers))
    persister = CombinedPersister(extra_paths)
    vcr.register_persister(persister)
    return vcr.use_cassette(markers[0][0][0], **merged_config)
def get_recorder(base_path=None, **kw):
    base_path = base_path or dirname(__file__)
    defaults = dict(
        record_mode="once",
        cassette_library_dir=join(base_path, "fixtures/cassettes"),
        path_transformer=VCR.ensure_suffix(".yaml"),
        match_on=["method", "path", "query"],
        filter_headers=["Authorization"],
        decode_compressed_response=True,
    )
    defaults.update(kw)
    return VCR(**defaults)