Beispiel #1
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 #2
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 #3
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 #4
0
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
Beispiel #5
0
 def setup_teardown(
     self,
     custom_vcr: VCR,
     smartsheet: Smartsheet,
     sheet_to_update: Sheet,
     rows_data: List[Dict[str, Any]],
 ) -> None:
     with custom_vcr.use_cassette("test_sheets/update_sheet_setup.yaml"):
         new_sheet = create_sheet_with_rows(smartsheet, sheet_to_update,
                                            rows_data)
     yield
     with custom_vcr.use_cassette("test_sheets/update_sheet_teardown.yaml"):
         smartsheet.sheets.delete(id=new_sheet.id)
Beispiel #6
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
Beispiel #7
0
def test_custom_patchers():
    class Test:
        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
Beispiel #8
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 #9
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 #10
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 #11
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)
Beispiel #12
0
def test_vcr_path_transformer():
    # Regression test for #199

    # Prevent actually saving the cassette
    with mock.patch("vcr.cassette.FilesystemPersister.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 os.path.abspath(
                cassette._path) == os.path.abspath("/foo/test")
Beispiel #13
0
 def _decorate_test(self, test_path):
     recorder = VCR(
         before_record_request=self._before_record,
         record_mode=os.environ.get('VCR_MODE', 'none'),
         cassette_library_dir=join(test_path, 'fixtures/cassettes'),
         path_transformer=VCR.ensure_suffix('.yaml'),
         filter_headers=['Authorization'],
     )
     for test_func in dir(self):
         if test_func.startswith('test'):
             setattr(self, test_func,
                     recorder.use_cassette(getattr(self, test_func)))
Beispiel #14
0
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
Beispiel #15
0
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
Beispiel #16
0
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.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
Beispiel #17
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 #18
0
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
Beispiel #19
0
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.FilesystemPersister.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
Beispiel #20
0
    def __new__(cls, name, bases, members):
        test_path = members['_test_path']

        # decorate test method with the cassette
        klass = type.__new__(cls, name, bases, members)
        for name, val in inspect.getmembers(klass, inspect.ismethod):
            if name.startswith('test'):
                recorder = VCR(
                    before_record_request=_before_record,
                    record_mode=os.environ.get('VCR_MODE', 'none'),
                    cassette_library_dir=join(test_path, 'fixtures/cassettes'),
                    path_transformer=VCR.ensure_suffix('.yaml'),
                    filter_headers=['Authorization'],
                )
                val = recorder.use_cassette(val)
                setattr(klass, name, val)
        return klass
Beispiel #21
0
def recorder(request):
    """Generate and start a recorder using a helium.Client."""
    cassette_name = ''

    if request.module is not None:
        cassette_name += request.module.__name__ + '.'

    cassette_name += request.function.__name__

    recorder = VCR(
        cassette_library_dir=RECORD_FOLDER,
        decode_compressed_response=True,
        path_transformer=VCR.ensure_suffix('.yml'),
        filter_headers=['Authorization'],
        match_on=['uri', 'method'],
    )
    cassette = recorder.use_cassette(path=cassette_name)
    with cassette:
        yield recorder
Beispiel #22
0
def use_cassette(
    default_cassette: str,
    vcr_cassette_dir: str,
    record_mode: str,
    markers: List[Mark],
    config: ConfigType,
    pytestconfig: Config,
) -> CassetteContextDecorator:
    """Create a VCR instance and return an appropriate context manager for the given cassette configuration."""
    merged_config = merge_kwargs(config, markers)
    if "record_mode" in merged_config:
        record_mode = merged_config["record_mode"]
    path_transformer = get_path_transformer(merged_config)
    if record_mode == "rewrite":
        path = path_transformer(
            os.path.join(vcr_cassette_dir, default_cassette))
        try:
            os.remove(path)
        except OSError:
            pass
        record_mode = "new_episodes"
    vcr = VCR(path_transformer=path_transformer,
              cassette_library_dir=vcr_cassette_dir,
              record_mode=record_mode)

    def extra_path_transformer(path: str) -> str:
        """Paths in extras can be handled as relative and as absolute.

        Relative paths will be checked in `vcr_cassette_dir`.
        """
        if not os.path.isabs(path):
            return os.path.join(vcr_cassette_dir, path)
        return path

    extra_paths = [
        extra_path_transformer(path) for marker in markers
        for path in marker.args
    ]
    persister = CombinedPersister(extra_paths)
    vcr.register_persister(persister)
    pytestconfig.hook.pytest_recording_configure(config=pytestconfig, vcr=vcr)
    return vcr.use_cassette(default_cassette, **merged_config)
Beispiel #23
0
"""Defines all test wide settings and variables"""
from os import environ

from domaintools import API
from vcr import VCR


def remove_server(response):
    response.get('headers', {}).pop('server', None)
    return response


vcr = VCR(before_record_response=remove_server, filter_query_parameters=['api_key', 'api_username'],
          cassette_library_dir='tests/fixtures/vcr/', path_transformer=VCR.ensure_suffix('.yaml'),
          record_mode='new_episodes')
with vcr.use_cassette('init_user_account'):
    api = API(environ.get('TEST_USER', 'test_user'), environ.get('TEST_KEY', 'test_key'))
Beispiel #24
-1
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