예제 #1
0
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
예제 #2
0
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"
예제 #3
0
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'
예제 #4
0
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
예제 #5
0
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
예제 #6
0
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 == []
예제 #7
0
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
예제 #8
0
def test_cassette_allow_playback_repeats():
    a = Cassette("test", allow_playback_repeats=True)
    a.append("foo", "bar")
    a.append("other", "resp")
    for x in range(10):
        assert a.play_response("foo") == "bar"
    assert a.play_count == 10
    assert a.all_played is False
    assert a.play_response("other") == "resp"
    assert a.play_count == 11
    assert a.all_played

    a.allow_playback_repeats = False
    with pytest.raises(UnhandledHTTPRequestError) as e:
        a.play_response("foo")
    assert str(
        e.value
    ) == "\"The cassette ('test') doesn't contain the request ('foo') asked for\""
    a.rewind()
    assert a.all_played is False
    assert a.play_response("foo") == "bar"
    assert a.all_played is False
    assert a.play_response("other") == "resp"
    assert a.all_played
예제 #9
0
def test_cassette_not_all_played():
    a = Cassette("test")
    a.append("foo", "bar")
    assert not a.all_played
예제 #10
0
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')
예제 #11
0
def test_cassette_responses_of():
    a = Cassette('test')
    a.append('foo', 'bar')
    assert a.responses_of('foo') == ['bar']
예제 #12
0
def test_cassette_contains():
    a = Cassette('test')
    a.append('foo', 'bar')
    assert 'foo' in a
예제 #13
0
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
예제 #14
0
def test_cassette_get_missing_response():
    a = Cassette("test")
    with pytest.raises(UnhandledHTTPRequestError):
        a.responses_of("foo")
예제 #15
0
def test_cassette_append():
    a = Cassette("test")
    a.append("foo", "bar")
    assert a.requests == ["foo"]
    assert a.responses == ["bar"]
예제 #16
0
def test_cassette_get_missing_response():
    a = Cassette('test')
    with pytest.raises(KeyError):
        a.response_of('foo')
예제 #17
0
파일: test_stubs.py 프로젝트: zh010zh/vcrpy
 def testing_connect(*args):
     vcr_connection = VCRHTTPSConnection("www.google.com")
     vcr_connection.cassette = Cassette("test", record_mode=mode.ALL)
     vcr_connection.real_connection.connect()
     assert vcr_connection.real_connection.sock is not None
예제 #18
0
def test_cassette_all_played():
    a = Cassette("test")
    a.append("foo", "bar")
    a.play_response("foo")
    assert a.all_played
예제 #19
0
def test_cassette_contains():
    a = Cassette("test")
    a.append("foo", "bar")
    assert "foo" in a
예제 #20
0
def test_cassette_not_all_played():
    a = Cassette('test')
    a.append('foo', 'bar')
    assert not a.all_played
예제 #21
0
 def testing_connect(*args):
     vcr_connection = VCRHTTPSConnection('www.google.com')
     vcr_connection.cassette = Cassette('test', record_mode='all')
     vcr_connection.real_connection.connect()
     assert vcr_connection.real_connection.sock is not None
예제 #22
0
def test_cassette_not_played():
    a = Cassette("test")
    assert not a.play_count
예제 #23
0
def test_cassette_all_played():
    a = Cassette('test')
    a.append('foo', 'bar')
    a.play_response('foo')
    assert a.all_played
예제 #24
0
def test_cassette_len():
    a = Cassette("test")
    a.append("foo", "bar")
    a.append("foo2", "bar2")
    assert len(a) == 2
예제 #25
0
def test_cassette_append():
    a = Cassette('test')
    a.append('foo', 'bar')
    assert a.requests == ['foo']
    assert a.responses == ['bar']
예제 #26
0
def test_cassette_responses_of():
    a = Cassette("test")
    a.append("foo", "bar")
    assert a.responses_of("foo") == ["bar"]
예제 #27
0
def test_cassette_len():
    a = Cassette('test')
    a.append('foo', 'bar')
    a.append('foo2', 'bar2')
    assert len(a) == 2
예제 #28
0
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")
예제 #29
0
def test_cassette_played():
    a = Cassette('test')
    a.mark_played('foo')
    a.mark_played('foo')
    assert a.play_count == 2