From dcffb53b167ed822741216755f3990b636896849 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Thu, 11 Nov 2021 09:41:13 +0200 Subject: [PATCH] Add flake8-docstrings, fix bunch of flagged issues (#6276) * Check docstrings with flake8-docstrings * Address pydocstyle D2xx issues * Add CHANGES entry * Fix linter Co-authored-by: Andrew Svetlov --- .pre-commit-config.yaml | 2 ++ CHANGES/6276.doc | 1 + aiohttp/client.py | 18 +++++----- aiohttp/client_exceptions.py | 3 +- aiohttp/connector.py | 19 +++++----- aiohttp/formdata.py | 6 ++-- aiohttp/helpers.py | 9 +++-- aiohttp/http_parser.py | 8 +++-- aiohttp/locks.py | 5 +-- aiohttp/multipart.py | 34 +++++++++--------- aiohttp/payload_streamer.py | 3 +- aiohttp/pytest_plugin.py | 21 ++++++----- aiohttp/resolver.py | 6 ++-- aiohttp/streams.py | 15 ++++---- aiohttp/test_utils.py | 24 +++++-------- aiohttp/tracing.py | 10 +++--- aiohttp/web_middlewares.py | 8 ++--- aiohttp/web_protocol.py | 25 ++++++++----- aiohttp/web_request.py | 3 +- aiohttp/web_response.py | 1 - aiohttp/web_urldispatcher.py | 41 ++++++++-------------- docs/spelling_wordlist.txt | 1 + examples/web_classview.py | 3 +- examples/web_cookies.py | 3 +- examples/web_rewrite_headers_middleware.py | 5 ++- examples/web_srv.py | 3 +- examples/web_srv_route_deco.py | 4 +-- examples/web_srv_route_table.py | 4 +-- examples/web_ws.py | 3 +- setup.cfg | 3 +- tests/conftest.py | 5 ++- tests/test___all__.py | 4 +-- tests/test_http_parser.py | 5 ++- tests/test_web_exceptions.py | 4 +-- tests/test_web_urldispatcher.py | 6 ++-- 35 files changed, 153 insertions(+), 162 deletions(-) create mode 100644 CHANGES/6276.doc diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 664f48f74d..31c701f0bb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -79,6 +79,8 @@ repos: rev: '4.0.1' hooks: - id: flake8 + additional_dependencies: + - flake8-docstrings==1.6.0 exclude: "^docs/" - repo: git://github.com/Lucas-C/pre-commit-hooks-markup rev: v1.0.1 diff --git a/CHANGES/6276.doc b/CHANGES/6276.doc new file mode 100644 index 0000000000..bfd0697149 --- /dev/null +++ b/CHANGES/6276.doc @@ -0,0 +1 @@ +Add flake8-docstrings to flake8 configuration, enable subset of checks. diff --git a/aiohttp/client.py b/aiohttp/client.py index 7adcf835d7..c6e4a76620 100644 --- a/aiohttp/client.py +++ b/aiohttp/client.py @@ -1057,23 +1057,21 @@ def connector_owner(self) -> bool: def raise_for_status( self, ) -> Union[bool, Callable[[ClientResponse], Awaitable[None]]]: - """ - Should `ClientResponse.raise_for_status()` - be called for each response - """ + """Should `ClientResponse.raise_for_status()` be called for each response.""" return self._raise_for_status @property def auto_decompress(self) -> bool: - """Should the body response be automatically decompressed""" + """Should the body response be automatically decompressed.""" return self._auto_decompress @property def trust_env(self) -> bool: """ - Should get proxies information - from HTTP_PROXY / HTTPS_PROXY environment variables - or ~/.netrc file if present + Should proxies information from environment or netrc be trusted. + + Information is from HTTP_PROXY / HTTPS_PROXY environment variables + or ~/.netrc file if present. """ return self._trust_env @@ -1229,7 +1227,9 @@ def request( read_bufsize: Optional[int] = None, loop: Optional[asyncio.AbstractEventLoop] = None, ) -> _SessionRequestContextManager: - """Constructs and sends a request. Returns response object. + """Constructs and sends a request. + + Returns response object. method - HTTP method url - request url params - (optional) Dictionary or bytes to be sent in the query diff --git a/aiohttp/client_exceptions.py b/aiohttp/client_exceptions.py index 0384128e08..dd55321054 100644 --- a/aiohttp/client_exceptions.py +++ b/aiohttp/client_exceptions.py @@ -262,7 +262,8 @@ class InvalidURL(ClientError, ValueError): """Invalid URL. URL used for fetching is malformed, e.g. it doesn't contains host - part.""" + part. + """ # Derive from ValueError for backward compatibility diff --git a/aiohttp/connector.py b/aiohttp/connector.py index 5641323144..08dc496d1b 100644 --- a/aiohttp/connector.py +++ b/aiohttp/connector.py @@ -328,12 +328,10 @@ def limit(self) -> int: @property def limit_per_host(self) -> int: - """The limit_per_host for simultaneous connections - to the same endpoint. + """The limit for simultaneous connections to the same endpoint. Endpoints are the same if they are have equal (host, port, is_ssl) triple. - """ return self._limit_per_host @@ -391,6 +389,7 @@ def _drop_acquired_per_host( def _cleanup_closed(self) -> None: """Double confirmation for transport close. + Some broken ssl servers may leave socket open without proper close. """ if self._cleanup_closed_handle: @@ -459,13 +458,13 @@ def closed(self) -> bool: def _available_connections(self, key: "ConnectionKey") -> int: """ - Return number of available connections taking into account - the limit, limit_per_host and the connection key. + Return number of available connections. - If it returns less than 1 means that there is no connections - availables. - """ + The limit, limit_per_host and the connection key are taken into account. + If it returns less than 1 means that there are no connections + available. + """ if self._limit: # total calc available connections available = self._limit - len(self._acquired) @@ -606,7 +605,9 @@ def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]: def _release_waiter(self) -> None: """ - Iterates over all waiters till found one that is not finsihed and + Iterates over all waiters until one to be released is found. + + The one to be released is not finsihed and belongs to a host that has available connections. """ if not self._waiters: diff --git a/aiohttp/formdata.py b/aiohttp/formdata.py index 6da5538629..4857c89856 100644 --- a/aiohttp/formdata.py +++ b/aiohttp/formdata.py @@ -12,8 +12,10 @@ class FormData: - """Helper class for multipart/form-data and - application/x-www-form-urlencoded body generation.""" + """Helper class for form body generation. + + Supports multipart/form-data and application/x-www-form-urlencoded. + """ def __init__( self, diff --git a/aiohttp/helpers.py b/aiohttp/helpers.py index 1b833a0af1..536d219012 100644 --- a/aiohttp/helpers.py +++ b/aiohttp/helpers.py @@ -196,7 +196,9 @@ def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: def netrc_from_env() -> Optional[netrc.netrc]: - """Attempt to load the netrc file from the path specified by the env-var + """Load netrc from file. + + Attempt to load it from the path specified by the env-var NETRC or in the default location in the user's home directory. Returns None if it couldn't be found or fails to parse. @@ -457,12 +459,13 @@ class _TSelf(Protocol, Generic[_T]): class reify(Generic[_T]): - """Use as a class method decorator. It operates almost exactly like + """Use as a class method decorator. + + It operates almost exactly like the Python `@property` decorator, but it puts the result of the method it decorates into the instance dict after the first call, effectively replacing the function it decorates with an instance variable. It is, in Python parlance, a data descriptor. - """ def __init__(self, wrapped: Callable[..., _T]) -> None: diff --git a/aiohttp/http_parser.py b/aiohttp/http_parser.py index e1b86e8e4f..c965c2b18e 100644 --- a/aiohttp/http_parser.py +++ b/aiohttp/http_parser.py @@ -504,13 +504,16 @@ def parse_headers( def set_upgraded(self, val: bool) -> None: """Set connection upgraded (to websocket) mode. + :param bool val: new state. """ self._upgraded = val class HttpRequestParser(HttpParser[RawRequestMessage]): - """Read request status line. Exception .http_exceptions.BadStatusLine + """Read request status line. + + Exception .http_exceptions.BadStatusLine could be raised in case of any errors in status line. Returns RawRequestMessage. """ @@ -588,7 +591,8 @@ class HttpResponseParser(HttpParser[RawResponseMessage]): """Read response status line and headers. BadStatusLine could be raised in case of any errors in status line. - Returns RawResponseMessage""" + Returns RawResponseMessage. + """ def parse_message(self, lines: List[bytes]) -> RawResponseMessage: line = lines[0].decode("utf-8", "surrogateescape") diff --git a/aiohttp/locks.py b/aiohttp/locks.py index e957d4f097..df65e3e47d 100644 --- a/aiohttp/locks.py +++ b/aiohttp/locks.py @@ -4,8 +4,9 @@ class EventResultOrError: - """ - This class wrappers the Event asyncio lock allowing either awake the + """Event asyncio lock helper class. + + Wraps the Event asyncio lock allowing either to awake the locked Tasks without any error or raising an exception. thanks to @vorpalsmith for the simple design. diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py index 54a3266a23..c84e20044f 100644 --- a/aiohttp/multipart.py +++ b/aiohttp/multipart.py @@ -242,8 +242,10 @@ async def next( return item async def release(self) -> None: - """Releases the connection gracefully, reading all the content - to the void.""" + """Release the connection gracefully. + + All remaining content is read to the void. + """ await self.resp.release() @@ -416,9 +418,7 @@ async def json(self, *, encoding: Optional[str] = None) -> Optional[Dict[str, An return cast(Dict[str, Any], json.loads(data.decode(encoding))) async def form(self, *, encoding: Optional[str] = None) -> List[Tuple[str, str]]: - """Like read(), but assumes that body parts contains form - urlencoded data. - """ + """Like read(), but assumes that body parts contain form urlencoded data.""" data = await self.read(decode=True) if not data: return [] @@ -437,7 +437,9 @@ def at_eof(self) -> bool: return self._at_eof def decode(self, data: bytes) -> bytes: - """Decodes data according the specified Content-Encoding + """Decodes data. + + Decoding is done according the specified Content-Encoding or Content-Transfer-Encoding headers value. """ if CONTENT_TRANSFER_ENCODING in self.headers: @@ -480,17 +482,18 @@ def get_charset(self, default: str) -> str: @reify def name(self) -> Optional[str]: - """Returns name specified in Content-Disposition header or None - if missed or header is malformed. - """ + """Returns name specified in Content-Disposition header. + If the header is missing or malformed, returns None. + """ _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) return content_disposition_filename(params, "name") @reify def filename(self) -> Optional[str]: - """Returns filename specified in Content-Disposition header or None - if missed or header is malformed. + """Returns filename specified in Content-Disposition header. + + Returns None if the header is missing or malformed. """ _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) return content_disposition_filename(params, "filename") @@ -568,9 +571,7 @@ def from_response( return obj def at_eof(self) -> bool: - """Returns True if the final boundary was reached or - False otherwise. - """ + """Returns True if the final boundary was reached, false otherwise.""" return self._at_eof async def next( @@ -610,8 +611,9 @@ def _get_part_reader( self, headers: "CIMultiDictProxy[str]", ) -> Union["MultipartReader", BodyPartReader]: - """Dispatches the response by the `Content-Type` header, returning - suitable reader instance. + """Dispatches the response by the `Content-Type` header. + + Returns a suitable reader instance. :param dict headers: Response headers """ diff --git a/aiohttp/payload_streamer.py b/aiohttp/payload_streamer.py index 1bde92f6a0..9f8b8bc57c 100644 --- a/aiohttp/payload_streamer.py +++ b/aiohttp/payload_streamer.py @@ -1,4 +1,5 @@ -""" Payload implemenation for coroutines as data provider. +""" +Payload implemenation for coroutines as data provider. As a simple case, you can upload data from file:: diff --git a/aiohttp/pytest_plugin.py b/aiohttp/pytest_plugin.py index e4d07028dd..dd9a9f6179 100644 --- a/aiohttp/pytest_plugin.py +++ b/aiohttp/pytest_plugin.py @@ -55,7 +55,8 @@ def pytest_addoption(parser): # type: ignore[no-untyped-def] def pytest_fixture_setup(fixturedef): # type: ignore[no-untyped-def] - """ + """Set up pytest fixture. + Allow fixtures to be coroutines. Run coroutine fixtures in an event loop. """ func = fixturedef.func @@ -124,8 +125,9 @@ def loop_debug(request): # type: ignore[no-untyped-def] @contextlib.contextmanager def _runtime_warning_context(): # type: ignore[no-untyped-def] - """ - Context manager which checks for RuntimeWarnings, specifically to + """Context manager which checks for RuntimeWarnings. + + This exists specifically to avoid "coroutine 'X' was never awaited" warnings being missed. If RuntimeWarnings occur in the context a RuntimeError is raised. @@ -147,8 +149,9 @@ def _runtime_warning_context(): # type: ignore[no-untyped-def] @contextlib.contextmanager def _passthrough_loop_context(loop, fast=False): # type: ignore[no-untyped-def] - """ - setups and tears down a loop unless one is passed in via the loop + """Passthrough loop context. + + Sets up and tears down a loop unless one is passed in via the loop argument when it's passed straight through. """ if loop: @@ -162,17 +165,13 @@ def _passthrough_loop_context(loop, fast=False): # type: ignore[no-untyped-def] def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def] - """ - Fix pytest collecting for coroutines. - """ + """Fix pytest collecting for coroutines.""" if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj): return list(collector._genfunctions(name, obj)) def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def] - """ - Run coroutines in an event loop instead of a normal function call. - """ + """Run coroutines in an event loop instead of a normal function call.""" fast = pyfuncitem.config.getoption("--aiohttp-fast") if asyncio.iscoroutinefunction(pyfuncitem.function): existing_loop = pyfuncitem.funcargs.get( diff --git a/aiohttp/resolver.py b/aiohttp/resolver.py index 50cefe0a48..886b605b0b 100644 --- a/aiohttp/resolver.py +++ b/aiohttp/resolver.py @@ -18,8 +18,10 @@ class ThreadedResolver(AbstractResolver): - """Use Executor for synchronous getaddrinfo() calls, which defaults to - concurrent.futures.ThreadPoolExecutor. + """Threaded resolver. + + Uses an Executor for synchronous getaddrinfo() calls. + concurrent.futures.ThreadPoolExecutor is used by default. """ def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: diff --git a/aiohttp/streams.py b/aiohttp/streams.py index 114424d24d..055848877e 100644 --- a/aiohttp/streams.py +++ b/aiohttp/streams.py @@ -68,16 +68,16 @@ def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]: ) def iter_any(self) -> AsyncStreamIterator[bytes]: - """Returns an asynchronous iterator that yields all the available - data as soon as it is received + """Yield all available data as soon as it is received. Python-3.5 available for Python 3.5+ only """ return AsyncStreamIterator(self.readany) # type: ignore[attr-defined] def iter_chunks(self) -> ChunkTupleAsyncStreamIterator: - """Returns an asynchronous iterator that yields chunks of data - as they are received by the server. The yielded objects are tuples + """Yield chunks of data as they are received by the server. + + The yielded objects are tuples of (bytes, bool) as returned by the StreamReader.readchunk method. Python-3.5 available for Python 3.5+ only @@ -399,7 +399,9 @@ async def readany(self) -> bytes: return self._read_nowait(-1) async def readchunk(self) -> Tuple[bytes, bool]: - """Returns a tuple of (data, end_of_http_chunk). When chunked transfer + """Returns a tuple of (data, end_of_http_chunk). + + When chunked transfer encoding is used, end_of_http_chunk is a boolean indicating if the end of the data corresponds to the end of a HTTP chunk , otherwise it is always False. @@ -633,7 +635,8 @@ def __aiter__(self) -> AsyncStreamIterator[_T]: class FlowControlDataQueue(DataQueue[_T]): """FlowControlDataQueue resumes and pauses an underlying stream. - It is a destination for parsed data.""" + It is a destination for parsed data. + """ def __init__( self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop diff --git a/aiohttp/test_utils.py b/aiohttp/test_utils.py index 7860573d31..361dae486c 100644 --- a/aiohttp/test_utils.py +++ b/aiohttp/test_utils.py @@ -424,8 +424,7 @@ async def __aexit__( class AioHTTPTestCase(TestCase): - """A base class to allow for unittest web applications using - aiohttp. + """A base class to allow for unittest web applications using aiohttp. Provides the following: @@ -440,19 +439,18 @@ class AioHTTPTestCase(TestCase): """ async def get_application(self) -> Application: - """ + """Get application. + This method should be overridden to return the aiohttp.web.Application object to test. - """ return self.get_app() def get_app(self) -> Application: """Obsolete method used to constructing web application. - Use .get_application() coroutine instead - + Use .get_application() coroutine instead. """ raise RuntimeError("Did you forget to define get_application()?") @@ -487,8 +485,8 @@ async def get_client(self, server: TestServer) -> TestClient: def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any: - """A decorator dedicated to use with asynchronous methods of an - AioHTTPTestCase in aiohttp <3.8. + """ + A decorator dedicated to use with asynchronous AioHTTPTestCase test methods. In 3.8+, this does nothing. """ @@ -519,8 +517,7 @@ def loop_context( def setup_test_loop( loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, ) -> asyncio.AbstractEventLoop: - """Create and return an asyncio.BaseEventLoop - instance. + """Create and return an asyncio.BaseEventLoop instance. The caller should also call teardown_test_loop, once they are done with the loop. @@ -552,10 +549,7 @@ def setup_test_loop( def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None: - """Teardown and cleanup an event_loop created - by setup_test_loop. - - """ + """Teardown and cleanup an event_loop created by setup_test_loop.""" closed = loop.is_closed() if not closed: loop.call_soon(loop.stop) @@ -620,9 +614,7 @@ def make_mocked_request( Useful in unit tests, when spinning full web server is overkill or specific conditions and errors are hard to trigger. - """ - task = mock.Mock() if loop is ...: loop = mock.Mock() diff --git a/aiohttp/tracing.py b/aiohttp/tracing.py index 3d7fa0f76a..0e118a3997 100644 --- a/aiohttp/tracing.py +++ b/aiohttp/tracing.py @@ -46,8 +46,7 @@ def __call__( class TraceConfig: - """First-class used to trace requests launched via ClientSession - objects.""" + """First-class used to trace requests launched via ClientSession objects.""" def __init__( self, trace_config_ctx_factory: Type[SimpleNamespace] = SimpleNamespace @@ -336,8 +335,11 @@ class TraceRequestHeadersSentParams: class Trace: - """Internal class used to keep together the main dependencies used - at the moment of send a signal.""" + """Internal dependency holder class. + + Used to keep together the main dependencies used + at the moment of send a signal. + """ def __init__( self, diff --git a/aiohttp/web_middlewares.py b/aiohttp/web_middlewares.py index be3cff498b..fabcc449a2 100644 --- a/aiohttp/web_middlewares.py +++ b/aiohttp/web_middlewares.py @@ -43,12 +43,11 @@ def normalize_path_middleware( append_slash: bool = True, remove_slash: bool = False, merge_slashes: bool = True, - redirect_class: Type[_HTTPMove] = HTTPPermanentRedirect + redirect_class: Type[_HTTPMove] = HTTPPermanentRedirect, ) -> _Middleware: - """ - Middleware factory which produces a middleware that normalizes - the path of a request. By normalizing it means: + """Factory for producing a middleware that normalizes the path of a request. + Normalizing means: - Add or remove a trailing slash to the path. - Double slashes are replaced by one. @@ -74,7 +73,6 @@ def normalize_path_middleware( If merge_slashes is True, merge multiple consecutive slashes in the path into one. """ - correct_configuration = not (append_slash and remove_slash) assert correct_configuration, "Cannot both remove and append slash" diff --git a/aiohttp/web_protocol.py b/aiohttp/web_protocol.py index d008b9f729..ad0c0498e3 100644 --- a/aiohttp/web_protocol.py +++ b/aiohttp/web_protocol.py @@ -237,9 +237,11 @@ def keepalive_timeout(self) -> float: return self._keepalive_timeout async def shutdown(self, timeout: Optional[float] = 15.0) -> None: - """Worker process is about to exit, we need cleanup everything and - stop accepting requests. It is especially important for keep-alive - connections.""" + """Do worker process exit preparations. + + We need to clean up everything and stop accepting requests. + It is especially important for keep-alive connections. + """ self._force_close = True if self._keepalive_handle is not None: @@ -371,14 +373,17 @@ def keep_alive(self, val: bool) -> None: self._keepalive_handle = None def close(self) -> None: - """Stop accepting new pipelining messages and close - connection when handlers done processing messages""" + """Close connection. + + Stop accepting new pipelining messages and close + connection when handlers done processing messages. + """ self._close = True if self._waiter: self._waiter.cancel() def force_close(self) -> None: - """Force close connection""" + """Forcefully close connection.""" self._force_close = True if self._waiter: self._waiter.cancel() @@ -580,8 +585,9 @@ async def start(self) -> None: async def finish_response( self, request: BaseRequest, resp: StreamResponse, start_time: float ) -> bool: - """ - Prepare the response and write_eof, then log access. This has to + """Prepare the response and write_eof, then log access. + + This has to be called within the context of any exception so the access logger can get exception information. Returns True if the client disconnects prematurely. @@ -623,7 +629,8 @@ def handle_error( """Handle errors. Returns HTTP response with specific status code. Logs additional - information. It always closes current connection.""" + information. It always closes current connection. + """ self.log_exception("Error handling request", exc_info=exc) # some data already got sent, connection is broken diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py index dc810f5de2..b3574cafb3 100644 --- a/aiohttp/web_request.py +++ b/aiohttp/web_request.py @@ -203,9 +203,7 @@ def clone( Creates and returns a new instance of Request object. If no parameters are given, an exact copy is returned. If a parameter is not passed, it will reuse the one from the current request object. - """ - if self._read_bytes: raise RuntimeError("Cannot clone request " "after reading its content") @@ -450,6 +448,7 @@ def path_qs(self) -> str: @reify def raw_path(self) -> str: """The URL including raw *PATH INFO* without the host or scheme. + Warning, the path is unquoted and may contains non valid URL characters E.g., ``/my%2Fpath%7Cwith%21some%25strange%24characters`` diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index 9477526c46..7880ab2d02 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -221,7 +221,6 @@ def set_cookie( Sets new cookie or updates existent with new value. Also updates only those params which are not None. """ - old = self._cookies.get(name) if old is not None and old.coded_value == "": # deleted cookie diff --git a/aiohttp/web_urldispatcher.py b/aiohttp/web_urldispatcher.py index 76ae76151f..73ec4c05d0 100644 --- a/aiohttp/web_urldispatcher.py +++ b/aiohttp/web_urldispatcher.py @@ -130,16 +130,16 @@ def url_for(self, **kwargs: str) -> URL: @abc.abstractmethod # pragma: no branch async def resolve(self, request: Request) -> _Resolve: - """Resolve resource + """Resolve resource. - Return (UrlMappingMatchInfo, allowed_methods) pair.""" + Return (UrlMappingMatchInfo, allowed_methods) pair. + """ @abc.abstractmethod def add_prefix(self, prefix: str) -> None: """Add a prefix to processed URLs. Required for subapplications support. - """ @abc.abstractmethod @@ -1135,15 +1135,11 @@ def add_static( return resource def add_head(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """ - Shortcut for add_route with method HEAD - """ + """Shortcut for add_route with method HEAD.""" return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs) def add_options(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """ - Shortcut for add_route with method OPTIONS - """ + """Shortcut for add_route with method OPTIONS.""" return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs) def add_get( @@ -1155,9 +1151,10 @@ def add_get( allow_head: bool = True, **kwargs: Any, ) -> AbstractRoute: - """ - Shortcut for add_route with method GET, if allow_head is true another - route is added allowing head requests to the same endpoint + """Shortcut for add_route with method GET. + + If allow_head is true, another + route is added allowing head requests to the same endpoint. """ resource = self.add_resource(path, name=name) if allow_head: @@ -1165,35 +1162,25 @@ def add_get( return resource.add_route(hdrs.METH_GET, handler, **kwargs) def add_post(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """ - Shortcut for add_route with method POST - """ + """Shortcut for add_route with method POST.""" return self.add_route(hdrs.METH_POST, path, handler, **kwargs) def add_put(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """ - Shortcut for add_route with method PUT - """ + """Shortcut for add_route with method PUT.""" return self.add_route(hdrs.METH_PUT, path, handler, **kwargs) def add_patch(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """ - Shortcut for add_route with method PATCH - """ + """Shortcut for add_route with method PATCH.""" return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs) def add_delete(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """ - Shortcut for add_route with method DELETE - """ + """Shortcut for add_route with method DELETE.""" return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs) def add_view( self, path: str, handler: Type[AbstractView], **kwargs: Any ) -> AbstractRoute: - """ - Shortcut for add_route with ANY methods for a class-based view - """ + """Shortcut for add_route with ANY methods for a class-based view.""" return self.add_route(hdrs.METH_ANY, path, handler, **kwargs) def freeze(self) -> None: diff --git a/docs/spelling_wordlist.txt b/docs/spelling_wordlist.txt index 5f13134973..565a07a6d7 100644 --- a/docs/spelling_wordlist.txt +++ b/docs/spelling_wordlist.txt @@ -152,6 +152,7 @@ dict django dns docstring +docstrings elasticsearch encodings env diff --git a/examples/web_classview.py b/examples/web_classview.py index a6d3e435ac..1f1afdae47 100755 --- a/examples/web_classview.py +++ b/examples/web_classview.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -"""Example for aiohttp.web class based views -""" +"""Example for aiohttp.web class based views.""" import functools diff --git a/examples/web_cookies.py b/examples/web_cookies.py index 7b4743699f..c028d19b55 100755 --- a/examples/web_cookies.py +++ b/examples/web_cookies.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -"""Example for aiohttp.web basic server with cookies. -""" +"""Example for aiohttp.web basic server with cookies.""" from pprint import pformat from typing import NoReturn diff --git a/examples/web_rewrite_headers_middleware.py b/examples/web_rewrite_headers_middleware.py index 4e3578116e..15e985e14d 100755 --- a/examples/web_rewrite_headers_middleware.py +++ b/examples/web_rewrite_headers_middleware.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 -""" -Example for rewriting response headers by middleware. -""" +"""Example for rewriting response headers by middleware.""" + from aiohttp import web from aiohttp.typedefs import Handler diff --git a/examples/web_srv.py b/examples/web_srv.py index b572326a3a..4d0e7c4697 100755 --- a/examples/web_srv.py +++ b/examples/web_srv.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -"""Example for aiohttp.web basic server -""" +"""Example for aiohttp.web basic server.""" import textwrap diff --git a/examples/web_srv_route_deco.py b/examples/web_srv_route_deco.py index 332990362c..4e1769d192 100644 --- a/examples/web_srv_route_deco.py +++ b/examples/web_srv_route_deco.py @@ -1,7 +1,5 @@ #!/usr/bin/env python3 -"""Example for aiohttp.web basic server -with decorator definition for routes -""" +"""Example for aiohttp.web basic server with decorator definition for routes.""" import textwrap diff --git a/examples/web_srv_route_table.py b/examples/web_srv_route_table.py index f53142adad..24815b237b 100644 --- a/examples/web_srv_route_table.py +++ b/examples/web_srv_route_table.py @@ -1,7 +1,5 @@ #!/usr/bin/env python3 -"""Example for aiohttp.web basic server -with table definition for routes -""" +"""Example for aiohttp.web basic server with table definition for routes.""" import textwrap diff --git a/examples/web_ws.py b/examples/web_ws.py index 970f1506be..f6c0593333 100755 --- a/examples/web_ws.py +++ b/examples/web_ws.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -"""Example for aiohttp.web websocket server -""" +"""Example for aiohttp.web websocket server.""" import os diff --git a/setup.cfg b/setup.cfg index 7ef2ebb218..4d8173815d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -84,7 +84,8 @@ max-line-length=79 zip_ok = false [flake8] -ignore = N801,N802,N803,E203,E226,E305,W504,E252,E301,E302,E704,W503,W504,F811 +# TODO: don't disable D*, fix up issues instead +ignore = N801,N802,N803,E203,E226,E305,W504,E252,E301,E302,E704,W503,W504,F811,D1,D4 max-line-length = 88 [isort] diff --git a/tests/conftest.py b/tests/conftest.py index 33f9bc7376..e57932837d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -26,9 +26,8 @@ @pytest.fixture def shorttmpdir(): - """Provides a temporary directory with a shorter file system path than the - tmpdir fixture. - """ + # Provides a temporary directory with a shorter file system path than the + # tmpdir fixture. tmpdir = pathlib.Path(tempfile.mkdtemp()) yield tmpdir # str(tmpdir) is required, Python 3.5 doesn't have __fspath__ diff --git a/tests/test___all__.py b/tests/test___all__.py index d5e6445f9c..6c7d855e59 100644 --- a/tests/test___all__.py +++ b/tests/test___all__.py @@ -2,9 +2,7 @@ def test___all__(pytester: Any) -> None: - """ - See https://github.com/aio-libs/aiohttp/issues/6197 - """ + """See https://github.com/aio-libs/aiohttp/issues/6197""" pytester.makepyfile( test_a=""" from aiohttp import * diff --git a/tests/test_http_parser.py b/tests/test_http_parser.py index 2ec307c2fb..23e1127c44 100644 --- a/tests/test_http_parser.py +++ b/tests/test_http_parser.py @@ -991,9 +991,8 @@ async def test_http_payload_parser_deflate(self, stream) -> None: assert b"data" == b"".join(d for d, _ in out._buffer) assert out.is_eof() - async def test_http_payload_parser_deflate_no_hdrs(self, stream) -> None: - """Tests incorrectly formed data (no zlib headers)""" - + async def test_http_payload_parser_deflate_no_hdrs(self, stream: Any) -> None: + """Tests incorrectly formed data (no zlib headers).""" # c=compressobj(wbits=-15); b''.join([c.compress(b'data'), c.flush()]) COMPRESSED = b"KI,I\x04\x00" diff --git a/tests/test_web_exceptions.py b/tests/test_web_exceptions.py index ab50c47aca..80932c8468 100644 --- a/tests/test_web_exceptions.py +++ b/tests/test_web_exceptions.py @@ -235,9 +235,7 @@ async def show(request): def test_unicode_text_body_unauthorized() -> None: - """ - Test that HTTPUnauthorized can be initialized with a string. - """ + """Test that HTTPUnauthorized can be initialized with a string.""" with pytest.warns( DeprecationWarning, match="body argument is deprecated for http web exceptions" ): diff --git a/tests/test_web_urldispatcher.py b/tests/test_web_urldispatcher.py index d4cdf39774..f24f451e9a 100644 --- a/tests/test_web_urldispatcher.py +++ b/tests/test_web_urldispatcher.py @@ -20,6 +20,7 @@ def tmp_dir_path(request): """ Give a path for a temporary directory + The directory is destroyed at the end of the test. """ # Temporary directory. @@ -195,10 +196,7 @@ async def handler(request): async def test_handler_metadata_persistence() -> None: - """ - Tests accessing metadata of a handler after registering it on the app - router. - """ + """Tests accessing metadata of a handler after registering it on the app router.""" app = web.Application() async def async_handler(request):