def test_nesting_cassette_context_managers(*args): first_response = { "body": { "string": b"first_response" }, "headers": {}, "status": { "message": "m", "code": 200 }, } second_response = copy.deepcopy(first_response) second_response["body"]["string"] = b"second_response" with contextlib.ExitStack() as exit_stack: first_cassette = exit_stack.enter_context(Cassette.use(path="test")) exit_stack.enter_context( mock.patch.object(first_cassette, "play_response", return_value=first_response)) assert_get_response_body_is("first_response") # Make sure a second cassette can supercede the first with Cassette.use(path="test") as second_cassette: with mock.patch.object(second_cassette, "play_response", return_value=second_response): assert_get_response_body_is("second_response") # Now the first cassette should be back in effect assert_get_response_body_is("first_response")
def test_before_record_response(): before_record_response = mock.Mock(return_value="mutated") cassette = Cassette("test", before_record_response=before_record_response) cassette.append("req", "res") before_record_response.assert_called_once_with("res") assert cassette.responses[0] == "mutated"
def test_before_record_response(): before_record_response = mock.Mock(return_value='mutated') cassette = Cassette('test', before_record_response=before_record_response) cassette.append('req', 'res') before_record_response.assert_called_once_with('res') assert cassette.responses[0] == 'mutated'
def test_nesting_cassette_context_managers(*args): first_response = { 'body': { 'string': b'first_response' }, 'headers': {}, 'status': { 'message': 'm', 'code': 200 } } second_response = copy.deepcopy(first_response) second_response['body']['string'] = b'second_response' with contextlib2.ExitStack() as exit_stack: first_cassette = exit_stack.enter_context(Cassette.use('test')) exit_stack.enter_context( mock.patch.object(first_cassette, 'play_response', return_value=first_response)) assert_get_response_body_is('first_response') # Make sure a second cassette can supercede the first with Cassette.use('test') as second_cassette: with mock.patch.object(second_cassette, 'play_response', return_value=second_response): assert_get_response_body_is('second_response') # Now the first cassette should be back in effect assert_get_response_body_is('first_response')
def test_serialize_cassette(self): c1 = Cassette() c1.requests = ['a', 'b', 'c'] c1.responses = ['d', 'e', 'f'] ser = c1.serialize() c2 = Cassette(ser) self.assertEqual(c1.requests, c2.requests) self.assertEqual(c1.responses, c2.responses)
def test_find_requests_with_most_matches_no_similar_requests(mock_get_matchers_results): mock_get_matchers_results.side_effect = [ ([], [("path", "failed : path"), ("query", "failed : query")]), ([], [("path", "failed : path"), ("query", "failed : query")]), ([], [("path", "failed : path"), ("query", "failed : query")]), ] cassette = Cassette("test") for request in range(1, 4): cassette.append(request, 'response') result = cassette.find_requests_with_most_matches("fake request") assert result == []
def test_nesting_context_managers_by_checking_references_of_http_connection(): original = httplib.HTTPConnection with Cassette.use(path='test'): first_cassette_HTTPConnection = httplib.HTTPConnection with Cassette.use(path='test'): second_cassette_HTTPConnection = httplib.HTTPConnection assert second_cassette_HTTPConnection is not first_cassette_HTTPConnection with Cassette.use(path='test'): assert httplib.HTTPConnection is not second_cassette_HTTPConnection with force_reset(): assert httplib.HTTPConnection is original assert httplib.HTTPConnection is second_cassette_HTTPConnection assert httplib.HTTPConnection is first_cassette_HTTPConnection
def test_nesting_context_managers_by_checking_references_of_http_connection(): original = httplib.HTTPConnection with Cassette.use(path="test"): first_cassette_HTTPConnection = httplib.HTTPConnection with Cassette.use(path="test"): second_cassette_HTTPConnection = httplib.HTTPConnection assert second_cassette_HTTPConnection is not first_cassette_HTTPConnection with Cassette.use(path="test"): assert httplib.HTTPConnection is not second_cassette_HTTPConnection with force_reset(): assert httplib.HTTPConnection is original assert httplib.HTTPConnection is second_cassette_HTTPConnection assert httplib.HTTPConnection is first_cassette_HTTPConnection
def test_cassette_rewound(): a = Cassette('test') a.append('foo', 'bar') a.play_response('foo') assert a.all_played a.rewind() assert not a.all_played
def test_cassette_rewound(): a = Cassette("test") a.append("foo", "bar") a.play_response("foo") assert a.all_played a.rewind() assert not a.all_played
def execute_request( url: str, method: str = 'get', headers: Dict = {}, params: Dict = {}, json: Dict = {}, recorder: Optional[vcr.VCR] = recorder, cassette_path: str = '', logger: Optional[MyLogger] = None ) -> Tuple[requests.models.Response, bool]: """ Execute a HTTP request and return response defined by the `requests` package. """ if logger: logger.logger.info('execute_request {} {}'.format( recorder, cassette_path)) is_cached = False method_func = requests.__getattribute__(method.lower()) if cassette_path and recorder: from vcr.cassette import Cassette from vcr.request import Request logger.logger.info('imported vcr') req = Request(method.upper(), url, 'irrelevant body?', {'some': 'header'}) logger.logger.info('req ' + str(req)) c_path = os.path.join(recorder.cassette_library_dir, cassette_path) logger.logger.info(c_path) logger.logger.info(Cassette(None).load(path=c_path)) if req in Cassette(None).load(path=c_path): is_cached = True with recorder.use_cassette(c_path): logger.logger.info('running...') if json: resp = method_func(url, headers=headers, params=params, json=json) else: resp = method_func(url, headers=headers, params=params) logger.logger.info('got it...') else: if json: resp = method_func(url, headers=headers, params=params, json=json) else: resp = method_func(url, headers=headers, params=params) # FIXME: requests.post('http://httpbin.org/post', json={"key": "value"}) return resp, is_cached
def test_cassette_load(tmpdir): a_file = tmpdir.join('test_cassette.yml') a_file.write(yaml.dump([ {'request': 'foo', 'response': 'bar'} ])) a_cassette = Cassette.load(str(a_file)) assert len(a_cassette) == 1
def test_arg_getter_functionality(): arg_getter = mock.Mock(return_value={'path': 'test'}) context_decorator = Cassette.use_arg_getter(arg_getter) with context_decorator as cassette: assert cassette._path == 'test' arg_getter.return_value = {'path': 'other'} with context_decorator as cassette: assert cassette._path == 'other' arg_getter.return_value = { 'path': 'other', 'filter_headers': ('header_name', ) } @context_decorator def function(): pass with mock.patch.object( Cassette, 'load', return_value=mock.MagicMock(inject=False)) as cassette_load: function() cassette_load.assert_called_once_with(**arg_getter.return_value)
def test_arg_getter_functionality(): arg_getter = mock.Mock(return_value={"path": "test"}) context_decorator = Cassette.use_arg_getter(arg_getter) with context_decorator as cassette: assert cassette._path == "test" arg_getter.return_value = {"path": "other"} with context_decorator as cassette: assert cassette._path == "other" arg_getter.return_value = { "path": "other", "filter_headers": ("header_name", ) } @context_decorator def function(): pass with mock.patch.object( Cassette, "load", return_value=mock.MagicMock(inject=False)) as cassette_load: function() cassette_load.assert_called_once_with(**arg_getter.return_value)
def test_cassette_load(tmpdir): a_file = tmpdir.join('test_cassette.yml') a_file.write(yaml.dump({'interactions': [ {'request': {'body': '', 'uri': 'foo', 'method': 'GET', 'headers': {}}, 'response': 'bar'} ]})) a_cassette = Cassette.load(str(a_file)) assert len(a_cassette) == 1
def test_cassette_load(tmpdir): a_file = tmpdir.join('test_cassette.yml') a_file.write(yaml.dump({'interactions': [ {'request': {'body': '', 'uri': 'foo', 'method': 'GET', 'headers': {}}, 'response': 'bar'} ]})) a_cassette = Cassette.load(path=str(a_file)) assert len(a_cassette) == 1
def test_custom_patchers(): class Test(object): attribute = None with Cassette.use(path="custom_patches", custom_patches=((Test, "attribute", VCRHTTPSConnection),)): assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute old_attribute = Test.attribute with Cassette.use(path="custom_patches", custom_patches=((Test, "attribute", VCRHTTPSConnection),)): assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute assert Test.attribute is not old_attribute assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute assert Test.attribute is old_attribute
def test_custom_patchers(): class Test(object): attribute = None with Cassette.use(path='custom_patches', custom_patches=((Test, 'attribute', VCRHTTPSConnection),)): assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute old_attribute = Test.attribute with Cassette.use(path='custom_patches', custom_patches=((Test, 'attribute', VCRHTTPSConnection),)): assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute assert Test.attribute is not old_attribute assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute assert Test.attribute is old_attribute
def test_nesting_cassette_context_managers(*args): first_response = {"body": {"string": b"first_response"}, "headers": {}, "status": {"message": "m", "code": 200}} second_response = copy.deepcopy(first_response) second_response["body"]["string"] = b"second_response" with contextlib.ExitStack() as exit_stack: first_cassette = exit_stack.enter_context(Cassette.use(path="test")) exit_stack.enter_context(mock.patch.object(first_cassette, "play_response", return_value=first_response)) assert_get_response_body_is("first_response") # Make sure a second cassette can supercede the first with Cassette.use(path="test") as second_cassette: with mock.patch.object(second_cassette, "play_response", return_value=second_response): assert_get_response_body_is("second_response") # Now the first cassette should be back in effect assert_get_response_body_is("first_response")
def request_has_matches(cassette_path, flask_request): cassette_requests = Request(method=flask_request.method, uri=request.url, body=flask_request.data, headers=flask_request.headers) with set_underlying_vcr_logging_level(): cassette = Cassette.load(path=cassette_path, match_on=(extended_vcr_body_matcher, extended_query_matcher, method, extended_vcr_body_matcher)) for matches in cassette.find_requests_with_most_matches(cassette_requests): *_, failure = matches if not failure: return True return False
def test_nesting_cassette_context_managers(*args): first_response = {'body': {'string': b'first_response'}, 'headers': {}, 'status': {'message': 'm', 'code': 200}} second_response = copy.deepcopy(first_response) second_response['body']['string'] = b'second_response' with contextlib.ExitStack() as exit_stack: first_cassette = exit_stack.enter_context(Cassette.use(path='test')) exit_stack.enter_context(mock.patch.object(first_cassette, 'play_response', return_value=first_response)) assert_get_response_body_is('first_response') # Make sure a second cassette can supercede the first with Cassette.use(path='test') as second_cassette: with mock.patch.object(second_cassette, 'play_response', return_value=second_response): assert_get_response_body_is('second_response') # Now the first cassette should be back in effect assert_get_response_body_is('first_response')
def test_cassette_load(tmpdir): a_file = tmpdir.join("test_cassette.yml") a_file.write( yaml.dump( { "interactions": [ {"request": {"body": "", "uri": "foo", "method": "GET", "headers": {}}, "response": "bar"} ] } ) ) a_cassette = Cassette.load(path=str(a_file)) assert len(a_cassette) == 1
def test_CannotOverwriteExistingCassetteException_get_message( mock_find_requests_with_most_matches, most_matches, expected_message): mock_find_requests_with_most_matches.return_value = most_matches cassette = Cassette("path") failed_request = "request" exception_message = errors.CannotOverwriteExistingCassetteException._get_message( cassette, "request") expected = ( "Can't overwrite existing cassette (%r) in your current record mode (%r).\n" "No match for the request (%r) was found.\n" "%s" % (cassette._path, cassette.record_mode, failed_request, expected_message)) assert exception_message == expected
def test_cassette_load(tmpdir): a_file = tmpdir.join("test_cassette.yml") a_file.write( yaml.dump({ "interactions": [{ "request": { "body": "", "uri": "foo", "method": "GET", "headers": {} }, "response": "bar" }] })) a_cassette = Cassette.load(path=str(a_file)) assert len(a_cassette) == 1
def __init__(self, cassette_path: str): config = vcr.get_merged_config() config.pop("path_transformer") config.pop("func_path_generator") self.vcrpy_cassette = Cassette.load(path=cassette_path, **config) self._host = None for request in self.vcrpy_cassette.requests: parsed_url = urlparse(request.uri) current_interaction_request_host = ( f"{parsed_url.scheme}://{parsed_url.netloc}") if current_interaction_request_host != self._host and self._host != None: raise MultipleHostsInCassette( "More than one host found in cassette interactions") if self._host == None: self._host = current_interaction_request_host
def test_arg_getter_functionality(): arg_getter = mock.Mock(return_value={"path": "test"}) context_decorator = Cassette.use_arg_getter(arg_getter) with context_decorator as cassette: assert cassette._path == "test" arg_getter.return_value = {"path": "other"} with context_decorator as cassette: assert cassette._path == "other" arg_getter.return_value = {"path": "other", "filter_headers": ("header_name",)} @context_decorator def function(): pass with mock.patch.object(Cassette, "load", return_value=mock.MagicMock(inject=False)) as cassette_load: function() cassette_load.assert_called_once_with(**arg_getter.return_value)
def test_arg_getter_functionality(): arg_getter = mock.Mock(return_value=('test', {})) context_decorator = Cassette.use_arg_getter(arg_getter) with context_decorator as cassette: assert cassette._path == 'test' arg_getter.return_value = ('other', {}) with context_decorator as cassette: assert cassette._path == 'other' arg_getter.return_value = ('', {'filter_headers': ('header_name', )}) @context_decorator def function(): pass with mock.patch.object(Cassette, 'load') as cassette_load: function() cassette_load.assert_called_once_with(arg_getter.return_value[0], **arg_getter.return_value[1])
def test_arg_getter_functionality(): arg_getter = mock.Mock(return_value={'path': 'test'}) context_decorator = Cassette.use_arg_getter(arg_getter) with context_decorator as cassette: assert cassette._path == 'test' arg_getter.return_value = {'path': 'other'} with context_decorator as cassette: assert cassette._path == 'other' arg_getter.return_value = {'path': 'other', 'filter_headers': ('header_name',)} @context_decorator def function(): pass with mock.patch.object( Cassette, 'load', return_value=mock.MagicMock(inject=False) ) as cassette_load: function() cassette_load.assert_called_once_with(**arg_getter.return_value)
def test_cassette_contains(): a = Cassette("test") a.append("foo", "bar") assert "foo" in a
def test_path_transformer_with_context_manager(): with Cassette.use( path='b', path_transformer=lambda *args: 'a' ) as cassette: assert cassette._path == 'a'
def test_cassette_responses_of(): a = Cassette("test") a.append("foo", "bar") assert a.responses_of("foo") == ["bar"]
def test_cassette_len(): a = Cassette("test") a.append("foo", "bar") a.append("foo2", "bar2") assert len(a) == 2
def test_cassette_not_played(): a = Cassette("test") assert not a.play_count
def test_path_transformer_with_context_manager(): with Cassette.use(path="b", path_transformer=lambda *args: "a") as cassette: assert cassette._path == "a"
def test_cassette_all_played(): a = Cassette('test') a.append('foo', 'bar') a.play_response('foo') assert a.all_played
def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times(*args): decorated_function = Cassette.use(path='test')(make_get_request) for i in range(4): decorated_function()
def test_cassette_cant_read_same_request_twice(): a = Cassette('test') a.append('foo', 'bar') a.play_response('foo') with pytest.raises(UnhandledHTTPRequestError): a.play_response('foo')
def test_cassette_get_missing_response(): a = Cassette('test') with pytest.raises(UnhandledHTTPRequestError): a.responses_of('foo')
def test_cassette_responses_of(): a = Cassette('test') a.append('foo', 'bar') assert a.responses_of('foo') == ['bar']
def test_cassette_contains(): a = Cassette('test') a.append('foo', 'bar') assert 'foo' in a
def test_cassette_len(): a = Cassette('test') a.append('foo', 'bar') a.append('foo2', 'bar2') assert len(a) == 2
def test_cassette_append(): a = Cassette('test') a.append('foo', 'bar') assert a.requests == ['foo'] assert a.responses == ['bar']
def test_cassette_played(): a = Cassette('test') a.mark_played('foo') a.mark_played('foo') assert a.play_count == 2
def test_cassette_cant_read_same_request_twice(): a = Cassette("test") a.append("foo", "bar") a.play_response("foo") with pytest.raises(UnhandledHTTPRequestError): a.play_response("foo")
def test_cassette_not_all_played(): a = Cassette('test') a.append('foo', 'bar') assert not a.all_played
def test_cassette_play_counter(): a = Cassette('test') a.mark_played('foo') a.mark_played('bar') assert a.play_counts['foo'] == 1 assert a.play_counts['bar'] == 1
def test_path_transformer_None(): with Cassette.use(path="a", path_transformer=None) as cassette: assert cassette._path == "a"
def test_cassette_append(): a = Cassette("test") a.append("foo", "bar") assert a.requests == ["foo"] assert a.responses == ["bar"]
def test_cassette_all_played(): a = Cassette("test") a.append("foo", "bar") a.play_response("foo") assert a.all_played
def test_cassette_get_missing_response(): a = Cassette("test") with pytest.raises(UnhandledHTTPRequestError): a.responses_of("foo")
def test_path_transformer_None(): with Cassette.use( path='a', path_transformer=None, ) as cassette: assert cassette._path == 'a'
def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times( *args): decorated_function = Cassette.use(path="test")(make_get_request) for i in range(4): decorated_function()
def test_cassette_get_missing_response(): a = Cassette('test') with pytest.raises(KeyError): a.response_of('foo')