Exemple #1
0
def build_response(vcr_request, vcr_response, history):
    request_info = RequestInfo(
        url=URL(vcr_request.url),
        method=vcr_request.method,
        headers=_deserialize_headers(vcr_request.headers),
        real_url=URL(vcr_request.url),
    )
    response = MockClientResponse(vcr_request.method, URL(vcr_response.get("url")), request_info=request_info)
    response.status = vcr_response["status"]["code"]
    response._body = vcr_response["body"].get("string", b"")
    response.reason = vcr_response["status"]["message"]
    response._headers = _deserialize_headers(vcr_response["headers"])
    response._history = tuple(history)
    # cookies
    for hdr in response.headers.getall(hdrs.SET_COOKIE, ()):
        try:
            cookies = SimpleCookie(hdr)
            for cookie_name, cookie in cookies.items():
                expires = cookie.get("expires", "").strip()
                if expires:
                    log.debug('Ignoring expiration date: %s="%s"', cookie_name, expires)
                cookie["expires"] = ""
                response.cookies.load(cookie.output(header="").strip())
        except CookieError as exc:
            log.warning("Can not load response cookies: %s", exc)

    response.close()
    return response
Exemple #2
0
def make_http_response(
    status=200, reason="OK", method="GET", url="/", headers=None, content=None
):
    """Return a minimal ClientResponse with fields used in tests."""
    url = URL(url)
    headers = CIMultiDict(headers or {})
    request_info = RequestInfo(url=url, method=method, headers=headers)
    response = ClientResponse(
        method,
        url,
        writer=None,
        continue100=None,
        timer=None,
        request_info=request_info,
        traces=(),
        loop=get_event_loop(),
        session=None,
    )
    response.status = status
    response.reason = reason
    response._headers = headers
    if isinstance(content, io.IOBase):
        response.content = FakeStreamReader(content)
    elif content is not None:
        response.content = FakeStreamReader(
            io.BytesIO(json_dumps(content).encode("utf8"))
        )
        response.headers["Content-Type"] = "application/json"
    return response
Exemple #3
0
async def test_server_error(hass: HomeAssistant, mock_get_regions) -> None:
    """Test server error."""
    mock_get_regions.side_effect = ClientResponseError(RequestInfo(
        None, None, None, real_url=URL("/regions")),
                                                       None,
                                                       status=500)
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})
    assert result["type"] == FlowResultType.ABORT
    assert result["reason"] == "unknown"
Exemple #4
0
def build_response(vcr_request, vcr_response, history):
    request_info = RequestInfo(
        url=URL(vcr_request.url),
        method=vcr_request.method,
        headers=CIMultiDictProxy(CIMultiDict(vcr_request.headers)),
        real_url=URL(vcr_request.url),
    )
    response = MockClientResponse(vcr_request.method, URL(vcr_response.get("url")), request_info=request_info)
    response.status = vcr_response["status"]["code"]
    response._body = vcr_response["body"].get("string", b"")
    response.reason = vcr_response["status"]["message"]
    response._headers = CIMultiDictProxy(CIMultiDict(vcr_response["headers"]))
    response._history = tuple(history)

    response.close()
    return response
 async def read(self):
     raise ClientResponseError(
         RequestInfo("", "", CIMultiDictProxy(CIMultiDict()), ""),
         ())
Exemple #6
0
 def json(self, encoding='utf-8'):
     if not getattr(self.body, "decode", False):
         raise ContentTypeError(request_info=RequestInfo(self.url, self.method, self.headers), history=[self])
     return json.loads(self.body.decode(encoding))
Exemple #7
0
 async def __aenter__(self):
     if self.raise_fails > self.count_raise:
         self.count_raise += 1
         raise ClientResponseError(RequestInfo('', '', Mock(), ''), ())
     return self.return_value or {}