diff --git a/aiohttp/client.py b/aiohttp/client.py index e7d3570dced..c21ce173cf2 100644 --- a/aiohttp/client.py +++ b/aiohttp/client.py @@ -222,7 +222,7 @@ def __init__( trust_env: bool = False, requote_redirect_url: bool = True, trace_configs: Optional[List[TraceConfig]] = None, - read_bufsize: int = 2 ** 16 + read_bufsize: int = 2 ** 16, ) -> None: if loop is None: @@ -336,7 +336,7 @@ def __del__(self, _warnings: Any = warnings) -> None: else: kwargs = {} _warnings.warn( - "Unclosed client session {!r}".format(self), ResourceWarning, **kwargs + f"Unclosed client session {self!r}", ResourceWarning, **kwargs ) context = {"client_session": self, "message": "Unclosed client session"} if self._source_traceback is not None: @@ -377,7 +377,7 @@ async def _request( ssl: Optional[Union[SSLContext, bool, Fingerprint]] = None, proxy_headers: Optional[LooseHeaders] = None, trace_request_ctx: Optional[SimpleNamespace] = None, - read_bufsize: Optional[int] = None + read_bufsize: Optional[int] = None, ) -> ClientResponse: # NOTE: timeout clamps existing connect and read timeouts. We cannot @@ -529,7 +529,7 @@ async def _request( ) except asyncio.TimeoutError as exc: raise ServerTimeoutError( - "Connection timeout " "to host {0}".format(url) + "Connection timeout " "to host {}".format(url) ) from exc assert conn.transport is not None @@ -677,7 +677,7 @@ def ws_connect( ssl_context: Optional[SSLContext] = None, proxy_headers: Optional[LooseHeaders] = None, compress: int = 0, - max_msg_size: int = 4 * 1024 * 1024 + max_msg_size: int = 4 * 1024 * 1024, ) -> "_WSRequestContextManager": """Initiate websocket connection.""" return _WSRequestContextManager( @@ -727,7 +727,7 @@ async def _ws_connect( ssl_context: Optional[SSLContext] = None, proxy_headers: Optional[LooseHeaders] = None, compress: int = 0, - max_msg_size: int = 4 * 1024 * 1024 + max_msg_size: int = 4 * 1024 * 1024, ) -> ClientWebSocketResponse: if headers is None: @@ -1207,7 +1207,7 @@ def request( version: HttpVersion = http.HttpVersion11, connector: Optional[BaseConnector] = None, read_bufsize: Optional[int] = None, - loop: Optional[asyncio.AbstractEventLoop] = None + loop: Optional[asyncio.AbstractEventLoop] = None, ) -> _SessionRequestContextManager: """Constructs and sends a request. Returns response object. method - HTTP method diff --git a/aiohttp/client_exceptions.py b/aiohttp/client_exceptions.py index ef6bec926f8..eb135a24062 100644 --- a/aiohttp/client_exceptions.py +++ b/aiohttp/client_exceptions.py @@ -64,7 +64,7 @@ def __init__( code: Optional[int] = None, status: Optional[int] = None, message: str = "", - headers: Optional[LooseHeaders] = None + headers: Optional[LooseHeaders] = None, ) -> None: self.request_info = request_info if code is not None: @@ -90,21 +90,21 @@ def __init__( self.args = (request_info, history) def __str__(self) -> str: - return "%s, message=%r, url=%r" % ( + return "{}, message={!r}, url={!r}".format( self.status, self.message, self.request_info.real_url, ) def __repr__(self) -> str: - args = "%r, %r" % (self.request_info, self.history) + args = f"{self.request_info!r}, {self.history!r}" if self.status != 0: - args += ", status=%r" % (self.status,) + args += f", status={self.status!r}" if self.message != "": - args += ", message=%r" % (self.message,) + args += f", message={self.message!r}" if self.headers is not None: - args += ", headers=%r" % (self.headers,) - return "%s(%s)" % (type(self).__name__, args) + args += f", headers={self.headers!r}" + return "{}({})".format(type(self).__name__, args) @property def code(self) -> int: @@ -257,7 +257,7 @@ def url(self) -> Any: return self.args[0] def __repr__(self) -> str: - return "<{} {}>".format(self.__class__.__name__, self.url) + return f"<{self.__class__.__name__} {self.url}>" class ClientSSLError(ClientConnectorError): diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index 1c0f922cdb7..a324b53b861 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -267,7 +267,7 @@ def __init__( session: Optional["ClientSession"] = None, ssl: Union[SSLContext, bool, Fingerprint, None] = None, proxy_headers: Optional[LooseHeaders] = None, - traces: Optional[List["Trace"]] = None + traces: Optional[List["Trace"]] = None, ): if loop is None: @@ -381,7 +381,7 @@ def update_version(self, version: Union[http.HttpVersion, str]) -> None: version = http.HttpVersion(int(v[0]), int(v[1])) except ValueError: raise ValueError( - "Can not parse http version number: {}".format(version) + f"Can not parse http version number: {version}" ) from None self.version = version @@ -392,7 +392,7 @@ def update_headers(self, headers: Optional[LooseHeaders]) -> None: # add host netloc = cast(str, self.url.raw_host) if helpers.is_ipv6_address(netloc): - netloc = "[{}]".format(netloc) + netloc = f"[{netloc}]" if self.url.port is not None and not self.url.is_default_port(): netloc += ":" + str(self.url.port) self.headers[hdrs.HOST] = netloc @@ -615,8 +615,8 @@ async def send(self, conn: "Connection") -> "ClientResponse": connect_host = self.url.raw_host assert connect_host is not None if helpers.is_ipv6_address(connect_host): - connect_host = "[{}]".format(connect_host) - path = "{}:{}".format(connect_host, self.url.port) + connect_host = f"[{connect_host}]" + path = f"{connect_host}:{self.url.port}" elif self.proxy and not self.is_ssl(): path = str(self.url) else: @@ -731,7 +731,7 @@ def __init__( request_info: RequestInfo, traces: List["Trace"], loop: asyncio.AbstractEventLoop, - session: "ClientSession" + session: "ClientSession", ) -> None: assert isinstance(url, URL) @@ -808,9 +808,7 @@ def __del__(self, _warnings: Any = warnings) -> None: kwargs = {"source": self} else: kwargs = {} - _warnings.warn( - "Unclosed response {!r}".format(self), ResourceWarning, **kwargs - ) + _warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs) context = {"client_response": self, "message": "Unclosed response"} if self._source_traceback: context["source_traceback"] = self._source_traceback @@ -1087,7 +1085,7 @@ async def json( *, encoding: Optional[str] = None, loads: JSONDecoder = DEFAULT_JSON_DECODER, - content_type: Optional[str] = "application/json" + content_type: Optional[str] = "application/json", ) -> Any: """Read and decodes JSON response.""" if self._body is None: diff --git a/aiohttp/client_ws.py b/aiohttp/client_ws.py index 1a5b6c06800..a90c60d9d3c 100644 --- a/aiohttp/client_ws.py +++ b/aiohttp/client_ws.py @@ -40,7 +40,7 @@ def __init__( receive_timeout: Optional[float] = None, heartbeat: Optional[float] = None, compress: int = 0, - client_notakeover: bool = False + client_notakeover: bool = False, ) -> None: self._response = response self._conn = response.connection @@ -159,7 +159,7 @@ async def send_json( data: Any, compress: Optional[int] = None, *, - dumps: JSONEncoder = DEFAULT_JSON_ENCODER + dumps: JSONEncoder = DEFAULT_JSON_ENCODER, ) -> None: await self.send_str(dumps(data), compress=compress) @@ -273,24 +273,20 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage: async def receive_str(self, *, timeout: Optional[float] = None) -> str: msg = await self.receive(timeout) if msg.type != WSMsgType.TEXT: - raise TypeError( - "Received message {}:{!r} is not str".format(msg.type, msg.data) - ) + raise TypeError(f"Received message {msg.type}:{msg.data!r} is not str") return msg.data async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: msg = await self.receive(timeout) if msg.type != WSMsgType.BINARY: - raise TypeError( - "Received message {}:{!r} is not bytes".format(msg.type, msg.data) - ) + raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes") return msg.data async def receive_json( self, *, loads: JSONDecoder = DEFAULT_JSON_DECODER, - timeout: Optional[float] = None + timeout: Optional[float] = None, ) -> Any: data = await self.receive_str(timeout=timeout) return loads(data) diff --git a/aiohttp/connector.py b/aiohttp/connector.py index e2fed54da09..d05687c2493 100644 --- a/aiohttp/connector.py +++ b/aiohttp/connector.py @@ -109,7 +109,7 @@ def __init__( self._source_traceback = traceback.extract_stack(sys._getframe(1)) def __repr__(self) -> str: - return "Connection<{}>".format(self._key) + return f"Connection<{self._key}>" def __del__(self, _warnings: Any = warnings) -> None: if self._protocol is not None: @@ -117,9 +117,7 @@ def __del__(self, _warnings: Any = warnings) -> None: kwargs = {"source": self} else: kwargs = {} - _warnings.warn( - "Unclosed connection {!r}".format(self), ResourceWarning, **kwargs - ) + _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs) if self._loop.is_closed(): return @@ -213,7 +211,7 @@ def __init__( limit: int = 100, limit_per_host: int = 0, enable_cleanup_closed: bool = False, - loop: Optional[asyncio.AbstractEventLoop] = None + loop: Optional[asyncio.AbstractEventLoop] = None, ) -> None: if force_close: @@ -276,9 +274,7 @@ def __del__(self, _warnings: Any = warnings) -> None: kwargs = {"source": self} else: kwargs = {} - _warnings.warn( - "Unclosed connector {!r}".format(self), ResourceWarning, **kwargs - ) + _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs) context = { "connector": self, "connections": conns, @@ -640,7 +636,7 @@ def _release( key: "ConnectionKey", protocol: ResponseHandler, *, - should_close: bool = False + should_close: bool = False, ) -> None: if self._closed: # acquired connection is already released on connector closing @@ -757,7 +753,7 @@ def __init__( limit: int = 100, limit_per_host: int = 0, enable_cleanup_closed: bool = False, - loop: Optional[asyncio.AbstractEventLoop] = None + loop: Optional[asyncio.AbstractEventLoop] = None, ): super().__init__( keepalive_timeout=keepalive_timeout, @@ -968,7 +964,7 @@ async def _wrap_create_connection( req: "ClientRequest", timeout: "ClientTimeout", client_error: Type[Exception] = ClientConnectorError, - **kwargs: Any + **kwargs: Any, ) -> Tuple[asyncio.Transport, ResponseHandler]: try: with CeilTimeout(timeout.sock_connect): @@ -986,7 +982,7 @@ async def _create_direct_connection( traces: List["Trace"], timeout: "ClientTimeout", *, - client_error: Type[Exception] = ClientConnectorError + client_error: Type[Exception] = ClientConnectorError, ) -> Tuple[asyncio.Transport, ResponseHandler]: sslcontext = self._get_ssl_context(req) fingerprint = self._get_fingerprint(req) diff --git a/aiohttp/frozenlist.py b/aiohttp/frozenlist.py index 42ddcd5ab46..46b26108cfa 100644 --- a/aiohttp/frozenlist.py +++ b/aiohttp/frozenlist.py @@ -58,7 +58,7 @@ def insert(self, pos, item): self._items.insert(pos, item) def __repr__(self): - return "".format(self._frozen, self._items) + return f"" PyFrozenList = FrozenList diff --git a/aiohttp/helpers.py b/aiohttp/helpers.py index 23cd6af4cde..e67cbd11068 100644 --- a/aiohttp/helpers.py +++ b/aiohttp/helpers.py @@ -94,8 +94,8 @@ def all_tasks( ) # type: bool -CHAR = set(chr(i) for i in range(0, 128)) -CTL = set(chr(i) for i in range(0, 32)) | { +CHAR = {chr(i) for i in range(0, 128)} +CTL = {chr(i) for i in range(0, 32)} | { chr(127), } SEPARATORS = { @@ -184,7 +184,7 @@ def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth" def encode(self) -> str: """Encode credentials.""" - creds = ("%s:%s" % (self.login, self.password)).encode(self.encoding) + creds = (f"{self.login}:{self.password}").encode(self.encoding) return "Basic %s" % base64.b64encode(creds).decode(self.encoding) @@ -777,4 +777,4 @@ def __bool__(self) -> bool: def __repr__(self) -> str: content = ", ".join(map(repr, self._maps)) - return "ChainMapProxy({})".format(content) + return f"ChainMapProxy({content})" diff --git a/aiohttp/http_exceptions.py b/aiohttp/http_exceptions.py index 0c1246a6b8f..c885f80f322 100644 --- a/aiohttp/http_exceptions.py +++ b/aiohttp/http_exceptions.py @@ -35,10 +35,10 @@ def __init__( self.message = message def __str__(self) -> str: - return "%s, message=%r" % (self.code, self.message) + return f"{self.code}, message={self.message!r}" def __repr__(self) -> str: - return "<%s: %s>" % (self.__class__.__name__, self) + return f"<{self.__class__.__name__}: {self}>" class BadHttpMessage(HttpProcessingError): @@ -78,7 +78,7 @@ def __init__( self, line: str, limit: str = "Unknown", actual_size: str = "Unknown" ) -> None: super().__init__( - "Got more than %s bytes (%s) when reading %s." % (limit, actual_size, line) + f"Got more than {limit} bytes ({actual_size}) when reading {line}." ) self.args = (line, limit, actual_size) @@ -87,7 +87,7 @@ class InvalidHeader(BadHttpMessage): def __init__(self, hdr: Union[bytes, str]) -> None: if isinstance(hdr, bytes): hdr = hdr.decode("utf-8", "surrogateescape") - super().__init__("Invalid HTTP Header: {}".format(hdr)) + super().__init__(f"Invalid HTTP Header: {hdr}") self.hdr = hdr self.args = (hdr,) diff --git a/aiohttp/http_websocket.py b/aiohttp/http_websocket.py index 965656e0eed..5cdaeea43c0 100644 --- a/aiohttp/http_websocket.py +++ b/aiohttp/http_websocket.py @@ -298,7 +298,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]: if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES: raise WebSocketError( WSCloseCode.PROTOCOL_ERROR, - "Invalid close code: {}".format(close_code), + f"Invalid close code: {close_code}", ) try: close_message = payload[2:].decode("utf-8") @@ -310,7 +310,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]: elif payload: raise WebSocketError( WSCloseCode.PROTOCOL_ERROR, - "Invalid close frame: {} {} {!r}".format(fin, opcode, payload), + f"Invalid close frame: {fin} {opcode} {payload!r}", ) else: msg = WSMessage(WSMsgType.CLOSE, 0, "") @@ -332,7 +332,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]: and self._opcode is None ): raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, "Unexpected opcode={!r}".format(opcode) + WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}" ) else: # load text/binary @@ -577,7 +577,7 @@ def __init__( limit: int = DEFAULT_LIMIT, random: Any = random.Random(), compress: int = 0, - notakeover: bool = False + notakeover: bool = False, ) -> None: self.protocol = protocol self.transport = transport diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py index 8b406dfdf21..d3a366440dc 100644 --- a/aiohttp/multipart.py +++ b/aiohttp/multipart.py @@ -90,7 +90,7 @@ def is_continuous_param(string: str) -> bool: return substring.isdigit() def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str: - return re.sub("\\\\([{}])".format(chars), "\\1", text) + return re.sub(f"\\\\([{chars}])", "\\1", text) if not header: return None, {} @@ -151,7 +151,7 @@ def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str: elif parts: # maybe just ; in filename, in any case this is just # one case fix, for proper fix we need to redesign parser - _value = "%s;%s" % (value, parts[0]) + _value = "{};{}".format(value, parts[0]) if is_quoted(_value): parts.pop(0) value = unescape(_value[1:-1].lstrip("\\/")) @@ -291,7 +291,7 @@ async def read(self, *, decode: bool = False) -> bytes: return b"" data = bytearray() while not self._at_eof: - data.extend((await self.read_chunk(self.chunk_size))) + data.extend(await self.read_chunk(self.chunk_size)) if decode: return self.decode(data) return data @@ -453,7 +453,7 @@ def _decode_content(self, data: bytes) -> bytes: elif encoding == "identity": return data else: - raise RuntimeError("unknown content encoding: {}".format(encoding)) + raise RuntimeError(f"unknown content encoding: {encoding}") def _decode_content_transfer(self, data: bytes) -> bytes: encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() @@ -678,9 +678,7 @@ async def _read_boundary(self) -> None: else: self._unread.extend([next_line, epilogue]) else: - raise ValueError( - "Invalid boundary %r, expected %r" % (chunk, self._boundary) - ) + raise ValueError(f"Invalid boundary {chunk!r}, expected {self._boundary!r}") async def _read_headers(self) -> "CIMultiDictProxy[str]": lines = [b""] @@ -720,7 +718,7 @@ def __init__(self, subtype: str = "mixed", boundary: Optional[str] = None) -> No self._boundary = boundary.encode("ascii") except UnicodeEncodeError: raise ValueError("boundary should contain ASCII only chars") from None - ctype = "multipart/{}; boundary={}".format(subtype, self._boundary_value) + ctype = f"multipart/{subtype}; boundary={self._boundary_value}" super().__init__(None, content_type=ctype) @@ -808,7 +806,7 @@ def append_payload(self, payload: Payload) -> Payload: "", ).lower() # type: Optional[str] if encoding and encoding not in ("deflate", "gzip", "identity"): - raise RuntimeError("unknown content encoding: {}".format(encoding)) + raise RuntimeError(f"unknown content encoding: {encoding}") if encoding == "identity": encoding = None diff --git a/aiohttp/payload.py b/aiohttp/payload.py index 78389c7679d..10afed65806 100644 --- a/aiohttp/payload.py +++ b/aiohttp/payload.py @@ -121,7 +121,7 @@ def register( elif order is Order.try_last: self._last.append((factory, type)) else: - raise ValueError("Unsupported order {!r}".format(order)) + raise ValueError(f"Unsupported order {order!r}") class Payload(ABC): @@ -138,7 +138,7 @@ def __init__( content_type: Optional[str] = sentinel, filename: Optional[str] = None, encoding: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> None: self._encoding = encoding self._filename = filename @@ -246,7 +246,7 @@ def __init__( *args: Any, encoding: Optional[str] = None, content_type: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> None: if encoding is None: @@ -306,7 +306,7 @@ def __init__( *args: Any, encoding: Optional[str] = None, content_type: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> None: if encoding is None: @@ -374,7 +374,7 @@ def __init__( content_type: str = "application/json", dumps: JSONEncoder = json.dumps, *args: Any, - **kwargs: Any + **kwargs: Any, ) -> None: super().__init__( diff --git a/aiohttp/test_utils.py b/aiohttp/test_utils.py index f415934503f..0a414565a11 100644 --- a/aiohttp/test_utils.py +++ b/aiohttp/test_utils.py @@ -94,7 +94,7 @@ def __init__( host: str = "127.0.0.1", port: Optional[int] = None, skip_url_asserts: bool = False, - **kwargs: Any + **kwargs: Any, ) -> None: self._loop = loop self.runner = None # type: Optional[BaseRunner] @@ -131,7 +131,7 @@ async def start_server( else: scheme = "http" self.scheme = scheme - self._root = URL("{}://{}:{}".format(self.scheme, self.host, self.port)) + self._root = URL(f"{self.scheme}://{self.host}:{self.port}") @abstractmethod # pragma: no cover async def _make_runner(self, **kwargs: Any) -> BaseRunner: @@ -215,7 +215,7 @@ def __init__( scheme: Union[str, object] = sentinel, host: str = "127.0.0.1", port: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ): self.app = app super().__init__(scheme=scheme, host=host, port=port, **kwargs) @@ -232,7 +232,7 @@ def __init__( scheme: Union[str, object] = sentinel, host: str = "127.0.0.1", port: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> None: self._handler = handler super().__init__(scheme=scheme, host=host, port=port, **kwargs) @@ -258,7 +258,7 @@ def __init__( *, cookie_jar: Optional[AbstractCookieJar] = None, loop: Optional[asyncio.AbstractEventLoop] = None, - **kwargs: Any + **kwargs: Any, ) -> None: if not isinstance(server, BaseTestServer): raise TypeError( @@ -593,7 +593,7 @@ def make_mocked_request( payload: Any = sentinel, sslcontext: Optional[SSLContext] = None, client_max_size: int = 1024 ** 2, - loop: Any = ... + loop: Any = ..., ) -> Any: """Creates mocked web.Request testing purposes. diff --git a/aiohttp/web.py b/aiohttp/web.py index 00e6eb706df..557e3c3b4d0 100644 --- a/aiohttp/web.py +++ b/aiohttp/web.py @@ -300,7 +300,7 @@ async def _run_app( access_log: Optional[logging.Logger] = access_logger, handle_signals: bool = True, reuse_address: Optional[bool] = None, - reuse_port: Optional[bool] = None + reuse_port: Optional[bool] = None, ) -> None: # A internal functio to actually do all dirty job for application running if asyncio.iscoroutine(app): @@ -473,7 +473,7 @@ def run_app( access_log: Optional[logging.Logger] = access_logger, handle_signals: bool = True, reuse_address: Optional[bool] = None, - reuse_port: Optional[bool] = None + reuse_port: Optional[bool] = None, ) -> None: """Run an app locally""" loop = asyncio.get_event_loop() @@ -558,11 +558,11 @@ def main(argv: List[str]) -> None: try: module = import_module(mod_str) except ImportError as ex: - arg_parser.error("unable to import %s: %s" % (mod_str, ex)) + arg_parser.error(f"unable to import {mod_str}: {ex}") try: func = getattr(module, func_str) except AttributeError: - arg_parser.error("module %r has no attribute %r" % (mod_str, func_str)) + arg_parser.error(f"module {mod_str!r} has no attribute {func_str!r}") # Compatibility logic if args.path is not None and not hasattr(socket, "AF_UNIX"): diff --git a/aiohttp/web_app.py b/aiohttp/web_app.py index fb35b49a873..1f0e41a7e11 100644 --- a/aiohttp/web_app.py +++ b/aiohttp/web_app.py @@ -110,7 +110,7 @@ def __init__( handler_args: Optional[Mapping[str, Any]] = None, client_max_size: int = 1024 ** 2, loop: Optional[asyncio.AbstractEventLoop] = None, - debug: Any = ... # mypy doesn't support ellipsis + debug: Any = ..., # mypy doesn't support ellipsis ) -> None: if router is None: router = UrlDispatcher() @@ -365,7 +365,7 @@ def _make_handler( *, loop: Optional[asyncio.AbstractEventLoop] = None, access_log_class: Type[AbstractAccessLogger] = AccessLogger, - **kwargs: Any + **kwargs: Any, ) -> Server: if not issubclass(access_log_class, AbstractAccessLogger): @@ -387,7 +387,7 @@ def _make_handler( self._handle, # type: ignore request_factory=self._make_request, loop=self._loop, - **kwargs + **kwargs, ) def make_handler( @@ -395,7 +395,7 @@ def make_handler( *, loop: Optional[asyncio.AbstractEventLoop] = None, access_log_class: Type[AbstractAccessLogger] = AccessLogger, - **kwargs: Any + **kwargs: Any, ) -> Server: warnings.warn( @@ -544,7 +544,7 @@ async def _on_cleanup(self, app: Application) -> None: except Exception as exc: errors.append(exc) else: - errors.append(RuntimeError("{!r} has more than one 'yield'".format(it))) + errors.append(RuntimeError(f"{it!r} has more than one 'yield'")) if errors: if len(errors) == 1: raise errors[0] diff --git a/aiohttp/web_exceptions.py b/aiohttp/web_exceptions.py index 30fabadfb18..2eadca0386a 100644 --- a/aiohttp/web_exceptions.py +++ b/aiohttp/web_exceptions.py @@ -89,7 +89,7 @@ def __init__( reason: Optional[str] = None, body: Any = None, text: Optional[str] = None, - content_type: Optional[str] = None + content_type: Optional[str] = None, ) -> None: if body is not None: warnings.warn( @@ -107,7 +107,7 @@ def __init__( ) Exception.__init__(self, self.reason) if self.body is None and not self.empty_body: - self.text = "{}: {}".format(self.status, self.reason) + self.text = f"{self.status}: {self.reason}" def __bool__(self) -> bool: return True @@ -169,7 +169,7 @@ def __init__( reason: Optional[str] = None, body: Any = None, text: Optional[str] = None, - content_type: Optional[str] = None + content_type: Optional[str] = None, ) -> None: if not location: raise ValueError("HTTP redirects need a location to redirect to.") @@ -262,7 +262,7 @@ def __init__( reason: Optional[str] = None, body: Any = None, text: Optional[str] = None, - content_type: Optional[str] = None + content_type: Optional[str] = None, ) -> None: allow = ",".join(sorted(allowed_methods)) super().__init__( @@ -372,7 +372,7 @@ def __init__( reason: Optional[str] = None, body: Any = None, text: Optional[str] = None, - content_type: Optional[str] = None + content_type: Optional[str] = None, ) -> None: super().__init__( headers=headers, diff --git a/aiohttp/web_fileresponse.py b/aiohttp/web_fileresponse.py index 4f74b816014..2b497085a2e 100644 --- a/aiohttp/web_fileresponse.py +++ b/aiohttp/web_fileresponse.py @@ -282,7 +282,7 @@ async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter # # Will do the same below. Many servers ignore this and do not # send a Content-Range header with HTTP 416 - self.headers[hdrs.CONTENT_RANGE] = "bytes */{0}".format(file_size) + self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" self.set_status(HTTPRequestRangeNotSatisfiable.status_code) return await super().prepare(request) @@ -318,7 +318,7 @@ async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter # suffix-byte-range-spec with a non-zero suffix-length, # then the byte-range-set is satisfiable. Otherwise, the # byte-range-set is unsatisfiable. - self.headers[hdrs.CONTENT_RANGE] = "bytes */{0}".format(file_size) + self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" self.set_status(HTTPRequestRangeNotSatisfiable.status_code) return await super().prepare(request) @@ -341,7 +341,7 @@ async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter real_start = cast(int, start) if status == HTTPPartialContent.status_code: - self.headers[hdrs.CONTENT_RANGE] = "bytes {0}-{1}/{2}".format( + self.headers[hdrs.CONTENT_RANGE] = "bytes {}-{}/{}".format( real_start, real_start + count - 1, file_size ) diff --git a/aiohttp/web_log.py b/aiohttp/web_log.py index b2e83a6f326..4cfa57929a9 100644 --- a/aiohttp/web_log.py +++ b/aiohttp/web_log.py @@ -154,7 +154,7 @@ def _format_P(request: BaseRequest, response: StreamResponse, time: float) -> st def _format_r(request: BaseRequest, response: StreamResponse, time: float) -> str: if request is None: return "-" - return "%s %s HTTP/%s.%s" % ( + return "{} {} HTTP/{}.{}".format( request.method, request.path_qs, request.version.major, diff --git a/aiohttp/web_protocol.py b/aiohttp/web_protocol.py index bc51de41b8e..9b18f4aa955 100644 --- a/aiohttp/web_protocol.py +++ b/aiohttp/web_protocol.py @@ -149,7 +149,7 @@ def __init__( max_headers: int = 32768, max_field_size: int = 8190, lingering_time: float = 10.0, - read_bufsize: int = 2 ** 16 + read_bufsize: int = 2 ** 16, ): super().__init__(loop) @@ -622,7 +622,7 @@ def handle_error( if "text/html" in request.headers.get("Accept", ""): if tb: tb = html_escape(tb) - msg = "

Traceback:

\n
{}
".format(tb) + msg = f"

Traceback:

\n
{tb}
" message = ( "" "{title}" diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py index 8dd21dc2c79..808f8877c5b 100644 --- a/aiohttp/web_request.py +++ b/aiohttp/web_request.py @@ -66,7 +66,7 @@ class FileField: _TCHAR = string.digits + string.ascii_letters + r"!#$%&'*+.^_`|~-" # '-' at the end to prevent interpretation as range in a char class -_TOKEN = r"[{tchar}]+".format(tchar=_TCHAR) +_TOKEN = fr"[{_TCHAR}]+" _QDTEXT = r"[{}]".format( r"".join(chr(c) for c in (0x09, 0x20, 0x21) + tuple(range(0x23, 0x7F))) @@ -139,7 +139,7 @@ def __init__( state: Optional[Dict[str, Any]] = None, scheme: Optional[str] = None, host: Optional[str] = None, - remote: Optional[str] = None + remote: Optional[str] = None, ) -> None: if state is None: state = {} @@ -183,7 +183,7 @@ def clone( headers: LooseHeaders = sentinel, scheme: str = sentinel, host: str = sentinel, - remote: str = sentinel + remote: str = sentinel, ) -> "BaseRequest": """Clone itself with replacement some attributes. @@ -229,7 +229,7 @@ def clone( self._loop, client_max_size=self._client_max_size, state=self._state.copy(), - **kwargs + **kwargs, ) @property @@ -778,7 +778,7 @@ def clone( headers: LooseHeaders = sentinel, scheme: str = sentinel, host: str = sentinel, - remote: str = sentinel + remote: str = sentinel, ) -> "Request": ret = super().clone( method=method, diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index 50a0dbe9d6f..a3fa9f3c12a 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -73,7 +73,7 @@ def __init__( *, status: int = 200, reason: Optional[str] = None, - headers: Optional[LooseHeaders] = None + headers: Optional[LooseHeaders] = None, ) -> None: self._body = None self._keep_alive = None # type: Optional[bool] @@ -202,7 +202,7 @@ def set_cookie( secure: Optional[bool] = None, httponly: Optional[bool] = None, version: Optional[str] = None, - samesite: Optional[str] = None + samesite: Optional[str] = None, ) -> None: """Set or update response cookie. @@ -343,7 +343,7 @@ def _generate_content_type_header( ) -> None: assert self._content_dict is not None assert self._content_type is not None - params = "; ".join("{}={}".format(k, v) for k, v in self._content_dict.items()) + params = "; ".join(f"{k}={v}" for k, v in self._content_dict.items()) if params: ctype = self._content_type + "; " + params else: @@ -500,10 +500,10 @@ def __repr__(self) -> str: info = "eof" elif self.prepared: assert self._req is not None - info = "{} {} ".format(self._req.method, self._req.path) + info = f"{self._req.method} {self._req.path} " else: info = "not prepared" - return "<{} {} {}>".format(self.__class__.__name__, self.reason, info) + return f"<{self.__class__.__name__} {self.reason} {info}>" def __getitem__(self, key: str) -> Any: return self._state[key] @@ -539,7 +539,7 @@ def __init__( content_type: Optional[str] = None, charset: Optional[str] = None, zlib_executor_size: Optional[int] = None, - zlib_executor: Optional[Executor] = None + zlib_executor: Optional[Executor] = None, ) -> None: if body is not None and text is not None: raise ValueError("body and text are not allowed together") @@ -694,7 +694,7 @@ async def write_eof(self, data: bytes = b"") -> None: body = self._body # type: Optional[Union[bytes, Payload]] else: body = self._compressed_body - assert not data, "data arg is not supported, got {!r}".format(data) + assert not data, f"data arg is not supported, got {data!r}" assert self._req is not None assert self._payload_writer is not None if body is not None: @@ -764,7 +764,7 @@ def json_response( reason: Optional[str] = None, headers: Optional[LooseHeaders] = None, content_type: str = "application/json", - dumps: JSONEncoder = json.dumps + dumps: JSONEncoder = json.dumps, ) -> Response: if data is not sentinel: if text or body: diff --git a/aiohttp/web_routedef.py b/aiohttp/web_routedef.py index 7541f3e1d54..16c3b0d3522 100644 --- a/aiohttp/web_routedef.py +++ b/aiohttp/web_routedef.py @@ -67,7 +67,7 @@ class RouteDef(AbstractRouteDef): def __repr__(self) -> str: info = [] for name, value in sorted(self.kwargs.items()): - info.append(", {}={!r}".format(name, value)) + info.append(f", {name}={value!r}") return " {handler.__name__!r}" "{info}>".format( method=self.method, path=self.path, handler=self.handler, info="".join(info) ) @@ -91,7 +91,7 @@ class StaticDef(AbstractRouteDef): def __repr__(self) -> str: info = [] for name, value in sorted(self.kwargs.items()): - info.append(", {}={!r}".format(name, value)) + info.append(f", {name}={value!r}") return " {path}" "{info}>".format( prefix=self.prefix, path=self.path, info="".join(info) ) @@ -120,7 +120,7 @@ def get( *, name: Optional[str] = None, allow_head: bool = True, - **kwargs: Any + **kwargs: Any, ) -> RouteDef: return route( hdrs.METH_GET, path, handler, name=name, allow_head=allow_head, **kwargs diff --git a/aiohttp/web_runner.py b/aiohttp/web_runner.py index 214c53fda1e..25ac28a7a89 100644 --- a/aiohttp/web_runner.py +++ b/aiohttp/web_runner.py @@ -45,7 +45,7 @@ def __init__( *, shutdown_timeout: float = 60.0, ssl_context: Optional[SSLContext] = None, - backlog: int = 128 + backlog: int = 128, ) -> None: if runner.server is None: raise RuntimeError("Call runner.setup() before making a site") @@ -92,7 +92,7 @@ def __init__( ssl_context: Optional[SSLContext] = None, backlog: int = 128, reuse_address: Optional[bool] = None, - reuse_port: Optional[bool] = None + reuse_port: Optional[bool] = None, ) -> None: super().__init__( runner, @@ -139,7 +139,7 @@ def __init__( *, shutdown_timeout: float = 60.0, ssl_context: Optional[SSLContext] = None, - backlog: int = 128 + backlog: int = 128, ) -> None: super().__init__( runner, @@ -152,7 +152,7 @@ def __init__( @property def name(self) -> str: scheme = "https" if self._ssl_context else "http" - return "{}://unix:{}:".format(scheme, self._path) + return f"{scheme}://unix:{self._path}:" async def start(self) -> None: await super().start() @@ -201,7 +201,7 @@ def __init__( *, shutdown_timeout: float = 60.0, ssl_context: Optional[SSLContext] = None, - backlog: int = 128 + backlog: int = 128, ) -> None: super().__init__( runner, @@ -212,7 +212,7 @@ def __init__( self._sock = sock scheme = "https" if self._ssl_context else "http" if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: - name = "{}://unix:{}:".format(scheme, sock.getsockname()) + name = f"{scheme}://unix:{sock.getsockname()}:" else: host, port = sock.getsockname()[:2] name = str(URL.build(scheme=scheme, host=host, port=port)) @@ -311,22 +311,16 @@ async def _cleanup_server(self) -> None: def _reg_site(self, site: BaseSite) -> None: if site in self._sites: - raise RuntimeError( - "Site {} is already registered in runner {}".format(site, self) - ) + raise RuntimeError(f"Site {site} is already registered in runner {self}") self._sites.append(site) def _check_site(self, site: BaseSite) -> None: if site not in self._sites: - raise RuntimeError( - "Site {} is not registered in runner {}".format(site, self) - ) + raise RuntimeError(f"Site {site} is not registered in runner {self}") def _unreg_site(self, site: BaseSite) -> None: if site not in self._sites: - raise RuntimeError( - "Site {} is not registered in runner {}".format(site, self) - ) + raise RuntimeError(f"Site {site} is not registered in runner {self}") self._sites.remove(site) diff --git a/aiohttp/web_urldispatcher.py b/aiohttp/web_urldispatcher.py index 760afb698d0..4b6b99e4f1c 100644 --- a/aiohttp/web_urldispatcher.py +++ b/aiohttp/web_urldispatcher.py @@ -167,11 +167,11 @@ def __init__( assert asyncio.iscoroutinefunction( expect_handler - ), "Coroutine is expected, got {!r}".format(expect_handler) + ), f"Coroutine is expected, got {expect_handler!r}" method = method.upper() if not HTTP_METHOD_RE.match(method): - raise ValueError("{} is not allowed HTTP method".format(method)) + raise ValueError(f"{method} is not allowed HTTP method") assert callable(handler), handler if asyncio.iscoroutinefunction(handler): @@ -296,7 +296,7 @@ def freeze(self) -> None: self._frozen = True def __repr__(self) -> str: - return "".format(super().__repr__(), self._route) + return f"" class MatchInfoError(UrlMappingMatchInfo): @@ -356,7 +356,7 @@ def add_route( def register_route(self, route: "ResourceRoute") -> None: assert isinstance( route, ResourceRoute - ), "Instance of Route class is required, got {!r}".format(route) + ), f"Instance of Route class is required, got {route!r}" self._routes.append(route) async def resolve(self, request: Request) -> _Resolve: @@ -426,7 +426,7 @@ def url_for(self) -> URL: # type: ignore def __repr__(self) -> str: name = "'" + self.name + "' " if self.name is not None else "" - return "".format(name=name, path=self._path) + return f"" class DynamicResource(Resource): @@ -453,7 +453,7 @@ def __init__(self, path: str, *, name: Optional[str] = None) -> None: continue if "{" in part or "}" in part: - raise ValueError("Invalid path '{}'['{}']".format(path, part)) + raise ValueError(f"Invalid path '{path}'['{part}']") part = _requote_path(part) formatter += part @@ -462,7 +462,7 @@ def __init__(self, path: str, *, name: Optional[str] = None) -> None: try: compiled = re.compile(pattern) except re.error as exc: - raise ValueError("Bad pattern '{}': {}".format(pattern, exc)) from None + raise ValueError(f"Bad pattern '{pattern}': {exc}") from None assert compiled.pattern.startswith(PATH_SEP) assert formatter.startswith("/") self._pattern = compiled @@ -552,7 +552,7 @@ def __init__( if not directory.is_dir(): raise ValueError("Not a directory") except (FileNotFoundError, ValueError) as error: - raise ValueError("No directory exists at '{}'".format(directory)) from error + raise ValueError(f"No directory exists at '{directory}'") from error self._directory = directory self._show_index = show_index self._chunk_size = chunk_size @@ -692,8 +692,8 @@ def _directory_as_html(self, filepath: Path) -> str: assert filepath.is_dir() relative_path_to_dir = filepath.relative_to(self._directory).as_posix() - index_of = "Index of /{}".format(relative_path_to_dir) - h1 = "

{}

".format(index_of) + index_of = f"Index of /{relative_path_to_dir}" + h1 = f"

{index_of}

" index_list = [] dir_index = filepath.iterdir() @@ -704,7 +704,7 @@ def _directory_as_html(self, filepath: Path) -> str: # if file is a directory, add '/' to the end of the name if _file.is_dir(): - file_name = "{}/".format(_file.name) + file_name = f"{_file.name}/" else: file_name = _file.name @@ -714,10 +714,10 @@ def _directory_as_html(self, filepath: Path) -> str: ) ) ul = "
    \n{}\n
".format("\n".join(index_list)) - body = "\n{}\n{}\n".format(h1, ul) + body = f"\n{h1}\n{ul}\n" - head_str = "\n{}\n ".format(index_of) - html = "\n{}\n{}\n".format(head_str, body) + head_str = f"\n{index_of}\n " + html = f"\n{head_str}\n{body}\n" return html @@ -812,7 +812,7 @@ def validation(self, domain: str) -> str: raise ValueError("Domain not valid") if url.port == 80: return url.raw_host - return "{}:{}".format(url.raw_host, url.port) + return f"{url.raw_host}:{url.port}" async def match(self, request: Request) -> bool: host = request.headers.get(hdrs.HOST) @@ -1036,7 +1036,7 @@ def named_resources(self) -> Mapping[str, AbstractResource]: def register_resource(self, resource: AbstractResource) -> None: assert isinstance( resource, AbstractResource - ), "Instance of AbstractResource class is required, got {!r}".format(resource) + ), f"Instance of AbstractResource class is required, got {resource!r}" if self.frozen: raise RuntimeError("Cannot register a resource into frozen router.") diff --git a/aiohttp/web_ws.py b/aiohttp/web_ws.py index 6234aef1477..475647e6e26 100644 --- a/aiohttp/web_ws.py +++ b/aiohttp/web_ws.py @@ -63,7 +63,7 @@ def __init__( heartbeat: Optional[float] = None, protocols: Iterable[str] = (), compress: bool = True, - max_msg_size: int = 4 * 1024 * 1024 + max_msg_size: int = 4 * 1024 * 1024, ) -> None: super().__init__(status=101) self._protocols = protocols @@ -180,15 +180,15 @@ def _handshake( # check supported version version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, "") if version not in ("13", "8", "7"): - raise HTTPBadRequest(text="Unsupported version: {}".format(version)) + raise HTTPBadRequest(text=f"Unsupported version: {version}") # check client handshake for validity key = headers.get(hdrs.SEC_WEBSOCKET_KEY) try: if not key or len(base64.b64decode(key)) != 16: - raise HTTPBadRequest(text="Handshake error: {!r}".format(key)) + raise HTTPBadRequest(text=f"Handshake error: {key!r}") except binascii.Error: - raise HTTPBadRequest(text="Handshake error: {!r}".format(key)) from None + raise HTTPBadRequest(text=f"Handshake error: {key!r}") from None accept_val = base64.b64encode( hashlib.sha1(key.encode() + WS_KEY).digest() @@ -311,7 +311,7 @@ async def send_json( data: Any, compress: Optional[bool] = None, *, - dumps: JSONEncoder = json.dumps + dumps: JSONEncoder = json.dumps, ) -> None: await self.send_str(dumps(data), compress=compress) @@ -455,9 +455,7 @@ async def receive_str(self, *, timeout: Optional[float] = None) -> str: async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: msg = await self.receive(timeout) if msg.type != WSMsgType.BINARY: - raise TypeError( - "Received message {}:{!r} is not bytes".format(msg.type, msg.data) - ) + raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes") return msg.data async def receive_json( diff --git a/docs/conf.py b/docs/conf.py index a09a773b3f6..f72bf1e5d82 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# -*- coding: utf-8 -*- # # aiohttp documentation build configuration file, created by # sphinx-quickstart on Wed Mar 5 12:35:35 2014. @@ -18,18 +17,22 @@ import re _docs_path = os.path.dirname(__file__) -_version_path = os.path.abspath(os.path.join(_docs_path, - '..', 'aiohttp', '__init__.py')) -with io.open(_version_path, 'r', encoding='latin1') as fp: +_version_path = os.path.abspath( + os.path.join(_docs_path, "..", "aiohttp", "__init__.py") +) +with open(_version_path, encoding="latin1") as fp: try: - _version_info = re.search(r'^__version__ = "' - r"(?P\d+)" - r"\.(?P\d+)" - r"\.(?P\d+)" - r'(?P.*)?"$', - fp.read(), re.M).groupdict() + _version_info = re.search( + r'^__version__ = "' + r"(?P\d+)" + r"\.(?P\d+)" + r"\.(?P\d+)" + r'(?P.*)?"$', + fp.read(), + re.M, + ).groupdict() except IndexError: - raise RuntimeError('Unable to determine version.') + raise RuntimeError("Unable to determine version.") # -- General configuration ------------------------------------------------ @@ -41,60 +44,55 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.viewcode', - 'sphinx.ext.intersphinx', - 'sphinxcontrib.asyncio', - 'sphinxcontrib.blockdiag', + "sphinx.ext.viewcode", + "sphinx.ext.intersphinx", + "sphinxcontrib.asyncio", + "sphinxcontrib.blockdiag", ] try: import sphinxcontrib.spelling # noqa - extensions.append('sphinxcontrib.spelling') + + extensions.append("sphinxcontrib.spelling") except ImportError: pass intersphinx_mapping = { - 'python': ('http://docs.python.org/3', None), - 'multidict': - ('https://multidict.readthedocs.io/en/stable/', None), - 'yarl': - ('https://yarl.readthedocs.io/en/stable/', None), - 'aiohttpjinja2': - ('https://aiohttp-jinja2.readthedocs.io/en/stable/', None), - 'aiohttpremotes': - ('https://aiohttp-remotes.readthedocs.io/en/stable/', None), - 'aiohttpsession': - ('https://aiohttp-session.readthedocs.io/en/stable/', None), - 'aiohttpdemos': - ('https://aiohttp-demos.readthedocs.io/en/latest/', None), + "python": ("http://docs.python.org/3", None), + "multidict": ("https://multidict.readthedocs.io/en/stable/", None), + "yarl": ("https://yarl.readthedocs.io/en/stable/", None), + "aiohttpjinja2": ("https://aiohttp-jinja2.readthedocs.io/en/stable/", None), + "aiohttpremotes": ("https://aiohttp-remotes.readthedocs.io/en/stable/", None), + "aiohttpsession": ("https://aiohttp-session.readthedocs.io/en/stable/", None), + "aiohttpdemos": ("https://aiohttp-demos.readthedocs.io/en/latest/", None), } # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'aiohttp' -copyright = '2013-2020, aiohttp maintainers' +project = "aiohttp" +copyright = "2013-2020, aiohttp maintainers" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '{major}.{minor}'.format(**_version_info) +version = "{major}.{minor}".format(**_version_info) # The full version, including alpha/beta/rc tags. -release = '{major}.{minor}.{patch}{tag}'.format(**_version_info) +release = "{major}.{minor}.{patch}{tag}".format(**_version_info) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -108,7 +106,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -129,7 +127,7 @@ # pygments_style = 'sphinx' # The default language to highlight source code in. -highlight_language = 'python3' +highlight_language = "python3" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] @@ -142,40 +140,52 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'aiohttp_theme' +html_theme = "aiohttp_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { - 'logo': 'aiohttp-icon-128x128.png', - 'description': 'Async HTTP client/server for asyncio and Python', - 'canonical_url': 'http://docs.aiohttp.org/en/stable/', - 'github_user': 'aio-libs', - 'github_repo': 'aiohttp', - 'github_button': True, - 'github_type': 'star', - 'github_banner': True, - 'badges': [{'image': 'https://dev.azure.com/aio-libs/aiohttp/_apis/build/status/CI?branchName=master', - 'target': 'https://dev.azure.com/aio-libs/aiohttp/_build', - 'height': '20', - 'alt': 'Azure Pipelines CI status'}, - {'image': 'https://codecov.io/github/aio-libs/aiohttp/coverage.svg?branch=master', - 'target': 'https://codecov.io/github/aio-libs/aiohttp', - 'height': '20', - 'alt': 'Code coverage status'}, - {'image': 'https://badge.fury.io/py/aiohttp.svg', - 'target': 'https://badge.fury.io/py/aiohttp', - 'height': '20', - 'alt': 'Latest PyPI package version'}, - {'image': 'https://img.shields.io/discourse/status?server=https%3A%2F%2Faio-libs.discourse.group', - 'target': 'https://aio-libs.discourse.group', - 'height': '20', - 'alt': 'Discourse status'}, - {'image': 'https://badges.gitter.im/Join%20Chat.svg', - 'target': 'https://gitter.im/aio-libs/Lobby', - 'height': '20', - 'alt': 'Chat on Gitter'}], + "logo": "aiohttp-icon-128x128.png", + "description": "Async HTTP client/server for asyncio and Python", + "canonical_url": "http://docs.aiohttp.org/en/stable/", + "github_user": "aio-libs", + "github_repo": "aiohttp", + "github_button": True, + "github_type": "star", + "github_banner": True, + "badges": [ + { + "image": "https://dev.azure.com/aio-libs/aiohttp/_apis/build/status/CI?branchName=master", + "target": "https://dev.azure.com/aio-libs/aiohttp/_build", + "height": "20", + "alt": "Azure Pipelines CI status", + }, + { + "image": "https://codecov.io/github/aio-libs/aiohttp/coverage.svg?branch=master", + "target": "https://codecov.io/github/aio-libs/aiohttp", + "height": "20", + "alt": "Code coverage status", + }, + { + "image": "https://badge.fury.io/py/aiohttp.svg", + "target": "https://badge.fury.io/py/aiohttp", + "height": "20", + "alt": "Latest PyPI package version", + }, + { + "image": "https://img.shields.io/discourse/status?server=https%3A%2F%2Faio-libs.discourse.group", + "target": "https://aio-libs.discourse.group", + "height": "20", + "alt": "Discourse status", + }, + { + "image": "https://badges.gitter.im/Join%20Chat.svg", + "target": "https://gitter.im/aio-libs/Lobby", + "height": "20", + "alt": "Chat on Gitter", + }, + ], } # Add any paths that contain custom themes here, relative to this directory. @@ -195,12 +205,12 @@ # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -html_favicon = 'favicon.ico' +html_favicon = "favicon.ico" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied @@ -217,8 +227,10 @@ # Custom sidebar templates, maps document names to template names. html_sidebars = { - '**': [ - 'about.html', 'navigation.html', 'searchbox.html', + "**": [ + "about.html", + "navigation.html", + "searchbox.html", ] } @@ -253,7 +265,7 @@ # html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'aiohttpdoc' +htmlhelp_basename = "aiohttpdoc" # -- Options for LaTeX output --------------------------------------------- @@ -261,10 +273,8 @@ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. # 'preamble': '', } @@ -273,8 +283,7 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - ('index', 'aiohttp.tex', 'aiohttp Documentation', - 'aiohttp contributors', 'manual'), + ("index", "aiohttp.tex", "aiohttp Documentation", "aiohttp contributors", "manual"), ] # The name of an image file (relative to this directory) to place at the top of @@ -302,10 +311,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'aiohttp', 'aiohttp Documentation', - ['aiohttp'], 1) -] +man_pages = [("index", "aiohttp", "aiohttp Documentation", ["aiohttp"], 1)] # If true, show URL addresses after external links. # man_show_urls = False @@ -317,9 +323,15 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'aiohttp', 'aiohttp Documentation', - 'Aiohttp contributors', 'aiohttp', 'One line description of project.', - 'Miscellaneous'), + ( + "index", + "aiohttp", + "aiohttp Documentation", + "Aiohttp contributors", + "aiohttp", + "One line description of project.", + "Miscellaneous", + ), ] # Documents to append as an appendix to all manuals. diff --git a/examples/background_tasks.py b/examples/background_tasks.py index f3d83d96564..2a1ec12afae 100755 --- a/examples/background_tasks.py +++ b/examples/background_tasks.py @@ -32,8 +32,8 @@ async def listen_to_redis(app): async for msg in ch.iter(encoding="utf-8"): # Forward message to all connected websockets: for ws in app["websockets"]: - await ws.send_str("{}: {}".format(ch.name, msg)) - print("message in {}: {}".format(ch.name, msg)) + await ws.send_str(f"{ch.name}: {msg}") + print(f"message in {ch.name}: {msg}") except asyncio.CancelledError: pass finally: diff --git a/examples/client_ws.py b/examples/client_ws.py index 32ac54b2652..ec48eccc9ad 100755 --- a/examples/client_ws.py +++ b/examples/client_ws.py @@ -64,7 +64,7 @@ async def dispatch(): args.host, port = args.host.split(":", 1) args.port = int(port) - url = "http://{}:{}".format(args.host, args.port) + url = f"http://{args.host}:{args.port}" loop = asyncio.get_event_loop() diff --git a/examples/legacy/tcp_protocol_parser.py b/examples/legacy/tcp_protocol_parser.py index 419f73ea6fd..ca49db7d8f9 100755 --- a/examples/legacy/tcp_protocol_parser.py +++ b/examples/legacy/tcp_protocol_parser.py @@ -60,7 +60,7 @@ def stop(self): self.transport.write(b"stop:\r\n") def send_text(self, text): - self.transport.write("text:{}\r\n".format(text.strip()).encode("utf-8")) + self.transport.write(f"text:{text.strip()}\r\n".encode("utf-8")) class EchoServer(asyncio.Protocol): @@ -90,7 +90,7 @@ async def dispatch(self): # client has been disconnected break - print("Message received: {}".format(msg)) + print(f"Message received: {msg}") if msg.type == MSG_PING: writer.pong() @@ -116,7 +116,7 @@ async def start_client(loop, host, port): print("Server has been disconnected.") break - print("Message received: {}".format(msg)) + print(f"Message received: {msg}") if msg.type == MSG_PONG: writer.send_text(message) print("data sent:", message) diff --git a/examples/server_simple.py b/examples/server_simple.py index e9c936d7c37..d464383d269 100644 --- a/examples/server_simple.py +++ b/examples/server_simple.py @@ -14,7 +14,7 @@ async def wshandle(request): async for msg in ws: if msg.type == web.WSMsgType.text: - await ws.send_str("Hello, {}".format(msg.data)) + await ws.send_str(f"Hello, {msg.data}") elif msg.type == web.WSMsgType.binary: await ws.send_bytes(msg.data) elif msg.type == web.WSMsgType.close: diff --git a/tests/conftest.py b/tests/conftest.py index 890278bda55..09cbf6c9ed7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -88,7 +88,7 @@ def tls_certificate_fingerprint_sha256(tls_certificate_pem_bytes): @pytest.fixture def pipe_name(): - name = r"\\.\pipe\{}".format(uuid.uuid4().hex) + name = fr"\\.\pipe\{uuid.uuid4().hex}" return name diff --git a/tests/test_client_exceptions.py b/tests/test_client_exceptions.py index 05e34df4f78..4268825897c 100644 --- a/tests/test_client_exceptions.py +++ b/tests/test_client_exceptions.py @@ -59,7 +59,7 @@ def test_pickle(self) -> None: def test_repr(self) -> None: err = client.ClientResponseError(request_info=self.request_info, history=()) - assert repr(err) == ("ClientResponseError(%r, ())" % (self.request_info,)) + assert repr(err) == (f"ClientResponseError({self.request_info!r}, ())") err = client.ClientResponseError( request_info=self.request_info, @@ -163,7 +163,7 @@ def test_repr(self) -> None: connection_key=self.connection_key, os_error=os_error ) assert repr(err) == ( - "ClientConnectorError(%r, %r)" % (self.connection_key, os_error) + f"ClientConnectorError({self.connection_key!r}, {os_error!r})" ) def test_str(self) -> None: diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py index ba75399fd48..6bd8d44bb5a 100644 --- a/tests/test_client_functional.py +++ b/tests/test_client_functional.py @@ -371,7 +371,7 @@ async def handler(request): server = await aiohttp_server(app) client = aiohttp.ClientSession() task = loop.create_task(client.get(server.make_url("/"))) - assert "{}".format(task).startswith(" None: def test_skip_default_useragent_header(make_request) -> None: req = make_request( - "get", "http://python.org/", skip_auto_headers=set([istr("user-agent")]) + "get", "http://python.org/", skip_auto_headers={istr("user-agent")} ) assert "User-Agent" not in req.headers diff --git a/tests/test_client_response.py b/tests/test_client_response.py index aac124663d7..55aae970861 100644 --- a/tests/test_client_response.py +++ b/tests/test_client_response.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Tests for aiohttp/client.py import gc diff --git a/tests/test_client_session.py b/tests/test_client_session.py index a9f23aa81f1..298dac9f274 100644 --- a/tests/test_client_session.py +++ b/tests/test_client_session.py @@ -644,7 +644,7 @@ class MyClientRequest(ClientRequest): headers = None def __init__(self, *args, **kwargs): - super(MyClientRequest, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) MyClientRequest.headers = self.headers async def new_headers(session, trace_config_ctx, data): diff --git a/tests/test_connector.py b/tests/test_connector.py index d22c69f2fda..09841923e16 100644 --- a/tests/test_connector.py +++ b/tests/test_connector.py @@ -1973,7 +1973,7 @@ async def test_resolver_not_called_with_address_is_ip(loop) -> None: req = ClientRequest( "GET", - URL("http://127.0.0.1:{}".format(unused_port())), + URL(f"http://127.0.0.1:{unused_port()}"), loop=loop, response_class=mock.Mock(), ) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 8581c221e55..3367c24b78a 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -629,5 +629,5 @@ def test_repr(self) -> None: d1 = {"a": 2, "b": 3} d2 = {"a": 1} cp = helpers.ChainMapProxy([d1, d2]) - expected = "ChainMapProxy({!r}, {!r})".format(d1, d2) + expected = f"ChainMapProxy({d1!r}, {d2!r})" assert expected == repr(cp) diff --git a/tests/test_http_parser.py b/tests/test_http_parser.py index fd07711f489..38b83ff4863 100644 --- a/tests/test_http_parser.py +++ b/tests/test_http_parser.py @@ -370,7 +370,7 @@ def test_max_header_field_size(parser, size) -> None: name = b"t" * size text = b"GET /test HTTP/1.1\r\n" + name + b":data\r\n\r\n" - match = "400, message='Got more than 8190 bytes \\({}\\) when reading".format(size) + match = f"400, message='Got more than 8190 bytes \\({size}\\) when reading" with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data(text) @@ -398,7 +398,7 @@ def test_max_header_value_size(parser, size) -> None: name = b"t" * size text = b"GET /test HTTP/1.1\r\n" b"data:" + name + b"\r\n\r\n" - match = "400, message='Got more than 8190 bytes \\({}\\) when reading".format(size) + match = f"400, message='Got more than 8190 bytes \\({size}\\) when reading" with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data(text) @@ -426,7 +426,7 @@ def test_max_header_value_size_continuation(parser, size) -> None: name = b"T" * (size - 5) text = b"GET /test HTTP/1.1\r\n" b"data: test\r\n " + name + b"\r\n\r\n" - match = "400, message='Got more than 8190 bytes \\({}\\) when reading".format(size) + match = f"400, message='Got more than 8190 bytes \\({size}\\) when reading" with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data(text) @@ -488,7 +488,7 @@ def test_http_request_upgrade(parser) -> None: def test_http_request_parser_utf8(parser) -> None: - text = "GET /path HTTP/1.1\r\nx-test:тест\r\n\r\n".encode("utf-8") + text = "GET /path HTTP/1.1\r\nx-test:тест\r\n\r\n".encode() messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] @@ -496,7 +496,7 @@ def test_http_request_parser_utf8(parser) -> None: assert msg.path == "/path" assert msg.version == (1, 1) assert msg.headers == CIMultiDict([("X-TEST", "тест")]) - assert msg.raw_headers == ((b"x-test", "тест".encode("utf-8")),) + assert msg.raw_headers == ((b"x-test", "тест".encode()),) assert not msg.should_close assert msg.compression is None assert not msg.upgrade @@ -548,7 +548,7 @@ def test_http_request_parser_bad_version(parser) -> None: @pytest.mark.parametrize("size", [40965, 8191]) def test_http_request_max_status_line(parser, size) -> None: path = b"t" * (size - 5) - match = "400, message='Got more than 8190 bytes \\({}\\) when reading".format(size) + match = f"400, message='Got more than 8190 bytes \\({size}\\) when reading" with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data(b"GET /path" + path + b" HTTP/1.1\r\n\r\n") @@ -573,7 +573,7 @@ def test_http_request_max_status_line_under_limit(parser) -> None: def test_http_response_parser_utf8(response) -> None: - text = "HTTP/1.1 200 Ok\r\nx-test:тест\r\n\r\n".encode("utf-8") + text = "HTTP/1.1 200 Ok\r\nx-test:тест\r\n\r\n".encode() messages, upgraded, tail = response.feed_data(text) assert len(messages) == 1 @@ -583,7 +583,7 @@ def test_http_response_parser_utf8(response) -> None: assert msg.code == 200 assert msg.reason == "Ok" assert msg.headers == CIMultiDict([("X-TEST", "тест")]) - assert msg.raw_headers == ((b"x-test", "тест".encode("utf-8")),) + assert msg.raw_headers == ((b"x-test", "тест".encode()),) assert not upgraded assert not tail @@ -591,7 +591,7 @@ def test_http_response_parser_utf8(response) -> None: @pytest.mark.parametrize("size", [40962, 8191]) def test_http_response_parser_bad_status_line_too_long(response, size) -> None: reason = b"t" * (size - 2) - match = "400, message='Got more than 8190 bytes \\({}\\) when reading".format(size) + match = f"400, message='Got more than 8190 bytes \\({size}\\) when reading" with pytest.raises(http_exceptions.LineTooLong, match=match): response.feed_data(b"HTTP/1.1 200 Ok" + reason + b"\r\n\r\n") @@ -760,7 +760,7 @@ def test_partial_url(parser) -> None: def test_url_parse_non_strict_mode(parser) -> None: - payload = "GET /test/тест HTTP/1.1\r\n\r\n".encode("utf-8") + payload = "GET /test/тест HTTP/1.1\r\n\r\n".encode() messages, upgrade, tail = parser.feed_data(payload) assert len(messages) == 1 @@ -784,7 +784,7 @@ def test_url_parse_non_strict_mode(parser) -> None: ], ) def test_parse_uri_percent_encoded(parser, uri, path, query, fragment) -> None: - text = ("GET %s HTTP/1.1\r\n\r\n" % (uri,)).encode() + text = (f"GET {uri} HTTP/1.1\r\n\r\n").encode() messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] @@ -825,7 +825,7 @@ def test_parse_uri_utf8_percent_encoded(parser) -> None: reason="C based HTTP parser not available", ) def test_parse_bad_method_for_c_parser_raises(loop, protocol): - payload = "GET1 /test HTTP/1.1\r\n\r\n".encode("utf-8") + payload = b"GET1 /test HTTP/1.1\r\n\r\n" parser = HttpRequestParserC( protocol, loop, diff --git a/tests/test_multipart.py b/tests/test_multipart.py index 71dff22e7a2..6c3f1214d9e 100644 --- a/tests/test_multipart.py +++ b/tests/test_multipart.py @@ -381,7 +381,7 @@ async def test_read_text(self) -> None: async def test_read_text_default_encoding(self) -> None: obj = aiohttp.BodyPartReader( - BOUNDARY, {}, Stream("Привет, Мир!\r\n--:--".encode("utf-8")) + BOUNDARY, {}, Stream("Привет, Мир!\r\n--:--".encode()) ) result = await obj.text() assert "Привет, Мир!" == result @@ -486,7 +486,7 @@ async def test_read_form_guess_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: "application/x-www-form-urlencoded; charset=utf-8"}, - Stream("foo=bar&foo=baz&boo=\r\n--:--".encode("utf-8")), + Stream(b"foo=bar&foo=baz&boo=\r\n--:--"), ) result = await obj.form() assert [("foo", "bar"), ("foo", "baz"), ("boo", "")] == result diff --git a/tests/test_proxy_functional.py b/tests/test_proxy_functional.py index 407fc9c77fc..68763cd446e 100644 --- a/tests/test_proxy_functional.py +++ b/tests/test_proxy_functional.py @@ -248,7 +248,7 @@ async def request(pid): responses = await asyncio.gather(*requests, loop=loop) assert len(responses) == multi_conn_num - assert set(resp.status for resp in responses) == {200} + assert {resp.status for resp in responses} == {200} await sess.close() @@ -453,7 +453,7 @@ async def request(pid): responses = await asyncio.gather(*requests, loop=loop) assert len(responses) == multi_conn_num - assert set(resp.status for resp in responses) == {200} + assert {resp.status for resp in responses} == {200} await sess.close() @@ -532,7 +532,7 @@ async def test_proxy_from_env_http_with_auth_from_netrc( proxy = await proxy_test_server() auth = aiohttp.BasicAuth("user", "pass") netrc_file = tmpdir.join("test_netrc") - netrc_file_data = "machine 127.0.0.1 login %s password %s" % ( + netrc_file_data = "machine 127.0.0.1 login {} password {}".format( auth.login, auth.password, ) @@ -558,7 +558,7 @@ async def test_proxy_from_env_http_without_auth_from_netrc( proxy = await proxy_test_server() auth = aiohttp.BasicAuth("user", "pass") netrc_file = tmpdir.join("test_netrc") - netrc_file_data = "machine 127.0.0.2 login %s password %s" % ( + netrc_file_data = "machine 127.0.0.2 login {} password {}".format( auth.login, auth.password, ) @@ -584,7 +584,7 @@ async def test_proxy_from_env_http_without_auth_from_wrong_netrc( proxy = await proxy_test_server() auth = aiohttp.BasicAuth("user", "pass") netrc_file = tmpdir.join("test_netrc") - invalid_data = "machine 127.0.0.1 %s pass %s" % (auth.login, auth.password) + invalid_data = f"machine 127.0.0.1 {auth.login} pass {auth.password}" with open(str(netrc_file), "w") as f: f.write(invalid_data) diff --git a/tests/test_run_app.py b/tests/test_run_app.py index b35c05be729..09187cebd72 100644 --- a/tests/test_run_app.py +++ b/tests/test_run_app.py @@ -509,7 +509,7 @@ def test_run_app_http_unix_socket(patched_loop, shorttmpdir) -> None: patched_loop.create_unix_server.assert_called_with( mock.ANY, sock_path, ssl=None, backlog=128 ) - assert "http://unix:{}:".format(sock_path) in printer.call_args[0][0] + assert f"http://unix:{sock_path}:" in printer.call_args[0][0] @skip_if_no_unix_socks @@ -524,7 +524,7 @@ def test_run_app_https_unix_socket(patched_loop, shorttmpdir) -> None: patched_loop.create_unix_server.assert_called_with( mock.ANY, sock_path, ssl=ssl_context, backlog=128 ) - assert "https://unix:{}:".format(sock_path) in printer.call_args[0][0] + assert f"https://unix:{sock_path}:" in printer.call_args[0][0] @skip_if_no_unix_socks @@ -555,7 +555,7 @@ def test_run_app_preexisting_inet_socket(patched_loop, mocker) -> None: patched_loop.create_server.assert_called_with( mock.ANY, sock=sock, backlog=128, ssl=None ) - assert "http://0.0.0.0:{}".format(port) in printer.call_args[0][0] + assert f"http://0.0.0.0:{port}" in printer.call_args[0][0] @pytest.mark.skipif(not HAS_IPV6, reason="IPv6 is not available") @@ -573,7 +573,7 @@ def test_run_app_preexisting_inet6_socket(patched_loop) -> None: patched_loop.create_server.assert_called_with( mock.ANY, sock=sock, backlog=128, ssl=None ) - assert "http://[::]:{}".format(port) in printer.call_args[0][0] + assert f"http://[::]:{port}" in printer.call_args[0][0] @skip_if_no_unix_socks @@ -592,7 +592,7 @@ def test_run_app_preexisting_unix_socket(patched_loop, mocker) -> None: patched_loop.create_server.assert_called_with( mock.ANY, sock=sock, backlog=128, ssl=None ) - assert "http://unix:{}:".format(sock_path) in printer.call_args[0][0] + assert f"http://unix:{sock_path}:" in printer.call_args[0][0] def test_run_app_multiple_preexisting_sockets(patched_loop) -> None: @@ -615,8 +615,8 @@ def test_run_app_multiple_preexisting_sockets(patched_loop) -> None: mock.call(mock.ANY, sock=sock2, backlog=128, ssl=None), ] ) - assert "http://0.0.0.0:{}".format(port1) in printer.call_args[0][0] - assert "http://0.0.0.0:{}".format(port2) in printer.call_args[0][0] + assert f"http://0.0.0.0:{port1}" in printer.call_args[0][0] + assert f"http://0.0.0.0:{port2}" in printer.call_args[0][0] _script_test_signal = """ diff --git a/tests/test_urldispatch.py b/tests/test_urldispatch.py index 4e3a55ad976..588daed8d40 100644 --- a/tests/test_urldispatch.py +++ b/tests/test_urldispatch.py @@ -719,7 +719,7 @@ async def test_dynamic_match_unquoted_path(router) -> None: handler = make_handler() router.add_route("GET", "/{path}/{subpath}", handler) resource_id = "my%2Fpath%7Cwith%21some%25strange%24characters" - req = make_mocked_request("GET", "/path/{0}".format(resource_id)) + req = make_mocked_request("GET", f"/path/{resource_id}") match_info = await router.resolve(req) assert match_info == {"path": "path", "subpath": unquote(resource_id)} diff --git a/tests/test_web_cli.py b/tests/test_web_cli.py index 035fdbc95e9..12a01dff577 100644 --- a/tests/test_web_cli.py +++ b/tests/test_web_cli.py @@ -75,7 +75,9 @@ def test_entry_func_non_existent_attribute(mocker) -> None: with pytest.raises(SystemExit): web.main(argv) - error.assert_called_with("module %r has no attribute %r" % ("alpha.beta", "func")) + error.assert_called_with( + "module {!r} has no attribute {!r}".format("alpha.beta", "func") + ) def test_path_when_unsupported(mocker, monkeypatch) -> None: diff --git a/tests/test_web_exceptions.py b/tests/test_web_exceptions.py index e45639be4d1..43e5029803f 100644 --- a/tests/test_web_exceptions.py +++ b/tests/test_web_exceptions.py @@ -150,7 +150,7 @@ async def test_HTTPMethodNotAllowed(buf, http_request) -> None: def test_override_body_with_text() -> None: resp = web.HTTPNotFound(text="Page not found") assert 404 == resp.status - assert "Page not found".encode("utf-8") == resp.body + assert b"Page not found" == resp.body assert "Page not found" == resp.text assert "text/plain" == resp.content_type assert "utf-8" == resp.charset diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py index f83d383e6fe..a28fcd4f56b 100644 --- a/tests/test_web_functional.py +++ b/tests/test_web_functional.py @@ -242,7 +242,7 @@ async def handler(request): reader = await request.multipart() assert isinstance(reader, multipart.MultipartReader) async for part in reader: - assert False, "Unexpected part found in reader: {!r}".format(part) + assert False, f"Unexpected part found in reader: {part!r}" return web.Response() app = web.Application() diff --git a/tests/test_web_log.py b/tests/test_web_log.py index 0652dd44227..0a4168ae72e 100644 --- a/tests/test_web_log.py +++ b/tests/test_web_log.py @@ -186,7 +186,7 @@ async def middleware(request, handler): class Logger(AbstractAccessLogger): def log(self, request, response, time): nonlocal msg - msg = "contextvars: {}".format(VAR.get()) + msg = f"contextvars: {VAR.get()}" app = web.Application(middlewares=[middleware]) app.router.add_get("/", handler) diff --git a/tests/test_web_middleware.py b/tests/test_web_middleware.py index d33cd4722ec..9b42ba3747e 100644 --- a/tests/test_web_middleware.py +++ b/tests/test_web_middleware.py @@ -66,7 +66,7 @@ async def middleware(request, handler): getattr(handler, "annotation", None) ) resp = await handler(request) - resp.text = resp.text + "[{}]".format(num) + resp.text = resp.text + f"[{num}]" return resp return middleware @@ -110,9 +110,7 @@ def make_middleware(num): async def middleware(request, handler): annotation = getattr(handler, "annotation", None) if annotation is not None: - middleware_annotation_seen_values.append( - "{}/{}".format(annotation, num) - ) + middleware_annotation_seen_values.append(f"{annotation}/{num}") return await handler(request) return middleware diff --git a/tests/test_web_request.py b/tests/test_web_request.py index c2a7b7ad43a..f251e04f4b9 100644 --- a/tests/test_web_request.py +++ b/tests/test_web_request.py @@ -350,7 +350,7 @@ def test_single_forwarded_header() -> None: ], ) def test_forwarded_node_identifier(forward_for_in, forward_for_out) -> None: - header = "for={}".format(forward_for_in) + header = f"for={forward_for_in}" req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header})) assert req.forwarded == ({"for": forward_for_out},) diff --git a/tests/test_web_sendfile_functional.py b/tests/test_web_sendfile_functional.py index 3f373382d5d..fdae26838a2 100644 --- a/tests/test_web_sendfile_functional.py +++ b/tests/test_web_sendfile_functional.py @@ -391,17 +391,17 @@ async def handler(request): ) assert len(responses) == 3 assert responses[0].status == 206, "failed 'bytes=0-999': %s" % responses[0].reason - assert responses[0].headers["Content-Range"] == "bytes 0-999/{0}".format( + assert responses[0].headers["Content-Range"] == "bytes 0-999/{}".format( filesize ), "failed: Content-Range Error" assert responses[1].status == 206, ( "failed 'bytes=1000-1999': %s" % responses[1].reason ) - assert responses[1].headers["Content-Range"] == "bytes 1000-1999/{0}".format( + assert responses[1].headers["Content-Range"] == "bytes 1000-1999/{}".format( filesize ), "failed: Content-Range Error" assert responses[2].status == 206, "failed 'bytes=2000-': %s" % responses[2].reason - assert responses[2].headers["Content-Range"] == "bytes 2000-{0}/{1}".format( + assert responses[2].headers["Content-Range"] == "bytes 2000-{}/{}".format( filesize - 1, filesize ), "failed: Content-Range Error" diff --git a/tools/check_changes.py b/tools/check_changes.py index c4e3554b372..4ee3fc1b2de 100755 --- a/tools/check_changes.py +++ b/tools/check_changes.py @@ -3,17 +3,12 @@ import sys from pathlib import Path - -ALLOWED_SUFFIXES = ['.feature', - '.bugfix', - '.doc', - '.removal', - '.misc'] +ALLOWED_SUFFIXES = [".feature", ".bugfix", ".doc", ".removal", ".misc"] def get_root(script_path): folder = script_path.absolute().parent - while not (folder / '.git').exists(): + while not (folder / ".git").exists(): folder = folder.parent if folder == folder.anchor: raise RuntimeError("git repo not found") @@ -21,29 +16,29 @@ def get_root(script_path): def main(argv): - print('Check "CHANGES" folder... ', end='', flush=True) + print('Check "CHANGES" folder... ', end="", flush=True) here = Path(argv[0]) root = get_root(here) - changes = root / 'CHANGES' + changes = root / "CHANGES" failed = False for fname in changes.iterdir(): - if fname.name in ('.gitignore', '.TEMPLATE.rst'): + if fname.name in (".gitignore", ".TEMPLATE.rst"): continue if fname.suffix not in ALLOWED_SUFFIXES: if not failed: - print('') - print(fname, 'has illegal suffix', file=sys.stderr) + print("") + print(fname, "has illegal suffix", file=sys.stderr) failed = True if failed: - print('', file=sys.stderr) - print('Allowed suffixes are:', ALLOWED_SUFFIXES, file=sys.stderr) - print('', file=sys.stderr) + print("", file=sys.stderr) + print("Allowed suffixes are:", ALLOWED_SUFFIXES, file=sys.stderr) + print("", file=sys.stderr) else: - print('OK') + print("OK") return int(failed) -if __name__ == '__main__': +if __name__ == "__main__": sys.exit(main(sys.argv)) diff --git a/tools/gen.py b/tools/gen.py index 64e770977df..7cb60eb67f3 100755 --- a/tools/gen.py +++ b/tools/gen.py @@ -1,14 +1,18 @@ #!/usr/bin/env python3 -import aiohttp +import io import pathlib -from aiohttp import hdrs from collections import defaultdict -import io -headers = [getattr(hdrs, name) - for name in dir(hdrs) - if isinstance(getattr(hdrs, name), hdrs.istr)] +import aiohttp +from aiohttp import hdrs + +headers = [ + getattr(hdrs, name) + for name in dir(hdrs) + if isinstance(getattr(hdrs, name), hdrs.istr) +] + def factory(): return defaultdict(factory) @@ -26,6 +30,7 @@ def build(headers): d[TERMINAL] = hdr return dct + dct = build(headers) @@ -82,9 +87,10 @@ def build(headers): }} """ + def gen_prefix(prefix, k): - if k == '-': - return prefix + '_' + if k == "-": + return prefix + "_" else: return prefix + k.upper() @@ -107,9 +113,9 @@ def gen_block(dct, prefix, used_blocks, missing, out): if lo != hi: case = CASE.format(char=lo, index=index, next=next_prefix) cases.append(case) - label = prefix if prefix else 'INITIAL' + label = prefix if prefix else "INITIAL" if cases: - block = BLOCK.format(label=label, cases='\n'.join(cases)) + block = BLOCK.format(label=label, cases="\n".join(cases)) out.write(block) else: missing.add(label) @@ -127,8 +133,8 @@ def gen(dct): out = io.StringIO() out.write(HEADER) missing = set() - gen_block(dct, '', set(), missing, out) - missing_labels = '\n'.join(m + ':' for m in sorted(missing)) + gen_block(dct, "", set(), missing, out) + missing_labels = "\n".join(m + ":" for m in sorted(missing)) out.write(FOOTER.format(missing=missing_labels)) return out @@ -141,17 +147,18 @@ def gen_headers(headers): out.write("from . import hdrs\n") out.write("cdef tuple headers = (\n") for hdr in headers: - out.write(" hdrs.{},\n".format(hdr.upper().replace('-', '_'))) + out.write(" hdrs.{},\n".format(hdr.upper().replace("-", "_"))) out.write(")\n") return out + # print(gen(dct).getvalue()) # print(gen_headers(headers).getvalue()) folder = pathlib.Path(aiohttp.__file__).parent -with (folder / '_find_header.c').open('w') as f: +with (folder / "_find_header.c").open("w") as f: f.write(gen(dct).getvalue()) -with (folder / '_headers.pxi').open('w') as f: +with (folder / "_headers.pxi").open("w") as f: f.write(gen_headers(headers).getvalue())