Ejemplo n.º 1
0
    def getresponse(self, _=False, **kwargs):
        '''Retrieve the response'''
        # Check to see if the cassette has a response for this request. If so,
        # then return it
        if self.cassette.can_play_response_for(self._vcr_request):
            log.info(
                "Playing response for {0} from cassette".format(
                    self._vcr_request
                )
            )
            response = self.cassette.play_response(self._vcr_request)
            return VCRHTTPResponse(response)
        else:
            if self.cassette.write_protected and self.cassette.filter_request(
                self._vcr_request
            ):
                raise CannotOverwriteExistingCassetteException(
                    "No match for the request (%r) was found. "
                    "Can't overwrite existing cassette (%r) in "
                    "your current record mode (%r)."
                    % (self._vcr_request, self.cassette._path,
                       self.cassette.record_mode)
                )

            # Otherwise, we should send the request, then get the response
            # and return it.

            log.info(
                "{0} not in cassette, sending to real server".format(
                    self._vcr_request
                )
            )
            # This is imported here to avoid circular import.
            # TODO(@IvanMalison): Refactor to allow normal import.
            from vcr.patch import force_reset
            with force_reset():
                self.real_connection.request(
                    method=self._vcr_request.method,
                    url=self._url(self._vcr_request.uri),
                    body=self._vcr_request.body,
                    headers=self._vcr_request.headers,
                )

            # get the response
            response = self.real_connection.getresponse()

            # put the response into the cassette
            response = {
                'status': {
                    'code': response.status,
                    'message': response.reason
                },
                'headers': serialize_headers(response),
                'body': {'string': response.read()},
            }
            self.cassette.append(self._vcr_request, response)
        return VCRHTTPResponse(response)
Ejemplo n.º 2
0
def _shared_vcr_send(cassette, real_send, *args, **kwargs):
    real_request = args[1]

    vcr_request = _make_vcr_request(real_request, **kwargs)

    if cassette.can_play_response_for(vcr_request):
        return vcr_request, _play_responses(cassette, real_request,
                                            vcr_request, args[0], kwargs)

    if cassette.write_protected and cassette.filter_request(vcr_request):
        raise CannotOverwriteExistingCassetteException(
            cassette=cassette, failed_request=vcr_request)

    _logger.info("%s not in cassette, sending to real server", vcr_request)
    return vcr_request, None
Ejemplo n.º 3
0
    def getresponse(self, _=False, **kwargs):
        """Retrieve the response"""
        # Check to see if the cassette has a response for this request. If so,
        # then return it
        if self.cassette.can_play_response_for(self._vcr_request):
            log.info("Playing response for {} from cassette".format(
                self._vcr_request))
            response = self.cassette.play_response(self._vcr_request)
            return VCRHTTPResponse(response)
        else:
            if self.cassette.write_protected and self.cassette.filter_request(
                    self._vcr_request):
                raise CannotOverwriteExistingCassetteException(
                    cassette=self.cassette, failed_request=self._vcr_request)

            # Otherwise, we should send the request, then get the response
            # and return it.

            log.info("{} not in cassette, sending to real server".format(
                self._vcr_request))
            # This is imported here to avoid circular import.
            # TODO(@IvanMalison): Refactor to allow normal import.
            from vcr.patch import force_reset

            with force_reset():
                self.real_connection.request(
                    method=self._vcr_request.method,
                    url=self._url(self._vcr_request.uri),
                    body=self._vcr_request.body,
                    headers=self._vcr_request.headers,
                )

            # get the response
            response = self.real_connection.getresponse()

            # put the response into the cassette
            response = {
                "status": {
                    "code": response.status,
                    "message": response.reason
                },
                "headers": serialize_headers(response),
                "body": {
                    "string": response.read()
                },
            }
            self.cassette.append(self._vcr_request, response)
        return VCRHTTPResponse(response)
Ejemplo n.º 4
0
    def getresponse(self, _=False):
        '''Retrieve a the response'''
        # Check to see if the cassette has a response for this request. If so,
        # then return it
        if self._vcr_request in self.cassette and \
                self.cassette.record_mode != "all" and \
                self.cassette.rewound:
            response = self.cassette.play_response(self._vcr_request)
            return VCRHTTPResponse(response)
        else:
            if self.cassette.write_protected:
                raise CannotOverwriteExistingCassetteException(
                    "Can't overwrite existing cassette (%r) in "
                    "your current record mode (%r)." %
                    (self.cassette._path, self.cassette.record_mode))

            # Otherwise, we should send the request, then get the response
            # and return it.

        # restore sock's value to None, since we need a real socket
            self._restore_socket()

            #make the actual request
            self._baseclass.request(self,
                                    method=self._vcr_request.method,
                                    url=self._vcr_request.path,
                                    body=self._vcr_request.body,
                                    headers=dict(self._vcr_request.headers
                                                 or {}))

            # get the response
            response = self._baseclass.getresponse(self)

            # put the response into the cassette
            response = {
                'status': {
                    'code': response.status,
                    'message': response.reason
                },
                'headers': response.msg.headers,
                'body': {
                    'string': response.read()
                },
            }
            self.cassette.append(self._vcr_request, response)
        return VCRHTTPResponse(response)
Ejemplo n.º 5
0
    async def new_request(self, method, url, **kwargs):
        headers = kwargs.get("headers")
        auth = kwargs.get("auth")
        headers = self._prepare_headers(headers)
        data = kwargs.get("data", kwargs.get("json"))
        params = kwargs.get("params")
        cookies = kwargs.get("cookies")

        if auth is not None:
            headers["AUTHORIZATION"] = auth.encode()

        request_url = URL(url)
        if params:
            for k, v in params.items():
                params[k] = str(v)
            request_url = URL(url).with_query(params)

        c_header = headers.pop(hdrs.COOKIE, None)
        cookie_header = _build_cookie_header(self, cookies, c_header,
                                             request_url)
        if cookie_header:
            headers[hdrs.COOKIE] = cookie_header

        vcr_request = Request(method, str(request_url), data,
                              _serialize_headers(headers))

        if cassette.can_play_response_for(vcr_request):
            log.info(
                "Playing response for {} from cassette".format(vcr_request))
            response = play_responses(cassette, vcr_request)
            for redirect in response.history:
                self._cookie_jar.update_cookies(redirect.cookies, redirect.url)
            self._cookie_jar.update_cookies(response.cookies, response.url)
            return response

        if cassette.write_protected and cassette.filter_request(vcr_request):
            raise CannotOverwriteExistingCassetteException(
                cassette=cassette, failed_request=vcr_request)

        log.info("%s not in cassette, sending to real server", vcr_request)

        response = await real_request(self, method, url,
                                      **kwargs)  # NOQA: E999
        await record_responses(cassette, vcr_request, response)
        return response
Ejemplo n.º 6
0
    def new_fetch_impl(self, request, callback):
        headers = request.headers.copy()
        if request.user_agent:
            headers.setdefault('User-Agent', request.user_agent)

        # TODO body_producer, header_callback, and streaming_callback are not
        # yet supported.

        unsupported_call = (request.body_producer is not None
                            or request.header_callback is not None
                            or request.streaming_callback is not None)
        if unsupported_call:
            response = HTTPResponse(
                request,
                599,
                error=Exception(
                    "The request (%s) uses AsyncHTTPClient functionality "
                    "that is not yet supported by VCR.py. Please make the "
                    "request outside a VCR.py context." % repr(request)),
                request_time=self.io_loop.time() - request.start_time,
            )
            return callback(response)

        vcr_request = Request(
            request.method,
            request.url,
            request.body,
            headers,
        )

        if cassette.can_play_response_for(vcr_request):
            vcr_response = cassette.play_response(vcr_request)
            headers = httputil.HTTPHeaders()

            recorded_headers = vcr_response['headers']
            if isinstance(recorded_headers, dict):
                recorded_headers = recorded_headers.items()
            for k, vs in recorded_headers:
                for v in vs:
                    headers.add(k, v)
            response = HTTPResponse(
                request,
                code=vcr_response['status']['code'],
                reason=vcr_response['status']['message'],
                headers=headers,
                buffer=BytesIO(vcr_response['body']['string']),
                effective_url=vcr_response.get('url'),
                request_time=self.io_loop.time() - request.start_time,
            )
            return callback(response)
        else:
            if cassette.write_protected and cassette.filter_request(
                    vcr_request):
                response = HTTPResponse(
                    request,
                    599,
                    error=CannotOverwriteExistingCassetteException(
                        "No match for the request (%r) was found. "
                        "Can't overwrite existing cassette (%r) in "
                        "your current record mode (%r)." %
                        (vcr_request, cassette._path, cassette.record_mode)),
                    request_time=self.io_loop.time() - request.start_time,
                )
                return callback(response)

            def new_callback(response):
                headers = [(k, response.headers.get_list(k))
                           for k in response.headers.keys()]

                vcr_response = {
                    'status': {
                        'code': response.code,
                        'message': response.reason,
                    },
                    'headers': headers,
                    'body': {
                        'string': response.body
                    },
                    'url': response.effective_url,
                }
                cassette.append(vcr_request, vcr_response)
                return callback(response)

            real_fetch_impl(self, request, new_callback)
    def new_fetch_impl(self, request, callback):
        headers = request.headers.copy()
        if request.user_agent:
            headers.setdefault("User-Agent", request.user_agent)

        # TODO body_producer, header_callback, and streaming_callback are not
        # yet supported.

        unsupported_call = (getattr(request, "body_producer", None) is not None
                            or request.header_callback is not None
                            or request.streaming_callback is not None)
        if unsupported_call:
            response = HTTPResponse(
                request,
                599,
                error=Exception(
                    "The request (%s) uses AsyncHTTPClient functionality "
                    "that is not yet supported by VCR.py. Please make the "
                    "request outside a VCR.py context." % repr(request)),
                request_time=self.io_loop.time() - request.start_time,
            )
            return callback(response)

        vcr_request = Request(request.method, request.url, request.body,
                              headers)

        if cassette.can_play_response_for(vcr_request):
            vcr_response = cassette.play_response(vcr_request)
            headers = httputil.HTTPHeaders()

            recorded_headers = vcr_response["headers"]
            if isinstance(recorded_headers, dict):
                recorded_headers = recorded_headers.items()
            for k, vs in recorded_headers:
                for v in vs:
                    headers.add(k, v)
            response = HTTPResponse(
                request,
                code=vcr_response["status"]["code"],
                reason=vcr_response["status"]["message"],
                headers=headers,
                buffer=BytesIO(vcr_response["body"]["string"]),
                effective_url=vcr_response.get("url"),
                request_time=self.io_loop.time() - request.start_time,
            )
            return callback(response)
        else:
            if cassette.write_protected and cassette.filter_request(
                    vcr_request):
                response = HTTPResponse(
                    request,
                    599,
                    error=CannotOverwriteExistingCassetteException(
                        cassette=cassette, failed_request=vcr_request),
                    request_time=self.io_loop.time() - request.start_time,
                )
                return callback(response)

            def new_callback(response):
                headers = [(k, response.headers.get_list(k))
                           for k in response.headers.keys()]

                vcr_response = {
                    "status": {
                        "code": response.code,
                        "message": response.reason
                    },
                    "headers": headers,
                    "body": {
                        "string": response.body
                    },
                    "url": response.effective_url,
                }
                cassette.append(vcr_request, vcr_response)
                return callback(response)

            real_fetch_impl(self, request, new_callback)