From edef59ac296804240a35ff551763ad601865c2c1 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 29 Jul 2024 09:26:58 -0500 Subject: [PATCH] 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