{"repo":"httpx","file":"httpx/__init__.py","line":18,"symbol":"main","kind":"function","lang":"python","code":"def main() -> None: # type: ignore\n import sys\n\n print(\n \"The httpx command line client could not run because the required \"\n \"dependencies were not installed.\\nMake sure you've installed \"\n \"everything with: pip install 'httpx[cli]'\"\n )\n sys.exit(1)"} {"repo":"httpx","file":"httpx/_api.py","line":39,"symbol":"request","kind":"function","lang":"python","code":"def request(\n method: str,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends an HTTP request.\n\n **Parameters:**\n\n * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,\n `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.\n * **url** - URL for the new `Request` object.\n * **params** - *(optional)* Query parameters to include in the URL, as a\n string, dictionary, or sequence of two-tuples.\n * **content** - *(optional)* Binary content to include in the body of the\n request, as bytes or a byte iterator.\n * **data** - *(optional)* Form data to include in the body of the request,\n as a dictionary.\n * **files** - *(optional)* "} {"repo":"httpx","file":"httpx/_api.py","line":124,"symbol":"stream","kind":"function","lang":"python","code":"def stream(\n method: str,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n trust_env: bool = True,\n) -> typing.Iterator[Response]:\n \"\"\"\n Alternative to `httpx.request()` that streams the response body\n instead of loading it into memory at once.\n\n **Parameters**: See `httpx.request`.\n\n See also: [Streaming Responses][0]\n\n [0]: /quickstart#streaming-responses\n \"\"\"\n with Client(\n cookies=cookies,\n proxy=proxy,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n ) as client:\n with client.stream(\n method=method,\n url=url,\n content=content,\n data=data,\n files=files,\n json=json,\n "} {"repo":"httpx","file":"httpx/_api.py","line":174,"symbol":"get","kind":"function","lang":"python","code":"def get(\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends a `GET` request.\n\n **Parameters**: See `httpx.request`.\n\n Note that the `data`, `files`, `json` and `content` parameters are not available\n on this function, as `GET` requests should not include a request body.\n \"\"\"\n return request(\n \"GET\",\n url,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n proxy=proxy,\n follow_redirects=follow_redirects,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n )"} {"repo":"httpx","file":"httpx/_api.py","line":210,"symbol":"options","kind":"function","lang":"python","code":"def options(\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends an `OPTIONS` request.\n\n **Parameters**: See `httpx.request`.\n\n Note that the `data`, `files`, `json` and `content` parameters are not available\n on this function, as `OPTIONS` requests should not include a request body.\n \"\"\"\n return request(\n \"OPTIONS\",\n url,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n proxy=proxy,\n follow_redirects=follow_redirects,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n )"} {"repo":"httpx","file":"httpx/_api.py","line":246,"symbol":"head","kind":"function","lang":"python","code":"def head(\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends a `HEAD` request.\n\n **Parameters**: See `httpx.request`.\n\n Note that the `data`, `files`, `json` and `content` parameters are not available\n on this function, as `HEAD` requests should not include a request body.\n \"\"\"\n return request(\n \"HEAD\",\n url,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n proxy=proxy,\n follow_redirects=follow_redirects,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n )"} {"repo":"httpx","file":"httpx/_api.py","line":282,"symbol":"post","kind":"function","lang":"python","code":"def post(\n url: URL | str,\n *,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends a `POST` request.\n\n **Parameters**: See `httpx.request`.\n \"\"\"\n return request(\n \"POST\",\n url,\n content=content,\n data=data,\n files=files,\n json=json,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n proxy=proxy,\n follow_redirects=follow_redirects,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n )"} {"repo":"httpx","file":"httpx/_api.py","line":323,"symbol":"put","kind":"function","lang":"python","code":"def put(\n url: URL | str,\n *,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends a `PUT` request.\n\n **Parameters**: See `httpx.request`.\n \"\"\"\n return request(\n \"PUT\",\n url,\n content=content,\n data=data,\n files=files,\n json=json,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n proxy=proxy,\n follow_redirects=follow_redirects,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n )"} {"repo":"httpx","file":"httpx/_api.py","line":364,"symbol":"patch","kind":"function","lang":"python","code":"def patch(\n url: URL | str,\n *,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n follow_redirects: bool = False,\n verify: ssl.SSLContext | str | bool = True,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends a `PATCH` request.\n\n **Parameters**: See `httpx.request`.\n \"\"\"\n return request(\n \"PATCH\",\n url,\n content=content,\n data=data,\n files=files,\n json=json,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n proxy=proxy,\n follow_redirects=follow_redirects,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n )"} {"repo":"httpx","file":"httpx/_api.py","line":405,"symbol":"delete","kind":"function","lang":"python","code":"def delete(\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | None = None,\n proxy: ProxyTypes | None = None,\n follow_redirects: bool = False,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n verify: ssl.SSLContext | str | bool = True,\n trust_env: bool = True,\n) -> Response:\n \"\"\"\n Sends a `DELETE` request.\n\n **Parameters**: See `httpx.request`.\n\n Note that the `data`, `files`, `json` and `content` parameters are not available\n on this function, as `DELETE` requests should not include a request body.\n \"\"\"\n return request(\n \"DELETE\",\n url,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n proxy=proxy,\n follow_redirects=follow_redirects,\n verify=verify,\n timeout=timeout,\n trust_env=trust_env,\n )"} {"repo":"httpx","file":"httpx/_auth.py","line":22,"symbol":"Auth","kind":"class","lang":"python","code":"class Auth:\n \"\"\"\n Base class for all authentication schemes.\n\n To implement a custom authentication scheme, subclass `Auth` and override\n the `.auth_flow()` method.\n\n If the authentication scheme does I/O such as disk access or network calls, or uses\n synchronization primitives such as locks, you should override `.sync_auth_flow()`\n and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized\n implementations that will be used by `Client` and `AsyncClient` respectively.\n \"\"\"\n\n requires_request_body = False\n requires_response_body = False\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n \"\"\"\n Execute the authentication flow.\n\n To dispatch a request, `yield` it:\n\n ```\n yield request\n ```\n\n The client will `.send()` the response back into the flow generator. You can\n access it like so:\n\n ```\n response = yield request\n ```\n\n A `return` (or reaching the end of the generator) will result in the\n client returning the last response obtained from the server.\n\n You can dispatch as many requests as is necessa"} {"repo":"httpx","file":"httpx/_auth.py","line":38,"symbol":"auth_flow","kind":"function","lang":"python","code":"def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n \"\"\"\n Execute the authentication flow.\n\n To dispatch a request, `yield` it:\n\n ```\n yield request\n ```\n\n The client will `.send()` the response back into the flow generator. You can\n access it like so:\n\n ```\n response = yield request\n ```\n\n A `return` (or reaching the end of the generator) will result in the\n client returning the last response obtained from the server.\n\n You can dispatch as many requests as is necessary.\n \"\"\"\n yield request"} {"repo":"httpx","file":"httpx/_auth.py","line":62,"symbol":"sync_auth_flow","kind":"function","lang":"python","code":"def sync_auth_flow(\n self, request: Request\n ) -> typing.Generator[Request, Response, None]:\n \"\"\"\n Execute the authentication flow synchronously.\n\n By default, this defers to `.auth_flow()`. You should override this method\n when the authentication scheme does I/O and/or uses concurrency primitives.\n \"\"\"\n if self.requires_request_body:\n request.read()\n\n flow = self.auth_flow(request)\n request = next(flow)\n\n while True:\n response = yield request\n if self.requires_response_body:\n response.read()\n\n try:\n request = flow.send(response)\n except StopIteration:\n break"} {"repo":"httpx","file":"httpx/_auth.py","line":87,"symbol":"async_auth_flow","kind":"function","lang":"python","code":"async def async_auth_flow(\n self, request: Request\n ) -> typing.AsyncGenerator[Request, Response]:\n \"\"\"\n Execute the authentication flow asynchronously.\n\n By default, this defers to `.auth_flow()`. You should override this method\n when the authentication scheme does I/O and/or uses concurrency primitives.\n \"\"\"\n if self.requires_request_body:\n await request.aread()\n\n flow = self.auth_flow(request)\n request = next(flow)\n\n while True:\n response = yield request\n if self.requires_response_body:\n await response.aread()\n\n try:\n request = flow.send(response)\n except StopIteration:\n break"} {"repo":"httpx","file":"httpx/_auth.py","line":113,"symbol":"FunctionAuth","kind":"class","lang":"python","code":"class FunctionAuth(Auth):\n \"\"\"\n Allows the 'auth' argument to be passed as a simple callable function,\n that takes the request, and returns a new, modified request.\n \"\"\"\n\n def __init__(self, func: typing.Callable[[Request], Request]) -> None:\n self._func = func\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n yield self._func(request)"} {"repo":"httpx","file":"httpx/_auth.py","line":119,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, func: typing.Callable[[Request], Request]) -> None:\n self._func = func"} {"repo":"httpx","file":"httpx/_auth.py","line":122,"symbol":"auth_flow","kind":"function","lang":"python","code":"def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n yield self._func(request)"} {"repo":"httpx","file":"httpx/_auth.py","line":126,"symbol":"BasicAuth","kind":"class","lang":"python","code":"class BasicAuth(Auth):\n \"\"\"\n Allows the 'auth' argument to be passed as a (username, password) pair,\n and uses HTTP Basic authentication.\n \"\"\"\n\n def __init__(self, username: str | bytes, password: str | bytes) -> None:\n self._auth_header = self._build_auth_header(username, password)\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n request.headers[\"Authorization\"] = self._auth_header\n yield request\n\n def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:\n userpass = b\":\".join((to_bytes(username), to_bytes(password)))\n token = b64encode(userpass).decode()\n return f\"Basic {token}\""} {"repo":"httpx","file":"httpx/_auth.py","line":132,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: str | bytes, password: str | bytes) -> None:\n self._auth_header = self._build_auth_header(username, password)"} {"repo":"httpx","file":"httpx/_auth.py","line":135,"symbol":"auth_flow","kind":"function","lang":"python","code":"def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n request.headers[\"Authorization\"] = self._auth_header\n yield request"} {"repo":"httpx","file":"httpx/_auth.py","line":139,"symbol":"_build_auth_header","kind":"function","lang":"python","code":"def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:\n userpass = b\":\".join((to_bytes(username), to_bytes(password)))\n token = b64encode(userpass).decode()\n return f\"Basic {token}\""} {"repo":"httpx","file":"httpx/_auth.py","line":145,"symbol":"NetRCAuth","kind":"class","lang":"python","code":"class NetRCAuth(Auth):\n \"\"\"\n Use a 'netrc' file to lookup basic auth credentials based on the url host.\n \"\"\"\n\n def __init__(self, file: str | None = None) -> None:\n # Lazily import 'netrc'.\n # There's no need for us to load this module unless 'NetRCAuth' is being used.\n import netrc\n\n self._netrc_info = netrc.netrc(file)\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n auth_info = self._netrc_info.authenticators(request.url.host)\n if auth_info is None or not auth_info[2]:\n # The netrc file did not have authentication credentials for this host.\n yield request\n else:\n # Build a basic auth header with credentials from the netrc file.\n request.headers[\"Authorization\"] = self._build_auth_header(\n username=auth_info[0], password=auth_info[2]\n )\n yield request\n\n def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:\n userpass = b\":\".join((to_bytes(username), to_bytes(password)))\n token = b64encode(userpass).decode()\n return f\"Basic {token}\""} {"repo":"httpx","file":"httpx/_auth.py","line":150,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, file: str | None = None) -> None:\n # Lazily import 'netrc'.\n # There's no need for us to load this module unless 'NetRCAuth' is being used.\n import netrc\n\n self._netrc_info = netrc.netrc(file)"} {"repo":"httpx","file":"httpx/_auth.py","line":157,"symbol":"auth_flow","kind":"function","lang":"python","code":"def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n auth_info = self._netrc_info.authenticators(request.url.host)\n if auth_info is None or not auth_info[2]:\n # The netrc file did not have authentication credentials for this host.\n yield request\n else:\n # Build a basic auth header with credentials from the netrc file.\n request.headers[\"Authorization\"] = self._build_auth_header(\n username=auth_info[0], password=auth_info[2]\n )\n yield request"} {"repo":"httpx","file":"httpx/_auth.py","line":169,"symbol":"_build_auth_header","kind":"function","lang":"python","code":"def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:\n userpass = b\":\".join((to_bytes(username), to_bytes(password)))\n token = b64encode(userpass).decode()\n return f\"Basic {token}\""} {"repo":"httpx","file":"httpx/_auth.py","line":175,"symbol":"DigestAuth","kind":"class","lang":"python","code":"class DigestAuth(Auth):\n _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = {\n \"MD5\": hashlib.md5,\n \"MD5-SESS\": hashlib.md5,\n \"SHA\": hashlib.sha1,\n \"SHA-SESS\": hashlib.sha1,\n \"SHA-256\": hashlib.sha256,\n \"SHA-256-SESS\": hashlib.sha256,\n \"SHA-512\": hashlib.sha512,\n \"SHA-512-SESS\": hashlib.sha512,\n }\n\n def __init__(self, username: str | bytes, password: str | bytes) -> None:\n self._username = to_bytes(username)\n self._password = to_bytes(password)\n self._last_challenge: _DigestAuthChallenge | None = None\n self._nonce_count = 1\n\n def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n if self._last_challenge:\n request.headers[\"Authorization\"] = self._build_auth_header(\n request, self._last_challenge\n )\n\n response = yield request\n\n if response.status_code != 401 or \"www-authenticate\" not in response.headers:\n # If the response is not a 401 then we don't\n # need to build an authenticated request.\n return\n\n for auth_header in response.headers.get_"} {"repo":"httpx","file":"httpx/_auth.py","line":187,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: str | bytes, password: str | bytes) -> None:\n self._username = to_bytes(username)\n self._password = to_bytes(password)\n self._last_challenge: _DigestAuthChallenge | None = None\n self._nonce_count = 1"} {"repo":"httpx","file":"httpx/_auth.py","line":193,"symbol":"auth_flow","kind":"function","lang":"python","code":"def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:\n if self._last_challenge:\n request.headers[\"Authorization\"] = self._build_auth_header(\n request, self._last_challenge\n )\n\n response = yield request\n\n if response.status_code != 401 or \"www-authenticate\" not in response.headers:\n # If the response is not a 401 then we don't\n # need to build an authenticated request.\n return\n\n for auth_header in response.headers.get_list(\"www-authenticate\"):\n if auth_header.lower().startswith(\"digest \"):\n break\n else:\n # If the response does not include a 'WWW-Authenticate: Digest ...'\n # header, then we don't need to build an authenticated request.\n return\n\n self._last_challenge = self._parse_challenge(request, response, auth_header)\n self._nonce_count = 1\n\n request.headers[\"Authorization\"] = self._build_auth_header(\n request, self._last_challenge\n )\n if response.cookies:\n Cookies(response.cookies).set_cookie_header(request=request)\n yield req"} {"repo":"httpx","file":"httpx/_auth.py","line":224,"symbol":"_parse_challenge","kind":"function","lang":"python","code":"def _parse_challenge(\n self, request: Request, response: Response, auth_header: str\n ) -> _DigestAuthChallenge:\n \"\"\"\n Returns a challenge from a Digest WWW-Authenticate header.\n These take the form of:\n `Digest realm=\"realm@host.com\",qop=\"auth,auth-int\",nonce=\"abc\",opaque=\"xyz\"`\n \"\"\"\n scheme, _, fields = auth_header.partition(\" \")\n\n # This method should only ever have been called with a Digest auth header.\n assert scheme.lower() == \"digest\"\n\n header_dict: dict[str, str] = {}\n for field in parse_http_list(fields):\n key, value = field.strip().split(\"=\", 1)\n header_dict[key] = unquote(value)\n\n try:\n realm = header_dict[\"realm\"].encode()\n nonce = header_dict[\"nonce\"].encode()\n algorithm = header_dict.get(\"algorithm\", \"MD5\")\n opaque = header_dict[\"opaque\"].encode() if \"opaque\" in header_dict else None\n qop = header_dict[\"qop\"].encode() if \"qop\" in header_dict else None\n return _DigestAuthChallenge(\n realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop\n )\n except Key"} {"repo":"httpx","file":"httpx/_auth.py","line":255,"symbol":"_build_auth_header","kind":"function","lang":"python","code":"def _build_auth_header(\n self, request: Request, challenge: _DigestAuthChallenge\n ) -> str:\n hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]\n\n def digest(data: bytes) -> bytes:\n return hash_func(data).hexdigest().encode()\n\n A1 = b\":\".join((self._username, challenge.realm, self._password))\n\n path = request.url.raw_path\n A2 = b\":\".join((request.method.encode(), path))\n # TODO: implement auth-int\n HA2 = digest(A2)\n\n nc_value = b\"%08x\" % self._nonce_count\n cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)\n self._nonce_count += 1\n\n HA1 = digest(A1)\n if challenge.algorithm.lower().endswith(\"-sess\"):\n HA1 = digest(b\":\".join((HA1, challenge.nonce, cnonce)))\n\n qop = self._resolve_qop(challenge.qop, request=request)\n if qop is None:\n # Following RFC 2069\n digest_data = [HA1, challenge.nonce, HA2]\n else:\n # Following RFC 2617/7616\n digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2]\n\n format_args = {\n \"username\": self._username,\n "} {"repo":"httpx","file":"httpx/_auth.py","line":260,"symbol":"digest","kind":"function","lang":"python","code":"def digest(data: bytes) -> bytes:\n return hash_func(data).hexdigest().encode()"} {"repo":"httpx","file":"httpx/_auth.py","line":303,"symbol":"_get_client_nonce","kind":"function","lang":"python","code":"def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:\n s = str(nonce_count).encode()\n s += nonce\n s += time.ctime().encode()\n s += os.urandom(8)\n\n return hashlib.sha1(s).hexdigest()[:16].encode()"} {"repo":"httpx","file":"httpx/_auth.py","line":311,"symbol":"_get_header_value","kind":"function","lang":"python","code":"def _get_header_value(self, header_fields: dict[str, bytes]) -> str:\n NON_QUOTED_FIELDS = (\"algorithm\", \"qop\", \"nc\")\n QUOTED_TEMPLATE = '{}=\"{}\"'\n NON_QUOTED_TEMPLATE = \"{}={}\"\n\n header_value = \"\"\n for i, (field, value) in enumerate(header_fields.items()):\n if i > 0:\n header_value += \", \"\n template = (\n QUOTED_TEMPLATE\n if field not in NON_QUOTED_FIELDS\n else NON_QUOTED_TEMPLATE\n )\n header_value += template.format(field, to_str(value))\n\n return header_value"} {"repo":"httpx","file":"httpx/_auth.py","line":329,"symbol":"_resolve_qop","kind":"function","lang":"python","code":"def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None:\n if qop is None:\n return None\n qops = re.split(b\", ?\", qop)\n if b\"auth\" in qops:\n return b\"auth\"\n\n if qops == [b\"auth-int\"]:\n raise NotImplementedError(\"Digest auth-int support is not yet implemented\")\n\n message = f'Unexpected qop value \"{qop!r}\" in digest auth'\n raise ProtocolError(message, request=request)"} {"repo":"httpx","file":"httpx/_auth.py","line":343,"symbol":"_DigestAuthChallenge","kind":"class","lang":"python","code":"class _DigestAuthChallenge(typing.NamedTuple):\n realm: bytes\n nonce: bytes\n algorithm: str\n opaque: bytes | None\n qop: bytes | None"} {"repo":"httpx","file":"httpx/_client.py","line":62,"symbol":"_is_https_redirect","kind":"function","lang":"python","code":"def _is_https_redirect(url: URL, location: URL) -> bool:\n \"\"\"\n Return 'True' if 'location' is a HTTPS upgrade of 'url'\n \"\"\"\n if url.host != location.host:\n return False\n\n return (\n url.scheme == \"http\"\n and _port_or_default(url) == 80\n and location.scheme == \"https\"\n and _port_or_default(location) == 443\n )"} {"repo":"httpx","file":"httpx/_client.py","line":77,"symbol":"_port_or_default","kind":"function","lang":"python","code":"def _port_or_default(url: URL) -> int | None:\n if url.port is not None:\n return url.port\n return {\"http\": 80, \"https\": 443}.get(url.scheme)"} {"repo":"httpx","file":"httpx/_client.py","line":83,"symbol":"_same_origin","kind":"function","lang":"python","code":"def _same_origin(url: URL, other: URL) -> bool:\n \"\"\"\n Return 'True' if the given URLs share the same origin.\n \"\"\"\n return (\n url.scheme == other.scheme\n and url.host == other.host\n and _port_or_default(url) == _port_or_default(other)\n )"} {"repo":"httpx","file":"httpx/_client.py","line":94,"symbol":"UseClientDefault","kind":"class","lang":"python","code":"class UseClientDefault:\n \"\"\"\n For some parameters such as `auth=...` and `timeout=...` we need to be able\n to indicate the default \"unset\" state, in a way that is distinctly different\n to using `None`.\n\n The default \"unset\" state indicates that whatever default is set on the\n client should be used. This is different to setting `None`, which\n explicitly disables the parameter, possibly overriding a client default.\n\n For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature.\n Omitting the `timeout` parameter will send a request using whatever default\n timeout has been configured on the client. Including `timeout=None` will\n ensure no timeout is used.\n\n Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant,\n but it is used internally when a parameter is not included.\n \"\"\""} {"repo":"httpx","file":"httpx/_client.py","line":125,"symbol":"ClientState","kind":"class","lang":"python","code":"class ClientState(enum.Enum):\n # UNOPENED:\n # The client has been instantiated, but has not been used to send a request,\n # or been opened by entering the context of a `with` block.\n UNOPENED = 1\n # OPENED:\n # The client has either sent a request, or is within a `with` block.\n OPENED = 2\n # CLOSED:\n # The client has either exited the `with` block, or `close()` has\n # been called explicitly.\n CLOSED = 3"} {"repo":"httpx","file":"httpx/_client.py","line":139,"symbol":"BoundSyncStream","kind":"class","lang":"python","code":"class BoundSyncStream(SyncByteStream):\n \"\"\"\n A byte stream that is bound to a given response instance, and that\n ensures the `response.elapsed` is set once the response is closed.\n \"\"\"\n\n def __init__(\n self, stream: SyncByteStream, response: Response, start: float\n ) -> None:\n self._stream = stream\n self._response = response\n self._start = start\n\n def __iter__(self) -> typing.Iterator[bytes]:\n for chunk in self._stream:\n yield chunk\n\n def close(self) -> None:\n elapsed = time.perf_counter() - self._start\n self._response.elapsed = datetime.timedelta(seconds=elapsed)\n self._stream.close()"} {"repo":"httpx","file":"httpx/_client.py","line":145,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self, stream: SyncByteStream, response: Response, start: float\n ) -> None:\n self._stream = stream\n self._response = response\n self._start = start"} {"repo":"httpx","file":"httpx/_client.py","line":152,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> typing.Iterator[bytes]:\n for chunk in self._stream:\n yield chunk"} {"repo":"httpx","file":"httpx/_client.py","line":156,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n elapsed = time.perf_counter() - self._start\n self._response.elapsed = datetime.timedelta(seconds=elapsed)\n self._stream.close()"} {"repo":"httpx","file":"httpx/_client.py","line":162,"symbol":"BoundAsyncStream","kind":"class","lang":"python","code":"class BoundAsyncStream(AsyncByteStream):\n \"\"\"\n An async byte stream that is bound to a given response instance, and that\n ensures the `response.elapsed` is set once the response is closed.\n \"\"\"\n\n def __init__(\n self, stream: AsyncByteStream, response: Response, start: float\n ) -> None:\n self._stream = stream\n self._response = response\n self._start = start\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n async for chunk in self._stream:\n yield chunk\n\n async def aclose(self) -> None:\n elapsed = time.perf_counter() - self._start\n self._response.elapsed = datetime.timedelta(seconds=elapsed)\n await self._stream.aclose()"} {"repo":"httpx","file":"httpx/_client.py","line":168,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self, stream: AsyncByteStream, response: Response, start: float\n ) -> None:\n self._stream = stream\n self._response = response\n self._start = start"} {"repo":"httpx","file":"httpx/_client.py","line":175,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n async for chunk in self._stream:\n yield chunk"} {"repo":"httpx","file":"httpx/_client.py","line":179,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self) -> None:\n elapsed = time.perf_counter() - self._start\n self._response.elapsed = datetime.timedelta(seconds=elapsed)\n await self._stream.aclose()"} {"repo":"httpx","file":"httpx/_client.py","line":188,"symbol":"BaseClient","kind":"class","lang":"python","code":"class BaseClient:\n def __init__(\n self,\n *,\n auth: AuthTypes | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n follow_redirects: bool = False,\n max_redirects: int = DEFAULT_MAX_REDIRECTS,\n event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,\n base_url: URL | str = \"\",\n trust_env: bool = True,\n default_encoding: str | typing.Callable[[bytes], str] = \"utf-8\",\n ) -> None:\n event_hooks = {} if event_hooks is None else event_hooks\n\n self._base_url = self._enforce_trailing_slash(URL(base_url))\n\n self._auth = self._build_auth(auth)\n self._params = QueryParams(params)\n self.headers = Headers(headers)\n self._cookies = Cookies(cookies)\n self._timeout = Timeout(timeout)\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self._event_hooks = {\n \"request\": list(event_hooks.get(\"request\", [])),\n \"response\": list(event_hooks.get(\"response\", [])"} {"repo":"httpx","file":"httpx/_client.py","line":189,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n *,\n auth: AuthTypes | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n follow_redirects: bool = False,\n max_redirects: int = DEFAULT_MAX_REDIRECTS,\n event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,\n base_url: URL | str = \"\",\n trust_env: bool = True,\n default_encoding: str | typing.Callable[[bytes], str] = \"utf-8\",\n ) -> None:\n event_hooks = {} if event_hooks is None else event_hooks\n\n self._base_url = self._enforce_trailing_slash(URL(base_url))\n\n self._auth = self._build_auth(auth)\n self._params = QueryParams(params)\n self.headers = Headers(headers)\n self._cookies = Cookies(cookies)\n self._timeout = Timeout(timeout)\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self._event_hooks = {\n \"request\": list(event_hooks.get(\"request\", [])),\n \"response\": list(event_hooks.get(\"response\", [])),\n }\n s"} {"repo":"httpx","file":"httpx/_client.py","line":224,"symbol":"is_closed","kind":"function","lang":"python","code":"def is_closed(self) -> bool:\n \"\"\"\n Check if the client being closed\n \"\"\"\n return self._state == ClientState.CLOSED"} {"repo":"httpx","file":"httpx/_client.py","line":231,"symbol":"trust_env","kind":"function","lang":"python","code":"def trust_env(self) -> bool:\n return self._trust_env"} {"repo":"httpx","file":"httpx/_client.py","line":234,"symbol":"_enforce_trailing_slash","kind":"function","lang":"python","code":"def _enforce_trailing_slash(self, url: URL) -> URL:\n if url.raw_path.endswith(b\"/\"):\n return url\n return url.copy_with(raw_path=url.raw_path + b\"/\")"} {"repo":"httpx","file":"httpx/_client.py","line":239,"symbol":"_get_proxy_map","kind":"function","lang":"python","code":"def _get_proxy_map(\n self, proxy: ProxyTypes | None, allow_env_proxies: bool\n ) -> dict[str, Proxy | None]:\n if proxy is None:\n if allow_env_proxies:\n return {\n key: None if url is None else Proxy(url=url)\n for key, url in get_environment_proxies().items()\n }\n return {}\n else:\n proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy\n return {\"all://\": proxy}"} {"repo":"httpx","file":"httpx/_client.py","line":254,"symbol":"timeout","kind":"function","lang":"python","code":"def timeout(self) -> Timeout:\n return self._timeout"} {"repo":"httpx","file":"httpx/_client.py","line":258,"symbol":"timeout","kind":"function","lang":"python","code":"def timeout(self, timeout: TimeoutTypes) -> None:\n self._timeout = Timeout(timeout)"} {"repo":"httpx","file":"httpx/_client.py","line":262,"symbol":"event_hooks","kind":"function","lang":"python","code":"def event_hooks(self) -> dict[str, list[EventHook]]:\n return self._event_hooks"} {"repo":"httpx","file":"httpx/_client.py","line":266,"symbol":"event_hooks","kind":"function","lang":"python","code":"def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None:\n self._event_hooks = {\n \"request\": list(event_hooks.get(\"request\", [])),\n \"response\": list(event_hooks.get(\"response\", [])),\n }"} {"repo":"httpx","file":"httpx/_client.py","line":273,"symbol":"auth","kind":"function","lang":"python","code":"def auth(self) -> Auth | None:\n \"\"\"\n Authentication class used when none is passed at the request-level.\n\n See also [Authentication][0].\n\n [0]: /quickstart/#authentication\n \"\"\"\n return self._auth"} {"repo":"httpx","file":"httpx/_client.py","line":284,"symbol":"auth","kind":"function","lang":"python","code":"def auth(self, auth: AuthTypes) -> None:\n self._auth = self._build_auth(auth)"} {"repo":"httpx","file":"httpx/_client.py","line":288,"symbol":"base_url","kind":"function","lang":"python","code":"def base_url(self) -> URL:\n \"\"\"\n Base URL to use when sending requests with relative URLs.\n \"\"\"\n return self._base_url"} {"repo":"httpx","file":"httpx/_client.py","line":295,"symbol":"base_url","kind":"function","lang":"python","code":"def base_url(self, url: URL | str) -> None:\n self._base_url = self._enforce_trailing_slash(URL(url))"} {"repo":"httpx","file":"httpx/_client.py","line":299,"symbol":"headers","kind":"function","lang":"python","code":"def headers(self) -> Headers:\n \"\"\"\n HTTP headers to include when sending requests.\n \"\"\"\n return self._headers"} {"repo":"httpx","file":"httpx/_client.py","line":306,"symbol":"headers","kind":"function","lang":"python","code":"def headers(self, headers: HeaderTypes) -> None:\n client_headers = Headers(\n {\n b\"Accept\": b\"*/*\",\n b\"Accept-Encoding\": ACCEPT_ENCODING.encode(\"ascii\"),\n b\"Connection\": b\"keep-alive\",\n b\"User-Agent\": USER_AGENT.encode(\"ascii\"),\n }\n )\n client_headers.update(headers)\n self._headers = client_headers"} {"repo":"httpx","file":"httpx/_client.py","line":319,"symbol":"cookies","kind":"function","lang":"python","code":"def cookies(self) -> Cookies:\n \"\"\"\n Cookie values to include when sending requests.\n \"\"\"\n return self._cookies"} {"repo":"httpx","file":"httpx/_client.py","line":326,"symbol":"cookies","kind":"function","lang":"python","code":"def cookies(self, cookies: CookieTypes) -> None:\n self._cookies = Cookies(cookies)"} {"repo":"httpx","file":"httpx/_client.py","line":330,"symbol":"params","kind":"function","lang":"python","code":"def params(self) -> QueryParams:\n \"\"\"\n Query parameters to include in the URL when sending requests.\n \"\"\"\n return self._params"} {"repo":"httpx","file":"httpx/_client.py","line":337,"symbol":"params","kind":"function","lang":"python","code":"def params(self, params: QueryParamTypes) -> None:\n self._params = QueryParams(params)"} {"repo":"httpx","file":"httpx/_client.py","line":340,"symbol":"build_request","kind":"function","lang":"python","code":"def build_request(\n self,\n method: str,\n url: URL | str,\n *,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n extensions: RequestExtensions | None = None,\n ) -> Request:\n \"\"\"\n Build and return a request instance.\n\n * The `params`, `headers` and `cookies` arguments\n are merged with any values set on the client.\n * The `url` argument is merged with any `base_url` set on the client.\n\n See also: [Request instances][0]\n\n [0]: /advanced/clients/#request-instances\n \"\"\"\n url = self._merge_url(url)\n headers = self._merge_headers(headers)\n cookies = self._merge_cookies(cookies)\n params = self._merge_queryparams(params)\n extensions = {} if extensions is None else extensions\n if \"timeout\" not in extensions:\n timeout = (\n "} {"repo":"httpx","file":"httpx/_client.py","line":391,"symbol":"_merge_url","kind":"function","lang":"python","code":"def _merge_url(self, url: URL | str) -> URL:\n \"\"\"\n Merge a URL argument together with any 'base_url' on the client,\n to create the URL used for the outgoing request.\n \"\"\"\n merge_url = URL(url)\n if merge_url.is_relative_url:\n # To merge URLs we always append to the base URL. To get this\n # behaviour correct we always ensure the base URL ends in a '/'\n # separator, and strip any leading '/' from the merge URL.\n #\n # So, eg...\n #\n # >>> client = Client(base_url=\"https://www.example.com/subpath\")\n # >>> client.base_url\n # URL('https://www.example.com/subpath/')\n # >>> client.build_request(\"GET\", \"/path\").url\n # URL('https://www.example.com/subpath/path')\n merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b\"/\")\n return self.base_url.copy_with(raw_path=merge_raw_path)\n return merge_url"} {"repo":"httpx","file":"httpx/_client.py","line":413,"symbol":"_merge_cookies","kind":"function","lang":"python","code":"def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None:\n \"\"\"\n Merge a cookies argument together with any cookies on the client,\n to create the cookies used for the outgoing request.\n \"\"\"\n if cookies or self.cookies:\n merged_cookies = Cookies(self.cookies)\n merged_cookies.update(cookies)\n return merged_cookies\n return cookies"} {"repo":"httpx","file":"httpx/_client.py","line":424,"symbol":"_merge_headers","kind":"function","lang":"python","code":"def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None:\n \"\"\"\n Merge a headers argument together with any headers on the client,\n to create the headers used for the outgoing request.\n \"\"\"\n merged_headers = Headers(self.headers)\n merged_headers.update(headers)\n return merged_headers"} {"repo":"httpx","file":"httpx/_client.py","line":433,"symbol":"_merge_queryparams","kind":"function","lang":"python","code":"def _merge_queryparams(\n self, params: QueryParamTypes | None = None\n ) -> QueryParamTypes | None:\n \"\"\"\n Merge a queryparams argument together with any queryparams on the client,\n to create the queryparams used for the outgoing request.\n \"\"\"\n if params or self.params:\n merged_queryparams = QueryParams(self.params)\n return merged_queryparams.merge(params)\n return params"} {"repo":"httpx","file":"httpx/_client.py","line":445,"symbol":"_build_auth","kind":"function","lang":"python","code":"def _build_auth(self, auth: AuthTypes | None) -> Auth | None:\n if auth is None:\n return None\n elif isinstance(auth, tuple):\n return BasicAuth(username=auth[0], password=auth[1])\n elif isinstance(auth, Auth):\n return auth\n elif callable(auth):\n return FunctionAuth(func=auth)\n else:\n raise TypeError(f'Invalid \"auth\" argument: {auth!r}')"} {"repo":"httpx","file":"httpx/_client.py","line":457,"symbol":"_build_request_auth","kind":"function","lang":"python","code":"def _build_request_auth(\n self,\n request: Request,\n auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,\n ) -> Auth:\n auth = (\n self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth)\n )\n\n if auth is not None:\n return auth\n\n username, password = request.url.username, request.url.password\n if username or password:\n return BasicAuth(username=username, password=password)\n\n return Auth()"} {"repo":"httpx","file":"httpx/_client.py","line":475,"symbol":"_build_redirect_request","kind":"function","lang":"python","code":"def _build_redirect_request(self, request: Request, response: Response) -> Request:\n \"\"\"\n Given a request and a redirect response, return a new request that\n should be used to effect the redirect.\n \"\"\"\n method = self._redirect_method(request, response)\n url = self._redirect_url(request, response)\n headers = self._redirect_headers(request, url, method)\n stream = self._redirect_stream(request, method)\n cookies = Cookies(self.cookies)\n return Request(\n method=method,\n url=url,\n headers=headers,\n cookies=cookies,\n stream=stream,\n extensions=request.extensions,\n )"} {"repo":"httpx","file":"httpx/_client.py","line":494,"symbol":"_redirect_method","kind":"function","lang":"python","code":"def _redirect_method(self, request: Request, response: Response) -> str:\n \"\"\"\n When being redirected we may want to change the method of the request\n based on certain specs or browser behavior.\n \"\"\"\n method = request.method\n\n # https://tools.ietf.org/html/rfc7231#section-6.4.4\n if response.status_code == codes.SEE_OTHER and method != \"HEAD\":\n method = \"GET\"\n\n # Do what the browsers do, despite standards...\n # Turn 302s into GETs.\n if response.status_code == codes.FOUND and method != \"HEAD\":\n method = \"GET\"\n\n # If a POST is responded to with a 301, turn it into a GET.\n # This bizarre behaviour is explained in 'requests' issue 1704.\n if response.status_code == codes.MOVED_PERMANENTLY and method == \"POST\":\n method = \"GET\"\n\n return method"} {"repo":"httpx","file":"httpx/_client.py","line":517,"symbol":"_redirect_url","kind":"function","lang":"python","code":"def _redirect_url(self, request: Request, response: Response) -> URL:\n \"\"\"\n Return the URL for the redirect to follow.\n \"\"\"\n location = response.headers[\"Location\"]\n\n try:\n url = URL(location)\n except InvalidURL as exc:\n raise RemoteProtocolError(\n f\"Invalid URL in location header: {exc}.\", request=request\n ) from None\n\n # Handle malformed 'Location' headers that are \"absolute\" form, have no host.\n # See: https://github.com/encode/httpx/issues/771\n if url.scheme and not url.host:\n url = url.copy_with(host=request.url.host)\n\n # Facilitate relative 'Location' headers, as allowed by RFC 7231.\n # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n if url.is_relative_url:\n url = request.url.join(url)\n\n # Attach previous fragment if needed (RFC 7231 7.1.2)\n if request.url.fragment and not url.fragment:\n url = url.copy_with(fragment=request.url.fragment)\n\n return url"} {"repo":"httpx","file":"httpx/_client.py","line":546,"symbol":"_redirect_headers","kind":"function","lang":"python","code":"def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers:\n \"\"\"\n Return the headers that should be used for the redirect request.\n \"\"\"\n headers = Headers(request.headers)\n\n if not _same_origin(url, request.url):\n if not _is_https_redirect(request.url, url):\n # Strip Authorization headers when responses are redirected\n # away from the origin. (Except for direct HTTP to HTTPS redirects.)\n headers.pop(\"Authorization\", None)\n\n # Update the Host header.\n headers[\"Host\"] = url.netloc.decode(\"ascii\")\n\n if method != request.method and method == \"GET\":\n # If we've switch to a 'GET' request, then strip any headers which\n # are only relevant to the request body.\n headers.pop(\"Content-Length\", None)\n headers.pop(\"Transfer-Encoding\", None)\n\n # We should use the client cookie store to determine any cookie header,\n # rather than whatever was on the original outgoing request.\n headers.pop(\"Cookie\", None)\n\n return headers"} {"repo":"httpx","file":"httpx/_client.py","line":573,"symbol":"_redirect_stream","kind":"function","lang":"python","code":"def _redirect_stream(\n self, request: Request, method: str\n ) -> SyncByteStream | AsyncByteStream | None:\n \"\"\"\n Return the body that should be used for the redirect request.\n \"\"\"\n if method != request.method and method == \"GET\":\n return None\n\n return request.stream"} {"repo":"httpx","file":"httpx/_client.py","line":584,"symbol":"_set_timeout","kind":"function","lang":"python","code":"def _set_timeout(self, request: Request) -> None:\n if \"timeout\" not in request.extensions:\n timeout = (\n self.timeout\n if isinstance(self.timeout, UseClientDefault)\n else Timeout(self.timeout)\n )\n request.extensions = dict(**request.extensions, timeout=timeout.as_dict())"} {"repo":"httpx","file":"httpx/_client.py","line":594,"symbol":"Client","kind":"class","lang":"python","code":"class Client(BaseClient):\n \"\"\"\n An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.\n\n It can be shared between threads.\n\n Usage:\n\n ```python\n >>> client = httpx.Client()\n >>> response = client.get('https://example.org')\n ```\n\n **Parameters:**\n\n * **auth** - *(optional)* An authentication class to use when sending\n requests.\n * **params** - *(optional)* Query parameters to include in request URLs, as\n a string, dictionary, or sequence of two-tuples.\n * **headers** - *(optional)* Dictionary of HTTP headers to include when\n sending requests.\n * **cookies** - *(optional)* Dictionary of Cookie items to include when\n sending requests.\n * **verify** - *(optional)* Either `True` to use an SSL context with the\n default CA bundle, `False` to disable verification, or an instance of\n `ssl.SSLContext` to use a custom context.\n * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be\n enabled. Defaults to `False`.\n * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.\n * **timeout** - *(optional)* The timeout configuration to use when sending\n re"} {"repo":"httpx","file":"httpx/_client.py","line":639,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n *,\n auth: AuthTypes | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n http1: bool = True,\n http2: bool = False,\n proxy: ProxyTypes | None = None,\n mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,\n timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,\n follow_redirects: bool = False,\n limits: Limits = DEFAULT_LIMITS,\n max_redirects: int = DEFAULT_MAX_REDIRECTS,\n event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,\n base_url: URL | str = \"\",\n transport: BaseTransport | None = None,\n default_encoding: str | typing.Callable[[bytes], str] = \"utf-8\",\n ) -> None:\n super().__init__(\n auth=auth,\n params=params,\n headers=headers,\n cookies=cookies,\n timeout=timeout,\n follow_redirects=follow_redirects,\n max_redirects=max_redirects,\n "} {"repo":"httpx","file":"httpx/_client.py","line":718,"symbol":"_init_transport","kind":"function","lang":"python","code":"def _init_transport(\n self,\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n http1: bool = True,\n http2: bool = False,\n limits: Limits = DEFAULT_LIMITS,\n transport: BaseTransport | None = None,\n ) -> BaseTransport:\n if transport is not None:\n return transport\n\n return HTTPTransport(\n verify=verify,\n cert=cert,\n trust_env=trust_env,\n http1=http1,\n http2=http2,\n limits=limits,\n )"} {"repo":"httpx","file":"httpx/_client.py","line":740,"symbol":"_init_proxy_transport","kind":"function","lang":"python","code":"def _init_proxy_transport(\n self,\n proxy: Proxy,\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n http1: bool = True,\n http2: bool = False,\n limits: Limits = DEFAULT_LIMITS,\n ) -> BaseTransport:\n return HTTPTransport(\n verify=verify,\n cert=cert,\n trust_env=trust_env,\n http1=http1,\n http2=http2,\n limits=limits,\n proxy=proxy,\n )"} {"repo":"httpx","file":"httpx/_client.py","line":760,"symbol":"_transport_for_url","kind":"function","lang":"python","code":"def _transport_for_url(self, url: URL) -> BaseTransport:\n \"\"\"\n Returns the transport instance that should be used for a given URL.\n This will either be the standard connection pool, or a proxy.\n \"\"\"\n for pattern, transport in self._mounts.items():\n if pattern.matches(url):\n return self._transport if transport is None else transport\n\n return self._transport"} {"repo":"httpx","file":"httpx/_client.py","line":771,"symbol":"request","kind":"function","lang":"python","code":"def request(\n self,\n method: str,\n url: URL | str,\n *,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,\n follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,\n timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n extensions: RequestExtensions | None = None,\n ) -> Response:\n \"\"\"\n Build and send a request.\n\n Equivalent to:\n\n ```python\n request = client.build_request(...)\n response = client.send(request, ...)\n ```\n\n See `Client.build_request()`, `Client.send()` and\n [Merging of configuration][0] for how the various parameters\n are merged with client-level configuration.\n\n [0]: /advanced/clients/#merging-of-configuration\n \"\"\"\n if cookies is not None:\n message = (\n \"Setting per"} {"repo":"httpx","file":"httpx/_client.py","line":828,"symbol":"stream","kind":"function","lang":"python","code":"def stream(\n self,\n method: str,\n url: URL | str,\n *,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,\n follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,\n timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n extensions: RequestExtensions | None = None,\n ) -> typing.Iterator[Response]:\n \"\"\"\n Alternative to `httpx.request()` that streams the response body\n instead of loading it into memory at once.\n\n **Parameters**: See `httpx.request`.\n\n See also: [Streaming Responses][0]\n\n [0]: /quickstart#streaming-responses\n \"\"\"\n request = self.build_request(\n method=method,\n url=url,\n content=content,\n data=data,\n files=files,\n json=json,\n params=params,\n "} {"repo":"httpx","file":"httpx/_client.py","line":879,"symbol":"send","kind":"function","lang":"python","code":"def send(\n self,\n request: Request,\n *,\n stream: bool = False,\n auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,\n follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,\n ) -> Response:\n \"\"\"\n Send a request.\n\n The request is sent as-is, unmodified.\n\n Typically you'll want to build one with `Client.build_request()`\n so that any client-level configuration is merged into the request,\n but passing an explicit `httpx.Request()` is supported as well.\n\n See also: [Request instances][0]\n\n [0]: /advanced/clients/#request-instances\n \"\"\"\n if self._state == ClientState.CLOSED:\n raise RuntimeError(\"Cannot send a request, as the client has been closed.\")\n\n self._state = ClientState.OPENED\n follow_redirects = (\n self.follow_redirects\n if isinstance(follow_redirects, UseClientDefault)\n else follow_redirects\n )\n\n self._set_timeout(request)\n\n auth = self._build_request_auth(request, auth)\n\n response = self._send_handling_auth(\n request,\n auth=auth,\n "} {"repo":"httpx","file":"httpx/_client.py","line":930,"symbol":"_send_handling_auth","kind":"function","lang":"python","code":"def _send_handling_auth(\n self,\n request: Request,\n auth: Auth,\n follow_redirects: bool,\n history: list[Response],\n ) -> Response:\n auth_flow = auth.sync_auth_flow(request)\n try:\n request = next(auth_flow)\n\n while True:\n response = self._send_handling_redirects(\n request,\n follow_redirects=follow_redirects,\n history=history,\n )\n try:\n try:\n next_request = auth_flow.send(response)\n except StopIteration:\n return response\n\n response.history = list(history)\n response.read()\n request = next_request\n history.append(response)\n\n except BaseException as exc:\n response.close()\n raise exc\n finally:\n auth_flow.close()"} {"repo":"httpx","file":"httpx/_client.py","line":964,"symbol":"_send_handling_redirects","kind":"function","lang":"python","code":"def _send_handling_redirects(\n self,\n request: Request,\n follow_redirects: bool,\n history: list[Response],\n ) -> Response:\n while True:\n if len(history) > self.max_redirects:\n raise TooManyRedirects(\n \"Exceeded maximum allowed redirects.\", request=request\n )\n\n for hook in self._event_hooks[\"request\"]:\n hook(request)\n\n response = self._send_single_request(request)\n try:\n for hook in self._event_hooks[\"response\"]:\n hook(response)\n response.history = list(history)\n\n if not response.has_redirect_location:\n return response\n\n request = self._build_redirect_request(request, response)\n history = history + [response]\n\n if follow_redirects:\n response.read()\n else:\n response.next_request = request\n return response\n\n except BaseException as exc:\n response.close()\n raise exc"} {"repo":"httpx","file":"httpx/_client.py","line":1001,"symbol":"_send_single_request","kind":"function","lang":"python","code":"def _send_single_request(self, request: Request) -> Response:\n \"\"\"\n Sends a single request, without handling any redirections.\n \"\"\"\n transport = self._transport_for_url(request.url)\n start = time.perf_counter()\n\n if not isinstance(request.stream, SyncByteStream):\n raise RuntimeError(\n \"Attempted to send an async request with a sync Client instance.\"\n )\n\n with request_context(request=request):\n response = transport.handle_request(request)\n\n assert isinstance(response.stream, SyncByteStream)\n\n response.request = request\n response.stream = BoundSyncStream(\n response.stream, response=response, start=start\n )\n self.cookies.extract_cookies(response)\n response.default_encoding = self._default_encoding\n\n logger.info(\n 'HTTP Request: %s %s \"%s %d %s\"',\n request.method,\n request.url,\n response.http_version,\n response.status_code,\n response.reason_phrase,\n )\n\n return response"} {"repo":"httpx","file":"httpx/_client.py","line":1036,"symbol":"get","kind":"function","lang":"python","code":"def get(\n self,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,\n follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,\n timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n extensions: RequestExtensions | None = None,\n ) -> Response:\n \"\"\"\n Send a `GET` request.\n\n **Parameters**: See `httpx.request`.\n \"\"\"\n return self.request(\n \"GET\",\n url,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n follow_redirects=follow_redirects,\n timeout=timeout,\n extensions=extensions,\n )"} {"repo":"httpx","file":"httpx/_client.py","line":1065,"symbol":"options","kind":"function","lang":"python","code":"def options(\n self,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,\n timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n extensions: RequestExtensions | None = None,\n ) -> Response:\n \"\"\"\n Send an `OPTIONS` request.\n\n **Parameters**: See `httpx.request`.\n \"\"\"\n return self.request(\n \"OPTIONS\",\n url,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n follow_redirects=follow_redirects,\n timeout=timeout,\n extensions=extensions,\n )"} {"repo":"httpx","file":"httpx/_client.py","line":1094,"symbol":"head","kind":"function","lang":"python","code":"def head(\n self,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,\n timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,\n extensions: RequestExtensions | None = None,\n ) -> Response:\n \"\"\"\n Send a `HEAD` request.\n\n **Parameters**: See `httpx.request`.\n \"\"\"\n return self.request(\n \"HEAD\",\n url,\n params=params,\n headers=headers,\n cookies=cookies,\n auth=auth,\n follow_redirects=follow_redirects,\n timeout=timeout,\n extensions=extensions,\n )"} {"repo":"httpx","file":"httpx/_config.py","line":16,"symbol":"UnsetType","kind":"class","lang":"python","code":"class UnsetType:\n pass # pragma: no cover"} {"repo":"httpx","file":"httpx/_config.py","line":23,"symbol":"create_ssl_context","kind":"function","lang":"python","code":"def create_ssl_context(\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n) -> ssl.SSLContext:\n import ssl\n import warnings\n\n import certifi\n\n if verify is True:\n if trust_env and os.environ.get(\"SSL_CERT_FILE\"): # pragma: nocover\n ctx = ssl.create_default_context(cafile=os.environ[\"SSL_CERT_FILE\"])\n elif trust_env and os.environ.get(\"SSL_CERT_DIR\"): # pragma: nocover\n ctx = ssl.create_default_context(capath=os.environ[\"SSL_CERT_DIR\"])\n else:\n # Default case...\n ctx = ssl.create_default_context(cafile=certifi.where())\n elif verify is False:\n ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n elif isinstance(verify, str): # pragma: nocover\n message = (\n \"`verify=` is deprecated. \"\n \"Use `verify=ssl.create_default_context(cafile=...)` \"\n \"or `verify=ssl.create_default_context(capath=...)` instead.\"\n )\n warnings.warn(message, DeprecationWarning)\n if os.path.isdir(verify):\n return ssl.crea"} {"repo":"httpx","file":"httpx/_config.py","line":72,"symbol":"Timeout","kind":"class","lang":"python","code":"class Timeout:\n \"\"\"\n Timeout configuration.\n\n **Usage**:\n\n Timeout(None) # No timeouts.\n Timeout(5.0) # 5s timeout on all operations.\n Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts.\n Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere.\n Timeout(5.0, pool=None) # No timeout on acquiring connection from pool.\n # 5s timeout elsewhere.\n \"\"\"\n\n def __init__(\n self,\n timeout: TimeoutTypes | UnsetType = UNSET,\n *,\n connect: None | float | UnsetType = UNSET,\n read: None | float | UnsetType = UNSET,\n write: None | float | UnsetType = UNSET,\n pool: None | float | UnsetType = UNSET,\n ) -> None:\n if isinstance(timeout, Timeout):\n # Passed as a single explicit Timeout.\n assert connect is UNSET\n assert read is UNSET\n assert write is UNSET\n assert pool is UNSET\n self.connect = timeout.connect # type: typing.Optional[float]\n self.read = timeout.read # type: typing.Optional[float]\n self.write = timeout.write # ty"} {"repo":"httpx","file":"httpx/_config.py","line":86,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n timeout: TimeoutTypes | UnsetType = UNSET,\n *,\n connect: None | float | UnsetType = UNSET,\n read: None | float | UnsetType = UNSET,\n write: None | float | UnsetType = UNSET,\n pool: None | float | UnsetType = UNSET,\n ) -> None:\n if isinstance(timeout, Timeout):\n # Passed as a single explicit Timeout.\n assert connect is UNSET\n assert read is UNSET\n assert write is UNSET\n assert pool is UNSET\n self.connect = timeout.connect # type: typing.Optional[float]\n self.read = timeout.read # type: typing.Optional[float]\n self.write = timeout.write # type: typing.Optional[float]\n self.pool = timeout.pool # type: typing.Optional[float]\n elif isinstance(timeout, tuple):\n # Passed as a tuple.\n self.connect = timeout[0]\n self.read = timeout[1]\n self.write = None if len(timeout) < 3 else timeout[2]\n self.pool = None if len(timeout) < 4 else timeout[3]\n elif not (\n isinstance(connect, UnsetType)\n or isinstance(read, UnsetType)\n "} {"repo":"httpx","file":"httpx/_config.py","line":132,"symbol":"as_dict","kind":"function","lang":"python","code":"def as_dict(self) -> dict[str, float | None]:\n return {\n \"connect\": self.connect,\n \"read\": self.read,\n \"write\": self.write,\n \"pool\": self.pool,\n }"} {"repo":"httpx","file":"httpx/_config.py","line":140,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: typing.Any) -> bool:\n return (\n isinstance(other, self.__class__)\n and self.connect == other.connect\n and self.read == other.read\n and self.write == other.write\n and self.pool == other.pool\n )"} {"repo":"httpx","file":"httpx/_config.py","line":149,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n class_name = self.__class__.__name__\n if len({self.connect, self.read, self.write, self.pool}) == 1:\n return f\"{class_name}(timeout={self.connect})\"\n return (\n f\"{class_name}(connect={self.connect}, \"\n f\"read={self.read}, write={self.write}, pool={self.pool})\"\n )"} {"repo":"httpx","file":"httpx/_config.py","line":159,"symbol":"Limits","kind":"class","lang":"python","code":"class Limits:\n \"\"\"\n Configuration for limits to various client behaviors.\n\n **Parameters:**\n\n * **max_connections** - The maximum number of concurrent connections that may be\n established.\n * **max_keepalive_connections** - Allow the connection pool to maintain\n keep-alive connections below this point. Should be less than or equal\n to `max_connections`.\n * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds.\n \"\"\"\n\n def __init__(\n self,\n *,\n max_connections: int | None = None,\n max_keepalive_connections: int | None = None,\n keepalive_expiry: float | None = 5.0,\n ) -> None:\n self.max_connections = max_connections\n self.max_keepalive_connections = max_keepalive_connections\n self.keepalive_expiry = keepalive_expiry\n\n def __eq__(self, other: typing.Any) -> bool:\n return (\n isinstance(other, self.__class__)\n and self.max_connections == other.max_connections\n and self.max_keepalive_connections == other.max_keepalive_connections\n and self.keepalive_expiry == other.keepalive_expiry\n )\n\n def"} {"repo":"httpx","file":"httpx/_config.py","line":173,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n *,\n max_connections: int | None = None,\n max_keepalive_connections: int | None = None,\n keepalive_expiry: float | None = 5.0,\n ) -> None:\n self.max_connections = max_connections\n self.max_keepalive_connections = max_keepalive_connections\n self.keepalive_expiry = keepalive_expiry"} {"repo":"httpx","file":"httpx/_config.py","line":184,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: typing.Any) -> bool:\n return (\n isinstance(other, self.__class__)\n and self.max_connections == other.max_connections\n and self.max_keepalive_connections == other.max_keepalive_connections\n and self.keepalive_expiry == other.keepalive_expiry\n )"} {"repo":"httpx","file":"httpx/_config.py","line":192,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n class_name = self.__class__.__name__\n return (\n f\"{class_name}(max_connections={self.max_connections}, \"\n f\"max_keepalive_connections={self.max_keepalive_connections}, \"\n f\"keepalive_expiry={self.keepalive_expiry})\"\n )"} {"repo":"httpx","file":"httpx/_config.py","line":201,"symbol":"Proxy","kind":"class","lang":"python","code":"class Proxy:\n def __init__(\n self,\n url: URL | str,\n *,\n ssl_context: ssl.SSLContext | None = None,\n auth: tuple[str, str] | None = None,\n headers: HeaderTypes | None = None,\n ) -> None:\n url = URL(url)\n headers = Headers(headers)\n\n if url.scheme not in (\"http\", \"https\", \"socks5\", \"socks5h\"):\n raise ValueError(f\"Unknown scheme for proxy URL {url!r}\")\n\n if url.username or url.password:\n # Remove any auth credentials from the URL.\n auth = (url.username, url.password)\n url = url.copy_with(username=None, password=None)\n\n self.url = url\n self.auth = auth\n self.headers = headers\n self.ssl_context = ssl_context\n\n @property\n def raw_auth(self) -> tuple[bytes, bytes] | None:\n # The proxy authentication as raw bytes.\n return (\n None\n if self.auth is None\n else (self.auth[0].encode(\"utf-8\"), self.auth[1].encode(\"utf-8\"))\n )\n\n def __repr__(self) -> str:\n # The authentication is represented with the password component masked.\n auth = (self.auth[0], \"********\") if self.auth "} {"repo":"httpx","file":"httpx/_config.py","line":202,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n url: URL | str,\n *,\n ssl_context: ssl.SSLContext | None = None,\n auth: tuple[str, str] | None = None,\n headers: HeaderTypes | None = None,\n ) -> None:\n url = URL(url)\n headers = Headers(headers)\n\n if url.scheme not in (\"http\", \"https\", \"socks5\", \"socks5h\"):\n raise ValueError(f\"Unknown scheme for proxy URL {url!r}\")\n\n if url.username or url.password:\n # Remove any auth credentials from the URL.\n auth = (url.username, url.password)\n url = url.copy_with(username=None, password=None)\n\n self.url = url\n self.auth = auth\n self.headers = headers\n self.ssl_context = ssl_context"} {"repo":"httpx","file":"httpx/_config.py","line":227,"symbol":"raw_auth","kind":"function","lang":"python","code":"def raw_auth(self) -> tuple[bytes, bytes] | None:\n # The proxy authentication as raw bytes.\n return (\n None\n if self.auth is None\n else (self.auth[0].encode(\"utf-8\"), self.auth[1].encode(\"utf-8\"))\n )"} {"repo":"httpx","file":"httpx/_config.py","line":235,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n # The authentication is represented with the password component masked.\n auth = (self.auth[0], \"********\") if self.auth else None\n\n # Build a nice concise representation.\n url_str = f\"{str(self.url)!r}\"\n auth_str = f\", auth={auth!r}\" if auth else \"\"\n headers_str = f\", headers={dict(self.headers)!r}\" if self.headers else \"\"\n return f\"Proxy({url_str}{auth_str}{headers_str})\""} {"repo":"httpx","file":"httpx/_content.py","line":31,"symbol":"ByteStream","kind":"class","lang":"python","code":"class ByteStream(AsyncByteStream, SyncByteStream):\n def __init__(self, stream: bytes) -> None:\n self._stream = stream\n\n def __iter__(self) -> Iterator[bytes]:\n yield self._stream\n\n async def __aiter__(self) -> AsyncIterator[bytes]:\n yield self._stream"} {"repo":"httpx","file":"httpx/_content.py","line":32,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, stream: bytes) -> None:\n self._stream = stream"} {"repo":"httpx","file":"httpx/_content.py","line":35,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> Iterator[bytes]:\n yield self._stream"} {"repo":"httpx","file":"httpx/_content.py","line":38,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> AsyncIterator[bytes]:\n yield self._stream"} {"repo":"httpx","file":"httpx/_content.py","line":42,"symbol":"IteratorByteStream","kind":"class","lang":"python","code":"class IteratorByteStream(SyncByteStream):\n CHUNK_SIZE = 65_536\n\n def __init__(self, stream: Iterable[bytes]) -> None:\n self._stream = stream\n self._is_stream_consumed = False\n self._is_generator = inspect.isgenerator(stream)\n\n def __iter__(self) -> Iterator[bytes]:\n if self._is_stream_consumed and self._is_generator:\n raise StreamConsumed()\n\n self._is_stream_consumed = True\n if hasattr(self._stream, \"read\"):\n # File-like interfaces should use 'read' directly.\n chunk = self._stream.read(self.CHUNK_SIZE)\n while chunk:\n yield chunk\n chunk = self._stream.read(self.CHUNK_SIZE)\n else:\n # Otherwise iterate.\n for part in self._stream:\n yield part"} {"repo":"httpx","file":"httpx/_content.py","line":45,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, stream: Iterable[bytes]) -> None:\n self._stream = stream\n self._is_stream_consumed = False\n self._is_generator = inspect.isgenerator(stream)"} {"repo":"httpx","file":"httpx/_content.py","line":50,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> Iterator[bytes]:\n if self._is_stream_consumed and self._is_generator:\n raise StreamConsumed()\n\n self._is_stream_consumed = True\n if hasattr(self._stream, \"read\"):\n # File-like interfaces should use 'read' directly.\n chunk = self._stream.read(self.CHUNK_SIZE)\n while chunk:\n yield chunk\n chunk = self._stream.read(self.CHUNK_SIZE)\n else:\n # Otherwise iterate.\n for part in self._stream:\n yield part"} {"repo":"httpx","file":"httpx/_content.py","line":67,"symbol":"AsyncIteratorByteStream","kind":"class","lang":"python","code":"class AsyncIteratorByteStream(AsyncByteStream):\n CHUNK_SIZE = 65_536\n\n def __init__(self, stream: AsyncIterable[bytes]) -> None:\n self._stream = stream\n self._is_stream_consumed = False\n self._is_generator = inspect.isasyncgen(stream)\n\n async def __aiter__(self) -> AsyncIterator[bytes]:\n if self._is_stream_consumed and self._is_generator:\n raise StreamConsumed()\n\n self._is_stream_consumed = True\n if hasattr(self._stream, \"aread\"):\n # File-like interfaces should use 'aread' directly.\n chunk = await self._stream.aread(self.CHUNK_SIZE)\n while chunk:\n yield chunk\n chunk = await self._stream.aread(self.CHUNK_SIZE)\n else:\n # Otherwise iterate.\n async for part in self._stream:\n yield part"} {"repo":"httpx","file":"httpx/_content.py","line":70,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, stream: AsyncIterable[bytes]) -> None:\n self._stream = stream\n self._is_stream_consumed = False\n self._is_generator = inspect.isasyncgen(stream)"} {"repo":"httpx","file":"httpx/_content.py","line":75,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> AsyncIterator[bytes]:\n if self._is_stream_consumed and self._is_generator:\n raise StreamConsumed()\n\n self._is_stream_consumed = True\n if hasattr(self._stream, \"aread\"):\n # File-like interfaces should use 'aread' directly.\n chunk = await self._stream.aread(self.CHUNK_SIZE)\n while chunk:\n yield chunk\n chunk = await self._stream.aread(self.CHUNK_SIZE)\n else:\n # Otherwise iterate.\n async for part in self._stream:\n yield part"} {"repo":"httpx","file":"httpx/_content.py","line":92,"symbol":"UnattachedStream","kind":"class","lang":"python","code":"class UnattachedStream(AsyncByteStream, SyncByteStream):\n \"\"\"\n If a request or response is serialized using pickle, then it is no longer\n attached to a stream for I/O purposes. Any stream operations should result\n in `httpx.StreamClosed`.\n \"\"\"\n\n def __iter__(self) -> Iterator[bytes]:\n raise StreamClosed()\n\n async def __aiter__(self) -> AsyncIterator[bytes]:\n raise StreamClosed()\n yield b\"\" # pragma: no cover"} {"repo":"httpx","file":"httpx/_content.py","line":99,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> Iterator[bytes]:\n raise StreamClosed()"} {"repo":"httpx","file":"httpx/_content.py","line":102,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> AsyncIterator[bytes]:\n raise StreamClosed()\n yield b\"\" # pragma: no cover"} {"repo":"httpx","file":"httpx/_content.py","line":107,"symbol":"encode_content","kind":"function","lang":"python","code":"def encode_content(\n content: str | bytes | Iterable[bytes] | AsyncIterable[bytes],\n) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:\n if isinstance(content, (bytes, str)):\n body = content.encode(\"utf-8\") if isinstance(content, str) else content\n content_length = len(body)\n headers = {\"Content-Length\": str(content_length)} if body else {}\n return headers, ByteStream(body)\n\n elif isinstance(content, Iterable) and not isinstance(content, dict):\n # `not isinstance(content, dict)` is a bit oddly specific, but it\n # catches a case that's easy for users to make in error, and would\n # otherwise pass through here, like any other bytes-iterable,\n # because `dict` happens to be iterable. See issue #2491.\n content_length_or_none = peek_filelike_length(content)\n\n if content_length_or_none is None:\n headers = {\"Transfer-Encoding\": \"chunked\"}\n else:\n headers = {\"Content-Length\": str(content_length_or_none)}\n return headers, IteratorByteStream(content) # type: ignore\n\n elif isinstance(content, AsyncIterable):\n headers = {\"Transfer-Encoding\": \"chunked\"}\n "} {"repo":"httpx","file":"httpx/_content.py","line":136,"symbol":"encode_urlencoded_data","kind":"function","lang":"python","code":"def encode_urlencoded_data(\n data: RequestData,\n) -> tuple[dict[str, str], ByteStream]:\n plain_data = []\n for key, value in data.items():\n if isinstance(value, (list, tuple)):\n plain_data.extend([(key, primitive_value_to_str(item)) for item in value])\n else:\n plain_data.append((key, primitive_value_to_str(value)))\n body = urlencode(plain_data, doseq=True).encode(\"utf-8\")\n content_length = str(len(body))\n content_type = \"application/x-www-form-urlencoded\"\n headers = {\"Content-Length\": content_length, \"Content-Type\": content_type}\n return headers, ByteStream(body)"} {"repo":"httpx","file":"httpx/_content.py","line":152,"symbol":"encode_multipart_data","kind":"function","lang":"python","code":"def encode_multipart_data(\n data: RequestData, files: RequestFiles, boundary: bytes | None\n) -> tuple[dict[str, str], MultipartStream]:\n multipart = MultipartStream(data=data, files=files, boundary=boundary)\n headers = multipart.get_headers()\n return headers, multipart"} {"repo":"httpx","file":"httpx/_content.py","line":160,"symbol":"encode_text","kind":"function","lang":"python","code":"def encode_text(text: str) -> tuple[dict[str, str], ByteStream]:\n body = text.encode(\"utf-8\")\n content_length = str(len(body))\n content_type = \"text/plain; charset=utf-8\"\n headers = {\"Content-Length\": content_length, \"Content-Type\": content_type}\n return headers, ByteStream(body)"} {"repo":"httpx","file":"httpx/_content.py","line":168,"symbol":"encode_html","kind":"function","lang":"python","code":"def encode_html(html: str) -> tuple[dict[str, str], ByteStream]:\n body = html.encode(\"utf-8\")\n content_length = str(len(body))\n content_type = \"text/html; charset=utf-8\"\n headers = {\"Content-Length\": content_length, \"Content-Type\": content_type}\n return headers, ByteStream(body)"} {"repo":"httpx","file":"httpx/_content.py","line":176,"symbol":"encode_json","kind":"function","lang":"python","code":"def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]:\n body = json_dumps(\n json, ensure_ascii=False, separators=(\",\", \":\"), allow_nan=False\n ).encode(\"utf-8\")\n content_length = str(len(body))\n content_type = \"application/json\"\n headers = {\"Content-Length\": content_length, \"Content-Type\": content_type}\n return headers, ByteStream(body)"} {"repo":"httpx","file":"httpx/_content.py","line":186,"symbol":"encode_request","kind":"function","lang":"python","code":"def encode_request(\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: Any | None = None,\n boundary: bytes | None = None,\n) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:\n \"\"\"\n Handles encoding the given `content`, `data`, `files`, and `json`,\n returning a two-tuple of (, ).\n \"\"\"\n if data is not None and not isinstance(data, Mapping):\n # We prefer to separate `content=`\n # for raw request content, and `data=
` for url encoded or\n # multipart form content.\n #\n # However for compat with requests, we *do* still support\n # `data=` usages. We deal with that case here, treating it\n # as if `content=<...>` had been supplied instead.\n message = \"Use 'content=<...>' to upload raw bytes/text content.\"\n warnings.warn(message, DeprecationWarning, stacklevel=2)\n return encode_content(data)\n\n if content is not None:\n return encode_content(content)\n elif files:\n return encode_multipart_data(data or {}, files, boundary)\n e"} {"repo":"httpx","file":"httpx/_content.py","line":221,"symbol":"encode_response","kind":"function","lang":"python","code":"def encode_response(\n content: ResponseContent | None = None,\n text: str | None = None,\n html: str | None = None,\n json: Any | None = None,\n) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:\n \"\"\"\n Handles encoding the given `content`, returning a two-tuple of\n (, ).\n \"\"\"\n if content is not None:\n return encode_content(content)\n elif text is not None:\n return encode_text(text)\n elif html is not None:\n return encode_html(html)\n elif json is not None:\n return encode_json(json)\n\n return {}, ByteStream(b\"\")"} {"repo":"httpx","file":"httpx/_decoders.py","line":36,"symbol":"ContentDecoder","kind":"class","lang":"python","code":"class ContentDecoder:\n def decode(self, data: bytes) -> bytes:\n raise NotImplementedError() # pragma: no cover\n\n def flush(self) -> bytes:\n raise NotImplementedError() # pragma: no cover"} {"repo":"httpx","file":"httpx/_decoders.py","line":37,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> bytes:\n raise NotImplementedError() # pragma: no cover"} {"repo":"httpx","file":"httpx/_decoders.py","line":40,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> bytes:\n raise NotImplementedError() # pragma: no cover"} {"repo":"httpx","file":"httpx/_decoders.py","line":44,"symbol":"IdentityDecoder","kind":"class","lang":"python","code":"class IdentityDecoder(ContentDecoder):\n \"\"\"\n Handle unencoded data.\n \"\"\"\n\n def decode(self, data: bytes) -> bytes:\n return data\n\n def flush(self) -> bytes:\n return b\"\""} {"repo":"httpx","file":"httpx/_decoders.py","line":49,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> bytes:\n return data"} {"repo":"httpx","file":"httpx/_decoders.py","line":52,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> bytes:\n return b\"\""} {"repo":"httpx","file":"httpx/_decoders.py","line":56,"symbol":"DeflateDecoder","kind":"class","lang":"python","code":"class DeflateDecoder(ContentDecoder):\n \"\"\"\n Handle 'deflate' decoding.\n\n See: https://stackoverflow.com/questions/1838699\n \"\"\"\n\n def __init__(self) -> None:\n self.first_attempt = True\n self.decompressor = zlib.decompressobj()\n\n def decode(self, data: bytes) -> bytes:\n was_first_attempt = self.first_attempt\n self.first_attempt = False\n try:\n return self.decompressor.decompress(data)\n except zlib.error as exc:\n if was_first_attempt:\n self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)\n return self.decode(data)\n raise DecodingError(str(exc)) from exc\n\n def flush(self) -> bytes:\n try:\n return self.decompressor.flush()\n except zlib.error as exc: # pragma: no cover\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":63,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.first_attempt = True\n self.decompressor = zlib.decompressobj()"} {"repo":"httpx","file":"httpx/_decoders.py","line":67,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> bytes:\n was_first_attempt = self.first_attempt\n self.first_attempt = False\n try:\n return self.decompressor.decompress(data)\n except zlib.error as exc:\n if was_first_attempt:\n self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)\n return self.decode(data)\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":78,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> bytes:\n try:\n return self.decompressor.flush()\n except zlib.error as exc: # pragma: no cover\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":85,"symbol":"GZipDecoder","kind":"class","lang":"python","code":"class GZipDecoder(ContentDecoder):\n \"\"\"\n Handle 'gzip' decoding.\n\n See: https://stackoverflow.com/questions/1838699\n \"\"\"\n\n def __init__(self) -> None:\n self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)\n\n def decode(self, data: bytes) -> bytes:\n try:\n return self.decompressor.decompress(data)\n except zlib.error as exc:\n raise DecodingError(str(exc)) from exc\n\n def flush(self) -> bytes:\n try:\n return self.decompressor.flush()\n except zlib.error as exc: # pragma: no cover\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":92,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)"} {"repo":"httpx","file":"httpx/_decoders.py","line":95,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> bytes:\n try:\n return self.decompressor.decompress(data)\n except zlib.error as exc:\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":101,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> bytes:\n try:\n return self.decompressor.flush()\n except zlib.error as exc: # pragma: no cover\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":108,"symbol":"BrotliDecoder","kind":"class","lang":"python","code":"class BrotliDecoder(ContentDecoder):\n \"\"\"\n Handle 'brotli' decoding.\n\n Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/\n or `pip install brotli`. See https://github.com/google/brotli\n Supports both 'brotlipy' and 'Brotli' packages since they share an import\n name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'\n \"\"\"\n\n def __init__(self) -> None:\n if brotli is None: # pragma: no cover\n raise ImportError(\n \"Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' \"\n \"packages have been installed. \"\n \"Make sure to install httpx using `pip install httpx[brotli]`.\"\n ) from None\n\n self.decompressor = brotli.Decompressor()\n self.seen_data = False\n self._decompress: typing.Callable[[bytes], bytes]\n if hasattr(self.decompressor, \"decompress\"):\n # The 'brotlicffi' package.\n self._decompress = self.decompressor.decompress # pragma: no cover\n else:\n # The 'brotli' package.\n self._decompress = self.decompressor.process # pragma: no cover\n\n def decode(self, "} {"repo":"httpx","file":"httpx/_decoders.py","line":118,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n if brotli is None: # pragma: no cover\n raise ImportError(\n \"Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' \"\n \"packages have been installed. \"\n \"Make sure to install httpx using `pip install httpx[brotli]`.\"\n ) from None\n\n self.decompressor = brotli.Decompressor()\n self.seen_data = False\n self._decompress: typing.Callable[[bytes], bytes]\n if hasattr(self.decompressor, \"decompress\"):\n # The 'brotlicffi' package.\n self._decompress = self.decompressor.decompress # pragma: no cover\n else:\n # The 'brotli' package.\n self._decompress = self.decompressor.process # pragma: no cover"} {"repo":"httpx","file":"httpx/_decoders.py","line":136,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> bytes:\n if not data:\n return b\"\"\n self.seen_data = True\n try:\n return self._decompress(data)\n except brotli.error as exc:\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":145,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> bytes:\n if not self.seen_data:\n return b\"\"\n try:\n if hasattr(self.decompressor, \"finish\"):\n # Only available in the 'brotlicffi' package.\n\n # As the decompressor decompresses eagerly, this\n # will never actually emit any data. However, it will potentially throw\n # errors if a truncated or damaged data stream has been used.\n self.decompressor.finish() # pragma: no cover\n return b\"\"\n except brotli.error as exc: # pragma: no cover\n raise DecodingError(str(exc)) from exc"} {"repo":"httpx","file":"httpx/_decoders.py","line":161,"symbol":"ZStandardDecoder","kind":"class","lang":"python","code":"class ZStandardDecoder(ContentDecoder):\n \"\"\"\n Handle 'zstd' RFC 8878 decoding.\n\n Requires `pip install zstandard`.\n Can be installed as a dependency of httpx using `pip install httpx[zstd]`.\n \"\"\"\n\n # inspired by the ZstdDecoder implementation in urllib3\n def __init__(self) -> None:\n if zstandard is None: # pragma: no cover\n raise ImportError(\n \"Using 'ZStandardDecoder', ...\"\n \"Make sure to install httpx using `pip install httpx[zstd]`.\"\n ) from None\n\n self.decompressor = zstandard.ZstdDecompressor().decompressobj()\n self.seen_data = False\n\n def decode(self, data: bytes) -> bytes:\n assert zstandard is not None\n self.seen_data = True\n output = io.BytesIO()\n try:\n output.write(self.decompressor.decompress(data))\n while self.decompressor.eof and self.decompressor.unused_data:\n unused_data = self.decompressor.unused_data\n self.decompressor = zstandard.ZstdDecompressor().decompressobj()\n output.write(self.decompressor.decompress(unused_data))\n except zstandard.ZstdError as exc:\n r"} {"repo":"httpx","file":"httpx/_decoders.py","line":170,"symbol":"__init__","kind":"function","lang":"python","doc":"inspired by the ZstdDecoder implementation in urllib3","code":"def __init__(self) -> None:\n if zstandard is None: # pragma: no cover\n raise ImportError(\n \"Using 'ZStandardDecoder', ...\"\n \"Make sure to install httpx using `pip install httpx[zstd]`.\"\n ) from None\n\n self.decompressor = zstandard.ZstdDecompressor().decompressobj()\n self.seen_data = False"} {"repo":"httpx","file":"httpx/_decoders.py","line":180,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> bytes:\n assert zstandard is not None\n self.seen_data = True\n output = io.BytesIO()\n try:\n output.write(self.decompressor.decompress(data))\n while self.decompressor.eof and self.decompressor.unused_data:\n unused_data = self.decompressor.unused_data\n self.decompressor = zstandard.ZstdDecompressor().decompressobj()\n output.write(self.decompressor.decompress(unused_data))\n except zstandard.ZstdError as exc:\n raise DecodingError(str(exc)) from exc\n return output.getvalue()"} {"repo":"httpx","file":"httpx/_decoders.py","line":194,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> bytes:\n if not self.seen_data:\n return b\"\"\n ret = self.decompressor.flush() # note: this is a no-op\n if not self.decompressor.eof:\n raise DecodingError(\"Zstandard data is incomplete\") # pragma: no cover\n return bytes(ret)"} {"repo":"httpx","file":"httpx/_decoders.py","line":203,"symbol":"MultiDecoder","kind":"class","lang":"python","code":"class MultiDecoder(ContentDecoder):\n \"\"\"\n Handle the case where multiple encodings have been applied.\n \"\"\"\n\n def __init__(self, children: typing.Sequence[ContentDecoder]) -> None:\n \"\"\"\n 'children' should be a sequence of decoders in the order in which\n each was applied.\n \"\"\"\n # Note that we reverse the order for decoding.\n self.children = list(reversed(children))\n\n def decode(self, data: bytes) -> bytes:\n for child in self.children:\n data = child.decode(data)\n return data\n\n def flush(self) -> bytes:\n data = b\"\"\n for child in self.children:\n data = child.decode(data) + child.flush()\n return data"} {"repo":"httpx","file":"httpx/_decoders.py","line":208,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, children: typing.Sequence[ContentDecoder]) -> None:\n \"\"\"\n 'children' should be a sequence of decoders in the order in which\n each was applied.\n \"\"\"\n # Note that we reverse the order for decoding.\n self.children = list(reversed(children))"} {"repo":"httpx","file":"httpx/_decoders.py","line":216,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> bytes:\n for child in self.children:\n data = child.decode(data)\n return data"} {"repo":"httpx","file":"httpx/_decoders.py","line":221,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> bytes:\n data = b\"\"\n for child in self.children:\n data = child.decode(data) + child.flush()\n return data"} {"repo":"httpx","file":"httpx/_decoders.py","line":228,"symbol":"ByteChunker","kind":"class","lang":"python","code":"class ByteChunker:\n \"\"\"\n Handles returning byte content in fixed-size chunks.\n \"\"\"\n\n def __init__(self, chunk_size: int | None = None) -> None:\n self._buffer = io.BytesIO()\n self._chunk_size = chunk_size\n\n def decode(self, content: bytes) -> list[bytes]:\n if self._chunk_size is None:\n return [content] if content else []\n\n self._buffer.write(content)\n if self._buffer.tell() >= self._chunk_size:\n value = self._buffer.getvalue()\n chunks = [\n value[i : i + self._chunk_size]\n for i in range(0, len(value), self._chunk_size)\n ]\n if len(chunks[-1]) == self._chunk_size:\n self._buffer.seek(0)\n self._buffer.truncate()\n return chunks\n else:\n self._buffer.seek(0)\n self._buffer.write(chunks[-1])\n self._buffer.truncate()\n return chunks[:-1]\n else:\n return []\n\n def flush(self) -> list[bytes]:\n value = self._buffer.getvalue()\n self._buffer.seek(0)\n self._buffer.truncate()\n return [value] if value else []"} {"repo":"httpx","file":"httpx/_decoders.py","line":233,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, chunk_size: int | None = None) -> None:\n self._buffer = io.BytesIO()\n self._chunk_size = chunk_size"} {"repo":"httpx","file":"httpx/_decoders.py","line":237,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, content: bytes) -> list[bytes]:\n if self._chunk_size is None:\n return [content] if content else []\n\n self._buffer.write(content)\n if self._buffer.tell() >= self._chunk_size:\n value = self._buffer.getvalue()\n chunks = [\n value[i : i + self._chunk_size]\n for i in range(0, len(value), self._chunk_size)\n ]\n if len(chunks[-1]) == self._chunk_size:\n self._buffer.seek(0)\n self._buffer.truncate()\n return chunks\n else:\n self._buffer.seek(0)\n self._buffer.write(chunks[-1])\n self._buffer.truncate()\n return chunks[:-1]\n else:\n return []"} {"repo":"httpx","file":"httpx/_decoders.py","line":260,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> list[bytes]:\n value = self._buffer.getvalue()\n self._buffer.seek(0)\n self._buffer.truncate()\n return [value] if value else []"} {"repo":"httpx","file":"httpx/_decoders.py","line":267,"symbol":"TextChunker","kind":"class","lang":"python","code":"class TextChunker:\n \"\"\"\n Handles returning text content in fixed-size chunks.\n \"\"\"\n\n def __init__(self, chunk_size: int | None = None) -> None:\n self._buffer = io.StringIO()\n self._chunk_size = chunk_size\n\n def decode(self, content: str) -> list[str]:\n if self._chunk_size is None:\n return [content] if content else []\n\n self._buffer.write(content)\n if self._buffer.tell() >= self._chunk_size:\n value = self._buffer.getvalue()\n chunks = [\n value[i : i + self._chunk_size]\n for i in range(0, len(value), self._chunk_size)\n ]\n if len(chunks[-1]) == self._chunk_size:\n self._buffer.seek(0)\n self._buffer.truncate()\n return chunks\n else:\n self._buffer.seek(0)\n self._buffer.write(chunks[-1])\n self._buffer.truncate()\n return chunks[:-1]\n else:\n return []\n\n def flush(self) -> list[str]:\n value = self._buffer.getvalue()\n self._buffer.seek(0)\n self._buffer.truncate()\n return [value] if value else []"} {"repo":"httpx","file":"httpx/_decoders.py","line":272,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, chunk_size: int | None = None) -> None:\n self._buffer = io.StringIO()\n self._chunk_size = chunk_size"} {"repo":"httpx","file":"httpx/_decoders.py","line":276,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, content: str) -> list[str]:\n if self._chunk_size is None:\n return [content] if content else []\n\n self._buffer.write(content)\n if self._buffer.tell() >= self._chunk_size:\n value = self._buffer.getvalue()\n chunks = [\n value[i : i + self._chunk_size]\n for i in range(0, len(value), self._chunk_size)\n ]\n if len(chunks[-1]) == self._chunk_size:\n self._buffer.seek(0)\n self._buffer.truncate()\n return chunks\n else:\n self._buffer.seek(0)\n self._buffer.write(chunks[-1])\n self._buffer.truncate()\n return chunks[:-1]\n else:\n return []"} {"repo":"httpx","file":"httpx/_decoders.py","line":299,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> list[str]:\n value = self._buffer.getvalue()\n self._buffer.seek(0)\n self._buffer.truncate()\n return [value] if value else []"} {"repo":"httpx","file":"httpx/_decoders.py","line":306,"symbol":"TextDecoder","kind":"class","lang":"python","code":"class TextDecoder:\n \"\"\"\n Handles incrementally decoding bytes into text\n \"\"\"\n\n def __init__(self, encoding: str = \"utf-8\") -> None:\n self.decoder = codecs.getincrementaldecoder(encoding)(errors=\"replace\")\n\n def decode(self, data: bytes) -> str:\n return self.decoder.decode(data)\n\n def flush(self) -> str:\n return self.decoder.decode(b\"\", True)"} {"repo":"httpx","file":"httpx/_decoders.py","line":311,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, encoding: str = \"utf-8\") -> None:\n self.decoder = codecs.getincrementaldecoder(encoding)(errors=\"replace\")"} {"repo":"httpx","file":"httpx/_decoders.py","line":314,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, data: bytes) -> str:\n return self.decoder.decode(data)"} {"repo":"httpx","file":"httpx/_decoders.py","line":317,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> str:\n return self.decoder.decode(b\"\", True)"} {"repo":"httpx","file":"httpx/_decoders.py","line":321,"symbol":"LineDecoder","kind":"class","lang":"python","code":"class LineDecoder:\n \"\"\"\n Handles incrementally reading lines from text.\n\n Has the same behaviour as the stdllib splitlines,\n but handling the input iteratively.\n \"\"\"\n\n def __init__(self) -> None:\n self.buffer: list[str] = []\n self.trailing_cr: bool = False\n\n def decode(self, text: str) -> list[str]:\n # See https://docs.python.org/3/library/stdtypes.html#str.splitlines\n NEWLINE_CHARS = \"\\n\\r\\x0b\\x0c\\x1c\\x1d\\x1e\\x85\\u2028\\u2029\"\n\n # We always push a trailing `\\r` into the next decode iteration.\n if self.trailing_cr:\n text = \"\\r\" + text\n self.trailing_cr = False\n if text.endswith(\"\\r\"):\n self.trailing_cr = True\n text = text[:-1]\n\n if not text:\n # NOTE: the edge case input of empty text doesn't occur in practice,\n # because other httpx internals filter out this value\n return [] # pragma: no cover\n\n trailing_newline = text[-1] in NEWLINE_CHARS\n lines = text.splitlines()\n\n if len(lines) == 1 and not trailing_newline:\n # No new lines, buffer the input and continue.\n self.buffer.append(lines[0])"} {"repo":"httpx","file":"httpx/_decoders.py","line":329,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.buffer: list[str] = []\n self.trailing_cr: bool = False"} {"repo":"httpx","file":"httpx/_decoders.py","line":333,"symbol":"decode","kind":"function","lang":"python","code":"def decode(self, text: str) -> list[str]:\n # See https://docs.python.org/3/library/stdtypes.html#str.splitlines\n NEWLINE_CHARS = \"\\n\\r\\x0b\\x0c\\x1c\\x1d\\x1e\\x85\\u2028\\u2029\"\n\n # We always push a trailing `\\r` into the next decode iteration.\n if self.trailing_cr:\n text = \"\\r\" + text\n self.trailing_cr = False\n if text.endswith(\"\\r\"):\n self.trailing_cr = True\n text = text[:-1]\n\n if not text:\n # NOTE: the edge case input of empty text doesn't occur in practice,\n # because other httpx internals filter out this value\n return [] # pragma: no cover\n\n trailing_newline = text[-1] in NEWLINE_CHARS\n lines = text.splitlines()\n\n if len(lines) == 1 and not trailing_newline:\n # No new lines, buffer the input and continue.\n self.buffer.append(lines[0])\n return []\n\n if self.buffer:\n # Include any existing buffer in the first portion of the\n # splitlines result.\n lines = [\"\".join(self.buffer) + lines[0]] + lines[1:]\n self.buffer = []\n\n if not trailing_newline:\n # "} {"repo":"httpx","file":"httpx/_decoders.py","line":371,"symbol":"flush","kind":"function","lang":"python","code":"def flush(self) -> list[str]:\n if not self.buffer and not self.trailing_cr:\n return []\n\n lines = [\"\".join(self.buffer)]\n self.buffer = []\n self.trailing_cr = False\n return lines"} {"repo":"httpx","file":"httpx/_exceptions.py","line":74,"symbol":"HTTPError","kind":"class","lang":"python","code":"class HTTPError(Exception):\n \"\"\"\n Base class for `RequestError` and `HTTPStatusError`.\n\n Useful for `try...except` blocks when issuing a request,\n and then calling `.raise_for_status()`.\n\n For example:\n\n ```\n try:\n response = httpx.get(\"https://www.example.com\")\n response.raise_for_status()\n except httpx.HTTPError as exc:\n print(f\"HTTP Exception for {exc.request.url} - {exc}\")\n ```\n \"\"\"\n\n def __init__(self, message: str) -> None:\n super().__init__(message)\n self._request: Request | None = None\n\n @property\n def request(self) -> Request:\n if self._request is None:\n raise RuntimeError(\"The .request property has not been set.\")\n return self._request\n\n @request.setter\n def request(self, request: Request) -> None:\n self._request = request"} {"repo":"httpx","file":"httpx/_exceptions.py","line":92,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, message: str) -> None:\n super().__init__(message)\n self._request: Request | None = None"} {"repo":"httpx","file":"httpx/_exceptions.py","line":97,"symbol":"request","kind":"function","lang":"python","code":"def request(self) -> Request:\n if self._request is None:\n raise RuntimeError(\"The .request property has not been set.\")\n return self._request"} {"repo":"httpx","file":"httpx/_exceptions.py","line":103,"symbol":"request","kind":"function","lang":"python","code":"def request(self, request: Request) -> None:\n self._request = request"} {"repo":"httpx","file":"httpx/_exceptions.py","line":107,"symbol":"RequestError","kind":"class","lang":"python","code":"class RequestError(HTTPError):\n \"\"\"\n Base class for all exceptions that may occur when issuing a `.request()`.\n \"\"\"\n\n def __init__(self, message: str, *, request: Request | None = None) -> None:\n super().__init__(message)\n # At the point an exception is raised we won't typically have a request\n # instance to associate it with.\n #\n # The 'request_context' context manager is used within the Client and\n # Response methods in order to ensure that any raised exceptions\n # have a `.request` property set on them.\n self._request = request"} {"repo":"httpx","file":"httpx/_exceptions.py","line":112,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, message: str, *, request: Request | None = None) -> None:\n super().__init__(message)\n # At the point an exception is raised we won't typically have a request\n # instance to associate it with.\n #\n # The 'request_context' context manager is used within the Client and\n # Response methods in order to ensure that any raised exceptions\n # have a `.request` property set on them.\n self._request = request"} {"repo":"httpx","file":"httpx/_exceptions.py","line":123,"symbol":"TransportError","kind":"class","lang":"python","code":"class TransportError(RequestError):\n \"\"\"\n Base class for all exceptions that occur at the level of the Transport API.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":132,"symbol":"TimeoutException","kind":"class","lang":"python","code":"class TimeoutException(TransportError):\n \"\"\"\n The base class for timeout errors.\n\n An operation has timed out.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":140,"symbol":"ConnectTimeout","kind":"class","lang":"python","code":"class ConnectTimeout(TimeoutException):\n \"\"\"\n Timed out while connecting to the host.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":146,"symbol":"ReadTimeout","kind":"class","lang":"python","code":"class ReadTimeout(TimeoutException):\n \"\"\"\n Timed out while receiving data from the host.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":152,"symbol":"WriteTimeout","kind":"class","lang":"python","code":"class WriteTimeout(TimeoutException):\n \"\"\"\n Timed out while sending data to the host.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":158,"symbol":"PoolTimeout","kind":"class","lang":"python","code":"class PoolTimeout(TimeoutException):\n \"\"\"\n Timed out waiting to acquire a connection from the pool.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":167,"symbol":"NetworkError","kind":"class","lang":"python","code":"class NetworkError(TransportError):\n \"\"\"\n The base class for network-related errors.\n\n An error occurred while interacting with the network.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":175,"symbol":"ReadError","kind":"class","lang":"python","code":"class ReadError(NetworkError):\n \"\"\"\n Failed to receive data from the network.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":181,"symbol":"WriteError","kind":"class","lang":"python","code":"class WriteError(NetworkError):\n \"\"\"\n Failed to send data through the network.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":187,"symbol":"ConnectError","kind":"class","lang":"python","code":"class ConnectError(NetworkError):\n \"\"\"\n Failed to establish a connection.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":193,"symbol":"CloseError","kind":"class","lang":"python","code":"class CloseError(NetworkError):\n \"\"\"\n Failed to close a connection.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":202,"symbol":"ProxyError","kind":"class","lang":"python","code":"class ProxyError(TransportError):\n \"\"\"\n An error occurred while establishing a proxy connection.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":208,"symbol":"UnsupportedProtocol","kind":"class","lang":"python","code":"class UnsupportedProtocol(TransportError):\n \"\"\"\n Attempted to make a request to an unsupported protocol.\n\n For example issuing a request to `ftp://www.example.com`.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":216,"symbol":"ProtocolError","kind":"class","lang":"python","code":"class ProtocolError(TransportError):\n \"\"\"\n The protocol was violated.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":222,"symbol":"LocalProtocolError","kind":"class","lang":"python","code":"class LocalProtocolError(ProtocolError):\n \"\"\"\n A protocol was violated by the client.\n\n For example if the user instantiated a `Request` instance explicitly,\n failed to include the mandatory `Host:` header, and then issued it directly\n using `client.send()`.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":232,"symbol":"RemoteProtocolError","kind":"class","lang":"python","code":"class RemoteProtocolError(ProtocolError):\n \"\"\"\n The protocol was violated by the server.\n\n For example, returning malformed HTTP.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":243,"symbol":"DecodingError","kind":"class","lang":"python","code":"class DecodingError(RequestError):\n \"\"\"\n Decoding of the response failed, due to a malformed encoding.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":249,"symbol":"TooManyRedirects","kind":"class","lang":"python","code":"class TooManyRedirects(RequestError):\n \"\"\"\n Too many redirects.\n \"\"\""} {"repo":"httpx","file":"httpx/_exceptions.py","line":258,"symbol":"HTTPStatusError","kind":"class","lang":"python","code":"class HTTPStatusError(HTTPError):\n \"\"\"\n The response had an error HTTP status of 4xx or 5xx.\n\n May be raised when calling `response.raise_for_status()`\n \"\"\"\n\n def __init__(self, message: str, *, request: Request, response: Response) -> None:\n super().__init__(message)\n self.request = request\n self.response = response"} {"repo":"httpx","file":"httpx/_exceptions.py","line":265,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, message: str, *, request: Request, response: Response) -> None:\n super().__init__(message)\n self.request = request\n self.response = response"} {"repo":"httpx","file":"httpx/_exceptions.py","line":271,"symbol":"InvalidURL","kind":"class","lang":"python","code":"class InvalidURL(Exception):\n \"\"\"\n URL is improperly formed or cannot be parsed.\n \"\"\"\n\n def __init__(self, message: str) -> None:\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":276,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, message: str) -> None:\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":280,"symbol":"CookieConflict","kind":"class","lang":"python","code":"class CookieConflict(Exception):\n \"\"\"\n Attempted to lookup a cookie by name, but multiple cookies existed.\n\n Can occur when calling `response.cookies.get(...)`.\n \"\"\"\n\n def __init__(self, message: str) -> None:\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":287,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, message: str) -> None:\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":297,"symbol":"StreamError","kind":"class","lang":"python","code":"class StreamError(RuntimeError):\n \"\"\"\n The base class for stream exceptions.\n\n The developer made an error in accessing the request stream in\n an invalid way.\n \"\"\"\n\n def __init__(self, message: str) -> None:\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":305,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, message: str) -> None:\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":309,"symbol":"StreamConsumed","kind":"class","lang":"python","code":"class StreamConsumed(StreamError):\n \"\"\"\n Attempted to read or stream content, but the content has already\n been streamed.\n \"\"\"\n\n def __init__(self) -> None:\n message = (\n \"Attempted to read or stream some content, but the content has \"\n \"already been streamed. For requests, this could be due to passing \"\n \"a generator as request content, and then receiving a redirect \"\n \"response or a secondary request as part of an authentication flow.\"\n \"For responses, this could be due to attempting to stream the response \"\n \"content more than once.\"\n )\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":315,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n message = (\n \"Attempted to read or stream some content, but the content has \"\n \"already been streamed. For requests, this could be due to passing \"\n \"a generator as request content, and then receiving a redirect \"\n \"response or a secondary request as part of an authentication flow.\"\n \"For responses, this could be due to attempting to stream the response \"\n \"content more than once.\"\n )\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":327,"symbol":"StreamClosed","kind":"class","lang":"python","code":"class StreamClosed(StreamError):\n \"\"\"\n Attempted to read or stream response content, but the request has been\n closed.\n \"\"\"\n\n def __init__(self) -> None:\n message = \"Attempted to read or stream content, but the stream has been closed.\"\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":333,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n message = \"Attempted to read or stream content, but the stream has been closed.\"\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":338,"symbol":"ResponseNotRead","kind":"class","lang":"python","code":"class ResponseNotRead(StreamError):\n \"\"\"\n Attempted to access streaming response content, without having called `read()`.\n \"\"\"\n\n def __init__(self) -> None:\n message = (\n \"Attempted to access streaming response content,\"\n \" without having called `read()`.\"\n )\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":343,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n message = (\n \"Attempted to access streaming response content,\"\n \" without having called `read()`.\"\n )\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":351,"symbol":"RequestNotRead","kind":"class","lang":"python","code":"class RequestNotRead(StreamError):\n \"\"\"\n Attempted to access streaming request content, without having called `read()`.\n \"\"\"\n\n def __init__(self) -> None:\n message = (\n \"Attempted to access streaming request content,\"\n \" without having called `read()`.\"\n )\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":356,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n message = (\n \"Attempted to access streaming request content,\"\n \" without having called `read()`.\"\n )\n super().__init__(message)"} {"repo":"httpx","file":"httpx/_exceptions.py","line":365,"symbol":"request_context","kind":"function","lang":"python","code":"def request_context(\n request: Request | None = None,\n) -> typing.Iterator[None]:\n \"\"\"\n A context manager that can be used to attach the given request context\n to any `RequestError` exceptions that are raised within the block.\n \"\"\"\n try:\n yield\n except RequestError as exc:\n if request is not None:\n exc.request = request\n raise exc"} {"repo":"httpx","file":"httpx/_main.py","line":26,"symbol":"print_help","kind":"function","lang":"python","code":"def print_help() -> None:\n console = rich.console.Console()\n\n console.print(\"[bold]HTTPX :butterfly:\", justify=\"center\")\n console.print()\n console.print(\"A next generation HTTP client.\", justify=\"center\")\n console.print()\n console.print(\n \"Usage: [bold]httpx[/bold] [cyan] [OPTIONS][/cyan] \", justify=\"left\"\n )\n console.print()\n\n table = rich.table.Table.grid(padding=1, pad_edge=True)\n table.add_column(\"Parameter\", no_wrap=True, justify=\"left\", style=\"bold\")\n table.add_column(\"Description\")\n table.add_row(\n \"-m, --method [cyan]METHOD\",\n \"Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\\n\"\n \"[Default: GET, or POST if a request body is included]\",\n )\n table.add_row(\n \"-p, --params [cyan] ...\",\n \"Query parameters to include in the request URL.\",\n )\n table.add_row(\n \"-c, --content [cyan]TEXT\", \"Byte content to include in the request body.\"\n )\n table.add_row(\n \"-d, --data [cyan] ...\", \"Form data to include in the request body.\"\n )\n table.add_row(\n \"-f, --files [cyan] ...\",\n \"Form files to include "} {"repo":"httpx","file":"httpx/_main.py","line":103,"symbol":"get_lexer_for_response","kind":"function","lang":"python","code":"def get_lexer_for_response(response: Response) -> str:\n content_type = response.headers.get(\"Content-Type\")\n if content_type is not None:\n mime_type, _, _ = content_type.partition(\";\")\n try:\n return typing.cast(\n str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name\n )\n except pygments.util.ClassNotFound: # pragma: no cover\n pass\n return \"\" # pragma: no cover"} {"repo":"httpx","file":"httpx/_main.py","line":116,"symbol":"format_request_headers","kind":"function","lang":"python","code":"def format_request_headers(request: httpcore.Request, http2: bool = False) -> str:\n version = \"HTTP/2\" if http2 else \"HTTP/1.1\"\n headers = [\n (name.lower() if http2 else name, value) for name, value in request.headers\n ]\n method = request.method.decode(\"ascii\")\n target = request.url.target.decode(\"ascii\")\n lines = [f\"{method} {target} {version}\"] + [\n f\"{name.decode('ascii')}: {value.decode('ascii')}\" for name, value in headers\n ]\n return \"\\n\".join(lines)"} {"repo":"httpx","file":"httpx/_main.py","line":129,"symbol":"format_response_headers","kind":"function","lang":"python","code":"def format_response_headers(\n http_version: bytes,\n status: int,\n reason_phrase: bytes | None,\n headers: list[tuple[bytes, bytes]],\n) -> str:\n version = http_version.decode(\"ascii\")\n reason = (\n codes.get_reason_phrase(status)\n if reason_phrase is None\n else reason_phrase.decode(\"ascii\")\n )\n lines = [f\"{version} {status} {reason}\"] + [\n f\"{name.decode('ascii')}: {value.decode('ascii')}\" for name, value in headers\n ]\n return \"\\n\".join(lines)"} {"repo":"httpx","file":"httpx/_main.py","line":147,"symbol":"print_request_headers","kind":"function","lang":"python","code":"def print_request_headers(request: httpcore.Request, http2: bool = False) -> None:\n console = rich.console.Console()\n http_text = format_request_headers(request, http2=http2)\n syntax = rich.syntax.Syntax(http_text, \"http\", theme=\"ansi_dark\", word_wrap=True)\n console.print(syntax)\n syntax = rich.syntax.Syntax(\"\", \"http\", theme=\"ansi_dark\", word_wrap=True)\n console.print(syntax)"} {"repo":"httpx","file":"httpx/_main.py","line":156,"symbol":"print_response_headers","kind":"function","lang":"python","code":"def print_response_headers(\n http_version: bytes,\n status: int,\n reason_phrase: bytes | None,\n headers: list[tuple[bytes, bytes]],\n) -> None:\n console = rich.console.Console()\n http_text = format_response_headers(http_version, status, reason_phrase, headers)\n syntax = rich.syntax.Syntax(http_text, \"http\", theme=\"ansi_dark\", word_wrap=True)\n console.print(syntax)\n syntax = rich.syntax.Syntax(\"\", \"http\", theme=\"ansi_dark\", word_wrap=True)\n console.print(syntax)"} {"repo":"httpx","file":"httpx/_main.py","line":170,"symbol":"print_response","kind":"function","lang":"python","code":"def print_response(response: Response) -> None:\n console = rich.console.Console()\n lexer_name = get_lexer_for_response(response)\n if lexer_name:\n if lexer_name.lower() == \"json\":\n try:\n data = response.json()\n text = json.dumps(data, indent=4)\n except ValueError: # pragma: no cover\n text = response.text\n else:\n text = response.text\n\n syntax = rich.syntax.Syntax(text, lexer_name, theme=\"ansi_dark\", word_wrap=True)\n console.print(syntax)\n else:\n console.print(f\"<{len(response.content)} bytes of binary data>\")"} {"repo":"httpx","file":"httpx/_main.py","line":194,"symbol":"format_certificate","kind":"function","lang":"python","code":"def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover\n lines = []\n for key, value in cert.items():\n if isinstance(value, (list, tuple)):\n lines.append(f\"* {key}:\")\n for item in value:\n if key in (\"subject\", \"issuer\"):\n for sub_item in item:\n lines.append(f\"* {sub_item[0]}: {sub_item[1]!r}\")\n elif isinstance(item, tuple) and len(item) == 2:\n lines.append(f\"* {item[0]}: {item[1]!r}\")\n else:\n lines.append(f\"* {item!r}\")\n else:\n lines.append(f\"* {key}: {value!r}\")\n return \"\\n\".join(lines)"} {"repo":"httpx","file":"httpx/_main.py","line":212,"symbol":"trace","kind":"function","lang":"python","code":"def trace(\n name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False\n) -> None:\n console = rich.console.Console()\n if name == \"connection.connect_tcp.started\" and verbose:\n host = info[\"host\"]\n console.print(f\"* Connecting to {host!r}\")\n elif name == \"connection.connect_tcp.complete\" and verbose:\n stream = info[\"return_value\"]\n server_addr = stream.get_extra_info(\"server_addr\")\n console.print(f\"* Connected to {server_addr[0]!r} on port {server_addr[1]}\")\n elif name == \"connection.start_tls.complete\" and verbose: # pragma: no cover\n stream = info[\"return_value\"]\n ssl_object = stream.get_extra_info(\"ssl_object\")\n version = ssl_object.version()\n cipher = ssl_object.cipher()\n server_cert = ssl_object.getpeercert()\n alpn = ssl_object.selected_alpn_protocol()\n console.print(f\"* SSL established using {version!r} / {cipher[0]!r}\")\n console.print(f\"* Selected ALPN protocol: {alpn!r}\")\n if server_cert:\n console.print(\"* Server certificate:\")\n console.print(format_certificate(server_cert))\n elif name == \"http11.send_request_headers.started\" "} {"repo":"httpx","file":"httpx/_main.py","line":251,"symbol":"download_response","kind":"function","lang":"python","code":"def download_response(response: Response, download: typing.BinaryIO) -> None:\n console = rich.console.Console()\n console.print()\n content_length = response.headers.get(\"Content-Length\")\n with rich.progress.Progress(\n \"[progress.description]{task.description}\",\n \"[progress.percentage]{task.percentage:>3.0f}%\",\n rich.progress.BarColumn(bar_width=None),\n rich.progress.DownloadColumn(),\n rich.progress.TransferSpeedColumn(),\n ) as progress:\n description = f\"Downloading [bold]{rich.markup.escape(download.name)}\"\n download_task = progress.add_task(\n description,\n total=int(content_length or 0),\n start=content_length is not None,\n )\n for chunk in response.iter_bytes():\n download.write(chunk)\n progress.update(download_task, completed=response.num_bytes_downloaded)"} {"repo":"httpx","file":"httpx/_main.py","line":273,"symbol":"validate_json","kind":"function","lang":"python","code":"def validate_json(\n ctx: click.Context,\n param: click.Option | click.Parameter,\n value: typing.Any,\n) -> typing.Any:\n if value is None:\n return None\n\n try:\n return json.loads(value)\n except json.JSONDecodeError: # pragma: no cover\n raise click.BadParameter(\"Not valid JSON\")"} {"repo":"httpx","file":"httpx/_main.py","line":287,"symbol":"validate_auth","kind":"function","lang":"python","code":"def validate_auth(\n ctx: click.Context,\n param: click.Option | click.Parameter,\n value: typing.Any,\n) -> typing.Any:\n if value == (None, None):\n return None\n\n username, password = value\n if password == \"-\": # pragma: no cover\n password = click.prompt(\"Password\", hide_input=True)\n return (username, password)"} {"repo":"httpx","file":"httpx/_main.py","line":301,"symbol":"handle_help","kind":"function","lang":"python","code":"def handle_help(\n ctx: click.Context,\n param: click.Option | click.Parameter,\n value: typing.Any,\n) -> None:\n if not value or ctx.resilient_parsing:\n return\n\n print_help()\n ctx.exit()"} {"repo":"httpx","file":"httpx/_main.py","line":452,"symbol":"main","kind":"function","lang":"python","code":"def main(\n url: str,\n method: str,\n params: list[tuple[str, str]],\n content: str,\n data: list[tuple[str, str]],\n files: list[tuple[str, click.File]],\n json: str,\n headers: list[tuple[str, str]],\n cookies: list[tuple[str, str]],\n auth: tuple[str, str] | None,\n proxy: str,\n timeout: float,\n follow_redirects: bool,\n verify: bool,\n http2: bool,\n download: typing.BinaryIO | None,\n verbose: bool,\n) -> None:\n \"\"\"\n An HTTP command line client.\n Sends a request and displays the response.\n \"\"\"\n if not method:\n method = \"POST\" if content or data or files or json else \"GET\"\n\n try:\n with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client:\n with client.stream(\n method,\n url,\n params=list(params),\n content=content,\n data=dict(data),\n files=files, # type: ignore\n json=json,\n headers=headers,\n cookies=dict(cookies),\n auth=auth,\n follow_redirects=follow_redirects,\n extensions={\"trace\": functools.partial(tr"} {"repo":"httpx","file":"httpx/_models.py","line":56,"symbol":"_is_known_encoding","kind":"function","lang":"python","code":"def _is_known_encoding(encoding: str) -> bool:\n \"\"\"\n Return `True` if `encoding` is a known codec.\n \"\"\"\n try:\n codecs.lookup(encoding)\n except LookupError:\n return False\n return True"} {"repo":"httpx","file":"httpx/_models.py","line":67,"symbol":"_normalize_header_key","kind":"function","lang":"python","code":"def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes:\n \"\"\"\n Coerce str/bytes into a strictly byte-wise HTTP header key.\n \"\"\"\n return key if isinstance(key, bytes) else key.encode(encoding or \"ascii\")"} {"repo":"httpx","file":"httpx/_models.py","line":74,"symbol":"_normalize_header_value","kind":"function","lang":"python","code":"def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes:\n \"\"\"\n Coerce str/bytes into a strictly byte-wise HTTP header value.\n \"\"\"\n if isinstance(value, bytes):\n return value\n if not isinstance(value, str):\n raise TypeError(f\"Header value must be str or bytes, not {type(value)}\")\n return value.encode(encoding or \"ascii\")"} {"repo":"httpx","file":"httpx/_models.py","line":85,"symbol":"_parse_content_type_charset","kind":"function","lang":"python","code":"def _parse_content_type_charset(content_type: str) -> str | None:\n # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery.\n # See: https://peps.python.org/pep-0594/#cgi\n msg = email.message.Message()\n msg[\"content-type\"] = content_type\n return msg.get_content_charset(failobj=None)"} {"repo":"httpx","file":"httpx/_models.py","line":93,"symbol":"_parse_header_links","kind":"function","lang":"python","code":"def _parse_header_links(value: str) -> list[dict[str, str]]:\n \"\"\"\n Returns a list of parsed link headers, for more info see:\n https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link\n The generic syntax of those is:\n Link: < uri-reference >; param1=value1; param2=\"value2\"\n So for instance:\n Link; '; type=\"image/jpeg\",;'\n would return\n [\n {\"url\": \"http:/.../front.jpeg\", \"type\": \"image/jpeg\"},\n {\"url\": \"http://.../back.jpeg\"},\n ]\n :param value: HTTP Link entity-header field\n :return: list of parsed link headers\n \"\"\"\n links: list[dict[str, str]] = []\n replace_chars = \" '\\\"\"\n value = value.strip(replace_chars)\n if not value:\n return links\n for val in re.split(\", *<\", value):\n try:\n url, params = val.split(\";\", 1)\n except ValueError:\n url, params = val, \"\"\n link = {\"url\": url.strip(\"<> '\\\"\")}\n for param in params.split(\";\"):\n try:\n key, value = param.split(\"=\")\n except ValueError:\n break\n link[key.strip(replace_chars)] = value.strip(repl"} {"repo":"httpx","file":"httpx/_models.py","line":130,"symbol":"_obfuscate_sensitive_headers","kind":"function","lang":"python","code":"def _obfuscate_sensitive_headers(\n items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]],\n) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]:\n for k, v in items:\n if to_str(k.lower()) in SENSITIVE_HEADERS:\n v = to_bytes_or_str(\"[secure]\", match_type_of=v)\n yield k, v"} {"repo":"httpx","file":"httpx/_models.py","line":139,"symbol":"Headers","kind":"class","lang":"python","code":"class Headers(typing.MutableMapping[str, str]):\n \"\"\"\n HTTP headers, as a case-insensitive multi-dict.\n \"\"\"\n\n def __init__(\n self,\n headers: HeaderTypes | None = None,\n encoding: str | None = None,\n ) -> None:\n self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]\n\n if isinstance(headers, Headers):\n self._list = list(headers._list)\n elif isinstance(headers, Mapping):\n for k, v in headers.items():\n bytes_key = _normalize_header_key(k, encoding)\n bytes_value = _normalize_header_value(v, encoding)\n self._list.append((bytes_key, bytes_key.lower(), bytes_value))\n elif headers is not None:\n for k, v in headers:\n bytes_key = _normalize_header_key(k, encoding)\n bytes_value = _normalize_header_value(v, encoding)\n self._list.append((bytes_key, bytes_key.lower(), bytes_value))\n\n self._encoding = encoding\n\n @property\n def encoding(self) -> str:\n \"\"\"\n Header encoding is mandated as ascii, but we allow fallbacks to utf-8\n or iso-8859-1.\n \"\"\"\n if se"} {"repo":"httpx","file":"httpx/_models.py","line":144,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n headers: HeaderTypes | None = None,\n encoding: str | None = None,\n ) -> None:\n self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]\n\n if isinstance(headers, Headers):\n self._list = list(headers._list)\n elif isinstance(headers, Mapping):\n for k, v in headers.items():\n bytes_key = _normalize_header_key(k, encoding)\n bytes_value = _normalize_header_value(v, encoding)\n self._list.append((bytes_key, bytes_key.lower(), bytes_value))\n elif headers is not None:\n for k, v in headers:\n bytes_key = _normalize_header_key(k, encoding)\n bytes_value = _normalize_header_value(v, encoding)\n self._list.append((bytes_key, bytes_key.lower(), bytes_value))\n\n self._encoding = encoding"} {"repo":"httpx","file":"httpx/_models.py","line":167,"symbol":"encoding","kind":"function","lang":"python","code":"def encoding(self) -> str:\n \"\"\"\n Header encoding is mandated as ascii, but we allow fallbacks to utf-8\n or iso-8859-1.\n \"\"\"\n if self._encoding is None:\n for encoding in [\"ascii\", \"utf-8\"]:\n for key, value in self.raw:\n try:\n key.decode(encoding)\n value.decode(encoding)\n except UnicodeDecodeError:\n break\n else:\n # The else block runs if 'break' did not occur, meaning\n # all values fitted the encoding.\n self._encoding = encoding\n break\n else:\n # The ISO-8859-1 encoding covers all 256 code points in a byte,\n # so will never raise decode errors.\n self._encoding = \"iso-8859-1\"\n return self._encoding"} {"repo":"httpx","file":"httpx/_models.py","line":192,"symbol":"encoding","kind":"function","lang":"python","code":"def encoding(self, value: str) -> None:\n self._encoding = value"} {"repo":"httpx","file":"httpx/_models.py","line":196,"symbol":"raw","kind":"function","lang":"python","code":"def raw(self) -> list[tuple[bytes, bytes]]:\n \"\"\"\n Returns a list of the raw header items, as byte pairs.\n \"\"\"\n return [(raw_key, value) for raw_key, _, value in self._list]"} {"repo":"httpx","file":"httpx/_models.py","line":202,"symbol":"keys","kind":"function","lang":"python","code":"def keys(self) -> typing.KeysView[str]:\n return {key.decode(self.encoding): None for _, key, value in self._list}.keys()"} {"repo":"httpx","file":"httpx/_models.py","line":205,"symbol":"values","kind":"function","lang":"python","code":"def values(self) -> typing.ValuesView[str]:\n values_dict: dict[str, str] = {}\n for _, key, value in self._list:\n str_key = key.decode(self.encoding)\n str_value = value.decode(self.encoding)\n if str_key in values_dict:\n values_dict[str_key] += f\", {str_value}\"\n else:\n values_dict[str_key] = str_value\n return values_dict.values()"} {"repo":"httpx","file":"httpx/_models.py","line":216,"symbol":"items","kind":"function","lang":"python","code":"def items(self) -> typing.ItemsView[str, str]:\n \"\"\"\n Return `(key, value)` items of headers. Concatenate headers\n into a single comma separated value when a key occurs multiple times.\n \"\"\"\n values_dict: dict[str, str] = {}\n for _, key, value in self._list:\n str_key = key.decode(self.encoding)\n str_value = value.decode(self.encoding)\n if str_key in values_dict:\n values_dict[str_key] += f\", {str_value}\"\n else:\n values_dict[str_key] = str_value\n return values_dict.items()"} {"repo":"httpx","file":"httpx/_models.py","line":231,"symbol":"multi_items","kind":"function","lang":"python","code":"def multi_items(self) -> list[tuple[str, str]]:\n \"\"\"\n Return a list of `(key, value)` pairs of headers. Allow multiple\n occurrences of the same key without concatenating into a single\n comma separated value.\n \"\"\"\n return [\n (key.decode(self.encoding), value.decode(self.encoding))\n for _, key, value in self._list\n ]"} {"repo":"httpx","file":"httpx/_models.py","line":242,"symbol":"get","kind":"function","lang":"python","code":"def get(self, key: str, default: typing.Any = None) -> typing.Any:\n \"\"\"\n Return a header value. If multiple occurrences of the header occur\n then concatenate them together with commas.\n \"\"\"\n try:\n return self[key]\n except KeyError:\n return default"} {"repo":"httpx","file":"httpx/_models.py","line":252,"symbol":"get_list","kind":"function","lang":"python","code":"def get_list(self, key: str, split_commas: bool = False) -> list[str]:\n \"\"\"\n Return a list of all header values for a given key.\n If `split_commas=True` is passed, then any comma separated header\n values are split into multiple return strings.\n \"\"\"\n get_header_key = key.lower().encode(self.encoding)\n\n values = [\n item_value.decode(self.encoding)\n for _, item_key, item_value in self._list\n if item_key.lower() == get_header_key\n ]\n\n if not split_commas:\n return values\n\n split_values = []\n for value in values:\n split_values.extend([item.strip() for item in value.split(\",\")])\n return split_values"} {"repo":"httpx","file":"httpx/_models.py","line":274,"symbol":"update","kind":"function","lang":"python","code":"def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore\n headers = Headers(headers)\n for key in headers.keys():\n if key in self:\n self.pop(key)\n self._list.extend(headers._list)"} {"repo":"httpx","file":"httpx/_models.py","line":281,"symbol":"copy","kind":"function","lang":"python","code":"def copy(self) -> Headers:\n return Headers(self, encoding=self.encoding)"} {"repo":"httpx","file":"httpx/_models.py","line":284,"symbol":"__getitem__","kind":"function","lang":"python","code":"def __getitem__(self, key: str) -> str:\n \"\"\"\n Return a single header value.\n\n If there are multiple headers with the same key, then we concatenate\n them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2\n \"\"\"\n normalized_key = key.lower().encode(self.encoding)\n\n items = [\n header_value.decode(self.encoding)\n for _, header_key, header_value in self._list\n if header_key == normalized_key\n ]\n\n if items:\n return \", \".join(items)\n\n raise KeyError(key)"} {"repo":"httpx","file":"httpx/_models.py","line":304,"symbol":"__setitem__","kind":"function","lang":"python","code":"def __setitem__(self, key: str, value: str) -> None:\n \"\"\"\n Set the header `key` to `value`, removing any duplicate entries.\n Retains insertion order.\n \"\"\"\n set_key = key.encode(self._encoding or \"utf-8\")\n set_value = value.encode(self._encoding or \"utf-8\")\n lookup_key = set_key.lower()\n\n found_indexes = [\n idx\n for idx, (_, item_key, _) in enumerate(self._list)\n if item_key == lookup_key\n ]\n\n for idx in reversed(found_indexes[1:]):\n del self._list[idx]\n\n if found_indexes:\n idx = found_indexes[0]\n self._list[idx] = (set_key, lookup_key, set_value)\n else:\n self._list.append((set_key, lookup_key, set_value))"} {"repo":"httpx","file":"httpx/_models.py","line":328,"symbol":"__delitem__","kind":"function","lang":"python","code":"def __delitem__(self, key: str) -> None:\n \"\"\"\n Remove the header `key`.\n \"\"\"\n del_key = key.lower().encode(self.encoding)\n\n pop_indexes = [\n idx\n for idx, (_, item_key, _) in enumerate(self._list)\n if item_key.lower() == del_key\n ]\n\n if not pop_indexes:\n raise KeyError(key)\n\n for idx in reversed(pop_indexes):\n del self._list[idx]"} {"repo":"httpx","file":"httpx/_models.py","line":346,"symbol":"__contains__","kind":"function","lang":"python","code":"def __contains__(self, key: typing.Any) -> bool:\n header_key = key.lower().encode(self.encoding)\n return header_key in [key for _, key, _ in self._list]"} {"repo":"httpx","file":"httpx/_models.py","line":350,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> typing.Iterator[typing.Any]:\n return iter(self.keys())"} {"repo":"httpx","file":"httpx/_models.py","line":353,"symbol":"__len__","kind":"function","lang":"python","code":"def __len__(self) -> int:\n return len(self._list)"} {"repo":"httpx","file":"httpx/_models.py","line":356,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: typing.Any) -> bool:\n try:\n other_headers = Headers(other)\n except ValueError:\n return False\n\n self_list = [(key, value) for _, key, value in self._list]\n other_list = [(key, value) for _, key, value in other_headers._list]\n return sorted(self_list) == sorted(other_list)"} {"repo":"httpx","file":"httpx/_models.py","line":366,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n class_name = self.__class__.__name__\n\n encoding_str = \"\"\n if self.encoding != \"ascii\":\n encoding_str = f\", encoding={self.encoding!r}\"\n\n as_list = list(_obfuscate_sensitive_headers(self.multi_items()))\n as_dict = dict(as_list)\n\n no_duplicate_keys = len(as_dict) == len(as_list)\n if no_duplicate_keys:\n return f\"{class_name}({as_dict!r}{encoding_str})\"\n return f\"{class_name}({as_list!r}{encoding_str})\""} {"repo":"httpx","file":"httpx/_models.py","line":382,"symbol":"Request","kind":"class","lang":"python","code":"class Request:\n def __init__(\n self,\n method: str,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n stream: SyncByteStream | AsyncByteStream | None = None,\n extensions: RequestExtensions | None = None,\n ) -> None:\n self.method = method.upper()\n self.url = URL(url) if params is None else URL(url, params=params)\n self.headers = Headers(headers)\n self.extensions = {} if extensions is None else dict(extensions)\n\n if cookies:\n Cookies(cookies).set_cookie_header(self)\n\n if stream is None:\n content_type: str | None = self.headers.get(\"content-type\")\n headers, stream = encode_request(\n content=content,\n data=data,\n files=files,\n json=json,\n boundary=get_multipart_boundary_from_content_type(\n content_typ"} {"repo":"httpx","file":"httpx/_models.py","line":383,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n method: str,\n url: URL | str,\n *,\n params: QueryParamTypes | None = None,\n headers: HeaderTypes | None = None,\n cookies: CookieTypes | None = None,\n content: RequestContent | None = None,\n data: RequestData | None = None,\n files: RequestFiles | None = None,\n json: typing.Any | None = None,\n stream: SyncByteStream | AsyncByteStream | None = None,\n extensions: RequestExtensions | None = None,\n ) -> None:\n self.method = method.upper()\n self.url = URL(url) if params is None else URL(url, params=params)\n self.headers = Headers(headers)\n self.extensions = {} if extensions is None else dict(extensions)\n\n if cookies:\n Cookies(cookies).set_cookie_header(self)\n\n if stream is None:\n content_type: str | None = self.headers.get(\"content-type\")\n headers, stream = encode_request(\n content=content,\n data=data,\n files=files,\n json=json,\n boundary=get_multipart_boundary_from_content_type(\n content_type=content_type.enco"} {"repo":"httpx","file":"httpx/_models.py","line":441,"symbol":"_prepare","kind":"function","lang":"python","code":"def _prepare(self, default_headers: dict[str, str]) -> None:\n for key, value in default_headers.items():\n # Ignore Transfer-Encoding if the Content-Length has been set explicitly.\n if key.lower() == \"transfer-encoding\" and \"Content-Length\" in self.headers:\n continue\n self.headers.setdefault(key, value)\n\n auto_headers: list[tuple[bytes, bytes]] = []\n\n has_host = \"Host\" in self.headers\n has_content_length = (\n \"Content-Length\" in self.headers or \"Transfer-Encoding\" in self.headers\n )\n\n if not has_host and self.url.host:\n auto_headers.append((b\"Host\", self.url.netloc))\n if not has_content_length and self.method in (\"POST\", \"PUT\", \"PATCH\"):\n auto_headers.append((b\"Content-Length\", b\"0\"))\n\n self.headers = Headers(auto_headers + self.headers.raw)"} {"repo":"httpx","file":"httpx/_models.py","line":463,"symbol":"content","kind":"function","lang":"python","code":"def content(self) -> bytes:\n if not hasattr(self, \"_content\"):\n raise RequestNotRead()\n return self._content"} {"repo":"httpx","file":"httpx/_models.py","line":468,"symbol":"read","kind":"function","lang":"python","code":"def read(self) -> bytes:\n \"\"\"\n Read and return the request content.\n \"\"\"\n if not hasattr(self, \"_content\"):\n assert isinstance(self.stream, typing.Iterable)\n self._content = b\"\".join(self.stream)\n if not isinstance(self.stream, ByteStream):\n # If a streaming request has been read entirely into memory, then\n # we can replace the stream with a raw bytes implementation,\n # to ensure that any non-replayable streams can still be used.\n self.stream = ByteStream(self._content)\n return self._content"} {"repo":"httpx","file":"httpx/_models.py","line":482,"symbol":"aread","kind":"function","lang":"python","code":"async def aread(self) -> bytes:\n \"\"\"\n Read and return the request content.\n \"\"\"\n if not hasattr(self, \"_content\"):\n assert isinstance(self.stream, typing.AsyncIterable)\n self._content = b\"\".join([part async for part in self.stream])\n if not isinstance(self.stream, ByteStream):\n # If a streaming request has been read entirely into memory, then\n # we can replace the stream with a raw bytes implementation,\n # to ensure that any non-replayable streams can still be used.\n self.stream = ByteStream(self._content)\n return self._content"} {"repo":"httpx","file":"httpx/_models.py","line":496,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n class_name = self.__class__.__name__\n url = str(self.url)\n return f\"<{class_name}({self.method!r}, {url!r})>\""} {"repo":"httpx","file":"httpx/_models.py","line":501,"symbol":"__getstate__","kind":"function","lang":"python","code":"def __getstate__(self) -> dict[str, typing.Any]:\n return {\n name: value\n for name, value in self.__dict__.items()\n if name not in [\"extensions\", \"stream\"]\n }"} {"repo":"httpx","file":"httpx/_models.py","line":508,"symbol":"__setstate__","kind":"function","lang":"python","code":"def __setstate__(self, state: dict[str, typing.Any]) -> None:\n for name, value in state.items():\n setattr(self, name, value)\n self.extensions = {}\n self.stream = UnattachedStream()"} {"repo":"httpx","file":"httpx/_models.py","line":515,"symbol":"Response","kind":"class","lang":"python","code":"class Response:\n def __init__(\n self,\n status_code: int,\n *,\n headers: HeaderTypes | None = None,\n content: ResponseContent | None = None,\n text: str | None = None,\n html: str | None = None,\n json: typing.Any = None,\n stream: SyncByteStream | AsyncByteStream | None = None,\n request: Request | None = None,\n extensions: ResponseExtensions | None = None,\n history: list[Response] | None = None,\n default_encoding: str | typing.Callable[[bytes], str] = \"utf-8\",\n ) -> None:\n self.status_code = status_code\n self.headers = Headers(headers)\n\n self._request: Request | None = request\n\n # When follow_redirects=False and a redirect is received,\n # the client will set `response.next_request`.\n self.next_request: Request | None = None\n\n self.extensions = {} if extensions is None else dict(extensions)\n self.history = [] if history is None else list(history)\n\n self.is_closed = False\n self.is_stream_consumed = False\n\n self.default_encoding = default_encoding\n\n if stream is None:\n headers, stream = encode_respons"} {"repo":"httpx","file":"httpx/_models.py","line":516,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n status_code: int,\n *,\n headers: HeaderTypes | None = None,\n content: ResponseContent | None = None,\n text: str | None = None,\n html: str | None = None,\n json: typing.Any = None,\n stream: SyncByteStream | AsyncByteStream | None = None,\n request: Request | None = None,\n extensions: ResponseExtensions | None = None,\n history: list[Response] | None = None,\n default_encoding: str | typing.Callable[[bytes], str] = \"utf-8\",\n ) -> None:\n self.status_code = status_code\n self.headers = Headers(headers)\n\n self._request: Request | None = request\n\n # When follow_redirects=False and a redirect is received,\n # the client will set `response.next_request`.\n self.next_request: Request | None = None\n\n self.extensions = {} if extensions is None else dict(extensions)\n self.history = [] if history is None else list(history)\n\n self.is_closed = False\n self.is_stream_consumed = False\n\n self.default_encoding = default_encoding\n\n if stream is None:\n headers, stream = encode_response(content, text, htm"} {"repo":"httpx","file":"httpx/_models.py","line":571,"symbol":"_prepare","kind":"function","lang":"python","code":"def _prepare(self, default_headers: dict[str, str]) -> None:\n for key, value in default_headers.items():\n # Ignore Transfer-Encoding if the Content-Length has been set explicitly.\n if key.lower() == \"transfer-encoding\" and \"content-length\" in self.headers:\n continue\n self.headers.setdefault(key, value)"} {"repo":"httpx","file":"httpx/_models.py","line":579,"symbol":"elapsed","kind":"function","lang":"python","code":"def elapsed(self) -> datetime.timedelta:\n \"\"\"\n Returns the time taken for the complete request/response\n cycle to complete.\n \"\"\"\n if not hasattr(self, \"_elapsed\"):\n raise RuntimeError(\n \"'.elapsed' may only be accessed after the response \"\n \"has been read or closed.\"\n )\n return self._elapsed"} {"repo":"httpx","file":"httpx/_models.py","line":592,"symbol":"elapsed","kind":"function","lang":"python","code":"def elapsed(self, elapsed: datetime.timedelta) -> None:\n self._elapsed = elapsed"} {"repo":"httpx","file":"httpx/_models.py","line":596,"symbol":"request","kind":"function","lang":"python","code":"def request(self) -> Request:\n \"\"\"\n Returns the request instance associated to the current response.\n \"\"\"\n if self._request is None:\n raise RuntimeError(\n \"The request instance has not been set on this response.\"\n )\n return self._request"} {"repo":"httpx","file":"httpx/_models.py","line":607,"symbol":"request","kind":"function","lang":"python","code":"def request(self, value: Request) -> None:\n self._request = value"} {"repo":"httpx","file":"httpx/_models.py","line":611,"symbol":"http_version","kind":"function","lang":"python","code":"def http_version(self) -> str:\n try:\n http_version: bytes = self.extensions[\"http_version\"]\n except KeyError:\n return \"HTTP/1.1\"\n else:\n return http_version.decode(\"ascii\", errors=\"ignore\")"} {"repo":"httpx","file":"httpx/_models.py","line":620,"symbol":"reason_phrase","kind":"function","lang":"python","code":"def reason_phrase(self) -> str:\n try:\n reason_phrase: bytes = self.extensions[\"reason_phrase\"]\n except KeyError:\n return codes.get_reason_phrase(self.status_code)\n else:\n return reason_phrase.decode(\"ascii\", errors=\"ignore\")"} {"repo":"httpx","file":"httpx/_models.py","line":629,"symbol":"url","kind":"function","lang":"python","code":"def url(self) -> URL:\n \"\"\"\n Returns the URL for which the request was made.\n \"\"\"\n return self.request.url"} {"repo":"httpx","file":"httpx/_models.py","line":636,"symbol":"content","kind":"function","lang":"python","code":"def content(self) -> bytes:\n if not hasattr(self, \"_content\"):\n raise ResponseNotRead()\n return self._content"} {"repo":"httpx","file":"httpx/_models.py","line":642,"symbol":"text","kind":"function","lang":"python","code":"def text(self) -> str:\n if not hasattr(self, \"_text\"):\n content = self.content\n if not content:\n self._text = \"\"\n else:\n decoder = TextDecoder(encoding=self.encoding or \"utf-8\")\n self._text = \"\".join([decoder.decode(self.content), decoder.flush()])\n return self._text"} {"repo":"httpx","file":"httpx/_models.py","line":653,"symbol":"encoding","kind":"function","lang":"python","code":"def encoding(self) -> str | None:\n \"\"\"\n Return an encoding to use for decoding the byte content into text.\n The priority for determining this is given by...\n\n * `.encoding = <>` has been set explicitly.\n * The encoding as specified by the charset parameter in the Content-Type header.\n * The encoding as determined by `default_encoding`, which may either be\n a string like \"utf-8\" indicating the encoding to use, or may be a callable\n which enables charset autodetection.\n \"\"\"\n if not hasattr(self, \"_encoding\"):\n encoding = self.charset_encoding\n if encoding is None or not _is_known_encoding(encoding):\n if isinstance(self.default_encoding, str):\n encoding = self.default_encoding\n elif hasattr(self, \"_content\"):\n encoding = self.default_encoding(self._content)\n self._encoding = encoding or \"utf-8\"\n return self._encoding"} {"repo":"httpx","file":"httpx/_models.py","line":675,"symbol":"encoding","kind":"function","lang":"python","code":"def encoding(self, value: str) -> None:\n \"\"\"\n Set the encoding to use for decoding the byte content into text.\n\n If the `text` attribute has been accessed, attempting to set the\n encoding will throw a ValueError.\n \"\"\"\n if hasattr(self, \"_text\"):\n raise ValueError(\n \"Setting encoding after `text` has been accessed is not allowed.\"\n )\n self._encoding = value"} {"repo":"httpx","file":"httpx/_models.py","line":689,"symbol":"charset_encoding","kind":"function","lang":"python","code":"def charset_encoding(self) -> str | None:\n \"\"\"\n Return the encoding, as specified by the Content-Type header.\n \"\"\"\n content_type = self.headers.get(\"Content-Type\")\n if content_type is None:\n return None\n\n return _parse_content_type_charset(content_type)"} {"repo":"httpx","file":"httpx/_models.py","line":699,"symbol":"_get_content_decoder","kind":"function","lang":"python","code":"def _get_content_decoder(self) -> ContentDecoder:\n \"\"\"\n Returns a decoder instance which can be used to decode the raw byte\n content, depending on the Content-Encoding used in the response.\n \"\"\"\n if not hasattr(self, \"_decoder\"):\n decoders: list[ContentDecoder] = []\n values = self.headers.get_list(\"content-encoding\", split_commas=True)\n for value in values:\n value = value.strip().lower()\n try:\n decoder_cls = SUPPORTED_DECODERS[value]\n decoders.append(decoder_cls())\n except KeyError:\n continue\n\n if len(decoders) == 1:\n self._decoder = decoders[0]\n elif len(decoders) > 1:\n self._decoder = MultiDecoder(children=decoders)\n else:\n self._decoder = IdentityDecoder()\n\n return self._decoder"} {"repo":"httpx","file":"httpx/_models.py","line":725,"symbol":"is_informational","kind":"function","lang":"python","code":"def is_informational(self) -> bool:\n \"\"\"\n A property which is `True` for 1xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_informational(self.status_code)"} {"repo":"httpx","file":"httpx/_models.py","line":732,"symbol":"is_success","kind":"function","lang":"python","code":"def is_success(self) -> bool:\n \"\"\"\n A property which is `True` for 2xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_success(self.status_code)"} {"repo":"httpx","file":"httpx/_models.py","line":739,"symbol":"is_redirect","kind":"function","lang":"python","code":"def is_redirect(self) -> bool:\n \"\"\"\n A property which is `True` for 3xx status codes, `False` otherwise.\n\n Note that not all responses with a 3xx status code indicate a URL redirect.\n\n Use `response.has_redirect_location` to determine responses with a properly\n formed URL redirection.\n \"\"\"\n return codes.is_redirect(self.status_code)"} {"repo":"httpx","file":"httpx/_models.py","line":751,"symbol":"is_client_error","kind":"function","lang":"python","code":"def is_client_error(self) -> bool:\n \"\"\"\n A property which is `True` for 4xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_client_error(self.status_code)"} {"repo":"httpx","file":"httpx/_models.py","line":758,"symbol":"is_server_error","kind":"function","lang":"python","code":"def is_server_error(self) -> bool:\n \"\"\"\n A property which is `True` for 5xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_server_error(self.status_code)"} {"repo":"httpx","file":"httpx/_models.py","line":765,"symbol":"is_error","kind":"function","lang":"python","code":"def is_error(self) -> bool:\n \"\"\"\n A property which is `True` for 4xx and 5xx status codes, `False` otherwise.\n \"\"\"\n return codes.is_error(self.status_code)"} {"repo":"httpx","file":"httpx/_models.py","line":772,"symbol":"has_redirect_location","kind":"function","lang":"python","code":"def has_redirect_location(self) -> bool:\n \"\"\"\n Returns True for 3xx responses with a properly formed URL redirection,\n `False` otherwise.\n \"\"\"\n return (\n self.status_code\n in (\n # 301 (Cacheable redirect. Method may change to GET.)\n codes.MOVED_PERMANENTLY,\n # 302 (Uncacheable redirect. Method may change to GET.)\n codes.FOUND,\n # 303 (Client should make a GET or HEAD request.)\n codes.SEE_OTHER,\n # 307 (Equiv. 302, but retain method)\n codes.TEMPORARY_REDIRECT,\n # 308 (Equiv. 301, but retain method)\n codes.PERMANENT_REDIRECT,\n )\n and \"Location\" in self.headers\n )"} {"repo":"httpx","file":"httpx/_models.py","line":794,"symbol":"raise_for_status","kind":"function","lang":"python","code":"def raise_for_status(self) -> Response:\n \"\"\"\n Raise the `HTTPStatusError` if one occurred.\n \"\"\"\n request = self._request\n if request is None:\n raise RuntimeError(\n \"Cannot call `raise_for_status` as the request \"\n \"instance has not been set on this response.\"\n )\n\n if self.is_success:\n return self\n\n if self.has_redirect_location:\n message = (\n \"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\\n\"\n \"Redirect location: '{0.headers[location]}'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}\"\n )\n else:\n message = (\n \"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}\"\n )\n\n status_class = self.status_code // 100\n error_types = {\n 1: \"Informational response\",\n 3: \"Redirect response\",\n 4: \"Client error\",\n "} {"repo":"httpx","file":"httpx/_multipart.py","line":33,"symbol":"_format_form_param","kind":"function","lang":"python","code":"def _format_form_param(name: str, value: str) -> bytes:\n \"\"\"\n Encode a name/value pair within a multipart form.\n \"\"\"\n\n def replacer(match: typing.Match[str]) -> str:\n return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]\n\n value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)\n return f'{name}=\"{value}\"'.encode()"} {"repo":"httpx","file":"httpx/_multipart.py","line":38,"symbol":"replacer","kind":"function","lang":"python","code":"def replacer(match: typing.Match[str]) -> str:\n return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]"} {"repo":"httpx","file":"httpx/_multipart.py","line":45,"symbol":"_guess_content_type","kind":"function","lang":"python","code":"def _guess_content_type(filename: str | None) -> str | None:\n \"\"\"\n Guesses the mimetype based on a filename. Defaults to `application/octet-stream`.\n\n Returns `None` if `filename` is `None` or empty.\n \"\"\"\n if filename:\n return mimetypes.guess_type(filename)[0] or \"application/octet-stream\"\n return None"} {"repo":"httpx","file":"httpx/_multipart.py","line":56,"symbol":"get_multipart_boundary_from_content_type","kind":"function","lang":"python","code":"def get_multipart_boundary_from_content_type(\n content_type: bytes | None,\n) -> bytes | None:\n if not content_type or not content_type.startswith(b\"multipart/form-data\"):\n return None\n # parse boundary according to\n # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1\n if b\";\" in content_type:\n for section in content_type.split(b\";\"):\n if section.strip().lower().startswith(b\"boundary=\"):\n return section.strip()[len(b\"boundary=\") :].strip(b'\"')\n return None"} {"repo":"httpx","file":"httpx/_multipart.py","line":70,"symbol":"DataField","kind":"class","lang":"python","code":"class DataField:\n \"\"\"\n A single form field item, within a multipart form field.\n \"\"\"\n\n def __init__(self, name: str, value: str | bytes | int | float | None) -> None:\n if not isinstance(name, str):\n raise TypeError(\n f\"Invalid type for name. Expected str, got {type(name)}: {name!r}\"\n )\n if value is not None and not isinstance(value, (str, bytes, int, float)):\n raise TypeError(\n \"Invalid type for value. Expected primitive type,\"\n f\" got {type(value)}: {value!r}\"\n )\n self.name = name\n self.value: str | bytes = (\n value if isinstance(value, bytes) else primitive_value_to_str(value)\n )\n\n def render_headers(self) -> bytes:\n if not hasattr(self, \"_headers\"):\n name = _format_form_param(\"name\", self.name)\n self._headers = b\"\".join(\n [b\"Content-Disposition: form-data; \", name, b\"\\r\\n\\r\\n\"]\n )\n\n return self._headers\n\n def render_data(self) -> bytes:\n if not hasattr(self, \"_data\"):\n self._data = to_bytes(self.value)\n\n return self._data\n\n def get_length(s"} {"repo":"httpx","file":"httpx/_multipart.py","line":75,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, name: str, value: str | bytes | int | float | None) -> None:\n if not isinstance(name, str):\n raise TypeError(\n f\"Invalid type for name. Expected str, got {type(name)}: {name!r}\"\n )\n if value is not None and not isinstance(value, (str, bytes, int, float)):\n raise TypeError(\n \"Invalid type for value. Expected primitive type,\"\n f\" got {type(value)}: {value!r}\"\n )\n self.name = name\n self.value: str | bytes = (\n value if isinstance(value, bytes) else primitive_value_to_str(value)\n )"} {"repo":"httpx","file":"httpx/_multipart.py","line":90,"symbol":"render_headers","kind":"function","lang":"python","code":"def render_headers(self) -> bytes:\n if not hasattr(self, \"_headers\"):\n name = _format_form_param(\"name\", self.name)\n self._headers = b\"\".join(\n [b\"Content-Disposition: form-data; \", name, b\"\\r\\n\\r\\n\"]\n )\n\n return self._headers"} {"repo":"httpx","file":"httpx/_multipart.py","line":99,"symbol":"render_data","kind":"function","lang":"python","code":"def render_data(self) -> bytes:\n if not hasattr(self, \"_data\"):\n self._data = to_bytes(self.value)\n\n return self._data"} {"repo":"httpx","file":"httpx/_multipart.py","line":105,"symbol":"get_length","kind":"function","lang":"python","code":"def get_length(self) -> int:\n headers = self.render_headers()\n data = self.render_data()\n return len(headers) + len(data)"} {"repo":"httpx","file":"httpx/_multipart.py","line":110,"symbol":"render","kind":"function","lang":"python","code":"def render(self) -> typing.Iterator[bytes]:\n yield self.render_headers()\n yield self.render_data()"} {"repo":"httpx","file":"httpx/_multipart.py","line":115,"symbol":"FileField","kind":"class","lang":"python","code":"class FileField:\n \"\"\"\n A single file field item, within a multipart form field.\n \"\"\"\n\n CHUNK_SIZE = 64 * 1024\n\n def __init__(self, name: str, value: FileTypes) -> None:\n self.name = name\n\n fileobj: FileContent\n\n headers: dict[str, str] = {}\n content_type: str | None = None\n\n # This large tuple based API largely mirror's requests' API\n # It would be good to think of better APIs for this that we could\n # include in httpx 2.0 since variable length tuples(especially of 4 elements)\n # are quite unwieldly\n if isinstance(value, tuple):\n if len(value) == 2:\n # neither the 3rd parameter (content_type) nor the 4th (headers)\n # was included\n filename, fileobj = value\n elif len(value) == 3:\n filename, fileobj, content_type = value\n else:\n # all 4 parameters included\n filename, fileobj, content_type, headers = value # type: ignore\n else:\n filename = Path(str(getattr(value, \"name\", \"upload\"))).name\n fileobj = value\n\n if content_type is None:\n content_"} {"repo":"httpx","file":"httpx/_multipart.py","line":122,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, name: str, value: FileTypes) -> None:\n self.name = name\n\n fileobj: FileContent\n\n headers: dict[str, str] = {}\n content_type: str | None = None\n\n # This large tuple based API largely mirror's requests' API\n # It would be good to think of better APIs for this that we could\n # include in httpx 2.0 since variable length tuples(especially of 4 elements)\n # are quite unwieldly\n if isinstance(value, tuple):\n if len(value) == 2:\n # neither the 3rd parameter (content_type) nor the 4th (headers)\n # was included\n filename, fileobj = value\n elif len(value) == 3:\n filename, fileobj, content_type = value\n else:\n # all 4 parameters included\n filename, fileobj, content_type, headers = value # type: ignore\n else:\n filename = Path(str(getattr(value, \"name\", \"upload\"))).name\n fileobj = value\n\n if content_type is None:\n content_type = _guess_content_type(filename)\n\n has_content_type_header = any(\"content-type\" in key.lower() for key in headers)\n "} {"repo":"httpx","file":"httpx/_multipart.py","line":171,"symbol":"get_length","kind":"function","lang":"python","code":"def get_length(self) -> int | None:\n headers = self.render_headers()\n\n if isinstance(self.file, (str, bytes)):\n return len(headers) + len(to_bytes(self.file))\n\n file_length = peek_filelike_length(self.file)\n\n # If we can't determine the filesize without reading it into memory,\n # then return `None` here, to indicate an unknown file length.\n if file_length is None:\n return None\n\n return len(headers) + file_length"} {"repo":"httpx","file":"httpx/_multipart.py","line":186,"symbol":"render_headers","kind":"function","lang":"python","code":"def render_headers(self) -> bytes:\n if not hasattr(self, \"_headers\"):\n parts = [\n b\"Content-Disposition: form-data; \",\n _format_form_param(\"name\", self.name),\n ]\n if self.filename:\n filename = _format_form_param(\"filename\", self.filename)\n parts.extend([b\"; \", filename])\n for header_name, header_value in self.headers.items():\n key, val = f\"\\r\\n{header_name}: \".encode(), header_value.encode()\n parts.extend([key, val])\n parts.append(b\"\\r\\n\\r\\n\")\n self._headers = b\"\".join(parts)\n\n return self._headers"} {"repo":"httpx","file":"httpx/_multipart.py","line":203,"symbol":"render_data","kind":"function","lang":"python","code":"def render_data(self) -> typing.Iterator[bytes]:\n if isinstance(self.file, (str, bytes)):\n yield to_bytes(self.file)\n return\n\n if hasattr(self.file, \"seek\"):\n try:\n self.file.seek(0)\n except io.UnsupportedOperation:\n pass\n\n chunk = self.file.read(self.CHUNK_SIZE)\n while chunk:\n yield to_bytes(chunk)\n chunk = self.file.read(self.CHUNK_SIZE)"} {"repo":"httpx","file":"httpx/_multipart.py","line":219,"symbol":"render","kind":"function","lang":"python","code":"def render(self) -> typing.Iterator[bytes]:\n yield self.render_headers()\n yield from self.render_data()"} {"repo":"httpx","file":"httpx/_multipart.py","line":224,"symbol":"MultipartStream","kind":"class","lang":"python","code":"class MultipartStream(SyncByteStream, AsyncByteStream):\n \"\"\"\n Request content as streaming multipart encoded form data.\n \"\"\"\n\n def __init__(\n self,\n data: RequestData,\n files: RequestFiles,\n boundary: bytes | None = None,\n ) -> None:\n if boundary is None:\n boundary = os.urandom(16).hex().encode(\"ascii\")\n\n self.boundary = boundary\n self.content_type = \"multipart/form-data; boundary=%s\" % boundary.decode(\n \"ascii\"\n )\n self.fields = list(self._iter_fields(data, files))\n\n def _iter_fields(\n self, data: RequestData, files: RequestFiles\n ) -> typing.Iterator[FileField | DataField]:\n for name, value in data.items():\n if isinstance(value, (tuple, list)):\n for item in value:\n yield DataField(name=name, value=item)\n else:\n yield DataField(name=name, value=value)\n\n file_items = files.items() if isinstance(files, typing.Mapping) else files\n for name, value in file_items:\n yield FileField(name=name, value=value)\n\n def iter_chunks(self) -> typing.Iterator[bytes]:\n for field"} {"repo":"httpx","file":"httpx/_multipart.py","line":229,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n data: RequestData,\n files: RequestFiles,\n boundary: bytes | None = None,\n ) -> None:\n if boundary is None:\n boundary = os.urandom(16).hex().encode(\"ascii\")\n\n self.boundary = boundary\n self.content_type = \"multipart/form-data; boundary=%s\" % boundary.decode(\n \"ascii\"\n )\n self.fields = list(self._iter_fields(data, files))"} {"repo":"httpx","file":"httpx/_multipart.py","line":244,"symbol":"_iter_fields","kind":"function","lang":"python","code":"def _iter_fields(\n self, data: RequestData, files: RequestFiles\n ) -> typing.Iterator[FileField | DataField]:\n for name, value in data.items():\n if isinstance(value, (tuple, list)):\n for item in value:\n yield DataField(name=name, value=item)\n else:\n yield DataField(name=name, value=value)\n\n file_items = files.items() if isinstance(files, typing.Mapping) else files\n for name, value in file_items:\n yield FileField(name=name, value=value)"} {"repo":"httpx","file":"httpx/_multipart.py","line":258,"symbol":"iter_chunks","kind":"function","lang":"python","code":"def iter_chunks(self) -> typing.Iterator[bytes]:\n for field in self.fields:\n yield b\"--%s\\r\\n\" % self.boundary\n yield from field.render()\n yield b\"\\r\\n\"\n yield b\"--%s--\\r\\n\" % self.boundary"} {"repo":"httpx","file":"httpx/_multipart.py","line":265,"symbol":"get_content_length","kind":"function","lang":"python","code":"def get_content_length(self) -> int | None:\n \"\"\"\n Return the length of the multipart encoded content, or `None` if\n any of the files have a length that cannot be determined upfront.\n \"\"\"\n boundary_length = len(self.boundary)\n length = 0\n\n for field in self.fields:\n field_length = field.get_length()\n if field_length is None:\n return None\n\n length += 2 + boundary_length + 2 # b\"--{boundary}\\r\\n\"\n length += field_length\n length += 2 # b\"\\r\\n\"\n\n length += 2 + boundary_length + 4 # b\"--{boundary}--\\r\\n\"\n return length"} {"repo":"httpx","file":"httpx/_multipart.py","line":287,"symbol":"get_headers","kind":"function","lang":"python","code":"def get_headers(self) -> dict[str, str]:\n content_length = self.get_content_length()\n content_type = self.content_type\n if content_length is None:\n return {\"Transfer-Encoding\": \"chunked\", \"Content-Type\": content_type}\n return {\"Content-Length\": str(content_length), \"Content-Type\": content_type}"} {"repo":"httpx","file":"httpx/_multipart.py","line":294,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> typing.Iterator[bytes]:\n for chunk in self.iter_chunks():\n yield chunk"} {"repo":"httpx","file":"httpx/_multipart.py","line":298,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n for chunk in self.iter_chunks():\n yield chunk"} {"repo":"httpx","file":"httpx/_status_codes.py","line":8,"symbol":"codes","kind":"class","lang":"python","code":"class codes(IntEnum):\n \"\"\"HTTP status codes and reason phrases\n\n Status codes from the following RFCs are all observed:\n\n * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616\n * RFC 6585: Additional HTTP Status Codes\n * RFC 3229: Delta encoding in HTTP\n * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518\n * RFC 5842: Binding Extensions to WebDAV\n * RFC 7238: Permanent Redirect\n * RFC 2295: Transparent Content Negotiation in HTTP\n * RFC 2774: An HTTP Extension Framework\n * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)\n * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)\n * RFC 7725: An HTTP Status Code to Report Legal Obstacles\n * RFC 8297: An HTTP Status Code for Indicating Hints\n * RFC 8470: Using Early Data in HTTP\n \"\"\"\n\n def __new__(cls, value: int, phrase: str = \"\") -> codes:\n obj = int.__new__(cls, value)\n obj._value_ = value\n\n obj.phrase = phrase # type: ignore[attr-defined]\n return obj\n\n def __str__(self) -> str:\n return str(self.value)\n\n @classmethod\n def get_reason_phrase(cls, value: int)"} {"repo":"httpx","file":"httpx/_status_codes.py","line":28,"symbol":"__new__","kind":"function","lang":"python","code":"def __new__(cls, value: int, phrase: str = \"\") -> codes:\n obj = int.__new__(cls, value)\n obj._value_ = value\n\n obj.phrase = phrase # type: ignore[attr-defined]\n return obj"} {"repo":"httpx","file":"httpx/_status_codes.py","line":35,"symbol":"__str__","kind":"function","lang":"python","code":"def __str__(self) -> str:\n return str(self.value)"} {"repo":"httpx","file":"httpx/_status_codes.py","line":39,"symbol":"get_reason_phrase","kind":"function","lang":"python","code":"def get_reason_phrase(cls, value: int) -> str:\n try:\n return codes(value).phrase # type: ignore\n except ValueError:\n return \"\""} {"repo":"httpx","file":"httpx/_status_codes.py","line":46,"symbol":"is_informational","kind":"function","lang":"python","code":"def is_informational(cls, value: int) -> bool:\n \"\"\"\n Returns `True` for 1xx status codes, `False` otherwise.\n \"\"\"\n return 100 <= value <= 199"} {"repo":"httpx","file":"httpx/_status_codes.py","line":53,"symbol":"is_success","kind":"function","lang":"python","code":"def is_success(cls, value: int) -> bool:\n \"\"\"\n Returns `True` for 2xx status codes, `False` otherwise.\n \"\"\"\n return 200 <= value <= 299"} {"repo":"httpx","file":"httpx/_status_codes.py","line":60,"symbol":"is_redirect","kind":"function","lang":"python","code":"def is_redirect(cls, value: int) -> bool:\n \"\"\"\n Returns `True` for 3xx status codes, `False` otherwise.\n \"\"\"\n return 300 <= value <= 399"} {"repo":"httpx","file":"httpx/_status_codes.py","line":67,"symbol":"is_client_error","kind":"function","lang":"python","code":"def is_client_error(cls, value: int) -> bool:\n \"\"\"\n Returns `True` for 4xx status codes, `False` otherwise.\n \"\"\"\n return 400 <= value <= 499"} {"repo":"httpx","file":"httpx/_status_codes.py","line":74,"symbol":"is_server_error","kind":"function","lang":"python","code":"def is_server_error(cls, value: int) -> bool:\n \"\"\"\n Returns `True` for 5xx status codes, `False` otherwise.\n \"\"\"\n return 500 <= value <= 599"} {"repo":"httpx","file":"httpx/_status_codes.py","line":81,"symbol":"is_error","kind":"function","lang":"python","code":"def is_error(cls, value: int) -> bool:\n \"\"\"\n Returns `True` for 4xx or 5xx status codes, `False` otherwise.\n \"\"\"\n return 400 <= value <= 599"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":29,"symbol":"is_running_trio","kind":"function","lang":"python","code":"def is_running_trio() -> bool:\n try:\n # sniffio is a dependency of trio.\n\n # See https://github.com/python-trio/trio/issues/2802\n import sniffio\n\n if sniffio.current_async_library() == \"trio\":\n return True\n except ImportError: # pragma: nocover\n pass\n\n return False"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":44,"symbol":"create_event","kind":"function","lang":"python","code":"def create_event() -> Event:\n if is_running_trio():\n import trio\n\n return trio.Event()\n\n import asyncio\n\n return asyncio.Event()"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":55,"symbol":"ASGIResponseStream","kind":"class","lang":"python","code":"class ASGIResponseStream(AsyncByteStream):\n def __init__(self, body: list[bytes]) -> None:\n self._body = body\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield b\"\".join(self._body)"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":56,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, body: list[bytes]) -> None:\n self._body = body"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":59,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield b\"\".join(self._body)"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":63,"symbol":"ASGITransport","kind":"class","lang":"python","code":"class ASGITransport(AsyncBaseTransport):\n \"\"\"\n A custom AsyncTransport that handles sending requests directly to an ASGI app.\n\n ```python\n transport = httpx.ASGITransport(\n app=app,\n root_path=\"/submount\",\n client=(\"1.2.3.4\", 123)\n )\n client = httpx.AsyncClient(transport=transport)\n ```\n\n Arguments:\n\n * `app` - The ASGI application.\n * `raise_app_exceptions` - Boolean indicating if exceptions in the application\n should be raised. Default to `True`. Can be set to `False` for use cases\n such as testing the content of a client 500 response.\n * `root_path` - The root path on which the ASGI application should be mounted.\n * `client` - A two-tuple indicating the client IP and port of incoming requests.\n ```\n \"\"\"\n\n def __init__(\n self,\n app: _ASGIApp,\n raise_app_exceptions: bool = True,\n root_path: str = \"\",\n client: tuple[str, int] = (\"127.0.0.1\", 123),\n ) -> None:\n self.app = app\n self.raise_app_exceptions = raise_app_exceptions\n self.root_path = root_path\n self.client = client\n\n async def handle_async_request(\n self,\n request: "} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":87,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n app: _ASGIApp,\n raise_app_exceptions: bool = True,\n root_path: str = \"\",\n client: tuple[str, int] = (\"127.0.0.1\", 123),\n ) -> None:\n self.app = app\n self.raise_app_exceptions = raise_app_exceptions\n self.root_path = root_path\n self.client = client"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":99,"symbol":"handle_async_request","kind":"function","lang":"python","code":"async def handle_async_request(\n self,\n request: Request,\n ) -> Response:\n assert isinstance(request.stream, AsyncByteStream)\n\n # ASGI scope.\n scope = {\n \"type\": \"http\",\n \"asgi\": {\"version\": \"3.0\"},\n \"http_version\": \"1.1\",\n \"method\": request.method,\n \"headers\": [(k.lower(), v) for (k, v) in request.headers.raw],\n \"scheme\": request.url.scheme,\n \"path\": request.url.path,\n \"raw_path\": request.url.raw_path.split(b\"?\")[0],\n \"query_string\": request.url.query,\n \"server\": (request.url.host, request.url.port),\n \"client\": self.client,\n \"root_path\": self.root_path,\n }\n\n # Request.\n request_body_chunks = request.stream.__aiter__()\n request_complete = False\n\n # Response.\n status_code = None\n response_headers = None\n body_parts = []\n response_started = False\n response_complete = create_event()\n\n # ASGI callables.\n\n async def receive() -> dict[str, typing.Any]:\n nonlocal request_complete\n\n if request_complete:\n "} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":134,"symbol":"receive","kind":"function","lang":"python","code":"async def receive() -> dict[str, typing.Any]:\n nonlocal request_complete\n\n if request_complete:\n await response_complete.wait()\n return {\"type\": \"http.disconnect\"}\n\n try:\n body = await request_body_chunks.__anext__()\n except StopAsyncIteration:\n request_complete = True\n return {\"type\": \"http.request\", \"body\": b\"\", \"more_body\": False}\n return {\"type\": \"http.request\", \"body\": body, \"more_body\": True}"} {"repo":"httpx","file":"httpx/_transports/asgi.py","line":148,"symbol":"send","kind":"function","lang":"python","code":"async def send(message: typing.MutableMapping[str, typing.Any]) -> None:\n nonlocal status_code, response_headers, response_started\n\n if message[\"type\"] == \"http.response.start\":\n assert not response_started\n\n status_code = message[\"status\"]\n response_headers = message.get(\"headers\", [])\n response_started = True\n\n elif message[\"type\"] == \"http.response.body\":\n assert not response_complete.is_set()\n body = message.get(\"body\", b\"\")\n more_body = message.get(\"more_body\", False)\n\n if body and request.method != \"HEAD\":\n body_parts.append(body)\n\n if not more_body:\n response_complete.set()"} {"repo":"httpx","file":"httpx/_transports/base.py","line":14,"symbol":"BaseTransport","kind":"class","lang":"python","code":"class BaseTransport:\n def __enter__(self: T) -> T:\n return self\n\n def __exit__(\n self,\n exc_type: type[BaseException] | None = None,\n exc_value: BaseException | None = None,\n traceback: TracebackType | None = None,\n ) -> None:\n self.close()\n\n def handle_request(self, request: Request) -> Response:\n \"\"\"\n Send a single HTTP request and return a response.\n\n Developers shouldn't typically ever need to call into this API directly,\n since the Client class provides all the higher level user-facing API\n niceties.\n\n In order to properly release any network resources, the response\n stream should *either* be consumed immediately, with a call to\n `response.stream.read()`, or else the `handle_request` call should\n be followed with a try/finally block to ensuring the stream is\n always closed.\n\n Example usage:\n\n with httpx.HTTPTransport() as transport:\n req = httpx.Request(\n method=b\"GET\",\n url=(b\"https\", b\"www.example.com\", 443, b\"/\"),\n headers=[(b\"Host\", b\"www.example.com\")],\n "} {"repo":"httpx","file":"httpx/_transports/base.py","line":15,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self: T) -> T:\n return self"} {"repo":"httpx","file":"httpx/_transports/base.py","line":18,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(\n self,\n exc_type: type[BaseException] | None = None,\n exc_value: BaseException | None = None,\n traceback: TracebackType | None = None,\n ) -> None:\n self.close()"} {"repo":"httpx","file":"httpx/_transports/base.py","line":26,"symbol":"handle_request","kind":"function","lang":"python","code":"def handle_request(self, request: Request) -> Response:\n \"\"\"\n Send a single HTTP request and return a response.\n\n Developers shouldn't typically ever need to call into this API directly,\n since the Client class provides all the higher level user-facing API\n niceties.\n\n In order to properly release any network resources, the response\n stream should *either* be consumed immediately, with a call to\n `response.stream.read()`, or else the `handle_request` call should\n be followed with a try/finally block to ensuring the stream is\n always closed.\n\n Example usage:\n\n with httpx.HTTPTransport() as transport:\n req = httpx.Request(\n method=b\"GET\",\n url=(b\"https\", b\"www.example.com\", 443, b\"/\"),\n headers=[(b\"Host\", b\"www.example.com\")],\n )\n resp = transport.handle_request(req)\n body = resp.stream.read()\n print(resp.status_code, resp.headers, body)\n\n\n Takes a `Request` instance as the only argument.\n\n Returns a `Response` instance.\n \"\"\"\n raise NotImpl"} {"repo":"httpx","file":"httpx/_transports/base.py","line":61,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n pass"} {"repo":"httpx","file":"httpx/_transports/base.py","line":65,"symbol":"AsyncBaseTransport","kind":"class","lang":"python","code":"class AsyncBaseTransport:\n async def __aenter__(self: A) -> A:\n return self\n\n async def __aexit__(\n self,\n exc_type: type[BaseException] | None = None,\n exc_value: BaseException | None = None,\n traceback: TracebackType | None = None,\n ) -> None:\n await self.aclose()\n\n async def handle_async_request(\n self,\n request: Request,\n ) -> Response:\n raise NotImplementedError(\n \"The 'handle_async_request' method must be implemented.\"\n ) # pragma: no cover\n\n async def aclose(self) -> None:\n pass"} {"repo":"httpx","file":"httpx/_transports/base.py","line":66,"symbol":"__aenter__","kind":"function","lang":"python","code":"async def __aenter__(self: A) -> A:\n return self"} {"repo":"httpx","file":"httpx/_transports/base.py","line":69,"symbol":"__aexit__","kind":"function","lang":"python","code":"async def __aexit__(\n self,\n exc_type: type[BaseException] | None = None,\n exc_value: BaseException | None = None,\n traceback: TracebackType | None = None,\n ) -> None:\n await self.aclose()"} {"repo":"httpx","file":"httpx/_transports/base.py","line":77,"symbol":"handle_async_request","kind":"function","lang":"python","code":"async def handle_async_request(\n self,\n request: Request,\n ) -> Response:\n raise NotImplementedError(\n \"The 'handle_async_request' method must be implemented.\"\n ) # pragma: no cover"} {"repo":"httpx","file":"httpx/_transports/base.py","line":85,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self) -> None:\n pass"} {"repo":"httpx","file":"httpx/_transports/default.py","line":74,"symbol":"_load_httpcore_exceptions","kind":"function","lang":"python","code":"def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]:\n import httpcore\n\n return {\n httpcore.TimeoutException: TimeoutException,\n httpcore.ConnectTimeout: ConnectTimeout,\n httpcore.ReadTimeout: ReadTimeout,\n httpcore.WriteTimeout: WriteTimeout,\n httpcore.PoolTimeout: PoolTimeout,\n httpcore.NetworkError: NetworkError,\n httpcore.ConnectError: ConnectError,\n httpcore.ReadError: ReadError,\n httpcore.WriteError: WriteError,\n httpcore.ProxyError: ProxyError,\n httpcore.UnsupportedProtocol: UnsupportedProtocol,\n httpcore.ProtocolError: ProtocolError,\n httpcore.LocalProtocolError: LocalProtocolError,\n httpcore.RemoteProtocolError: RemoteProtocolError,\n }"} {"repo":"httpx","file":"httpx/_transports/default.py","line":96,"symbol":"map_httpcore_exceptions","kind":"function","lang":"python","code":"def map_httpcore_exceptions() -> typing.Iterator[None]:\n global HTTPCORE_EXC_MAP\n if len(HTTPCORE_EXC_MAP) == 0:\n HTTPCORE_EXC_MAP = _load_httpcore_exceptions()\n try:\n yield\n except Exception as exc:\n mapped_exc = None\n\n for from_exc, to_exc in HTTPCORE_EXC_MAP.items():\n if not isinstance(exc, from_exc):\n continue\n # We want to map to the most specific exception we can find.\n # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to\n # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.\n if mapped_exc is None or issubclass(to_exc, mapped_exc):\n mapped_exc = to_exc\n\n if mapped_exc is None: # pragma: no cover\n raise\n\n message = str(exc)\n raise mapped_exc(message) from exc"} {"repo":"httpx","file":"httpx/_transports/default.py","line":121,"symbol":"ResponseStream","kind":"class","lang":"python","code":"class ResponseStream(SyncByteStream):\n def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None:\n self._httpcore_stream = httpcore_stream\n\n def __iter__(self) -> typing.Iterator[bytes]:\n with map_httpcore_exceptions():\n for part in self._httpcore_stream:\n yield part\n\n def close(self) -> None:\n if hasattr(self._httpcore_stream, \"close\"):\n self._httpcore_stream.close()"} {"repo":"httpx","file":"httpx/_transports/default.py","line":122,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None:\n self._httpcore_stream = httpcore_stream"} {"repo":"httpx","file":"httpx/_transports/default.py","line":125,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> typing.Iterator[bytes]:\n with map_httpcore_exceptions():\n for part in self._httpcore_stream:\n yield part"} {"repo":"httpx","file":"httpx/_transports/default.py","line":130,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n if hasattr(self._httpcore_stream, \"close\"):\n self._httpcore_stream.close()"} {"repo":"httpx","file":"httpx/_transports/default.py","line":135,"symbol":"HTTPTransport","kind":"class","lang":"python","code":"class HTTPTransport(BaseTransport):\n def __init__(\n self,\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n http1: bool = True,\n http2: bool = False,\n limits: Limits = DEFAULT_LIMITS,\n proxy: ProxyTypes | None = None,\n uds: str | None = None,\n local_address: str | None = None,\n retries: int = 0,\n socket_options: typing.Iterable[SOCKET_OPTION] | None = None,\n ) -> None:\n import httpcore\n\n proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy\n ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)\n\n if proxy is None:\n self._pool = httpcore.ConnectionPool(\n ssl_context=ssl_context,\n max_connections=limits.max_connections,\n max_keepalive_connections=limits.max_keepalive_connections,\n keepalive_expiry=limits.keepalive_expiry,\n http1=http1,\n http2=http2,\n uds=uds,\n local_address=local_address,\n retries=retries,\n socket_opt"} {"repo":"httpx","file":"httpx/_transports/default.py","line":136,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n http1: bool = True,\n http2: bool = False,\n limits: Limits = DEFAULT_LIMITS,\n proxy: ProxyTypes | None = None,\n uds: str | None = None,\n local_address: str | None = None,\n retries: int = 0,\n socket_options: typing.Iterable[SOCKET_OPTION] | None = None,\n ) -> None:\n import httpcore\n\n proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy\n ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)\n\n if proxy is None:\n self._pool = httpcore.ConnectionPool(\n ssl_context=ssl_context,\n max_connections=limits.max_connections,\n max_keepalive_connections=limits.max_keepalive_connections,\n keepalive_expiry=limits.keepalive_expiry,\n http1=http1,\n http2=http2,\n uds=uds,\n local_address=local_address,\n retries=retries,\n socket_options=socket_options,\n )\n "} {"repo":"httpx","file":"httpx/_transports/default.py","line":217,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self: T) -> T: # Use generics for subclass support.\n self._pool.__enter__()\n return self"} {"repo":"httpx","file":"httpx/_transports/default.py","line":221,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(\n self,\n exc_type: type[BaseException] | None = None,\n exc_value: BaseException | None = None,\n traceback: TracebackType | None = None,\n ) -> None:\n with map_httpcore_exceptions():\n self._pool.__exit__(exc_type, exc_value, traceback)"} {"repo":"httpx","file":"httpx/_transports/default.py","line":230,"symbol":"handle_request","kind":"function","lang":"python","code":"def handle_request(\n self,\n request: Request,\n ) -> Response:\n assert isinstance(request.stream, SyncByteStream)\n import httpcore\n\n req = httpcore.Request(\n method=request.method,\n url=httpcore.URL(\n scheme=request.url.raw_scheme,\n host=request.url.raw_host,\n port=request.url.port,\n target=request.url.raw_path,\n ),\n headers=request.headers.raw,\n content=request.stream,\n extensions=request.extensions,\n )\n with map_httpcore_exceptions():\n resp = self._pool.handle_request(req)\n\n assert isinstance(resp.stream, typing.Iterable)\n\n return Response(\n status_code=resp.status,\n headers=resp.headers,\n stream=ResponseStream(resp.stream),\n extensions=resp.extensions,\n )"} {"repo":"httpx","file":"httpx/_transports/default.py","line":261,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n self._pool.close()"} {"repo":"httpx","file":"httpx/_transports/default.py","line":265,"symbol":"AsyncResponseStream","kind":"class","lang":"python","code":"class AsyncResponseStream(AsyncByteStream):\n def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None:\n self._httpcore_stream = httpcore_stream\n\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n with map_httpcore_exceptions():\n async for part in self._httpcore_stream:\n yield part\n\n async def aclose(self) -> None:\n if hasattr(self._httpcore_stream, \"aclose\"):\n await self._httpcore_stream.aclose()"} {"repo":"httpx","file":"httpx/_transports/default.py","line":266,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None:\n self._httpcore_stream = httpcore_stream"} {"repo":"httpx","file":"httpx/_transports/default.py","line":269,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n with map_httpcore_exceptions():\n async for part in self._httpcore_stream:\n yield part"} {"repo":"httpx","file":"httpx/_transports/default.py","line":274,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self) -> None:\n if hasattr(self._httpcore_stream, \"aclose\"):\n await self._httpcore_stream.aclose()"} {"repo":"httpx","file":"httpx/_transports/default.py","line":279,"symbol":"AsyncHTTPTransport","kind":"class","lang":"python","code":"class AsyncHTTPTransport(AsyncBaseTransport):\n def __init__(\n self,\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n http1: bool = True,\n http2: bool = False,\n limits: Limits = DEFAULT_LIMITS,\n proxy: ProxyTypes | None = None,\n uds: str | None = None,\n local_address: str | None = None,\n retries: int = 0,\n socket_options: typing.Iterable[SOCKET_OPTION] | None = None,\n ) -> None:\n import httpcore\n\n proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy\n ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)\n\n if proxy is None:\n self._pool = httpcore.AsyncConnectionPool(\n ssl_context=ssl_context,\n max_connections=limits.max_connections,\n max_keepalive_connections=limits.max_keepalive_connections,\n keepalive_expiry=limits.keepalive_expiry,\n http1=http1,\n http2=http2,\n uds=uds,\n local_address=local_address,\n retries=retries,\n "} {"repo":"httpx","file":"httpx/_transports/default.py","line":280,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n verify: ssl.SSLContext | str | bool = True,\n cert: CertTypes | None = None,\n trust_env: bool = True,\n http1: bool = True,\n http2: bool = False,\n limits: Limits = DEFAULT_LIMITS,\n proxy: ProxyTypes | None = None,\n uds: str | None = None,\n local_address: str | None = None,\n retries: int = 0,\n socket_options: typing.Iterable[SOCKET_OPTION] | None = None,\n ) -> None:\n import httpcore\n\n proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy\n ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)\n\n if proxy is None:\n self._pool = httpcore.AsyncConnectionPool(\n ssl_context=ssl_context,\n max_connections=limits.max_connections,\n max_keepalive_connections=limits.max_keepalive_connections,\n keepalive_expiry=limits.keepalive_expiry,\n http1=http1,\n http2=http2,\n uds=uds,\n local_address=local_address,\n retries=retries,\n socket_options=socket_options,\n )\n"} {"repo":"httpx","file":"httpx/_transports/default.py","line":361,"symbol":"__aenter__","kind":"function","lang":"python","code":"async def __aenter__(self: A) -> A: # Use generics for subclass support.\n await self._pool.__aenter__()\n return self"} {"repo":"httpx","file":"httpx/_transports/default.py","line":365,"symbol":"__aexit__","kind":"function","lang":"python","code":"async def __aexit__(\n self,\n exc_type: type[BaseException] | None = None,\n exc_value: BaseException | None = None,\n traceback: TracebackType | None = None,\n ) -> None:\n with map_httpcore_exceptions():\n await self._pool.__aexit__(exc_type, exc_value, traceback)"} {"repo":"httpx","file":"httpx/_transports/default.py","line":374,"symbol":"handle_async_request","kind":"function","lang":"python","code":"async def handle_async_request(\n self,\n request: Request,\n ) -> Response:\n assert isinstance(request.stream, AsyncByteStream)\n import httpcore\n\n req = httpcore.Request(\n method=request.method,\n url=httpcore.URL(\n scheme=request.url.raw_scheme,\n host=request.url.raw_host,\n port=request.url.port,\n target=request.url.raw_path,\n ),\n headers=request.headers.raw,\n content=request.stream,\n extensions=request.extensions,\n )\n with map_httpcore_exceptions():\n resp = await self._pool.handle_async_request(req)\n\n assert isinstance(resp.stream, typing.AsyncIterable)\n\n return Response(\n status_code=resp.status,\n headers=resp.headers,\n stream=AsyncResponseStream(resp.stream),\n extensions=resp.extensions,\n )"} {"repo":"httpx","file":"httpx/_transports/default.py","line":405,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self) -> None:\n await self._pool.aclose()"} {"repo":"httpx","file":"httpx/_transports/mock.py","line":15,"symbol":"MockTransport","kind":"class","lang":"python","code":"class MockTransport(AsyncBaseTransport, BaseTransport):\n def __init__(self, handler: SyncHandler | AsyncHandler) -> None:\n self.handler = handler\n\n def handle_request(\n self,\n request: Request,\n ) -> Response:\n request.read()\n response = self.handler(request)\n if not isinstance(response, Response): # pragma: no cover\n raise TypeError(\"Cannot use an async handler in a sync Client\")\n return response\n\n async def handle_async_request(\n self,\n request: Request,\n ) -> Response:\n await request.aread()\n response = self.handler(request)\n\n # Allow handler to *optionally* be an `async` function.\n # If it is, then the `response` variable need to be awaited to actually\n # return the result.\n\n if not isinstance(response, Response):\n response = await response\n\n return response"} {"repo":"httpx","file":"httpx/_transports/mock.py","line":16,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, handler: SyncHandler | AsyncHandler) -> None:\n self.handler = handler"} {"repo":"httpx","file":"httpx/_transports/mock.py","line":19,"symbol":"handle_request","kind":"function","lang":"python","code":"def handle_request(\n self,\n request: Request,\n ) -> Response:\n request.read()\n response = self.handler(request)\n if not isinstance(response, Response): # pragma: no cover\n raise TypeError(\"Cannot use an async handler in a sync Client\")\n return response"} {"repo":"httpx","file":"httpx/_transports/mock.py","line":29,"symbol":"handle_async_request","kind":"function","lang":"python","code":"async def handle_async_request(\n self,\n request: Request,\n ) -> Response:\n await request.aread()\n response = self.handler(request)\n\n # Allow handler to *optionally* be an `async` function.\n # If it is, then the `response` variable need to be awaited to actually\n # return the result.\n\n if not isinstance(response, Response):\n response = await response\n\n return response"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":22,"symbol":"_skip_leading_empty_chunks","kind":"function","lang":"python","code":"def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]:\n body = iter(body)\n for chunk in body:\n if chunk:\n return itertools.chain([chunk], body)\n return []"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":30,"symbol":"WSGIByteStream","kind":"class","lang":"python","code":"class WSGIByteStream(SyncByteStream):\n def __init__(self, result: typing.Iterable[bytes]) -> None:\n self._close = getattr(result, \"close\", None)\n self._result = _skip_leading_empty_chunks(result)\n\n def __iter__(self) -> typing.Iterator[bytes]:\n for part in self._result:\n yield part\n\n def close(self) -> None:\n if self._close is not None:\n self._close()"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":31,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, result: typing.Iterable[bytes]) -> None:\n self._close = getattr(result, \"close\", None)\n self._result = _skip_leading_empty_chunks(result)"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":35,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> typing.Iterator[bytes]:\n for part in self._result:\n yield part"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":39,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n if self._close is not None:\n self._close()"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":44,"symbol":"WSGITransport","kind":"class","lang":"python","code":"class WSGITransport(BaseTransport):\n \"\"\"\n A custom transport that handles sending requests directly to an WSGI app.\n The simplest way to use this functionality is to use the `app` argument.\n\n ```\n client = httpx.Client(app=app)\n ```\n\n Alternatively, you can setup the transport instance explicitly.\n This allows you to include any additional configuration arguments specific\n to the WSGITransport class:\n\n ```\n transport = httpx.WSGITransport(\n app=app,\n script_name=\"/submount\",\n remote_addr=\"1.2.3.4\"\n )\n client = httpx.Client(transport=transport)\n ```\n\n Arguments:\n\n * `app` - The WSGI application.\n * `raise_app_exceptions` - Boolean indicating if exceptions in the application\n should be raised. Default to `True`. Can be set to `False` for use cases\n such as testing the content of a client 500 response.\n * `script_name` - The root path on which the WSGI application should be mounted.\n * `remote_addr` - A string indicating the client IP of incoming requests.\n ```\n \"\"\"\n\n def __init__(\n self,\n app: WSGIApplication,\n raise_app_exceptions: bool = True,\n script_name:"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":77,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n app: WSGIApplication,\n raise_app_exceptions: bool = True,\n script_name: str = \"\",\n remote_addr: str = \"127.0.0.1\",\n wsgi_errors: typing.TextIO | None = None,\n ) -> None:\n self.app = app\n self.raise_app_exceptions = raise_app_exceptions\n self.script_name = script_name\n self.remote_addr = remote_addr\n self.wsgi_errors = wsgi_errors"} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":91,"symbol":"handle_request","kind":"function","lang":"python","code":"def handle_request(self, request: Request) -> Response:\n request.read()\n wsgi_input = io.BytesIO(request.content)\n\n port = request.url.port or {\"http\": 80, \"https\": 443}[request.url.scheme]\n environ = {\n \"wsgi.version\": (1, 0),\n \"wsgi.url_scheme\": request.url.scheme,\n \"wsgi.input\": wsgi_input,\n \"wsgi.errors\": self.wsgi_errors or sys.stderr,\n \"wsgi.multithread\": True,\n \"wsgi.multiprocess\": False,\n \"wsgi.run_once\": False,\n \"REQUEST_METHOD\": request.method,\n \"SCRIPT_NAME\": self.script_name,\n \"PATH_INFO\": request.url.path,\n \"QUERY_STRING\": request.url.query.decode(\"ascii\"),\n \"SERVER_NAME\": request.url.host,\n \"SERVER_PORT\": str(port),\n \"SERVER_PROTOCOL\": \"HTTP/1.1\",\n \"REMOTE_ADDR\": self.remote_addr,\n }\n for header_key, header_value in request.headers.raw:\n key = header_key.decode(\"ascii\").upper().replace(\"-\", \"_\")\n if key not in (\"CONTENT_TYPE\", \"CONTENT_LENGTH\"):\n key = \"HTTP_\" + key\n environ[key] = header_value.decode(\"ascii\")\n\n "} {"repo":"httpx","file":"httpx/_transports/wsgi.py","line":123,"symbol":"start_response","kind":"function","lang":"python","code":"def start_response(\n status: str,\n response_headers: list[tuple[str, str]],\n exc_info: OptExcInfo | None = None,\n ) -> typing.Callable[[bytes], typing.Any]:\n nonlocal seen_status, seen_response_headers, seen_exc_info\n seen_status = status\n seen_response_headers = response_headers\n seen_exc_info = exc_info\n return lambda _: None"} {"repo":"httpx","file":"httpx/_types.py","line":92,"symbol":"SyncByteStream","kind":"class","lang":"python","code":"class SyncByteStream:\n def __iter__(self) -> Iterator[bytes]:\n raise NotImplementedError(\n \"The '__iter__' method must be implemented.\"\n ) # pragma: no cover\n yield b\"\" # pragma: no cover\n\n def close(self) -> None:\n \"\"\"\n Subclasses can override this method to release any network resources\n after a request/response cycle is complete.\n \"\"\""} {"repo":"httpx","file":"httpx/_types.py","line":93,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> Iterator[bytes]:\n raise NotImplementedError(\n \"The '__iter__' method must be implemented.\"\n ) # pragma: no cover\n yield b\"\" # pragma: no cover"} {"repo":"httpx","file":"httpx/_types.py","line":99,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n \"\"\"\n Subclasses can override this method to release any network resources\n after a request/response cycle is complete.\n \"\"\""} {"repo":"httpx","file":"httpx/_types.py","line":106,"symbol":"AsyncByteStream","kind":"class","lang":"python","code":"class AsyncByteStream:\n async def __aiter__(self) -> AsyncIterator[bytes]:\n raise NotImplementedError(\n \"The '__aiter__' method must be implemented.\"\n ) # pragma: no cover\n yield b\"\" # pragma: no cover\n\n async def aclose(self) -> None:\n pass"} {"repo":"httpx","file":"httpx/_types.py","line":107,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> AsyncIterator[bytes]:\n raise NotImplementedError(\n \"The '__aiter__' method must be implemented.\"\n ) # pragma: no cover\n yield b\"\" # pragma: no cover"} {"repo":"httpx","file":"httpx/_types.py","line":113,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self) -> None:\n pass"} {"repo":"httpx","file":"httpx/_urlparse.py","line":158,"symbol":"ParseResult","kind":"class","lang":"python","code":"class ParseResult(typing.NamedTuple):\n scheme: str\n userinfo: str\n host: str\n port: int | None\n path: str\n query: str | None\n fragment: str | None\n\n @property\n def authority(self) -> str:\n return \"\".join(\n [\n f\"{self.userinfo}@\" if self.userinfo else \"\",\n f\"[{self.host}]\" if \":\" in self.host else self.host,\n f\":{self.port}\" if self.port is not None else \"\",\n ]\n )\n\n @property\n def netloc(self) -> str:\n return \"\".join(\n [\n f\"[{self.host}]\" if \":\" in self.host else self.host,\n f\":{self.port}\" if self.port is not None else \"\",\n ]\n )\n\n def copy_with(self, **kwargs: str | None) -> ParseResult:\n if not kwargs:\n return self\n\n defaults = {\n \"scheme\": self.scheme,\n \"authority\": self.authority,\n \"path\": self.path,\n \"query\": self.query,\n \"fragment\": self.fragment,\n }\n defaults.update(kwargs)\n return urlparse(\"\", **defaults)\n\n def __str__(self) -> str:\n authority = self.authority\n return \"\".join(\n "} {"repo":"httpx","file":"httpx/_urlparse.py","line":168,"symbol":"authority","kind":"function","lang":"python","code":"def authority(self) -> str:\n return \"\".join(\n [\n f\"{self.userinfo}@\" if self.userinfo else \"\",\n f\"[{self.host}]\" if \":\" in self.host else self.host,\n f\":{self.port}\" if self.port is not None else \"\",\n ]\n )"} {"repo":"httpx","file":"httpx/_urlparse.py","line":178,"symbol":"netloc","kind":"function","lang":"python","code":"def netloc(self) -> str:\n return \"\".join(\n [\n f\"[{self.host}]\" if \":\" in self.host else self.host,\n f\":{self.port}\" if self.port is not None else \"\",\n ]\n )"} {"repo":"httpx","file":"httpx/_urlparse.py","line":186,"symbol":"copy_with","kind":"function","lang":"python","code":"def copy_with(self, **kwargs: str | None) -> ParseResult:\n if not kwargs:\n return self\n\n defaults = {\n \"scheme\": self.scheme,\n \"authority\": self.authority,\n \"path\": self.path,\n \"query\": self.query,\n \"fragment\": self.fragment,\n }\n defaults.update(kwargs)\n return urlparse(\"\", **defaults)"} {"repo":"httpx","file":"httpx/_urlparse.py","line":200,"symbol":"__str__","kind":"function","lang":"python","code":"def __str__(self) -> str:\n authority = self.authority\n return \"\".join(\n [\n f\"{self.scheme}:\" if self.scheme else \"\",\n f\"//{authority}\" if authority else \"\",\n self.path,\n f\"?{self.query}\" if self.query is not None else \"\",\n f\"#{self.fragment}\" if self.fragment is not None else \"\",\n ]\n )"} {"repo":"httpx","file":"httpx/_urlparse.py","line":213,"symbol":"urlparse","kind":"function","lang":"python","code":"def urlparse(url: str = \"\", **kwargs: str | None) -> ParseResult:\n # Initial basic checks on allowable URLs.\n # ---------------------------------------\n\n # Hard limit the maximum allowable URL length.\n if len(url) > MAX_URL_LENGTH:\n raise InvalidURL(\"URL too long\")\n\n # If a URL includes any ASCII control characters including \\t, \\r, \\n,\n # then treat it as invalid.\n if any(char.isascii() and not char.isprintable() for char in url):\n char = next(char for char in url if char.isascii() and not char.isprintable())\n idx = url.find(char)\n error = (\n f\"Invalid non-printable ASCII character in URL, {char!r} at position {idx}.\"\n )\n raise InvalidURL(error)\n\n # Some keyword arguments require special handling.\n # ------------------------------------------------\n\n # Coerce \"port\" to a string, if it is provided as an integer.\n if \"port\" in kwargs:\n port = kwargs[\"port\"]\n kwargs[\"port\"] = str(port) if isinstance(port, int) else port\n\n # Replace \"netloc\" with \"host and \"port\".\n if \"netloc\" in kwargs:\n netloc = kwargs.pop(\"netloc\") or \"\"\n kwargs[\"host\"], _, kwargs[\"port\"] = netloc"} {"repo":"httpx","file":"httpx/_urlparse.py","line":348,"symbol":"encode_host","kind":"function","lang":"python","code":"def encode_host(host: str) -> str:\n if not host:\n return \"\"\n\n elif IPv4_STYLE_HOSTNAME.match(host):\n # Validate IPv4 hostnames like #.#.#.#\n #\n # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2\n #\n # IPv4address = dec-octet \".\" dec-octet \".\" dec-octet \".\" dec-octet\n try:\n ipaddress.IPv4Address(host)\n except ipaddress.AddressValueError:\n raise InvalidURL(f\"Invalid IPv4 address: {host!r}\")\n return host\n\n elif IPv6_STYLE_HOSTNAME.match(host):\n # Validate IPv6 hostnames like [...]\n #\n # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2\n #\n # \"A host identified by an Internet Protocol literal address, version 6\n # [RFC3513] or later, is distinguished by enclosing the IP literal\n # within square brackets (\"[\" and \"]\"). This is the only place where\n # square bracket characters are allowed in the URI syntax.\"\n try:\n ipaddress.IPv6Address(host[1:-1])\n except ipaddress.AddressValueError:\n raise InvalidURL(f\"Invalid IPv6 address: {host!r}\")\n return host[1:-1]\n\n elif"} {"repo":"httpx","file":"httpx/_urlparse.py","line":395,"symbol":"normalize_port","kind":"function","lang":"python","code":"def normalize_port(port: str | int | None, scheme: str) -> int | None:\n # From https://tools.ietf.org/html/rfc3986#section-3.2.3\n #\n # \"A scheme may define a default port. For example, the \"http\" scheme\n # defines a default port of \"80\", corresponding to its reserved TCP\n # port number. The type of port designated by the port number (e.g.,\n # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and\n # normalizers should omit the port component and its \":\" delimiter if\n # port is empty or if its value would be the same as that of the\n # scheme's default.\"\n if port is None or port == \"\":\n return None\n\n try:\n port_as_int = int(port)\n except ValueError:\n raise InvalidURL(f\"Invalid port: {port!r}\")\n\n # See https://url.spec.whatwg.org/#url-miscellaneous\n default_port = {\"ftp\": 21, \"http\": 80, \"https\": 443, \"ws\": 80, \"wss\": 443}.get(\n scheme\n )\n if port_as_int == default_port:\n return None\n return port_as_int"} {"repo":"httpx","file":"httpx/_urlparse.py","line":422,"symbol":"validate_path","kind":"function","lang":"python","code":"def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None:\n \"\"\"\n Path validation rules that depend on if the URL contains\n a scheme or authority component.\n\n See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3\n \"\"\"\n if has_authority:\n # If a URI contains an authority component, then the path component\n # must either be empty or begin with a slash (\"/\") character.\"\n if path and not path.startswith(\"/\"):\n raise InvalidURL(\"For absolute URLs, path must be empty or begin with '/'\")\n\n if not has_scheme and not has_authority:\n # If a URI does not contain an authority component, then the path cannot begin\n # with two slash characters (\"//\").\n if path.startswith(\"//\"):\n raise InvalidURL(\"Relative URLs cannot have a path starting with '//'\")\n\n # In addition, a URI reference (Section 4.1) may be a relative-path reference,\n # in which case the first path segment cannot contain a colon (\":\") character.\n if path.startswith(\":\"):\n raise InvalidURL(\"Relative URLs cannot have a path starting with ':'\")"} {"repo":"httpx","file":"httpx/_urlparse.py","line":447,"symbol":"normalize_path","kind":"function","lang":"python","code":"def normalize_path(path: str) -> str:\n \"\"\"\n Drop \".\" and \"..\" segments from a URL path.\n\n For example:\n\n normalize_path(\"/path/./to/somewhere/..\") == \"/path/to\"\n \"\"\"\n # Fast return when no '.' characters in the path.\n if \".\" not in path:\n return path\n\n components = path.split(\"/\")\n\n # Fast return when no '.' or '..' components in the path.\n if \".\" not in components and \"..\" not in components:\n return path\n\n # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n output: list[str] = []\n for component in components:\n if component == \".\":\n pass\n elif component == \"..\":\n if output and output != [\"\"]:\n output.pop()\n else:\n output.append(component)\n return \"/\".join(output)"} {"repo":"httpx","file":"httpx/_urlparse.py","line":478,"symbol":"PERCENT","kind":"function","lang":"python","code":"def PERCENT(string: str) -> str:\n return \"\".join([f\"%{byte:02X}\" for byte in string.encode(\"utf-8\")])"} {"repo":"httpx","file":"httpx/_urlparse.py","line":482,"symbol":"percent_encoded","kind":"function","lang":"python","code":"def percent_encoded(string: str, safe: str) -> str:\n \"\"\"\n Use percent-encoding to quote a string.\n \"\"\"\n NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe\n\n # Fast path for strings that don't need escaping.\n if not string.rstrip(NON_ESCAPED_CHARS):\n return string\n\n return \"\".join(\n [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string]\n )"} {"repo":"httpx","file":"httpx/_urlparse.py","line":497,"symbol":"quote","kind":"function","lang":"python","code":"def quote(string: str, safe: str) -> str:\n \"\"\"\n Use percent-encoding to quote a string, omitting existing '%xx' escape sequences.\n\n See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1\n\n * `string`: The string to be percent-escaped.\n * `safe`: A string containing characters that may be treated as safe, and do not\n need to be escaped. Unreserved characters are always treated as safe.\n See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3\n \"\"\"\n parts = []\n current_position = 0\n for match in re.finditer(PERCENT_ENCODED_REGEX, string):\n start_position, end_position = match.start(), match.end()\n matched_text = match.group(0)\n # Add any text up to the '%xx' escape sequence.\n if start_position != current_position:\n leading_text = string[current_position:start_position]\n parts.append(percent_encoded(leading_text, safe=safe))\n\n # Add the '%xx' escape sequence.\n parts.append(matched_text)\n current_position = end_position\n\n # Add any text after the final '%xx' escape sequence.\n if current_position != len(string):\n trailing_text = string[current_position:]\n p"} {"repo":"httpx","file":"httpx/_urls.py","line":15,"symbol":"URL","kind":"class","lang":"python","code":"class URL:\n \"\"\"\n url = httpx.URL(\"HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink\")\n\n assert url.scheme == \"https\"\n assert url.username == \"jo@email.com\"\n assert url.password == \"a secret\"\n assert url.userinfo == b\"jo%40email.com:a%20secret\"\n assert url.host == \"müller.de\"\n assert url.raw_host == b\"xn--mller-kva.de\"\n assert url.port == 1234\n assert url.netloc == b\"xn--mller-kva.de:1234\"\n assert url.path == \"/pa th\"\n assert url.query == b\"?search=ab\"\n assert url.raw_path == b\"/pa%20th?search=ab\"\n assert url.fragment == \"anchorlink\"\n\n The components of a URL are broken down like this:\n\n https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink\n [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment]\n [ userinfo ] [ netloc ][ raw_path ]\n\n Note that:\n\n * `url.scheme` is normalized to always be lowercased.\n\n * `url.host` is normalized to always be lowercased. Internationalized domain\n names are represented in unicode, without IDNA encoding applied. For instance:\n\n url = httpx.URL(\"http://中国.icom.museum\")\n"} {"repo":"httpx","file":"httpx/_urls.py","line":77,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, url: URL | str = \"\", **kwargs: typing.Any) -> None:\n if kwargs:\n allowed = {\n \"scheme\": str,\n \"username\": str,\n \"password\": str,\n \"userinfo\": bytes,\n \"host\": str,\n \"port\": int,\n \"netloc\": bytes,\n \"path\": str,\n \"query\": bytes,\n \"raw_path\": bytes,\n \"fragment\": str,\n \"params\": object,\n }\n\n # Perform type checking for all supported keyword arguments.\n for key, value in kwargs.items():\n if key not in allowed:\n message = f\"{key!r} is an invalid keyword argument for URL()\"\n raise TypeError(message)\n if value is not None and not isinstance(value, allowed[key]):\n expected = allowed[key].__name__\n seen = type(value).__name__\n message = f\"Argument {key!r} must be {expected} but got {seen}\"\n raise TypeError(message)\n if isinstance(value, bytes):\n kwargs[key] = value.decode("} {"repo":"httpx","file":"httpx/_urls.py","line":127,"symbol":"scheme","kind":"function","lang":"python","code":"def scheme(self) -> str:\n \"\"\"\n The URL scheme, such as \"http\", \"https\".\n Always normalised to lowercase.\n \"\"\"\n return self._uri_reference.scheme"} {"repo":"httpx","file":"httpx/_urls.py","line":135,"symbol":"raw_scheme","kind":"function","lang":"python","code":"def raw_scheme(self) -> bytes:\n \"\"\"\n The raw bytes representation of the URL scheme, such as b\"http\", b\"https\".\n Always normalised to lowercase.\n \"\"\"\n return self._uri_reference.scheme.encode(\"ascii\")"} {"repo":"httpx","file":"httpx/_urls.py","line":143,"symbol":"userinfo","kind":"function","lang":"python","code":"def userinfo(self) -> bytes:\n \"\"\"\n The URL userinfo as a raw bytestring.\n For example: b\"jo%40email.com:a%20secret\".\n \"\"\"\n return self._uri_reference.userinfo.encode(\"ascii\")"} {"repo":"httpx","file":"httpx/_urls.py","line":151,"symbol":"username","kind":"function","lang":"python","code":"def username(self) -> str:\n \"\"\"\n The URL username as a string, with URL decoding applied.\n For example: \"jo@email.com\"\n \"\"\"\n userinfo = self._uri_reference.userinfo\n return unquote(userinfo.partition(\":\")[0])"} {"repo":"httpx","file":"httpx/_urls.py","line":160,"symbol":"password","kind":"function","lang":"python","code":"def password(self) -> str:\n \"\"\"\n The URL password as a string, with URL decoding applied.\n For example: \"a secret\"\n \"\"\"\n userinfo = self._uri_reference.userinfo\n return unquote(userinfo.partition(\":\")[2])"} {"repo":"httpx","file":"httpx/_urls.py","line":169,"symbol":"host","kind":"function","lang":"python","code":"def host(self) -> str:\n \"\"\"\n The URL host as a string.\n Always normalized to lowercase, with IDNA hosts decoded into unicode.\n\n Examples:\n\n url = httpx.URL(\"http://www.EXAMPLE.org\")\n assert url.host == \"www.example.org\"\n\n url = httpx.URL(\"http://中国.icom.museum\")\n assert url.host == \"中国.icom.museum\"\n\n url = httpx.URL(\"http://xn--fiqs8s.icom.museum\")\n assert url.host == \"中国.icom.museum\"\n\n url = httpx.URL(\"https://[::ffff:192.168.0.1]\")\n assert url.host == \"::ffff:192.168.0.1\"\n \"\"\"\n host: str = self._uri_reference.host\n\n if host.startswith(\"xn--\"):\n host = idna.decode(host)\n\n return host"} {"repo":"httpx","file":"httpx/_urls.py","line":196,"symbol":"raw_host","kind":"function","lang":"python","code":"def raw_host(self) -> bytes:\n \"\"\"\n The raw bytes representation of the URL host.\n Always normalized to lowercase, and IDNA encoded.\n\n Examples:\n\n url = httpx.URL(\"http://www.EXAMPLE.org\")\n assert url.raw_host == b\"www.example.org\"\n\n url = httpx.URL(\"http://中国.icom.museum\")\n assert url.raw_host == b\"xn--fiqs8s.icom.museum\"\n\n url = httpx.URL(\"http://xn--fiqs8s.icom.museum\")\n assert url.raw_host == b\"xn--fiqs8s.icom.museum\"\n\n url = httpx.URL(\"https://[::ffff:192.168.0.1]\")\n assert url.raw_host == b\"::ffff:192.168.0.1\"\n \"\"\"\n return self._uri_reference.host.encode(\"ascii\")"} {"repo":"httpx","file":"httpx/_urls.py","line":218,"symbol":"port","kind":"function","lang":"python","code":"def port(self) -> int | None:\n \"\"\"\n The URL port as an integer.\n\n Note that the URL class performs port normalization as per the WHATWG spec.\n Default ports for \"http\", \"https\", \"ws\", \"wss\", and \"ftp\" schemes are always\n treated as `None`.\n\n For example:\n\n assert httpx.URL(\"http://www.example.com\") == httpx.URL(\"http://www.example.com:80\")\n assert httpx.URL(\"http://www.example.com:80\").port is None\n \"\"\"\n return self._uri_reference.port"} {"repo":"httpx","file":"httpx/_urls.py","line":234,"symbol":"netloc","kind":"function","lang":"python","code":"def netloc(self) -> bytes:\n \"\"\"\n Either `` or `:` as bytes.\n Always normalized to lowercase, and IDNA encoded.\n\n This property may be used for generating the value of a request\n \"Host\" header.\n \"\"\"\n return self._uri_reference.netloc.encode(\"ascii\")"} {"repo":"httpx","file":"httpx/_urls.py","line":245,"symbol":"path","kind":"function","lang":"python","code":"def path(self) -> str:\n \"\"\"\n The URL path as a string. Excluding the query string, and URL decoded.\n\n For example:\n\n url = httpx.URL(\"https://example.com/pa%20th\")\n assert url.path == \"/pa th\"\n \"\"\"\n path = self._uri_reference.path or \"/\"\n return unquote(path)"} {"repo":"httpx","file":"httpx/_urls.py","line":258,"symbol":"query","kind":"function","lang":"python","code":"def query(self) -> bytes:\n \"\"\"\n The URL query string, as raw bytes, excluding the leading b\"?\".\n\n This is necessarily a bytewise interface, because we cannot\n perform URL decoding of this representation until we've parsed\n the keys and values into a QueryParams instance.\n\n For example:\n\n url = httpx.URL(\"https://example.com/?filter=some%20search%20terms\")\n assert url.query == b\"filter=some%20search%20terms\"\n \"\"\"\n query = self._uri_reference.query or \"\"\n return query.encode(\"ascii\")"} {"repo":"httpx","file":"httpx/_urls.py","line":275,"symbol":"params","kind":"function","lang":"python","code":"def params(self) -> QueryParams:\n \"\"\"\n The URL query parameters, neatly parsed and packaged into an immutable\n multidict representation.\n \"\"\"\n return QueryParams(self._uri_reference.query)"} {"repo":"httpx","file":"httpx/_urls.py","line":283,"symbol":"raw_path","kind":"function","lang":"python","code":"def raw_path(self) -> bytes:\n \"\"\"\n The complete URL path and query string as raw bytes.\n Used as the target when constructing HTTP requests.\n\n For example:\n\n GET /users?search=some%20text HTTP/1.1\n Host: www.example.org\n Connection: close\n \"\"\"\n path = self._uri_reference.path or \"/\"\n if self._uri_reference.query is not None:\n path += \"?\" + self._uri_reference.query\n return path.encode(\"ascii\")"} {"repo":"httpx","file":"httpx/_urls.py","line":300,"symbol":"fragment","kind":"function","lang":"python","code":"def fragment(self) -> str:\n \"\"\"\n The URL fragments, as used in HTML anchors.\n As a string, without the leading '#'.\n \"\"\"\n return unquote(self._uri_reference.fragment or \"\")"} {"repo":"httpx","file":"httpx/_urls.py","line":308,"symbol":"is_absolute_url","kind":"function","lang":"python","code":"def is_absolute_url(self) -> bool:\n \"\"\"\n Return `True` for absolute URLs such as 'http://example.com/path',\n and `False` for relative URLs such as '/path'.\n \"\"\"\n # We don't use `.is_absolute` from `rfc3986` because it treats\n # URLs with a fragment portion as not absolute.\n # What we actually care about is if the URL provides\n # a scheme and hostname to which connections should be made.\n return bool(self._uri_reference.scheme and self._uri_reference.host)"} {"repo":"httpx","file":"httpx/_urls.py","line":320,"symbol":"is_relative_url","kind":"function","lang":"python","code":"def is_relative_url(self) -> bool:\n \"\"\"\n Return `False` for absolute URLs such as 'http://example.com/path',\n and `True` for relative URLs such as '/path'.\n \"\"\"\n return not self.is_absolute_url"} {"repo":"httpx","file":"httpx/_urls.py","line":327,"symbol":"copy_with","kind":"function","lang":"python","code":"def copy_with(self, **kwargs: typing.Any) -> URL:\n \"\"\"\n Copy this URL, returning a new URL with some components altered.\n Accepts the same set of parameters as the components that are made\n available via properties on the `URL` class.\n\n For example:\n\n url = httpx.URL(\"https://www.example.com\").copy_with(\n username=\"jo@gmail.com\", password=\"a secret\"\n )\n assert url == \"https://jo%40email.com:a%20secret@www.example.com\"\n \"\"\"\n return URL(self, **kwargs)"} {"repo":"httpx","file":"httpx/_urls.py","line":342,"symbol":"copy_set_param","kind":"function","lang":"python","code":"def copy_set_param(self, key: str, value: typing.Any = None) -> URL:\n return self.copy_with(params=self.params.set(key, value))"} {"repo":"httpx","file":"httpx/_urls.py","line":345,"symbol":"copy_add_param","kind":"function","lang":"python","code":"def copy_add_param(self, key: str, value: typing.Any = None) -> URL:\n return self.copy_with(params=self.params.add(key, value))"} {"repo":"httpx","file":"httpx/_urls.py","line":348,"symbol":"copy_remove_param","kind":"function","lang":"python","code":"def copy_remove_param(self, key: str) -> URL:\n return self.copy_with(params=self.params.remove(key))"} {"repo":"httpx","file":"httpx/_urls.py","line":351,"symbol":"copy_merge_params","kind":"function","lang":"python","code":"def copy_merge_params(self, params: QueryParamTypes) -> URL:\n return self.copy_with(params=self.params.merge(params))"} {"repo":"httpx","file":"httpx/_urls.py","line":354,"symbol":"join","kind":"function","lang":"python","code":"def join(self, url: URL | str) -> URL:\n \"\"\"\n Return an absolute URL, using this URL as the base.\n\n Eg.\n\n url = httpx.URL(\"https://www.example.com/test\")\n url = url.join(\"/new/path\")\n assert url == \"https://www.example.com/new/path\"\n \"\"\"\n from urllib.parse import urljoin\n\n return URL(urljoin(str(self), str(URL(url))))"} {"repo":"httpx","file":"httpx/_urls.py","line":368,"symbol":"__hash__","kind":"function","lang":"python","code":"def __hash__(self) -> int:\n return hash(str(self))"} {"repo":"httpx","file":"httpx/_urls.py","line":371,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, (URL, str)) and str(self) == str(URL(other))"} {"repo":"httpx","file":"httpx/_urls.py","line":374,"symbol":"__str__","kind":"function","lang":"python","code":"def __str__(self) -> str:\n return str(self._uri_reference)"} {"repo":"httpx","file":"httpx/_urls.py","line":377,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n scheme, userinfo, host, port, path, query, fragment = self._uri_reference\n\n if \":\" in userinfo:\n # Mask any password component.\n userinfo = f\"{userinfo.split(':')[0]}:[secure]\"\n\n authority = \"\".join(\n [\n f\"{userinfo}@\" if userinfo else \"\",\n f\"[{host}]\" if \":\" in host else host,\n f\":{port}\" if port is not None else \"\",\n ]\n )\n url = \"\".join(\n [\n f\"{self.scheme}:\" if scheme else \"\",\n f\"//{authority}\" if authority else \"\",\n path,\n f\"?{query}\" if query is not None else \"\",\n f\"#{fragment}\" if fragment is not None else \"\",\n ]\n )\n\n return f\"{self.__class__.__name__}({url!r})\""} {"repo":"httpx","file":"httpx/_urls.py","line":404,"symbol":"raw","kind":"function","lang":"python","code":"def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover\n import collections\n import warnings\n\n warnings.warn(\"URL.raw is deprecated.\")\n RawURL = collections.namedtuple(\n \"RawURL\", [\"raw_scheme\", \"raw_host\", \"port\", \"raw_path\"]\n )\n return RawURL(\n raw_scheme=self.raw_scheme,\n raw_host=self.raw_host,\n port=self.port,\n raw_path=self.raw_path,\n )"} {"repo":"httpx","file":"httpx/_urls.py","line":420,"symbol":"QueryParams","kind":"class","lang":"python","code":"class QueryParams(typing.Mapping[str, str]):\n \"\"\"\n URL query parameters, as a multi-dict.\n \"\"\"\n\n def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None:\n assert len(args) < 2, \"Too many arguments.\"\n assert not (args and kwargs), \"Cannot mix named and unnamed arguments.\"\n\n value = args[0] if args else kwargs\n\n if value is None or isinstance(value, (str, bytes)):\n value = value.decode(\"ascii\") if isinstance(value, bytes) else value\n self._dict = parse_qs(value, keep_blank_values=True)\n elif isinstance(value, QueryParams):\n self._dict = {k: list(v) for k, v in value._dict.items()}\n else:\n dict_value: dict[typing.Any, list[typing.Any]] = {}\n if isinstance(value, (list, tuple)):\n # Convert list inputs like:\n # [(\"a\", \"123\"), (\"a\", \"456\"), (\"b\", \"789\")]\n # To a dict representation, like:\n # {\"a\": [\"123\", \"456\"], \"b\": [\"789\"]}\n for item in value:\n dict_value.setdefault(item[0], []).append(item[1])\n else:\n # Convert dict inputs like"} {"repo":"httpx","file":"httpx/_urls.py","line":425,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None:\n assert len(args) < 2, \"Too many arguments.\"\n assert not (args and kwargs), \"Cannot mix named and unnamed arguments.\"\n\n value = args[0] if args else kwargs\n\n if value is None or isinstance(value, (str, bytes)):\n value = value.decode(\"ascii\") if isinstance(value, bytes) else value\n self._dict = parse_qs(value, keep_blank_values=True)\n elif isinstance(value, QueryParams):\n self._dict = {k: list(v) for k, v in value._dict.items()}\n else:\n dict_value: dict[typing.Any, list[typing.Any]] = {}\n if isinstance(value, (list, tuple)):\n # Convert list inputs like:\n # [(\"a\", \"123\"), (\"a\", \"456\"), (\"b\", \"789\")]\n # To a dict representation, like:\n # {\"a\": [\"123\", \"456\"], \"b\": [\"789\"]}\n for item in value:\n dict_value.setdefault(item[0], []).append(item[1])\n else:\n # Convert dict inputs like:\n # {\"a\": \"123\", \"b\": [\"456\", \"789\"]}\n # To dict inputs where values are al"} {"repo":"httpx","file":"httpx/_urls.py","line":463,"symbol":"keys","kind":"function","lang":"python","code":"def keys(self) -> typing.KeysView[str]:\n \"\"\"\n Return all the keys in the query params.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123&a=456&b=789\")\n assert list(q.keys()) == [\"a\", \"b\"]\n \"\"\"\n return self._dict.keys()"} {"repo":"httpx","file":"httpx/_urls.py","line":474,"symbol":"values","kind":"function","lang":"python","code":"def values(self) -> typing.ValuesView[str]:\n \"\"\"\n Return all the values in the query params. If a key occurs more than once\n only the first item for that key is returned.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123&a=456&b=789\")\n assert list(q.values()) == [\"123\", \"789\"]\n \"\"\"\n return {k: v[0] for k, v in self._dict.items()}.values()"} {"repo":"httpx","file":"httpx/_urls.py","line":486,"symbol":"items","kind":"function","lang":"python","code":"def items(self) -> typing.ItemsView[str, str]:\n \"\"\"\n Return all items in the query params. If a key occurs more than once\n only the first item for that key is returned.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123&a=456&b=789\")\n assert list(q.items()) == [(\"a\", \"123\"), (\"b\", \"789\")]\n \"\"\"\n return {k: v[0] for k, v in self._dict.items()}.items()"} {"repo":"httpx","file":"httpx/_urls.py","line":498,"symbol":"multi_items","kind":"function","lang":"python","code":"def multi_items(self) -> list[tuple[str, str]]:\n \"\"\"\n Return all items in the query params. Allow duplicate keys to occur.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123&a=456&b=789\")\n assert list(q.multi_items()) == [(\"a\", \"123\"), (\"a\", \"456\"), (\"b\", \"789\")]\n \"\"\"\n multi_items: list[tuple[str, str]] = []\n for k, v in self._dict.items():\n multi_items.extend([(k, i) for i in v])\n return multi_items"} {"repo":"httpx","file":"httpx/_urls.py","line":512,"symbol":"get","kind":"function","lang":"python","code":"def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:\n \"\"\"\n Get a value from the query param for a given key. If the key occurs\n more than once, then only the first value is returned.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123&a=456&b=789\")\n assert q.get(\"a\") == \"123\"\n \"\"\"\n if key in self._dict:\n return self._dict[str(key)][0]\n return default"} {"repo":"httpx","file":"httpx/_urls.py","line":526,"symbol":"get_list","kind":"function","lang":"python","code":"def get_list(self, key: str) -> list[str]:\n \"\"\"\n Get all values from the query param for a given key.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123&a=456&b=789\")\n assert q.get_list(\"a\") == [\"123\", \"456\"]\n \"\"\"\n return list(self._dict.get(str(key), []))"} {"repo":"httpx","file":"httpx/_urls.py","line":537,"symbol":"set","kind":"function","lang":"python","code":"def set(self, key: str, value: typing.Any = None) -> QueryParams:\n \"\"\"\n Return a new QueryParams instance, setting the value of a key.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123\")\n q = q.set(\"a\", \"456\")\n assert q == httpx.QueryParams(\"a=456\")\n \"\"\"\n q = QueryParams()\n q._dict = dict(self._dict)\n q._dict[str(key)] = [primitive_value_to_str(value)]\n return q"} {"repo":"httpx","file":"httpx/_urls.py","line":552,"symbol":"add","kind":"function","lang":"python","code":"def add(self, key: str, value: typing.Any = None) -> QueryParams:\n \"\"\"\n Return a new QueryParams instance, setting or appending the value of a key.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123\")\n q = q.add(\"a\", \"456\")\n assert q == httpx.QueryParams(\"a=123&a=456\")\n \"\"\"\n q = QueryParams()\n q._dict = dict(self._dict)\n q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]\n return q"} {"repo":"httpx","file":"httpx/_urls.py","line":567,"symbol":"remove","kind":"function","lang":"python","code":"def remove(self, key: str) -> QueryParams:\n \"\"\"\n Return a new QueryParams instance, removing the value of a key.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123\")\n q = q.remove(\"a\")\n assert q == httpx.QueryParams(\"\")\n \"\"\"\n q = QueryParams()\n q._dict = dict(self._dict)\n q._dict.pop(str(key), None)\n return q"} {"repo":"httpx","file":"httpx/_urls.py","line":582,"symbol":"merge","kind":"function","lang":"python","code":"def merge(self, params: QueryParamTypes | None = None) -> QueryParams:\n \"\"\"\n Return a new QueryParams instance, updated with.\n\n Usage:\n\n q = httpx.QueryParams(\"a=123\")\n q = q.merge({\"b\": \"456\"})\n assert q == httpx.QueryParams(\"a=123&b=456\")\n\n q = httpx.QueryParams(\"a=123\")\n q = q.merge({\"a\": \"456\", \"b\": \"789\"})\n assert q == httpx.QueryParams(\"a=456&b=789\")\n \"\"\"\n q = QueryParams(params)\n q._dict = {**self._dict, **q._dict}\n return q"} {"repo":"httpx","file":"httpx/_urls.py","line":600,"symbol":"__getitem__","kind":"function","lang":"python","code":"def __getitem__(self, key: typing.Any) -> str:\n return self._dict[key][0]"} {"repo":"httpx","file":"httpx/_urls.py","line":603,"symbol":"__contains__","kind":"function","lang":"python","code":"def __contains__(self, key: typing.Any) -> bool:\n return key in self._dict"} {"repo":"httpx","file":"httpx/_urls.py","line":606,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> typing.Iterator[typing.Any]:\n return iter(self.keys())"} {"repo":"httpx","file":"httpx/_urls.py","line":609,"symbol":"__len__","kind":"function","lang":"python","code":"def __len__(self) -> int:\n return len(self._dict)"} {"repo":"httpx","file":"httpx/_urls.py","line":612,"symbol":"__bool__","kind":"function","lang":"python","code":"def __bool__(self) -> bool:\n return bool(self._dict)"} {"repo":"httpx","file":"httpx/_urls.py","line":615,"symbol":"__hash__","kind":"function","lang":"python","code":"def __hash__(self) -> int:\n return hash(str(self))"} {"repo":"httpx","file":"httpx/_urls.py","line":618,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: typing.Any) -> bool:\n if not isinstance(other, self.__class__):\n return False\n return sorted(self.multi_items()) == sorted(other.multi_items())"} {"repo":"httpx","file":"httpx/_urls.py","line":623,"symbol":"__str__","kind":"function","lang":"python","code":"def __str__(self) -> str:\n return urlencode(self.multi_items())"} {"repo":"httpx","file":"httpx/_urls.py","line":626,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n class_name = self.__class__.__name__\n query_string = str(self)\n return f\"{class_name}({query_string!r})\""} {"repo":"httpx","file":"httpx/_urls.py","line":631,"symbol":"update","kind":"function","lang":"python","code":"def update(self, params: QueryParamTypes | None = None) -> None:\n raise RuntimeError(\n \"QueryParams are immutable since 0.18.0. \"\n \"Use `q = q.merge(...)` to create an updated copy.\"\n )"} {"repo":"httpx","file":"httpx/_urls.py","line":637,"symbol":"__setitem__","kind":"function","lang":"python","code":"def __setitem__(self, key: str, value: str) -> None:\n raise RuntimeError(\n \"QueryParams are immutable since 0.18.0. \"\n \"Use `q = q.set(key, value)` to create an updated copy.\"\n )"} {"repo":"httpx","file":"httpx/_utils.py","line":15,"symbol":"primitive_value_to_str","kind":"function","lang":"python","code":"def primitive_value_to_str(value: PrimitiveData) -> str:\n \"\"\"\n Coerce a primitive data type into a string value.\n\n Note that we prefer JSON-style 'true'/'false' for boolean values here.\n \"\"\"\n if value is True:\n return \"true\"\n elif value is False:\n return \"false\"\n elif value is None:\n return \"\"\n return str(value)"} {"repo":"httpx","file":"httpx/_utils.py","line":30,"symbol":"get_environment_proxies","kind":"function","lang":"python","code":"def get_environment_proxies() -> dict[str, str | None]:\n \"\"\"Gets proxy information from the environment\"\"\"\n\n # urllib.request.getproxies() falls back on System\n # Registry and Config for proxies on Windows and macOS.\n # We don't want to propagate non-HTTP proxies into\n # our configuration such as 'TRAVIS_APT_PROXY'.\n proxy_info = getproxies()\n mounts: dict[str, str | None] = {}\n\n for scheme in (\"http\", \"https\", \"all\"):\n if proxy_info.get(scheme):\n hostname = proxy_info[scheme]\n mounts[f\"{scheme}://\"] = (\n hostname if \"://\" in hostname else f\"http://{hostname}\"\n )\n\n no_proxy_hosts = [host.strip() for host in proxy_info.get(\"no\", \"\").split(\",\")]\n for hostname in no_proxy_hosts:\n # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details\n # on how names in `NO_PROXY` are handled.\n if hostname == \"*\":\n # If NO_PROXY=* is used or if \"*\" occurs as any one of the comma\n # separated hostnames, then we should just bypass any information\n # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore\n # proxies.\n return {}\n "} {"repo":"httpx","file":"httpx/_utils.py","line":79,"symbol":"to_bytes","kind":"function","lang":"python","code":"def to_bytes(value: str | bytes, encoding: str = \"utf-8\") -> bytes:\n return value.encode(encoding) if isinstance(value, str) else value"} {"repo":"httpx","file":"httpx/_utils.py","line":83,"symbol":"to_str","kind":"function","lang":"python","code":"def to_str(value: str | bytes, encoding: str = \"utf-8\") -> str:\n return value if isinstance(value, str) else value.decode(encoding)"} {"repo":"httpx","file":"httpx/_utils.py","line":87,"symbol":"to_bytes_or_str","kind":"function","lang":"python","code":"def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:\n return value if isinstance(match_type_of, str) else value.encode()"} {"repo":"httpx","file":"httpx/_utils.py","line":91,"symbol":"unquote","kind":"function","lang":"python","code":"def unquote(value: str) -> str:\n return value[1:-1] if value[0] == value[-1] == '\"' else value"} {"repo":"httpx","file":"httpx/_utils.py","line":95,"symbol":"peek_filelike_length","kind":"function","lang":"python","code":"def peek_filelike_length(stream: typing.Any) -> int | None:\n \"\"\"\n Given a file-like stream object, return its length in number of bytes\n without reading it into memory.\n \"\"\"\n try:\n # Is it an actual file?\n fd = stream.fileno()\n # Yup, seems to be an actual file.\n length = os.fstat(fd).st_size\n except (AttributeError, OSError):\n # No... Maybe it's something that supports random access, like `io.BytesIO`?\n try:\n # Assuming so, go to end of stream to figure out its length,\n # then put it back in place.\n offset = stream.tell()\n length = stream.seek(0, os.SEEK_END)\n stream.seek(offset)\n except (AttributeError, OSError):\n # Not even that? Sorry, we're doomed...\n return None\n\n return length"} {"repo":"httpx","file":"httpx/_utils.py","line":120,"symbol":"URLPattern","kind":"class","lang":"python","code":"class URLPattern:\n \"\"\"\n A utility class currently used for making lookups against proxy keys...\n\n # Wildcard matching...\n >>> pattern = URLPattern(\"all://\")\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n True\n\n # Witch scheme matching...\n >>> pattern = URLPattern(\"https://\")\n >>> pattern.matches(httpx.URL(\"https://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n False\n\n # With domain matching...\n >>> pattern = URLPattern(\"https://example.com\")\n >>> pattern.matches(httpx.URL(\"https://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n False\n >>> pattern.matches(httpx.URL(\"https://other.com\"))\n False\n\n # Wildcard scheme, with domain matching...\n >>> pattern = URLPattern(\"all://example.com\")\n >>> pattern.matches(httpx.URL(\"https://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"http://example.com\"))\n True\n >>> pattern.matches(httpx.URL(\"https://other.com\"))\n False\n\n # With port matching...\n >>> pattern = URLPattern(\"https://example.com:1234\")\n >>> pattern.matches(httpx.URL(\"https://example.com:1234\"))\n True\n >>> pattern.matc"} {"repo":"httpx","file":"httpx/_utils.py","line":162,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, pattern: str) -> None:\n from ._urls import URL\n\n if pattern and \":\" not in pattern:\n raise ValueError(\n f\"Proxy keys should use proper URL forms rather \"\n f\"than plain scheme strings. \"\n f'Instead of \"{pattern}\", use \"{pattern}://\"'\n )\n\n url = URL(pattern)\n self.pattern = pattern\n self.scheme = \"\" if url.scheme == \"all\" else url.scheme\n self.host = \"\" if url.host == \"*\" else url.host\n self.port = url.port\n if not url.host or url.host == \"*\":\n self.host_regex: typing.Pattern[str] | None = None\n elif url.host.startswith(\"*.\"):\n # *.example.com should match \"www.example.com\", but not \"example.com\"\n domain = re.escape(url.host[2:])\n self.host_regex = re.compile(f\"^.+\\\\.{domain}$\")\n elif url.host.startswith(\"*\"):\n # *example.com should match \"www.example.com\" and \"example.com\"\n domain = re.escape(url.host[1:])\n self.host_regex = re.compile(f\"^(.+\\\\.)?{domain}$\")\n else:\n # example.com should match \"example.com\" but not \"www.example.com\"\n "} {"repo":"httpx","file":"httpx/_utils.py","line":192,"symbol":"matches","kind":"function","lang":"python","code":"def matches(self, other: URL) -> bool:\n if self.scheme and self.scheme != other.scheme:\n return False\n if (\n self.host\n and self.host_regex is not None\n and not self.host_regex.match(other.host)\n ):\n return False\n if self.port is not None and self.port != other.port:\n return False\n return True"} {"repo":"httpx","file":"httpx/_utils.py","line":206,"symbol":"priority","kind":"function","lang":"python","code":"def priority(self) -> tuple[int, int, int]:\n \"\"\"\n The priority allows URLPattern instances to be sortable, so that\n we can match from most specific to least specific.\n \"\"\"\n # URLs with a port should take priority over URLs without a port.\n port_priority = 0 if self.port is not None else 1\n # Longer hostnames should match first.\n host_priority = -len(self.host)\n # Longer schemes should match first.\n scheme_priority = -len(self.scheme)\n return (port_priority, host_priority, scheme_priority)"} {"repo":"httpx","file":"httpx/_utils.py","line":219,"symbol":"__hash__","kind":"function","lang":"python","code":"def __hash__(self) -> int:\n return hash(self.pattern)"} {"repo":"httpx","file":"httpx/_utils.py","line":222,"symbol":"__lt__","kind":"function","lang":"python","code":"def __lt__(self, other: URLPattern) -> bool:\n return self.priority < other.priority"} {"repo":"httpx","file":"httpx/_utils.py","line":225,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, URLPattern) and self.pattern == other.pattern"} {"repo":"httpx","file":"httpx/_utils.py","line":229,"symbol":"is_ipv4_hostname","kind":"function","lang":"python","code":"def is_ipv4_hostname(hostname: str) -> bool:\n try:\n ipaddress.IPv4Address(hostname.split(\"/\")[0])\n except Exception:\n return False\n return True"} {"repo":"httpx","file":"httpx/_utils.py","line":237,"symbol":"is_ipv6_hostname","kind":"function","lang":"python","code":"def is_ipv6_hostname(hostname: str) -> bool:\n try:\n ipaddress.IPv6Address(hostname.split(\"/\")[0])\n except Exception:\n return False\n return True"} {"repo":"httpx","file":"requirements.txt","line":9,"symbol":"chardet","kind":"field","lang":"requirements","code":"chardet==5.2.0"} {"repo":"httpx","file":"requirements.txt","line":12,"symbol":"mkdocs","kind":"field","lang":"requirements","code":"mkdocs==1.6.1"} {"repo":"httpx","file":"requirements.txt","line":13,"symbol":"mkautodoc","kind":"field","lang":"requirements","code":"mkautodoc==0.2.0"} {"repo":"httpx","file":"requirements.txt","line":14,"symbol":"mkdocs-material","kind":"field","lang":"requirements","code":"mkdocs-material==9.6.18"} {"repo":"httpx","file":"requirements.txt","line":17,"symbol":"build","kind":"field","lang":"requirements","code":"build==1.3.0"} {"repo":"httpx","file":"requirements.txt","line":18,"symbol":"twine","kind":"field","lang":"requirements","code":"twine==6.1.0"} {"repo":"httpx","file":"requirements.txt","line":21,"symbol":"coverage","kind":"field","lang":"requirements","code":"coverage[toml]==7.10.6"} {"repo":"httpx","file":"requirements.txt","line":22,"symbol":"cryptography","kind":"field","lang":"requirements","code":"cryptography==45.0.7"} {"repo":"httpx","file":"requirements.txt","line":23,"symbol":"mypy","kind":"field","lang":"requirements","code":"mypy==1.17.1"} {"repo":"httpx","file":"requirements.txt","line":24,"symbol":"pytest","kind":"field","lang":"requirements","code":"pytest==8.4.1"} {"repo":"httpx","file":"requirements.txt","line":25,"symbol":"ruff","kind":"field","lang":"requirements","code":"ruff==0.12.11"} {"repo":"httpx","file":"requirements.txt","line":26,"symbol":"trio","kind":"field","lang":"requirements","code":"trio==0.31.0"} {"repo":"httpx","file":"requirements.txt","line":27,"symbol":"trio-typing","kind":"field","lang":"requirements","code":"trio-typing==0.10.0"} {"repo":"httpx","file":"requirements.txt","line":28,"symbol":"trustme","kind":"field","lang":"requirements","code":"trustme==1.2.1"} {"repo":"httpx","file":"requirements.txt","line":29,"symbol":"uvicorn","kind":"field","lang":"requirements","code":"uvicorn==0.35.0"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":12,"symbol":"test_get","kind":"function","lang":"python","code":"async def test_get(server):\n url = server.url\n async with httpx.AsyncClient(http2=True) as client:\n response = await client.get(url)\n assert response.status_code == 200\n assert response.text == \"Hello, world!\"\n assert response.http_version == \"HTTP/1.1\"\n assert response.headers\n assert repr(response) == \"\"\n assert response.elapsed > timedelta(seconds=0)"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":33,"symbol":"test_get_invalid_url","kind":"function","lang":"python","code":"async def test_get_invalid_url(server, url):\n async with httpx.AsyncClient() as client:\n with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):\n await client.get(url)"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":40,"symbol":"test_build_request","kind":"function","lang":"python","code":"async def test_build_request(server):\n url = server.url.copy_with(path=\"/echo_headers\")\n headers = {\"Custom-header\": \"value\"}\n async with httpx.AsyncClient() as client:\n request = client.build_request(\"GET\", url)\n request.headers.update(headers)\n response = await client.send(request)\n\n assert response.status_code == 200\n assert response.url == url\n\n assert response.json()[\"Custom-header\"] == \"value\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":55,"symbol":"test_post","kind":"function","lang":"python","code":"async def test_post(server):\n url = server.url\n async with httpx.AsyncClient() as client:\n response = await client.post(url, content=b\"Hello, world!\")\n assert response.status_code == 200"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":63,"symbol":"test_post_json","kind":"function","lang":"python","code":"async def test_post_json(server):\n url = server.url\n async with httpx.AsyncClient() as client:\n response = await client.post(url, json={\"text\": \"Hello, world!\"})\n assert response.status_code == 200"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":71,"symbol":"test_stream_response","kind":"function","lang":"python","code":"async def test_stream_response(server):\n async with httpx.AsyncClient() as client:\n async with client.stream(\"GET\", server.url) as response:\n body = await response.aread()\n\n assert response.status_code == 200\n assert body == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":82,"symbol":"test_access_content_stream_response","kind":"function","lang":"python","code":"async def test_access_content_stream_response(server):\n async with httpx.AsyncClient() as client:\n async with client.stream(\"GET\", server.url) as response:\n pass\n\n assert response.status_code == 200\n with pytest.raises(httpx.ResponseNotRead):\n response.content # noqa: B018"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":93,"symbol":"test_stream_request","kind":"function","lang":"python","code":"async def test_stream_request(server):\n async def hello_world() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\"\n\n async with httpx.AsyncClient() as client:\n response = await client.post(server.url, content=hello_world())\n assert response.status_code == 200"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":94,"symbol":"hello_world","kind":"function","lang":"python","code":"async def hello_world() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":104,"symbol":"test_cannot_stream_sync_request","kind":"function","lang":"python","code":"async def test_cannot_stream_sync_request(server):\n def hello_world() -> typing.Iterator[bytes]: # pragma: no cover\n yield b\"Hello, \"\n yield b\"world!\"\n\n async with httpx.AsyncClient() as client:\n with pytest.raises(RuntimeError):\n await client.post(server.url, content=hello_world())"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":105,"symbol":"hello_world","kind":"function","lang":"python","code":"def hello_world() -> typing.Iterator[bytes]: # pragma: no cover\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":115,"symbol":"test_raise_for_status","kind":"function","lang":"python","code":"async def test_raise_for_status(server):\n async with httpx.AsyncClient() as client:\n for status_code in (200, 400, 404, 500, 505):\n response = await client.request(\n \"GET\", server.url.copy_with(path=f\"/status/{status_code}\")\n )\n\n if 400 <= status_code < 600:\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert exc_info.value.response == response\n else:\n assert response.raise_for_status() is response"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":131,"symbol":"test_options","kind":"function","lang":"python","code":"async def test_options(server):\n async with httpx.AsyncClient() as client:\n response = await client.options(server.url)\n assert response.status_code == 200\n assert response.text == \"Hello, world!\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":139,"symbol":"test_head","kind":"function","lang":"python","code":"async def test_head(server):\n async with httpx.AsyncClient() as client:\n response = await client.head(server.url)\n assert response.status_code == 200\n assert response.text == \"\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":147,"symbol":"test_put","kind":"function","lang":"python","code":"async def test_put(server):\n async with httpx.AsyncClient() as client:\n response = await client.put(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":154,"symbol":"test_patch","kind":"function","lang":"python","code":"async def test_patch(server):\n async with httpx.AsyncClient() as client:\n response = await client.patch(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":161,"symbol":"test_delete","kind":"function","lang":"python","code":"async def test_delete(server):\n async with httpx.AsyncClient() as client:\n response = await client.delete(server.url)\n assert response.status_code == 200\n assert response.text == \"Hello, world!\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":169,"symbol":"test_100_continue","kind":"function","lang":"python","code":"async def test_100_continue(server):\n headers = {\"Expect\": \"100-continue\"}\n content = b\"Echo request body\"\n\n async with httpx.AsyncClient() as client:\n response = await client.post(\n server.url.copy_with(path=\"/echo_body\"), headers=headers, content=content\n )\n\n assert response.status_code == 200\n assert response.content == content"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":183,"symbol":"test_context_managed_transport","kind":"function","lang":"python","code":"async def test_context_managed_transport():\n class Transport(httpx.AsyncBaseTransport):\n def __init__(self) -> None:\n self.events: list[str] = []\n\n async def aclose(self):\n # The base implementation of httpx.AsyncBaseTransport just\n # calls into `.aclose`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__aenter__`/`__aexit__`.\n self.events.append(\"transport.aclose\")\n\n async def __aenter__(self):\n await super().__aenter__()\n self.events.append(\"transport.__aenter__\")\n\n async def __aexit__(self, *args):\n await super().__aexit__(*args)\n self.events.append(\"transport.__aexit__\")\n\n transport = Transport()\n async with httpx.AsyncClient(transport=transport):\n pass\n\n assert transport.events == [\n \"transport.__aenter__\",\n \"transport.aclose\",\n \"transport.__aexit__\",\n ]"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":184,"symbol":"Transport","kind":"class","lang":"python","code":"class Transport(httpx.AsyncBaseTransport):\n def __init__(self) -> None:\n self.events: list[str] = []\n\n async def aclose(self):\n # The base implementation of httpx.AsyncBaseTransport just\n # calls into `.aclose`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__aenter__`/`__aexit__`.\n self.events.append(\"transport.aclose\")\n\n async def __aenter__(self):\n await super().__aenter__()\n self.events.append(\"transport.__aenter__\")\n\n async def __aexit__(self, *args):\n await super().__aexit__(*args)\n self.events.append(\"transport.__aexit__\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":185,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.events: list[str] = []"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":188,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self):\n # The base implementation of httpx.AsyncBaseTransport just\n # calls into `.aclose`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__aenter__`/`__aexit__`.\n self.events.append(\"transport.aclose\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":195,"symbol":"__aenter__","kind":"function","lang":"python","code":"async def __aenter__(self):\n await super().__aenter__()\n self.events.append(\"transport.__aenter__\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":199,"symbol":"__aexit__","kind":"function","lang":"python","code":"async def __aexit__(self, *args):\n await super().__aexit__(*args)\n self.events.append(\"transport.__aexit__\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":215,"symbol":"test_context_managed_transport_and_mount","kind":"function","lang":"python","code":"async def test_context_managed_transport_and_mount():\n class Transport(httpx.AsyncBaseTransport):\n def __init__(self, name: str) -> None:\n self.name: str = name\n self.events: list[str] = []\n\n async def aclose(self):\n # The base implementation of httpx.AsyncBaseTransport just\n # calls into `.aclose`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__aenter__`/`__aexit__`.\n self.events.append(f\"{self.name}.aclose\")\n\n async def __aenter__(self):\n await super().__aenter__()\n self.events.append(f\"{self.name}.__aenter__\")\n\n async def __aexit__(self, *args):\n await super().__aexit__(*args)\n self.events.append(f\"{self.name}.__aexit__\")\n\n transport = Transport(name=\"transport\")\n mounted = Transport(name=\"mounted\")\n async with httpx.AsyncClient(\n transport=transport, mounts={\"http://www.example.org\": mounted}\n ):\n pass\n\n assert transport.events == [\n \"transport.__aenter__\",\n \"transport.aclose\",\n \"trans"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":216,"symbol":"Transport","kind":"class","lang":"python","code":"class Transport(httpx.AsyncBaseTransport):\n def __init__(self, name: str) -> None:\n self.name: str = name\n self.events: list[str] = []\n\n async def aclose(self):\n # The base implementation of httpx.AsyncBaseTransport just\n # calls into `.aclose`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__aenter__`/`__aexit__`.\n self.events.append(f\"{self.name}.aclose\")\n\n async def __aenter__(self):\n await super().__aenter__()\n self.events.append(f\"{self.name}.__aenter__\")\n\n async def __aexit__(self, *args):\n await super().__aexit__(*args)\n self.events.append(f\"{self.name}.__aexit__\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":217,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, name: str) -> None:\n self.name: str = name\n self.events: list[str] = []"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":221,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self):\n # The base implementation of httpx.AsyncBaseTransport just\n # calls into `.aclose`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__aenter__`/`__aexit__`.\n self.events.append(f\"{self.name}.aclose\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":228,"symbol":"__aenter__","kind":"function","lang":"python","code":"async def __aenter__(self):\n await super().__aenter__()\n self.events.append(f\"{self.name}.__aenter__\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":232,"symbol":"__aexit__","kind":"function","lang":"python","code":"async def __aexit__(self, *args):\n await super().__aexit__(*args)\n self.events.append(f\"{self.name}.__aexit__\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":255,"symbol":"hello_world","kind":"function","lang":"python","code":"def hello_world(request):\n return httpx.Response(200, text=\"Hello, world!\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":260,"symbol":"test_client_closed_state_using_implicit_open","kind":"function","lang":"python","code":"async def test_client_closed_state_using_implicit_open():\n client = httpx.AsyncClient(transport=httpx.MockTransport(hello_world))\n\n assert not client.is_closed\n await client.get(\"http://example.com\")\n\n assert not client.is_closed\n await client.aclose()\n\n assert client.is_closed\n # Once we're close we cannot make any more requests.\n with pytest.raises(RuntimeError):\n await client.get(\"http://example.com\")\n\n # Once we're closed we cannot reopen the client.\n with pytest.raises(RuntimeError):\n async with client:\n pass # pragma: no cover"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":281,"symbol":"test_client_closed_state_using_with_block","kind":"function","lang":"python","code":"async def test_client_closed_state_using_with_block():\n async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:\n assert not client.is_closed\n await client.get(\"http://example.com\")\n\n assert client.is_closed\n with pytest.raises(RuntimeError):\n await client.get(\"http://example.com\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":291,"symbol":"unmounted","kind":"function","lang":"python","code":"def unmounted(request: httpx.Request) -> httpx.Response:\n data = {\"app\": \"unmounted\"}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":296,"symbol":"mounted","kind":"function","lang":"python","code":"def mounted(request: httpx.Request) -> httpx.Response:\n data = {\"app\": \"mounted\"}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":302,"symbol":"test_mounted_transport","kind":"function","lang":"python","code":"async def test_mounted_transport():\n transport = httpx.MockTransport(unmounted)\n mounts = {\"custom://\": httpx.MockTransport(mounted)}\n\n async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:\n response = await client.get(\"https://www.example.com\")\n assert response.status_code == 200\n assert response.json() == {\"app\": \"unmounted\"}\n\n response = await client.get(\"custom://www.example.com\")\n assert response.status_code == 200\n assert response.json() == {\"app\": \"mounted\"}"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":317,"symbol":"test_async_mock_transport","kind":"function","lang":"python","code":"async def test_async_mock_transport():\n async def hello_world(request: httpx.Request) -> httpx.Response:\n return httpx.Response(200, text=\"Hello, world!\")\n\n transport = httpx.MockTransport(hello_world)\n\n async with httpx.AsyncClient(transport=transport) as client:\n response = await client.get(\"https://www.example.com\")\n assert response.status_code == 200\n assert response.text == \"Hello, world!\""} {"repo":"httpx","file":"tests/client/test_async_client.py","line":318,"symbol":"hello_world","kind":"function","lang":"python","code":"async def hello_world(request: httpx.Request) -> httpx.Response:\n return httpx.Response(200, text=\"Hello, world!\")"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":330,"symbol":"test_cancellation_during_stream","kind":"function","lang":"python","code":"async def test_cancellation_during_stream():\n \"\"\"\n If any BaseException is raised during streaming the response, then the\n stream should be closed.\n\n This includes:\n\n * `asyncio.CancelledError` (A subclass of BaseException from Python 3.8 onwards.)\n * `trio.Cancelled`\n * `KeyboardInterrupt`\n * `SystemExit`\n\n See https://github.com/encode/httpx/issues/2139\n \"\"\"\n stream_was_closed = False\n\n def response_with_cancel_during_stream(request):\n class CancelledStream(httpx.AsyncByteStream):\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield b\"Hello\"\n raise KeyboardInterrupt()\n yield b\", world\" # pragma: no cover\n\n async def aclose(self) -> None:\n nonlocal stream_was_closed\n stream_was_closed = True\n\n return httpx.Response(\n 200, headers={\"Content-Length\": \"12\"}, stream=CancelledStream()\n )\n\n transport = httpx.MockTransport(response_with_cancel_during_stream)\n\n async with httpx.AsyncClient(transport=transport) as client:\n with pytest.raises(KeyboardInterrupt):\n await client.get(\"https://ww"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":346,"symbol":"response_with_cancel_during_stream","kind":"function","lang":"python","code":"def response_with_cancel_during_stream(request):\n class CancelledStream(httpx.AsyncByteStream):\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield b\"Hello\"\n raise KeyboardInterrupt()\n yield b\", world\" # pragma: no cover\n\n async def aclose(self) -> None:\n nonlocal stream_was_closed\n stream_was_closed = True\n\n return httpx.Response(\n 200, headers={\"Content-Length\": \"12\"}, stream=CancelledStream()\n )"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":347,"symbol":"CancelledStream","kind":"class","lang":"python","code":"class CancelledStream(httpx.AsyncByteStream):\n async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield b\"Hello\"\n raise KeyboardInterrupt()\n yield b\", world\" # pragma: no cover\n\n async def aclose(self) -> None:\n nonlocal stream_was_closed\n stream_was_closed = True"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":348,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self) -> typing.AsyncIterator[bytes]:\n yield b\"Hello\"\n raise KeyboardInterrupt()\n yield b\", world\" # pragma: no cover"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":353,"symbol":"aclose","kind":"function","lang":"python","code":"async def aclose(self) -> None:\n nonlocal stream_was_closed\n stream_was_closed = True"} {"repo":"httpx","file":"tests/client/test_async_client.py","line":370,"symbol":"test_server_extensions","kind":"function","lang":"python","code":"async def test_server_extensions(server):\n url = server.url\n async with httpx.AsyncClient(http2=True) as client:\n response = await client.get(url)\n assert response.status_code == 200\n assert response.extensions[\"http_version\"] == b\"HTTP/1.1\""} {"repo":"httpx","file":"tests/client/test_auth.py","line":23,"symbol":"App","kind":"class","lang":"python","code":"class App:\n \"\"\"\n A mock app to test auth credentials.\n \"\"\"\n\n def __init__(self, auth_header: str = \"\", status_code: int = 200) -> None:\n self.auth_header = auth_header\n self.status_code = status_code\n\n def __call__(self, request: httpx.Request) -> httpx.Response:\n headers = {\"www-authenticate\": self.auth_header} if self.auth_header else {}\n data = {\"auth\": request.headers.get(\"Authorization\")}\n return httpx.Response(self.status_code, headers=headers, json=data)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":28,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, auth_header: str = \"\", status_code: int = 200) -> None:\n self.auth_header = auth_header\n self.status_code = status_code"} {"repo":"httpx","file":"tests/client/test_auth.py","line":32,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, request: httpx.Request) -> httpx.Response:\n headers = {\"www-authenticate\": self.auth_header} if self.auth_header else {}\n data = {\"auth\": request.headers.get(\"Authorization\")}\n return httpx.Response(self.status_code, headers=headers, json=data)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":38,"symbol":"DigestApp","kind":"class","lang":"python","code":"class DigestApp:\n def __init__(\n self,\n algorithm: str = \"SHA-256\",\n send_response_after_attempt: int = 1,\n qop: str = \"auth\",\n regenerate_nonce: bool = True,\n ) -> None:\n self.algorithm = algorithm\n self.send_response_after_attempt = send_response_after_attempt\n self.qop = qop\n self._regenerate_nonce = regenerate_nonce\n self._response_count = 0\n\n def __call__(self, request: httpx.Request) -> httpx.Response:\n if self._response_count < self.send_response_after_attempt:\n return self.challenge_send(request)\n\n data = {\"auth\": request.headers.get(\"Authorization\")}\n return httpx.Response(200, json=data)\n\n def challenge_send(self, request: httpx.Request) -> httpx.Response:\n self._response_count += 1\n nonce = (\n hashlib.sha256(os.urandom(8)).hexdigest()\n if self._regenerate_nonce\n else \"ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3\"\n )\n challenge_data = {\n \"nonce\": nonce,\n \"qop\": self.qop,\n \"opaque\": (\n \"ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2"} {"repo":"httpx","file":"tests/client/test_auth.py","line":39,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n algorithm: str = \"SHA-256\",\n send_response_after_attempt: int = 1,\n qop: str = \"auth\",\n regenerate_nonce: bool = True,\n ) -> None:\n self.algorithm = algorithm\n self.send_response_after_attempt = send_response_after_attempt\n self.qop = qop\n self._regenerate_nonce = regenerate_nonce\n self._response_count = 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":52,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, request: httpx.Request) -> httpx.Response:\n if self._response_count < self.send_response_after_attempt:\n return self.challenge_send(request)\n\n data = {\"auth\": request.headers.get(\"Authorization\")}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":59,"symbol":"challenge_send","kind":"function","lang":"python","code":"def challenge_send(self, request: httpx.Request) -> httpx.Response:\n self._response_count += 1\n nonce = (\n hashlib.sha256(os.urandom(8)).hexdigest()\n if self._regenerate_nonce\n else \"ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3\"\n )\n challenge_data = {\n \"nonce\": nonce,\n \"qop\": self.qop,\n \"opaque\": (\n \"ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1\"\n ),\n \"algorithm\": self.algorithm,\n \"stale\": \"FALSE\",\n }\n challenge_str = \", \".join(\n '{}=\"{}\"'.format(key, value)\n for key, value in challenge_data.items()\n if value\n )\n\n headers = {\n \"www-authenticate\": f'Digest realm=\"httpx@example.org\", {challenge_str}',\n }\n return httpx.Response(401, headers=headers)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":87,"symbol":"RepeatAuth","kind":"class","lang":"python","code":"class RepeatAuth(httpx.Auth):\n \"\"\"\n A mock authentication scheme that requires clients to send\n the request a fixed number of times, and then send a last request containing\n an aggregation of nonces that the server sent in 'WWW-Authenticate' headers\n of intermediate responses.\n \"\"\"\n\n requires_request_body = True\n\n def __init__(self, repeat: int) -> None:\n self.repeat = repeat\n\n def auth_flow(\n self, request: httpx.Request\n ) -> typing.Generator[httpx.Request, httpx.Response, None]:\n nonces = []\n\n for index in range(self.repeat):\n request.headers[\"Authorization\"] = f\"Repeat {index}\"\n response = yield request\n nonces.append(response.headers[\"www-authenticate\"])\n\n key = \".\".join(nonces)\n request.headers[\"Authorization\"] = f\"Repeat {key}\"\n yield request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":97,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, repeat: int) -> None:\n self.repeat = repeat"} {"repo":"httpx","file":"tests/client/test_auth.py","line":100,"symbol":"auth_flow","kind":"function","lang":"python","code":"def auth_flow(\n self, request: httpx.Request\n ) -> typing.Generator[httpx.Request, httpx.Response, None]:\n nonces = []\n\n for index in range(self.repeat):\n request.headers[\"Authorization\"] = f\"Repeat {index}\"\n response = yield request\n nonces.append(response.headers[\"www-authenticate\"])\n\n key = \".\".join(nonces)\n request.headers[\"Authorization\"] = f\"Repeat {key}\"\n yield request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":115,"symbol":"ResponseBodyAuth","kind":"class","lang":"python","code":"class ResponseBodyAuth(httpx.Auth):\n \"\"\"\n A mock authentication scheme that requires clients to send an 'Authorization'\n header, then send back the contents of the response in the 'Authorization'\n header.\n \"\"\"\n\n requires_response_body = True\n\n def __init__(self, token: str) -> None:\n self.token = token\n\n def auth_flow(\n self, request: httpx.Request\n ) -> typing.Generator[httpx.Request, httpx.Response, None]:\n request.headers[\"Authorization\"] = self.token\n response = yield request\n data = response.text\n request.headers[\"Authorization\"] = data\n yield request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":124,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, token: str) -> None:\n self.token = token"} {"repo":"httpx","file":"tests/client/test_auth.py","line":127,"symbol":"auth_flow","kind":"function","lang":"python","code":"def auth_flow(\n self, request: httpx.Request\n ) -> typing.Generator[httpx.Request, httpx.Response, None]:\n request.headers[\"Authorization\"] = self.token\n response = yield request\n data = response.text\n request.headers[\"Authorization\"] = data\n yield request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":137,"symbol":"SyncOrAsyncAuth","kind":"class","lang":"python","code":"class SyncOrAsyncAuth(httpx.Auth):\n \"\"\"\n A mock authentication scheme that uses a different implementation for the\n sync and async cases.\n \"\"\"\n\n def __init__(self) -> None:\n self._lock = threading.Lock()\n self._async_lock = anyio.Lock()\n\n def sync_auth_flow(\n self, request: httpx.Request\n ) -> typing.Generator[httpx.Request, httpx.Response, None]:\n with self._lock:\n request.headers[\"Authorization\"] = \"sync-auth\"\n yield request\n\n async def async_auth_flow(\n self, request: httpx.Request\n ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:\n async with self._async_lock:\n request.headers[\"Authorization\"] = \"async-auth\"\n yield request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":143,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self._lock = threading.Lock()\n self._async_lock = anyio.Lock()"} {"repo":"httpx","file":"tests/client/test_auth.py","line":147,"symbol":"sync_auth_flow","kind":"function","lang":"python","code":"def sync_auth_flow(\n self, request: httpx.Request\n ) -> typing.Generator[httpx.Request, httpx.Response, None]:\n with self._lock:\n request.headers[\"Authorization\"] = \"sync-auth\"\n yield request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":154,"symbol":"async_auth_flow","kind":"function","lang":"python","code":"async def async_auth_flow(\n self, request: httpx.Request\n ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:\n async with self._async_lock:\n request.headers[\"Authorization\"] = \"async-auth\"\n yield request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":163,"symbol":"test_basic_auth","kind":"function","lang":"python","code":"async def test_basic_auth() -> None:\n url = \"https://example.org/\"\n auth = (\"user\", \"password123\")\n app = App()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Basic dXNlcjpwYXNzd29yZDEyMw==\"}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":176,"symbol":"test_basic_auth_with_stream","kind":"function","lang":"python","code":"async def test_basic_auth_with_stream() -> None:\n \"\"\"\n See: https://github.com/encode/httpx/pull/1312\n \"\"\"\n url = \"https://example.org/\"\n auth = (\"user\", \"password123\")\n app = App()\n\n async with httpx.AsyncClient(\n transport=httpx.MockTransport(app), auth=auth\n ) as client:\n async with client.stream(\"GET\", url) as response:\n await response.aread()\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Basic dXNlcjpwYXNzd29yZDEyMw==\"}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":195,"symbol":"test_basic_auth_in_url","kind":"function","lang":"python","code":"async def test_basic_auth_in_url() -> None:\n url = \"https://user:password123@example.org/\"\n app = App()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Basic dXNlcjpwYXNzd29yZDEyMw==\"}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":207,"symbol":"test_basic_auth_on_session","kind":"function","lang":"python","code":"async def test_basic_auth_on_session() -> None:\n url = \"https://example.org/\"\n auth = (\"user\", \"password123\")\n app = App()\n\n async with httpx.AsyncClient(\n transport=httpx.MockTransport(app), auth=auth\n ) as client:\n response = await client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Basic dXNlcjpwYXNzd29yZDEyMw==\"}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":222,"symbol":"test_custom_auth","kind":"function","lang":"python","code":"async def test_custom_auth() -> None:\n url = \"https://example.org/\"\n app = App()\n\n def auth(request: httpx.Request) -> httpx.Request:\n request.headers[\"Authorization\"] = \"Token 123\"\n return request\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Token 123\"}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":226,"symbol":"auth","kind":"function","lang":"python","code":"def auth(request: httpx.Request) -> httpx.Request:\n request.headers[\"Authorization\"] = \"Token 123\"\n return request"} {"repo":"httpx","file":"tests/client/test_auth.py","line":237,"symbol":"test_netrc_auth_credentials_exist","kind":"function","lang":"python","code":"def test_netrc_auth_credentials_exist() -> None:\n \"\"\"\n When netrc auth is being used and a request is made to a host that is\n in the netrc file, then the relevant credentials should be applied.\n \"\"\"\n netrc_file = str(FIXTURES_DIR / \".netrc\")\n url = \"http://netrcexample.org\"\n app = App()\n auth = httpx.NetRCAuth(netrc_file)\n\n with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\n \"auth\": \"Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk\"\n }"} {"repo":"httpx","file":"tests/client/test_auth.py","line":256,"symbol":"test_netrc_auth_credentials_do_not_exist","kind":"function","lang":"python","code":"def test_netrc_auth_credentials_do_not_exist() -> None:\n \"\"\"\n When netrc auth is being used and a request is made to a host that is\n not in the netrc file, then no credentials should be applied.\n \"\"\"\n netrc_file = str(FIXTURES_DIR / \".netrc\")\n url = \"http://example.org\"\n app = App()\n auth = httpx.NetRCAuth(netrc_file)\n\n with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": None}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":277,"symbol":"test_netrc_auth_nopassword_parse_error","kind":"function","lang":"python","code":"def test_netrc_auth_nopassword_parse_error() -> None: # pragma: no cover\n \"\"\"\n Python has different netrc parsing behaviours with different versions.\n For Python < 3.11 a netrc file with no password is invalid. In this case\n we want to allow the parse error to be raised.\n \"\"\"\n netrc_file = str(FIXTURES_DIR / \".netrc-nopassword\")\n with pytest.raises(netrc.NetrcParseError):\n httpx.NetRCAuth(netrc_file)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":289,"symbol":"test_auth_disable_per_request","kind":"function","lang":"python","code":"async def test_auth_disable_per_request() -> None:\n url = \"https://example.org/\"\n auth = (\"user\", \"password123\")\n app = App()\n\n async with httpx.AsyncClient(\n transport=httpx.MockTransport(app), auth=auth\n ) as client:\n response = await client.get(url, auth=None)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": None}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":303,"symbol":"test_auth_hidden_url","kind":"function","lang":"python","code":"def test_auth_hidden_url() -> None:\n url = \"http://example-username:example-password@example.org/\"\n expected = \"URL('http://example-username:[secure]@example.org/')\"\n assert url == httpx.URL(url)\n assert expected == repr(httpx.URL(url))"} {"repo":"httpx","file":"tests/client/test_auth.py","line":311,"symbol":"test_auth_hidden_header","kind":"function","lang":"python","code":"async def test_auth_hidden_header() -> None:\n url = \"https://example.org/\"\n auth = (\"example-username\", \"example-password\")\n app = App()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert \"'authorization': '[secure]'\" in str(response.request.headers)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":323,"symbol":"test_auth_property","kind":"function","lang":"python","code":"async def test_auth_property() -> None:\n app = App()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n assert client.auth is None\n\n client.auth = (\"user\", \"password123\")\n assert isinstance(client.auth, httpx.BasicAuth)\n\n url = \"https://example.org/\"\n response = await client.get(url)\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Basic dXNlcjpwYXNzd29yZDEyMw==\"}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":339,"symbol":"test_auth_invalid_type","kind":"function","lang":"python","code":"async def test_auth_invalid_type() -> None:\n app = App()\n\n with pytest.raises(TypeError):\n client = httpx.AsyncClient(\n transport=httpx.MockTransport(app),\n auth=\"not a tuple, not a callable\", # type: ignore\n )\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n with pytest.raises(TypeError):\n await client.get(auth=\"not a tuple, not a callable\") # type: ignore\n\n with pytest.raises(TypeError):\n client.auth = \"not a tuple, not a callable\" # type: ignore"} {"repo":"httpx","file":"tests/client/test_auth.py","line":357,"symbol":"test_digest_auth_returns_no_auth_if_no_digest_header_in_response","kind":"function","lang":"python","code":"async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = App()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": None}\n assert len(response.history) == 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":370,"symbol":"test_digest_auth_returns_no_auth_if_alternate_auth_scheme","kind":"function","lang":"python","code":"def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n auth_header = \"Token ...\"\n app = App(auth_header=auth_header, status_code=401)\n\n client = httpx.Client(transport=httpx.MockTransport(app))\n response = client.get(url, auth=auth)\n\n assert response.status_code == 401\n assert response.json() == {\"auth\": None}\n assert len(response.history) == 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":385,"symbol":"test_digest_auth_200_response_including_digest_auth_header","kind":"function","lang":"python","code":"async def test_digest_auth_200_response_including_digest_auth_header() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n auth_header = 'Digest realm=\"realm@host.com\",qop=\"auth\",nonce=\"abc\",opaque=\"xyz\"'\n app = App(auth_header=auth_header, status_code=200)\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": None}\n assert len(response.history) == 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":400,"symbol":"test_digest_auth_401_response_without_digest_auth_header","kind":"function","lang":"python","code":"async def test_digest_auth_401_response_without_digest_auth_header() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = App(auth_header=\"\", status_code=401)\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 401\n assert response.json() == {\"auth\": None}\n assert len(response.history) == 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":427,"symbol":"test_digest_auth","kind":"function","lang":"python","code":"async def test_digest_auth(\n algorithm: str, expected_hash_length: int, expected_response_length: int\n) -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp(algorithm=algorithm)\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert len(response.history) == 1\n\n authorization = typing.cast(typing.Dict[str, typing.Any], response.json())[\"auth\"]\n scheme, _, fields = authorization.partition(\" \")\n assert scheme == \"Digest\"\n\n response_fields = [field.strip() for field in fields.split(\",\")]\n digest_data = dict(field.split(\"=\") for field in response_fields)\n\n assert digest_data[\"username\"] == '\"user\"'\n assert digest_data[\"realm\"] == '\"httpx@example.org\"'\n assert \"nonce\" in digest_data\n assert digest_data[\"uri\"] == '\"/\"'\n assert len(digest_data[\"response\"]) == expected_response_length + 2 # extra quotes\n assert len(digest_data[\"opaque\"]) == expected_hash_length + 2\n assert digest_data[\"algorithm\"] == algorithm\n assert digest_data[\"qop\"] == \"auth"} {"repo":"httpx","file":"tests/client/test_auth.py","line":460,"symbol":"test_digest_auth_no_specified_qop","kind":"function","lang":"python","code":"async def test_digest_auth_no_specified_qop() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp(qop=\"\")\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert len(response.history) == 1\n\n authorization = typing.cast(typing.Dict[str, typing.Any], response.json())[\"auth\"]\n scheme, _, fields = authorization.partition(\" \")\n assert scheme == \"Digest\"\n\n response_fields = [field.strip() for field in fields.split(\",\")]\n digest_data = dict(field.split(\"=\") for field in response_fields)\n\n assert \"qop\" not in digest_data\n assert \"nc\" not in digest_data\n assert \"cnonce\" not in digest_data\n assert digest_data[\"username\"] == '\"user\"'\n assert digest_data[\"realm\"] == '\"httpx@example.org\"'\n assert len(digest_data[\"nonce\"]) == 64 + 2 # extra quotes\n assert digest_data[\"uri\"] == '\"/\"'\n assert len(digest_data[\"response\"]) == 64 + 2\n assert len(digest_data[\"opaque\"]) == 64 + 2\n assert digest_data[\"algorithm\"] == \"SHA-256\""} {"repo":"httpx","file":"tests/client/test_auth.py","line":492,"symbol":"test_digest_auth_qop_including_spaces_and_auth_returns_auth","kind":"function","lang":"python","code":"async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp(qop=qop)\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_auth.py","line":505,"symbol":"test_digest_auth_qop_auth_int_not_implemented","kind":"function","lang":"python","code":"async def test_digest_auth_qop_auth_int_not_implemented() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp(qop=\"auth-int\")\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n with pytest.raises(NotImplementedError):\n await client.get(url, auth=auth)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":516,"symbol":"test_digest_auth_qop_must_be_auth_or_auth_int","kind":"function","lang":"python","code":"async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp(qop=\"not-auth\")\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n with pytest.raises(httpx.ProtocolError):\n await client.get(url, auth=auth)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":527,"symbol":"test_digest_auth_incorrect_credentials","kind":"function","lang":"python","code":"async def test_digest_auth_incorrect_credentials() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp(send_response_after_attempt=2)\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 401\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_auth.py","line":540,"symbol":"test_digest_auth_reuses_challenge","kind":"function","lang":"python","code":"async def test_digest_auth_reuses_challenge() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response_1 = await client.get(url, auth=auth)\n response_2 = await client.get(url, auth=auth)\n\n assert response_1.status_code == 200\n assert response_2.status_code == 200\n\n assert len(response_1.history) == 1\n assert len(response_2.history) == 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":557,"symbol":"test_digest_auth_resets_nonce_count_after_401","kind":"function","lang":"python","code":"async def test_digest_auth_resets_nonce_count_after_401() -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response_1 = await client.get(url, auth=auth)\n assert response_1.status_code == 200\n assert len(response_1.history) == 1\n\n first_nonce = parse_keqv_list(\n response_1.request.headers[\"Authorization\"].split(\", \")\n )[\"nonce\"]\n first_nc = parse_keqv_list(\n response_1.request.headers[\"Authorization\"].split(\", \")\n )[\"nc\"]\n\n # with this we now force a 401 on a subsequent (but initial) request\n app.send_response_after_attempt = 2\n\n # we expect the client again to try to authenticate,\n # i.e. the history length must be 1\n response_2 = await client.get(url, auth=auth)\n assert response_2.status_code == 200\n assert len(response_2.history) == 1\n\n second_nonce = parse_keqv_list(\n response_2.request.headers[\"Authorization\"].split(\", \")\n )[\"nonce\"]\n second_nc = parse_keqv_list(\n "} {"repo":"httpx","file":"tests/client/test_auth.py","line":604,"symbol":"test_async_digest_auth_raises_protocol_error_on_malformed_header","kind":"function","lang":"python","code":"async def test_async_digest_auth_raises_protocol_error_on_malformed_header(\n auth_header: str,\n) -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = App(auth_header=auth_header, status_code=401)\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n with pytest.raises(httpx.ProtocolError):\n await client.get(url, auth=auth)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":623,"symbol":"test_sync_digest_auth_raises_protocol_error_on_malformed_header","kind":"function","lang":"python","code":"def test_sync_digest_auth_raises_protocol_error_on_malformed_header(\n auth_header: str,\n) -> None:\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = App(auth_header=auth_header, status_code=401)\n\n with httpx.Client(transport=httpx.MockTransport(app)) as client:\n with pytest.raises(httpx.ProtocolError):\n client.get(url, auth=auth)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":636,"symbol":"test_async_auth_history","kind":"function","lang":"python","code":"async def test_async_auth_history() -> None:\n \"\"\"\n Test that intermediate requests sent as part of an authentication flow\n are recorded in the response history.\n \"\"\"\n url = \"https://example.org/\"\n auth = RepeatAuth(repeat=2)\n app = App(auth_header=\"abc\")\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Repeat abc.abc\"}\n\n assert len(response.history) == 2\n resp1, resp2 = response.history\n assert resp1.json() == {\"auth\": \"Repeat 0\"}\n assert resp2.json() == {\"auth\": \"Repeat 1\"}\n\n assert len(resp2.history) == 1\n assert resp2.history == [resp1]\n\n assert len(resp1.history) == 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":662,"symbol":"test_sync_auth_history","kind":"function","lang":"python","code":"def test_sync_auth_history() -> None:\n \"\"\"\n Test that intermediate requests sent as part of an authentication flow\n are recorded in the response history.\n \"\"\"\n url = \"https://example.org/\"\n auth = RepeatAuth(repeat=2)\n app = App(auth_header=\"abc\")\n\n with httpx.Client(transport=httpx.MockTransport(app)) as client:\n response = client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"Repeat abc.abc\"}\n\n assert len(response.history) == 2\n resp1, resp2 = response.history\n assert resp1.json() == {\"auth\": \"Repeat 0\"}\n assert resp2.json() == {\"auth\": \"Repeat 1\"}\n\n assert len(resp2.history) == 1\n assert resp2.history == [resp1]\n\n assert len(resp1.history) == 0"} {"repo":"httpx","file":"tests/client/test_auth.py","line":688,"symbol":"ConsumeBodyTransport","kind":"class","lang":"python","code":"class ConsumeBodyTransport(httpx.MockTransport):\n async def handle_async_request(self, request: httpx.Request) -> httpx.Response:\n assert isinstance(request.stream, httpx.AsyncByteStream)\n [_ async for _ in request.stream]\n return self.handler(request) # type: ignore[return-value]"} {"repo":"httpx","file":"tests/client/test_auth.py","line":689,"symbol":"handle_async_request","kind":"function","lang":"python","code":"async def handle_async_request(self, request: httpx.Request) -> httpx.Response:\n assert isinstance(request.stream, httpx.AsyncByteStream)\n [_ async for _ in request.stream]\n return self.handler(request) # type: ignore[return-value]"} {"repo":"httpx","file":"tests/client/test_auth.py","line":696,"symbol":"test_digest_auth_unavailable_streaming_body","kind":"function","lang":"python","code":"async def test_digest_auth_unavailable_streaming_body():\n url = \"https://example.org/\"\n auth = httpx.DigestAuth(username=\"user\", password=\"password123\")\n app = DigestApp()\n\n async def streaming_body() -> typing.AsyncIterator[bytes]:\n yield b\"Example request body\" # pragma: no cover\n\n async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:\n with pytest.raises(httpx.StreamConsumed):\n await client.post(url, content=streaming_body(), auth=auth)"} {"repo":"httpx","file":"tests/client/test_auth.py","line":701,"symbol":"streaming_body","kind":"function","lang":"python","code":"async def streaming_body() -> typing.AsyncIterator[bytes]:\n yield b\"Example request body\" # pragma: no cover"} {"repo":"httpx","file":"tests/client/test_auth.py","line":710,"symbol":"test_async_auth_reads_response_body","kind":"function","lang":"python","code":"async def test_async_auth_reads_response_body() -> None:\n \"\"\"\n Test that we can read the response body in an auth flow if `requires_response_body`\n is set.\n \"\"\"\n url = \"https://example.org/\"\n auth = ResponseBodyAuth(\"xyz\")\n app = App()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": '{\"auth\":\"xyz\"}'}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":726,"symbol":"test_sync_auth_reads_response_body","kind":"function","lang":"python","code":"def test_sync_auth_reads_response_body() -> None:\n \"\"\"\n Test that we can read the response body in an auth flow if `requires_response_body`\n is set.\n \"\"\"\n url = \"https://example.org/\"\n auth = ResponseBodyAuth(\"xyz\")\n app = App()\n\n with httpx.Client(transport=httpx.MockTransport(app)) as client:\n response = client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": '{\"auth\":\"xyz\"}'}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":743,"symbol":"test_async_auth","kind":"function","lang":"python","code":"async def test_async_auth() -> None:\n \"\"\"\n Test that we can use an auth implementation specific to the async case, to\n support cases that require performing I/O or using concurrency primitives (such\n as checking a disk-based cache or fetching a token from a remote auth server).\n \"\"\"\n url = \"https://example.org/\"\n auth = SyncOrAsyncAuth()\n app = App()\n\n async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:\n response = await client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"async-auth\"}"} {"repo":"httpx","file":"tests/client/test_auth.py","line":760,"symbol":"test_sync_auth","kind":"function","lang":"python","code":"def test_sync_auth() -> None:\n \"\"\"\n Test that we can use an auth implementation specific to the sync case.\n \"\"\"\n url = \"https://example.org/\"\n auth = SyncOrAsyncAuth()\n app = App()\n\n with httpx.Client(transport=httpx.MockTransport(app)) as client:\n response = client.get(url, auth=auth)\n\n assert response.status_code == 200\n assert response.json() == {\"auth\": \"sync-auth\"}"} {"repo":"httpx","file":"tests/client/test_client.py","line":12,"symbol":"autodetect","kind":"function","lang":"python","code":"def autodetect(content):\n return chardet.detect(content).get(\"encoding\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":16,"symbol":"test_get","kind":"function","lang":"python","code":"def test_get(server):\n url = server.url\n with httpx.Client(http2=True) as http:\n response = http.get(url)\n assert response.status_code == 200\n assert response.url == url\n assert response.content == b\"Hello, world!\"\n assert response.text == \"Hello, world!\"\n assert response.http_version == \"HTTP/1.1\"\n assert response.encoding == \"utf-8\"\n assert response.request.url == url\n assert response.headers\n assert response.is_redirect is False\n assert repr(response) == \"\"\n assert response.elapsed > timedelta(0)"} {"repo":"httpx","file":"tests/client/test_client.py","line":41,"symbol":"test_get_invalid_url","kind":"function","lang":"python","code":"def test_get_invalid_url(server, url):\n with httpx.Client() as client:\n with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):\n client.get(url)"} {"repo":"httpx","file":"tests/client/test_client.py","line":47,"symbol":"test_build_request","kind":"function","lang":"python","code":"def test_build_request(server):\n url = server.url.copy_with(path=\"/echo_headers\")\n headers = {\"Custom-header\": \"value\"}\n\n with httpx.Client() as client:\n request = client.build_request(\"GET\", url)\n request.headers.update(headers)\n response = client.send(request)\n\n assert response.status_code == 200\n assert response.url == url\n\n assert response.json()[\"Custom-header\"] == \"value\""} {"repo":"httpx","file":"tests/client/test_client.py","line":62,"symbol":"test_build_post_request","kind":"function","lang":"python","code":"def test_build_post_request(server):\n url = server.url.copy_with(path=\"/echo_headers\")\n headers = {\"Custom-header\": \"value\"}\n\n with httpx.Client() as client:\n request = client.build_request(\"POST\", url)\n request.headers.update(headers)\n response = client.send(request)\n\n assert response.status_code == 200\n assert response.url == url\n\n assert response.json()[\"Content-length\"] == \"0\"\n assert response.json()[\"Custom-header\"] == \"value\""} {"repo":"httpx","file":"tests/client/test_client.py","line":78,"symbol":"test_post","kind":"function","lang":"python","code":"def test_post(server):\n with httpx.Client() as client:\n response = client.post(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/client/test_client.py","line":85,"symbol":"test_post_json","kind":"function","lang":"python","code":"def test_post_json(server):\n with httpx.Client() as client:\n response = client.post(server.url, json={\"text\": \"Hello, world!\"})\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/client/test_client.py","line":92,"symbol":"test_stream_response","kind":"function","lang":"python","code":"def test_stream_response(server):\n with httpx.Client() as client:\n with client.stream(\"GET\", server.url) as response:\n content = response.read()\n assert response.status_code == 200\n assert content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/client/test_client.py","line":100,"symbol":"test_stream_iterator","kind":"function","lang":"python","code":"def test_stream_iterator(server):\n body = b\"\"\n\n with httpx.Client() as client:\n with client.stream(\"GET\", server.url) as response:\n for chunk in response.iter_bytes():\n body += chunk\n\n assert response.status_code == 200\n assert body == b\"Hello, world!\""} {"repo":"httpx","file":"tests/client/test_client.py","line":112,"symbol":"test_raw_iterator","kind":"function","lang":"python","code":"def test_raw_iterator(server):\n body = b\"\"\n\n with httpx.Client() as client:\n with client.stream(\"GET\", server.url) as response:\n for chunk in response.iter_raw():\n body += chunk\n\n assert response.status_code == 200\n assert body == b\"Hello, world!\""} {"repo":"httpx","file":"tests/client/test_client.py","line":124,"symbol":"test_cannot_stream_async_request","kind":"function","lang":"python","code":"def test_cannot_stream_async_request(server):\n async def hello_world() -> typing.AsyncIterator[bytes]: # pragma: no cover\n yield b\"Hello, \"\n yield b\"world!\"\n\n with httpx.Client() as client:\n with pytest.raises(RuntimeError):\n client.post(server.url, content=hello_world())"} {"repo":"httpx","file":"tests/client/test_client.py","line":125,"symbol":"hello_world","kind":"function","lang":"python","code":"async def hello_world() -> typing.AsyncIterator[bytes]: # pragma: no cover\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/client/test_client.py","line":134,"symbol":"test_raise_for_status","kind":"function","lang":"python","code":"def test_raise_for_status(server):\n with httpx.Client() as client:\n for status_code in (200, 400, 404, 500, 505):\n response = client.request(\n \"GET\", server.url.copy_with(path=f\"/status/{status_code}\")\n )\n if 400 <= status_code < 600:\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert exc_info.value.response == response\n assert exc_info.value.request.url.path == f\"/status/{status_code}\"\n else:\n assert response.raise_for_status() is response"} {"repo":"httpx","file":"tests/client/test_client.py","line":149,"symbol":"test_options","kind":"function","lang":"python","code":"def test_options(server):\n with httpx.Client() as client:\n response = client.options(server.url)\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/client/test_client.py","line":156,"symbol":"test_head","kind":"function","lang":"python","code":"def test_head(server):\n with httpx.Client() as client:\n response = client.head(server.url)\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/client/test_client.py","line":163,"symbol":"test_put","kind":"function","lang":"python","code":"def test_put(server):\n with httpx.Client() as client:\n response = client.put(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/client/test_client.py","line":170,"symbol":"test_patch","kind":"function","lang":"python","code":"def test_patch(server):\n with httpx.Client() as client:\n response = client.patch(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/client/test_client.py","line":177,"symbol":"test_delete","kind":"function","lang":"python","code":"def test_delete(server):\n with httpx.Client() as client:\n response = client.delete(server.url)\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/client/test_client.py","line":184,"symbol":"test_base_url","kind":"function","lang":"python","code":"def test_base_url(server):\n base_url = server.url\n with httpx.Client(base_url=base_url) as client:\n response = client.get(\"/\")\n assert response.status_code == 200\n assert response.url == base_url"} {"repo":"httpx","file":"tests/client/test_client.py","line":192,"symbol":"test_merge_absolute_url","kind":"function","lang":"python","code":"def test_merge_absolute_url():\n client = httpx.Client(base_url=\"https://www.example.com/\")\n request = client.build_request(\"GET\", \"http://www.example.com/\")\n assert request.url == \"http://www.example.com/\""} {"repo":"httpx","file":"tests/client/test_client.py","line":198,"symbol":"test_merge_relative_url","kind":"function","lang":"python","code":"def test_merge_relative_url():\n client = httpx.Client(base_url=\"https://www.example.com/\")\n request = client.build_request(\"GET\", \"/testing/123\")\n assert request.url == \"https://www.example.com/testing/123\""} {"repo":"httpx","file":"tests/client/test_client.py","line":204,"symbol":"test_merge_relative_url_with_path","kind":"function","lang":"python","code":"def test_merge_relative_url_with_path():\n client = httpx.Client(base_url=\"https://www.example.com/some/path\")\n request = client.build_request(\"GET\", \"/testing/123\")\n assert request.url == \"https://www.example.com/some/path/testing/123\""} {"repo":"httpx","file":"tests/client/test_client.py","line":210,"symbol":"test_merge_relative_url_with_dotted_path","kind":"function","lang":"python","code":"def test_merge_relative_url_with_dotted_path():\n client = httpx.Client(base_url=\"https://www.example.com/some/path\")\n request = client.build_request(\"GET\", \"../testing/123\")\n assert request.url == \"https://www.example.com/some/testing/123\""} {"repo":"httpx","file":"tests/client/test_client.py","line":216,"symbol":"test_merge_relative_url_with_path_including_colon","kind":"function","lang":"python","code":"def test_merge_relative_url_with_path_including_colon():\n client = httpx.Client(base_url=\"https://www.example.com/some/path\")\n request = client.build_request(\"GET\", \"/testing:123\")\n assert request.url == \"https://www.example.com/some/path/testing:123\""} {"repo":"httpx","file":"tests/client/test_client.py","line":222,"symbol":"test_merge_relative_url_with_encoded_slashes","kind":"function","lang":"python","code":"def test_merge_relative_url_with_encoded_slashes():\n client = httpx.Client(base_url=\"https://www.example.com/\")\n request = client.build_request(\"GET\", \"/testing%2F123\")\n assert request.url == \"https://www.example.com/testing%2F123\"\n\n client = httpx.Client(base_url=\"https://www.example.com/base%2Fpath\")\n request = client.build_request(\"GET\", \"/testing\")\n assert request.url == \"https://www.example.com/base%2Fpath/testing\""} {"repo":"httpx","file":"tests/client/test_client.py","line":232,"symbol":"test_context_managed_transport","kind":"function","lang":"python","code":"def test_context_managed_transport():\n class Transport(httpx.BaseTransport):\n def __init__(self) -> None:\n self.events: list[str] = []\n\n def close(self):\n # The base implementation of httpx.BaseTransport just\n # calls into `.close`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__enter__`/`__exit__`.\n self.events.append(\"transport.close\")\n\n def __enter__(self):\n super().__enter__()\n self.events.append(\"transport.__enter__\")\n\n def __exit__(self, *args):\n super().__exit__(*args)\n self.events.append(\"transport.__exit__\")\n\n transport = Transport()\n with httpx.Client(transport=transport):\n pass\n\n assert transport.events == [\n \"transport.__enter__\",\n \"transport.close\",\n \"transport.__exit__\",\n ]"} {"repo":"httpx","file":"tests/client/test_client.py","line":233,"symbol":"Transport","kind":"class","lang":"python","code":"class Transport(httpx.BaseTransport):\n def __init__(self) -> None:\n self.events: list[str] = []\n\n def close(self):\n # The base implementation of httpx.BaseTransport just\n # calls into `.close`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__enter__`/`__exit__`.\n self.events.append(\"transport.close\")\n\n def __enter__(self):\n super().__enter__()\n self.events.append(\"transport.__enter__\")\n\n def __exit__(self, *args):\n super().__exit__(*args)\n self.events.append(\"transport.__exit__\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":234,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self.events: list[str] = []"} {"repo":"httpx","file":"tests/client/test_client.py","line":237,"symbol":"close","kind":"function","lang":"python","code":"def close(self):\n # The base implementation of httpx.BaseTransport just\n # calls into `.close`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__enter__`/`__exit__`.\n self.events.append(\"transport.close\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":244,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self):\n super().__enter__()\n self.events.append(\"transport.__enter__\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":248,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(self, *args):\n super().__exit__(*args)\n self.events.append(\"transport.__exit__\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":263,"symbol":"test_context_managed_transport_and_mount","kind":"function","lang":"python","code":"def test_context_managed_transport_and_mount():\n class Transport(httpx.BaseTransport):\n def __init__(self, name: str) -> None:\n self.name: str = name\n self.events: list[str] = []\n\n def close(self):\n # The base implementation of httpx.BaseTransport just\n # calls into `.close`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__enter__`/`__exit__`.\n self.events.append(f\"{self.name}.close\")\n\n def __enter__(self):\n super().__enter__()\n self.events.append(f\"{self.name}.__enter__\")\n\n def __exit__(self, *args):\n super().__exit__(*args)\n self.events.append(f\"{self.name}.__exit__\")\n\n transport = Transport(name=\"transport\")\n mounted = Transport(name=\"mounted\")\n with httpx.Client(transport=transport, mounts={\"http://www.example.org\": mounted}):\n pass\n\n assert transport.events == [\n \"transport.__enter__\",\n \"transport.close\",\n \"transport.__exit__\",\n ]\n assert mounted.events == [\n \"mounted.__enter__\",\n "} {"repo":"httpx","file":"tests/client/test_client.py","line":264,"symbol":"Transport","kind":"class","lang":"python","code":"class Transport(httpx.BaseTransport):\n def __init__(self, name: str) -> None:\n self.name: str = name\n self.events: list[str] = []\n\n def close(self):\n # The base implementation of httpx.BaseTransport just\n # calls into `.close`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__enter__`/`__exit__`.\n self.events.append(f\"{self.name}.close\")\n\n def __enter__(self):\n super().__enter__()\n self.events.append(f\"{self.name}.__enter__\")\n\n def __exit__(self, *args):\n super().__exit__(*args)\n self.events.append(f\"{self.name}.__exit__\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":265,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, name: str) -> None:\n self.name: str = name\n self.events: list[str] = []"} {"repo":"httpx","file":"tests/client/test_client.py","line":269,"symbol":"close","kind":"function","lang":"python","code":"def close(self):\n # The base implementation of httpx.BaseTransport just\n # calls into `.close`, so simple transport cases can just override\n # this method for any cleanup, where more complex cases\n # might want to additionally override `__enter__`/`__exit__`.\n self.events.append(f\"{self.name}.close\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":276,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self):\n super().__enter__()\n self.events.append(f\"{self.name}.__enter__\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":280,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(self, *args):\n super().__exit__(*args)\n self.events.append(f\"{self.name}.__exit__\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":301,"symbol":"hello_world","kind":"function","lang":"python","code":"def hello_world(request):\n return httpx.Response(200, text=\"Hello, world!\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":305,"symbol":"test_client_closed_state_using_implicit_open","kind":"function","lang":"python","code":"def test_client_closed_state_using_implicit_open():\n client = httpx.Client(transport=httpx.MockTransport(hello_world))\n\n assert not client.is_closed\n client.get(\"http://example.com\")\n\n assert not client.is_closed\n client.close()\n\n assert client.is_closed\n\n # Once we're close we cannot make any more requests.\n with pytest.raises(RuntimeError):\n client.get(\"http://example.com\")\n\n # Once we're closed we cannot reopen the client.\n with pytest.raises(RuntimeError):\n with client:\n pass # pragma: no cover"} {"repo":"httpx","file":"tests/client/test_client.py","line":326,"symbol":"test_client_closed_state_using_with_block","kind":"function","lang":"python","code":"def test_client_closed_state_using_with_block():\n with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:\n assert not client.is_closed\n client.get(\"http://example.com\")\n\n assert client.is_closed\n with pytest.raises(RuntimeError):\n client.get(\"http://example.com\")"} {"repo":"httpx","file":"tests/client/test_client.py","line":336,"symbol":"echo_raw_headers","kind":"function","lang":"python","code":"def echo_raw_headers(request: httpx.Request) -> httpx.Response:\n data = [\n (name.decode(\"ascii\"), value.decode(\"ascii\"))\n for name, value in request.headers.raw\n ]\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_client.py","line":344,"symbol":"test_raw_client_header","kind":"function","lang":"python","code":"def test_raw_client_header():\n \"\"\"\n Set a header in the Client.\n \"\"\"\n url = \"http://example.org/echo_headers\"\n headers = {\"Example-Header\": \"example-value\"}\n\n client = httpx.Client(\n transport=httpx.MockTransport(echo_raw_headers), headers=headers\n )\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == [\n [\"Host\", \"example.org\"],\n [\"Accept\", \"*/*\"],\n [\"Accept-Encoding\", \"gzip, deflate, br, zstd\"],\n [\"Connection\", \"keep-alive\"],\n [\"User-Agent\", f\"python-httpx/{httpx.__version__}\"],\n [\"Example-Header\", \"example-value\"],\n ]"} {"repo":"httpx","file":"tests/client/test_client.py","line":367,"symbol":"unmounted","kind":"function","lang":"python","code":"def unmounted(request: httpx.Request) -> httpx.Response:\n data = {\"app\": \"unmounted\"}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_client.py","line":372,"symbol":"mounted","kind":"function","lang":"python","code":"def mounted(request: httpx.Request) -> httpx.Response:\n data = {\"app\": \"mounted\"}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_client.py","line":377,"symbol":"test_mounted_transport","kind":"function","lang":"python","code":"def test_mounted_transport():\n transport = httpx.MockTransport(unmounted)\n mounts = {\"custom://\": httpx.MockTransport(mounted)}\n\n client = httpx.Client(transport=transport, mounts=mounts)\n\n response = client.get(\"https://www.example.com\")\n assert response.status_code == 200\n assert response.json() == {\"app\": \"unmounted\"}\n\n response = client.get(\"custom://www.example.com\")\n assert response.status_code == 200\n assert response.json() == {\"app\": \"mounted\"}"} {"repo":"httpx","file":"tests/client/test_client.py","line":392,"symbol":"test_all_mounted_transport","kind":"function","lang":"python","code":"def test_all_mounted_transport():\n mounts = {\"all://\": httpx.MockTransport(mounted)}\n\n client = httpx.Client(mounts=mounts)\n\n response = client.get(\"https://www.example.com\")\n assert response.status_code == 200\n assert response.json() == {\"app\": \"mounted\"}"} {"repo":"httpx","file":"tests/client/test_client.py","line":402,"symbol":"test_server_extensions","kind":"function","lang":"python","code":"def test_server_extensions(server):\n url = server.url.copy_with(path=\"/http_version_2\")\n with httpx.Client(http2=True) as client:\n response = client.get(url)\n assert response.status_code == 200\n assert response.extensions[\"http_version\"] == b\"HTTP/1.1\""} {"repo":"httpx","file":"tests/client/test_client.py","line":410,"symbol":"test_client_decode_text_using_autodetect","kind":"function","lang":"python","code":"def test_client_decode_text_using_autodetect():\n # Ensure that a 'default_encoding=autodetect' on the response allows for\n # encoding autodetection to be used when no \"Content-Type: text/plain; charset=...\"\n # info is present.\n #\n # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.\n text = (\n \"Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains \"\n \"que la France a produits, sans excepter Voltaire lui-même, imprégné de \"\n \"l'esprit anglais par son séjour à Londres, c'est incontestablement \"\n \"Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la \"\n \"plus complète le fond du génie français.\"\n )\n\n def cp1252_but_no_content_type(request):\n content = text.encode(\"ISO-8859-1\")\n return httpx.Response(200, content=content)\n\n transport = httpx.MockTransport(cp1252_but_no_content_type)\n with httpx.Client(transport=transport, default_encoding=autodetect) as client:\n response = client.get(\"http://www.example.com\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.encoding == \"ISO-8859-1\""} {"repo":"httpx","file":"tests/client/test_client.py","line":424,"symbol":"cp1252_but_no_content_type","kind":"function","lang":"python","code":"def cp1252_but_no_content_type(request):\n content = text.encode(\"ISO-8859-1\")\n return httpx.Response(200, content=content)"} {"repo":"httpx","file":"tests/client/test_client.py","line":438,"symbol":"test_client_decode_text_using_explicit_encoding","kind":"function","lang":"python","code":"def test_client_decode_text_using_explicit_encoding():\n # Ensure that a 'default_encoding=\"...\"' on the response is used for text decoding\n # when no \"Content-Type: text/plain; charset=...\"\" info is present.\n #\n # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.\n text = (\n \"Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains \"\n \"que la France a produits, sans excepter Voltaire lui-même, imprégné de \"\n \"l'esprit anglais par son séjour à Londres, c'est incontestablement \"\n \"Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la \"\n \"plus complète le fond du génie français.\"\n )\n\n def cp1252_but_no_content_type(request):\n content = text.encode(\"ISO-8859-1\")\n return httpx.Response(200, content=content)\n\n transport = httpx.MockTransport(cp1252_but_no_content_type)\n with httpx.Client(transport=transport, default_encoding=autodetect) as client:\n response = client.get(\"http://www.example.com\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.encoding == \"ISO-8859-1\"\n assert respon"} {"repo":"httpx","file":"tests/client/test_client.py","line":451,"symbol":"cp1252_but_no_content_type","kind":"function","lang":"python","code":"def cp1252_but_no_content_type(request):\n content = text.encode(\"ISO-8859-1\")\n return httpx.Response(200, content=content)"} {"repo":"httpx","file":"tests/client/test_cookies.py","line":8,"symbol":"get_and_set_cookies","kind":"function","lang":"python","code":"def get_and_set_cookies(request: httpx.Request) -> httpx.Response:\n if request.url.path == \"/echo_cookies\":\n data = {\"cookies\": request.headers.get(\"cookie\")}\n return httpx.Response(200, json=data)\n elif request.url.path == \"/set_cookie\":\n return httpx.Response(200, headers={\"set-cookie\": \"example-name=example-value\"})\n else:\n raise NotImplementedError() # pragma: no cover"} {"repo":"httpx","file":"tests/client/test_cookies.py","line":18,"symbol":"test_set_cookie","kind":"function","lang":"python","code":"def test_set_cookie() -> None:\n \"\"\"\n Send a request including a cookie.\n \"\"\"\n url = \"http://example.org/echo_cookies\"\n cookies = {\"example-name\": \"example-value\"}\n\n client = httpx.Client(\n cookies=cookies, transport=httpx.MockTransport(get_and_set_cookies)\n )\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"cookies\": \"example-name=example-value\"}"} {"repo":"httpx","file":"tests/client/test_cookies.py","line":34,"symbol":"test_set_per_request_cookie_is_deprecated","kind":"function","lang":"python","code":"def test_set_per_request_cookie_is_deprecated() -> None:\n \"\"\"\n Sending a request including a per-request cookie is deprecated.\n \"\"\"\n url = \"http://example.org/echo_cookies\"\n cookies = {\"example-name\": \"example-value\"}\n\n client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))\n with pytest.warns(DeprecationWarning):\n response = client.get(url, cookies=cookies)\n\n assert response.status_code == 200\n assert response.json() == {\"cookies\": \"example-name=example-value\"}"} {"repo":"httpx","file":"tests/client/test_cookies.py","line":49,"symbol":"test_set_cookie_with_cookiejar","kind":"function","lang":"python","code":"def test_set_cookie_with_cookiejar() -> None:\n \"\"\"\n Send a request including a cookie, using a `CookieJar` instance.\n \"\"\"\n\n url = \"http://example.org/echo_cookies\"\n cookies = CookieJar()\n cookie = Cookie(\n version=0,\n name=\"example-name\",\n value=\"example-value\",\n port=None,\n port_specified=False,\n domain=\"\",\n domain_specified=False,\n domain_initial_dot=False,\n path=\"/\",\n path_specified=True,\n secure=False,\n expires=None,\n discard=True,\n comment=None,\n comment_url=None,\n rest={\"HttpOnly\": \"\"},\n rfc2109=False,\n )\n cookies.set_cookie(cookie)\n\n client = httpx.Client(\n cookies=cookies, transport=httpx.MockTransport(get_and_set_cookies)\n )\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"cookies\": \"example-name=example-value\"}"} {"repo":"httpx","file":"tests/client/test_cookies.py","line":86,"symbol":"test_setting_client_cookies_to_cookiejar","kind":"function","lang":"python","code":"def test_setting_client_cookies_to_cookiejar() -> None:\n \"\"\"\n Send a request including a cookie, using a `CookieJar` instance.\n \"\"\"\n\n url = \"http://example.org/echo_cookies\"\n cookies = CookieJar()\n cookie = Cookie(\n version=0,\n name=\"example-name\",\n value=\"example-value\",\n port=None,\n port_specified=False,\n domain=\"\",\n domain_specified=False,\n domain_initial_dot=False,\n path=\"/\",\n path_specified=True,\n secure=False,\n expires=None,\n discard=True,\n comment=None,\n comment_url=None,\n rest={\"HttpOnly\": \"\"},\n rfc2109=False,\n )\n cookies.set_cookie(cookie)\n\n client = httpx.Client(\n cookies=cookies, transport=httpx.MockTransport(get_and_set_cookies)\n )\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"cookies\": \"example-name=example-value\"}"} {"repo":"httpx","file":"tests/client/test_cookies.py","line":123,"symbol":"test_set_cookie_with_cookies_model","kind":"function","lang":"python","code":"def test_set_cookie_with_cookies_model() -> None:\n \"\"\"\n Send a request including a cookie, using a `Cookies` instance.\n \"\"\"\n\n url = \"http://example.org/echo_cookies\"\n cookies = httpx.Cookies()\n cookies[\"example-name\"] = \"example-value\"\n\n client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))\n client.cookies = cookies\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"cookies\": \"example-name=example-value\"}"} {"repo":"httpx","file":"tests/client/test_cookies.py","line":140,"symbol":"test_get_cookie","kind":"function","lang":"python","code":"def test_get_cookie() -> None:\n url = \"http://example.org/set_cookie\"\n\n client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.cookies[\"example-name\"] == \"example-value\"\n assert client.cookies[\"example-name\"] == \"example-value\""} {"repo":"httpx","file":"tests/client/test_cookies.py","line":151,"symbol":"test_cookie_persistence","kind":"function","lang":"python","code":"def test_cookie_persistence() -> None:\n \"\"\"\n Ensure that Client instances persist cookies between requests.\n \"\"\"\n client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))\n\n response = client.get(\"http://example.org/echo_cookies\")\n assert response.status_code == 200\n assert response.json() == {\"cookies\": None}\n\n response = client.get(\"http://example.org/set_cookie\")\n assert response.status_code == 200\n assert response.cookies[\"example-name\"] == \"example-value\"\n assert client.cookies[\"example-name\"] == \"example-value\"\n\n response = client.get(\"http://example.org/echo_cookies\")\n assert response.status_code == 200\n assert response.json() == {\"cookies\": \"example-name=example-value\"}"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":6,"symbol":"app","kind":"function","lang":"python","code":"def app(request: httpx.Request) -> httpx.Response:\n if request.url.path == \"/redirect\":\n return httpx.Response(303, headers={\"server\": \"testserver\", \"location\": \"/\"})\n elif request.url.path.startswith(\"/status/\"):\n status_code = int(request.url.path[-3:])\n return httpx.Response(status_code, headers={\"server\": \"testserver\"})\n\n return httpx.Response(200, headers={\"server\": \"testserver\"})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":16,"symbol":"test_event_hooks","kind":"function","lang":"python","code":"def test_event_hooks():\n events = []\n\n def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})\n\n def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})\n\n event_hooks = {\"request\": [on_request], \"response\": [on_response]}\n\n with httpx.Client(\n event_hooks=event_hooks, transport=httpx.MockTransport(app)\n ) as http:\n http.get(\"http://127.0.0.1:8000/\", auth=(\"username\", \"password\"))\n\n assert events == [\n {\n \"event\": \"request\",\n \"headers\": {\n \"host\": \"127.0.0.1:8000\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n },\n },\n {\n \"event\": \"response\",\n \"headers\": {\"server\": \"testserver\"},\n },\n ]"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":19,"symbol":"on_request","kind":"function","lang":"python","code":"def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":22,"symbol":"on_response","kind":"function","lang":"python","code":"def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":51,"symbol":"test_event_hooks_raising_exception","kind":"function","lang":"python","code":"def test_event_hooks_raising_exception(server):\n def raise_on_4xx_5xx(response):\n response.raise_for_status()\n\n event_hooks = {\"response\": [raise_on_4xx_5xx]}\n\n with httpx.Client(\n event_hooks=event_hooks, transport=httpx.MockTransport(app)\n ) as http:\n try:\n http.get(\"http://127.0.0.1:8000/status/400\")\n except httpx.HTTPStatusError as exc:\n assert exc.response.is_closed"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":52,"symbol":"raise_on_4xx_5xx","kind":"function","lang":"python","code":"def raise_on_4xx_5xx(response):\n response.raise_for_status()"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":67,"symbol":"test_async_event_hooks","kind":"function","lang":"python","code":"async def test_async_event_hooks():\n events = []\n\n async def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})\n\n async def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})\n\n event_hooks = {\"request\": [on_request], \"response\": [on_response]}\n\n async with httpx.AsyncClient(\n event_hooks=event_hooks, transport=httpx.MockTransport(app)\n ) as http:\n await http.get(\"http://127.0.0.1:8000/\", auth=(\"username\", \"password\"))\n\n assert events == [\n {\n \"event\": \"request\",\n \"headers\": {\n \"host\": \"127.0.0.1:8000\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n },\n },\n {\n \"event\": \"response\",\n \"headers\": {\"server\": \"testserver\"},\n },\n ]"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":70,"symbol":"on_request","kind":"function","lang":"python","code":"async def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":73,"symbol":"on_response","kind":"function","lang":"python","code":"async def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":103,"symbol":"test_async_event_hooks_raising_exception","kind":"function","lang":"python","code":"async def test_async_event_hooks_raising_exception():\n async def raise_on_4xx_5xx(response):\n response.raise_for_status()\n\n event_hooks = {\"response\": [raise_on_4xx_5xx]}\n\n async with httpx.AsyncClient(\n event_hooks=event_hooks, transport=httpx.MockTransport(app)\n ) as http:\n try:\n await http.get(\"http://127.0.0.1:8000/status/400\")\n except httpx.HTTPStatusError as exc:\n assert exc.response.is_closed"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":104,"symbol":"raise_on_4xx_5xx","kind":"function","lang":"python","code":"async def raise_on_4xx_5xx(response):\n response.raise_for_status()"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":118,"symbol":"test_event_hooks_with_redirect","kind":"function","lang":"python","code":"def test_event_hooks_with_redirect():\n \"\"\"\n A redirect request should trigger additional 'request' and 'response' event hooks.\n \"\"\"\n\n events = []\n\n def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})\n\n def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})\n\n event_hooks = {\"request\": [on_request], \"response\": [on_response]}\n\n with httpx.Client(\n event_hooks=event_hooks,\n transport=httpx.MockTransport(app),\n follow_redirects=True,\n ) as http:\n http.get(\"http://127.0.0.1:8000/redirect\", auth=(\"username\", \"password\"))\n\n assert events == [\n {\n \"event\": \"request\",\n \"headers\": {\n \"host\": \"127.0.0.1:8000\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n },\n },\n {\n \"event\": \"response\",\n \"headers\": {\"location\": \"/\", \"serv"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":125,"symbol":"on_request","kind":"function","lang":"python","code":"def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":128,"symbol":"on_response","kind":"function","lang":"python","code":"def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":175,"symbol":"test_async_event_hooks_with_redirect","kind":"function","lang":"python","code":"async def test_async_event_hooks_with_redirect():\n \"\"\"\n A redirect request should trigger additional 'request' and 'response' event hooks.\n \"\"\"\n\n events = []\n\n async def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})\n\n async def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})\n\n event_hooks = {\"request\": [on_request], \"response\": [on_response]}\n\n async with httpx.AsyncClient(\n event_hooks=event_hooks,\n transport=httpx.MockTransport(app),\n follow_redirects=True,\n ) as http:\n await http.get(\"http://127.0.0.1:8000/redirect\", auth=(\"username\", \"password\"))\n\n assert events == [\n {\n \"event\": \"request\",\n \"headers\": {\n \"host\": \"127.0.0.1:8000\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n },\n },\n {\n \"event\": \"response\",\n "} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":182,"symbol":"on_request","kind":"function","lang":"python","code":"async def on_request(request):\n events.append({\"event\": \"request\", \"headers\": dict(request.headers)})"} {"repo":"httpx","file":"tests/client/test_event_hooks.py","line":185,"symbol":"on_response","kind":"function","lang":"python","code":"async def on_response(response):\n events.append({\"event\": \"response\", \"headers\": dict(response.headers)})"} {"repo":"httpx","file":"tests/client/test_headers.py","line":8,"symbol":"echo_headers","kind":"function","lang":"python","code":"def echo_headers(request: httpx.Request) -> httpx.Response:\n data = {\"headers\": dict(request.headers)}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_headers.py","line":13,"symbol":"echo_repeated_headers_multi_items","kind":"function","lang":"python","code":"def echo_repeated_headers_multi_items(request: httpx.Request) -> httpx.Response:\n data = {\"headers\": list(request.headers.multi_items())}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_headers.py","line":18,"symbol":"echo_repeated_headers_items","kind":"function","lang":"python","code":"def echo_repeated_headers_items(request: httpx.Request) -> httpx.Response:\n data = {\"headers\": list(request.headers.items())}\n return httpx.Response(200, json=data)"} {"repo":"httpx","file":"tests/client/test_headers.py","line":23,"symbol":"test_client_header","kind":"function","lang":"python","code":"def test_client_header():\n \"\"\"\n Set a header in the Client.\n \"\"\"\n url = \"http://example.org/echo_headers\"\n headers = {\"Example-Header\": \"example-value\"}\n\n client = httpx.Client(transport=httpx.MockTransport(echo_headers), headers=headers)\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"example-header\": \"example-value\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n }\n }"} {"repo":"httpx","file":"tests/client/test_headers.py","line":46,"symbol":"test_header_merge","kind":"function","lang":"python","code":"def test_header_merge():\n url = \"http://example.org/echo_headers\"\n client_headers = {\"User-Agent\": \"python-myclient/0.2.1\"}\n request_headers = {\"X-Auth-Token\": \"FooBarBazToken\"}\n client = httpx.Client(\n transport=httpx.MockTransport(echo_headers), headers=client_headers\n )\n response = client.get(url, headers=request_headers)\n\n assert response.status_code == 200\n assert response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.org\",\n \"user-agent\": \"python-myclient/0.2.1\",\n \"x-auth-token\": \"FooBarBazToken\",\n }\n }"} {"repo":"httpx","file":"tests/client/test_headers.py","line":68,"symbol":"test_header_merge_conflicting_headers","kind":"function","lang":"python","code":"def test_header_merge_conflicting_headers():\n url = \"http://example.org/echo_headers\"\n client_headers = {\"X-Auth-Token\": \"FooBar\"}\n request_headers = {\"X-Auth-Token\": \"BazToken\"}\n client = httpx.Client(\n transport=httpx.MockTransport(echo_headers), headers=client_headers\n )\n response = client.get(url, headers=request_headers)\n\n assert response.status_code == 200\n assert response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n \"x-auth-token\": \"BazToken\",\n }\n }"} {"repo":"httpx","file":"tests/client/test_headers.py","line":90,"symbol":"test_header_update","kind":"function","lang":"python","code":"def test_header_update():\n url = \"http://example.org/echo_headers\"\n client = httpx.Client(transport=httpx.MockTransport(echo_headers))\n first_response = client.get(url)\n client.headers.update(\n {\"User-Agent\": \"python-myclient/0.2.1\", \"Another-Header\": \"AThing\"}\n )\n second_response = client.get(url)\n\n assert first_response.status_code == 200\n assert first_response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n }\n }\n\n assert second_response.status_code == 200\n assert second_response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"another-header\": \"AThing\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.org\",\n \"user-agent\": \"python-myclient/0.2.1\",\n }\n }"} {"repo":"httpx","file":"tests/client/test_headers.py","line":123,"symbol":"test_header_repeated_items","kind":"function","lang":"python","code":"def test_header_repeated_items():\n url = \"http://example.org/echo_headers\"\n client = httpx.Client(transport=httpx.MockTransport(echo_repeated_headers_items))\n response = client.get(url, headers=[(\"x-header\", \"1\"), (\"x-header\", \"2,3\")])\n\n assert response.status_code == 200\n\n echoed_headers = response.json()[\"headers\"]\n # as per RFC 7230, the whitespace after a comma is insignificant\n # so we split and strip here so that we can do a safe comparison\n assert [\"x-header\", [\"1\", \"2\", \"3\"]] in [\n [k, [subv.lstrip() for subv in v.split(\",\")]] for k, v in echoed_headers\n ]"} {"repo":"httpx","file":"tests/client/test_headers.py","line":138,"symbol":"test_header_repeated_multi_items","kind":"function","lang":"python","code":"def test_header_repeated_multi_items():\n url = \"http://example.org/echo_headers\"\n client = httpx.Client(\n transport=httpx.MockTransport(echo_repeated_headers_multi_items)\n )\n response = client.get(url, headers=[(\"x-header\", \"1\"), (\"x-header\", \"2,3\")])\n\n assert response.status_code == 200\n\n echoed_headers = response.json()[\"headers\"]\n assert [\"x-header\", \"1\"] in echoed_headers\n assert [\"x-header\", \"2,3\"] in echoed_headers"} {"repo":"httpx","file":"tests/client/test_headers.py","line":152,"symbol":"test_remove_default_header","kind":"function","lang":"python","code":"def test_remove_default_header():\n \"\"\"\n Remove a default header from the Client.\n \"\"\"\n url = \"http://example.org/echo_headers\"\n\n client = httpx.Client(transport=httpx.MockTransport(echo_headers))\n del client.headers[\"User-Agent\"]\n\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.org\",\n }\n }"} {"repo":"httpx","file":"tests/client/test_headers.py","line":174,"symbol":"test_header_does_not_exist","kind":"function","lang":"python","code":"def test_header_does_not_exist():\n headers = httpx.Headers({\"foo\": \"bar\"})\n with pytest.raises(KeyError):\n del headers[\"baz\"]"} {"repo":"httpx","file":"tests/client/test_headers.py","line":180,"symbol":"test_header_with_incorrect_value","kind":"function","lang":"python","code":"def test_header_with_incorrect_value():\n with pytest.raises(\n TypeError,\n match=f\"Header value must be str or bytes, not {type(None)}\",\n ):\n httpx.Headers({\"foo\": None}) # type: ignore"} {"repo":"httpx","file":"tests/client/test_headers.py","line":188,"symbol":"test_host_with_auth_and_port_in_url","kind":"function","lang":"python","code":"def test_host_with_auth_and_port_in_url():\n \"\"\"\n The Host header should only include the hostname, or hostname:port\n (for non-default ports only). Any userinfo or default port should not\n be present.\n \"\"\"\n url = \"http://username:password@example.org:80/echo_headers\"\n\n client = httpx.Client(transport=httpx.MockTransport(echo_headers))\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.org\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n }\n }"} {"repo":"httpx","file":"tests/client/test_headers.py","line":212,"symbol":"test_host_with_non_default_port_in_url","kind":"function","lang":"python","code":"def test_host_with_non_default_port_in_url():\n \"\"\"\n If the URL includes a non-default port, then it should be included in\n the Host header.\n \"\"\"\n url = \"http://username:password@example.org:123/echo_headers\"\n\n client = httpx.Client(transport=httpx.MockTransport(echo_headers))\n response = client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\n \"headers\": {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br, zstd\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.org:123\",\n \"user-agent\": f\"python-httpx/{httpx.__version__}\",\n \"authorization\": \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n }\n }"} {"repo":"httpx","file":"tests/client/test_headers.py","line":235,"symbol":"test_request_auto_headers","kind":"function","lang":"python","code":"def test_request_auto_headers():\n request = httpx.Request(\"GET\", \"https://www.example.org/\")\n assert \"host\" in request.headers"} {"repo":"httpx","file":"tests/client/test_headers.py","line":240,"symbol":"test_same_origin","kind":"function","lang":"python","code":"def test_same_origin():\n origin = httpx.URL(\"https://example.com\")\n request = httpx.Request(\"GET\", \"HTTPS://EXAMPLE.COM:443\")\n\n client = httpx.Client()\n headers = client._redirect_headers(request, origin, \"GET\")\n\n assert headers[\"Host\"] == request.url.netloc.decode(\"ascii\")"} {"repo":"httpx","file":"tests/client/test_headers.py","line":250,"symbol":"test_not_same_origin","kind":"function","lang":"python","code":"def test_not_same_origin():\n origin = httpx.URL(\"https://example.com\")\n request = httpx.Request(\"GET\", \"HTTP://EXAMPLE.COM:80\")\n\n client = httpx.Client()\n headers = client._redirect_headers(request, origin, \"GET\")\n\n assert headers[\"Host\"] == origin.netloc.decode(\"ascii\")"} {"repo":"httpx","file":"tests/client/test_headers.py","line":260,"symbol":"test_is_https_redirect","kind":"function","lang":"python","code":"def test_is_https_redirect():\n url = httpx.URL(\"https://example.com\")\n request = httpx.Request(\n \"GET\", \"http://example.com\", headers={\"Authorization\": \"empty\"}\n )\n\n client = httpx.Client()\n headers = client._redirect_headers(request, url, \"GET\")\n\n assert \"Authorization\" in headers"} {"repo":"httpx","file":"tests/client/test_headers.py","line":272,"symbol":"test_is_not_https_redirect","kind":"function","lang":"python","code":"def test_is_not_https_redirect():\n url = httpx.URL(\"https://www.example.com\")\n request = httpx.Request(\n \"GET\", \"http://example.com\", headers={\"Authorization\": \"empty\"}\n )\n\n client = httpx.Client()\n headers = client._redirect_headers(request, url, \"GET\")\n\n assert \"Authorization\" not in headers"} {"repo":"httpx","file":"tests/client/test_headers.py","line":284,"symbol":"test_is_not_https_redirect_if_not_default_ports","kind":"function","lang":"python","code":"def test_is_not_https_redirect_if_not_default_ports():\n url = httpx.URL(\"https://example.com:1337\")\n request = httpx.Request(\n \"GET\", \"http://example.com:9999\", headers={\"Authorization\": \"empty\"}\n )\n\n client = httpx.Client()\n headers = client._redirect_headers(request, url, \"GET\")\n\n assert \"Authorization\" not in headers"} {"repo":"httpx","file":"tests/client/test_properties.py","line":4,"symbol":"test_client_base_url","kind":"function","lang":"python","code":"def test_client_base_url():\n client = httpx.Client()\n client.base_url = \"https://www.example.org/\"\n assert isinstance(client.base_url, httpx.URL)\n assert client.base_url == \"https://www.example.org/\""} {"repo":"httpx","file":"tests/client/test_properties.py","line":11,"symbol":"test_client_base_url_without_trailing_slash","kind":"function","lang":"python","code":"def test_client_base_url_without_trailing_slash():\n client = httpx.Client()\n client.base_url = \"https://www.example.org/path\"\n assert isinstance(client.base_url, httpx.URL)\n assert client.base_url == \"https://www.example.org/path/\""} {"repo":"httpx","file":"tests/client/test_properties.py","line":18,"symbol":"test_client_base_url_with_trailing_slash","kind":"function","lang":"python","code":"def test_client_base_url_with_trailing_slash():\n client = httpx.Client()\n client.base_url = \"https://www.example.org/path/\"\n assert isinstance(client.base_url, httpx.URL)\n assert client.base_url == \"https://www.example.org/path/\""} {"repo":"httpx","file":"tests/client/test_properties.py","line":25,"symbol":"test_client_headers","kind":"function","lang":"python","code":"def test_client_headers():\n client = httpx.Client()\n client.headers = {\"a\": \"b\"}\n assert isinstance(client.headers, httpx.Headers)\n assert client.headers[\"A\"] == \"b\""} {"repo":"httpx","file":"tests/client/test_properties.py","line":32,"symbol":"test_client_cookies","kind":"function","lang":"python","code":"def test_client_cookies():\n client = httpx.Client()\n client.cookies = {\"a\": \"b\"}\n assert isinstance(client.cookies, httpx.Cookies)\n mycookies = list(client.cookies.jar)\n assert len(mycookies) == 1\n assert mycookies[0].name == \"a\" and mycookies[0].value == \"b\""} {"repo":"httpx","file":"tests/client/test_properties.py","line":41,"symbol":"test_client_timeout","kind":"function","lang":"python","code":"def test_client_timeout():\n expected_timeout = 12.0\n client = httpx.Client()\n\n client.timeout = expected_timeout\n\n assert isinstance(client.timeout, httpx.Timeout)\n assert client.timeout.connect == expected_timeout\n assert client.timeout.read == expected_timeout\n assert client.timeout.write == expected_timeout\n assert client.timeout.pool == expected_timeout"} {"repo":"httpx","file":"tests/client/test_properties.py","line":54,"symbol":"test_client_event_hooks","kind":"function","lang":"python","code":"def test_client_event_hooks():\n def on_request(request):\n pass # pragma: no cover\n\n client = httpx.Client()\n client.event_hooks = {\"request\": [on_request]}\n assert client.event_hooks == {\"request\": [on_request], \"response\": []}"} {"repo":"httpx","file":"tests/client/test_properties.py","line":55,"symbol":"on_request","kind":"function","lang":"python","code":"def on_request(request):\n pass # pragma: no cover"} {"repo":"httpx","file":"tests/client/test_properties.py","line":63,"symbol":"test_client_trust_env","kind":"function","lang":"python","code":"def test_client_trust_env():\n client = httpx.Client()\n assert client.trust_env\n\n client = httpx.Client(trust_env=False)\n assert not client.trust_env"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":7,"symbol":"url_to_origin","kind":"function","lang":"python","code":"def url_to_origin(url: str) -> httpcore.URL:\n \"\"\"\n Given a URL string, return the origin in the raw tuple format that\n `httpcore` uses for it's representation.\n \"\"\"\n u = httpx.URL(url)\n return httpcore.URL(scheme=u.raw_scheme, host=u.raw_host, port=u.port, target=\"/\")"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":16,"symbol":"test_socks_proxy","kind":"function","lang":"python","code":"def test_socks_proxy():\n url = httpx.URL(\"http://www.example.com\")\n\n for proxy in (\"socks5://localhost/\", \"socks5h://localhost/\"):\n client = httpx.Client(proxy=proxy)\n transport = client._transport_for_url(url)\n assert isinstance(transport, httpx.HTTPTransport)\n assert isinstance(transport._pool, httpcore.SOCKSProxy)\n\n async_client = httpx.AsyncClient(proxy=proxy)\n async_transport = async_client._transport_for_url(url)\n assert isinstance(async_transport, httpx.AsyncHTTPTransport)\n assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":88,"symbol":"test_transport_for_request","kind":"function","lang":"python","code":"def test_transport_for_request(url, proxies, expected):\n mounts = {key: httpx.HTTPTransport(proxy=value) for key, value in proxies.items()}\n client = httpx.Client(mounts=mounts)\n\n transport = client._transport_for_url(httpx.URL(url))\n\n if expected is None:\n assert transport is client._transport\n else:\n assert isinstance(transport, httpx.HTTPTransport)\n assert isinstance(transport._pool, httpcore.HTTPProxy)\n assert transport._pool._proxy_url == url_to_origin(expected)"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":104,"symbol":"test_async_proxy_close","kind":"function","lang":"python","code":"async def test_async_proxy_close():\n try:\n transport = httpx.AsyncHTTPTransport(proxy=PROXY_URL)\n client = httpx.AsyncClient(mounts={\"https://\": transport})\n await client.get(\"http://example.com\")\n finally:\n await client.aclose()"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":114,"symbol":"test_sync_proxy_close","kind":"function","lang":"python","code":"def test_sync_proxy_close():\n try:\n transport = httpx.HTTPTransport(proxy=PROXY_URL)\n client = httpx.Client(mounts={\"https://\": transport})\n client.get(\"http://example.com\")\n finally:\n client.close()"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":123,"symbol":"test_unsupported_proxy_scheme","kind":"function","lang":"python","code":"def test_unsupported_proxy_scheme():\n with pytest.raises(ValueError):\n httpx.Client(proxy=\"ftp://127.0.0.1\")"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":226,"symbol":"test_proxies_environ","kind":"function","lang":"python","code":"def test_proxies_environ(monkeypatch, client_class, url, env, expected):\n for name, value in env.items():\n monkeypatch.setenv(name, value)\n\n client = client_class()\n transport = client._transport_for_url(httpx.URL(url))\n\n if expected is None:\n assert transport == client._transport\n else:\n assert transport._pool._proxy_url == url_to_origin(expected)"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":250,"symbol":"test_for_deprecated_proxy_params","kind":"function","lang":"python","code":"def test_for_deprecated_proxy_params(proxies, is_valid):\n mounts = {key: httpx.HTTPTransport(proxy=value) for key, value in proxies.items()}\n\n if not is_valid:\n with pytest.raises(ValueError):\n httpx.Client(mounts=mounts)\n else:\n httpx.Client(mounts=mounts)"} {"repo":"httpx","file":"tests/client/test_proxies.py","line":260,"symbol":"test_proxy_with_mounts","kind":"function","lang":"python","code":"def test_proxy_with_mounts():\n proxy_transport = httpx.HTTPTransport(proxy=\"http://127.0.0.1\")\n client = httpx.Client(mounts={\"http://\": proxy_transport})\n\n transport = client._transport_for_url(httpx.URL(\"http://example.com\"))\n assert transport == proxy_transport"} {"repo":"httpx","file":"tests/client/test_queryparams.py","line":4,"symbol":"hello_world","kind":"function","lang":"python","code":"def hello_world(request: httpx.Request) -> httpx.Response:\n return httpx.Response(200, text=\"Hello, world\")"} {"repo":"httpx","file":"tests/client/test_queryparams.py","line":8,"symbol":"test_client_queryparams","kind":"function","lang":"python","code":"def test_client_queryparams():\n client = httpx.Client(params={\"a\": \"b\"})\n assert isinstance(client.params, httpx.QueryParams)\n assert client.params[\"a\"] == \"b\""} {"repo":"httpx","file":"tests/client/test_queryparams.py","line":14,"symbol":"test_client_queryparams_string","kind":"function","lang":"python","code":"def test_client_queryparams_string():\n client = httpx.Client(params=\"a=b\")\n assert isinstance(client.params, httpx.QueryParams)\n assert client.params[\"a\"] == \"b\"\n\n client = httpx.Client()\n client.params = \"a=b\"\n assert isinstance(client.params, httpx.QueryParams)\n assert client.params[\"a\"] == \"b\""} {"repo":"httpx","file":"tests/client/test_queryparams.py","line":25,"symbol":"test_client_queryparams_echo","kind":"function","lang":"python","code":"def test_client_queryparams_echo():\n url = \"http://example.org/echo_queryparams\"\n client_queryparams = \"first=str\"\n request_queryparams = {\"second\": \"dict\"}\n client = httpx.Client(\n transport=httpx.MockTransport(hello_world), params=client_queryparams\n )\n response = client.get(url, params=request_queryparams)\n\n assert response.status_code == 200\n assert response.url == \"http://example.org/echo_queryparams?first=str&second=dict\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":8,"symbol":"redirects","kind":"function","lang":"python","code":"def redirects(request: httpx.Request) -> httpx.Response:\n if request.url.scheme not in (\"http\", \"https\"):\n raise httpx.UnsupportedProtocol(f\"Scheme {request.url.scheme!r} not supported.\")\n\n if request.url.path == \"/redirect_301\":\n status_code = httpx.codes.MOVED_PERMANENTLY\n content = b\"here\"\n headers = {\"location\": \"https://example.org/\"}\n return httpx.Response(status_code, headers=headers, content=content)\n\n elif request.url.path == \"/redirect_302\":\n status_code = httpx.codes.FOUND\n headers = {\"location\": \"https://example.org/\"}\n return httpx.Response(status_code, headers=headers)\n\n elif request.url.path == \"/redirect_303\":\n status_code = httpx.codes.SEE_OTHER\n headers = {\"location\": \"https://example.org/\"}\n return httpx.Response(status_code, headers=headers)\n\n elif request.url.path == \"/relative_redirect\":\n status_code = httpx.codes.SEE_OTHER\n headers = {\"location\": \"/\"}\n return httpx.Response(status_code, headers=headers)\n\n elif request.url.path == \"/malformed_redirect\":\n status_code = httpx.codes.SEE_OTHER\n headers"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":116,"symbol":"test_redirect_301","kind":"function","lang":"python","code":"def test_redirect_301():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.post(\"https://example.org/redirect_301\", follow_redirects=True)\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":124,"symbol":"test_redirect_302","kind":"function","lang":"python","code":"def test_redirect_302():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.post(\"https://example.org/redirect_302\", follow_redirects=True)\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":132,"symbol":"test_redirect_303","kind":"function","lang":"python","code":"def test_redirect_303():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.get(\"https://example.org/redirect_303\", follow_redirects=True)\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":140,"symbol":"test_next_request","kind":"function","lang":"python","code":"def test_next_request():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n request = client.build_request(\"POST\", \"https://example.org/redirect_303\")\n response = client.send(request, follow_redirects=False)\n assert response.status_code == httpx.codes.SEE_OTHER\n assert response.url == \"https://example.org/redirect_303\"\n assert response.next_request is not None\n\n response = client.send(response.next_request, follow_redirects=False)\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert response.next_request is None"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":155,"symbol":"test_async_next_request","kind":"function","lang":"python","code":"async def test_async_next_request():\n async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:\n request = client.build_request(\"POST\", \"https://example.org/redirect_303\")\n response = await client.send(request, follow_redirects=False)\n assert response.status_code == httpx.codes.SEE_OTHER\n assert response.url == \"https://example.org/redirect_303\"\n assert response.next_request is not None\n\n response = await client.send(response.next_request, follow_redirects=False)\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert response.next_request is None"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":169,"symbol":"test_head_redirect","kind":"function","lang":"python","code":"def test_head_redirect():\n \"\"\"\n Contrary to Requests, redirects remain enabled by default for HEAD requests.\n \"\"\"\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.head(\"https://example.org/redirect_302\", follow_redirects=True)\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert response.request.method == \"HEAD\"\n assert len(response.history) == 1\n assert response.text == \"\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":182,"symbol":"test_relative_redirect","kind":"function","lang":"python","code":"def test_relative_redirect():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.get(\n \"https://example.org/relative_redirect\", follow_redirects=True\n )\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":192,"symbol":"test_malformed_redirect","kind":"function","lang":"python","code":"def test_malformed_redirect():\n # https://github.com/encode/httpx/issues/771\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.get(\n \"http://example.org/malformed_redirect\", follow_redirects=True\n )\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org:443/\"\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":203,"symbol":"test_invalid_redirect","kind":"function","lang":"python","code":"def test_invalid_redirect():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n with pytest.raises(httpx.RemoteProtocolError):\n client.get(\"http://example.org/invalid_redirect\", follow_redirects=True)"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":209,"symbol":"test_no_scheme_redirect","kind":"function","lang":"python","code":"def test_no_scheme_redirect():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.get(\n \"https://example.org/no_scheme_redirect\", follow_redirects=True\n )\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/\"\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":219,"symbol":"test_fragment_redirect","kind":"function","lang":"python","code":"def test_fragment_redirect():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.get(\n \"https://example.org/relative_redirect#fragment\", follow_redirects=True\n )\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/#fragment\"\n assert len(response.history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":229,"symbol":"test_multiple_redirects","kind":"function","lang":"python","code":"def test_multiple_redirects():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n response = client.get(\n \"https://example.org/multiple_redirects?count=20\", follow_redirects=True\n )\n assert response.status_code == httpx.codes.OK\n assert response.url == \"https://example.org/multiple_redirects\"\n assert len(response.history) == 20\n assert response.history[0].url == \"https://example.org/multiple_redirects?count=20\"\n assert response.history[1].url == \"https://example.org/multiple_redirects?count=19\"\n assert len(response.history[0].history) == 0\n assert len(response.history[1].history) == 1"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":244,"symbol":"test_async_too_many_redirects","kind":"function","lang":"python","code":"async def test_async_too_many_redirects():\n async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:\n with pytest.raises(httpx.TooManyRedirects):\n await client.get(\n \"https://example.org/multiple_redirects?count=21\", follow_redirects=True\n )"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":252,"symbol":"test_sync_too_many_redirects","kind":"function","lang":"python","code":"def test_sync_too_many_redirects():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n with pytest.raises(httpx.TooManyRedirects):\n client.get(\n \"https://example.org/multiple_redirects?count=21\", follow_redirects=True\n )"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":260,"symbol":"test_redirect_loop","kind":"function","lang":"python","code":"def test_redirect_loop():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n with pytest.raises(httpx.TooManyRedirects):\n client.get(\"https://example.org/redirect_loop\", follow_redirects=True)"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":266,"symbol":"test_cross_domain_redirect_with_auth_header","kind":"function","lang":"python","code":"def test_cross_domain_redirect_with_auth_header():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"https://example.com/cross_domain\"\n headers = {\"Authorization\": \"abc\"}\n response = client.get(url, headers=headers, follow_redirects=True)\n assert response.url == \"https://example.org/cross_domain_target\"\n assert \"authorization\" not in response.json()[\"headers\"]"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":275,"symbol":"test_cross_domain_https_redirect_with_auth_header","kind":"function","lang":"python","code":"def test_cross_domain_https_redirect_with_auth_header():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"http://example.com/cross_domain\"\n headers = {\"Authorization\": \"abc\"}\n response = client.get(url, headers=headers, follow_redirects=True)\n assert response.url == \"https://example.org/cross_domain_target\"\n assert \"authorization\" not in response.json()[\"headers\"]"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":284,"symbol":"test_cross_domain_redirect_with_auth","kind":"function","lang":"python","code":"def test_cross_domain_redirect_with_auth():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"https://example.com/cross_domain\"\n response = client.get(url, auth=(\"user\", \"pass\"), follow_redirects=True)\n assert response.url == \"https://example.org/cross_domain_target\"\n assert \"authorization\" not in response.json()[\"headers\"]"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":292,"symbol":"test_same_domain_redirect","kind":"function","lang":"python","code":"def test_same_domain_redirect():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"https://example.org/cross_domain\"\n headers = {\"Authorization\": \"abc\"}\n response = client.get(url, headers=headers, follow_redirects=True)\n assert response.url == \"https://example.org/cross_domain_target\"\n assert response.json()[\"headers\"][\"authorization\"] == \"abc\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":301,"symbol":"test_same_domain_https_redirect_with_auth_header","kind":"function","lang":"python","code":"def test_same_domain_https_redirect_with_auth_header():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"http://example.org/cross_domain\"\n headers = {\"Authorization\": \"abc\"}\n response = client.get(url, headers=headers, follow_redirects=True)\n assert response.url == \"https://example.org/cross_domain_target\"\n assert response.json()[\"headers\"][\"authorization\"] == \"abc\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":310,"symbol":"test_body_redirect","kind":"function","lang":"python","code":"def test_body_redirect():\n \"\"\"\n A 308 redirect should preserve the request body.\n \"\"\"\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"https://example.org/redirect_body\"\n content = b\"Example request body\"\n response = client.post(url, content=content, follow_redirects=True)\n assert response.url == \"https://example.org/redirect_body_target\"\n assert response.json()[\"body\"] == \"Example request body\"\n assert \"content-length\" in response.json()[\"headers\"]"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":323,"symbol":"test_no_body_redirect","kind":"function","lang":"python","code":"def test_no_body_redirect():\n \"\"\"\n A 303 redirect should remove the request body.\n \"\"\"\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"https://example.org/redirect_no_body\"\n content = b\"Example request body\"\n response = client.post(url, content=content, follow_redirects=True)\n assert response.url == \"https://example.org/redirect_body_target\"\n assert response.json()[\"body\"] == \"\"\n assert \"content-length\" not in response.json()[\"headers\"]"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":336,"symbol":"test_can_stream_if_no_redirect","kind":"function","lang":"python","code":"def test_can_stream_if_no_redirect():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"https://example.org/redirect_301\"\n with client.stream(\"GET\", url, follow_redirects=False) as response:\n pass\n assert response.status_code == httpx.codes.MOVED_PERMANENTLY\n assert response.headers[\"location\"] == \"https://example.org/\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":345,"symbol":"ConsumeBodyTransport","kind":"class","lang":"python","code":"class ConsumeBodyTransport(httpx.MockTransport):\n def handle_request(self, request: httpx.Request) -> httpx.Response:\n assert isinstance(request.stream, httpx.SyncByteStream)\n list(request.stream)\n return self.handler(request) # type: ignore[return-value]"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":346,"symbol":"handle_request","kind":"function","lang":"python","code":"def handle_request(self, request: httpx.Request) -> httpx.Response:\n assert isinstance(request.stream, httpx.SyncByteStream)\n list(request.stream)\n return self.handler(request) # type: ignore[return-value]"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":352,"symbol":"test_cannot_redirect_streaming_body","kind":"function","lang":"python","code":"def test_cannot_redirect_streaming_body():\n client = httpx.Client(transport=ConsumeBodyTransport(redirects))\n url = \"https://example.org/redirect_body\"\n\n def streaming_body() -> typing.Iterator[bytes]:\n yield b\"Example request body\" # pragma: no cover\n\n with pytest.raises(httpx.StreamConsumed):\n client.post(url, content=streaming_body(), follow_redirects=True)"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":356,"symbol":"streaming_body","kind":"function","lang":"python","code":"def streaming_body() -> typing.Iterator[bytes]:\n yield b\"Example request body\" # pragma: no cover"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":363,"symbol":"test_cross_subdomain_redirect","kind":"function","lang":"python","code":"def test_cross_subdomain_redirect():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n url = \"https://example.com/cross_subdomain\"\n response = client.get(url, follow_redirects=True)\n assert response.url == \"https://www.example.org/cross_subdomain\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":370,"symbol":"cookie_sessions","kind":"function","lang":"python","code":"def cookie_sessions(request: httpx.Request) -> httpx.Response:\n if request.url.path == \"/\":\n cookie = request.headers.get(\"Cookie\")\n if cookie is not None:\n content = b\"Logged in\"\n else:\n content = b\"Not logged in\"\n return httpx.Response(200, content=content)\n\n elif request.url.path == \"/login\":\n status_code = httpx.codes.SEE_OTHER\n headers = {\n \"location\": \"/\",\n \"set-cookie\": (\n \"session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; \"\n \"httponly; samesite=lax\"\n ),\n }\n return httpx.Response(status_code, headers=headers)\n\n else:\n assert request.url.path == \"/logout\"\n status_code = httpx.codes.SEE_OTHER\n headers = {\n \"location\": \"/\",\n \"set-cookie\": (\n \"session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; \"\n \"httponly; samesite=lax\"\n ),\n }\n return httpx.Response(status_code, headers=headers)"} {"repo":"httpx","file":"tests/client/test_redirects.py","line":403,"symbol":"test_redirect_cookie_behavior","kind":"function","lang":"python","code":"def test_redirect_cookie_behavior():\n client = httpx.Client(\n transport=httpx.MockTransport(cookie_sessions), follow_redirects=True\n )\n\n # The client is not logged in.\n response = client.get(\"https://example.com/\")\n assert response.url == \"https://example.com/\"\n assert response.text == \"Not logged in\"\n\n # Login redirects to the homepage, setting a session cookie.\n response = client.post(\"https://example.com/login\")\n assert response.url == \"https://example.com/\"\n assert response.text == \"Logged in\"\n\n # The client is logged in.\n response = client.get(\"https://example.com/\")\n assert response.url == \"https://example.com/\"\n assert response.text == \"Logged in\"\n\n # Logout redirects to the homepage, expiring the session cookie.\n response = client.post(\"https://example.com/logout\")\n assert response.url == \"https://example.com/\"\n assert response.text == \"Not logged in\"\n\n # The client is not logged in.\n response = client.get(\"https://example.com/\")\n assert response.url == \"https://example.com/\"\n assert response.text == \"Not logged in\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":434,"symbol":"test_redirect_custom_scheme","kind":"function","lang":"python","code":"def test_redirect_custom_scheme():\n client = httpx.Client(transport=httpx.MockTransport(redirects))\n with pytest.raises(httpx.UnsupportedProtocol) as e:\n client.post(\"https://example.org/redirect_custom_scheme\", follow_redirects=True)\n assert str(e.value) == \"Scheme 'market' not supported.\""} {"repo":"httpx","file":"tests/client/test_redirects.py","line":442,"symbol":"test_async_invalid_redirect","kind":"function","lang":"python","code":"async def test_async_invalid_redirect():\n async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:\n with pytest.raises(httpx.RemoteProtocolError):\n await client.get(\n \"http://example.org/invalid_redirect\", follow_redirects=True\n )"} {"repo":"httpx","file":"tests/concurrency.py","line":11,"symbol":"sleep","kind":"function","lang":"python","code":"async def sleep(seconds: float) -> None:\n if sniffio.current_async_library() == \"trio\":\n await trio.sleep(seconds) # pragma: no cover\n else:\n await asyncio.sleep(seconds)"} {"repo":"httpx","file":"tests/conftest.py","line":35,"symbol":"clean_environ","kind":"function","lang":"python","code":"def clean_environ():\n \"\"\"Keeps os.environ clean for every test without having to mock os.environ\"\"\"\n original_environ = os.environ.copy()\n os.environ.clear()\n os.environ.update(\n {\n k: v\n for k, v in original_environ.items()\n if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES\n }\n )\n yield\n os.environ.clear()\n os.environ.update(original_environ)"} {"repo":"httpx","file":"tests/conftest.py","line":59,"symbol":"app","kind":"function","lang":"python","code":"async def app(scope: Scope, receive: Receive, send: Send) -> None:\n assert scope[\"type\"] == \"http\"\n if scope[\"path\"].startswith(\"/slow_response\"):\n await slow_response(scope, receive, send)\n elif scope[\"path\"].startswith(\"/status\"):\n await status_code(scope, receive, send)\n elif scope[\"path\"].startswith(\"/echo_body\"):\n await echo_body(scope, receive, send)\n elif scope[\"path\"].startswith(\"/echo_binary\"):\n await echo_binary(scope, receive, send)\n elif scope[\"path\"].startswith(\"/echo_headers\"):\n await echo_headers(scope, receive, send)\n elif scope[\"path\"].startswith(\"/redirect_301\"):\n await redirect_301(scope, receive, send)\n elif scope[\"path\"].startswith(\"/json\"):\n await hello_world_json(scope, receive, send)\n else:\n await hello_world(scope, receive, send)"} {"repo":"httpx","file":"tests/conftest.py","line":79,"symbol":"hello_world","kind":"function","lang":"python","code":"async def hello_world(scope: Scope, receive: Receive, send: Send) -> None:\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": 200,\n \"headers\": [[b\"content-type\", b\"text/plain\"]],\n }\n )\n await send({\"type\": \"http.response.body\", \"body\": b\"Hello, world!\"})"} {"repo":"httpx","file":"tests/conftest.py","line":90,"symbol":"hello_world_json","kind":"function","lang":"python","code":"async def hello_world_json(scope: Scope, receive: Receive, send: Send) -> None:\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": 200,\n \"headers\": [[b\"content-type\", b\"application/json\"]],\n }\n )\n await send({\"type\": \"http.response.body\", \"body\": b'{\"Hello\": \"world!\"}'})"} {"repo":"httpx","file":"tests/conftest.py","line":101,"symbol":"slow_response","kind":"function","lang":"python","code":"async def slow_response(scope: Scope, receive: Receive, send: Send) -> None:\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": 200,\n \"headers\": [[b\"content-type\", b\"text/plain\"]],\n }\n )\n await sleep(1.0) # Allow triggering a read timeout.\n await send({\"type\": \"http.response.body\", \"body\": b\"Hello, world!\"})"} {"repo":"httpx","file":"tests/conftest.py","line":113,"symbol":"status_code","kind":"function","lang":"python","code":"async def status_code(scope: Scope, receive: Receive, send: Send) -> None:\n status_code = int(scope[\"path\"].replace(\"/status/\", \"\"))\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": status_code,\n \"headers\": [[b\"content-type\", b\"text/plain\"]],\n }\n )\n await send({\"type\": \"http.response.body\", \"body\": b\"Hello, world!\"})"} {"repo":"httpx","file":"tests/conftest.py","line":125,"symbol":"echo_body","kind":"function","lang":"python","code":"async def echo_body(scope: Scope, receive: Receive, send: Send) -> None:\n body = b\"\"\n more_body = True\n\n while more_body:\n message = await receive()\n body += message.get(\"body\", b\"\")\n more_body = message.get(\"more_body\", False)\n\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": 200,\n \"headers\": [[b\"content-type\", b\"text/plain\"]],\n }\n )\n await send({\"type\": \"http.response.body\", \"body\": body})"} {"repo":"httpx","file":"tests/conftest.py","line":144,"symbol":"echo_binary","kind":"function","lang":"python","code":"async def echo_binary(scope: Scope, receive: Receive, send: Send) -> None:\n body = b\"\"\n more_body = True\n\n while more_body:\n message = await receive()\n body += message.get(\"body\", b\"\")\n more_body = message.get(\"more_body\", False)\n\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": 200,\n \"headers\": [[b\"content-type\", b\"application/octet-stream\"]],\n }\n )\n await send({\"type\": \"http.response.body\", \"body\": body})"} {"repo":"httpx","file":"tests/conftest.py","line":163,"symbol":"echo_headers","kind":"function","lang":"python","code":"async def echo_headers(scope: Scope, receive: Receive, send: Send) -> None:\n body = {\n name.capitalize().decode(): value.decode()\n for name, value in scope.get(\"headers\", [])\n }\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": 200,\n \"headers\": [[b\"content-type\", b\"application/json\"]],\n }\n )\n await send({\"type\": \"http.response.body\", \"body\": json.dumps(body).encode()})"} {"repo":"httpx","file":"tests/conftest.py","line":178,"symbol":"redirect_301","kind":"function","lang":"python","code":"async def redirect_301(scope: Scope, receive: Receive, send: Send) -> None:\n await send(\n {\"type\": \"http.response.start\", \"status\": 301, \"headers\": [[b\"location\", b\"/\"]]}\n )\n await send({\"type\": \"http.response.body\"})"} {"repo":"httpx","file":"tests/conftest.py","line":186,"symbol":"cert_authority","kind":"function","lang":"python","code":"def cert_authority():\n return trustme.CA()"} {"repo":"httpx","file":"tests/conftest.py","line":191,"symbol":"localhost_cert","kind":"function","lang":"python","code":"def localhost_cert(cert_authority):\n return cert_authority.issue_cert(\"localhost\")"} {"repo":"httpx","file":"tests/conftest.py","line":196,"symbol":"cert_pem_file","kind":"function","lang":"python","code":"def cert_pem_file(localhost_cert):\n with localhost_cert.cert_chain_pems[0].tempfile() as tmp:\n yield tmp"} {"repo":"httpx","file":"tests/conftest.py","line":202,"symbol":"cert_private_key_file","kind":"function","lang":"python","code":"def cert_private_key_file(localhost_cert):\n with localhost_cert.private_key_pem.tempfile() as tmp:\n yield tmp"} {"repo":"httpx","file":"tests/conftest.py","line":208,"symbol":"cert_encrypted_private_key_file","kind":"function","lang":"python","code":"def cert_encrypted_private_key_file(localhost_cert):\n # Deserialize the private key and then reserialize with a password\n private_key = load_pem_private_key(\n localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()\n )\n encrypted_private_key_pem = trustme.Blob(\n private_key.private_bytes(\n Encoding.PEM,\n PrivateFormat.TraditionalOpenSSL,\n BestAvailableEncryption(password=b\"password\"),\n )\n )\n with encrypted_private_key_pem.tempfile() as tmp:\n yield tmp"} {"repo":"httpx","file":"tests/conftest.py","line":224,"symbol":"TestServer","kind":"class","lang":"python","code":"class TestServer(Server):\n @property\n def url(self) -> httpx.URL:\n protocol = \"https\" if self.config.is_ssl else \"http\"\n return httpx.URL(f\"{protocol}://{self.config.host}:{self.config.port}/\")\n\n def install_signal_handlers(self) -> None:\n # Disable the default installation of handlers for signals such as SIGTERM,\n # because it can only be done in the main thread.\n pass # pragma: nocover\n\n async def serve(self, sockets=None):\n self.restart_requested = asyncio.Event()\n\n loop = asyncio.get_event_loop()\n tasks = {\n loop.create_task(super().serve(sockets=sockets)),\n loop.create_task(self.watch_restarts()),\n }\n await asyncio.wait(tasks)\n\n async def restart(self) -> None: # pragma: no cover\n # This coroutine may be called from a different thread than the one the\n # server is running on, and from an async environment that's not asyncio.\n # For this reason, we use an event to coordinate with the server\n # instead of calling shutdown()/startup() directly, and should not make\n # any asyncio-specific operations.\n self.started = False\n se"} {"repo":"httpx","file":"tests/conftest.py","line":226,"symbol":"url","kind":"function","lang":"python","code":"def url(self) -> httpx.URL:\n protocol = \"https\" if self.config.is_ssl else \"http\"\n return httpx.URL(f\"{protocol}://{self.config.host}:{self.config.port}/\")"} {"repo":"httpx","file":"tests/conftest.py","line":230,"symbol":"install_signal_handlers","kind":"function","lang":"python","code":"def install_signal_handlers(self) -> None:\n # Disable the default installation of handlers for signals such as SIGTERM,\n # because it can only be done in the main thread.\n pass # pragma: nocover"} {"repo":"httpx","file":"tests/conftest.py","line":235,"symbol":"serve","kind":"function","lang":"python","code":"async def serve(self, sockets=None):\n self.restart_requested = asyncio.Event()\n\n loop = asyncio.get_event_loop()\n tasks = {\n loop.create_task(super().serve(sockets=sockets)),\n loop.create_task(self.watch_restarts()),\n }\n await asyncio.wait(tasks)"} {"repo":"httpx","file":"tests/conftest.py","line":245,"symbol":"restart","kind":"function","lang":"python","code":"async def restart(self) -> None: # pragma: no cover\n # This coroutine may be called from a different thread than the one the\n # server is running on, and from an async environment that's not asyncio.\n # For this reason, we use an event to coordinate with the server\n # instead of calling shutdown()/startup() directly, and should not make\n # any asyncio-specific operations.\n self.started = False\n self.restart_requested.set()\n while not self.started:\n await sleep(0.2)"} {"repo":"httpx","file":"tests/conftest.py","line":256,"symbol":"watch_restarts","kind":"function","lang":"python","code":"async def watch_restarts(self) -> None: # pragma: no cover\n while True:\n if self.should_exit:\n return\n\n try:\n await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)\n except asyncio.TimeoutError:\n continue\n\n self.restart_requested.clear()\n await self.shutdown()\n await self.startup()"} {"repo":"httpx","file":"tests/conftest.py","line":271,"symbol":"serve_in_thread","kind":"function","lang":"python","code":"def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:\n thread = threading.Thread(target=server.run)\n thread.start()\n try:\n while not server.started:\n time.sleep(1e-3)\n yield server\n finally:\n server.should_exit = True\n thread.join()"} {"repo":"httpx","file":"tests/conftest.py","line":284,"symbol":"server","kind":"function","lang":"python","code":"def server() -> typing.Iterator[TestServer]:\n config = Config(app=app, lifespan=\"off\", loop=\"asyncio\")\n server = TestServer(config=config)\n yield from serve_in_thread(server)"} {"repo":"httpx","file":"tests/models/test_cookies.py","line":8,"symbol":"test_cookies","kind":"function","lang":"python","code":"def test_cookies():\n cookies = httpx.Cookies({\"name\": \"value\"})\n assert cookies[\"name\"] == \"value\"\n assert \"name\" in cookies\n assert len(cookies) == 1\n assert dict(cookies) == {\"name\": \"value\"}\n assert bool(cookies) is True\n\n del cookies[\"name\"]\n assert \"name\" not in cookies\n assert len(cookies) == 0\n assert dict(cookies) == {}\n assert bool(cookies) is False"} {"repo":"httpx","file":"tests/models/test_cookies.py","line":23,"symbol":"test_cookies_update","kind":"function","lang":"python","code":"def test_cookies_update():\n cookies = httpx.Cookies()\n more_cookies = httpx.Cookies()\n more_cookies.set(\"name\", \"value\", domain=\"example.com\")\n\n cookies.update(more_cookies)\n assert dict(cookies) == {\"name\": \"value\"}\n assert cookies.get(\"name\", domain=\"example.com\") == \"value\""} {"repo":"httpx","file":"tests/models/test_cookies.py","line":33,"symbol":"test_cookies_with_domain","kind":"function","lang":"python","code":"def test_cookies_with_domain():\n cookies = httpx.Cookies()\n cookies.set(\"name\", \"value\", domain=\"example.com\")\n cookies.set(\"name\", \"value\", domain=\"example.org\")\n\n with pytest.raises(httpx.CookieConflict):\n cookies[\"name\"]\n\n cookies.clear(domain=\"example.com\")\n assert len(cookies) == 1"} {"repo":"httpx","file":"tests/models/test_cookies.py","line":45,"symbol":"test_cookies_with_domain_and_path","kind":"function","lang":"python","code":"def test_cookies_with_domain_and_path():\n cookies = httpx.Cookies()\n cookies.set(\"name\", \"value\", domain=\"example.com\", path=\"/subpath/1\")\n cookies.set(\"name\", \"value\", domain=\"example.com\", path=\"/subpath/2\")\n cookies.clear(domain=\"example.com\", path=\"/subpath/1\")\n assert len(cookies) == 1\n cookies.delete(\"name\", domain=\"example.com\", path=\"/subpath/2\")\n assert len(cookies) == 0"} {"repo":"httpx","file":"tests/models/test_cookies.py","line":55,"symbol":"test_multiple_set_cookie","kind":"function","lang":"python","code":"def test_multiple_set_cookie():\n jar = http.cookiejar.CookieJar()\n headers = [\n (\n b\"Set-Cookie\",\n b\"1P_JAR=2020-08-09-18; expires=Tue, 08-Sep-2099 18:33:35 GMT; \"\n b\"path=/; domain=.example.org; Secure\",\n ),\n (\n b\"Set-Cookie\",\n b\"NID=204=KWdXOuypc86YvRfBSiWoW1dEXfSl_5qI7sxZY4umlk4J35yNTeNEkw15\"\n b\"MRaujK6uYCwkrtjihTTXZPp285z_xDOUzrdHt4dj0Z5C0VOpbvdLwRdHatHAzQs7\"\n b\"7TsaiWY78a3qU9r7KP_RbSLvLl2hlhnWFR2Hp5nWKPsAcOhQgSg; expires=Mon, \"\n b\"08-Feb-2099 18:33:35 GMT; path=/; domain=.example.org; HttpOnly\",\n ),\n ]\n request = httpx.Request(\"GET\", \"https://www.example.org\")\n response = httpx.Response(200, request=request, headers=headers)\n\n cookies = httpx.Cookies(jar)\n cookies.extract_cookies(response)\n\n assert len(cookies) == 2"} {"repo":"httpx","file":"tests/models/test_cookies.py","line":80,"symbol":"test_cookies_can_be_a_list_of_tuples","kind":"function","lang":"python","code":"def test_cookies_can_be_a_list_of_tuples():\n cookies_val = [(\"name1\", \"val1\"), (\"name2\", \"val2\")]\n\n cookies = httpx.Cookies(cookies_val)\n\n assert len(cookies.items()) == 2\n for k, v in cookies_val:\n assert cookies[k] == v"} {"repo":"httpx","file":"tests/models/test_cookies.py","line":90,"symbol":"test_cookies_repr","kind":"function","lang":"python","code":"def test_cookies_repr():\n cookies = httpx.Cookies()\n cookies.set(name=\"foo\", value=\"bar\", domain=\"http://blah.com\")\n cookies.set(name=\"fizz\", value=\"buzz\", domain=\"http://hello.com\")\n\n assert repr(cookies) == (\n \",\"\n \" ]>\"\n )"} {"repo":"httpx","file":"tests/models/test_headers.py","line":6,"symbol":"test_headers","kind":"function","lang":"python","code":"def test_headers():\n h = httpx.Headers([(\"a\", \"123\"), (\"a\", \"456\"), (\"b\", \"789\")])\n assert \"a\" in h\n assert \"A\" in h\n assert \"b\" in h\n assert \"B\" in h\n assert \"c\" not in h\n assert h[\"a\"] == \"123, 456\"\n assert h.get(\"a\") == \"123, 456\"\n assert h.get(\"nope\", default=None) is None\n assert h.get_list(\"a\") == [\"123\", \"456\"]\n\n assert list(h.keys()) == [\"a\", \"b\"]\n assert list(h.values()) == [\"123, 456\", \"789\"]\n assert list(h.items()) == [(\"a\", \"123, 456\"), (\"b\", \"789\")]\n assert h.multi_items() == [(\"a\", \"123\"), (\"a\", \"456\"), (\"b\", \"789\")]\n assert list(h) == [\"a\", \"b\"]\n assert dict(h) == {\"a\": \"123, 456\", \"b\": \"789\"}\n assert repr(h) == \"Headers([('a', '123'), ('a', '456'), ('b', '789')])\"\n assert h == [(\"a\", \"123\"), (\"b\", \"789\"), (\"a\", \"456\")]\n assert h == [(\"a\", \"123\"), (\"A\", \"456\"), (\"b\", \"789\")]\n assert h == {\"a\": \"123\", \"A\": \"456\", \"b\": \"789\"}\n assert h != \"a: 123\\nA: 456\\nb: 789\"\n\n h = httpx.Headers({\"a\": \"123\", \"b\": \"789\"})\n assert h[\"A\"] == \"123\"\n assert h[\"B\"] == \"789\"\n assert h.raw == [(b\"a\", b\"123\"), (b\"b\", b\"789\")]\n assert repr(h) == \"Headers({'a': '123', 'b': '789'})\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":37,"symbol":"test_header_mutations","kind":"function","lang":"python","code":"def test_header_mutations():\n h = httpx.Headers()\n assert dict(h) == {}\n h[\"a\"] = \"1\"\n assert dict(h) == {\"a\": \"1\"}\n h[\"a\"] = \"2\"\n assert dict(h) == {\"a\": \"2\"}\n h.setdefault(\"a\", \"3\")\n assert dict(h) == {\"a\": \"2\"}\n h.setdefault(\"b\", \"4\")\n assert dict(h) == {\"a\": \"2\", \"b\": \"4\"}\n del h[\"a\"]\n assert dict(h) == {\"b\": \"4\"}\n assert h.raw == [(b\"b\", b\"4\")]"} {"repo":"httpx","file":"tests/models/test_headers.py","line":53,"symbol":"test_copy_headers_method","kind":"function","lang":"python","code":"def test_copy_headers_method():\n headers = httpx.Headers({\"custom\": \"example\"})\n headers_copy = headers.copy()\n assert headers == headers_copy\n assert headers is not headers_copy"} {"repo":"httpx","file":"tests/models/test_headers.py","line":60,"symbol":"test_copy_headers_init","kind":"function","lang":"python","code":"def test_copy_headers_init():\n headers = httpx.Headers({\"custom\": \"example\"})\n headers_copy = httpx.Headers(headers)\n assert headers == headers_copy"} {"repo":"httpx","file":"tests/models/test_headers.py","line":66,"symbol":"test_headers_insert_retains_ordering","kind":"function","lang":"python","code":"def test_headers_insert_retains_ordering():\n headers = httpx.Headers({\"a\": \"a\", \"b\": \"b\", \"c\": \"c\"})\n headers[\"b\"] = \"123\"\n assert list(headers.values()) == [\"a\", \"123\", \"c\"]"} {"repo":"httpx","file":"tests/models/test_headers.py","line":72,"symbol":"test_headers_insert_appends_if_new","kind":"function","lang":"python","code":"def test_headers_insert_appends_if_new():\n headers = httpx.Headers({\"a\": \"a\", \"b\": \"b\", \"c\": \"c\"})\n headers[\"d\"] = \"123\"\n assert list(headers.values()) == [\"a\", \"b\", \"c\", \"123\"]"} {"repo":"httpx","file":"tests/models/test_headers.py","line":78,"symbol":"test_headers_insert_removes_all_existing","kind":"function","lang":"python","code":"def test_headers_insert_removes_all_existing():\n headers = httpx.Headers([(\"a\", \"123\"), (\"a\", \"456\")])\n headers[\"a\"] = \"789\"\n assert dict(headers) == {\"a\": \"789\"}"} {"repo":"httpx","file":"tests/models/test_headers.py","line":84,"symbol":"test_headers_delete_removes_all_existing","kind":"function","lang":"python","code":"def test_headers_delete_removes_all_existing():\n headers = httpx.Headers([(\"a\", \"123\"), (\"a\", \"456\")])\n del headers[\"a\"]\n assert dict(headers) == {}"} {"repo":"httpx","file":"tests/models/test_headers.py","line":90,"symbol":"test_headers_dict_repr","kind":"function","lang":"python","code":"def test_headers_dict_repr():\n \"\"\"\n Headers should display with a dict repr by default.\n \"\"\"\n headers = httpx.Headers({\"custom\": \"example\"})\n assert repr(headers) == \"Headers({'custom': 'example'})\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":98,"symbol":"test_headers_encoding_in_repr","kind":"function","lang":"python","code":"def test_headers_encoding_in_repr():\n \"\"\"\n Headers should display an encoding in the repr if required.\n \"\"\"\n headers = httpx.Headers({b\"custom\": \"example ☃\".encode(\"utf-8\")})\n assert repr(headers) == \"Headers({'custom': 'example ☃'}, encoding='utf-8')\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":106,"symbol":"test_headers_list_repr","kind":"function","lang":"python","code":"def test_headers_list_repr():\n \"\"\"\n Headers should display with a list repr if they include multiple identical keys.\n \"\"\"\n headers = httpx.Headers([(\"custom\", \"example 1\"), (\"custom\", \"example 2\")])\n assert (\n repr(headers) == \"Headers([('custom', 'example 1'), ('custom', 'example 2')])\"\n )"} {"repo":"httpx","file":"tests/models/test_headers.py","line":116,"symbol":"test_headers_decode_ascii","kind":"function","lang":"python","code":"def test_headers_decode_ascii():\n \"\"\"\n Headers should decode as ascii by default.\n \"\"\"\n raw_headers = [(b\"Custom\", b\"Example\")]\n headers = httpx.Headers(raw_headers)\n assert dict(headers) == {\"custom\": \"Example\"}\n assert headers.encoding == \"ascii\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":126,"symbol":"test_headers_decode_utf_8","kind":"function","lang":"python","code":"def test_headers_decode_utf_8():\n \"\"\"\n Headers containing non-ascii codepoints should default to decoding as utf-8.\n \"\"\"\n raw_headers = [(b\"Custom\", \"Code point: ☃\".encode(\"utf-8\"))]\n headers = httpx.Headers(raw_headers)\n assert dict(headers) == {\"custom\": \"Code point: ☃\"}\n assert headers.encoding == \"utf-8\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":136,"symbol":"test_headers_decode_iso_8859_1","kind":"function","lang":"python","code":"def test_headers_decode_iso_8859_1():\n \"\"\"\n Headers containing non-UTF-8 codepoints should default to decoding as iso-8859-1.\n \"\"\"\n raw_headers = [(b\"Custom\", \"Code point: ÿ\".encode(\"iso-8859-1\"))]\n headers = httpx.Headers(raw_headers)\n assert dict(headers) == {\"custom\": \"Code point: ÿ\"}\n assert headers.encoding == \"iso-8859-1\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":146,"symbol":"test_headers_decode_explicit_encoding","kind":"function","lang":"python","code":"def test_headers_decode_explicit_encoding():\n \"\"\"\n An explicit encoding may be set on headers in order to force a\n particular decoding.\n \"\"\"\n raw_headers = [(b\"Custom\", \"Code point: ☃\".encode(\"utf-8\"))]\n headers = httpx.Headers(raw_headers)\n headers.encoding = \"iso-8859-1\"\n assert dict(headers) == {\"custom\": \"Code point: â\\x98\\x83\"}\n assert headers.encoding == \"iso-8859-1\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":158,"symbol":"test_multiple_headers","kind":"function","lang":"python","code":"def test_multiple_headers():\n \"\"\"\n `Headers.get_list` should support both split_commas=False and split_commas=True.\n \"\"\"\n h = httpx.Headers([(\"set-cookie\", \"a, b\"), (\"set-cookie\", \"c\")])\n assert h.get_list(\"Set-Cookie\") == [\"a, b\", \"c\"]\n\n h = httpx.Headers([(\"vary\", \"a, b\"), (\"vary\", \"c\")])\n assert h.get_list(\"Vary\", split_commas=True) == [\"a\", \"b\", \"c\"]"} {"repo":"httpx","file":"tests/models/test_headers.py","line":170,"symbol":"test_sensitive_headers","kind":"function","lang":"python","code":"def test_sensitive_headers(header):\n \"\"\"\n Some headers should be obfuscated because they contain sensitive data.\n \"\"\"\n value = \"s3kr3t\"\n h = httpx.Headers({header: value})\n assert repr(h) == \"Headers({'%s': '[secure]'})\" % header"} {"repo":"httpx","file":"tests/models/test_headers.py","line":187,"symbol":"test_obfuscate_sensitive_headers","kind":"function","lang":"python","code":"def test_obfuscate_sensitive_headers(headers, output):\n as_dict = {k: v for k, v in output}\n headers_class = httpx.Headers({k: v for k, v in headers})\n assert repr(headers_class) == f\"Headers({as_dict!r})\""} {"repo":"httpx","file":"tests/models/test_headers.py","line":212,"symbol":"test_parse_header_links","kind":"function","lang":"python","code":"def test_parse_header_links(value, expected):\n all_links = httpx.Response(200, headers={\"link\": value}).links.values()\n assert all(link in all_links for link in expected)"} {"repo":"httpx","file":"tests/models/test_headers.py","line":217,"symbol":"test_parse_header_links_no_link","kind":"function","lang":"python","code":"def test_parse_header_links_no_link():\n all_links = httpx.Response(200).links\n assert all_links == {}"} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":16,"symbol":"test_queryparams","kind":"function","lang":"python","code":"def test_queryparams(source):\n q = httpx.QueryParams(source)\n assert \"a\" in q\n assert \"A\" not in q\n assert \"c\" not in q\n assert q[\"a\"] == \"123\"\n assert q.get(\"a\") == \"123\"\n assert q.get(\"nope\", default=None) is None\n assert q.get_list(\"a\") == [\"123\", \"456\"]\n\n assert list(q.keys()) == [\"a\", \"b\"]\n assert list(q.values()) == [\"123\", \"789\"]\n assert list(q.items()) == [(\"a\", \"123\"), (\"b\", \"789\")]\n assert len(q) == 2\n assert list(q) == [\"a\", \"b\"]\n assert dict(q) == {\"a\": \"123\", \"b\": \"789\"}\n assert str(q) == \"a=123&a=456&b=789\"\n assert repr(q) == \"QueryParams('a=123&a=456&b=789')\"\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) == httpx.QueryParams(\n [(\"a\", \"123\"), (\"b\", \"456\")]\n )\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) == httpx.QueryParams(\n \"a=123&b=456\"\n )\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) == httpx.QueryParams(\n {\"b\": \"456\", \"a\": \"123\"}\n )\n assert httpx.QueryParams() == httpx.QueryParams({})\n assert httpx.QueryParams([(\"a\", \"123\"), (\"a\", \"456\")]) == httpx.QueryParams(\n \"a=123&a=456\"\n )\n assert httpx.QueryParams({\"a\": \"123\", \"b\": \"456\"}) != \"invali"} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":53,"symbol":"test_queryparam_types","kind":"function","lang":"python","code":"def test_queryparam_types():\n q = httpx.QueryParams(None)\n assert str(q) == \"\"\n\n q = httpx.QueryParams({\"a\": True})\n assert str(q) == \"a=true\"\n\n q = httpx.QueryParams({\"a\": False})\n assert str(q) == \"a=false\"\n\n q = httpx.QueryParams({\"a\": \"\"})\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams({\"a\": None})\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams({\"a\": 1.23})\n assert str(q) == \"a=1.23\"\n\n q = httpx.QueryParams({\"a\": 123})\n assert str(q) == \"a=123\"\n\n q = httpx.QueryParams({\"a\": [1, 2]})\n assert str(q) == \"a=1&a=2\""} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":79,"symbol":"test_empty_query_params","kind":"function","lang":"python","code":"def test_empty_query_params():\n q = httpx.QueryParams({\"a\": \"\"})\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams(\"a=\")\n assert str(q) == \"a=\"\n\n q = httpx.QueryParams(\"a\")\n assert str(q) == \"a=\""} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":90,"symbol":"test_queryparam_update_is_hard_deprecated","kind":"function","lang":"python","code":"def test_queryparam_update_is_hard_deprecated():\n q = httpx.QueryParams(\"a=123\")\n with pytest.raises(RuntimeError):\n q.update({\"a\": \"456\"})"} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":96,"symbol":"test_queryparam_setter_is_hard_deprecated","kind":"function","lang":"python","code":"def test_queryparam_setter_is_hard_deprecated():\n q = httpx.QueryParams(\"a=123\")\n with pytest.raises(RuntimeError):\n q[\"a\"] = \"456\""} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":102,"symbol":"test_queryparam_set","kind":"function","lang":"python","code":"def test_queryparam_set():\n q = httpx.QueryParams(\"a=123\")\n q = q.set(\"a\", \"456\")\n assert q == httpx.QueryParams(\"a=456\")"} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":108,"symbol":"test_queryparam_add","kind":"function","lang":"python","code":"def test_queryparam_add():\n q = httpx.QueryParams(\"a=123\")\n q = q.add(\"a\", \"456\")\n assert q == httpx.QueryParams(\"a=123&a=456\")"} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":114,"symbol":"test_queryparam_remove","kind":"function","lang":"python","code":"def test_queryparam_remove():\n q = httpx.QueryParams(\"a=123\")\n q = q.remove(\"a\")\n assert q == httpx.QueryParams(\"\")"} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":120,"symbol":"test_queryparam_merge","kind":"function","lang":"python","code":"def test_queryparam_merge():\n q = httpx.QueryParams(\"a=123\")\n q = q.merge({\"b\": \"456\"})\n assert q == httpx.QueryParams(\"a=123&b=456\")\n q = q.merge({\"a\": \"000\", \"c\": \"789\"})\n assert q == httpx.QueryParams(\"a=000&b=456&c=789\")"} {"repo":"httpx","file":"tests/models/test_queryparams.py","line":128,"symbol":"test_queryparams_are_hashable","kind":"function","lang":"python","code":"def test_queryparams_are_hashable():\n params = (\n httpx.QueryParams(\"a=123\"),\n httpx.QueryParams({\"a\": 123}),\n httpx.QueryParams(\"b=456\"),\n httpx.QueryParams({\"b\": 456}),\n )\n\n assert len(set(params)) == 2"} {"repo":"httpx","file":"tests/models/test_requests.py","line":9,"symbol":"test_request_repr","kind":"function","lang":"python","code":"def test_request_repr():\n request = httpx.Request(\"GET\", \"http://example.org\")\n assert repr(request) == \"\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":14,"symbol":"test_no_content","kind":"function","lang":"python","code":"def test_no_content():\n request = httpx.Request(\"GET\", \"http://example.org\")\n assert \"Content-Length\" not in request.headers"} {"repo":"httpx","file":"tests/models/test_requests.py","line":19,"symbol":"test_content_length_header","kind":"function","lang":"python","code":"def test_content_length_header():\n request = httpx.Request(\"POST\", \"http://example.org\", content=b\"test 123\")\n assert request.headers[\"Content-Length\"] == \"8\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":24,"symbol":"test_iterable_content","kind":"function","lang":"python","code":"def test_iterable_content():\n class Content:\n def __iter__(self):\n yield b\"test 123\" # pragma: no cover\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=Content())\n assert request.headers == {\"Host\": \"example.org\", \"Transfer-Encoding\": \"chunked\"}"} {"repo":"httpx","file":"tests/models/test_requests.py","line":25,"symbol":"Content","kind":"class","lang":"python","code":"class Content:\n def __iter__(self):\n yield b\"test 123\" # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":26,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self):\n yield b\"test 123\" # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":33,"symbol":"test_generator_with_transfer_encoding_header","kind":"function","lang":"python","code":"def test_generator_with_transfer_encoding_header():\n def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=content())\n assert request.headers == {\"Host\": \"example.org\", \"Transfer-Encoding\": \"chunked\"}"} {"repo":"httpx","file":"tests/models/test_requests.py","line":34,"symbol":"content","kind":"function","lang":"python","code":"def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":41,"symbol":"test_generator_with_content_length_header","kind":"function","lang":"python","code":"def test_generator_with_content_length_header():\n def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover\n\n headers = {\"Content-Length\": \"8\"}\n request = httpx.Request(\n \"POST\", \"http://example.org\", content=content(), headers=headers\n )\n assert request.headers == {\"Host\": \"example.org\", \"Content-Length\": \"8\"}"} {"repo":"httpx","file":"tests/models/test_requests.py","line":42,"symbol":"content","kind":"function","lang":"python","code":"def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":52,"symbol":"test_url_encoded_data","kind":"function","lang":"python","code":"def test_url_encoded_data():\n request = httpx.Request(\"POST\", \"http://example.org\", data={\"test\": \"123\"})\n request.read()\n\n assert request.headers[\"Content-Type\"] == \"application/x-www-form-urlencoded\"\n assert request.content == b\"test=123\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":60,"symbol":"test_json_encoded_data","kind":"function","lang":"python","code":"def test_json_encoded_data():\n request = httpx.Request(\"POST\", \"http://example.org\", json={\"test\": 123})\n request.read()\n\n assert request.headers[\"Content-Type\"] == \"application/json\"\n assert request.content == b'{\"test\":123}'"} {"repo":"httpx","file":"tests/models/test_requests.py","line":68,"symbol":"test_headers","kind":"function","lang":"python","code":"def test_headers():\n request = httpx.Request(\"POST\", \"http://example.org\", json={\"test\": 123})\n\n assert request.headers == {\n \"Host\": \"example.org\",\n \"Content-Type\": \"application/json\",\n \"Content-Length\": \"12\",\n }"} {"repo":"httpx","file":"tests/models/test_requests.py","line":78,"symbol":"test_read_and_stream_data","kind":"function","lang":"python","code":"def test_read_and_stream_data():\n # Ensure a request may still be streamed if it has been read.\n # Needed for cases such as authentication classes that read the request body.\n request = httpx.Request(\"POST\", \"http://example.org\", json={\"test\": 123})\n request.read()\n assert request.stream is not None\n assert isinstance(request.stream, typing.Iterable)\n content = b\"\".join(list(request.stream))\n assert content == request.content"} {"repo":"httpx","file":"tests/models/test_requests.py","line":90,"symbol":"test_aread_and_stream_data","kind":"function","lang":"python","code":"async def test_aread_and_stream_data():\n # Ensure a request may still be streamed if it has been read.\n # Needed for cases such as authentication classes that read the request body.\n request = httpx.Request(\"POST\", \"http://example.org\", json={\"test\": 123})\n await request.aread()\n assert request.stream is not None\n assert isinstance(request.stream, typing.AsyncIterable)\n content = b\"\".join([part async for part in request.stream])\n assert content == request.content"} {"repo":"httpx","file":"tests/models/test_requests.py","line":101,"symbol":"test_cannot_access_streaming_content_without_read","kind":"function","lang":"python","code":"def test_cannot_access_streaming_content_without_read():\n # Ensure that streaming requests\n def streaming_body() -> typing.Iterator[bytes]: # pragma: no cover\n yield b\"\"\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=streaming_body())\n with pytest.raises(httpx.RequestNotRead):\n request.content # noqa: B018"} {"repo":"httpx","file":"tests/models/test_requests.py","line":103,"symbol":"streaming_body","kind":"function","lang":"python","doc":"Ensure that streaming requests","code":"def streaming_body() -> typing.Iterator[bytes]: # pragma: no cover\n yield b\"\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":111,"symbol":"test_transfer_encoding_header","kind":"function","lang":"python","code":"def test_transfer_encoding_header():\n async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:\n yield data # pragma: no cover\n\n data = streaming_body(b\"test 123\")\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=data)\n assert \"Content-Length\" not in request.headers\n assert request.headers[\"Transfer-Encoding\"] == \"chunked\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":112,"symbol":"streaming_body","kind":"function","lang":"python","code":"async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:\n yield data # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":122,"symbol":"test_ignore_transfer_encoding_header_if_content_length_exists","kind":"function","lang":"python","code":"def test_ignore_transfer_encoding_header_if_content_length_exists():\n \"\"\"\n `Transfer-Encoding` should be ignored if `Content-Length` has been set explicitly.\n See https://github.com/encode/httpx/issues/1168\n \"\"\"\n\n def streaming_body(data: bytes) -> typing.Iterator[bytes]:\n yield data # pragma: no cover\n\n data = streaming_body(b\"abcd\")\n\n headers = {\"Content-Length\": \"4\"}\n request = httpx.Request(\"POST\", \"http://example.org\", content=data, headers=headers)\n assert \"Transfer-Encoding\" not in request.headers\n assert request.headers[\"Content-Length\"] == \"4\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":128,"symbol":"streaming_body","kind":"function","lang":"python","code":"def streaming_body(data: bytes) -> typing.Iterator[bytes]:\n yield data # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":139,"symbol":"test_override_host_header","kind":"function","lang":"python","code":"def test_override_host_header():\n headers = {\"host\": \"1.2.3.4:80\"}\n\n request = httpx.Request(\"GET\", \"http://example.org\", headers=headers)\n assert request.headers[\"Host\"] == \"1.2.3.4:80\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":146,"symbol":"test_override_accept_encoding_header","kind":"function","lang":"python","code":"def test_override_accept_encoding_header():\n headers = {\"Accept-Encoding\": \"identity\"}\n\n request = httpx.Request(\"GET\", \"http://example.org\", headers=headers)\n assert request.headers[\"Accept-Encoding\"] == \"identity\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":153,"symbol":"test_override_content_length_header","kind":"function","lang":"python","code":"def test_override_content_length_header():\n async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:\n yield data # pragma: no cover\n\n data = streaming_body(b\"test 123\")\n headers = {\"Content-Length\": \"8\"}\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=data, headers=headers)\n assert request.headers[\"Content-Length\"] == \"8\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":154,"symbol":"streaming_body","kind":"function","lang":"python","code":"async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:\n yield data # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":164,"symbol":"test_url","kind":"function","lang":"python","code":"def test_url():\n url = \"http://example.org\"\n request = httpx.Request(\"GET\", url)\n assert request.url.scheme == \"http\"\n assert request.url.port is None\n assert request.url.path == \"/\"\n assert request.url.raw_path == b\"/\"\n\n url = \"https://example.org/abc?foo=bar\"\n request = httpx.Request(\"GET\", url)\n assert request.url.scheme == \"https\"\n assert request.url.port is None\n assert request.url.path == \"/abc\"\n assert request.url.raw_path == b\"/abc?foo=bar\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":180,"symbol":"test_request_picklable","kind":"function","lang":"python","code":"def test_request_picklable():\n request = httpx.Request(\"POST\", \"http://example.org\", json={\"test\": 123})\n pickle_request = pickle.loads(pickle.dumps(request))\n assert pickle_request.method == \"POST\"\n assert pickle_request.url.path == \"/\"\n assert pickle_request.headers[\"Content-Type\"] == \"application/json\"\n assert pickle_request.content == b'{\"test\":123}'\n assert pickle_request.stream is not None\n assert request.headers == {\n \"Host\": \"example.org\",\n \"Content-Type\": \"application/json\",\n \"content-length\": \"12\",\n }"} {"repo":"httpx","file":"tests/models/test_requests.py","line":196,"symbol":"test_request_async_streaming_content_picklable","kind":"function","lang":"python","code":"async def test_request_async_streaming_content_picklable():\n async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:\n yield data\n\n data = streaming_body(b\"test 123\")\n request = httpx.Request(\"POST\", \"http://example.org\", content=data)\n pickle_request = pickle.loads(pickle.dumps(request))\n with pytest.raises(httpx.RequestNotRead):\n pickle_request.content # noqa: B018\n with pytest.raises(httpx.StreamClosed):\n await pickle_request.aread()\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=data)\n await request.aread()\n pickle_request = pickle.loads(pickle.dumps(request))\n assert pickle_request.content == b\"test 123\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":197,"symbol":"streaming_body","kind":"function","lang":"python","code":"async def streaming_body(data: bytes) -> typing.AsyncIterator[bytes]:\n yield data"} {"repo":"httpx","file":"tests/models/test_requests.py","line":214,"symbol":"test_request_generator_content_picklable","kind":"function","lang":"python","code":"def test_request_generator_content_picklable():\n def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=content())\n pickle_request = pickle.loads(pickle.dumps(request))\n with pytest.raises(httpx.RequestNotRead):\n pickle_request.content # noqa: B018\n with pytest.raises(httpx.StreamClosed):\n pickle_request.read()\n\n request = httpx.Request(\"POST\", \"http://example.org\", content=content())\n request.read()\n pickle_request = pickle.loads(pickle.dumps(request))\n assert pickle_request.content == b\"test 123\""} {"repo":"httpx","file":"tests/models/test_requests.py","line":215,"symbol":"content","kind":"function","lang":"python","code":"def content() -> typing.Iterator[bytes]:\n yield b\"test 123\" # pragma: no cover"} {"repo":"httpx","file":"tests/models/test_requests.py","line":231,"symbol":"test_request_params","kind":"function","lang":"python","code":"def test_request_params():\n request = httpx.Request(\"GET\", \"http://example.com\", params={})\n assert str(request.url) == \"http://example.com\"\n\n request = httpx.Request(\n \"GET\", \"http://example.com?c=3\", params={\"a\": \"1\", \"b\": \"2\"}\n )\n assert str(request.url) == \"http://example.com?a=1&b=2\"\n\n request = httpx.Request(\"GET\", \"http://example.com?a=1\", params={})\n assert str(request.url) == \"http://example.com\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":11,"symbol":"StreamingBody","kind":"class","lang":"python","code":"class StreamingBody:\n def __iter__(self):\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":12,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self):\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":17,"symbol":"streaming_body","kind":"function","lang":"python","code":"def streaming_body() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":22,"symbol":"async_streaming_body","kind":"function","lang":"python","code":"async def async_streaming_body() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":27,"symbol":"autodetect","kind":"function","lang":"python","code":"def autodetect(content):\n return chardet.detect(content).get(\"encoding\")"} {"repo":"httpx","file":"tests/models/test_responses.py","line":31,"symbol":"test_response","kind":"function","lang":"python","code":"def test_response():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n request=httpx.Request(\"GET\", \"https://example.org\"),\n )\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.request.method == \"GET\"\n assert response.request.url == \"https://example.org\"\n assert not response.is_error"} {"repo":"httpx","file":"tests/models/test_responses.py","line":46,"symbol":"test_response_content","kind":"function","lang":"python","code":"def test_response_content():\n response = httpx.Response(200, content=\"Hello, world!\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.headers == {\"Content-Length\": \"13\"}"} {"repo":"httpx","file":"tests/models/test_responses.py","line":55,"symbol":"test_response_text","kind":"function","lang":"python","code":"def test_response_text():\n response = httpx.Response(200, text=\"Hello, world!\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.headers == {\n \"Content-Length\": \"13\",\n \"Content-Type\": \"text/plain; charset=utf-8\",\n }"} {"repo":"httpx","file":"tests/models/test_responses.py","line":67,"symbol":"test_response_html","kind":"function","lang":"python","code":"def test_response_html():\n response = httpx.Response(200, html=\"Hello, world!\")\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.headers == {\n \"Content-Length\": \"39\",\n \"Content-Type\": \"text/html; charset=utf-8\",\n }"} {"repo":"httpx","file":"tests/models/test_responses.py","line":79,"symbol":"test_response_json","kind":"function","lang":"python","code":"def test_response_json():\n response = httpx.Response(200, json={\"hello\": \"world\"})\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert str(response.json()) == \"{'hello': 'world'}\"\n assert response.headers == {\n \"Content-Length\": \"17\",\n \"Content-Type\": \"application/json\",\n }"} {"repo":"httpx","file":"tests/models/test_responses.py","line":91,"symbol":"test_raise_for_status","kind":"function","lang":"python","code":"def test_raise_for_status():\n request = httpx.Request(\"GET\", \"https://example.org\")\n\n # 2xx status codes are not an error.\n response = httpx.Response(200, request=request)\n response.raise_for_status()\n\n # 1xx status codes are informational responses.\n response = httpx.Response(101, request=request)\n assert response.is_informational\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert str(exc_info.value) == (\n \"Informational response '101 Switching Protocols' for url 'https://example.org'\\n\"\n \"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/101\"\n )\n\n # 3xx status codes are redirections.\n headers = {\"location\": \"https://other.org\"}\n response = httpx.Response(303, headers=headers, request=request)\n assert response.is_redirect\n with pytest.raises(httpx.HTTPStatusError) as exc_info:\n response.raise_for_status()\n assert str(exc_info.value) == (\n \"Redirect response '303 See Other' for url 'https://example.org'\\n\"\n \"Redirect location: 'https://other.org'\\n\"\n \"For more information check: https://developer.mozilla.org/en"} {"repo":"httpx","file":"tests/models/test_responses.py","line":149,"symbol":"test_response_repr","kind":"function","lang":"python","code":"def test_response_repr():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n assert repr(response) == \"\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":157,"symbol":"test_response_content_type_encoding","kind":"function","lang":"python","code":"def test_response_content_type_encoding():\n \"\"\"\n Use the charset encoding in the Content-Type header if possible.\n \"\"\"\n headers = {\"Content-Type\": \"text-plain; charset=latin-1\"}\n content = \"Latin 1: ÿ\".encode(\"latin-1\")\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.text == \"Latin 1: ÿ\"\n assert response.encoding == \"latin-1\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":172,"symbol":"test_response_default_to_utf8_encoding","kind":"function","lang":"python","code":"def test_response_default_to_utf8_encoding():\n \"\"\"\n Default to utf-8 encoding if there is no Content-Type header.\n \"\"\"\n content = \"おはようございます。\".encode(\"utf-8\")\n response = httpx.Response(\n 200,\n content=content,\n )\n assert response.text == \"おはようございます。\"\n assert response.encoding == \"utf-8\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":185,"symbol":"test_response_fallback_to_utf8_encoding","kind":"function","lang":"python","code":"def test_response_fallback_to_utf8_encoding():\n \"\"\"\n Fallback to utf-8 if we get an invalid charset in the Content-Type header.\n \"\"\"\n headers = {\"Content-Type\": \"text-plain; charset=invalid-codec-name\"}\n content = \"おはようございます。\".encode(\"utf-8\")\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.text == \"おはようございます。\"\n assert response.encoding == \"utf-8\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":200,"symbol":"test_response_no_charset_with_ascii_content","kind":"function","lang":"python","code":"def test_response_no_charset_with_ascii_content():\n \"\"\"\n A response with ascii encoded content should decode correctly,\n even with no charset specified.\n \"\"\"\n content = b\"Hello, world!\"\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.status_code == 200\n assert response.encoding == \"utf-8\"\n assert response.text == \"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":217,"symbol":"test_response_no_charset_with_utf8_content","kind":"function","lang":"python","code":"def test_response_no_charset_with_utf8_content():\n \"\"\"\n A response with UTF-8 encoded content should decode correctly,\n even with no charset specified.\n \"\"\"\n content = \"Unicode Snowman: ☃\".encode(\"utf-8\")\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200,\n content=content,\n headers=headers,\n )\n assert response.text == \"Unicode Snowman: ☃\"\n assert response.encoding == \"utf-8\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":233,"symbol":"test_response_no_charset_with_iso_8859_1_content","kind":"function","lang":"python","code":"def test_response_no_charset_with_iso_8859_1_content():\n \"\"\"\n A response with ISO 8859-1 encoded content should decode correctly,\n even with no charset specified, if autodetect is enabled.\n \"\"\"\n content = \"Accented: Österreich abcdefghijklmnopqrstuzwxyz\".encode(\"iso-8859-1\")\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200, content=content, headers=headers, default_encoding=autodetect\n )\n assert response.text == \"Accented: Österreich abcdefghijklmnopqrstuzwxyz\"\n assert response.charset_encoding is None"} {"repo":"httpx","file":"tests/models/test_responses.py","line":247,"symbol":"test_response_no_charset_with_cp_1252_content","kind":"function","lang":"python","code":"def test_response_no_charset_with_cp_1252_content():\n \"\"\"\n A response with Windows 1252 encoded content should decode correctly,\n even with no charset specified, if autodetect is enabled.\n \"\"\"\n content = \"Euro Currency: € abcdefghijklmnopqrstuzwxyz\".encode(\"cp1252\")\n headers = {\"Content-Type\": \"text/plain\"}\n response = httpx.Response(\n 200, content=content, headers=headers, default_encoding=autodetect\n )\n assert response.text == \"Euro Currency: € abcdefghijklmnopqrstuzwxyz\"\n assert response.charset_encoding is None"} {"repo":"httpx","file":"tests/models/test_responses.py","line":261,"symbol":"test_response_non_text_encoding","kind":"function","lang":"python","code":"def test_response_non_text_encoding():\n \"\"\"\n Default to attempting utf-8 encoding for non-text content-type headers.\n \"\"\"\n headers = {\"Content-Type\": \"image/png\"}\n response = httpx.Response(\n 200,\n content=b\"xyz\",\n headers=headers,\n )\n assert response.text == \"xyz\"\n assert response.encoding == \"utf-8\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":275,"symbol":"test_response_set_explicit_encoding","kind":"function","lang":"python","code":"def test_response_set_explicit_encoding():\n headers = {\n \"Content-Type\": \"text-plain; charset=utf-8\"\n } # Deliberately incorrect charset\n response = httpx.Response(\n 200,\n content=\"Latin 1: ÿ\".encode(\"latin-1\"),\n headers=headers,\n )\n response.encoding = \"latin-1\"\n assert response.text == \"Latin 1: ÿ\"\n assert response.encoding == \"latin-1\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":289,"symbol":"test_response_force_encoding","kind":"function","lang":"python","code":"def test_response_force_encoding():\n response = httpx.Response(\n 200,\n content=\"Snowman: ☃\".encode(\"utf-8\"),\n )\n response.encoding = \"iso-8859-1\"\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Snowman: â\\x98\\x83\"\n assert response.encoding == \"iso-8859-1\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":301,"symbol":"test_response_force_encoding_after_text_accessed","kind":"function","lang":"python","code":"def test_response_force_encoding_after_text_accessed():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.encoding == \"utf-8\"\n\n with pytest.raises(ValueError):\n response.encoding = \"UTF8\"\n\n with pytest.raises(ValueError):\n response.encoding = \"iso-8859-1\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":318,"symbol":"test_read","kind":"function","lang":"python","code":"def test_read():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n assert response.status_code == 200\n assert response.text == \"Hello, world!\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = response.read()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed"} {"repo":"httpx","file":"tests/models/test_responses.py","line":336,"symbol":"test_empty_read","kind":"function","lang":"python","code":"def test_empty_read():\n response = httpx.Response(200)\n\n assert response.status_code == 200\n assert response.text == \"\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = response.read()\n\n assert content == b\"\"\n assert response.content == b\"\"\n assert response.is_closed"} {"repo":"httpx","file":"tests/models/test_responses.py","line":352,"symbol":"test_aread","kind":"function","lang":"python","code":"async def test_aread():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n assert response.status_code == 200\n assert response.text == \"Hello, world!\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = await response.aread()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed"} {"repo":"httpx","file":"tests/models/test_responses.py","line":371,"symbol":"test_empty_aread","kind":"function","lang":"python","code":"async def test_empty_aread():\n response = httpx.Response(200)\n\n assert response.status_code == 200\n assert response.text == \"\"\n assert response.encoding == \"utf-8\"\n assert response.is_closed\n\n content = await response.aread()\n\n assert content == b\"\"\n assert response.content == b\"\"\n assert response.is_closed"} {"repo":"httpx","file":"tests/models/test_responses.py","line":386,"symbol":"test_iter_raw","kind":"function","lang":"python","code":"def test_iter_raw():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n raw = b\"\"\n for part in response.iter_raw():\n raw += part\n assert raw == b\"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":398,"symbol":"test_iter_raw_with_chunksize","kind":"function","lang":"python","code":"def test_iter_raw_with_chunksize():\n response = httpx.Response(200, content=streaming_body())\n parts = list(response.iter_raw(chunk_size=5))\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = list(response.iter_raw(chunk_size=7))\n assert parts == [b\"Hello, \", b\"world!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = list(response.iter_raw(chunk_size=13))\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = list(response.iter_raw(chunk_size=20))\n assert parts == [b\"Hello, world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":416,"symbol":"test_iter_raw_doesnt_return_empty_chunks","kind":"function","lang":"python","code":"def test_iter_raw_doesnt_return_empty_chunks():\n def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"\"\n yield b\"world!\"\n yield b\"\"\n\n response = httpx.Response(200, content=streaming_body_with_empty_chunks())\n\n parts = list(response.iter_raw())\n assert parts == [b\"Hello, \", b\"world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":417,"symbol":"streaming_body_with_empty_chunks","kind":"function","lang":"python","code":"def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"\"\n yield b\"world!\"\n yield b\"\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":429,"symbol":"test_iter_raw_on_iterable","kind":"function","lang":"python","code":"def test_iter_raw_on_iterable():\n response = httpx.Response(\n 200,\n content=StreamingBody(),\n )\n\n raw = b\"\"\n for part in response.iter_raw():\n raw += part\n assert raw == b\"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":441,"symbol":"test_iter_raw_on_async","kind":"function","lang":"python","code":"def test_iter_raw_on_async():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n list(response.iter_raw())"} {"repo":"httpx","file":"tests/models/test_responses.py","line":451,"symbol":"test_close_on_async","kind":"function","lang":"python","code":"def test_close_on_async():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n response.close()"} {"repo":"httpx","file":"tests/models/test_responses.py","line":461,"symbol":"test_iter_raw_increments_updates_counter","kind":"function","lang":"python","code":"def test_iter_raw_increments_updates_counter():\n response = httpx.Response(200, content=streaming_body())\n\n num_downloaded = response.num_bytes_downloaded\n for part in response.iter_raw():\n assert len(part) == (response.num_bytes_downloaded - num_downloaded)\n num_downloaded = response.num_bytes_downloaded"} {"repo":"httpx","file":"tests/models/test_responses.py","line":471,"symbol":"test_aiter_raw","kind":"function","lang":"python","code":"async def test_aiter_raw():\n response = httpx.Response(200, content=async_streaming_body())\n\n raw = b\"\"\n async for part in response.aiter_raw():\n raw += part\n assert raw == b\"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":481,"symbol":"test_aiter_raw_with_chunksize","kind":"function","lang":"python","code":"async def test_aiter_raw_with_chunksize():\n response = httpx.Response(200, content=async_streaming_body())\n\n parts = [part async for part in response.aiter_raw(chunk_size=5)]\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n\n parts = [part async for part in response.aiter_raw(chunk_size=13)]\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n\n parts = [part async for part in response.aiter_raw(chunk_size=20)]\n assert parts == [b\"Hello, world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":499,"symbol":"test_aiter_raw_on_sync","kind":"function","lang":"python","code":"async def test_aiter_raw_on_sync():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n [part async for part in response.aiter_raw()]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":510,"symbol":"test_aclose_on_sync","kind":"function","lang":"python","code":"async def test_aclose_on_sync():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n await response.aclose()"} {"repo":"httpx","file":"tests/models/test_responses.py","line":521,"symbol":"test_aiter_raw_increments_updates_counter","kind":"function","lang":"python","code":"async def test_aiter_raw_increments_updates_counter():\n response = httpx.Response(200, content=async_streaming_body())\n\n num_downloaded = response.num_bytes_downloaded\n async for part in response.aiter_raw():\n assert len(part) == (response.num_bytes_downloaded - num_downloaded)\n num_downloaded = response.num_bytes_downloaded"} {"repo":"httpx","file":"tests/models/test_responses.py","line":530,"symbol":"test_iter_bytes","kind":"function","lang":"python","code":"def test_iter_bytes():\n response = httpx.Response(200, content=b\"Hello, world!\")\n\n content = b\"\"\n for part in response.iter_bytes():\n content += part\n assert content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":539,"symbol":"test_iter_bytes_with_chunk_size","kind":"function","lang":"python","code":"def test_iter_bytes_with_chunk_size():\n response = httpx.Response(200, content=streaming_body())\n parts = list(response.iter_bytes(chunk_size=5))\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = list(response.iter_bytes(chunk_size=13))\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=streaming_body())\n parts = list(response.iter_bytes(chunk_size=20))\n assert parts == [b\"Hello, world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":553,"symbol":"test_iter_bytes_with_empty_response","kind":"function","lang":"python","code":"def test_iter_bytes_with_empty_response():\n response = httpx.Response(200, content=b\"\")\n parts = list(response.iter_bytes())\n assert parts == []"} {"repo":"httpx","file":"tests/models/test_responses.py","line":559,"symbol":"test_iter_bytes_doesnt_return_empty_chunks","kind":"function","lang":"python","code":"def test_iter_bytes_doesnt_return_empty_chunks():\n def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"\"\n yield b\"world!\"\n yield b\"\"\n\n response = httpx.Response(200, content=streaming_body_with_empty_chunks())\n\n parts = list(response.iter_bytes())\n assert parts == [b\"Hello, \", b\"world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":560,"symbol":"streaming_body_with_empty_chunks","kind":"function","lang":"python","code":"def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"\"\n yield b\"world!\"\n yield b\"\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":573,"symbol":"test_aiter_bytes","kind":"function","lang":"python","code":"async def test_aiter_bytes():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n content = b\"\"\n async for part in response.aiter_bytes():\n content += part\n assert content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":586,"symbol":"test_aiter_bytes_with_chunk_size","kind":"function","lang":"python","code":"async def test_aiter_bytes_with_chunk_size():\n response = httpx.Response(200, content=async_streaming_body())\n parts = [part async for part in response.aiter_bytes(chunk_size=5)]\n assert parts == [b\"Hello\", b\", wor\", b\"ld!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n parts = [part async for part in response.aiter_bytes(chunk_size=13)]\n assert parts == [b\"Hello, world!\"]\n\n response = httpx.Response(200, content=async_streaming_body())\n parts = [part async for part in response.aiter_bytes(chunk_size=20)]\n assert parts == [b\"Hello, world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":600,"symbol":"test_iter_text","kind":"function","lang":"python","code":"def test_iter_text():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n content = \"\"\n for part in response.iter_text():\n content += part\n assert content == \"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":612,"symbol":"test_iter_text_with_chunk_size","kind":"function","lang":"python","code":"def test_iter_text_with_chunk_size():\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = list(response.iter_text(chunk_size=5))\n assert parts == [\"Hello\", \", wor\", \"ld!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!!\")\n parts = list(response.iter_text(chunk_size=7))\n assert parts == [\"Hello, \", \"world!!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = list(response.iter_text(chunk_size=7))\n assert parts == [\"Hello, \", \"world!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = list(response.iter_text(chunk_size=13))\n assert parts == [\"Hello, world!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = list(response.iter_text(chunk_size=20))\n assert parts == [\"Hello, world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":635,"symbol":"test_aiter_text","kind":"function","lang":"python","code":"async def test_aiter_text():\n response = httpx.Response(\n 200,\n content=b\"Hello, world!\",\n )\n\n content = \"\"\n async for part in response.aiter_text():\n content += part\n assert content == \"Hello, world!\""} {"repo":"httpx","file":"tests/models/test_responses.py","line":648,"symbol":"test_aiter_text_with_chunk_size","kind":"function","lang":"python","code":"async def test_aiter_text_with_chunk_size():\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part async for part in response.aiter_text(chunk_size=5)]\n assert parts == [\"Hello\", \", wor\", \"ld!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part async for part in response.aiter_text(chunk_size=13)]\n assert parts == [\"Hello, world!\"]\n\n response = httpx.Response(200, content=b\"Hello, world!\")\n parts = [part async for part in response.aiter_text(chunk_size=20)]\n assert parts == [\"Hello, world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":662,"symbol":"test_iter_lines","kind":"function","lang":"python","code":"def test_iter_lines():\n response = httpx.Response(\n 200,\n content=b\"Hello,\\nworld!\",\n )\n content = list(response.iter_lines())\n assert content == [\"Hello,\", \"world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":672,"symbol":"test_aiter_lines","kind":"function","lang":"python","code":"async def test_aiter_lines():\n response = httpx.Response(\n 200,\n content=b\"Hello,\\nworld!\",\n )\n\n content = []\n async for line in response.aiter_lines():\n content.append(line)\n assert content == [\"Hello,\", \"world!\"]"} {"repo":"httpx","file":"tests/models/test_responses.py","line":684,"symbol":"test_sync_streaming_response","kind":"function","lang":"python","code":"def test_sync_streaming_response():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n assert response.status_code == 200\n assert not response.is_closed\n\n content = response.read()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed"} {"repo":"httpx","file":"tests/models/test_responses.py","line":701,"symbol":"test_async_streaming_response","kind":"function","lang":"python","code":"async def test_async_streaming_response():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n assert response.status_code == 200\n assert not response.is_closed\n\n content = await response.aread()\n\n assert content == b\"Hello, world!\"\n assert response.content == b\"Hello, world!\"\n assert response.is_closed"} {"repo":"httpx","file":"tests/models/test_responses.py","line":717,"symbol":"test_cannot_read_after_stream_consumed","kind":"function","lang":"python","code":"def test_cannot_read_after_stream_consumed():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n content = b\"\"\n for part in response.iter_bytes():\n content += part\n\n with pytest.raises(httpx.StreamConsumed):\n response.read()"} {"repo":"httpx","file":"tests/models/test_responses.py","line":732,"symbol":"test_cannot_aread_after_stream_consumed","kind":"function","lang":"python","code":"async def test_cannot_aread_after_stream_consumed():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n content = b\"\"\n async for part in response.aiter_bytes():\n content += part\n\n with pytest.raises(httpx.StreamConsumed):\n await response.aread()"} {"repo":"httpx","file":"tests/models/test_responses.py","line":746,"symbol":"test_cannot_read_after_response_closed","kind":"function","lang":"python","code":"def test_cannot_read_after_response_closed():\n response = httpx.Response(\n 200,\n content=streaming_body(),\n )\n\n response.close()\n with pytest.raises(httpx.StreamClosed):\n response.read()"} {"repo":"httpx","file":"tests/models/test_responses.py","line":758,"symbol":"test_cannot_aread_after_response_closed","kind":"function","lang":"python","code":"async def test_cannot_aread_after_response_closed():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n await response.aclose()\n with pytest.raises(httpx.StreamClosed):\n await response.aread()"} {"repo":"httpx","file":"tests/models/test_responses.py","line":770,"symbol":"test_elapsed_not_available_until_closed","kind":"function","lang":"python","code":"async def test_elapsed_not_available_until_closed():\n response = httpx.Response(\n 200,\n content=async_streaming_body(),\n )\n\n with pytest.raises(RuntimeError):\n response.elapsed # noqa: B018"} {"repo":"httpx","file":"tests/models/test_url.py","line":8,"symbol":"test_basic_url","kind":"function","lang":"python","code":"def test_basic_url():\n url = httpx.URL(\"https://www.example.com/\")\n\n assert url.scheme == \"https\"\n assert url.userinfo == b\"\"\n assert url.netloc == b\"www.example.com\"\n assert url.host == \"www.example.com\"\n assert url.port is None\n assert url.path == \"/\"\n assert url.query == b\"\"\n assert url.fragment == \"\"\n\n assert str(url) == \"https://www.example.com/\"\n assert repr(url) == \"URL('https://www.example.com/')\""} {"repo":"httpx","file":"tests/models/test_url.py","line":24,"symbol":"test_complete_url","kind":"function","lang":"python","code":"def test_complete_url():\n url = httpx.URL(\"https://example.org:123/path/to/somewhere?abc=123#anchor\")\n assert url.scheme == \"https\"\n assert url.host == \"example.org\"\n assert url.port == 123\n assert url.path == \"/path/to/somewhere\"\n assert url.query == b\"abc=123\"\n assert url.raw_path == b\"/path/to/somewhere?abc=123\"\n assert url.fragment == \"anchor\"\n\n assert str(url) == \"https://example.org:123/path/to/somewhere?abc=123#anchor\"\n assert (\n repr(url) == \"URL('https://example.org:123/path/to/somewhere?abc=123#anchor')\"\n )"} {"repo":"httpx","file":"tests/models/test_url.py","line":40,"symbol":"test_url_with_empty_query","kind":"function","lang":"python","code":"def test_url_with_empty_query():\n \"\"\"\n URLs with and without a trailing `?` but an empty query component\n should preserve the information on the raw path.\n \"\"\"\n url = httpx.URL(\"https://www.example.com/path\")\n assert url.path == \"/path\"\n assert url.query == b\"\"\n assert url.raw_path == b\"/path\"\n\n url = httpx.URL(\"https://www.example.com/path?\")\n assert url.path == \"/path\"\n assert url.query == b\"\"\n assert url.raw_path == b\"/path?\""} {"repo":"httpx","file":"tests/models/test_url.py","line":56,"symbol":"test_url_no_scheme","kind":"function","lang":"python","code":"def test_url_no_scheme():\n url = httpx.URL(\"://example.com\")\n assert url.scheme == \"\"\n assert url.host == \"example.com\"\n assert url.path == \"/\""} {"repo":"httpx","file":"tests/models/test_url.py","line":63,"symbol":"test_url_no_authority","kind":"function","lang":"python","code":"def test_url_no_authority():\n url = httpx.URL(\"http://\")\n assert url.scheme == \"http\"\n assert url.host == \"\"\n assert url.path == \"/\""} {"repo":"httpx","file":"tests/models/test_url.py","line":135,"symbol":"test_path_query_fragment","kind":"function","lang":"python","code":"def test_path_query_fragment(url, raw_path, path, query, fragment):\n url = httpx.URL(url)\n assert url.raw_path == raw_path\n assert url.path == path\n assert url.query == query\n assert url.fragment == fragment"} {"repo":"httpx","file":"tests/models/test_url.py","line":143,"symbol":"test_url_query_encoding","kind":"function","lang":"python","code":"def test_url_query_encoding():\n url = httpx.URL(\"https://www.example.com/?a=b c&d=e/f\")\n assert url.raw_path == b\"/?a=b%20c&d=e/f\"\n\n url = httpx.URL(\"https://www.example.com/?a=b+c&d=e/f\")\n assert url.raw_path == b\"/?a=b+c&d=e/f\"\n\n url = httpx.URL(\"https://www.example.com/\", params={\"a\": \"b c\", \"d\": \"e/f\"})\n assert url.raw_path == b\"/?a=b+c&d=e%2Ff\""} {"repo":"httpx","file":"tests/models/test_url.py","line":154,"symbol":"test_url_params","kind":"function","lang":"python","code":"def test_url_params():\n url = httpx.URL(\"https://example.org:123/path/to/somewhere\", params={\"a\": \"123\"})\n assert str(url) == \"https://example.org:123/path/to/somewhere?a=123\"\n assert url.params == httpx.QueryParams({\"a\": \"123\"})\n\n url = httpx.URL(\n \"https://example.org:123/path/to/somewhere?b=456\", params={\"a\": \"123\"}\n )\n assert str(url) == \"https://example.org:123/path/to/somewhere?a=123\"\n assert url.params == httpx.QueryParams({\"a\": \"123\"})"} {"repo":"httpx","file":"tests/models/test_url.py","line":207,"symbol":"test_url_username_and_password","kind":"function","lang":"python","code":"def test_url_username_and_password(url, userinfo, username, password):\n url = httpx.URL(url)\n assert url.userinfo == userinfo\n assert url.username == username\n assert url.password == password"} {"repo":"httpx","file":"tests/models/test_url.py","line":217,"symbol":"test_url_valid_host","kind":"function","lang":"python","code":"def test_url_valid_host():\n url = httpx.URL(\"https://example.com/\")\n assert url.host == \"example.com\""} {"repo":"httpx","file":"tests/models/test_url.py","line":222,"symbol":"test_url_normalized_host","kind":"function","lang":"python","code":"def test_url_normalized_host():\n url = httpx.URL(\"https://EXAMPLE.com/\")\n assert url.host == \"example.com\""} {"repo":"httpx","file":"tests/models/test_url.py","line":227,"symbol":"test_url_percent_escape_host","kind":"function","lang":"python","code":"def test_url_percent_escape_host():\n url = httpx.URL(\"https://exam le.com/\")\n assert url.host == \"exam%20le.com\""} {"repo":"httpx","file":"tests/models/test_url.py","line":232,"symbol":"test_url_ipv4_like_host","kind":"function","lang":"python","code":"def test_url_ipv4_like_host():\n \"\"\"rare host names used to quality as IPv4\"\"\"\n url = httpx.URL(\"https://023b76x43144/\")\n assert url.host == \"023b76x43144\""} {"repo":"httpx","file":"tests/models/test_url.py","line":241,"symbol":"test_url_valid_port","kind":"function","lang":"python","code":"def test_url_valid_port():\n url = httpx.URL(\"https://example.com:123/\")\n assert url.port == 123"} {"repo":"httpx","file":"tests/models/test_url.py","line":246,"symbol":"test_url_normalized_port","kind":"function","lang":"python","code":"def test_url_normalized_port():\n # If the port matches the scheme default it is normalized to None.\n url = httpx.URL(\"https://example.com:443/\")\n assert url.port is None"} {"repo":"httpx","file":"tests/models/test_url.py","line":252,"symbol":"test_url_invalid_port","kind":"function","lang":"python","code":"def test_url_invalid_port():\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(\"https://example.com:abc/\")\n assert str(exc.value) == \"Invalid port: 'abc'\""} {"repo":"httpx","file":"tests/models/test_url.py","line":261,"symbol":"test_url_normalized_path","kind":"function","lang":"python","code":"def test_url_normalized_path():\n url = httpx.URL(\"https://example.com/abc/def/../ghi/./jkl\")\n assert url.path == \"/abc/ghi/jkl\""} {"repo":"httpx","file":"tests/models/test_url.py","line":266,"symbol":"test_url_escaped_path","kind":"function","lang":"python","code":"def test_url_escaped_path():\n url = httpx.URL(\"https://example.com/ /🌟/\")\n assert url.raw_path == b\"/%20/%F0%9F%8C%9F/\""} {"repo":"httpx","file":"tests/models/test_url.py","line":271,"symbol":"test_url_leading_dot_prefix_on_absolute_url","kind":"function","lang":"python","code":"def test_url_leading_dot_prefix_on_absolute_url():\n url = httpx.URL(\"https://example.com/../abc\")\n assert url.path == \"/abc\""} {"repo":"httpx","file":"tests/models/test_url.py","line":276,"symbol":"test_url_leading_dot_prefix_on_relative_url","kind":"function","lang":"python","code":"def test_url_leading_dot_prefix_on_relative_url():\n url = httpx.URL(\"../abc\")\n assert url.path == \"../abc\""} {"repo":"httpx","file":"tests/models/test_url.py","line":286,"symbol":"test_param_with_space","kind":"function","lang":"python","code":"def test_param_with_space():\n # Params passed as form key-value pairs should be form escaped,\n # Including the special case of \"+\" for space seperators.\n url = httpx.URL(\"http://webservice\", params={\"u\": \"with spaces\"})\n assert str(url) == \"http://webservice?u=with+spaces\""} {"repo":"httpx","file":"tests/models/test_url.py","line":293,"symbol":"test_param_requires_encoding","kind":"function","lang":"python","code":"def test_param_requires_encoding():\n # Params passed as form key-value pairs should be escaped.\n url = httpx.URL(\"http://webservice\", params={\"u\": \"%\"})\n assert str(url) == \"http://webservice?u=%25\""} {"repo":"httpx","file":"tests/models/test_url.py","line":299,"symbol":"test_param_with_percent_encoded","kind":"function","lang":"python","code":"def test_param_with_percent_encoded():\n # Params passed as form key-value pairs should always be escaped,\n # even if they include a valid escape sequence.\n # We want to match browser form behaviour here.\n url = httpx.URL(\"http://webservice\", params={\"u\": \"with%20spaces\"})\n assert str(url) == \"http://webservice?u=with%2520spaces\""} {"repo":"httpx","file":"tests/models/test_url.py","line":307,"symbol":"test_param_with_existing_escape_requires_encoding","kind":"function","lang":"python","code":"def test_param_with_existing_escape_requires_encoding():\n # Params passed as form key-value pairs should always be escaped,\n # even if they include a valid escape sequence.\n # We want to match browser form behaviour here.\n url = httpx.URL(\"http://webservice\", params={\"u\": \"http://example.com?q=foo%2Fa\"})\n assert str(url) == \"http://webservice?u=http%3A%2F%2Fexample.com%3Fq%3Dfoo%252Fa\""} {"repo":"httpx","file":"tests/models/test_url.py","line":320,"symbol":"test_query_with_existing_percent_encoding","kind":"function","lang":"python","code":"def test_query_with_existing_percent_encoding():\n # Valid percent encoded sequences should not be double encoded.\n url = httpx.URL(\"http://webservice?u=phrase%20with%20spaces\")\n assert str(url) == \"http://webservice?u=phrase%20with%20spaces\""} {"repo":"httpx","file":"tests/models/test_url.py","line":326,"symbol":"test_query_requiring_percent_encoding","kind":"function","lang":"python","code":"def test_query_requiring_percent_encoding():\n # Characters that require percent encoding should be encoded.\n url = httpx.URL(\"http://webservice?u=phrase with spaces\")\n assert str(url) == \"http://webservice?u=phrase%20with%20spaces\""} {"repo":"httpx","file":"tests/models/test_url.py","line":332,"symbol":"test_query_with_mixed_percent_encoding","kind":"function","lang":"python","code":"def test_query_with_mixed_percent_encoding():\n # When a mix of encoded and unencoded characters are present,\n # characters that require percent encoding should be encoded,\n # while existing sequences should not be double encoded.\n url = httpx.URL(\"http://webservice?u=phrase%20with spaces\")\n assert str(url) == \"http://webservice?u=phrase%20with%20spaces\""} {"repo":"httpx","file":"tests/models/test_url.py","line":343,"symbol":"test_url_invalid_hostname","kind":"function","lang":"python","code":"def test_url_invalid_hostname():\n \"\"\"\n Ensure that invalid URLs raise an `httpx.InvalidURL` exception.\n \"\"\"\n with pytest.raises(httpx.InvalidURL):\n httpx.URL(\"https://😇/\")"} {"repo":"httpx","file":"tests/models/test_url.py","line":351,"symbol":"test_url_excessively_long_url","kind":"function","lang":"python","code":"def test_url_excessively_long_url():\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(\"https://www.example.com/\" + \"x\" * 100_000)\n assert str(exc.value) == \"URL too long\""} {"repo":"httpx","file":"tests/models/test_url.py","line":357,"symbol":"test_url_excessively_long_component","kind":"function","lang":"python","code":"def test_url_excessively_long_component():\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(\"https://www.example.com\", path=\"/\" + \"x\" * 100_000)\n assert str(exc.value) == \"URL component 'path' too long\""} {"repo":"httpx","file":"tests/models/test_url.py","line":363,"symbol":"test_url_non_printing_character_in_url","kind":"function","lang":"python","code":"def test_url_non_printing_character_in_url():\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(\"https://www.example.com/\\n\")\n assert str(exc.value) == (\n \"Invalid non-printable ASCII character in URL, '\\\\n' at position 24.\"\n )"} {"repo":"httpx","file":"tests/models/test_url.py","line":371,"symbol":"test_url_non_printing_character_in_component","kind":"function","lang":"python","code":"def test_url_non_printing_character_in_component():\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(\"https://www.example.com\", path=\"/\\n\")\n assert str(exc.value) == (\n \"Invalid non-printable ASCII character in URL path component, \"\n \"'\\\\n' at position 1.\"\n )"} {"repo":"httpx","file":"tests/models/test_url.py","line":383,"symbol":"test_url_with_components","kind":"function","lang":"python","code":"def test_url_with_components():\n url = httpx.URL(scheme=\"https\", host=\"www.example.com\", path=\"/\")\n\n assert url.scheme == \"https\"\n assert url.userinfo == b\"\"\n assert url.host == \"www.example.com\"\n assert url.port is None\n assert url.path == \"/\"\n assert url.query == b\"\"\n assert url.fragment == \"\"\n\n assert str(url) == \"https://www.example.com/\""} {"repo":"httpx","file":"tests/models/test_url.py","line":397,"symbol":"test_urlparse_with_invalid_component","kind":"function","lang":"python","code":"def test_urlparse_with_invalid_component():\n with pytest.raises(TypeError) as exc:\n httpx.URL(scheme=\"https\", host=\"www.example.com\", incorrect=\"/\")\n assert str(exc.value) == \"'incorrect' is an invalid keyword argument for URL()\""} {"repo":"httpx","file":"tests/models/test_url.py","line":403,"symbol":"test_urlparse_with_invalid_scheme","kind":"function","lang":"python","code":"def test_urlparse_with_invalid_scheme():\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(scheme=\"~\", host=\"www.example.com\", path=\"/\")\n assert str(exc.value) == \"Invalid URL component 'scheme'\""} {"repo":"httpx","file":"tests/models/test_url.py","line":409,"symbol":"test_urlparse_with_invalid_path","kind":"function","lang":"python","code":"def test_urlparse_with_invalid_path():\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(scheme=\"https\", host=\"www.example.com\", path=\"abc\")\n assert str(exc.value) == \"For absolute URLs, path must be empty or begin with '/'\"\n\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(path=\"//abc\")\n assert str(exc.value) == \"Relative URLs cannot have a path starting with '//'\"\n\n with pytest.raises(httpx.InvalidURL) as exc:\n httpx.URL(path=\":abc\")\n assert str(exc.value) == \"Relative URLs cannot have a path starting with ':'\""} {"repo":"httpx","file":"tests/models/test_url.py","line":423,"symbol":"test_url_with_relative_path","kind":"function","lang":"python","code":"def test_url_with_relative_path():\n # This path would be invalid for an absolute URL, but is valid as a relative URL.\n url = httpx.URL(path=\"abc\")\n assert url.path == \"abc\""} {"repo":"httpx","file":"tests/models/test_url.py","line":432,"symbol":"test_url_eq_str","kind":"function","lang":"python","code":"def test_url_eq_str():\n \"\"\"\n Ensure that `httpx.URL` supports the equality operator.\n \"\"\"\n url = httpx.URL(\"https://example.org:123/path/to/somewhere?abc=123#anchor\")\n assert url == \"https://example.org:123/path/to/somewhere?abc=123#anchor\"\n assert str(url) == url"} {"repo":"httpx","file":"tests/models/test_url.py","line":441,"symbol":"test_url_set","kind":"function","lang":"python","code":"def test_url_set():\n \"\"\"\n Ensure that `httpx.URL` instances can be used in sets.\n \"\"\"\n urls = (\n httpx.URL(\"http://example.org:123/path/to/somewhere\"),\n httpx.URL(\"http://example.org:123/path/to/somewhere/else\"),\n )\n\n url_set = set(urls)\n\n assert all(url in urls for url in url_set)"} {"repo":"httpx","file":"tests/models/test_url.py","line":458,"symbol":"test_url_invalid_type","kind":"function","lang":"python","code":"def test_url_invalid_type():\n \"\"\"\n Ensure that invalid types on `httpx.URL()` raise a `TypeError`.\n \"\"\"\n\n class ExternalURLClass: # representing external URL class\n pass\n\n with pytest.raises(TypeError):\n httpx.URL(ExternalURLClass()) # type: ignore"} {"repo":"httpx","file":"tests/models/test_url.py","line":463,"symbol":"ExternalURLClass","kind":"class","lang":"python","code":"class ExternalURLClass: # representing external URL class\n pass"} {"repo":"httpx","file":"tests/models/test_url.py","line":470,"symbol":"test_url_with_invalid_component","kind":"function","lang":"python","code":"def test_url_with_invalid_component():\n with pytest.raises(TypeError) as exc:\n httpx.URL(scheme=\"https\", host=\"www.example.com\", incorrect=\"/\")\n assert str(exc.value) == \"'incorrect' is an invalid keyword argument for URL()\""} {"repo":"httpx","file":"tests/models/test_url.py","line":479,"symbol":"test_url_join","kind":"function","lang":"python","code":"def test_url_join():\n \"\"\"\n Some basic URL joining tests.\n \"\"\"\n url = httpx.URL(\"https://example.org:123/path/to/somewhere\")\n assert url.join(\"/somewhere-else\") == \"https://example.org:123/somewhere-else\"\n assert (\n url.join(\"somewhere-else\") == \"https://example.org:123/path/to/somewhere-else\"\n )\n assert (\n url.join(\"../somewhere-else\") == \"https://example.org:123/path/somewhere-else\"\n )\n assert url.join(\"../../somewhere-else\") == \"https://example.org:123/somewhere-else\""} {"repo":"httpx","file":"tests/models/test_url.py","line":494,"symbol":"test_relative_url_join","kind":"function","lang":"python","code":"def test_relative_url_join():\n url = httpx.URL(\"/path/to/somewhere\")\n assert url.join(\"/somewhere-else\") == \"/somewhere-else\"\n assert url.join(\"somewhere-else\") == \"/path/to/somewhere-else\"\n assert url.join(\"../somewhere-else\") == \"/path/somewhere-else\"\n assert url.join(\"../../somewhere-else\") == \"/somewhere-else\""} {"repo":"httpx","file":"tests/models/test_url.py","line":502,"symbol":"test_url_join_rfc3986","kind":"function","lang":"python","code":"def test_url_join_rfc3986():\n \"\"\"\n URL joining tests, as-per reference examples in RFC 3986.\n\n https://tools.ietf.org/html/rfc3986#section-5.4\n \"\"\"\n\n url = httpx.URL(\"http://example.com/b/c/d;p?q\")\n\n assert url.join(\"g\") == \"http://example.com/b/c/g\"\n assert url.join(\"./g\") == \"http://example.com/b/c/g\"\n assert url.join(\"g/\") == \"http://example.com/b/c/g/\"\n assert url.join(\"/g\") == \"http://example.com/g\"\n assert url.join(\"//g\") == \"http://g\"\n assert url.join(\"?y\") == \"http://example.com/b/c/d;p?y\"\n assert url.join(\"g?y\") == \"http://example.com/b/c/g?y\"\n assert url.join(\"#s\") == \"http://example.com/b/c/d;p?q#s\"\n assert url.join(\"g#s\") == \"http://example.com/b/c/g#s\"\n assert url.join(\"g?y#s\") == \"http://example.com/b/c/g?y#s\"\n assert url.join(\";x\") == \"http://example.com/b/c/;x\"\n assert url.join(\"g;x\") == \"http://example.com/b/c/g;x\"\n assert url.join(\"g;x?y#s\") == \"http://example.com/b/c/g;x?y#s\"\n assert url.join(\"\") == \"http://example.com/b/c/d;p?q\"\n assert url.join(\".\") == \"http://example.com/b/c/\"\n assert url.join(\"./\") == \"http://example.com/b/c/\"\n assert url.join(\"..\") == \"http://example.com/b/\"\n assert url.joi"} {"repo":"httpx","file":"tests/models/test_url.py","line":557,"symbol":"test_resolution_error_1833","kind":"function","lang":"python","code":"def test_resolution_error_1833():\n \"\"\"\n See https://github.com/encode/httpx/issues/1833\n \"\"\"\n url = httpx.URL(\"https://example.com/?[]\")\n assert url.join(\"/\") == \"https://example.com/\""} {"repo":"httpx","file":"tests/models/test_url.py","line":568,"symbol":"test_copy_with","kind":"function","lang":"python","code":"def test_copy_with():\n url = httpx.URL(\"https://www.example.com/\")\n assert str(url) == \"https://www.example.com/\"\n\n url = url.copy_with()\n assert str(url) == \"https://www.example.com/\"\n\n url = url.copy_with(scheme=\"http\")\n assert str(url) == \"http://www.example.com/\"\n\n url = url.copy_with(netloc=b\"example.com\")\n assert str(url) == \"http://example.com/\"\n\n url = url.copy_with(path=\"/abc\")\n assert str(url) == \"http://example.com/abc\""} {"repo":"httpx","file":"tests/models/test_url.py","line":585,"symbol":"test_url_copywith_authority_subcomponents","kind":"function","lang":"python","code":"def test_url_copywith_authority_subcomponents():\n copy_with_kwargs = {\n \"username\": \"username\",\n \"password\": \"password\",\n \"port\": 444,\n \"host\": \"example.net\",\n }\n url = httpx.URL(\"https://example.org\")\n new = url.copy_with(**copy_with_kwargs)\n assert str(new) == \"https://username:password@example.net:444\""} {"repo":"httpx","file":"tests/models/test_url.py","line":597,"symbol":"test_url_copywith_netloc","kind":"function","lang":"python","code":"def test_url_copywith_netloc():\n copy_with_kwargs = {\n \"netloc\": b\"example.net:444\",\n }\n url = httpx.URL(\"https://example.org\")\n new = url.copy_with(**copy_with_kwargs)\n assert str(new) == \"https://example.net:444\""} {"repo":"httpx","file":"tests/models/test_url.py","line":606,"symbol":"test_url_copywith_userinfo_subcomponents","kind":"function","lang":"python","code":"def test_url_copywith_userinfo_subcomponents():\n copy_with_kwargs = {\n \"username\": \"tom@example.org\",\n \"password\": \"abc123@ %\",\n }\n url = httpx.URL(\"https://example.org\")\n new = url.copy_with(**copy_with_kwargs)\n assert str(new) == \"https://tom%40example.org:abc123%40%20%@example.org\"\n assert new.username == \"tom@example.org\"\n assert new.password == \"abc123@ %\"\n assert new.userinfo == b\"tom%40example.org:abc123%40%20%\""} {"repo":"httpx","file":"tests/models/test_url.py","line":619,"symbol":"test_url_copywith_invalid_component","kind":"function","lang":"python","code":"def test_url_copywith_invalid_component():\n url = httpx.URL(\"https://example.org\")\n with pytest.raises(TypeError):\n url.copy_with(pathh=\"/incorrect-spelling\")\n with pytest.raises(TypeError):\n url.copy_with(userinfo=\"should be bytes\")"} {"repo":"httpx","file":"tests/models/test_url.py","line":627,"symbol":"test_url_copywith_urlencoded_path","kind":"function","lang":"python","code":"def test_url_copywith_urlencoded_path():\n url = httpx.URL(\"https://example.org\")\n url = url.copy_with(path=\"/path to somewhere\")\n assert url.path == \"/path to somewhere\"\n assert url.query == b\"\"\n assert url.raw_path == b\"/path%20to%20somewhere\""} {"repo":"httpx","file":"tests/models/test_url.py","line":635,"symbol":"test_url_copywith_query","kind":"function","lang":"python","code":"def test_url_copywith_query():\n url = httpx.URL(\"https://example.org\")\n url = url.copy_with(query=b\"a=123\")\n assert url.path == \"/\"\n assert url.query == b\"a=123\"\n assert url.raw_path == b\"/?a=123\""} {"repo":"httpx","file":"tests/models/test_url.py","line":643,"symbol":"test_url_copywith_raw_path","kind":"function","lang":"python","code":"def test_url_copywith_raw_path():\n url = httpx.URL(\"https://example.org\")\n url = url.copy_with(raw_path=b\"/some/path\")\n assert url.path == \"/some/path\"\n assert url.query == b\"\"\n assert url.raw_path == b\"/some/path\"\n\n url = httpx.URL(\"https://example.org\")\n url = url.copy_with(raw_path=b\"/some/path?\")\n assert url.path == \"/some/path\"\n assert url.query == b\"\"\n assert url.raw_path == b\"/some/path?\"\n\n url = httpx.URL(\"https://example.org\")\n url = url.copy_with(raw_path=b\"/some/path?a=123\")\n assert url.path == \"/some/path\"\n assert url.query == b\"a=123\"\n assert url.raw_path == b\"/some/path?a=123\""} {"repo":"httpx","file":"tests/models/test_url.py","line":663,"symbol":"test_url_copywith_security","kind":"function","lang":"python","code":"def test_url_copywith_security():\n \"\"\"\n Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945)\n \"\"\"\n with pytest.raises(httpx.InvalidURL):\n httpx.URL(\"https://u:p@[invalid!]//evilHost/path?t=w#tw\")\n\n url = httpx.URL(\"https://example.com/path?t=w#tw\")\n bad = \"https://xxxx:xxxx@xxxxxxx/xxxxx/xxx?x=x#xxxxx\"\n with pytest.raises(httpx.InvalidURL):\n url.copy_with(scheme=bad)"} {"repo":"httpx","file":"tests/models/test_url.py","line":684,"symbol":"test_url_set_param_manipulation","kind":"function","lang":"python","code":"def test_url_set_param_manipulation():\n \"\"\"\n Some basic URL query parameter manipulation.\n \"\"\"\n url = httpx.URL(\"https://example.org:123/?a=123\")\n assert url.copy_set_param(\"a\", \"456\") == \"https://example.org:123/?a=456\""} {"repo":"httpx","file":"tests/models/test_url.py","line":692,"symbol":"test_url_add_param_manipulation","kind":"function","lang":"python","code":"def test_url_add_param_manipulation():\n \"\"\"\n Some basic URL query parameter manipulation.\n \"\"\"\n url = httpx.URL(\"https://example.org:123/?a=123\")\n assert url.copy_add_param(\"a\", \"456\") == \"https://example.org:123/?a=123&a=456\""} {"repo":"httpx","file":"tests/models/test_url.py","line":700,"symbol":"test_url_remove_param_manipulation","kind":"function","lang":"python","code":"def test_url_remove_param_manipulation():\n \"\"\"\n Some basic URL query parameter manipulation.\n \"\"\"\n url = httpx.URL(\"https://example.org:123/?a=123\")\n assert url.copy_remove_param(\"a\") == \"https://example.org:123/\""} {"repo":"httpx","file":"tests/models/test_url.py","line":708,"symbol":"test_url_merge_params_manipulation","kind":"function","lang":"python","code":"def test_url_merge_params_manipulation():\n \"\"\"\n Some basic URL query parameter manipulation.\n \"\"\"\n url = httpx.URL(\"https://example.org:123/?a=123\")\n assert url.copy_merge_params({\"b\": \"456\"}) == \"https://example.org:123/?a=123&b=456\""} {"repo":"httpx","file":"tests/models/test_url.py","line":780,"symbol":"test_idna_url","kind":"function","lang":"python","code":"def test_idna_url(given, idna, host, raw_host, scheme, port):\n url = httpx.URL(given)\n assert url == httpx.URL(idna)\n assert url.host == host\n assert url.raw_host == raw_host\n assert url.scheme == scheme\n assert url.port == port"} {"repo":"httpx","file":"tests/models/test_whatwg.py","line":23,"symbol":"test_urlparse","kind":"function","lang":"python","code":"def test_urlparse(test_case):\n if test_case[\"href\"] in (\"a: foo.com\", \"lolscheme:x x#x%20x\"):\n # Skip these two test cases.\n # WHATWG cases where are not using percent-encoding for the space character.\n # Anyone know what's going on here?\n return\n\n p = urlparse(test_case[\"href\"])\n\n # Test cases include the protocol with the trailing \":\"\n protocol = p.scheme + \":\"\n # Include the square brackets for IPv6 addresses.\n hostname = f\"[{p.host}]\" if \":\" in p.host else p.host\n # The test cases use a string representation of the port.\n port = \"\" if p.port is None else str(p.port)\n # I have nothing to say about this one.\n path = p.path\n # The 'search' and 'hash' components in the whatwg tests are semantic, not literal.\n # Our parsing differentiates between no query/hash and empty-string query/hash.\n search = \"\" if p.query in (None, \"\") else \"?\" + str(p.query)\n hash = \"\" if p.fragment in (None, \"\") else \"#\" + str(p.fragment)\n\n # URL hostnames are case-insensitive.\n # We normalize these, unlike the WHATWG test cases.\n assert protocol == test_case[\"protocol\"]\n assert hostname.lower() == test_case[\"hostname\"].lower("} {"repo":"httpx","file":"tests/test_api.py","line":8,"symbol":"test_get","kind":"function","lang":"python","code":"def test_get(server):\n response = httpx.get(server.url)\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.http_version == \"HTTP/1.1\""} {"repo":"httpx","file":"tests/test_api.py","line":16,"symbol":"test_post","kind":"function","lang":"python","code":"def test_post(server):\n response = httpx.post(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":22,"symbol":"test_post_byte_iterator","kind":"function","lang":"python","code":"def test_post_byte_iterator(server):\n def data() -> typing.Iterator[bytes]:\n yield b\"Hello\"\n yield b\", \"\n yield b\"world!\"\n\n response = httpx.post(server.url, content=data())\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":23,"symbol":"data","kind":"function","lang":"python","code":"def data() -> typing.Iterator[bytes]:\n yield b\"Hello\"\n yield b\", \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/test_api.py","line":33,"symbol":"test_post_byte_stream","kind":"function","lang":"python","code":"def test_post_byte_stream(server):\n class Data(httpx.SyncByteStream):\n def __iter__(self):\n yield b\"Hello\"\n yield b\", \"\n yield b\"world!\"\n\n response = httpx.post(server.url, content=Data())\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":34,"symbol":"Data","kind":"class","lang":"python","code":"class Data(httpx.SyncByteStream):\n def __iter__(self):\n yield b\"Hello\"\n yield b\", \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/test_api.py","line":35,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self):\n yield b\"Hello\"\n yield b\", \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/test_api.py","line":45,"symbol":"test_options","kind":"function","lang":"python","code":"def test_options(server):\n response = httpx.options(server.url)\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":51,"symbol":"test_head","kind":"function","lang":"python","code":"def test_head(server):\n response = httpx.head(server.url)\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":57,"symbol":"test_put","kind":"function","lang":"python","code":"def test_put(server):\n response = httpx.put(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":63,"symbol":"test_patch","kind":"function","lang":"python","code":"def test_patch(server):\n response = httpx.patch(server.url, content=b\"Hello, world!\")\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":69,"symbol":"test_delete","kind":"function","lang":"python","code":"def test_delete(server):\n response = httpx.delete(server.url)\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\""} {"repo":"httpx","file":"tests/test_api.py","line":75,"symbol":"test_stream","kind":"function","lang":"python","code":"def test_stream(server):\n with httpx.stream(\"GET\", server.url) as response:\n response.read()\n\n assert response.status_code == 200\n assert response.reason_phrase == \"OK\"\n assert response.text == \"Hello, world!\"\n assert response.http_version == \"HTTP/1.1\""} {"repo":"httpx","file":"tests/test_api.py","line":85,"symbol":"test_get_invalid_url","kind":"function","lang":"python","code":"def test_get_invalid_url():\n with pytest.raises(httpx.UnsupportedProtocol):\n httpx.get(\"invalid://example.org\")"} {"repo":"httpx","file":"tests/test_api.py","line":91,"symbol":"test_httpcore_lazy_loading","kind":"function","lang":"python","doc":"check that httpcore isn't imported until we do a request","code":"def test_httpcore_lazy_loading(server):\n import sys\n\n # unload our module if it is already loaded\n if \"httpx\" in sys.modules:\n del sys.modules[\"httpx\"]\n del sys.modules[\"httpcore\"]\n import httpx\n\n assert \"httpcore\" not in sys.modules\n _response = httpx.get(server.url)\n assert \"httpcore\" in sys.modules"} {"repo":"httpx","file":"tests/test_asgi.py","line":8,"symbol":"hello_world","kind":"function","lang":"python","code":"async def hello_world(scope, receive, send):\n status = 200\n output = b\"Hello, World!\"\n headers = [(b\"content-type\", \"text/plain\"), (b\"content-length\", str(len(output)))]\n\n await send({\"type\": \"http.response.start\", \"status\": status, \"headers\": headers})\n await send({\"type\": \"http.response.body\", \"body\": output})"} {"repo":"httpx","file":"tests/test_asgi.py","line":17,"symbol":"echo_path","kind":"function","lang":"python","code":"async def echo_path(scope, receive, send):\n status = 200\n output = json.dumps({\"path\": scope[\"path\"]}).encode(\"utf-8\")\n headers = [(b\"content-type\", \"text/plain\"), (b\"content-length\", str(len(output)))]\n\n await send({\"type\": \"http.response.start\", \"status\": status, \"headers\": headers})\n await send({\"type\": \"http.response.body\", \"body\": output})"} {"repo":"httpx","file":"tests/test_asgi.py","line":26,"symbol":"echo_raw_path","kind":"function","lang":"python","code":"async def echo_raw_path(scope, receive, send):\n status = 200\n output = json.dumps({\"raw_path\": scope[\"raw_path\"].decode(\"ascii\")}).encode(\"utf-8\")\n headers = [(b\"content-type\", \"text/plain\"), (b\"content-length\", str(len(output)))]\n\n await send({\"type\": \"http.response.start\", \"status\": status, \"headers\": headers})\n await send({\"type\": \"http.response.body\", \"body\": output})"} {"repo":"httpx","file":"tests/test_asgi.py","line":35,"symbol":"echo_body","kind":"function","lang":"python","code":"async def echo_body(scope, receive, send):\n status = 200\n headers = [(b\"content-type\", \"text/plain\")]\n\n await send({\"type\": \"http.response.start\", \"status\": status, \"headers\": headers})\n more_body = True\n while more_body:\n message = await receive()\n body = message.get(\"body\", b\"\")\n more_body = message.get(\"more_body\", False)\n await send({\"type\": \"http.response.body\", \"body\": body, \"more_body\": more_body})"} {"repo":"httpx","file":"tests/test_asgi.py","line":48,"symbol":"echo_headers","kind":"function","lang":"python","code":"async def echo_headers(scope, receive, send):\n status = 200\n output = json.dumps(\n {\"headers\": [[k.decode(), v.decode()] for k, v in scope[\"headers\"]]}\n ).encode(\"utf-8\")\n headers = [(b\"content-type\", \"text/plain\"), (b\"content-length\", str(len(output)))]\n\n await send({\"type\": \"http.response.start\", \"status\": status, \"headers\": headers})\n await send({\"type\": \"http.response.body\", \"body\": output})"} {"repo":"httpx","file":"tests/test_asgi.py","line":59,"symbol":"raise_exc","kind":"function","lang":"python","code":"async def raise_exc(scope, receive, send):\n raise RuntimeError()"} {"repo":"httpx","file":"tests/test_asgi.py","line":63,"symbol":"raise_exc_after_response","kind":"function","lang":"python","code":"async def raise_exc_after_response(scope, receive, send):\n status = 200\n output = b\"Hello, World!\"\n headers = [(b\"content-type\", \"text/plain\"), (b\"content-length\", str(len(output)))]\n\n await send({\"type\": \"http.response.start\", \"status\": status, \"headers\": headers})\n await send({\"type\": \"http.response.body\", \"body\": output})\n raise RuntimeError()"} {"repo":"httpx","file":"tests/test_asgi.py","line":74,"symbol":"test_asgi_transport","kind":"function","lang":"python","code":"async def test_asgi_transport():\n async with httpx.ASGITransport(app=hello_world) as transport:\n request = httpx.Request(\"GET\", \"http://www.example.com/\")\n response = await transport.handle_async_request(request)\n await response.aread()\n assert response.status_code == 200\n assert response.content == b\"Hello, World!\""} {"repo":"httpx","file":"tests/test_asgi.py","line":84,"symbol":"test_asgi_transport_no_body","kind":"function","lang":"python","code":"async def test_asgi_transport_no_body():\n async with httpx.ASGITransport(app=echo_body) as transport:\n request = httpx.Request(\"GET\", \"http://www.example.com/\")\n response = await transport.handle_async_request(request)\n await response.aread()\n assert response.status_code == 200\n assert response.content == b\"\""} {"repo":"httpx","file":"tests/test_asgi.py","line":94,"symbol":"test_asgi","kind":"function","lang":"python","code":"async def test_asgi():\n transport = httpx.ASGITransport(app=hello_world)\n async with httpx.AsyncClient(transport=transport) as client:\n response = await client.get(\"http://www.example.org/\")\n\n assert response.status_code == 200\n assert response.text == \"Hello, World!\""} {"repo":"httpx","file":"tests/test_asgi.py","line":104,"symbol":"test_asgi_urlencoded_path","kind":"function","lang":"python","code":"async def test_asgi_urlencoded_path():\n transport = httpx.ASGITransport(app=echo_path)\n async with httpx.AsyncClient(transport=transport) as client:\n url = httpx.URL(\"http://www.example.org/\").copy_with(path=\"/user@example.org\")\n response = await client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"path\": \"/user@example.org\"}"} {"repo":"httpx","file":"tests/test_asgi.py","line":115,"symbol":"test_asgi_raw_path","kind":"function","lang":"python","code":"async def test_asgi_raw_path():\n transport = httpx.ASGITransport(app=echo_raw_path)\n async with httpx.AsyncClient(transport=transport) as client:\n url = httpx.URL(\"http://www.example.org/\").copy_with(path=\"/user@example.org\")\n response = await client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"raw_path\": \"/user@example.org\"}"} {"repo":"httpx","file":"tests/test_asgi.py","line":126,"symbol":"test_asgi_raw_path_should_not_include_querystring_portion","kind":"function","lang":"python","code":"async def test_asgi_raw_path_should_not_include_querystring_portion():\n \"\"\"\n See https://github.com/encode/httpx/issues/2810\n \"\"\"\n transport = httpx.ASGITransport(app=echo_raw_path)\n async with httpx.AsyncClient(transport=transport) as client:\n url = httpx.URL(\"http://www.example.org/path?query\")\n response = await client.get(url)\n\n assert response.status_code == 200\n assert response.json() == {\"raw_path\": \"/path\"}"} {"repo":"httpx","file":"tests/test_asgi.py","line":140,"symbol":"test_asgi_upload","kind":"function","lang":"python","code":"async def test_asgi_upload():\n transport = httpx.ASGITransport(app=echo_body)\n async with httpx.AsyncClient(transport=transport) as client:\n response = await client.post(\"http://www.example.org/\", content=b\"example\")\n\n assert response.status_code == 200\n assert response.text == \"example\""} {"repo":"httpx","file":"tests/test_asgi.py","line":150,"symbol":"test_asgi_headers","kind":"function","lang":"python","code":"async def test_asgi_headers():\n transport = httpx.ASGITransport(app=echo_headers)\n async with httpx.AsyncClient(transport=transport) as client:\n response = await client.get(\"http://www.example.org/\")\n\n assert response.status_code == 200\n assert response.json() == {\n \"headers\": [\n [\"host\", \"www.example.org\"],\n [\"accept\", \"*/*\"],\n [\"accept-encoding\", \"gzip, deflate, br, zstd\"],\n [\"connection\", \"keep-alive\"],\n [\"user-agent\", f\"python-httpx/{httpx.__version__}\"],\n ]\n }"} {"repo":"httpx","file":"tests/test_asgi.py","line":168,"symbol":"test_asgi_exc","kind":"function","lang":"python","code":"async def test_asgi_exc():\n transport = httpx.ASGITransport(app=raise_exc)\n async with httpx.AsyncClient(transport=transport) as client:\n with pytest.raises(RuntimeError):\n await client.get(\"http://www.example.org/\")"} {"repo":"httpx","file":"tests/test_asgi.py","line":176,"symbol":"test_asgi_exc_after_response","kind":"function","lang":"python","code":"async def test_asgi_exc_after_response():\n transport = httpx.ASGITransport(app=raise_exc_after_response)\n async with httpx.AsyncClient(transport=transport) as client:\n with pytest.raises(RuntimeError):\n await client.get(\"http://www.example.org/\")"} {"repo":"httpx","file":"tests/test_asgi.py","line":184,"symbol":"test_asgi_disconnect_after_response_complete","kind":"function","lang":"python","code":"async def test_asgi_disconnect_after_response_complete():\n disconnect = False\n\n async def read_body(scope, receive, send):\n nonlocal disconnect\n\n status = 200\n headers = [(b\"content-type\", \"text/plain\")]\n\n await send(\n {\"type\": \"http.response.start\", \"status\": status, \"headers\": headers}\n )\n more_body = True\n while more_body:\n message = await receive()\n more_body = message.get(\"more_body\", False)\n\n await send({\"type\": \"http.response.body\", \"body\": b\"\", \"more_body\": False})\n\n # The ASGI spec says of the Disconnect message:\n # \"Sent to the application when a HTTP connection is closed or if receive is\n # called after a response has been sent.\"\n # So if receive() is called again, the disconnect message should be received\n message = await receive()\n disconnect = message.get(\"type\") == \"http.disconnect\"\n\n transport = httpx.ASGITransport(app=read_body)\n async with httpx.AsyncClient(transport=transport) as client:\n response = await client.post(\"http://www.example.org/\", content=b\"example\")\n\n assert response.status_code == 200\n assert di"} {"repo":"httpx","file":"tests/test_asgi.py","line":187,"symbol":"read_body","kind":"function","lang":"python","code":"async def read_body(scope, receive, send):\n nonlocal disconnect\n\n status = 200\n headers = [(b\"content-type\", \"text/plain\")]\n\n await send(\n {\"type\": \"http.response.start\", \"status\": status, \"headers\": headers}\n )\n more_body = True\n while more_body:\n message = await receive()\n more_body = message.get(\"more_body\", False)\n\n await send({\"type\": \"http.response.body\", \"body\": b\"\", \"more_body\": False})\n\n # The ASGI spec says of the Disconnect message:\n # \"Sent to the application when a HTTP connection is closed or if receive is\n # called after a response has been sent.\"\n # So if receive() is called again, the disconnect message should be received\n message = await receive()\n disconnect = message.get(\"type\") == \"http.disconnect\""} {"repo":"httpx","file":"tests/test_asgi.py","line":219,"symbol":"test_asgi_exc_no_raise","kind":"function","lang":"python","code":"async def test_asgi_exc_no_raise():\n transport = httpx.ASGITransport(app=raise_exc, raise_app_exceptions=False)\n async with httpx.AsyncClient(transport=transport) as client:\n response = await client.get(\"http://www.example.org/\")\n\n assert response.status_code == 500"} {"repo":"httpx","file":"tests/test_auth.py","line":14,"symbol":"test_basic_auth","kind":"function","lang":"python","code":"def test_basic_auth():\n auth = httpx.BasicAuth(username=\"user\", password=\"pass\")\n request = httpx.Request(\"GET\", \"https://www.example.com\")\n\n # The initial request should include a basic auth header.\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert request.headers[\"Authorization\"].startswith(\"Basic\")\n\n # No other requests are made.\n response = httpx.Response(content=b\"Hello, world!\", status_code=200)\n with pytest.raises(StopIteration):\n flow.send(response)"} {"repo":"httpx","file":"tests/test_auth.py","line":29,"symbol":"test_digest_auth_with_200","kind":"function","lang":"python","code":"def test_digest_auth_with_200():\n auth = httpx.DigestAuth(username=\"user\", password=\"pass\")\n request = httpx.Request(\"GET\", \"https://www.example.com\")\n\n # The initial request should not include an auth header.\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert \"Authorization\" not in request.headers\n\n # If a 200 response is returned, then no other requests are made.\n response = httpx.Response(content=b\"Hello, world!\", status_code=200)\n with pytest.raises(StopIteration):\n flow.send(response)"} {"repo":"httpx","file":"tests/test_auth.py","line":44,"symbol":"test_digest_auth_with_401","kind":"function","lang":"python","code":"def test_digest_auth_with_401():\n auth = httpx.DigestAuth(username=\"user\", password=\"pass\")\n request = httpx.Request(\"GET\", \"https://www.example.com\")\n\n # The initial request should not include an auth header.\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert \"Authorization\" not in request.headers\n\n # If a 401 response is returned, then a digest auth request is made.\n headers = {\n \"WWW-Authenticate\": 'Digest realm=\"...\", qop=\"auth\", nonce=\"...\", opaque=\"...\"'\n }\n response = httpx.Response(\n content=b\"Auth required\", status_code=401, headers=headers, request=request\n )\n request = flow.send(response)\n assert request.headers[\"Authorization\"].startswith(\"Digest\")\n\n # No other requests are made.\n response = httpx.Response(content=b\"Hello, world!\", status_code=200)\n with pytest.raises(StopIteration):\n flow.send(response)"} {"repo":"httpx","file":"tests/test_auth.py","line":69,"symbol":"test_digest_auth_with_401_nonce_counting","kind":"function","lang":"python","code":"def test_digest_auth_with_401_nonce_counting():\n auth = httpx.DigestAuth(username=\"user\", password=\"pass\")\n request = httpx.Request(\"GET\", \"https://www.example.com\")\n\n # The initial request should not include an auth header.\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert \"Authorization\" not in request.headers\n\n # If a 401 response is returned, then a digest auth request is made.\n headers = {\n \"WWW-Authenticate\": 'Digest realm=\"...\", qop=\"auth\", nonce=\"...\", opaque=\"...\"'\n }\n response = httpx.Response(\n content=b\"Auth required\", status_code=401, headers=headers, request=request\n )\n first_request = flow.send(response)\n assert first_request.headers[\"Authorization\"].startswith(\"Digest\")\n\n # Each subsequent request contains the digest header by default...\n request = httpx.Request(\"GET\", \"https://www.example.com\")\n flow = auth.sync_auth_flow(request)\n second_request = next(flow)\n assert second_request.headers[\"Authorization\"].startswith(\"Digest\")\n\n # ... and the client nonce count (nc) is increased\n first_nc = parse_keqv_list(first_request.headers[\"Authorization\"].split(\", \"))[\"nc\"]\n second_n"} {"repo":"httpx","file":"tests/test_auth.py","line":107,"symbol":"set_cookies","kind":"function","lang":"python","code":"def set_cookies(request: httpx.Request) -> httpx.Response:\n headers = {\n \"Set-Cookie\": \"session=.session_value...\",\n \"WWW-Authenticate\": 'Digest realm=\"...\", qop=\"auth\", nonce=\"...\", opaque=\"...\"',\n }\n if request.url.path == \"/auth\":\n return httpx.Response(\n content=b\"Auth required\", status_code=401, headers=headers\n )\n else:\n raise NotImplementedError() # pragma: no cover"} {"repo":"httpx","file":"tests/test_auth.py","line":120,"symbol":"test_digest_auth_setting_cookie_in_request","kind":"function","lang":"python","code":"def test_digest_auth_setting_cookie_in_request():\n url = \"https://www.example.com/auth\"\n client = httpx.Client(transport=httpx.MockTransport(set_cookies))\n request = client.build_request(\"GET\", url)\n\n auth = httpx.DigestAuth(username=\"user\", password=\"pass\")\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert \"Authorization\" not in request.headers\n\n response = client.get(url)\n assert len(response.cookies) > 0\n assert response.cookies[\"session\"] == \".session_value...\"\n\n request = flow.send(response)\n assert request.headers[\"Authorization\"].startswith(\"Digest\")\n assert request.headers[\"Cookie\"] == \"session=.session_value...\"\n\n # No other requests are made.\n response = httpx.Response(\n content=b\"Hello, world!\", status_code=200, request=request\n )\n with pytest.raises(StopIteration):\n flow.send(response)"} {"repo":"httpx","file":"tests/test_auth.py","line":146,"symbol":"test_digest_auth_rfc_2069","kind":"function","lang":"python","code":"def test_digest_auth_rfc_2069():\n # Example from https://datatracker.ietf.org/doc/html/rfc2069#section-2.4\n # with corrected response from https://www.rfc-editor.org/errata/eid749\n\n auth = httpx.DigestAuth(username=\"Mufasa\", password=\"CircleOfLife\")\n request = httpx.Request(\"GET\", \"https://www.example.com/dir/index.html\")\n\n # The initial request should not include an auth header.\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert \"Authorization\" not in request.headers\n\n # If a 401 response is returned, then a digest auth request is made.\n headers = {\n \"WWW-Authenticate\": (\n 'Digest realm=\"testrealm@host.com\", '\n 'nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", '\n 'opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"'\n )\n }\n response = httpx.Response(\n content=b\"Auth required\", status_code=401, headers=headers, request=request\n )\n request = flow.send(response)\n assert request.headers[\"Authorization\"].startswith(\"Digest\")\n assert 'username=\"Mufasa\"' in request.headers[\"Authorization\"]\n assert 'realm=\"testrealm@host.com\"' in request.headers[\"Authorization\"]\n assert (\n 'n"} {"repo":"httpx","file":"tests/test_auth.py","line":191,"symbol":"test_digest_auth_rfc_7616_md5","kind":"function","lang":"python","code":"def test_digest_auth_rfc_7616_md5(monkeypatch):\n # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1\n\n def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:\n return \"f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ\".encode()\n\n auth = httpx.DigestAuth(username=\"Mufasa\", password=\"Circle of Life\")\n monkeypatch.setattr(auth, \"_get_client_nonce\", mock_get_client_nonce)\n\n request = httpx.Request(\"GET\", \"https://www.example.com/dir/index.html\")\n\n # The initial request should not include an auth header.\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert \"Authorization\" not in request.headers\n\n # If a 401 response is returned, then a digest auth request is made.\n headers = {\n \"WWW-Authenticate\": (\n 'Digest realm=\"http-auth@example.org\", '\n 'qop=\"auth, auth-int\", '\n \"algorithm=MD5, \"\n 'nonce=\"7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v\", '\n 'opaque=\"FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS\"'\n )\n }\n response = httpx.Response(\n content=b\"Auth required\", status_code=401, headers=headers, request=request\n )\n request"} {"repo":"httpx","file":"tests/test_auth.py","line":194,"symbol":"mock_get_client_nonce","kind":"function","lang":"python","code":"def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:\n return \"f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ\".encode()"} {"repo":"httpx","file":"tests/test_auth.py","line":251,"symbol":"test_digest_auth_rfc_7616_sha_256","kind":"function","lang":"python","code":"def test_digest_auth_rfc_7616_sha_256(monkeypatch):\n # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1\n\n def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:\n return \"f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ\".encode()\n\n auth = httpx.DigestAuth(username=\"Mufasa\", password=\"Circle of Life\")\n monkeypatch.setattr(auth, \"_get_client_nonce\", mock_get_client_nonce)\n\n request = httpx.Request(\"GET\", \"https://www.example.com/dir/index.html\")\n\n # The initial request should not include an auth header.\n flow = auth.sync_auth_flow(request)\n request = next(flow)\n assert \"Authorization\" not in request.headers\n\n # If a 401 response is returned, then a digest auth request is made.\n headers = {\n \"WWW-Authenticate\": (\n 'Digest realm=\"http-auth@example.org\", '\n 'qop=\"auth, auth-int\", '\n \"algorithm=SHA-256, \"\n 'nonce=\"7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v\", '\n 'opaque=\"FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS\"'\n )\n }\n response = httpx.Response(\n content=b\"Auth required\", status_code=401, headers=headers, request=request\n )\n "} {"repo":"httpx","file":"tests/test_auth.py","line":254,"symbol":"mock_get_client_nonce","kind":"function","lang":"python","code":"def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:\n return \"f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ\".encode()"} {"repo":"httpx","file":"tests/test_config.py","line":11,"symbol":"test_load_ssl_config","kind":"function","lang":"python","code":"def test_load_ssl_config():\n context = httpx.create_ssl_context()\n assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED\n assert context.check_hostname is True"} {"repo":"httpx","file":"tests/test_config.py","line":17,"symbol":"test_load_ssl_config_verify_non_existing_file","kind":"function","lang":"python","code":"def test_load_ssl_config_verify_non_existing_file():\n with pytest.raises(IOError):\n context = httpx.create_ssl_context()\n context.load_verify_locations(cafile=\"/path/to/nowhere\")"} {"repo":"httpx","file":"tests/test_config.py","line":23,"symbol":"test_load_ssl_with_keylog","kind":"function","lang":"python","code":"def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None:\n monkeypatch.setenv(\"SSLKEYLOGFILE\", \"test\")\n context = httpx.create_ssl_context()\n assert context.keylog_filename == \"test\""} {"repo":"httpx","file":"tests/test_config.py","line":29,"symbol":"test_load_ssl_config_verify_existing_file","kind":"function","lang":"python","code":"def test_load_ssl_config_verify_existing_file():\n context = httpx.create_ssl_context()\n context.load_verify_locations(capath=certifi.where())\n assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED\n assert context.check_hostname is True"} {"repo":"httpx","file":"tests/test_config.py","line":36,"symbol":"test_load_ssl_config_verify_directory","kind":"function","lang":"python","code":"def test_load_ssl_config_verify_directory():\n context = httpx.create_ssl_context()\n context.load_verify_locations(capath=Path(certifi.where()).parent)\n assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED\n assert context.check_hostname is True"} {"repo":"httpx","file":"tests/test_config.py","line":43,"symbol":"test_load_ssl_config_cert_and_key","kind":"function","lang":"python","code":"def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):\n context = httpx.create_ssl_context()\n context.load_cert_chain(cert_pem_file, cert_private_key_file)\n assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED\n assert context.check_hostname is True"} {"repo":"httpx","file":"tests/test_config.py","line":51,"symbol":"test_load_ssl_config_cert_and_encrypted_key","kind":"function","lang":"python","code":"def test_load_ssl_config_cert_and_encrypted_key(\n cert_pem_file, cert_encrypted_private_key_file, password\n):\n context = httpx.create_ssl_context()\n context.load_cert_chain(cert_pem_file, cert_encrypted_private_key_file, password)\n assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED\n assert context.check_hostname is True"} {"repo":"httpx","file":"tests/test_config.py","line":60,"symbol":"test_load_ssl_config_cert_and_key_invalid_password","kind":"function","lang":"python","code":"def test_load_ssl_config_cert_and_key_invalid_password(\n cert_pem_file, cert_encrypted_private_key_file\n):\n with pytest.raises(ssl.SSLError):\n context = httpx.create_ssl_context()\n context.load_cert_chain(\n cert_pem_file, cert_encrypted_private_key_file, \"password1\"\n )"} {"repo":"httpx","file":"tests/test_config.py","line":70,"symbol":"test_load_ssl_config_cert_without_key_raises","kind":"function","lang":"python","code":"def test_load_ssl_config_cert_without_key_raises(cert_pem_file):\n with pytest.raises(ssl.SSLError):\n context = httpx.create_ssl_context()\n context.load_cert_chain(cert_pem_file)"} {"repo":"httpx","file":"tests/test_config.py","line":76,"symbol":"test_load_ssl_config_no_verify","kind":"function","lang":"python","code":"def test_load_ssl_config_no_verify():\n context = httpx.create_ssl_context(verify=False)\n assert context.verify_mode == ssl.VerifyMode.CERT_NONE\n assert context.check_hostname is False"} {"repo":"httpx","file":"tests/test_config.py","line":82,"symbol":"test_SSLContext_with_get_request","kind":"function","lang":"python","code":"def test_SSLContext_with_get_request(server, cert_pem_file):\n context = httpx.create_ssl_context()\n context.load_verify_locations(cert_pem_file)\n response = httpx.get(server.url, verify=context)\n assert response.status_code == 200"} {"repo":"httpx","file":"tests/test_config.py","line":89,"symbol":"test_limits_repr","kind":"function","lang":"python","code":"def test_limits_repr():\n limits = httpx.Limits(max_connections=100)\n expected = (\n \"Limits(max_connections=100, max_keepalive_connections=None,\"\n \" keepalive_expiry=5.0)\"\n )\n assert repr(limits) == expected"} {"repo":"httpx","file":"tests/test_config.py","line":98,"symbol":"test_limits_eq","kind":"function","lang":"python","code":"def test_limits_eq():\n limits = httpx.Limits(max_connections=100)\n assert limits == httpx.Limits(max_connections=100)"} {"repo":"httpx","file":"tests/test_config.py","line":103,"symbol":"test_timeout_eq","kind":"function","lang":"python","code":"def test_timeout_eq():\n timeout = httpx.Timeout(timeout=5.0)\n assert timeout == httpx.Timeout(timeout=5.0)"} {"repo":"httpx","file":"tests/test_config.py","line":108,"symbol":"test_timeout_all_parameters_set","kind":"function","lang":"python","code":"def test_timeout_all_parameters_set():\n timeout = httpx.Timeout(connect=5.0, read=5.0, write=5.0, pool=5.0)\n assert timeout == httpx.Timeout(timeout=5.0)"} {"repo":"httpx","file":"tests/test_config.py","line":113,"symbol":"test_timeout_from_nothing","kind":"function","lang":"python","code":"def test_timeout_from_nothing():\n timeout = httpx.Timeout(None)\n assert timeout.connect is None\n assert timeout.read is None\n assert timeout.write is None\n assert timeout.pool is None"} {"repo":"httpx","file":"tests/test_config.py","line":121,"symbol":"test_timeout_from_none","kind":"function","lang":"python","code":"def test_timeout_from_none():\n timeout = httpx.Timeout(timeout=None)\n assert timeout == httpx.Timeout(None)"} {"repo":"httpx","file":"tests/test_config.py","line":126,"symbol":"test_timeout_from_one_none_value","kind":"function","lang":"python","code":"def test_timeout_from_one_none_value():\n timeout = httpx.Timeout(None, read=None)\n assert timeout == httpx.Timeout(None)"} {"repo":"httpx","file":"tests/test_config.py","line":131,"symbol":"test_timeout_from_one_value","kind":"function","lang":"python","code":"def test_timeout_from_one_value():\n timeout = httpx.Timeout(None, read=5.0)\n assert timeout == httpx.Timeout(timeout=(None, 5.0, None, None))"} {"repo":"httpx","file":"tests/test_config.py","line":136,"symbol":"test_timeout_from_one_value_and_default","kind":"function","lang":"python","code":"def test_timeout_from_one_value_and_default():\n timeout = httpx.Timeout(5.0, pool=60.0)\n assert timeout == httpx.Timeout(timeout=(5.0, 5.0, 5.0, 60.0))"} {"repo":"httpx","file":"tests/test_config.py","line":141,"symbol":"test_timeout_missing_default","kind":"function","lang":"python","code":"def test_timeout_missing_default():\n with pytest.raises(ValueError):\n httpx.Timeout(pool=60.0)"} {"repo":"httpx","file":"tests/test_config.py","line":146,"symbol":"test_timeout_from_tuple","kind":"function","lang":"python","code":"def test_timeout_from_tuple():\n timeout = httpx.Timeout(timeout=(5.0, 5.0, 5.0, 5.0))\n assert timeout == httpx.Timeout(timeout=5.0)"} {"repo":"httpx","file":"tests/test_config.py","line":151,"symbol":"test_timeout_from_config_instance","kind":"function","lang":"python","code":"def test_timeout_from_config_instance():\n timeout = httpx.Timeout(timeout=5.0)\n assert httpx.Timeout(timeout) == httpx.Timeout(timeout=5.0)"} {"repo":"httpx","file":"tests/test_config.py","line":156,"symbol":"test_timeout_repr","kind":"function","lang":"python","code":"def test_timeout_repr():\n timeout = httpx.Timeout(timeout=5.0)\n assert repr(timeout) == \"Timeout(timeout=5.0)\"\n\n timeout = httpx.Timeout(None, read=5.0)\n assert repr(timeout) == \"Timeout(connect=None, read=5.0, write=None, pool=None)\""} {"repo":"httpx","file":"tests/test_config.py","line":164,"symbol":"test_proxy_from_url","kind":"function","lang":"python","code":"def test_proxy_from_url():\n proxy = httpx.Proxy(\"https://example.com\")\n\n assert str(proxy.url) == \"https://example.com\"\n assert proxy.auth is None\n assert proxy.headers == {}\n assert repr(proxy) == \"Proxy('https://example.com')\""} {"repo":"httpx","file":"tests/test_config.py","line":173,"symbol":"test_proxy_with_auth_from_url","kind":"function","lang":"python","code":"def test_proxy_with_auth_from_url():\n proxy = httpx.Proxy(\"https://username:password@example.com\")\n\n assert str(proxy.url) == \"https://example.com\"\n assert proxy.auth == (\"username\", \"password\")\n assert proxy.headers == {}\n assert repr(proxy) == \"Proxy('https://example.com', auth=('username', '********'))\""} {"repo":"httpx","file":"tests/test_config.py","line":182,"symbol":"test_invalid_proxy_scheme","kind":"function","lang":"python","code":"def test_invalid_proxy_scheme():\n with pytest.raises(ValueError):\n httpx.Proxy(\"invalid://example.com\")"} {"repo":"httpx","file":"tests/test_content.py","line":13,"symbol":"test_empty_content","kind":"function","lang":"python","code":"async def test_empty_content():\n request = httpx.Request(method, url)\n assert isinstance(request.stream, httpx.SyncByteStream)\n assert isinstance(request.stream, httpx.AsyncByteStream)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\"Host\": \"www.example.com\", \"Content-Length\": \"0\"}\n assert sync_content == b\"\"\n assert async_content == b\"\""} {"repo":"httpx","file":"tests/test_content.py","line":27,"symbol":"test_bytes_content","kind":"function","lang":"python","code":"async def test_bytes_content():\n request = httpx.Request(method, url, content=b\"Hello, world!\")\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\"Host\": \"www.example.com\", \"Content-Length\": \"13\"}\n assert sync_content == b\"Hello, world!\"\n assert async_content == b\"Hello, world!\"\n\n # Support 'data' for compat with requests.\n with pytest.warns(DeprecationWarning):\n request = httpx.Request(method, url, data=b\"Hello, world!\") # type: ignore\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\"Host\": \"www.example.com\", \"Content-Length\": \"13\"}\n assert sync_content == b\"Hello, world!\"\n assert async_content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/test_content.py","line":54,"symbol":"test_bytesio_content","kind":"function","lang":"python","code":"async def test_bytesio_content():\n request = httpx.Request(method, url, content=io.BytesIO(b\"Hello, world!\"))\n assert isinstance(request.stream, typing.Iterable)\n assert not isinstance(request.stream, typing.AsyncIterable)\n\n content = b\"\".join(list(request.stream))\n\n assert request.headers == {\"Host\": \"www.example.com\", \"Content-Length\": \"13\"}\n assert content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/test_content.py","line":66,"symbol":"test_async_bytesio_content","kind":"function","lang":"python","code":"async def test_async_bytesio_content():\n class AsyncBytesIO:\n def __init__(self, content: bytes) -> None:\n self._idx = 0\n self._content = content\n\n async def aread(self, chunk_size: int) -> bytes:\n chunk = self._content[self._idx : self._idx + chunk_size]\n self._idx = self._idx + chunk_size\n return chunk\n\n async def __aiter__(self):\n yield self._content # pragma: no cover\n\n request = httpx.Request(method, url, content=AsyncBytesIO(b\"Hello, world!\"))\n assert not isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Transfer-Encoding\": \"chunked\",\n }\n assert content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/test_content.py","line":67,"symbol":"AsyncBytesIO","kind":"class","lang":"python","code":"class AsyncBytesIO:\n def __init__(self, content: bytes) -> None:\n self._idx = 0\n self._content = content\n\n async def aread(self, chunk_size: int) -> bytes:\n chunk = self._content[self._idx : self._idx + chunk_size]\n self._idx = self._idx + chunk_size\n return chunk\n\n async def __aiter__(self):\n yield self._content # pragma: no cover"} {"repo":"httpx","file":"tests/test_content.py","line":68,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, content: bytes) -> None:\n self._idx = 0\n self._content = content"} {"repo":"httpx","file":"tests/test_content.py","line":72,"symbol":"aread","kind":"function","lang":"python","code":"async def aread(self, chunk_size: int) -> bytes:\n chunk = self._content[self._idx : self._idx + chunk_size]\n self._idx = self._idx + chunk_size\n return chunk"} {"repo":"httpx","file":"tests/test_content.py","line":77,"symbol":"__aiter__","kind":"function","lang":"python","code":"async def __aiter__(self):\n yield self._content # pragma: no cover"} {"repo":"httpx","file":"tests/test_content.py","line":94,"symbol":"test_iterator_content","kind":"function","lang":"python","code":"async def test_iterator_content():\n def hello_world() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\"\n\n request = httpx.Request(method, url, content=hello_world())\n assert isinstance(request.stream, typing.Iterable)\n assert not isinstance(request.stream, typing.AsyncIterable)\n\n content = b\"\".join(list(request.stream))\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Transfer-Encoding\": \"chunked\",\n }\n assert content == b\"Hello, world!\"\n\n with pytest.raises(httpx.StreamConsumed):\n list(request.stream)\n\n # Support 'data' for compat with requests.\n with pytest.warns(DeprecationWarning):\n request = httpx.Request(method, url, data=hello_world()) # type: ignore\n assert isinstance(request.stream, typing.Iterable)\n assert not isinstance(request.stream, typing.AsyncIterable)\n\n content = b\"\".join(list(request.stream))\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Transfer-Encoding\": \"chunked\",\n }\n assert content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/test_content.py","line":95,"symbol":"hello_world","kind":"function","lang":"python","code":"def hello_world() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/test_content.py","line":130,"symbol":"test_aiterator_content","kind":"function","lang":"python","code":"async def test_aiterator_content():\n async def hello_world() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\"\n\n request = httpx.Request(method, url, content=hello_world())\n assert not isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Transfer-Encoding\": \"chunked\",\n }\n assert content == b\"Hello, world!\"\n\n with pytest.raises(httpx.StreamConsumed):\n [part async for part in request.stream]\n\n # Support 'data' for compat with requests.\n with pytest.warns(DeprecationWarning):\n request = httpx.Request(method, url, data=hello_world()) # type: ignore\n assert not isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Transfer-Encoding\": \"chunked\",\n }\n assert content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/test_content.py","line":131,"symbol":"hello_world","kind":"function","lang":"python","code":"async def hello_world() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/test_content.py","line":166,"symbol":"test_json_content","kind":"function","lang":"python","code":"async def test_json_content():\n request = httpx.Request(method, url, json={\"Hello\": \"world!\"})\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"18\",\n \"Content-Type\": \"application/json\",\n }\n assert sync_content == b'{\"Hello\":\"world!\"}'\n assert async_content == b'{\"Hello\":\"world!\"}'"} {"repo":"httpx","file":"tests/test_content.py","line":184,"symbol":"test_urlencoded_content","kind":"function","lang":"python","code":"async def test_urlencoded_content():\n request = httpx.Request(method, url, data={\"Hello\": \"world!\"})\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"14\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }\n assert sync_content == b\"Hello=world%21\"\n assert async_content == b\"Hello=world%21\""} {"repo":"httpx","file":"tests/test_content.py","line":202,"symbol":"test_urlencoded_boolean","kind":"function","lang":"python","code":"async def test_urlencoded_boolean():\n request = httpx.Request(method, url, data={\"example\": True})\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"12\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }\n assert sync_content == b\"example=true\"\n assert async_content == b\"example=true\""} {"repo":"httpx","file":"tests/test_content.py","line":220,"symbol":"test_urlencoded_none","kind":"function","lang":"python","code":"async def test_urlencoded_none():\n request = httpx.Request(method, url, data={\"example\": None})\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"8\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }\n assert sync_content == b\"example=\"\n assert async_content == b\"example=\""} {"repo":"httpx","file":"tests/test_content.py","line":238,"symbol":"test_urlencoded_list","kind":"function","lang":"python","code":"async def test_urlencoded_list():\n request = httpx.Request(method, url, data={\"example\": [\"a\", 1, True]})\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"32\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }\n assert sync_content == b\"example=a&example=1&example=true\"\n assert async_content == b\"example=a&example=1&example=true\""} {"repo":"httpx","file":"tests/test_content.py","line":256,"symbol":"test_multipart_files_content","kind":"function","lang":"python","code":"async def test_multipart_files_content():\n files = {\"file\": io.BytesIO(b\"\")}\n headers = {\"Content-Type\": \"multipart/form-data; boundary=+++\"}\n request = httpx.Request(\n method,\n url,\n files=files,\n headers=headers,\n )\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"138\",\n \"Content-Type\": \"multipart/form-data; boundary=+++\",\n }\n assert sync_content == b\"\".join(\n [\n b\"--+++\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n',\n b\"Content-Type: application/octet-stream\\r\\n\",\n b\"\\r\\n\",\n b\"\\r\\n\",\n b\"--+++--\\r\\n\",\n ]\n )\n assert async_content == b\"\".join(\n [\n b\"--+++\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n',\n b\"Content-Type: application/octet-stream"} {"repo":"httpx","file":"tests/test_content.py","line":299,"symbol":"test_multipart_data_and_files_content","kind":"function","lang":"python","code":"async def test_multipart_data_and_files_content():\n data = {\"message\": \"Hello, world!\"}\n files = {\"file\": io.BytesIO(b\"\")}\n headers = {\"Content-Type\": \"multipart/form-data; boundary=+++\"}\n request = httpx.Request(method, url, data=data, files=files, headers=headers)\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"210\",\n \"Content-Type\": \"multipart/form-data; boundary=+++\",\n }\n assert sync_content == b\"\".join(\n [\n b\"--+++\\r\\n\",\n b'Content-Disposition: form-data; name=\"message\"\\r\\n',\n b\"\\r\\n\",\n b\"Hello, world!\\r\\n\",\n b\"--+++\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n',\n b\"Content-Type: application/octet-stream\\r\\n\",\n b\"\\r\\n\",\n b\"\\r\\n\",\n b\"--+++--\\r\\n\",\n ]\n )\n assert async_content == b\"\".join(\n "} {"repo":"httpx","file":"tests/test_content.py","line":346,"symbol":"test_empty_request","kind":"function","lang":"python","code":"async def test_empty_request():\n request = httpx.Request(method, url, data={}, files={})\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\"Host\": \"www.example.com\", \"Content-Length\": \"0\"}\n assert sync_content == b\"\"\n assert async_content == b\"\""} {"repo":"httpx","file":"tests/test_content.py","line":359,"symbol":"test_invalid_argument","kind":"function","lang":"python","code":"def test_invalid_argument():\n with pytest.raises(TypeError):\n httpx.Request(method, url, content=123) # type: ignore\n\n with pytest.raises(TypeError):\n httpx.Request(method, url, content={\"a\": \"b\"}) # type: ignore"} {"repo":"httpx","file":"tests/test_content.py","line":368,"symbol":"test_multipart_multiple_files_single_input_content","kind":"function","lang":"python","code":"async def test_multipart_multiple_files_single_input_content():\n files = [\n (\"file\", io.BytesIO(b\"\")),\n (\"file\", io.BytesIO(b\"\")),\n ]\n headers = {\"Content-Type\": \"multipart/form-data; boundary=+++\"}\n request = httpx.Request(method, url, files=files, headers=headers)\n assert isinstance(request.stream, typing.Iterable)\n assert isinstance(request.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(request.stream))\n async_content = b\"\".join([part async for part in request.stream])\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Length\": \"271\",\n \"Content-Type\": \"multipart/form-data; boundary=+++\",\n }\n assert sync_content == b\"\".join(\n [\n b\"--+++\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n',\n b\"Content-Type: application/octet-stream\\r\\n\",\n b\"\\r\\n\",\n b\"\\r\\n\",\n b\"--+++\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n',\n b\"Content-Type: application/octet-stream\\r\\n\",\n b\"\\r\\n\",\n "} {"repo":"httpx","file":"tests/test_content.py","line":419,"symbol":"test_response_empty_content","kind":"function","lang":"python","code":"async def test_response_empty_content():\n response = httpx.Response(200)\n assert isinstance(response.stream, typing.Iterable)\n assert isinstance(response.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(response.stream))\n async_content = b\"\".join([part async for part in response.stream])\n\n assert response.headers == {}\n assert sync_content == b\"\"\n assert async_content == b\"\""} {"repo":"httpx","file":"tests/test_content.py","line":433,"symbol":"test_response_bytes_content","kind":"function","lang":"python","code":"async def test_response_bytes_content():\n response = httpx.Response(200, content=b\"Hello, world!\")\n assert isinstance(response.stream, typing.Iterable)\n assert isinstance(response.stream, typing.AsyncIterable)\n\n sync_content = b\"\".join(list(response.stream))\n async_content = b\"\".join([part async for part in response.stream])\n\n assert response.headers == {\"Content-Length\": \"13\"}\n assert sync_content == b\"Hello, world!\"\n assert async_content == b\"Hello, world!\""} {"repo":"httpx","file":"tests/test_content.py","line":447,"symbol":"test_response_iterator_content","kind":"function","lang":"python","code":"async def test_response_iterator_content():\n def hello_world() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\"\n\n response = httpx.Response(200, content=hello_world())\n assert isinstance(response.stream, typing.Iterable)\n assert not isinstance(response.stream, typing.AsyncIterable)\n\n content = b\"\".join(list(response.stream))\n\n assert response.headers == {\"Transfer-Encoding\": \"chunked\"}\n assert content == b\"Hello, world!\"\n\n with pytest.raises(httpx.StreamConsumed):\n list(response.stream)"} {"repo":"httpx","file":"tests/test_content.py","line":448,"symbol":"hello_world","kind":"function","lang":"python","code":"def hello_world() -> typing.Iterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/test_content.py","line":466,"symbol":"test_response_aiterator_content","kind":"function","lang":"python","code":"async def test_response_aiterator_content():\n async def hello_world() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\"\n\n response = httpx.Response(200, content=hello_world())\n assert not isinstance(response.stream, typing.Iterable)\n assert isinstance(response.stream, typing.AsyncIterable)\n\n content = b\"\".join([part async for part in response.stream])\n\n assert response.headers == {\"Transfer-Encoding\": \"chunked\"}\n assert content == b\"Hello, world!\"\n\n with pytest.raises(httpx.StreamConsumed):\n [part async for part in response.stream]"} {"repo":"httpx","file":"tests/test_content.py","line":467,"symbol":"hello_world","kind":"function","lang":"python","code":"async def hello_world() -> typing.AsyncIterator[bytes]:\n yield b\"Hello, \"\n yield b\"world!\""} {"repo":"httpx","file":"tests/test_content.py","line":484,"symbol":"test_response_invalid_argument","kind":"function","lang":"python","code":"def test_response_invalid_argument():\n with pytest.raises(TypeError):\n httpx.Response(200, content=123) # type: ignore"} {"repo":"httpx","file":"tests/test_content.py","line":489,"symbol":"test_ensure_ascii_false_with_french_characters","kind":"function","lang":"python","code":"def test_ensure_ascii_false_with_french_characters():\n data = {\"greeting\": \"Bonjour, ça va ?\"}\n response = httpx.Response(200, json=data)\n assert \"ça va\" in response.text, (\n \"ensure_ascii=False should preserve French accented characters\"\n )\n assert response.headers[\"Content-Type\"] == \"application/json\""} {"repo":"httpx","file":"tests/test_content.py","line":498,"symbol":"test_separators_for_compact_json","kind":"function","lang":"python","code":"def test_separators_for_compact_json():\n data = {\"clé\": \"valeur\", \"liste\": [1, 2, 3]}\n response = httpx.Response(200, json=data)\n assert response.text == '{\"clé\":\"valeur\",\"liste\":[1,2,3]}', (\n \"separators=(',', ':') should produce a compact representation\"\n )\n assert response.headers[\"Content-Type\"] == \"application/json\""} {"repo":"httpx","file":"tests/test_content.py","line":507,"symbol":"test_allow_nan_false","kind":"function","lang":"python","code":"def test_allow_nan_false():\n data_with_nan = {\"nombre\": float(\"nan\")}\n data_with_inf = {\"nombre\": float(\"inf\")}\n\n with pytest.raises(\n ValueError, match=\"Out of range float values are not JSON compliant\"\n ):\n httpx.Response(200, json=data_with_nan)\n with pytest.raises(\n ValueError, match=\"Out of range float values are not JSON compliant\"\n ):\n httpx.Response(200, json=data_with_inf)"} {"repo":"httpx","file":"tests/test_decoders.py","line":14,"symbol":"test_deflate","kind":"function","lang":"python","code":"def test_deflate():\n \"\"\"\n Deflate encoding may use either 'zlib' or 'deflate' in the wild.\n\n https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297\n \"\"\"\n body = b\"test 123\"\n compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)\n compressed_body = compressor.compress(body) + compressor.flush()\n\n headers = [(b\"Content-Encoding\", b\"deflate\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":33,"symbol":"test_zlib","kind":"function","lang":"python","code":"def test_zlib():\n \"\"\"\n Deflate encoding may use either 'zlib' or 'deflate' in the wild.\n\n https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297\n \"\"\"\n body = b\"test 123\"\n compressed_body = zlib.compress(body)\n\n headers = [(b\"Content-Encoding\", b\"deflate\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":51,"symbol":"test_gzip","kind":"function","lang":"python","code":"def test_gzip():\n body = b\"test 123\"\n compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)\n compressed_body = compressor.compress(body) + compressor.flush()\n\n headers = [(b\"Content-Encoding\", b\"gzip\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":65,"symbol":"test_brotli","kind":"function","lang":"python","code":"def test_brotli():\n body = b\"test 123\"\n compressed_body = b\"\\x8b\\x03\\x80test 123\\x03\"\n\n headers = [(b\"Content-Encoding\", b\"br\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":78,"symbol":"test_zstd","kind":"function","lang":"python","code":"def test_zstd():\n body = b\"test 123\"\n compressed_body = zstd.compress(body)\n\n headers = [(b\"Content-Encoding\", b\"zstd\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":91,"symbol":"test_zstd_decoding_error","kind":"function","lang":"python","code":"def test_zstd_decoding_error():\n compressed_body = \"this_is_not_zstd_compressed_data\"\n\n headers = [(b\"Content-Encoding\", b\"zstd\")]\n with pytest.raises(httpx.DecodingError):\n httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )"} {"repo":"httpx","file":"tests/test_decoders.py","line":103,"symbol":"test_zstd_empty","kind":"function","lang":"python","code":"def test_zstd_empty():\n headers = [(b\"Content-Encoding\", b\"zstd\")]\n response = httpx.Response(200, headers=headers, content=b\"\")\n assert response.content == b\"\""} {"repo":"httpx","file":"tests/test_decoders.py","line":109,"symbol":"test_zstd_truncated","kind":"function","lang":"python","code":"def test_zstd_truncated():\n body = b\"test 123\"\n compressed_body = zstd.compress(body)\n\n headers = [(b\"Content-Encoding\", b\"zstd\")]\n with pytest.raises(httpx.DecodingError):\n httpx.Response(\n 200,\n headers=headers,\n content=compressed_body[1:3],\n )"} {"repo":"httpx","file":"tests/test_decoders.py","line":122,"symbol":"test_zstd_multiframe","kind":"function","lang":"python","code":"def test_zstd_multiframe():\n # test inspired by urllib3 test suite\n data = (\n # Zstandard frame\n zstd.compress(b\"foo\")\n # skippable frame (must be ignored)\n + bytes.fromhex(\n \"50 2A 4D 18\" # Magic_Number (little-endian)\n \"07 00 00 00\" # Frame_Size (little-endian)\n \"00 00 00 00 00 00 00\" # User_Data\n )\n # Zstandard frame\n + zstd.compress(b\"bar\")\n )\n compressed_body = io.BytesIO(data)\n\n headers = [(b\"Content-Encoding\", b\"zstd\")]\n response = httpx.Response(200, headers=headers, content=compressed_body)\n response.read()\n assert response.content == b\"foobar\""} {"repo":"httpx","file":"tests/test_decoders.py","line":144,"symbol":"test_multi","kind":"function","lang":"python","code":"def test_multi():\n body = b\"test 123\"\n\n deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)\n compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()\n\n gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)\n compressed_body = (\n gzip_compressor.compress(compressed_body) + gzip_compressor.flush()\n )\n\n headers = [(b\"Content-Encoding\", b\"deflate, gzip\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":164,"symbol":"test_multi_with_identity","kind":"function","lang":"python","code":"def test_multi_with_identity():\n body = b\"test 123\"\n compressed_body = b\"\\x8b\\x03\\x80test 123\\x03\"\n\n headers = [(b\"Content-Encoding\", b\"br, identity\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body\n\n headers = [(b\"Content-Encoding\", b\"identity, br\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compressed_body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":186,"symbol":"test_streaming","kind":"function","lang":"python","code":"async def test_streaming():\n body = b\"test 123\"\n compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)\n\n async def compress(body: bytes) -> typing.AsyncIterator[bytes]:\n yield compressor.compress(body)\n yield compressor.flush()\n\n headers = [(b\"Content-Encoding\", b\"gzip\")]\n response = httpx.Response(\n 200,\n headers=headers,\n content=compress(body),\n )\n assert not hasattr(response, \"body\")\n assert await response.aread() == body"} {"repo":"httpx","file":"tests/test_decoders.py","line":190,"symbol":"compress","kind":"function","lang":"python","code":"async def compress(body: bytes) -> typing.AsyncIterator[bytes]:\n yield compressor.compress(body)\n yield compressor.flush()"} {"repo":"httpx","file":"tests/test_decoders.py","line":205,"symbol":"test_empty_content","kind":"function","lang":"python","code":"def test_empty_content(header_value):\n headers = [(b\"Content-Encoding\", header_value)]\n response = httpx.Response(\n 200,\n headers=headers,\n content=b\"\",\n )\n assert response.content == b\"\""} {"repo":"httpx","file":"tests/test_decoders.py","line":216,"symbol":"test_decoders_empty_cases","kind":"function","lang":"python","code":"def test_decoders_empty_cases(header_value):\n headers = [(b\"Content-Encoding\", header_value)]\n response = httpx.Response(content=b\"\", status_code=200, headers=headers)\n assert response.read() == b\"\""} {"repo":"httpx","file":"tests/test_decoders.py","line":223,"symbol":"test_decoding_errors","kind":"function","lang":"python","code":"def test_decoding_errors(header_value):\n headers = [(b\"Content-Encoding\", header_value)]\n compressed_body = b\"invalid\"\n with pytest.raises(httpx.DecodingError):\n request = httpx.Request(\"GET\", \"https://example.org\")\n httpx.Response(200, headers=headers, content=compressed_body, request=request)\n\n with pytest.raises(httpx.DecodingError):\n httpx.Response(200, headers=headers, content=compressed_body)"} {"repo":"httpx","file":"tests/test_decoders.py","line":244,"symbol":"test_text_decoder_with_autodetect","kind":"function","lang":"python","code":"async def test_text_decoder_with_autodetect(data, encoding):\n async def iterator() -> typing.AsyncIterator[bytes]:\n nonlocal data\n for chunk in data:\n yield chunk\n\n def autodetect(content):\n return chardet.detect(content).get(\"encoding\")\n\n # Accessing `.text` on a read response.\n response = httpx.Response(200, content=iterator(), default_encoding=autodetect)\n await response.aread()\n assert response.text == (b\"\".join(data)).decode(encoding)\n\n # Streaming `.aiter_text` iteratively.\n # Note that if we streamed the text *without* having read it first, then\n # we won't get a `charset_normalizer` guess, and will instead always rely\n # on utf-8 if no charset is specified.\n text = \"\".join([part async for part in response.aiter_text()])\n assert text == (b\"\".join(data)).decode(encoding)"} {"repo":"httpx","file":"tests/test_decoders.py","line":245,"symbol":"iterator","kind":"function","lang":"python","code":"async def iterator() -> typing.AsyncIterator[bytes]:\n nonlocal data\n for chunk in data:\n yield chunk"} {"repo":"httpx","file":"tests/test_decoders.py","line":250,"symbol":"autodetect","kind":"function","lang":"python","code":"def autodetect(content):\n return chardet.detect(content).get(\"encoding\")"} {"repo":"httpx","file":"tests/test_decoders.py","line":267,"symbol":"test_text_decoder_known_encoding","kind":"function","lang":"python","code":"async def test_text_decoder_known_encoding():\n async def iterator() -> typing.AsyncIterator[bytes]:\n yield b\"\\x83g\"\n yield b\"\\x83\"\n yield b\"\\x89\\x83x\\x83\\x8b\"\n\n response = httpx.Response(\n 200,\n headers=[(b\"Content-Type\", b\"text/html; charset=shift-jis\")],\n content=iterator(),\n )\n\n await response.aread()\n assert \"\".join(response.text) == \"トラベル\""} {"repo":"httpx","file":"tests/test_decoders.py","line":268,"symbol":"iterator","kind":"function","lang":"python","code":"async def iterator() -> typing.AsyncIterator[bytes]:\n yield b\"\\x83g\"\n yield b\"\\x83\"\n yield b\"\\x89\\x83x\\x83\\x8b\""} {"repo":"httpx","file":"tests/test_decoders.py","line":283,"symbol":"test_text_decoder_empty_cases","kind":"function","lang":"python","code":"def test_text_decoder_empty_cases():\n response = httpx.Response(200, content=b\"\")\n assert response.text == \"\"\n\n response = httpx.Response(200, content=[b\"\"])\n response.read()\n assert response.text == \"\""} {"repo":"httpx","file":"tests/test_decoders.py","line":296,"symbol":"test_streaming_text_decoder","kind":"function","lang":"python","code":"def test_streaming_text_decoder(\n data: typing.Iterable[bytes], expected: list[str]\n) -> None:\n response = httpx.Response(200, content=iter(data))\n assert list(response.iter_text()) == expected"} {"repo":"httpx","file":"tests/test_decoders.py","line":303,"symbol":"test_line_decoder_nl","kind":"function","lang":"python","code":"def test_line_decoder_nl():\n response = httpx.Response(200, content=[b\"\"])\n assert list(response.iter_lines()) == []\n\n response = httpx.Response(200, content=[b\"\", b\"a\\n\\nb\\nc\"])\n assert list(response.iter_lines()) == [\"a\", \"\", \"b\", \"c\"]\n\n # Issue #1033\n response = httpx.Response(\n 200, content=[b\"\", b\"12345\\n\", b\"foo \", b\"bar \", b\"baz\\n\"]\n )\n assert list(response.iter_lines()) == [\"12345\", \"foo bar baz\"]"} {"repo":"httpx","file":"tests/test_decoders.py","line":317,"symbol":"test_line_decoder_cr","kind":"function","lang":"python","code":"def test_line_decoder_cr():\n response = httpx.Response(200, content=[b\"\", b\"a\\r\\rb\\rc\"])\n assert list(response.iter_lines()) == [\"a\", \"\", \"b\", \"c\"]\n\n response = httpx.Response(200, content=[b\"\", b\"a\\r\\rb\\rc\\r\"])\n assert list(response.iter_lines()) == [\"a\", \"\", \"b\", \"c\"]\n\n # Issue #1033\n response = httpx.Response(\n 200, content=[b\"\", b\"12345\\r\", b\"foo \", b\"bar \", b\"baz\\r\"]\n )\n assert list(response.iter_lines()) == [\"12345\", \"foo bar baz\"]"} {"repo":"httpx","file":"tests/test_decoders.py","line":331,"symbol":"test_line_decoder_crnl","kind":"function","lang":"python","code":"def test_line_decoder_crnl():\n response = httpx.Response(200, content=[b\"\", b\"a\\r\\n\\r\\nb\\r\\nc\"])\n assert list(response.iter_lines()) == [\"a\", \"\", \"b\", \"c\"]\n\n response = httpx.Response(200, content=[b\"\", b\"a\\r\\n\\r\\nb\\r\\nc\\r\\n\"])\n assert list(response.iter_lines()) == [\"a\", \"\", \"b\", \"c\"]\n\n response = httpx.Response(200, content=[b\"\", b\"a\\r\", b\"\\n\\r\\nb\\r\\nc\"])\n assert list(response.iter_lines()) == [\"a\", \"\", \"b\", \"c\"]\n\n # Issue #1033\n response = httpx.Response(200, content=[b\"\", b\"12345\\r\\n\", b\"foo bar baz\\r\\n\"])\n assert list(response.iter_lines()) == [\"12345\", \"foo bar baz\"]"} {"repo":"httpx","file":"tests/test_decoders.py","line":346,"symbol":"test_invalid_content_encoding_header","kind":"function","lang":"python","code":"def test_invalid_content_encoding_header():\n headers = [(b\"Content-Encoding\", b\"invalid-header\")]\n body = b\"test 123\"\n\n response = httpx.Response(\n 200,\n headers=headers,\n content=body,\n )\n assert response.content == body"} {"repo":"httpx","file":"tests/test_exceptions.py","line":14,"symbol":"test_httpcore_all_exceptions_mapped","kind":"function","lang":"python","code":"def test_httpcore_all_exceptions_mapped() -> None:\n \"\"\"\n All exception classes exposed by HTTPCore are properly mapped to an HTTPX-specific\n exception class.\n \"\"\"\n expected_mapped_httpcore_exceptions = {\n value.__name__\n for _, value in vars(httpcore).items()\n if isinstance(value, type)\n and issubclass(value, Exception)\n and value is not httpcore.ConnectionNotAvailable\n }\n\n httpx_exceptions = {\n value.__name__\n for _, value in vars(httpx).items()\n if isinstance(value, type) and issubclass(value, Exception)\n }\n\n unmapped_exceptions = expected_mapped_httpcore_exceptions - httpx_exceptions\n\n if unmapped_exceptions: # pragma: no cover\n pytest.fail(f\"Unmapped httpcore exceptions: {unmapped_exceptions}\")"} {"repo":"httpx","file":"tests/test_exceptions.py","line":39,"symbol":"test_httpcore_exception_mapping","kind":"function","lang":"python","code":"def test_httpcore_exception_mapping(server: TestServer) -> None:\n \"\"\"\n HTTPCore exception mapping works as expected.\n \"\"\"\n impossible_port = 123456\n with pytest.raises(httpx.ConnectError):\n httpx.get(server.url.copy_with(port=impossible_port))\n\n with pytest.raises(httpx.ReadTimeout):\n httpx.get(\n server.url.copy_with(path=\"/slow_response\"),\n timeout=httpx.Timeout(5, read=0.01),\n )"} {"repo":"httpx","file":"tests/test_exceptions.py","line":54,"symbol":"test_request_attribute","kind":"function","lang":"python","code":"def test_request_attribute() -> None:\n # Exception without request attribute\n exc = httpx.ReadTimeout(\"Read operation timed out\")\n with pytest.raises(RuntimeError):\n exc.request # noqa: B018\n\n # Exception with request attribute\n request = httpx.Request(\"GET\", \"https://www.example.com\")\n exc = httpx.ReadTimeout(\"Read operation timed out\", request=request)\n assert exc.request == request"} {"repo":"httpx","file":"tests/test_exported_members.py","line":4,"symbol":"test_all_imports_are_exported","kind":"function","lang":"python","code":"def test_all_imports_are_exported() -> None:\n included_private_members = [\"__description__\", \"__title__\", \"__version__\"]\n assert httpx.__all__ == sorted(\n (\n member\n for member in vars(httpx).keys()\n if not member.startswith(\"_\") or member in included_private_members\n ),\n key=str.casefold,\n )"} {"repo":"httpx","file":"tests/test_main.py","line":9,"symbol":"splitlines","kind":"function","lang":"python","code":"def splitlines(output: str) -> typing.Iterable[str]:\n return [line.strip() for line in output.splitlines()]"} {"repo":"httpx","file":"tests/test_main.py","line":13,"symbol":"remove_date_header","kind":"function","lang":"python","code":"def remove_date_header(lines: typing.Iterable[str]) -> typing.Iterable[str]:\n return [line for line in lines if not line.startswith(\"date:\")]"} {"repo":"httpx","file":"tests/test_main.py","line":17,"symbol":"test_help","kind":"function","lang":"python","code":"def test_help():\n runner = CliRunner()\n result = runner.invoke(httpx.main, [\"--help\"])\n assert result.exit_code == 0\n assert \"A next generation HTTP client.\" in result.output"} {"repo":"httpx","file":"tests/test_main.py","line":24,"symbol":"test_get","kind":"function","lang":"python","code":"def test_get(server):\n url = str(server.url)\n runner = CliRunner()\n result = runner.invoke(httpx.main, [url])\n assert result.exit_code == 0\n assert remove_date_header(splitlines(result.output)) == [\n \"HTTP/1.1 200 OK\",\n \"server: uvicorn\",\n \"content-type: text/plain\",\n \"Transfer-Encoding: chunked\",\n \"\",\n \"Hello, world!\",\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":39,"symbol":"test_json","kind":"function","lang":"python","code":"def test_json(server):\n url = str(server.url.copy_with(path=\"/json\"))\n runner = CliRunner()\n result = runner.invoke(httpx.main, [url])\n assert result.exit_code == 0\n assert remove_date_header(splitlines(result.output)) == [\n \"HTTP/1.1 200 OK\",\n \"server: uvicorn\",\n \"content-type: application/json\",\n \"Transfer-Encoding: chunked\",\n \"\",\n \"{\",\n '\"Hello\": \"world!\"',\n \"}\",\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":56,"symbol":"test_binary","kind":"function","lang":"python","code":"def test_binary(server):\n url = str(server.url.copy_with(path=\"/echo_binary\"))\n runner = CliRunner()\n content = \"Hello, world!\"\n result = runner.invoke(httpx.main, [url, \"-c\", content])\n assert result.exit_code == 0\n assert remove_date_header(splitlines(result.output)) == [\n \"HTTP/1.1 200 OK\",\n \"server: uvicorn\",\n \"content-type: application/octet-stream\",\n \"Transfer-Encoding: chunked\",\n \"\",\n f\"<{len(content)} bytes of binary data>\",\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":72,"symbol":"test_redirects","kind":"function","lang":"python","code":"def test_redirects(server):\n url = str(server.url.copy_with(path=\"/redirect_301\"))\n runner = CliRunner()\n result = runner.invoke(httpx.main, [url])\n assert result.exit_code == 1\n assert remove_date_header(splitlines(result.output)) == [\n \"HTTP/1.1 301 Moved Permanently\",\n \"server: uvicorn\",\n \"location: /\",\n \"Transfer-Encoding: chunked\",\n \"\",\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":86,"symbol":"test_follow_redirects","kind":"function","lang":"python","code":"def test_follow_redirects(server):\n url = str(server.url.copy_with(path=\"/redirect_301\"))\n runner = CliRunner()\n result = runner.invoke(httpx.main, [url, \"--follow-redirects\"])\n assert result.exit_code == 0\n assert remove_date_header(splitlines(result.output)) == [\n \"HTTP/1.1 301 Moved Permanently\",\n \"server: uvicorn\",\n \"location: /\",\n \"Transfer-Encoding: chunked\",\n \"\",\n \"HTTP/1.1 200 OK\",\n \"server: uvicorn\",\n \"content-type: text/plain\",\n \"Transfer-Encoding: chunked\",\n \"\",\n \"Hello, world!\",\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":106,"symbol":"test_post","kind":"function","lang":"python","code":"def test_post(server):\n url = str(server.url.copy_with(path=\"/echo_body\"))\n runner = CliRunner()\n result = runner.invoke(httpx.main, [url, \"-m\", \"POST\", \"-j\", '{\"hello\": \"world\"}'])\n assert result.exit_code == 0\n assert remove_date_header(splitlines(result.output)) == [\n \"HTTP/1.1 200 OK\",\n \"server: uvicorn\",\n \"content-type: text/plain\",\n \"Transfer-Encoding: chunked\",\n \"\",\n '{\"hello\":\"world\"}',\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":121,"symbol":"test_verbose","kind":"function","lang":"python","code":"def test_verbose(server):\n url = str(server.url)\n runner = CliRunner()\n result = runner.invoke(httpx.main, [url, \"-v\"])\n assert result.exit_code == 0\n assert remove_date_header(splitlines(result.output)) == [\n \"* Connecting to '127.0.0.1'\",\n \"* Connected to '127.0.0.1' on port 8000\",\n \"GET / HTTP/1.1\",\n f\"Host: {server.url.netloc.decode('ascii')}\",\n \"Accept: */*\",\n \"Accept-Encoding: gzip, deflate, br, zstd\",\n \"Connection: keep-alive\",\n f\"User-Agent: python-httpx/{httpx.__version__}\",\n \"\",\n \"HTTP/1.1 200 OK\",\n \"server: uvicorn\",\n \"content-type: text/plain\",\n \"Transfer-Encoding: chunked\",\n \"\",\n \"Hello, world!\",\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":145,"symbol":"test_auth","kind":"function","lang":"python","code":"def test_auth(server):\n url = str(server.url)\n runner = CliRunner()\n result = runner.invoke(httpx.main, [url, \"-v\", \"--auth\", \"username\", \"password\"])\n print(result.output)\n assert result.exit_code == 0\n assert remove_date_header(splitlines(result.output)) == [\n \"* Connecting to '127.0.0.1'\",\n \"* Connected to '127.0.0.1' on port 8000\",\n \"GET / HTTP/1.1\",\n f\"Host: {server.url.netloc.decode('ascii')}\",\n \"Accept: */*\",\n \"Accept-Encoding: gzip, deflate, br, zstd\",\n \"Connection: keep-alive\",\n f\"User-Agent: python-httpx/{httpx.__version__}\",\n \"Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\",\n \"\",\n \"HTTP/1.1 200 OK\",\n \"server: uvicorn\",\n \"content-type: text/plain\",\n \"Transfer-Encoding: chunked\",\n \"\",\n \"Hello, world!\",\n ]"} {"repo":"httpx","file":"tests/test_main.py","line":171,"symbol":"test_download","kind":"function","lang":"python","code":"def test_download(server):\n url = str(server.url)\n runner = CliRunner()\n with runner.isolated_filesystem():\n runner.invoke(httpx.main, [url, \"--download\", \"index.txt\"])\n assert os.path.exists(\"index.txt\")\n with open(\"index.txt\", \"r\") as input_file:\n assert input_file.read() == \"Hello, world!\""} {"repo":"httpx","file":"tests/test_main.py","line":181,"symbol":"test_errors","kind":"function","lang":"python","code":"def test_errors():\n runner = CliRunner()\n result = runner.invoke(httpx.main, [\"invalid://example.org\"])\n assert result.exit_code == 1\n assert splitlines(result.output) == [\n \"UnsupportedProtocol: Request URL has an unsupported protocol 'invalid://'.\",\n ]"} {"repo":"httpx","file":"tests/test_multipart.py","line":12,"symbol":"echo_request_content","kind":"function","lang":"python","code":"def echo_request_content(request: httpx.Request) -> httpx.Response:\n return httpx.Response(200, content=request.content)"} {"repo":"httpx","file":"tests/test_multipart.py","line":17,"symbol":"test_multipart","kind":"function","lang":"python","code":"def test_multipart(value, output):\n client = httpx.Client(transport=httpx.MockTransport(echo_request_content))\n\n # Test with a single-value 'data' argument, and a plain file 'files' argument.\n data = {\"text\": value}\n files = {\"file\": io.BytesIO(b\"\")}\n response = client.post(\"http://127.0.0.1:8000/\", data=data, files=files)\n boundary = response.request.headers[\"Content-Type\"].split(\"boundary=\")[-1]\n boundary_bytes = boundary.encode(\"ascii\")\n\n assert response.status_code == 200\n assert response.content == b\"\".join(\n [\n b\"--\" + boundary_bytes + b\"\\r\\n\",\n b'Content-Disposition: form-data; name=\"text\"\\r\\n',\n b\"\\r\\n\",\n b\"abc\\r\\n\",\n b\"--\" + boundary_bytes + b\"\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n',\n b\"Content-Type: application/octet-stream\\r\\n\",\n b\"\\r\\n\",\n b\"\\r\\n\",\n b\"--\" + boundary_bytes + b\"--\\r\\n\",\n ]\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":57,"symbol":"test_multipart_explicit_boundary","kind":"function","lang":"python","code":"def test_multipart_explicit_boundary(header: str) -> None:\n client = httpx.Client(transport=httpx.MockTransport(echo_request_content))\n\n files = {\"file\": io.BytesIO(b\"\")}\n headers = {\"content-type\": header}\n response = client.post(\"http://127.0.0.1:8000/\", files=files, headers=headers)\n boundary_bytes = b\"+++\"\n\n assert response.status_code == 200\n assert response.request.headers[\"Content-Type\"] == header\n assert response.content == b\"\".join(\n [\n b\"--\" + boundary_bytes + b\"\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n',\n b\"Content-Type: application/octet-stream\\r\\n\",\n b\"\\r\\n\",\n b\"\\r\\n\",\n b\"--\" + boundary_bytes + b\"--\\r\\n\",\n ]\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":86,"symbol":"test_multipart_header_without_boundary","kind":"function","lang":"python","code":"def test_multipart_header_without_boundary(header: str) -> None:\n client = httpx.Client(transport=httpx.MockTransport(echo_request_content))\n\n files = {\"file\": io.BytesIO(b\"\")}\n headers = {\"content-type\": header}\n response = client.post(\"http://127.0.0.1:8000/\", files=files, headers=headers)\n\n assert response.status_code == 200\n assert response.request.headers[\"Content-Type\"] == header"} {"repo":"httpx","file":"tests/test_multipart.py","line":98,"symbol":"test_multipart_invalid_key","kind":"function","lang":"python","code":"def test_multipart_invalid_key(key):\n client = httpx.Client(transport=httpx.MockTransport(echo_request_content))\n\n data = {key: \"abc\"}\n files = {\"file\": io.BytesIO(b\"\")}\n with pytest.raises(TypeError) as e:\n client.post(\n \"http://127.0.0.1:8000/\",\n data=data,\n files=files,\n )\n assert \"Invalid type for name\" in str(e.value)\n assert repr(key) in str(e.value)"} {"repo":"httpx","file":"tests/test_multipart.py","line":114,"symbol":"test_multipart_invalid_value","kind":"function","lang":"python","code":"def test_multipart_invalid_value(value):\n client = httpx.Client(transport=httpx.MockTransport(echo_request_content))\n\n data = {\"text\": value}\n files = {\"file\": io.BytesIO(b\"\")}\n with pytest.raises(TypeError) as e:\n client.post(\"http://127.0.0.1:8000/\", data=data, files=files)\n assert \"Invalid type for value\" in str(e.value)"} {"repo":"httpx","file":"tests/test_multipart.py","line":124,"symbol":"test_multipart_file_tuple","kind":"function","lang":"python","code":"def test_multipart_file_tuple():\n client = httpx.Client(transport=httpx.MockTransport(echo_request_content))\n\n # Test with a list of values 'data' argument,\n # and a tuple style 'files' argument.\n data = {\"text\": [\"abc\"]}\n files = {\"file\": (\"name.txt\", io.BytesIO(b\"\"))}\n response = client.post(\"http://127.0.0.1:8000/\", data=data, files=files)\n boundary = response.request.headers[\"Content-Type\"].split(\"boundary=\")[-1]\n boundary_bytes = boundary.encode(\"ascii\")\n\n assert response.status_code == 200\n assert response.content == b\"\".join(\n [\n b\"--\" + boundary_bytes + b\"\\r\\n\",\n b'Content-Disposition: form-data; name=\"text\"\\r\\n',\n b\"\\r\\n\",\n b\"abc\\r\\n\",\n b\"--\" + boundary_bytes + b\"\\r\\n\",\n b'Content-Disposition: form-data; name=\"file\"; filename=\"name.txt\"\\r\\n',\n b\"Content-Type: text/plain\\r\\n\",\n b\"\\r\\n\",\n b\"\\r\\n\",\n b\"--\" + boundary_bytes + b\"--\\r\\n\",\n ]\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":153,"symbol":"test_multipart_file_tuple_headers","kind":"function","lang":"python","code":"def test_multipart_file_tuple_headers(file_content_type: str | None) -> None:\n file_name = \"test.txt\"\n file_content = io.BytesIO(b\"\")\n file_headers = {\"Expires\": \"0\"}\n\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n files = {\"file\": (file_name, file_content, file_content_type, file_headers)}\n\n request = httpx.Request(\"POST\", url, headers=headers, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n f'--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"file\"; '\n f'filename=\"{file_name}\"\\r\\nExpires: 0\\r\\nContent-Type: '\n f\"text/plain\\r\\n\\r\\n\\r\\n--BOUNDARY--\\r\\n\"\n \"\".encode(\"ascii\")\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":178,"symbol":"test_multipart_headers_include_content_type","kind":"function","lang":"python","code":"def test_multipart_headers_include_content_type() -> None:\n \"\"\"\n Content-Type from 4th tuple parameter (headers) should\n override the 3rd parameter (content_type)\n \"\"\"\n file_name = \"test.txt\"\n file_content = io.BytesIO(b\"\")\n file_content_type = \"text/plain\"\n file_headers = {\"Content-Type\": \"image/png\"}\n\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n files = {\"file\": (file_name, file_content, file_content_type, file_headers)}\n\n request = httpx.Request(\"POST\", url, headers=headers, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n f'--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"file\"; '\n f'filename=\"{file_name}\"\\r\\nContent-Type: '\n f\"image/png\\r\\n\\r\\n\\r\\n--BOUNDARY--\\r\\n\"\n \"\".encode(\"ascii\")\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":208,"symbol":"test_multipart_encode","kind":"function","lang":"python","code":"def test_multipart_encode(tmp_path: typing.Any) -> None:\n path = str(tmp_path / \"name.txt\")\n with open(path, \"wb\") as f:\n f.write(b\"\")\n\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n data = {\n \"a\": \"1\",\n \"b\": b\"C\",\n \"c\": [\"11\", \"22\", \"33\"],\n \"d\": \"\",\n \"e\": True,\n \"f\": \"\",\n }\n with open(path, \"rb\") as input_file:\n files = {\"file\": (\"name.txt\", input_file)}\n\n request = httpx.Request(\"POST\", url, headers=headers, data=data, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n '--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"a\"\\r\\n\\r\\n1\\r\\n'\n '--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"b\"\\r\\n\\r\\nC\\r\\n'\n '--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"c\"\\r\\n\\r\\n11\\r\\n'\n '--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"c\"\\r\\n\\r\\n22\\r\\n'\n "} {"repo":"httpx","file":"tests/test_multipart.py","line":251,"symbol":"test_multipart_encode_unicode_file_contents","kind":"function","lang":"python","code":"def test_multipart_encode_unicode_file_contents() -> None:\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n files = {\"file\": (\"name.txt\", b\"\")}\n\n request = httpx.Request(\"POST\", url, headers=headers, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n b'--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"file\";'\n b' filename=\"name.txt\"\\r\\n'\n b\"Content-Type: text/plain\\r\\n\\r\\n\\r\\n\"\n b\"--BOUNDARY--\\r\\n\"\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":272,"symbol":"test_multipart_encode_files_allows_filenames_as_none","kind":"function","lang":"python","code":"def test_multipart_encode_files_allows_filenames_as_none() -> None:\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n files = {\"file\": (None, io.BytesIO(b\"\"))}\n\n request = httpx.Request(\"POST\", url, headers=headers, data={}, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n '--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"file\"\\r\\n\\r\\n'\n \"\\r\\n--BOUNDARY--\\r\\n\"\n \"\".encode(\"ascii\")\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":300,"symbol":"test_multipart_encode_files_guesses_correct_content_type","kind":"function","lang":"python","code":"def test_multipart_encode_files_guesses_correct_content_type(\n file_name: str, expected_content_type: str\n) -> None:\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n files = {\"file\": (file_name, io.BytesIO(b\"\"))}\n\n request = httpx.Request(\"POST\", url, headers=headers, data={}, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n f'--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"file\"; '\n f'filename=\"{file_name}\"\\r\\nContent-Type: '\n f\"{expected_content_type}\\r\\n\\r\\n\\r\\n--BOUNDARY--\\r\\n\"\n \"\".encode(\"ascii\")\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":323,"symbol":"test_multipart_encode_files_allows_bytes_content","kind":"function","lang":"python","code":"def test_multipart_encode_files_allows_bytes_content() -> None:\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n files = {\"file\": (\"test.txt\", b\"\", \"text/plain\")}\n\n request = httpx.Request(\"POST\", url, headers=headers, data={}, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n '--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"file\"; '\n 'filename=\"test.txt\"\\r\\n'\n \"Content-Type: text/plain\\r\\n\\r\\n\\r\\n\"\n \"--BOUNDARY--\\r\\n\"\n \"\".encode(\"ascii\")\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":345,"symbol":"test_multipart_encode_files_allows_str_content","kind":"function","lang":"python","code":"def test_multipart_encode_files_allows_str_content() -> None:\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n files = {\"file\": (\"test.txt\", \"\", \"text/plain\")}\n\n request = httpx.Request(\"POST\", url, headers=headers, data={}, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Content-Length\": str(len(request.content)),\n }\n assert request.content == (\n '--BOUNDARY\\r\\nContent-Disposition: form-data; name=\"file\"; '\n 'filename=\"test.txt\"\\r\\n'\n \"Content-Type: text/plain\\r\\n\\r\\n\\r\\n\"\n \"--BOUNDARY--\\r\\n\"\n \"\".encode(\"ascii\")\n )"} {"repo":"httpx","file":"tests/test_multipart.py","line":367,"symbol":"test_multipart_encode_files_raises_exception_with_StringIO_content","kind":"function","lang":"python","code":"def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:\n url = \"https://www.example.com\"\n files = {\"file\": (\"test.txt\", io.StringIO(\"content\"), \"text/plain\")}\n with pytest.raises(TypeError):\n httpx.Request(\"POST\", url, data={}, files=files) # type: ignore"} {"repo":"httpx","file":"tests/test_multipart.py","line":374,"symbol":"test_multipart_encode_files_raises_exception_with_text_mode_file","kind":"function","lang":"python","code":"def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:\n url = \"https://www.example.com\"\n with tempfile.TemporaryFile(mode=\"w\") as upload:\n files = {\"file\": (\"test.txt\", upload, \"text/plain\")}\n with pytest.raises(TypeError):\n httpx.Request(\"POST\", url, data={}, files=files) # type: ignore"} {"repo":"httpx","file":"tests/test_multipart.py","line":382,"symbol":"test_multipart_encode_non_seekable_filelike","kind":"function","lang":"python","code":"def test_multipart_encode_non_seekable_filelike() -> None:\n \"\"\"\n Test that special readable but non-seekable filelike objects are supported.\n In this case uploads with use 'Transfer-Encoding: chunked', instead of\n a 'Content-Length' header.\n \"\"\"\n\n class IteratorIO(io.IOBase):\n def __init__(self, iterator: typing.Iterator[bytes]) -> None:\n self._iterator = iterator\n\n def read(self, *args: typing.Any) -> bytes:\n return b\"\".join(self._iterator)\n\n def data() -> typing.Iterator[bytes]:\n yield b\"Hello\"\n yield b\"World\"\n\n url = \"https://www.example.com/\"\n headers = {\"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\"}\n fileobj: typing.Any = IteratorIO(data())\n files = {\"file\": fileobj}\n\n request = httpx.Request(\"POST\", url, headers=headers, files=files)\n request.read()\n\n assert request.headers == {\n \"Host\": \"www.example.com\",\n \"Content-Type\": \"multipart/form-data; boundary=BOUNDARY\",\n \"Transfer-Encoding\": \"chunked\",\n }\n assert request.content == (\n b\"--BOUNDARY\\r\\n\"\n b'Content-Disposition: form-data; name=\"file\"; filename=\"upload\"\\r\\n'\n b\"Content-"} {"repo":"httpx","file":"tests/test_multipart.py","line":389,"symbol":"IteratorIO","kind":"class","lang":"python","code":"class IteratorIO(io.IOBase):\n def __init__(self, iterator: typing.Iterator[bytes]) -> None:\n self._iterator = iterator\n\n def read(self, *args: typing.Any) -> bytes:\n return b\"\".join(self._iterator)"} {"repo":"httpx","file":"tests/test_multipart.py","line":390,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, iterator: typing.Iterator[bytes]) -> None:\n self._iterator = iterator"} {"repo":"httpx","file":"tests/test_multipart.py","line":393,"symbol":"read","kind":"function","lang":"python","code":"def read(self, *args: typing.Any) -> bytes:\n return b\"\".join(self._iterator)"} {"repo":"httpx","file":"tests/test_multipart.py","line":396,"symbol":"data","kind":"function","lang":"python","code":"def data() -> typing.Iterator[bytes]:\n yield b\"Hello\"\n yield b\"World\""} {"repo":"httpx","file":"tests/test_multipart.py","line":423,"symbol":"test_multipart_rewinds_files","kind":"function","lang":"python","code":"def test_multipart_rewinds_files():\n with tempfile.TemporaryFile() as upload:\n upload.write(b\"Hello, world!\")\n\n transport = httpx.MockTransport(echo_request_content)\n client = httpx.Client(transport=transport)\n\n files = {\"file\": upload}\n response = client.post(\"http://127.0.0.1:8000/\", files=files)\n assert response.status_code == 200\n assert b\"\\r\\nHello, world!\\r\\n\" in response.content\n\n # POSTing the same file instance a second time should have the same content.\n files = {\"file\": upload}\n response = client.post(\"http://127.0.0.1:8000/\", files=files)\n assert response.status_code == 200\n assert b\"\\r\\nHello, world!\\r\\n\" in response.content"} {"repo":"httpx","file":"tests/test_multipart.py","line":442,"symbol":"TestHeaderParamHTML5Formatting","kind":"class","lang":"python","code":"class TestHeaderParamHTML5Formatting:\n def test_unicode(self):\n filename = \"n\\u00e4me\"\n expected = b'filename=\"n\\xc3\\xa4me\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in request.read()\n\n def test_ascii(self):\n filename = \"name\"\n expected = b'filename=\"name\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in request.read()\n\n def test_unicode_escape(self):\n filename = \"hello\\\\world\\u0022\"\n expected = b'filename=\"hello\\\\\\\\world%22\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in request.read()\n\n def test_unicode_with_control_character(self):\n filename = \"hello\\x1a\\x1b\\x1c\"\n expected = b'filename=\"hello%1A\\x1b%1C\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in"} {"repo":"httpx","file":"tests/test_multipart.py","line":443,"symbol":"test_unicode","kind":"function","lang":"python","code":"def test_unicode(self):\n filename = \"n\\u00e4me\"\n expected = b'filename=\"n\\xc3\\xa4me\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in request.read()"} {"repo":"httpx","file":"tests/test_multipart.py","line":450,"symbol":"test_ascii","kind":"function","lang":"python","code":"def test_ascii(self):\n filename = \"name\"\n expected = b'filename=\"name\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in request.read()"} {"repo":"httpx","file":"tests/test_multipart.py","line":457,"symbol":"test_unicode_escape","kind":"function","lang":"python","code":"def test_unicode_escape(self):\n filename = \"hello\\\\world\\u0022\"\n expected = b'filename=\"hello\\\\\\\\world%22\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in request.read()"} {"repo":"httpx","file":"tests/test_multipart.py","line":464,"symbol":"test_unicode_with_control_character","kind":"function","lang":"python","code":"def test_unicode_with_control_character(self):\n filename = \"hello\\x1a\\x1b\\x1c\"\n expected = b'filename=\"hello%1A\\x1b%1C\"'\n files = {\"upload\": (filename, b\"\")}\n request = httpx.Request(\"GET\", \"https://www.example.com\", files=files)\n assert expected in request.read()"} {"repo":"httpx","file":"tests/test_status_codes.py","line":4,"symbol":"test_status_code_as_int","kind":"function","lang":"python","code":"def test_status_code_as_int():\n # mypy doesn't (yet) recognize that IntEnum members are ints, so ignore it here\n assert httpx.codes.NOT_FOUND == 404 # type: ignore[comparison-overlap]\n assert str(httpx.codes.NOT_FOUND) == \"404\""} {"repo":"httpx","file":"tests/test_status_codes.py","line":10,"symbol":"test_status_code_value_lookup","kind":"function","lang":"python","code":"def test_status_code_value_lookup():\n assert httpx.codes(404) == 404"} {"repo":"httpx","file":"tests/test_status_codes.py","line":14,"symbol":"test_status_code_phrase_lookup","kind":"function","lang":"python","code":"def test_status_code_phrase_lookup():\n assert httpx.codes[\"NOT_FOUND\"] == 404"} {"repo":"httpx","file":"tests/test_status_codes.py","line":18,"symbol":"test_lowercase_status_code","kind":"function","lang":"python","code":"def test_lowercase_status_code():\n assert httpx.codes.not_found == 404 # type: ignore"} {"repo":"httpx","file":"tests/test_status_codes.py","line":22,"symbol":"test_reason_phrase_for_status_code","kind":"function","lang":"python","code":"def test_reason_phrase_for_status_code():\n assert httpx.codes.get_reason_phrase(404) == \"Not Found\""} {"repo":"httpx","file":"tests/test_status_codes.py","line":26,"symbol":"test_reason_phrase_for_unknown_status_code","kind":"function","lang":"python","code":"def test_reason_phrase_for_unknown_status_code():\n assert httpx.codes.get_reason_phrase(499) == \"\""} {"repo":"httpx","file":"tests/test_timeouts.py","line":7,"symbol":"test_read_timeout","kind":"function","lang":"python","code":"async def test_read_timeout(server):\n timeout = httpx.Timeout(None, read=1e-6)\n\n async with httpx.AsyncClient(timeout=timeout) as client:\n with pytest.raises(httpx.ReadTimeout):\n await client.get(server.url.copy_with(path=\"/slow_response\"))"} {"repo":"httpx","file":"tests/test_timeouts.py","line":16,"symbol":"test_write_timeout","kind":"function","lang":"python","code":"async def test_write_timeout(server):\n timeout = httpx.Timeout(None, write=1e-6)\n\n async with httpx.AsyncClient(timeout=timeout) as client:\n with pytest.raises(httpx.WriteTimeout):\n data = b\"*\" * 1024 * 1024 * 100\n await client.put(server.url.copy_with(path=\"/slow_response\"), content=data)"} {"repo":"httpx","file":"tests/test_timeouts.py","line":27,"symbol":"test_connect_timeout","kind":"function","lang":"python","code":"async def test_connect_timeout(server):\n timeout = httpx.Timeout(None, connect=1e-6)\n\n async with httpx.AsyncClient(timeout=timeout) as client:\n with pytest.raises(httpx.ConnectTimeout):\n # See https://stackoverflow.com/questions/100841/\n await client.get(\"http://10.255.255.1/\")"} {"repo":"httpx","file":"tests/test_timeouts.py","line":37,"symbol":"test_pool_timeout","kind":"function","lang":"python","code":"async def test_pool_timeout(server):\n limits = httpx.Limits(max_connections=1)\n timeout = httpx.Timeout(None, pool=1e-4)\n\n async with httpx.AsyncClient(limits=limits, timeout=timeout) as client:\n with pytest.raises(httpx.PoolTimeout):\n async with client.stream(\"GET\", server.url):\n await client.get(server.url)"} {"repo":"httpx","file":"tests/test_timeouts.py","line":48,"symbol":"test_async_client_new_request_send_timeout","kind":"function","lang":"python","code":"async def test_async_client_new_request_send_timeout(server):\n timeout = httpx.Timeout(1e-6)\n\n async with httpx.AsyncClient(timeout=timeout) as client:\n with pytest.raises(httpx.TimeoutException):\n await client.send(\n httpx.Request(\"GET\", server.url.copy_with(path=\"/slow_response\"))\n )"} {"repo":"httpx","file":"tests/test_utils.py","line":25,"symbol":"test_encoded","kind":"function","lang":"python","code":"def test_encoded(encoding):\n content = '{\"abc\": 123}'.encode(encoding)\n response = httpx.Response(200, content=content)\n assert response.json() == {\"abc\": 123}"} {"repo":"httpx","file":"tests/test_utils.py","line":31,"symbol":"test_bad_utf_like_encoding","kind":"function","lang":"python","code":"def test_bad_utf_like_encoding():\n content = b\"\\x00\\x00\\x00\\x00\"\n response = httpx.Response(200, content=content)\n with pytest.raises(json.decoder.JSONDecodeError):\n response.json()"} {"repo":"httpx","file":"tests/test_utils.py","line":47,"symbol":"test_guess_by_bom","kind":"function","lang":"python","code":"def test_guess_by_bom(encoding, expected):\n content = '\\ufeff{\"abc\": 123}'.encode(encoding)\n response = httpx.Response(200, content=content)\n assert response.json() == {\"abc\": 123}"} {"repo":"httpx","file":"tests/test_utils.py","line":53,"symbol":"test_logging_request","kind":"function","lang":"python","code":"def test_logging_request(server, caplog):\n caplog.set_level(logging.INFO)\n with httpx.Client() as client:\n response = client.get(server.url)\n assert response.status_code == 200\n\n assert caplog.record_tuples == [\n (\n \"httpx\",\n logging.INFO,\n 'HTTP Request: GET http://127.0.0.1:8000/ \"HTTP/1.1 200 OK\"',\n )\n ]"} {"repo":"httpx","file":"tests/test_utils.py","line":68,"symbol":"test_logging_redirect_chain","kind":"function","lang":"python","code":"def test_logging_redirect_chain(server, caplog):\n caplog.set_level(logging.INFO)\n with httpx.Client(follow_redirects=True) as client:\n response = client.get(server.url.copy_with(path=\"/redirect_301\"))\n assert response.status_code == 200\n\n assert caplog.record_tuples == [\n (\n \"httpx\",\n logging.INFO,\n \"HTTP Request: GET http://127.0.0.1:8000/redirect_301\"\n ' \"HTTP/1.1 301 Moved Permanently\"',\n ),\n (\n \"httpx\",\n logging.INFO,\n 'HTTP Request: GET http://127.0.0.1:8000/ \"HTTP/1.1 200 OK\"',\n ),\n ]"} {"repo":"httpx","file":"tests/test_utils.py","line":109,"symbol":"test_get_environment_proxies","kind":"function","lang":"python","code":"def test_get_environment_proxies(environment, proxies):\n os.environ.update(environment)\n\n assert get_environment_proxies() == proxies"} {"repo":"httpx","file":"tests/test_utils.py","line":132,"symbol":"test_url_matches","kind":"function","lang":"python","code":"def test_url_matches(pattern, url, expected):\n pattern = URLPattern(pattern)\n assert pattern.matches(httpx.URL(url)) == expected"} {"repo":"httpx","file":"tests/test_utils.py","line":137,"symbol":"test_pattern_priority","kind":"function","lang":"python","code":"def test_pattern_priority():\n matchers = [\n URLPattern(\"all://\"),\n URLPattern(\"http://\"),\n URLPattern(\"http://example.com\"),\n URLPattern(\"http://example.com:123\"),\n ]\n random.shuffle(matchers)\n assert sorted(matchers) == [\n URLPattern(\"http://example.com:123\"),\n URLPattern(\"http://example.com\"),\n URLPattern(\"http://\"),\n URLPattern(\"all://\"),\n ]"} {"repo":"httpx","file":"tests/test_wsgi.py","line":17,"symbol":"application_factory","kind":"function","lang":"python","code":"def application_factory(output: typing.Iterable[bytes]) -> WSGIApplication:\n def application(environ, start_response):\n status = \"200 OK\"\n\n response_headers = [\n (\"Content-type\", \"text/plain\"),\n ]\n\n start_response(status, response_headers)\n\n for item in output:\n yield item\n\n return wsgiref.validate.validator(application)"} {"repo":"httpx","file":"tests/test_wsgi.py","line":18,"symbol":"application","kind":"function","lang":"python","code":"def application(environ, start_response):\n status = \"200 OK\"\n\n response_headers = [\n (\"Content-type\", \"text/plain\"),\n ]\n\n start_response(status, response_headers)\n\n for item in output:\n yield item"} {"repo":"httpx","file":"tests/test_wsgi.py","line":33,"symbol":"echo_body","kind":"function","lang":"python","code":"def echo_body(\n environ: WSGIEnvironment, start_response: StartResponse\n) -> typing.Iterable[bytes]:\n status = \"200 OK\"\n output = environ[\"wsgi.input\"].read()\n\n response_headers = [\n (\"Content-type\", \"text/plain\"),\n ]\n\n start_response(status, response_headers)\n\n return [output]"} {"repo":"httpx","file":"tests/test_wsgi.py","line":48,"symbol":"echo_body_with_response_stream","kind":"function","lang":"python","code":"def echo_body_with_response_stream(\n environ: WSGIEnvironment, start_response: StartResponse\n) -> typing.Iterable[bytes]:\n status = \"200 OK\"\n\n response_headers = [(\"Content-Type\", \"text/plain\")]\n\n start_response(status, response_headers)\n\n def output_generator(f: typing.IO[bytes]) -> typing.Iterator[bytes]:\n while True:\n output = f.read(2)\n if not output:\n break\n yield output\n\n return output_generator(f=environ[\"wsgi.input\"])"} {"repo":"httpx","file":"tests/test_wsgi.py","line":57,"symbol":"output_generator","kind":"function","lang":"python","code":"def output_generator(f: typing.IO[bytes]) -> typing.Iterator[bytes]:\n while True:\n output = f.read(2)\n if not output:\n break\n yield output"} {"repo":"httpx","file":"tests/test_wsgi.py","line":67,"symbol":"raise_exc","kind":"function","lang":"python","code":"def raise_exc(\n environ: WSGIEnvironment,\n start_response: StartResponse,\n exc: type[Exception] = ValueError,\n) -> typing.Iterable[bytes]:\n status = \"500 Server Error\"\n output = b\"Nope!\"\n\n response_headers = [\n (\"Content-type\", \"text/plain\"),\n ]\n\n try:\n raise exc()\n except exc:\n exc_info = sys.exc_info()\n start_response(status, response_headers, exc_info)\n\n return [output]"} {"repo":"httpx","file":"tests/test_wsgi.py","line":88,"symbol":"log_to_wsgi_log_buffer","kind":"function","lang":"python","code":"def log_to_wsgi_log_buffer(environ, start_response):\n print(\"test1\", file=environ[\"wsgi.errors\"])\n environ[\"wsgi.errors\"].write(\"test2\")\n return echo_body(environ, start_response)"} {"repo":"httpx","file":"tests/test_wsgi.py","line":94,"symbol":"test_wsgi","kind":"function","lang":"python","code":"def test_wsgi():\n transport = httpx.WSGITransport(app=application_factory([b\"Hello, World!\"]))\n client = httpx.Client(transport=transport)\n response = client.get(\"http://www.example.org/\")\n assert response.status_code == 200\n assert response.text == \"Hello, World!\""} {"repo":"httpx","file":"tests/test_wsgi.py","line":102,"symbol":"test_wsgi_upload","kind":"function","lang":"python","code":"def test_wsgi_upload():\n transport = httpx.WSGITransport(app=echo_body)\n client = httpx.Client(transport=transport)\n response = client.post(\"http://www.example.org/\", content=b\"example\")\n assert response.status_code == 200\n assert response.text == \"example\""} {"repo":"httpx","file":"tests/test_wsgi.py","line":110,"symbol":"test_wsgi_upload_with_response_stream","kind":"function","lang":"python","code":"def test_wsgi_upload_with_response_stream():\n transport = httpx.WSGITransport(app=echo_body_with_response_stream)\n client = httpx.Client(transport=transport)\n response = client.post(\"http://www.example.org/\", content=b\"example\")\n assert response.status_code == 200\n assert response.text == \"example\""} {"repo":"httpx","file":"tests/test_wsgi.py","line":118,"symbol":"test_wsgi_exc","kind":"function","lang":"python","code":"def test_wsgi_exc():\n transport = httpx.WSGITransport(app=raise_exc)\n client = httpx.Client(transport=transport)\n with pytest.raises(ValueError):\n client.get(\"http://www.example.org/\")"} {"repo":"httpx","file":"tests/test_wsgi.py","line":125,"symbol":"test_wsgi_http_error","kind":"function","lang":"python","code":"def test_wsgi_http_error():\n transport = httpx.WSGITransport(app=partial(raise_exc, exc=RuntimeError))\n client = httpx.Client(transport=transport)\n with pytest.raises(RuntimeError):\n client.get(\"http://www.example.org/\")"} {"repo":"httpx","file":"tests/test_wsgi.py","line":132,"symbol":"test_wsgi_generator","kind":"function","lang":"python","code":"def test_wsgi_generator():\n output = [b\"\", b\"\", b\"Some content\", b\" and more content\"]\n transport = httpx.WSGITransport(app=application_factory(output))\n client = httpx.Client(transport=transport)\n response = client.get(\"http://www.example.org/\")\n assert response.status_code == 200\n assert response.text == \"Some content and more content\""} {"repo":"httpx","file":"tests/test_wsgi.py","line":141,"symbol":"test_wsgi_generator_empty","kind":"function","lang":"python","code":"def test_wsgi_generator_empty():\n output = [b\"\", b\"\", b\"\", b\"\"]\n transport = httpx.WSGITransport(app=application_factory(output))\n client = httpx.Client(transport=transport)\n response = client.get(\"http://www.example.org/\")\n assert response.status_code == 200\n assert response.text == \"\""} {"repo":"httpx","file":"tests/test_wsgi.py","line":150,"symbol":"test_logging","kind":"function","lang":"python","code":"def test_logging():\n buffer = StringIO()\n transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer)\n client = httpx.Client(transport=transport)\n response = client.post(\"http://www.example.org/\", content=b\"example\")\n assert response.status_code == 200 # no errors\n buffer.seek(0)\n assert buffer.read() == \"test1\\ntest2\""} {"repo":"httpx","file":"tests/test_wsgi.py","line":168,"symbol":"test_wsgi_server_port","kind":"function","lang":"python","code":"def test_wsgi_server_port(url: str, expected_server_port: str) -> None:\n \"\"\"\n SERVER_PORT is populated correctly from the requested URL.\n \"\"\"\n hello_world_app = application_factory([b\"Hello, World!\"])\n server_port: str | None = None\n\n def app(environ, start_response):\n nonlocal server_port\n server_port = environ[\"SERVER_PORT\"]\n return hello_world_app(environ, start_response)\n\n transport = httpx.WSGITransport(app=app)\n client = httpx.Client(transport=transport)\n response = client.get(url)\n assert response.status_code == 200\n assert response.text == \"Hello, World!\"\n assert server_port == expected_server_port"} {"repo":"httpx","file":"tests/test_wsgi.py","line":175,"symbol":"app","kind":"function","lang":"python","code":"def app(environ, start_response):\n nonlocal server_port\n server_port = environ[\"SERVER_PORT\"]\n return hello_world_app(environ, start_response)"} {"repo":"httpx","file":"tests/test_wsgi.py","line":188,"symbol":"test_wsgi_server_protocol","kind":"function","lang":"python","code":"def test_wsgi_server_protocol():\n server_protocol = None\n\n def app(environ, start_response):\n nonlocal server_protocol\n server_protocol = environ[\"SERVER_PROTOCOL\"]\n start_response(\"200 OK\", [(\"Content-Type\", \"text/plain\")])\n return [b\"success\"]\n\n transport = httpx.WSGITransport(app=app)\n with httpx.Client(transport=transport, base_url=\"http://testserver\") as client:\n response = client.get(\"/\")\n\n assert response.status_code == 200\n assert response.text == \"success\"\n assert server_protocol == \"HTTP/1.1\""} {"repo":"httpx","file":"tests/test_wsgi.py","line":191,"symbol":"app","kind":"function","lang":"python","code":"def app(environ, start_response):\n nonlocal server_protocol\n server_protocol = environ[\"SERVER_PROTOCOL\"]\n start_response(\"200 OK\", [(\"Content-Type\", \"text/plain\")])\n return [b\"success\"]"}