Python vcr.VCR Examples

The following are 13 code examples of vcr.VCR(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module vcr , or try the search function .
Example #1
Source File: conftest.py    From goodreads-api-client-python with MIT License 6 votes vote down vote up
def make_vcr():
    cassette_library_dir = os.path.join(os.path.dirname(__file__),
                                        'fixtures',
                                        'cassettes')
    return VCR(cassette_library_dir=cassette_library_dir,
               filter_query_parameters=[
                   'key',
                   'oauth_consumer_key',
                   'oauth_nonce',
                   'oauth_signature_method',
                   'oauth_timestamp',
                   'oauth_token',
                   'oauth_version',
                   'oauth_signature',
               ],
               record_mode='new_episodes') 
Example #2
Source File: testcase.py    From azure-cosmos-table-python with Apache License 2.0 6 votes vote down vote up
def recording(self):
        if TestMode.need_recording_file(self.test_mode):
            cassette_name = '{0}.yaml'.format(self.qualified_test_name)

            my_vcr = vcr.VCR(
                before_record_request = self._scrub_sensitive_request_info,
                before_record_response = self._scrub_sensitive_response_info,
                record_mode = 'none' if TestMode.is_playback(self.test_mode) else 'all' 
            )

            self.assertIsNotNone(self.working_folder)
            return my_vcr.use_cassette(
                os.path.join(self.working_folder, 'recordings', cassette_name),
                filter_headers=['authorization'],
            )
        else:
            @contextmanager
            def _nop_context_manager():
                yield
            return _nop_context_manager() 
Example #3
Source File: testcase.py    From azure-storage-python with MIT License 6 votes vote down vote up
def recording(self):
        if TestMode.need_recording_file(self.test_mode):
            cassette_name = '{0}.yaml'.format(self.qualified_test_name)

            my_vcr = vcr.VCR(
                before_record_request = self._scrub_sensitive_request_info,
                before_record_response = self._scrub_sensitive_response_info,
                record_mode = 'none' if TestMode.is_playback(self.test_mode) else 'all'
            )

            self.assertIsNotNone(self.working_folder)
            return my_vcr.use_cassette(
                os.path.join(self.working_folder, 'recordings', cassette_name),
                filter_headers=['authorization'],
            )
        else:
            @contextmanager
            def _nop_context_manager():
                yield
            return _nop_context_manager() 
Example #4
Source File: base.py    From knack with MIT License 5 votes vote down vote up
def __init__(self, cli, method_name, filter_headers=None):
        super(ScenarioTest, self).__init__(cli, method_name)
        self.name_replacer = GeneralNameReplacer()
        self.recording_processors = [LargeRequestBodyProcessor(),
                                     LargeResponseBodyProcessor(),
                                     self.name_replacer]
        self.replay_processors = [LargeResponseBodyReplacer()]
        self.filter_headers = filter_headers or []

        test_file_path = inspect.getfile(self.__class__)
        recordings_dir = find_recording_dir(test_file_path)
        live_test = os.environ.get(ENV_LIVE_TEST, None) == 'True'

        self.vcr = vcr.VCR(
            cassette_library_dir=recordings_dir,
            before_record_request=self._process_request_recording,
            before_record_response=self._process_response_recording,
            decode_compressed_response=True,
            record_mode='once' if not live_test else 'all',
            filter_headers=self.filter_headers
        )
        self.vcr.register_matcher('query', self._custom_request_query_matcher)

        self.recording_file = os.path.join(recordings_dir, '{}.yaml'.format(method_name))
        if live_test and os.path.exists(self.recording_file):
            os.remove(self.recording_file)

        self.in_recording = live_test or not os.path.exists(self.recording_file)
        self.test_resources_count = 0
        self.original_env = os.environ.copy() 
Example #5
Source File: __init__.py    From mendeley-python-sdk with Apache License 2.0 5 votes vote down vote up
def cassette(path):
    config = load_config()
    my_vcr = vcr.VCR()
    my_vcr.register_serializer('file', YamlFileSerializer())

    return my_vcr.use_cassette(path,
                               filter_headers=['authorization'],
                               record_mode=config['recordMode'],
                               serializer='file') 
Example #6
Source File: demo_theme.py    From ttrv with MIT License 5 votes vote down vote up
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


# Patch the getch method so we can display multiple notifications or
# other elements that require a keyboard input on the screen at the
# same time without blocking the main thread. 
Example #7
Source File: base.py    From azure-python-devtools with MIT License 5 votes vote down vote up
def __init__(self,  # pylint: disable=too-many-arguments
                 method_name, config_file=None, recording_dir=None, recording_name=None, recording_processors=None,
                 replay_processors=None, recording_patches=None, replay_patches=None):
        super(ReplayableTest, self).__init__(method_name)

        self.recording_processors = recording_processors or []
        self.replay_processors = replay_processors or []

        self.recording_patches = recording_patches or []
        self.replay_patches = replay_patches or []

        self.config = TestConfig(config_file=config_file)

        self.disable_recording = False

        test_file_path = inspect.getfile(self.__class__)
        recording_dir = recording_dir or os.path.join(os.path.dirname(test_file_path), 'recordings')
        self.is_live = self.config.record_mode

        self.vcr = vcr.VCR(
            cassette_library_dir=recording_dir,
            before_record_request=self._process_request_recording,
            before_record_response=self._process_response_recording,
            decode_compressed_response=True,
            record_mode='once' if not self.is_live else 'all',
            filter_headers=self.FILTER_HEADERS
        )
        self.vcr.register_matcher('query', self._custom_request_query_matcher)

        self.recording_file = os.path.join(
            recording_dir,
            '{}.yaml'.format(recording_name or method_name)
        )
        if self.is_live and os.path.exists(self.recording_file):
            os.remove(self.recording_file)

        self.in_recording = self.is_live or not os.path.exists(self.recording_file)
        self.test_resources_count = 0
        self.original_env = os.environ.copy() 
Example #8
Source File: test_base.py    From the-new-hotness with GNU Lesser General Public License v2.1 5 votes vote down vote up
def setUp(self):
        """Set a basic test environment.

        This simply starts recording a VCR on start-up and stops on tearDown.
        """
        cwd = os.path.dirname(os.path.realpath(__file__))
        my_vcr = vcr.VCR(
            cassette_library_dir=os.path.join(cwd, "request-data/"), record_mode="once"
        )
        self.vcr = my_vcr.use_cassette(self.id())
        self.vcr.__enter__()
        self.addCleanup(self.vcr.__exit__, None, None, None) 
Example #9
Source File: hello_world_vcenter_with_yaml_recorder.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = get_args()

    try:
        my_vcr = vcr.VCR()
        # use the vcr instance to setup an instance of service_instance
        with my_vcr.use_cassette('hello_world_vcenter.yaml',
                                 record_mode='all'):
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))
            # the recording will show up in the working directory

        atexit.register(connect.Disconnect, service_instance)

        print "\nHello World!\n"
        print "If you got here, you authenticted into vCenter."
        print "The server is {0}!".format(args.host)
        # NOTE (hartsock): only a successfully authenticated session has a
        # session key aka session id.
        session_id = service_instance.content.sessionManager.currentSession.key
        print "current session id: {0}".format(session_id)
        print "Well done!"
        print "\n"
        print "Download, learn and contribute back:"
        print "https://github.com/vmware/pyvmomi-community-samples"
        print "\n\n"

    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return -1

    return 0

# Start program 
Example #10
Source File: test_util.py    From fast_arrow with MIT License 5 votes vote down vote up
def gen_vcr():
    return vcr.VCR(
        cassette_library_dir='tests/fixtures_vcr',
        record_mode='none',
        match_on=['method', 'scheme', 'host', 'port', 'path', 'query'],
    ) 
Example #11
Source File: conftest.py    From rtv with MIT License 5 votes vote down vote up
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 
Example #12
Source File: demo_theme.py    From rtv with MIT License 5 votes vote down vote up
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


# Patch the getch method so we can display multiple notifications or
# other elements that require a keyboard input on the screen at the
# same time without blocking the main thread. 
Example #13
Source File: test_io.py    From civis-python with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def setUpClass(cls, *mocks):
        get_api_spec.cache_clear()
        generate_classes.cache_clear()

        setup_vcr = vcr.VCR(filter_headers=['Authorization'])
        setup_cassette = os.path.join(cassette_dir(), 'io_setup.yml')
        with setup_vcr.use_cassette(setup_cassette):
            # create a file
            buf = StringIO()
            buf.write('a,b,c\n1,2,3')
            buf.seek(0)
            file_id = civis.io.file_to_civis(buf, 'somename')
            cls.file_id = file_id

            # create the table. assumes this function works.
            sql = """
                DROP TABLE IF EXISTS scratch.api_client_test_fixture;

                CREATE TABLE scratch.api_client_test_fixture (
                    a int,
                    b int,
                    c int
                );

                INSERT INTO scratch.api_client_test_fixture
                VALUES (1,2,3);
            """
            res = civis.io.query_civis(sql, 'redshift-general',
                                       polling_interval=POLL_INTERVAL)
            res.result()  # block

            # create an export to check get_url. also tests export_csv
            with TemporaryDirectory() as temp_dir:
                fname = os.path.join(temp_dir, 'tempfile')
                sql = "SELECT * FROM scratch.api_client_test_fixture"
                database = 'redshift-general'
                result = civis.io.civis_to_csv(fname, sql, database,
                                               polling_interval=POLL_INTERVAL)
                result = result.result()
                cls.export_url = result['output'][0]['path']
                assert result.state == 'succeeded'

            cls.export_job_id = result.sql_id