From bd275ba9fffd4dd18f1a1519de6cb3003cdb01ce Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 07:53:16 -0700 Subject: [PATCH 1/9] Add ruff formatter --- .gitattributes | 5 ++ .pre-commit-config.yaml | 46 ++++--------------- .../expanded/requests_wifi_api_twitter.py | 1 + .../expanded/requests_wifi_api_youtube.py | 1 + pyproject.toml | 6 +++ tests/chunk_test.py | 2 +- tests/chunked_redirect_test.py | 2 +- tests/concurrent_test.py | 2 +- tests/conftest.py | 2 +- tests/header_test.py | 2 +- tests/method_test.py | 2 +- tests/mocket.py | 6 +-- tests/parse_test.py | 2 +- tests/protocol_test.py | 2 +- tests/reuse_test.py | 2 +- 15 files changed, 33 insertions(+), 50 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d54c593 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +* text eol=lf diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7b20fd7..0981ef3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,47 +1,19 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio PettenΓ² +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: - - repo: https://github.com/python/black - rev: 24.2.0 - hooks: - - id: black - - repo: https://github.com/PyCQA/isort - rev: 5.13.2 - hooks: - - id: isort - args: ["--profile", "black", "--filter-files"] - - repo: https://github.com/fsfe/reuse-tool - rev: v1.1.2 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.17.4 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 + hooks: + - id: ruff-format + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name,protected-access,redefined-outer-name + - id: reuse diff --git a/examples/wifi/expanded/requests_wifi_api_twitter.py b/examples/wifi/expanded/requests_wifi_api_twitter.py index 4dcdfa6..062fb43 100644 --- a/examples/wifi/expanded/requests_wifi_api_twitter.py +++ b/examples/wifi/expanded/requests_wifi_api_twitter.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.0 """DJDevon3 Adafruit Feather ESP32-S2 Twitter_API_Example""" + import gc import json import os diff --git a/examples/wifi/expanded/requests_wifi_api_youtube.py b/examples/wifi/expanded/requests_wifi_api_youtube.py index e9bc6a2..8c14a19 100644 --- a/examples/wifi/expanded/requests_wifi_api_youtube.py +++ b/examples/wifi/expanded/requests_wifi_api_youtube.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.0 """DJDevon3 Adafruit Feather ESP32-S2 YouTube_API_Example""" + import gc import json import os diff --git a/pyproject.toml b/pyproject.toml index d9ee51a..be93e38 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,12 @@ classifiers = [ ] dynamic = ["dependencies", "optional-dependencies"] +[tool.ruff] +target-version = "py38" + +[tool.ruff.format] +line-ending = "lf" + [tool.setuptools] py-modules = ["adafruit_requests"] diff --git a/tests/chunk_test.py b/tests/chunk_test.py index ec4606d..f67e44a 100644 --- a/tests/chunk_test.py +++ b/tests/chunk_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Chunk Tests """ +"""Chunk Tests""" from unittest import mock diff --git a/tests/chunked_redirect_test.py b/tests/chunked_redirect_test.py index 69f8b27..706aa4c 100644 --- a/tests/chunked_redirect_test.py +++ b/tests/chunked_redirect_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Redirection Tests """ +"""Redirection Tests""" from unittest import mock diff --git a/tests/concurrent_test.py b/tests/concurrent_test.py index 58c2ade..d24e3c7 100644 --- a/tests/concurrent_test.py +++ b/tests/concurrent_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Concurrent Tests """ +"""Concurrent Tests""" import errno from unittest import mock diff --git a/tests/conftest.py b/tests/conftest.py index 94023cb..25bac4b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" PyTest Setup """ +"""PyTest Setup""" import adafruit_connection_manager import mocket diff --git a/tests/header_test.py b/tests/header_test.py index 8bcb354..e93f5da 100644 --- a/tests/header_test.py +++ b/tests/header_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Header Tests """ +"""Header Tests""" import mocket import pytest diff --git a/tests/method_test.py b/tests/method_test.py index d75e754..09471a3 100644 --- a/tests/method_test.py +++ b/tests/method_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Post Tests """ +"""Post Tests""" from unittest import mock diff --git a/tests/mocket.py b/tests/mocket.py index 3155231..7b19f66 100644 --- a/tests/mocket.py +++ b/tests/mocket.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: Unlicense -""" Mock Socket """ +"""Mock Socket""" from unittest import mock @@ -84,9 +84,7 @@ class SSLContext: # pylint: disable=too-few-public-methods def __init__(self): self.wrap_socket = mock.Mock(side_effect=self._wrap_socket) - def _wrap_socket( - self, sock, server_hostname=None - ): # pylint: disable=no-self-use,unused-argument + def _wrap_socket(self, sock, server_hostname=None): # pylint: disable=no-self-use,unused-argument return sock diff --git a/tests/parse_test.py b/tests/parse_test.py index d9e1a56..8f3c5fe 100644 --- a/tests/parse_test.py +++ b/tests/parse_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Parse Tests """ +"""Parse Tests""" import json diff --git a/tests/protocol_test.py b/tests/protocol_test.py index 4fd7770..2c9ce1f 100644 --- a/tests/protocol_test.py +++ b/tests/protocol_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Protocol Tests """ +"""Protocol Tests""" from unittest import mock diff --git a/tests/reuse_test.py b/tests/reuse_test.py index 0c0e9a5..a7d4607 100644 --- a/tests/reuse_test.py +++ b/tests/reuse_test.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Unlicense -""" Reuse Tests """ +"""Reuse Tests""" from unittest import mock From 004b21058b60c9de2e00fc81c941afdb6068ee68 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 08:08:58 -0700 Subject: [PATCH 2/9] Add ruff isort --- .pre-commit-config.yaml | 2 ++ pyproject.toml | 3 +++ 2 files changed, 5 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0981ef3..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,6 +13,8 @@ repos: rev: v0.3.4 hooks: - id: ruff-format + - id: ruff + args: ["--fix"] - repo: https://github.com/fsfe/reuse-tool rev: v3.0.1 hooks: diff --git a/pyproject.toml b/pyproject.toml index be93e38..7ddf858 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,9 @@ dynamic = ["dependencies", "optional-dependencies"] [tool.ruff] target-version = "py38" +[tool.ruff.lint] +select = ["I"] + [tool.ruff.format] line-ending = "lf" From 00c1bcd97622c54c53bd25acc953e204816116d5 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:13:55 -0700 Subject: [PATCH 3/9] Add ruff lint --- .pylintrc | 399 ------------------ adafruit_requests.py | 11 +- examples/fona/requests_fona_advanced.py | 4 +- examples/fona/requests_fona_simpletest.py | 4 +- ...sts_wifi_adafruit_discord_active_online.py | 1 - .../expanded/requests_wifi_api_discord.py | 1 - .../wifi/expanded/requests_wifi_api_fitbit.py | 1 - .../wifi/expanded/requests_wifi_api_github.py | 1 - .../expanded/requests_wifi_api_mastodon.py | 1 - .../requests_wifi_api_premiereleague.py | 1 - .../wifi/expanded/requests_wifi_api_steam.py | 1 - .../wifi/expanded/requests_wifi_api_twitch.py | 1 - pyproject.toml | 3 +- tests/chunked_redirect_test.py | 2 +- tests/mocket.py | 10 +- tests/reuse_test.py | 2 +- 16 files changed, 15 insertions(+), 428 deletions(-) delete mode 100644 .pylintrc diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index f945e92..0000000 --- a/.pylintrc +++ /dev/null @@ -1,399 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins=pylint.extensions.no_self_use - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=builtins.Exception diff --git a/adafruit_requests.py b/adafruit_requests.py index 9f38502..22edcb0 100644 --- a/adafruit_requests.py +++ b/adafruit_requests.py @@ -72,7 +72,7 @@ def read(self, size: int = -1) -> bytes: def readinto(self, buf: bytearray) -> int: """Read as much as available into buf or until it is full. Returns the number of bytes read into buf.""" - return self._response._readinto(buf) # pylint: disable=protected-access + return self._response._readinto(buf) class OutOfRetries(Exception): @@ -82,8 +82,6 @@ class OutOfRetries(Exception): class Response: """The response from a request, contains all the headers/content""" - # pylint: disable=too-many-instance-attributes - encoding = None def __init__(self, sock: SocketType, session: "Session") -> None: @@ -232,7 +230,6 @@ def close(self) -> None: return if self._session: - # pylint: disable=protected-access self._session._connection_manager.free_socket(self.socket) else: self.socket.close() @@ -405,8 +402,7 @@ def _send_header(self, socket, header, value): self._send_as_bytes(socket, value) self._send(socket, b"\r\n") - # pylint: disable=too-many-arguments - def _send_request( + def _send_request( # noqa: PLR0913 Too many arguments in function definition self, socket: SocketType, host: str, @@ -467,8 +463,7 @@ def _send_request( if data: self._send(socket, bytes(data)) - # pylint: disable=too-many-branches, too-many-statements, unused-argument, too-many-arguments, too-many-locals - def request( + def request( # noqa: PLR0912,PLR0913,PLR0915 Too many branches,Too many arguments in function definition,Too many statements self, method: str, url: str, diff --git a/examples/fona/requests_fona_advanced.py b/examples/fona/requests_fona_advanced.py index 33bc6f0..318f6be 100644 --- a/examples/fona/requests_fona_advanced.py +++ b/examples/fona/requests_fona_advanced.py @@ -10,8 +10,8 @@ import board import busio import digitalio -from adafruit_fona.adafruit_fona import FONA # pylint: disable=unused-import -from adafruit_fona.fona_3g import FONA3G # pylint: disable=unused-import +from adafruit_fona.adafruit_fona import FONA +from adafruit_fona.fona_3g import FONA3G import adafruit_requests diff --git a/examples/fona/requests_fona_simpletest.py b/examples/fona/requests_fona_simpletest.py index 8841d3d..516dc9d 100644 --- a/examples/fona/requests_fona_simpletest.py +++ b/examples/fona/requests_fona_simpletest.py @@ -10,8 +10,8 @@ import board import busio import digitalio -from adafruit_fona.adafruit_fona import FONA # pylint: disable=unused-import -from adafruit_fona.fona_3g import FONA3G # pylint: disable=unused-import +from adafruit_fona.adafruit_fona import FONA +from adafruit_fona.fona_3g import FONA3G import adafruit_requests diff --git a/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py b/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py index dec0e6e..3ebcaf4 100644 --- a/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py +++ b/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Discord Active Online Shields.IO Example""" -# pylint: disable=import-error import os import time diff --git a/examples/wifi/expanded/requests_wifi_api_discord.py b/examples/wifi/expanded/requests_wifi_api_discord.py index 83b8f8f..08ad16c 100644 --- a/examples/wifi/expanded/requests_wifi_api_discord.py +++ b/examples/wifi/expanded/requests_wifi_api_discord.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Discord Web Scrape Example""" -# pylint: disable=import-error import os import time diff --git a/examples/wifi/expanded/requests_wifi_api_fitbit.py b/examples/wifi/expanded/requests_wifi_api_fitbit.py index 802995c..b5f45b2 100644 --- a/examples/wifi/expanded/requests_wifi_api_fitbit.py +++ b/examples/wifi/expanded/requests_wifi_api_fitbit.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Fitbit API Example""" -# pylint: disable=import-error, disable=no-member import os import time diff --git a/examples/wifi/expanded/requests_wifi_api_github.py b/examples/wifi/expanded/requests_wifi_api_github.py index 6fbe8fe..e045299 100644 --- a/examples/wifi/expanded/requests_wifi_api_github.py +++ b/examples/wifi/expanded/requests_wifi_api_github.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Github API Example""" -# pylint: disable=import-error import os import time diff --git a/examples/wifi/expanded/requests_wifi_api_mastodon.py b/examples/wifi/expanded/requests_wifi_api_mastodon.py index f6bce9f..fd4266e 100644 --- a/examples/wifi/expanded/requests_wifi_api_mastodon.py +++ b/examples/wifi/expanded/requests_wifi_api_mastodon.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Mastodon API Example""" -# pylint: disable=import-error import os import time diff --git a/examples/wifi/expanded/requests_wifi_api_premiereleague.py b/examples/wifi/expanded/requests_wifi_api_premiereleague.py index 0a2e607..88524e9 100644 --- a/examples/wifi/expanded/requests_wifi_api_premiereleague.py +++ b/examples/wifi/expanded/requests_wifi_api_premiereleague.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Premiere League Total Players API Example""" -# pylint: disable=import-error import os import time diff --git a/examples/wifi/expanded/requests_wifi_api_steam.py b/examples/wifi/expanded/requests_wifi_api_steam.py index a05d6c7..fb1f7bd 100644 --- a/examples/wifi/expanded/requests_wifi_api_steam.py +++ b/examples/wifi/expanded/requests_wifi_api_steam.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Steam API Get Owned Games Example""" -# pylint: disable=import-error import os import time diff --git a/examples/wifi/expanded/requests_wifi_api_twitch.py b/examples/wifi/expanded/requests_wifi_api_twitch.py index 8e15098..1f02e5c 100644 --- a/examples/wifi/expanded/requests_wifi_api_twitch.py +++ b/examples/wifi/expanded/requests_wifi_api_twitch.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT # Coded for Circuit Python 8.2.x """Twitch API Example""" -# pylint: disable=import-error import os import time diff --git a/pyproject.toml b/pyproject.toml index 7ddf858..99d4775 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,8 @@ dynamic = ["dependencies", "optional-dependencies"] target-version = "py38" [tool.ruff.lint] -select = ["I"] +select = ["I", "PL"] +ignore = ["PLR2004"] [tool.ruff.format] line-ending = "lf" diff --git a/tests/chunked_redirect_test.py b/tests/chunked_redirect_test.py index 706aa4c..0990acb 100644 --- a/tests/chunked_redirect_test.py +++ b/tests/chunked_redirect_test.py @@ -113,7 +113,7 @@ ) -class MocketRecvInto(mocket.Mocket): # pylint: disable=too-few-public-methods +class MocketRecvInto(mocket.Mocket): """A special Mocket to cap the number of bytes returned from recv_into()""" def __init__(self, response): diff --git a/tests/mocket.py b/tests/mocket.py index 7b19f66..98f2de7 100644 --- a/tests/mocket.py +++ b/tests/mocket.py @@ -19,19 +19,18 @@ MOCK_RESPONSE = b"HTTP/1.0 200 OK\r\nContent-Length: 70\r\n\r\n" + MOCK_RESPONSE_TEXT -class MocketPool: # pylint: disable=too-few-public-methods +class MocketPool: """Mock SocketPool""" SOCK_STREAM = 0 - # pylint: disable=unused-argument def __init__(self, radio=None): self.getaddrinfo = mock.Mock() self.getaddrinfo.return_value = ((None, None, None, None, (MOCK_POOL_IP, 80)),) self.socket = mock.Mock() -class Mocket: # pylint: disable=too-few-public-methods +class Mocket: """Mock Socket""" def __init__(self, response=MOCK_RESPONSE): @@ -78,17 +77,16 @@ def _recv_into(self, buf, nbytes=0): return read -class SSLContext: # pylint: disable=too-few-public-methods +class SSLContext: """Mock SSL Context""" def __init__(self): self.wrap_socket = mock.Mock(side_effect=self._wrap_socket) - def _wrap_socket(self, sock, server_hostname=None): # pylint: disable=no-self-use,unused-argument + def _wrap_socket(self, sock, server_hostname=None): return sock -# pylint: disable=too-few-public-methods class MockRadio: class Radio: pass diff --git a/tests/reuse_test.py b/tests/reuse_test.py index a7d4607..9229626 100644 --- a/tests/reuse_test.py +++ b/tests/reuse_test.py @@ -106,7 +106,7 @@ def test_get_twice_after_second(pool, requests_ssl): pool.socket.assert_called_once() with pytest.raises(RuntimeError) as context: - result = response.text # pylint: disable=unused-variable + result = response.text assert "Newer Response closed this one. Use Responses immediately." in str(context) From 2f8ae41c474fef1968fe82be0466b20016b29cea Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:32:57 -0700 Subject: [PATCH 4/9] Add ruff upgrade --- docs/conf.py | 2 -- examples/wifi/expanded/requests_wifi_api_fitbit.py | 2 +- pyproject.toml | 4 ++-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 4e19482..c9c7548 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT diff --git a/examples/wifi/expanded/requests_wifi_api_fitbit.py b/examples/wifi/expanded/requests_wifi_api_fitbit.py index b5f45b2..bae8e86 100644 --- a/examples/wifi/expanded/requests_wifi_api_fitbit.py +++ b/examples/wifi/expanded/requests_wifi_api_fitbit.py @@ -284,7 +284,7 @@ def time_calc(input_time): ] print(f" | | Fitbit Date: {activities_timestamp}") if MIDNIGHT_DEBUG: - ACTIVITIES_LATEST_HEART_TIME = str("00:05:00") + ACTIVITIES_LATEST_HEART_TIME = "00:05:00" else: ACTIVITIES_LATEST_HEART_TIME = fitbit_json[ "activities-heart-intraday" diff --git a/pyproject.toml b/pyproject.toml index 99d4775..fd96270 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,8 +42,8 @@ dynamic = ["dependencies", "optional-dependencies"] target-version = "py38" [tool.ruff.lint] -select = ["I", "PL"] -ignore = ["PLR2004"] +select = ["I", "PL", "UP"] +ignore = ["PLR2004", "UP028", "UP030", "UP031", "UP032"] [tool.ruff.format] line-ending = "lf" From aa5bd1619277d230125db75ebc1528c1464dc355 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:48:42 -0700 Subject: [PATCH 5/9] remove upgrade UP028 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fd96270..5bc3971 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ target-version = "py38" [tool.ruff.lint] select = ["I", "PL", "UP"] -ignore = ["PLR2004", "UP028", "UP030", "UP031", "UP032"] +ignore = ["PLR2004", "UP030", "UP031", "UP032"] [tool.ruff.format] line-ending = "lf" From f5a8022744fbe2dd3f1328af2c645ff25d4a8c26 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:54:24 -0700 Subject: [PATCH 6/9] remove upgrade UP031 --- examples/wifi/expanded/requests_wifi_api_twitter.py | 2 +- examples/wifi/expanded/requests_wifi_api_youtube.py | 2 +- pyproject.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/wifi/expanded/requests_wifi_api_twitter.py b/examples/wifi/expanded/requests_wifi_api_twitter.py index 062fb43..35e1ea5 100644 --- a/examples/wifi/expanded/requests_wifi_api_twitter.py +++ b/examples/wifi/expanded/requests_wifi_api_twitter.py @@ -110,7 +110,7 @@ print("Monotonic: ", time.monotonic()) print("\nFinished!") - print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion)) + print("Next Update in {} {}".format(int(sleep_int), sleep_time_conversion)) print("===============================") gc.collect() diff --git a/examples/wifi/expanded/requests_wifi_api_youtube.py b/examples/wifi/expanded/requests_wifi_api_youtube.py index 8c14a19..529217d 100644 --- a/examples/wifi/expanded/requests_wifi_api_youtube.py +++ b/examples/wifi/expanded/requests_wifi_api_youtube.py @@ -113,7 +113,7 @@ print("Monotonic: ", time.monotonic()) print("\nFinished!") - print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion)) + print("Next Update in {} {}".format(int(sleep_int), sleep_time_conversion)) print("===============================") gc.collect() diff --git a/pyproject.toml b/pyproject.toml index 5bc3971..0d4b773 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ target-version = "py38" [tool.ruff.lint] select = ["I", "PL", "UP"] -ignore = ["PLR2004", "UP030", "UP031", "UP032"] +ignore = ["PLR2004", "UP030", "UP032"] [tool.ruff.format] line-ending = "lf" From e26ab09fd84cff76f197287b1b7442464922a7da Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 10:02:16 -0700 Subject: [PATCH 7/9] remove upgrade UP032 --- adafruit_requests.py | 2 +- examples/cpython/requests_cpython_simpletest.py | 4 ++-- examples/esp32spi/requests_esp32spi_simpletest.py | 4 ++-- examples/fona/requests_fona_simpletest.py | 4 ++-- .../requests_wifi_api_openskynetwork_private.py | 11 ++--------- .../requests_wifi_api_openskynetwork_private_area.py | 11 ++--------- .../requests_wifi_api_openskynetwork_public.py | 11 ++--------- examples/wifi/expanded/requests_wifi_api_twitter.py | 2 +- examples/wifi/expanded/requests_wifi_api_youtube.py | 2 +- examples/wifi/requests_wifi_simpletest.py | 4 ++-- examples/wiznet5k/requests_wiznet5k_simpletest.py | 4 ++-- pyproject.toml | 2 +- tests/parse_test.py | 10 +++------- 13 files changed, 23 insertions(+), 48 deletions(-) diff --git a/adafruit_requests.py b/adafruit_requests.py index 22edcb0..1a4e6de 100644 --- a/adafruit_requests.py +++ b/adafruit_requests.py @@ -429,7 +429,7 @@ def _send_request( # noqa: PLR0913 Too many arguments in function definition content_type_header = "application/x-www-form-urlencoded" _post_data = "" for k in data: - _post_data = "{}&{}={}".format(_post_data, k, data[k]) + _post_data = f"{_post_data}&{k}={data[k]}" # remove first "&" from concatenation data = _post_data[1:] diff --git a/examples/cpython/requests_cpython_simpletest.py b/examples/cpython/requests_cpython_simpletest.py index 70bdfde..7ab318a 100644 --- a/examples/cpython/requests_cpython_simpletest.py +++ b/examples/cpython/requests_cpython_simpletest.py @@ -30,7 +30,7 @@ response.close() data = "31F" -print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) +print(f"POSTing data to {JSON_POST_URL}: {data}") response = requests.post(JSON_POST_URL, data=data) print("-" * 40) @@ -41,7 +41,7 @@ response.close() json_data = {"Date": "July 25, 2019"} -print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) +print(f"POSTing data to {JSON_POST_URL}: {json_data}") response = requests.post(JSON_POST_URL, json=json_data) print("-" * 40) diff --git a/examples/esp32spi/requests_esp32spi_simpletest.py b/examples/esp32spi/requests_esp32spi_simpletest.py index 3ace026..2b7ef94 100644 --- a/examples/esp32spi/requests_esp32spi_simpletest.py +++ b/examples/esp32spi/requests_esp32spi_simpletest.py @@ -68,7 +68,7 @@ response.close() data = "31F" -print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) +print(f"POSTing data to {JSON_POST_URL}: {data}") response = requests.post(JSON_POST_URL, data=data) print("-" * 40) @@ -79,7 +79,7 @@ response.close() json_data = {"Date": "July 25, 2019"} -print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) +print(f"POSTing data to {JSON_POST_URL}: {json_data}") response = requests.post(JSON_POST_URL, json=json_data) print("-" * 40) diff --git a/examples/fona/requests_fona_simpletest.py b/examples/fona/requests_fona_simpletest.py index 516dc9d..2294f40 100644 --- a/examples/fona/requests_fona_simpletest.py +++ b/examples/fona/requests_fona_simpletest.py @@ -69,7 +69,7 @@ response.close() data = "31F" -print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) +print(f"POSTing data to {JSON_POST_URL}: {data}") response = requests.post(JSON_POST_URL, data=data) print("-" * 40) @@ -80,7 +80,7 @@ response.close() json_data = {"Date": "July 25, 2019"} -print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) +print(f"POSTing data to {JSON_POST_URL}: {json_data}") response = requests.post(JSON_POST_URL, json=json_data) print("-" * 40) diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py index 486a4de..4ce0581 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py @@ -76,14 +76,7 @@ def time_calc(input_time): # input_time in seconds def _format_datetime(datetime): - return "{:02}/{:02}/{} {:02}:{:02}:{:02}".format( - datetime.tm_mon, - datetime.tm_mday, - datetime.tm_year, - datetime.tm_hour, - datetime.tm_min, - datetime.tm_sec, - ) + return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" # Connect to Wi-Fi @@ -124,7 +117,7 @@ def _format_datetime(datetime): print("Current Unix Time: ", osn_flight) current_struct_time = time.localtime(osn_flight) - current_date = "{}".format(_format_datetime(current_struct_time)) + current_date = f"{_format_datetime(current_struct_time)}" print(f"Unix to Readable Time: {current_date}") # Current flight data for single callsign (right now) diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py index 8cd08a2..d89f2f3 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py @@ -91,14 +91,7 @@ def time_calc(input_time): # input_time in seconds def _format_datetime(datetime): - return "{:02}/{:02}/{} {:02}:{:02}:{:02}".format( - datetime.tm_mon, - datetime.tm_mday, - datetime.tm_year, - datetime.tm_hour, - datetime.tm_min, - datetime.tm_sec, - ) + return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" # Connect to Wi-Fi @@ -139,7 +132,7 @@ def _format_datetime(datetime): print("Current Unix Time: ", osn_flight) current_struct_time = time.localtime(osn_flight) - current_date = "{}".format(_format_datetime(current_struct_time)) + current_date = f"{_format_datetime(current_struct_time)}" print(f"Unix to Readable Time: {current_date}") # Current flight data for single callsign (right now) diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py index 5bcd69b..4038694 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py @@ -55,14 +55,7 @@ def time_calc(input_time): # input_time in seconds def _format_datetime(datetime): - return "{:02}/{:02}/{} {:02}:{:02}:{:02}".format( - datetime.tm_mon, - datetime.tm_mday, - datetime.tm_year, - datetime.tm_hour, - datetime.tm_min, - datetime.tm_sec, - ) + return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" # Connect to Wi-Fi @@ -104,7 +97,7 @@ def _format_datetime(datetime): print("Current Unix Time: ", osn_flight) current_struct_time = time.localtime(osn_flight) - current_date = "{}".format(_format_datetime(current_struct_time)) + current_date = f"{_format_datetime(current_struct_time)}" print(f"Unix to Readable Time: {current_date}") osn_single_flight_data = osn_json["states"] diff --git a/examples/wifi/expanded/requests_wifi_api_twitter.py b/examples/wifi/expanded/requests_wifi_api_twitter.py index 35e1ea5..431279a 100644 --- a/examples/wifi/expanded/requests_wifi_api_twitter.py +++ b/examples/wifi/expanded/requests_wifi_api_twitter.py @@ -110,7 +110,7 @@ print("Monotonic: ", time.monotonic()) print("\nFinished!") - print("Next Update in {} {}".format(int(sleep_int), sleep_time_conversion)) + print(f"Next Update in {int(sleep_int)} {sleep_time_conversion}") print("===============================") gc.collect() diff --git a/examples/wifi/expanded/requests_wifi_api_youtube.py b/examples/wifi/expanded/requests_wifi_api_youtube.py index 529217d..8400382 100644 --- a/examples/wifi/expanded/requests_wifi_api_youtube.py +++ b/examples/wifi/expanded/requests_wifi_api_youtube.py @@ -113,7 +113,7 @@ print("Monotonic: ", time.monotonic()) print("\nFinished!") - print("Next Update in {} {}".format(int(sleep_int), sleep_time_conversion)) + print(f"Next Update in {int(sleep_int)} {sleep_time_conversion}") print("===============================") gc.collect() diff --git a/examples/wifi/requests_wifi_simpletest.py b/examples/wifi/requests_wifi_simpletest.py index 35b835a..055551b 100644 --- a/examples/wifi/requests_wifi_simpletest.py +++ b/examples/wifi/requests_wifi_simpletest.py @@ -50,7 +50,7 @@ response.close() data = "31F" -print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) +print(f"POSTing data to {JSON_POST_URL}: {data}") response = requests.post(JSON_POST_URL, data=data) print("-" * 40) @@ -61,7 +61,7 @@ response.close() json_data = {"Date": "July 25, 2019"} -print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) +print(f"POSTing data to {JSON_POST_URL}: {json_data}") response = requests.post(JSON_POST_URL, json=json_data) print("-" * 40) diff --git a/examples/wiznet5k/requests_wiznet5k_simpletest.py b/examples/wiznet5k/requests_wiznet5k_simpletest.py index e35b5ab..357a77a 100644 --- a/examples/wiznet5k/requests_wiznet5k_simpletest.py +++ b/examples/wiznet5k/requests_wiznet5k_simpletest.py @@ -41,7 +41,7 @@ response.close() data = "31F" -print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) +print(f"POSTing data to {JSON_POST_URL}: {data}") response = requests.post(JSON_POST_URL, data=data) print("-" * 40) @@ -52,7 +52,7 @@ response.close() json_data = {"Date": "July 25, 2019"} -print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) +print(f"POSTing data to {JSON_POST_URL}: {json_data}") response = requests.post(JSON_POST_URL, json=json_data) print("-" * 40) diff --git a/pyproject.toml b/pyproject.toml index 0d4b773..291a9cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ target-version = "py38" [tool.ruff.lint] select = ["I", "PL", "UP"] -ignore = ["PLR2004", "UP030", "UP032"] +ignore = ["PLR2004", "UP030"] [tool.ruff.format] line-ending = "lf" diff --git a/tests/parse_test.py b/tests/parse_test.py index 8f3c5fe..7cff9f5 100644 --- a/tests/parse_test.py +++ b/tests/parse_test.py @@ -15,13 +15,9 @@ # Padding here tests the case where a header line is exactly 32 bytes buffered by # aligning the Content-Type header after it. HEADERS = ( - ( - "HTTP/1.0 200 OK\r\npadding: 000\r\n" - "Content-Type: application/json\r\nContent-Length: {}\r\n\r\n" - ) - .format(len(ENCODED)) - .encode("utf-8") -) + "HTTP/1.0 200 OK\r\npadding: 000\r\n" + f"Content-Type: application/json\r\nContent-Length: {len(ENCODED)}\r\n\r\n" +).encode() def test_json(pool): From 69406bb10947852370255b03b95d9a7b56123093 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sun, 24 Mar 2024 07:43:15 -0700 Subject: [PATCH 8/9] Update README badge --- README.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.rst b/README.rst index a04f450..4e73438 100755 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_Requests/actions/ :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff A requests-like library for HTTP commands. From edef59ac296804240a35ff551763ad601865c2c1 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 29 Jul 2024 09:26:58 -0500 Subject: [PATCH 9/9] merge main, resolve conflicts --- adafruit_requests.py | 24 ++--- docs/conf.py | 4 +- .../expanded/requests_wifi_api_discord.py | 4 +- .../wifi/expanded/requests_wifi_api_fitbit.py | 21 ++-- .../wifi/expanded/requests_wifi_api_github.py | 4 +- .../expanded/requests_wifi_api_mastodon.py | 6 +- ...equests_wifi_api_openskynetwork_private.py | 9 +- ...ts_wifi_api_openskynetwork_private_area.py | 9 +- ...requests_wifi_api_openskynetwork_public.py | 5 +- .../wifi/expanded/requests_wifi_api_twitch.py | 5 +- .../requests_wifi_file_upload_image.png | Bin 7615 -> 7614 bytes .../requests_wifi_multiple_cookies.py | 2 +- .../requests_wifi_rachio_irrigation.py | 10 +- .../expanded/requests_wifi_status_codes.py | 22 ++-- examples/wifi/requests_wifi_advanced.py | 2 +- examples/wifi/requests_wifi_simpletest.py | 2 +- ruff.toml | 99 ++++++++++++++++++ tests/chunk_test.py | 6 +- tests/chunked_redirect_test.py | 36 ++----- tests/conftest.py | 4 +- tests/files/green_red.png | Bin 125 -> 124 bytes tests/files/red_green.png | Bin 123 -> 122 bytes tests/files_test.py | 12 +-- tests/header_test.py | 4 +- tests/mocket.py | 4 +- tests/reuse_test.py | 2 +- 26 files changed, 162 insertions(+), 134 deletions(-) create mode 100644 ruff.toml diff --git a/adafruit_requests.py b/adafruit_requests.py index 032d69e..f0c9e65 100644 --- a/adafruit_requests.py +++ b/adafruit_requests.py @@ -191,9 +191,7 @@ def _read_from_buffer( def _readinto(self, buf: bytearray) -> int: if not self.socket: - raise RuntimeError( - "Newer Response closed this one. Use Responses immediately." - ) + raise RuntimeError("Newer Response closed this one. Use Responses immediately.") if not self._remaining: # Consume the chunk header if need be. @@ -280,10 +278,7 @@ def _parse_headers(self) -> None: def _validate_not_gzip(self) -> None: """gzip encoding is not supported. Raise an exception if found.""" - if ( - "content-encoding" in self.headers - and self.headers["content-encoding"] == "gzip" - ): + if "content-encoding" in self.headers and self.headers["content-encoding"] == "gzip": raise ValueError( "Content-encoding is gzip, data cannot be accessed as json or text. " "Use content property to access raw bytes." @@ -394,9 +389,7 @@ def _build_boundary_data(self, files: dict): # pylint: disable=too-many-locals if len(field_values) >= 4: file_headers = field_values[3] for file_header_key, file_header_value in file_headers.items(): - boundary_objects.append( - f"{file_header_key}: {file_header_value}\r\n" - ) + boundary_objects.append(f"{file_header_key}: {file_header_value}\r\n") boundary_objects.append("\r\n") if hasattr(file_handle, "read"): @@ -500,7 +493,8 @@ def _send_header(self, socket, header, value): self._send_as_bytes(socket, value) self._send(socket, b"\r\n") - def _send_request( # noqa: PLR0913 Too many arguments in function definition + # noqa: PLR0912 Too many branches + def _send_request( # noqa: PLR0913,PLR0912 Too many arguments in function definition,Too many branches self, socket: SocketType, host: str, @@ -543,9 +537,7 @@ def _send_request( # noqa: PLR0913 Too many arguments in function definition data_is_file = False boundary_objects = None if files and isinstance(files, dict): - boundary_string, content_length, boundary_objects = ( - self._build_boundary_data(files) - ) + boundary_string, content_length, boundary_objects = self._build_boundary_data(files) content_type_header = f"multipart/form-data; boundary={boundary_string}" elif data and hasattr(data, "read"): data_is_file = True @@ -644,9 +636,7 @@ def request( # noqa: PLR0912,PLR0913,PLR0915 Too many branches,Too many argumen ) ok = True try: - self._send_request( - socket, host, method, path, headers, data, json, files - ) + self._send_request(socket, host, method, path, headers, data, json, files) except OSError as exc: last_exc = exc ok = False diff --git a/docs/conf.py b/docs/conf.py index c9c7548..f3a8700 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -46,9 +46,7 @@ creation_year = "2019" current_year = str(datetime.datetime.now().year) year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year + current_year if current_year == creation_year else creation_year + " - " + current_year ) copyright = year_duration + " ladyada" author = "ladyada" diff --git a/examples/wifi/expanded/requests_wifi_api_discord.py b/examples/wifi/expanded/requests_wifi_api_discord.py index 19c2522..f1b50bc 100644 --- a/examples/wifi/expanded/requests_wifi_api_discord.py +++ b/examples/wifi/expanded/requests_wifi_api_discord.py @@ -69,9 +69,7 @@ def time_calc(input_time): DEBUG_RESPONSE = False try: - with requests.get( - url=DISCORD_SOURCE, headers=DISCORD_HEADER - ) as discord_response: + with requests.get(url=DISCORD_SOURCE, headers=DISCORD_HEADER) as discord_response: discord_json = discord_response.json() except ConnectionError as e: print(f"Connection Error: {e}") diff --git a/examples/wifi/expanded/requests_wifi_api_fitbit.py b/examples/wifi/expanded/requests_wifi_api_fitbit.py index 193fe62..ee26a0a 100644 --- a/examples/wifi/expanded/requests_wifi_api_fitbit.py +++ b/examples/wifi/expanded/requests_wifi_api_fitbit.py @@ -30,9 +30,7 @@ password = os.getenv("CIRCUITPY_WIFI_PASSWORD") Fitbit_ClientID = os.getenv("FITBIT_CLIENTID") Fitbit_Token = os.getenv("FITBIT_ACCESS_TOKEN") -Fitbit_First_Refresh_Token = os.getenv( - "FITBIT_FIRST_REFRESH_TOKEN" -) # overides nvm first run only +Fitbit_First_Refresh_Token = os.getenv("FITBIT_FIRST_REFRESH_TOKEN") # overides nvm first run only Fitbit_UserID = os.getenv("FITBIT_USERID") # Set debug to True for full INTRADAY JSON response. @@ -167,8 +165,7 @@ def time_calc(input_time): print(" | Requesting authorization for next token") if DEBUG: print( - "FULL REFRESH TOKEN POST:" - + f"{FITBIT_OAUTH_TOKEN}{FITBIT_OAUTH_REFRESH_TOKEN}" + "FULL REFRESH TOKEN POST:" + f"{FITBIT_OAUTH_TOKEN}{FITBIT_OAUTH_REFRESH_TOKEN}" ) print(f"Current Refresh Token: {Refresh_Token}") # TOKEN REFRESH POST @@ -270,24 +267,20 @@ def time_calc(input_time): try: # Fitbit's sync to mobile device & server every 15 minutes in chunks. # Pointless to poll their API faster than 15 minute intervals. - activities_heart_value = fitbit_json["activities-heart-intraday"][ - "dataset" - ] + activities_heart_value = fitbit_json["activities-heart-intraday"]["dataset"] if MIDNIGHT_DEBUG: RESPONSE_LENGTH = 0 else: RESPONSE_LENGTH = len(activities_heart_value) if RESPONSE_LENGTH >= 15: - activities_timestamp = fitbit_json["activities-heart"][0][ - "dateTime" - ] + activities_timestamp = fitbit_json["activities-heart"][0]["dateTime"] print(f" | | Fitbit Date: {activities_timestamp}") if MIDNIGHT_DEBUG: ACTIVITIES_LATEST_HEART_TIME = "00:05:00" else: - ACTIVITIES_LATEST_HEART_TIME = fitbit_json[ - "activities-heart-intraday" - ]["dataset"][RESPONSE_LENGTH - 1]["time"] + ACTIVITIES_LATEST_HEART_TIME = fitbit_json["activities-heart-intraday"][ + "dataset" + ][RESPONSE_LENGTH - 1]["time"] print(f" | | Fitbit Time: {ACTIVITIES_LATEST_HEART_TIME[0:-3]}") print(f" | | Today's Logged Pulses: {RESPONSE_LENGTH}") diff --git a/examples/wifi/expanded/requests_wifi_api_github.py b/examples/wifi/expanded/requests_wifi_api_github.py index d25b15d..9d6770b 100644 --- a/examples/wifi/expanded/requests_wifi_api_github.py +++ b/examples/wifi/expanded/requests_wifi_api_github.py @@ -61,9 +61,7 @@ def time_calc(input_time): try: print(" | Attempting to GET Github JSON!") try: - with requests.get( - url=GITHUB_SOURCE, headers=GITHUB_HEADER - ) as github_response: + with requests.get(url=GITHUB_SOURCE, headers=GITHUB_HEADER) as github_response: github_json = github_response.json() except ConnectionError as e: print("Connection Error:", e) diff --git a/examples/wifi/expanded/requests_wifi_api_mastodon.py b/examples/wifi/expanded/requests_wifi_api_mastodon.py index 92455e2..bcbf211 100644 --- a/examples/wifi/expanded/requests_wifi_api_mastodon.py +++ b/examples/wifi/expanded/requests_wifi_api_mastodon.py @@ -48,11 +48,7 @@ def time_calc(input_time): # Publicly available data no header required MAST_SOURCE = ( - "https://" - + MASTODON_SERVER - + "/api/v1/accounts/" - + MASTODON_USERID - + "/statuses?limit=1" + "https://" + MASTODON_SERVER + "/api/v1/accounts/" + MASTODON_USERID + "/statuses?limit=1" ) while True: diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py index c8d54b6..0608b30 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py @@ -69,7 +69,10 @@ def time_calc(input_time): def _format_datetime(datetime): - return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" + return ( + f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} " + f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" + ) while True: @@ -87,9 +90,7 @@ def _format_datetime(datetime): print(" | Attempting to GET OpenSky-Network Single Private Flight JSON!") print(" | Website Credentials Required! Allows more daily calls than Public.") try: - with requests.get( - url=OPENSKY_SOURCE, headers=OPENSKY_HEADER - ) as opensky_response: + with requests.get(url=OPENSKY_SOURCE, headers=OPENSKY_HEADER) as opensky_response: opensky_json = opensky_response.json() except ConnectionError as e: print("Connection Error:", e) diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py index 8f2b28f..243c859 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py @@ -83,7 +83,10 @@ def time_calc(input_time): def _format_datetime(datetime): - return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" + return ( + f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} " + f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" + ) while True: @@ -100,9 +103,7 @@ def _format_datetime(datetime): try: print(" | Attempting to GET OpenSky-Network Area Flights JSON!") try: - with requests.get( - url=OPENSKY_SOURCE, headers=OSN_HEADER - ) as opensky_response: + with requests.get(url=OPENSKY_SOURCE, headers=OSN_HEADER) as opensky_response: opensky_json = opensky_response.json() except ConnectionError as e: print("Connection Error:", e) diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py index b07b476..f89f88d 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py @@ -54,7 +54,10 @@ def time_calc(input_time): def _format_datetime(datetime): - return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" + return ( + f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} " + f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}" + ) while True: diff --git a/examples/wifi/expanded/requests_wifi_api_twitch.py b/examples/wifi/expanded/requests_wifi_api_twitch.py index 57f9cdd..15cbcc0 100644 --- a/examples/wifi/expanded/requests_wifi_api_twitch.py +++ b/examples/wifi/expanded/requests_wifi_api_twitch.py @@ -129,10 +129,7 @@ def _format_datetime(datetime): "Client-Id": "" + TWITCH_CID + "", } TWITCH_FOLLOWERS_SOURCE = ( - "https://api.twitch.tv/helix/channels" - + "/followers?" - + "broadcaster_id=" - + TWITCH_UID + "https://api.twitch.tv/helix/channels" + "/followers?" + "broadcaster_id=" + TWITCH_UID ) print(" | Attempting to GET Twitch JSON!") try: diff --git a/examples/wifi/expanded/requests_wifi_file_upload_image.png b/examples/wifi/expanded/requests_wifi_file_upload_image.png index f08a15472271eba34ce6044e276bf3c86887609a..da2d2194b4dc5b413271e5e21462075f1725632b 100644 GIT binary patch delta 13 UcmdmQz0aDZGr-S%BkL|%03|a7^8f$< delta 14 VcmdmIz2BO(Gr-TCcO%O#SpX>C1poj5 diff --git a/examples/wifi/expanded/requests_wifi_multiple_cookies.py b/examples/wifi/expanded/requests_wifi_multiple_cookies.py index cfc0641..21fe9ba 100644 --- a/examples/wifi/expanded/requests_wifi_multiple_cookies.py +++ b/examples/wifi/expanded/requests_wifi_multiple_cookies.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: 2022 Alec Delaney # SPDX-License-Identifier: MIT # Coded for Circuit Python 9.0 -""" Multiple Cookies Example written for MagTag """ +"""Multiple Cookies Example written for MagTag""" import os diff --git a/examples/wifi/expanded/requests_wifi_rachio_irrigation.py b/examples/wifi/expanded/requests_wifi_rachio_irrigation.py index 2b8650d..55a46a1 100644 --- a/examples/wifi/expanded/requests_wifi_rachio_irrigation.py +++ b/examples/wifi/expanded/requests_wifi_rachio_irrigation.py @@ -106,9 +106,7 @@ def _format_datetime(datetime): try: print(" | Attempting to GET Rachio Authorization") try: - with requests.get( - url=RACHIO_SOURCE, headers=RACHIO_HEADER - ) as rachio_response: + with requests.get(url=RACHIO_SOURCE, headers=RACHIO_HEADER) as rachio_response: rachio_json = rachio_response.json() except ConnectionError as e: print("Connection Error:", e) @@ -127,9 +125,7 @@ def _format_datetime(datetime): print(f"Failed to GET data: {e}") time.sleep(60) break - print( - "\nThis script can only continue when a proper APIKey & PersonID is used." - ) + print("\nThis script can only continue when a proper APIKey & PersonID is used.") print("\nFinished!") print("===============================") time.sleep(SLEEP_TIME) @@ -191,7 +187,7 @@ def _format_datetime(datetime): print(f" | | Unix Registration Date: {rachio_createdate}") print(f" | | Unix Timezone Offset: {rachio_timezone_offset}") current_struct_time = time.localtime(local_unix_time) - final_timestamp = "{}".format(_format_datetime(current_struct_time)) + final_timestamp = f"{_format_datetime(current_struct_time)}" print(f" | | Registration Date: {final_timestamp}") rachio_devices = rachio_json["devices"][0]["name"] diff --git a/examples/wifi/expanded/requests_wifi_status_codes.py b/examples/wifi/expanded/requests_wifi_status_codes.py index 036b7bb..a933c28 100644 --- a/examples/wifi/expanded/requests_wifi_status_codes.py +++ b/examples/wifi/expanded/requests_wifi_status_codes.py @@ -3,7 +3,7 @@ # Updated for Circuit Python 9.0 # https://help.openai.com/en/articles/6825453-chatgpt-release-notes # https://chat.openai.com/share/32ef0c5f-ac92-4d36-9d1e-0f91e0c4c574 -""" WiFi Status Codes Example """ +"""WiFi Status Codes Example""" import os import time @@ -27,21 +27,13 @@ def print_http_status(expected_code, actual_code, description): """Returns HTTP status code and description""" if "100" <= actual_code <= "103": - print( - f" | βœ… Status Test Expected: {expected_code} Actual: {actual_code} - {description}" - ) + print(f" | βœ… Status Test Expected: {expected_code} Actual: {actual_code} - {description}") elif "200" == actual_code: - print( - f" | πŸ†— Status Test Expected: {expected_code} Actual: {actual_code} - {description}" - ) + print(f" | πŸ†— Status Test Expected: {expected_code} Actual: {actual_code} - {description}") elif "201" <= actual_code <= "299": - print( - f" | βœ… Status Test Expected: {expected_code} Actual: {actual_code} - {description}" - ) + print(f" | βœ… Status Test Expected: {expected_code} Actual: {actual_code} - {description}") elif "300" <= actual_code <= "600": - print( - f" | ❌ Status Test Expected: {expected_code} Actual: {actual_code} - {description}" - ) + print(f" | ❌ Status Test Expected: {expected_code} Actual: {actual_code} - {description}") else: print( f" | Unknown Response Status Expected: {expected_code} " @@ -138,9 +130,7 @@ def print_http_status(expected_code, actual_code, description): header_status_test_url = STATUS_TEST_URL + current_code with requests.get(header_status_test_url) as response: response_status_code = str(response.status_code) - SORT_STATUS_DESC = http_status_codes.get( - response_status_code, "Unknown Status Code" - ) + SORT_STATUS_DESC = http_status_codes.get(response_status_code, "Unknown Status Code") print_http_status(current_code, response_status_code, SORT_STATUS_DESC) # Rate limit ourselves a little to avoid strain on server diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index bfad6af..bc29df7 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT # Updated for Circuit Python 9.0 -""" WiFi Advanced Example """ +"""WiFi Advanced Example""" import os diff --git a/examples/wifi/requests_wifi_simpletest.py b/examples/wifi/requests_wifi_simpletest.py index 6bce412..ddc70a2 100644 --- a/examples/wifi/requests_wifi_simpletest.py +++ b/examples/wifi/requests_wifi_simpletest.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Updated for Circuit Python 9.0 -""" WiFi Simpletest """ +"""WiFi Simpletest""" import os diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..db37c83 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + +] + +[format] +line-ending = "lf" diff --git a/tests/chunk_test.py b/tests/chunk_test.py index f67e44a..4be0e05 100644 --- a/tests/chunk_test.py +++ b/tests/chunk_test.py @@ -28,11 +28,7 @@ def _chunk(response, split, extra=b""): chunk_size = remaining new_i = i + chunk_size chunked += ( - hex(chunk_size)[2:].encode("ascii") - + extra - + b"\r\n" - + response[i:new_i] - + b"\r\n" + hex(chunk_size)[2:].encode("ascii") + extra + b"\r\n" + response[i:new_i] + b"\r\n" ) i = new_i # The final chunk is zero length. diff --git a/tests/chunked_redirect_test.py b/tests/chunked_redirect_test.py index 0990acb..871dc21 100644 --- a/tests/chunked_redirect_test.py +++ b/tests/chunked_redirect_test.py @@ -27,9 +27,7 @@ b"370cmver1f290kjsnpar5ku2h9g/3llvt5u8njbvat22m9l19db1h4/1656191325000/109226138307867586192/*/" + FILE_REDIRECT ) -RELATIVE_ABSOLUTE_REDIRECT = ( - b"/pub/70cmver1f290kjsnpar5ku2h9g/" + RELATIVE_RELATIVE_REDIRECT -) +RELATIVE_ABSOLUTE_REDIRECT = b"/pub/70cmver1f290kjsnpar5ku2h9g/" + RELATIVE_RELATIVE_REDIRECT ABSOLUTE_ABSOLUTE_REDIRECT = ( b"https://doc-14-2g-sheets.googleusercontent.com" + RELATIVE_ABSOLUTE_REDIRECT ) @@ -137,9 +135,7 @@ def test_chunked_absolute_absolute_redirect(): chunk = _chunk(BODY_REDIRECT, len(BODY_REDIRECT)) chunk2 = _chunk(BODY, len(BODY)) - redirect = HEADERS_REDIRECT.replace( - b"NEW_LOCATION_HERE", ABSOLUTE_ABSOLUTE_REDIRECT - ) + redirect = HEADERS_REDIRECT.replace(b"NEW_LOCATION_HERE", ABSOLUTE_ABSOLUTE_REDIRECT) sock1 = MocketRecvInto(redirect + chunk) sock2 = mocket.Mocket(HEADERS + chunk2) pool.socket.side_effect = (sock1, sock2) @@ -148,9 +144,7 @@ def test_chunked_absolute_absolute_redirect(): response = requests_session.get("https://" + HOST + PATH) sock1.connect.assert_called_once_with((HOST, 443)) - sock2.connect.assert_called_once_with( - ("doc-14-2g-sheets.googleusercontent.com", 443) - ) + sock2.connect.assert_called_once_with(("doc-14-2g-sheets.googleusercontent.com", 443)) sock2.send.assert_has_calls([mock.call(RELATIVE_ABSOLUTE_REDIRECT[1:])]) assert response.text == str(BODY, "utf-8") @@ -162,9 +156,7 @@ def test_chunked_relative_absolute_redirect(): chunk = _chunk(BODY_REDIRECT, len(BODY_REDIRECT)) chunk2 = _chunk(BODY, len(BODY)) - redirect = HEADERS_REDIRECT.replace( - b"NEW_LOCATION_HERE", RELATIVE_ABSOLUTE_REDIRECT - ) + redirect = HEADERS_REDIRECT.replace(b"NEW_LOCATION_HERE", RELATIVE_ABSOLUTE_REDIRECT) sock1 = MocketRecvInto(redirect + chunk) sock2 = mocket.Mocket(HEADERS + chunk2) pool.socket.side_effect = (sock1, sock2) @@ -185,9 +177,7 @@ def test_chunked_relative_relative_redirect(): chunk = _chunk(BODY_REDIRECT, len(BODY_REDIRECT)) chunk2 = _chunk(BODY, len(BODY)) - redirect = HEADERS_REDIRECT.replace( - b"NEW_LOCATION_HERE", RELATIVE_RELATIVE_REDIRECT - ) + redirect = HEADERS_REDIRECT.replace(b"NEW_LOCATION_HERE", RELATIVE_RELATIVE_REDIRECT) sock1 = MocketRecvInto(redirect + chunk) sock2 = mocket.Mocket(HEADERS + chunk2) pool.socket.side_effect = (sock1, sock2) @@ -214,13 +204,9 @@ def test_chunked_relative_relative_redirect_backstep(): backstep = b"../" * remove_paths path_base_parts = PATH_BASE.split("/") # PATH_BASE starts with "/" so skip it and also remove from the count - path_base = ( - "/".join(path_base_parts[1 : len(path_base_parts) - remove_paths - 1]) + "/" - ) + path_base = "/".join(path_base_parts[1 : len(path_base_parts) - remove_paths - 1]) + "/" - redirect = HEADERS_REDIRECT.replace( - b"NEW_LOCATION_HERE", backstep + RELATIVE_RELATIVE_REDIRECT - ) + redirect = HEADERS_REDIRECT.replace(b"NEW_LOCATION_HERE", backstep + RELATIVE_RELATIVE_REDIRECT) sock1 = MocketRecvInto(redirect + chunk) sock2 = mocket.Mocket(HEADERS + chunk2) pool.socket.side_effect = (sock1, sock2) @@ -230,9 +216,7 @@ def test_chunked_relative_relative_redirect_backstep(): sock1.connect.assert_called_once_with((HOST, 443)) sock2.connect.assert_called_once_with(("docs.google.com", 443)) - sock2.send.assert_has_calls( - [mock.call(bytes(path_base, "utf-8") + RELATIVE_RELATIVE_REDIRECT)] - ) + sock2.send.assert_has_calls([mock.call(bytes(path_base, "utf-8") + RELATIVE_RELATIVE_REDIRECT)]) assert response.text == str(BODY, "utf-8") @@ -243,9 +227,7 @@ def test_chunked_allow_redirects_false(): chunk = _chunk(BODY_REDIRECT, len(BODY_REDIRECT)) chunk2 = _chunk(BODY, len(BODY)) - redirect = HEADERS_REDIRECT.replace( - b"NEW_LOCATION_HERE", ABSOLUTE_ABSOLUTE_REDIRECT - ) + redirect = HEADERS_REDIRECT.replace(b"NEW_LOCATION_HERE", ABSOLUTE_ABSOLUTE_REDIRECT) sock1 = MocketRecvInto(redirect + chunk) sock2 = mocket.Mocket(HEADERS + chunk2) pool.socket.side_effect = (sock1, sock2) diff --git a/tests/conftest.py b/tests/conftest.py index 25bac4b..02aa1a6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -28,9 +28,7 @@ def sock(): @pytest.fixture def pool(sock): pool = mocket.MocketPool() - pool.getaddrinfo.return_value = ( - (None, None, None, None, (mocket.MOCK_POOL_IP, 80)), - ) + pool.getaddrinfo.return_value = ((None, None, None, None, (mocket.MOCK_POOL_IP, 80)),) pool.socket.return_value = sock return pool diff --git a/tests/files/green_red.png b/tests/files/green_red.png index 7d8ddb37c20bcff4cbb43154844f21966c74bc44..532c956355bccd356a67877a8e89e6fa76676280 100644 GIT binary patch delta 10 Rcmb=eVd)I;bDzjs0RR);19|`e delta 11 Scmb=aW$g^`bLXANQUL%Kgad~F diff --git a/tests/files/red_green.png b/tests/files/red_green.png index 6b4fc3052e22c6f90c25bcc4385ac3fa9b36d2ba..9d3bdb6f2b567ef4e3c5d98e98dc8814a7392491 100644 GIT binary patch delta 10 Rcmb=fV(AR