repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
asgiref
tests/test_sync.py
.py
import asyncio import contextvars import functools import multiprocessing import sys import threading import time import warnings from concurrent.futures import ThreadPoolExecutor from functools import wraps from typing import Any from unittest import TestCase import pytest from asgiref.sync import ( AsyncSingleT...
1,577
44,516
asgiref
tests/test_compatibility.py
.py
import pytest from asgiref.compatibility import double_to_single_callable, is_double_callable from asgiref.testing import ApplicationCommunicator def double_application_function(scope): """ A nested function based double-callable application. """ async def inner(receive, send): message = awa...
96
2,329
asgiref
tests/test_local.py
.py
import asyncio import contextvars import gc import threading from threading import Thread import pytest from asgiref.local import Local from asgiref.sync import async_to_sync, sync_to_async @pytest.mark.asyncio async def test_local_task(): """ Tests that local works just inside a normal task context """...
434
11,953
asgiref
tests/test_sync_contextvars.py
.py
import asyncio import contextvars import sys import threading import time import pytest from asgiref.sync import ThreadSensitiveContext, async_to_sync, sync_to_async foo: "contextvars.ContextVar[str]" = contextvars.ContextVar("foo") @pytest.mark.asyncio async def test_thread_sensitive_with_context_different(): ...
165
4,830
asgiref
tests/test_wsgi.py
.py
import sys import pytest from asgiref.testing import ApplicationCommunicator from asgiref.wsgi import WsgiToAsgi, WsgiToAsgiInstance @pytest.mark.asyncio async def test_basic_wsgi(): """ Makes sure the WSGI wrapper has basic functionality. """ # Define WSGI app def wsgi_application(environ, sta...
383
11,261
asgiref
tests/test_garbage_collection.py
.py
import gc import sys import pytest from asgiref.local import Local def disable_gc_for_garbage_collection_test() -> None: # Disable automatic garbage collection. To have control over when # garbage collection is performed. This is necessary to ensure that another # that thread doesn't accidentally trigge...
70
2,625
asgiref
asgiref/wsgi.py
.py
import sys from collections import defaultdict from tempfile import SpooledTemporaryFile from asgiref.sync import AsyncToSync, sync_to_async class WsgiToAsgi: """ Wraps a WSGI application to make it into an ASGI application. """ def __init__(self, wsgi_application, duplicate_header_limit=100): ...
198
7,941
asgiref
asgiref/server.py
.py
import asyncio import logging import time import traceback from .compatibility import guarantee_single_callable logger = logging.getLogger(__name__) class StatelessServer: """ Base server class that handles basic concepts like application instance creation/pooling, exception handling, and similar, for s...
173
6,247
asgiref
asgiref/timeout.py
.py
# This code is originally sourced from the aio-libs project "async_timeout", # under the Apache 2.0 license. You may see the original project at # https://github.com/aio-libs/async-timeout # It is vendored here to reduce chain-dependencies on this library, and # modified slightly to remove some features we don't use. ...
119
3,617
asgiref
asgiref/sync.py
.py
import asyncio import asyncio.coroutines import contextvars import functools import inspect import os import sys import threading import warnings import weakref from collections.abc import Awaitable, Callable, Coroutine from concurrent.futures import Future, InvalidStateError, ThreadPoolExecutor from typing import ( ...
668
24,206
asgiref
asgiref/testing.py
.py
import asyncio import contextvars import time from .compatibility import guarantee_single_callable from .timeout import timeout as async_timeout class ApplicationCommunicator: """ Runs an ASGI application in a test mode, allowing sending of messages to it and retrieval of messages it sends. """ ...
138
4,421
asgiref
asgiref/compatibility.py
.py
import inspect from .sync import iscoroutinefunction def is_double_callable(application): """ Tests to see if an application is a legacy-style (double-callable) application. """ # Look for a hint on the object first if getattr(application, "_asgi_single_callable", False): return False ...
49
1,606
asgiref
asgiref/current_thread_executor.py
.py
import threading from collections import deque from collections.abc import Callable from concurrent.futures import Executor, Future from typing import Any, ParamSpec, TypeVar _T = TypeVar("_T") _P = ParamSpec("_P") _R = TypeVar("_R") class _WorkItem: """ Represents an item needing to be run in the executor. ...
119
4,068
asgiref
asgiref/typing.py
.py
import sys from collections.abc import Awaitable, Callable, Iterable from typing import Any, Literal, Protocol, TypedDict, Union if sys.version_info >= (3, 11): from typing import NotRequired else: from typing_extensions import NotRequired __all__ = ( "ASGIVersions", "HTTPScope", "WebSocketScope",...
268
6,185
asgiref
asgiref/local.py
.py
import asyncio import contextlib import contextvars import threading from typing import Any, Union class _Storage: """Thread-tagged storage for a non-thread-critical ``Local``. The data is tagged with the identity of the thread that owns it. This lets ``_CVar`` ignore data that leaked into an unrelated t...
169
6,568
aiohttp
setup.py
.py
import os import pathlib import sys from setuptools import Extension, setup from setuptools.command.build_ext import build_ext if sys.version_info < (3, 10): raise RuntimeError("aiohttp 4.x requires Python 3.10+") USE_SYSTEM_DEPS = bool( os.environ.get("AIOHTTP_USE_SYSTEM_DEPS", os.environ.get("USE_SYSTEM_D...
109
2,892
aiohttp
aiohttp/client_middleware_digest_auth.py
.py
""" Digest authentication middleware for aiohttp client. This middleware implements HTTP Digest Authentication according to RFC 7616, providing a more secure alternative to Basic Authentication. It supports all standard hash algorithms including MD5, SHA, SHA-256, SHA-512 and their session variants, as well as both 'a...
508
19,681
aiohttp
aiohttp/web_middlewares.py
.py
import re import warnings from typing import TYPE_CHECKING, TypeVar from .typedefs import Handler, Middleware from .web_exceptions import ( HTTPMethodNotAllowed, HTTPMove, HTTPNotFound, HTTPPermanentRedirect, ) from .web_request import Request from .web_response import StreamResponse __all__ = ( "...
133
4,387
aiohttp
aiohttp/web.py
.py
import asyncio import logging import os import socket import sys import warnings from argparse import ArgumentParser from collections.abc import Awaitable, Callable, Iterable, Iterable as TypingIterable from contextlib import suppress from importlib import import_module from typing import Any, cast from .abc import Ab...
579
16,221
aiohttp
aiohttp/_cookie_helpers.py
.py
""" Internal cookie handling helpers. This module contains internal utilities for cookie parsing and manipulation. These are not part of the public API and may change without notice. """ import re from collections.abc import Sequence from http.cookies import CookieError, Morsel from typing import cast from .log impo...
362
14,092
aiohttp
aiohttp/compression_utils.py
.py
import asyncio import sys import zlib from abc import ABC, abstractmethod from concurrent.futures import Executor from typing import Any, Final, Generic, Protocol, TypedDict, TypeVar, cast if sys.version_info >= (3, 12): from collections.abc import Buffer else: from typing import Union Buffer = Union[byte...
530
18,677
aiohttp
aiohttp/client_ws.py
.py
"""WebSocket client for asyncio.""" import asyncio import sys from collections.abc import Callable from types import TracebackType from typing import Any, Final, Generic, Literal, overload from ._websocket.reader import WebSocketDataQueue from .client_exceptions import ClientError, ServerTimeoutError, WSMessageTypeEr...
561
19,469
aiohttp
aiohttp/http_writer.py
.py
"""Http related parsers and protocol.""" import asyncio import re import sys from typing import ( # noqa TYPE_CHECKING, Any, Awaitable, Callable, Iterable, List, NamedTuple, Optional, Union, ) from multidict import CIMultiDict from .abc import AbstractStreamWriter from .base_prot...
398
12,936
aiohttp
aiohttp/client_proto.py
.py
import asyncio from contextlib import suppress from typing import Callable, Protocol from ._websocket.reader import WebSocketDataQueue from .base_protocol import BaseProtocol from .client_exceptions import ( ClientConnectionError, ClientOSError, ClientPayloadError, ServerDisconnectedError, SocketTi...
374
12,753
aiohttp
aiohttp/web_app.py
.py
import asyncio import logging import warnings from collections.abc import ( AsyncIterator, Awaitable, Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence, ) from contextlib import AbstractAsyncContextManager, asynccontextmanager from functools import lru_cache, partial, updat...
448
14,019
aiohttp
aiohttp/client_middlewares.py
.py
"""Client middleware support.""" from collections.abc import Awaitable, Callable from functools import lru_cache from .client_reqrep import ClientRequest, ClientResponse __all__ = ("ClientMiddlewareType", "ClientHandlerType", "build_client_middlewares") # Type alias for client request handlers - functions that proc...
59
1,954
aiohttp
aiohttp/web_ws.py
.py
import asyncio import base64 import binascii import hashlib import json import sys from collections.abc import Callable, Iterable from typing import Any, Final, Generic, Literal, Union, overload from multidict import CIMultiDict from . import hdrs from ._websocket.reader import WebSocketDataQueue from .abc import Abs...
775
27,176
aiohttp
aiohttp/streams.py
.py
import asyncio import collections import sys import warnings from collections.abc import Awaitable, Callable, Coroutine from typing import Final, Generic, TypeVar from .base_protocol import BaseProtocol from .helpers import ( _EXC_SENTINEL, DEFAULT_CHUNK_SIZE, BaseTimerContext, TimerNoop, set_excep...
746
24,080
aiohttp
aiohttp/web_protocol.py
.py
import asyncio import asyncio.streams import sys import traceback from collections import deque from collections.abc import Awaitable, Callable, Sequence from contextlib import suppress from html import escape as html_escape from http import HTTPStatus from logging import Logger from typing import TYPE_CHECKING, Any, G...
904
32,024
aiohttp
aiohttp/web_routedef.py
.py
import abc import dataclasses from collections.abc import Callable, Iterator, Sequence from typing import TYPE_CHECKING, Any, Union, overload from . import hdrs from .abc import AbstractView from .typedefs import Handler, PathLike if TYPE_CHECKING: from .web_request import Request from .web_response import St...
206
6,169
aiohttp
aiohttp/base_protocol.py
.py
import asyncio from typing import TYPE_CHECKING, Any, cast from .client_exceptions import ClientConnectionResetError from .helpers import set_exception from .tcp_helpers import tcp_nodelay if TYPE_CHECKING: from .http_parser import HttpParser # Raised by transport.pause_reading()/resume_reading() when the transp...
141
4,688
aiohttp
aiohttp/web_response.py
.py
import asyncio import datetime import enum import json import math import time import warnings from collections.abc import Iterator, MutableMapping from concurrent.futures import Executor from http import HTTPStatus from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union, cast, overload from multidict import C...
792
27,302
aiohttp
aiohttp/__init__.py
.py
__version__ = "4.0.0a2.dev0" from typing import TYPE_CHECKING from . import hdrs from .client import ( BaseConnector, ClientConnectionError, ClientConnectionResetError, ClientConnectorCertificateError, ClientConnectorDNSError, ClientConnectorError, ClientConnectorSSLError, ClientError,...
259
6,785
aiohttp
aiohttp/web_server.py
.py
"""Low level HTTP server.""" import asyncio import warnings from collections.abc import Awaitable, Callable from typing import Any, Generic, TypeVar, overload from .abc import AbstractStreamWriter from .http_parser import RawRequestMessage from .streams import StreamReader from .web_exceptions import HTTPBadRequest f...
143
4,633
aiohttp
aiohttp/tcp_helpers.py
.py
"""Helper methods to tune a TCP connection""" import asyncio import socket from contextlib import suppress __all__ = ("tcp_keepalive", "tcp_nodelay") if hasattr(socket, "SO_KEEPALIVE"): def tcp_keepalive(transport: asyncio.Transport) -> None: sock = transport.get_extra_info("socket") if sock is...
37
941
aiohttp
aiohttp/http_websocket.py
.py
"""WebSocket protocol versions 13 and 8.""" from ._websocket.helpers import WS_KEY, ws_ext_gen, ws_ext_parse from ._websocket.models import ( WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE, WebSocketError, WSCloseCode, WSHandshakeError, WSMessage, WSMessageBinary, WSMessageClose, WSMessageCl...
60
1,377
aiohttp
aiohttp/payload.py
.py
import asyncio import enum import io import json import mimetypes import os import sys import warnings from abc import ABC, abstractmethod from collections.abc import AsyncIterable, AsyncIterator, Iterable from itertools import chain from typing import IO, Any, Final, TextIO from multidict import CIMultiDict from . i...
1,125
41,359
aiohttp
aiohttp/connector.py
.py
import asyncio import functools import random import socket import sys import traceback import warnings from collections import OrderedDict, defaultdict, deque from collections.abc import Awaitable, Callable, Iterator, Sequence from contextlib import suppress from http import HTTPStatus from itertools import chain, cyc...
1,789
67,031
aiohttp
aiohttp/web_runner.py
.py
import asyncio import signal import socket from abc import ABC, abstractmethod from collections.abc import Callable from typing import Any, Generic, TypeVar from yarl import URL from .abc import AbstractAccessLogger, AbstractStreamWriter from .http_parser import RawRequestMessage from .streams import StreamReader fro...
502
14,680
aiohttp
aiohttp/typedefs.py
.py
import json import os from collections.abc import Awaitable, Callable, Iterable, Mapping from http.cookies import BaseCookie, Morsel from typing import TYPE_CHECKING, Any, Protocol from multidict import CIMultiDict, CIMultiDictProxy, istr from yarl import URL DEFAULT_JSON_ENCODER = json.dumps DEFAULT_JSON_DECODER = j...
44
1,243
aiohttp
aiohttp/web_exceptions.py
.py
import warnings from collections.abc import Iterable from http import HTTPStatus from typing import Any from multidict import CIMultiDict from yarl import URL from . import hdrs from .helpers import CookieMixin from .typedefs import LooseHeaders, StrOrURL __all__ = ( "HTTPException", "HTTPError", "HTTPRe...
512
12,165
aiohttp
aiohttp/cookiejar.py
.py
import calendar import contextlib import datetime import heapq import itertools import json import os import pathlib import re import time import warnings from collections import defaultdict from collections.abc import Iterable, Iterator, Mapping from http.cookies import BaseCookie, Morsel, SimpleCookie from types impo...
623
23,579
aiohttp
aiohttp/worker.py
.py
"""Async gunicorn worker for aiohttp.web""" import asyncio import inspect import os import re import signal import sys from types import FrameType from typing import Any, Optional from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat from gunicorn.workers import base from aiohttp import web from .h...
256
8,526
aiohttp
aiohttp/multipart.py
.py
import base64 import binascii import builtins import json import re import sys import uuid import warnings from collections import deque from collections.abc import AsyncIterator, Iterator, Mapping, Sequence from types import TracebackType from typing import TYPE_CHECKING, Any, Union, cast from urllib.parse import pars...
1,261
45,748
aiohttp
aiohttp/tracing.py
.py
from types import SimpleNamespace from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, overload from aiosignal import Signal from multidict import CIMultiDict from yarl import URL from .client_reqrep import ClientResponse from .helpers import frozen_dataclass_decorator if TYPE_CHECKING: from .clien...
469
14,644
aiohttp
aiohttp/http.py
.py
import sys from . import __version__ from .http_exceptions import HttpProcessingError from .http_parser import ( HeadersParser, HttpParser, HttpRequestParser, HttpResponseParser, RawRequestMessage, RawResponseMessage, ) from .http_websocket import ( WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE...
65
1,348
aiohttp
aiohttp/web_fileresponse.py
.py
import asyncio import io import os import pathlib import sys from collections.abc import Awaitable, Callable from contextlib import suppress from enum import Enum, auto from mimetypes import MimeTypes from stat import S_ISREG from types import MappingProxyType from typing import TYPE_CHECKING, BinaryIO, Final, Optional...
415
16,568
aiohttp
aiohttp/client.py
.py
"""HTTP Client for asyncio.""" import asyncio import base64 import dataclasses import hashlib import json import os import sys import traceback import warnings from collections.abc import ( Awaitable, Callable, Collection, Coroutine, Generator, Iterable, Sequence, ) from contextlib import s...
1,611
56,735
aiohttp
aiohttp/http_parser.py
.py
import abc import asyncio import re import string import sys from contextlib import suppress from enum import IntEnum from re import Pattern from typing import ( TYPE_CHECKING, Any, ClassVar, Final, Generic, Literal, NamedTuple, TypeVar, ) from multidict import CIMultiDict, istr from ya...
1,247
47,989
aiohttp
aiohttp/hdrs.py
.py
"""HTTP Headers constants.""" # After changing the file content call ./tools/gen.py # to regenerate the headers parser import itertools from typing import Final from multidict import istr METH_ANY: Final[str] = "*" METH_CONNECT: Final[str] = "CONNECT" METH_HEAD: Final[str] = "HEAD" METH_GET: Final[str] = "GET" METH_...
117
4,887
aiohttp
aiohttp/web_urldispatcher.py
.py
import abc import asyncio import base64 import functools import hashlib import html import inspect import keyword import os import platform import re import sys from collections.abc import ( Awaitable, Callable, Container, Generator, Iterable, Iterator, Mapping, Sized, ) from pathlib imp...
1,249
42,964
aiohttp
aiohttp/log.py
.py
import logging access_logger = logging.getLogger("aiohttp.access") client_logger = logging.getLogger("aiohttp.client") internal_logger = logging.getLogger("aiohttp.internal") server_logger = logging.getLogger("aiohttp.server") web_logger = logging.getLogger("aiohttp.web") ws_logger = logging.getLogger("aiohttp.websock...
9
325
aiohttp
aiohttp/client_reqrep.py
.py
import asyncio import codecs import contextlib import functools import io import re import sys import traceback import warnings from collections.abc import Callable, Iterable, Sequence from hashlib import md5, sha1, sha256 from http.cookies import BaseCookie, SimpleCookie from types import MappingProxyType, TracebackTy...
1,553
54,062
aiohttp
aiohttp/helpers.py
.py
"""Various helper functions""" import asyncio import base64 import contextlib import dataclasses import datetime import enum import functools import inspect import netrc import os import platform import re import sys import time import warnings import weakref from collections.abc import Callable, Iterable, Iterator, M...
1,181
36,455
aiohttp
aiohttp/abc.py
.py
import logging import socket from abc import ABC, abstractmethod from collections.abc import Awaitable, Callable, Generator, Iterable, Sequence, Sized from http.cookies import BaseCookie, Morsel, SimpleCookie from types import MappingProxyType from typing import TYPE_CHECKING, Any, TypedDict from multidict import CIMu...
278
7,711
aiohttp
aiohttp/web_log.py
.py
import datetime import functools import logging import os import re import time as time_mod from collections.abc import Iterable from typing import Callable, ClassVar, NamedTuple from .abc import AbstractAccessLogger from .web_request import BaseRequest from .web_response import StreamResponse class KeyMethod(NamedT...
225
8,322
aiohttp
aiohttp/http_exceptions.py
.py
"""Low-level http related exceptions.""" from textwrap import indent from multidict import CIMultiDict __all__ = ("HttpProcessingError",) class HttpProcessingError(Exception): """HTTP error. Shortcut for raising HTTP errors with custom code, message and headers. code: HTTP Error code. message: (o...
114
2,953
aiohttp
aiohttp/resolver.py
.py
import asyncio import socket import sys import weakref from typing import Any, Optional from .abc import AbstractResolver, ResolveResult __all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver") try: import aiodns aiodns_default = hasattr(aiodns.DNSResolver, "getaddrinfo") except ImportError: ...
264
9,606
aiohttp
aiohttp/formdata.py
.py
import io from collections import deque from collections.abc import Iterable from typing import Any from urllib.parse import urlencode from multidict import MultiDict, MultiDictProxy from . import hdrs, multipart, payload from .helpers import guess_filename from .http_writer import _safe_header from .payload import P...
167
5,741
aiohttp
aiohttp/client_exceptions.py
.py
"""HTTP related errors.""" import asyncio from collections.abc import Mapping from typing import TYPE_CHECKING, Union from .typedefs import StrOrURL try: import ssl SSLContext = ssl.SSLContext except ImportError: # pragma: no cover ssl = SSLContext = None # type: ignore[assignment] if TYPE_CHECKING: ...
399
10,828
aiohttp
aiohttp/web_request.py
.py
import asyncio import datetime import io import re import string import sys import tempfile import types from collections.abc import Iterator, Mapping, MutableMapping from re import Pattern from types import MappingProxyType from typing import ( TYPE_CHECKING, Any, Final, Optional, TypedDict, Ty...
918
30,788
aiohttp
aiohttp/test_utils.py
.py
"""Utilities shared by tests.""" import asyncio import ipaddress import os import socket import sys from abc import ABC, abstractmethod from collections.abc import Callable from types import TracebackType from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, overload from unittest import IsolatedAsyncioTes...
666
20,661
aiohttp
aiohttp/_websocket/writer.py
.py
"""WebSocket protocol versions 13 and 8.""" import asyncio import random import sys from functools import partial from typing import Final from ..base_protocol import BaseProtocol from ..client_exceptions import ClientConnectionResetError from ..compression_utils import ZLibBackend, ZLibCompressor from ..helpers impo...
262
11,241
aiohttp
aiohttp/_websocket/models.py
.py
"""Models for WebSocket protocol versions 13 and 8.""" import json from collections.abc import Callable from enum import IntEnum from typing import Any, Final, Literal, NamedTuple, cast WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF]) class WSCloseCode(IntEnum): OK = 1000 GOING_AWAY = 100...
168
3,991
aiohttp
aiohttp/_websocket/reader_py.py
.py
"""Reader for WebSocket protocol versions 13 and 8.""" import asyncio import builtins from collections import deque from typing import Final from ..base_protocol import BaseProtocol from ..compression_utils import TooManyMembersError, ZLibDecompressor from ..helpers import _EXC_SENTINEL, set_exception from ..streams ...
546
21,742
aiohttp
aiohttp/_websocket/helpers.py
.py
"""Helpers for WebSocket protocol versions 13 and 8.""" import functools import re from re import Pattern from struct import Struct from typing import TYPE_CHECKING, Final from ..helpers import NO_EXTENSIONS from .models import WSHandshakeError UNPACK_LEN3 = Struct("!Q").unpack_from UNPACK_CLOSE_CODE = Struct("!H")....
149
5,006
aiohttp
aiohttp/_websocket/reader.py
.py
"""Reader for WebSocket protocol versions 13 and 8.""" from typing import TYPE_CHECKING from ..helpers import NO_EXTENSIONS if TYPE_CHECKING or NO_EXTENSIONS: from .reader_py import ( WebSocketDataQueue as WebSocketDataQueuePython, WebSocketReader as WebSocketReaderPython, ) WebSocketRea...
32
1,010
aiohttp
tools/check_changes.py
.py
#!/usr/bin/env python3 import re import sys from pathlib import Path ALLOWED_SUFFIXES = ( "bugfix", "feature", "deprecation", "breaking", "doc", "packaging", "contrib", "misc", ) PATTERN = re.compile( r"(\d+|[0-9a-f]{8}|[0-9a-f]{7}|[0-9a-f]{40})\.(" + "|".join(ALLOWED_SUFFIXES)...
60
1,384
aiohttp
tools/gen.py
.py
#!/usr/bin/env python import io import pathlib from collections import defaultdict import multidict ROOT = pathlib.Path.cwd() while ROOT.parent != ROOT and not (ROOT / "pyproject.toml").exists(): ROOT = ROOT.parent def calc_headers(root): hdrs_file = root / "aiohttp/hdrs.py" code = compile(hdrs_file.re...
175
3,784
aiohttp
tools/bench-asyncio-write.py
.py
import asyncio import atexit import math import os import signal PORT = 8888 server = os.fork() if server == 0: loop = asyncio.get_event_loop() coro = asyncio.start_server(lambda *_: None, port=PORT) loop.run_until_complete(coro) loop.run_forever() else: atexit.register(os.kill, server, signal.SIG...
133
3,060
aiohttp
tools/check_sum.py
.py
#!/usr/bin/env python import argparse import hashlib import pathlib import sys PARSER = argparse.ArgumentParser( description="Helper for check file hashes in Makefile instead of bare timestamps" ) PARSER.add_argument("dst", metavar="DST", type=pathlib.Path) PARSER.add_argument("-d", "--debug", action="store_true"...
51
1,346
aiohttp
tools/cleanup_changes.py
.py
#!/usr/bin/env python # Run me after the backport branch release to cleanup CHANGES records # that was backported and published. import re import subprocess from pathlib import Path ALLOWED_SUFFIXES = ( "bugfix", "feature", "deprecation", "breaking", "doc", "packaging", "contrib", "mi...
46
1,170
aiohttp
requirements/sync-direct-runtime-deps.py
.py
#!/usr/bin/env python """Sync direct runtime dependencies from pyproject.toml to runtime-deps.in.""" import sys from pathlib import Path if sys.version_info >= (3, 11): import tomllib else: raise RuntimeError("Use Python 3.11+ to run 'make sync-direct-runtime-deps'") data = tomllib.loads(Path("pyproject.toml...
23
706
aiohttp
docs/code/client_middleware_cookbook.py
.py
"""This is a collection of semi-complete examples that get included into the cookbook page.""" import asyncio import logging import time from collections.abc import AsyncIterator, Sequence from contextlib import asynccontextmanager, suppress from aiohttp import ( ClientError, ClientHandlerType, ClientRequ...
144
5,072
aiohttp
tests/test_imports.py
.py
import os import platform import sys from pathlib import Path import pytest def test___all__(pytester: pytest.Pytester) -> None: """See https://github.com/aio-libs/aiohttp/issues/6197""" pytester.makepyfile(test_a=""" from aiohttp import * assert 'GunicornWebWorker' in globals() ...
77
2,430
aiohttp
tests/test_web_request.py
.py
import asyncio import datetime import logging import ssl import sys import time import weakref from collections.abc import Iterator, MutableMapping from typing import NoReturn from unittest import mock import pytest from multidict import CIMultiDict, MultiDict from pytest_aiohttp import AiohttpClient from yarl import ...
1,378
46,757
aiohttp
tests/test_benchmarks_http_writer.py
.py
"""codspeed benchmarks for http writer.""" from typing import TYPE_CHECKING import pytest from multidict import CIMultiDict from aiohttp import hdrs from aiohttp.http_writer import _serialize_headers if TYPE_CHECKING: from pytest_codspeed import BenchmarkFixture else: pytest_codspeed = pytest.importorskip("...
42
1,245
aiohttp
tests/test_client_request.py
.py
import asyncio import hashlib import io import pathlib import sys from collections.abc import AsyncIterator, Callable, Iterable from http.cookies import BaseCookie, SimpleCookie from typing import Any from unittest import mock import pytest from multidict import CIMultiDict, CIMultiDictProxy, istr from yarl import URL...
2,315
76,538
aiohttp
tests/test_base_protocol.py
.py
import asyncio from contextlib import suppress from unittest import mock import pytest from aiohttp.base_protocol import BaseProtocol from aiohttp.http_parser import HttpParser async def test_loop() -> None: loop = asyncio.get_running_loop() asyncio.set_event_loop(None) pr = BaseProtocol(loop) asser...
257
6,871
aiohttp
tests/test_web_runner.py
.py
import asyncio import platform import signal import socket from collections.abc import AsyncIterator from typing import Any, NoReturn, Protocol from unittest import mock import pytest from aiohttp import web, web_runner as web_runner_module from aiohttp.abc import AbstractAccessLogger from aiohttp.test_utils import R...
326
9,707
aiohttp
tests/test_benchmarks_client_request.py
.py
"""codspeed benchmarks for client requests.""" import asyncio import sys from collections.abc import Callable from http.cookies import BaseCookie from typing import TYPE_CHECKING, Any import pytest from multidict import CIMultiDict from yarl import URL from aiohttp.client_reqrep import ( ClientRequest, Clien...
217
6,102
aiohttp
tests/test_benchmarks_web_response.py
.py
"""codspeed benchmarks for the web responses.""" from typing import TYPE_CHECKING import pytest from aiohttp import web if TYPE_CHECKING: from pytest_codspeed import BenchmarkFixture else: pytest_codspeed = pytest.importorskip("pytest_codspeed") BenchmarkFixture = pytest_codspeed.BenchmarkFixture def ...
71
1,845
aiohttp
tests/test_formdata.py
.py
import io from unittest import mock import pytest from pytest_aiohttp import AiohttpClient from aiohttp import FormData, web from aiohttp.http_writer import StreamWriter @pytest.fixture def buf() -> bytearray: return bytearray() @pytest.fixture def writer(buf: bytearray) -> StreamWriter: writer = mock.cre...
319
8,824
aiohttp
tests/test_client_session.py
.py
import asyncio import contextlib import gc import io import json import ssl import sys import warnings from collections import deque from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from http.cookies import BaseCookie, SimpleCookie from types import MappingProxyType, SimpleNamespace from typing ...
1,732
60,715
aiohttp
tests/test_benchmarks_web_fileresponse.py
.py
"""codspeed benchmarks for the web file responses.""" import asyncio import os import pathlib import ssl import sys from collections.abc import Awaitable, Callable, Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, TypedDict import pytest from multidict import CIMultiDict from pytest_a...
207
6,507
aiohttp
tests/test_compression_utils.py
.py
"""Tests for compression utils.""" import gzip import os import sys import zlib from typing import Any import pytest from aiohttp.compression_utils import ( MAX_DECOMPRESS_MEMBERS, MEMBER_WINDOW_MAX, MEMBER_WINDOW_MIN, TooManyMembersError, ZLibBackend, ZLibCompressor, ZLibDecompressObjPro...
292
11,181
aiohttp
tests/test_leaks.py
.py
import pathlib import platform import subprocess import sys import pytest IS_PYPY = platform.python_implementation() == "PyPy" @pytest.mark.skipif( sys.platform in ("android", "ios"), reason="subprocess not supported" ) @pytest.mark.skipif(IS_PYPY, reason="gc.DEBUG_LEAK not available on PyPy") @pytest.mark.para...
41
1,215
aiohttp
tests/test_proxy.py
.py
import asyncio import socket import ssl import sys from typing import Callable from unittest import mock import pytest from multidict import CIMultiDict from yarl import URL import aiohttp from aiohttp import connector as connector_module, hdrs from aiohttp.abc import AbstractStreamWriter from aiohttp.client_reqrep i...
1,149
38,500
aiohttp
tests/test_client_functional.py
.py
# HTTP client functional tests against aiohttp.web server from __future__ import annotations # TODO(PY311): Remove import asyncio import datetime import http.cookies import io import json import logging import pathlib import socket import ssl import sys import tarfile import time import zipfile import zlib from colle...
6,177
208,291
aiohttp
tests/test_websocket_data_queue.py
.py
import asyncio from unittest import mock import pytest from aiohttp._websocket.models import WSMessageBinary from aiohttp._websocket.reader import WebSocketDataQueue from aiohttp.base_protocol import BaseProtocol @pytest.fixture def protocol() -> BaseProtocol: return mock.create_autospec(BaseProtocol, spec_set=...
37
1,196
aiohttp
tests/test_proxy_functional.py
.py
import asyncio import os import pathlib import platform import ssl import sys from collections.abc import Awaitable, Callable, Iterator from contextlib import ExitStack, suppress from re import match as match_regex from typing import TYPE_CHECKING, TypedDict from unittest import mock from uuid import uuid4 import pyte...
1,061
34,476
aiohttp
tests/test_circular_imports.py
.py
"""Tests for circular imports in all local packages and modules. This ensures all internal packages can be imported right away without any need to import some other module before doing so. This module is based on an idea that pytest uses for self-testing: * https://github.com/sanitizers/octomachinery/blob/be18b54/tes...
123
3,712
aiohttp
tests/test_cookie_helpers.py
.py
"""Tests for internal cookie helper functions.""" import logging import sys from http.cookies import ( CookieError, Morsel, SimpleCookie, _unquote as simplecookie_unquote, ) import pytest from aiohttp import _cookie_helpers as helpers from aiohttp._cookie_helpers import ( _unquote, parse_cook...
1,887
65,977
aiohttp
tests/test_test_utils.py
.py
import asyncio import gzip import socket import sys from collections.abc import AsyncIterator, Mapping from typing import NoReturn from unittest import mock import pytest from multidict import CIMultiDict from pytest_aiohttp import AiohttpClient from yarl import URL import aiohttp from aiohttp import hdrs, web from a...
462
13,976
aiohttp
tests/test_websocket_writer.py
.py
import asyncio import random from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from contextlib import suppress from unittest import mock import pytest from aiohttp import WSMsgType from aiohttp._websocket.reader import WebSocketDataQueue from aiohttp.base_protocol import BaseProto...
342
13,409
aiohttp
tests/test_web_request_handler.py
.py
from unittest import mock from aiohttp import web async def serve(request: web.BaseRequest) -> web.Response: assert False async def test_repr() -> None: manager = web.Server(serve) handler = manager() assert "<RequestHandler disconnected>" == repr(handler) with mock.patch.object(handler, "tra...
63
1,701
aiohttp
tests/test_classbasedview.py
.py
from unittest import mock import pytest from aiohttp import web from aiohttp.web_urldispatcher import View def test_ctor() -> None: request = mock.Mock() view = View(request) assert view.request is request async def test_render_ok() -> None: resp = web.Response(text="OK") class MyView(View): ...
56
1,341
aiohttp
tests/test_web_middleware.py
.py
import asyncio from collections.abc import Awaitable, Callable, Iterable from contextlib import suppress from typing import NoReturn import pytest from pytest_aiohttp import AiohttpClient, AiohttpServer from yarl import URL from aiohttp import web, web_app from aiohttp.test_utils import TestClient from aiohttp.typede...
611
21,674
aiohttp
tests/test_web_functional.py
.py
import asyncio import io import json import pathlib import socket import sys import zlib from collections.abc import AsyncIterator, Awaitable, Callable, Generator from contextlib import suppress from typing import NoReturn from unittest import mock import pytest from multidict import MultiDict from pytest_aiohttp impo...
2,729
86,446
aiohttp
tests/test_tcp_helpers.py
.py
import socket from unittest import mock import pytest from aiohttp.tcp_helpers import tcp_nodelay has_ipv6: bool = socket.has_ipv6 if has_ipv6: # The socket.has_ipv6 flag may be True if Python was built with IPv6 # support, but the target system still may not have it. # So let's ensure that we really hav...
75
2,458