From 273093790dd0725fbb161031f4dfc77414a6ada9 Mon Sep 17 00:00:00 2001 From: 4EYES44 Date: Sat, 17 Oct 2026 10:33:46 +0300 Subject: [PATCH 1/2] Download the Automation Build when no Extension Directory is supplied. Users should not have to fetch chromium_automation.zip themselves, and the Nopecha Manifest Config should turn on every captcha type instead of leaving solver flags at the zip defaults. Co-authored-by: Cursor --- README.md | 15 +- nopecha_extension/patcher.py | 159 ++++++++++++++++++-- tests/test_automation_build_download.py | 192 ++++++++++++++++++++++++ tests/test_automation_manifest_key.py | 48 +++++- 4 files changed, 394 insertions(+), 20 deletions(-) create mode 100644 tests/test_automation_build_download.py diff --git a/README.md b/README.md index 657d5d5..47bee30 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ Write a NopeCHA API key into an unpacked [Automation Build](https://developers.nopecha.com/guides/extension_advanced/#automation-build) (`chromium_automation.zip`). -The Automation Build reads its key from the Nopecha Manifest Config, `manifest["nopecha"]["key"]` in `manifest.json`. This package sets that field and leaves every other manifest field alone, including the top-level `"key"` (the Chrome extension public key). It does not modify JavaScript or HTML, and it does not download the Web Store CRX. +The Automation Build reads its key from the Nopecha Manifest Config, `manifest["nopecha"]["key"]` in `manifest.json`. This package sets that field, turns on every captcha `*_auto_solve` and `*_auto_open` flag, and sets `enabled` to `true`. It leaves the rest of the Nopecha Manifest Config alone, including delay times and selectors, and it never rewrites the top-level `"key"` (the Chrome extension public key). It does not modify JavaScript or HTML, and it does not download the Web Store CRX. + +If you omit `extension_path`, `load()` downloads `chromium_automation.zip` from NopeCHA GitHub releases into `extensions/NopeCHA` and re-downloads when `manifest["version_name"]` differs from the latest release tag. Pass `version="0.6.1"` to pin a tag. A user-supplied Extension Directory is never overwritten by a download. The API key stays in the process. `load()` does not call `chrome_extension_python`'s storage writer, so the key is not saved in `site-packages/chrome_extension_python/package_storage.json`. @@ -14,7 +16,7 @@ pip install nopecha-extension ## Patch the Extension Directory -`extension_path` is the unpacked Automation Build directory. `update_files()` rewrites `manifest.json` only when `manifest["nopecha"]["key"]` differs. A second call with the same key leaves the file unchanged and reports it under `skipped`. +`extension_path` is the unpacked Automation Build directory. `update_files()` rewrites `manifest.json` when the API key differs or any captcha type is still disabled. A second call with the same key and all captcha types already enabled leaves the file unchanged and reports it under `skipped`. ```python import os @@ -45,7 +47,7 @@ An empty string, a whitespace-only string, `None`, or any non-string raises `Val ## Load it in Botasaurus -Install Botasaurus separately (`pip install botasaurus`). Passing the `Nopecha` instance in `extensions` makes Botasaurus call `load()`, which patches `manifest.json` and returns Chrome's `--load-extension` flag. `load()` raises `FileNotFoundError` when `manifest.json` is not in the Extension Directory. +Install Botasaurus separately (`pip install botasaurus`). Passing the `Nopecha` instance in `extensions` makes Botasaurus call `load()`, which downloads the Automation Build if needed, patches `manifest.json`, and returns Chrome's `--load-extension` flag. `load()` raises `FileNotFoundError` when a user-supplied Extension Directory has no `manifest.json`. ```python import os @@ -54,10 +56,7 @@ from botasaurus.browser import Driver, browser from nopecha_extension import Nopecha -ext = Nopecha( - api_key=os.environ["NOPECHA_API_KEY"], - extension_path="path/to/chromium_automation", -) +ext = Nopecha(api_key=os.environ["NOPECHA_API_KEY"]) @browser(extensions=[ext]) def open_example(driver: Driver, data): @@ -68,7 +67,7 @@ if __name__ == "__main__": open_example() ``` -`load(with_command_line_option=False)` returns the Extension Directory path instead of the flag. +Point `extension_path` at an unpacked Automation Build to skip the download. `load(with_command_line_option=False)` returns the Extension Directory path instead of the flag. ## Command line diff --git a/nopecha_extension/patcher.py b/nopecha_extension/patcher.py index ebe8233..dc38c59 100644 --- a/nopecha_extension/patcher.py +++ b/nopecha_extension/patcher.py @@ -3,13 +3,69 @@ import argparse import json import os +import shutil import sys +from io import BytesIO from typing import Any +from zipfile import BadZipFile, ZipFile + +from requests import get as http_get from chrome_extension_python import Extension, File, relative_path _MANIFEST_NAME = "manifest.json" _MANIFEST_READ_ERRORS = (OSError, UnicodeError, json.JSONDecodeError, TypeError) +_AUTOMATION_ZIP_LATEST = ( + "https://github.com/NopeCHALLC/nopecha-extension/releases/latest/download/" + "chromium_automation.zip" +) +_AUTOMATION_ZIP_TAG = ( + "https://github.com/NopeCHALLC/nopecha-extension/releases/download/" + "{tag}/chromium_automation.zip" +) +_LATEST_RELEASE_API = ( + "https://api.github.com/repos/NopeCHALLC/nopecha-extension/releases/latest" +) + + +def _fetch_bytes(url: str) -> bytes: + response = http_get(url, timeout=60) + response.raise_for_status() + return response.content + + +def _fetch_json(url: str) -> dict[str, Any]: + response = http_get(url, timeout=60) + response.raise_for_status() + payload = response.json() + if not isinstance(payload, dict): + raise TypeError("GitHub release response must be a JSON object") + return payload + + +def _normalized_version(value: str) -> str: + return value.strip().lstrip("vV") + + +def _latest_release_tag() -> str: + tag = _fetch_json(_LATEST_RELEASE_API).get("tag_name") + if not isinstance(tag, str) or tag.strip() == "": + raise ValueError("GitHub latest release is missing tag_name") + return tag.strip() + + +def _extract_zip(payload: bytes, dest: str) -> None: + dest = os.path.abspath(dest) + try: + archive = ZipFile(BytesIO(payload)) + except BadZipFile as exc: + raise ValueError("Automation Build download is not a valid zip") from exc + with archive: + for info in archive.infolist(): + target = os.path.abspath(os.path.join(dest, info.filename)) + if target != dest and not target.startswith(dest + os.sep): + raise ValueError(f"unsafe path in Automation Build zip: {info.filename}") + archive.extractall(dest) def _validated_api_key(api_key: str) -> str: @@ -18,15 +74,39 @@ def _validated_api_key(api_key: str) -> str: raise ValueError("api_key must be a non-empty string") -def _with_nopecha_key(manifest: dict[str, Any], api_key: str) -> dict[str, Any] | None: +def _is_captcha_toggle(name: str) -> bool: + return name.endswith("_auto_solve") or name.endswith("_auto_open") + + +def _with_captcha_types_enabled(settings: dict[str, Any]) -> dict[str, Any]: + updated = dict(settings) + updated["enabled"] = True + for name in list(updated): + if _is_captcha_toggle(name): + updated[name] = True + return updated + + +def _nopecha_config_matches(settings: dict[str, Any], api_key: str) -> bool: + if settings.get("key") != api_key or settings.get("enabled") is not True: + return False + return all( + value is True + for name, value in settings.items() + if _is_captcha_toggle(name) + ) + + +def _with_nopecha_config(manifest: dict[str, Any], api_key: str) -> dict[str, Any] | None: nopecha_settings = manifest.get("nopecha") - if isinstance(nopecha_settings, dict) and nopecha_settings.get("key") == api_key: + if isinstance(nopecha_settings, dict) and _nopecha_config_matches(nopecha_settings, api_key): return None if not isinstance(nopecha_settings, dict): nopecha_settings = {} else: nopecha_settings = dict(nopecha_settings) + nopecha_settings = _with_captcha_types_enabled(nopecha_settings) nopecha_settings["key"] = api_key updated = dict(manifest) @@ -47,24 +127,33 @@ def _manifest_read_error(exc: Exception) -> str: class Nopecha(Extension): """Point an unpacked Automation Build at a NopeCHA API key. - The key is written to the Nopecha Manifest Config, ``manifest["nopecha"]["key"]``. + The key is written to the Nopecha Manifest Config, ``manifest["nopecha"]["key"]``, + and every captcha ``*_auto_solve`` / ``*_auto_open`` flag is turned on. It is not passed into ``chrome_extension_python``, so ``load()`` does not persist it in ``package_storage.json``. + + When no Extension Directory is supplied, ``load()`` downloads + ``chromium_automation.zip`` into ``extensions/NopeCHA``. """ def __init__( self, api_key: str, extension_path: str | os.PathLike[str] | None = None, + version: str | None = None, extension_id: str = "dknlfmjaanfblgfdfebhijalfmhmjjjo", extension_name: str = "NopeCHA", ) -> None: key = _validated_api_key(api_key) + self._user_supplied_path = False + self._count_path_as_user_supplied = False super().__init__( extension_id=extension_id, extension_name=extension_name, ) + self._count_path_as_user_supplied = True self.api_key = key + self.version = version if extension_path is not None: self.extension_path = extension_path @@ -80,6 +169,8 @@ def extension_path(self, extension_path: str | os.PathLike[str]) -> None: self.extension_absolute_path = os.path.abspath(path) else: self.extension_absolute_path = relative_path(path) + if self._count_path_as_user_supplied: + self._user_supplied_path = True def get_file(self, path: str) -> File: relative = path.lstrip("/\\") @@ -102,7 +193,7 @@ def _write_manifest(self, manifest: dict[str, Any], relative_manifest_path: str def _manifest_for_write(self, api_key: str | None) -> dict[str, Any] | None: key = self._api_key_for_patch(api_key) - return _with_nopecha_key(self._read_manifest(_MANIFEST_NAME), key) + return _with_nopecha_config(self._read_manifest(_MANIFEST_NAME), key) def _plan_update(self, api_key: str | None) -> tuple[dict[str, list[str]], dict[str, Any] | None]: report: dict[str, list[str]] = {"modified": [], "skipped": [], "errors": []} @@ -118,10 +209,11 @@ def _plan_update(self, api_key: str | None) -> tuple[dict[str, list[str]], dict[ return report, updated def update_files(self, api_key: str | None = None) -> dict[str, list[str]]: - """Write the API key into ``manifest.json`` when it differs. + """Write the API key and enable captcha types in ``manifest.json``. - A matching ``manifest["nopecha"]["key"]`` leaves the file untouched. - ``manifest.json`` is listed in ``modified`` only after a successful write. + A matching key with every captcha type already enabled leaves the file + untouched. ``manifest.json`` is listed in ``modified`` only after a + successful write. """ report, updated = self._plan_update(api_key) if updated is None: @@ -141,21 +233,66 @@ def quick_patch_file(self, path: str = _MANIFEST_NAME, api_key: str | None = Non return False key = self._api_key_for_patch(api_key) try: - updated = _with_nopecha_key(self._read_manifest(relative_manifest_path), key) + updated = _with_nopecha_config(self._read_manifest(relative_manifest_path), key) if updated is not None: self._write_manifest(updated, relative_manifest_path) except _MANIFEST_READ_ERRORS: return False return True + def _cached_version_name(self) -> str | None: + try: + manifest = self._read_manifest(_MANIFEST_NAME) + except _MANIFEST_READ_ERRORS: + return None + name = manifest.get("version_name") + if isinstance(name, str) and name.strip() != "": + return name.strip() + return None + + def _desired_tag(self) -> str: + if self.version: + return self.version + return _latest_release_tag() + + def _cache_is_stale(self) -> bool: + cached = self._cached_version_name() + if cached is None: + return True + return _normalized_version(cached) != _normalized_version(self._desired_tag()) + + def _automation_zip_url(self) -> str: + if self.version: + return _AUTOMATION_ZIP_TAG.format(tag=self.version) + return _AUTOMATION_ZIP_LATEST + + def download(self) -> None: + """Fetch the Automation Build zip into the Extension Directory cache.""" + if self._user_supplied_path: + return + payload = _fetch_bytes(self._automation_zip_url()) + dest = self.extension_absolute_path + if os.path.exists(dest): + shutil.rmtree(dest) + os.makedirs(dest, exist_ok=True) + _extract_zip(payload, dest) + def load(self, with_command_line_option: bool = True) -> str: """Patch ``manifest.json`` and return the Chrome load flag. - Raises ``FileNotFoundError`` when the manifest is missing. Read and write - failures propagate (``ValueError``, ``TypeError``, or ``OSError``) instead - of returning a path for an unpatched manifest. + When no Extension Directory was supplied, fetches the Automation Build + first. Raises ``FileNotFoundError`` when the manifest is missing. Read + and write failures propagate (``ValueError``, ``TypeError``, or + ``OSError``) instead of returning a path for an unpatched manifest. """ manifest_path = os.path.join(self.extension_absolute_path, _MANIFEST_NAME) + if not self._user_supplied_path and ( + not os.path.isfile(manifest_path) + or self.force_update + or self._cache_is_stale() + ): + self.download() + manifest_path = os.path.join(self.extension_absolute_path, _MANIFEST_NAME) if not os.path.isfile(manifest_path): raise FileNotFoundError(manifest_path) updated = self._manifest_for_write(self.api_key) diff --git a/tests/test_automation_build_download.py b/tests/test_automation_build_download.py new file mode 100644 index 0000000..2556933 --- /dev/null +++ b/tests/test_automation_build_download.py @@ -0,0 +1,192 @@ +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from contextlib import contextmanager +from io import BytesIO +from pathlib import Path +from unittest.mock import patch +from zipfile import ZipFile + +from nopecha_extension.patcher import Nopecha + + +MARKER = "automation-build-marker.txt" + +AUTOMATION_MANIFEST = { + "nopecha": { + "key": "", + "keys": [], + "enabled": True, + "hcaptcha_auto_solve": True, + "hcaptcha_auto_open": True, + "recaptcha_auto_solve": False, + "recaptcha_auto_open": False, + "awscaptcha_auto_solve": False, + "awscaptcha_auto_open": False, + "funcaptcha_auto_solve": False, + "funcaptcha_auto_open": False, + "geetest_auto_solve": False, + "geetest_auto_open": False, + "lemincaptcha_auto_solve": False, + "lemincaptcha_auto_open": False, + "perimeterx_auto_solve": False, + "textcaptcha_auto_solve": False, + "turnstile_auto_solve": True, + }, + "name": "NopeCHA: CAPTCHA Solver", + "version": "0.6.1", + "version_name": "v0.6.1", + "manifest_version": 3, + "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC-extension-public-key", +} + + +@contextmanager +def _in_temp_cwd(): + with tempfile.TemporaryDirectory() as tmp: + previous = os.getcwd() + os.chdir(tmp) + try: + yield tmp + finally: + os.chdir(previous) + + +def _automation_zip(manifest: dict | None = None) -> bytes: + payload = AUTOMATION_MANIFEST if manifest is None else manifest + buf = BytesIO() + with ZipFile(buf, "w") as archive: + archive.writestr("manifest.json", json.dumps(payload)) + archive.writestr(MARKER, "from-github-automation-zip") + archive.writestr("popup.js", "apiKey: ''\n") + return buf.getvalue() + + +class AutomationBuildDownloadTest(unittest.TestCase): + def test_load_without_extension_directory_fetches_automation_build(self): + zip_bytes = _automation_zip() + fetched: list[str] = [] + + def fake_fetch_bytes(url: str) -> bytes: + fetched.append(url) + if "clients2.google.com" in url: + raise AssertionError("must not download the Web Store CRX") + return zip_bytes + + with _in_temp_cwd(): + with patch("nopecha_extension.patcher._fetch_bytes", fake_fetch_bytes), patch( + "nopecha_extension.patcher._fetch_json", + return_value={"tag_name": "0.6.1"}, + ): + ext = Nopecha(api_key="sub_test_key") + path = ext.load(with_command_line_option=False) + flagged = ext.load() + written = json.loads( + (Path(path) / "manifest.json").read_text(encoding="utf-8") + ) + marker_exists = (Path(path) / MARKER).is_file() + absolute_path = ext.extension_absolute_path + + self.assertEqual(len(fetched), 1) + self.assertTrue(all("chromium_automation.zip" in url for url in fetched)) + self.assertTrue(marker_exists) + self.assertEqual(path, absolute_path) + self.assertEqual(flagged, f"--load-extension={absolute_path}") + self.assertEqual(written["nopecha"]["key"], "sub_test_key") + self.assertEqual(written["key"], AUTOMATION_MANIFEST["key"]) + self.assertIs(written["nopecha"]["enabled"], True) + for name, value in written["nopecha"].items(): + if name.endswith("_auto_solve") or name.endswith("_auto_open"): + self.assertIs(value, True, name) + + def test_load_redownloads_when_cached_version_differs_from_latest_release(self): + old_manifest = json.loads(json.dumps(AUTOMATION_MANIFEST)) + old_manifest["version"] = "0.6.0" + old_manifest["version_name"] = "v0.6.0" + new_manifest = json.loads(json.dumps(AUTOMATION_MANIFEST)) + new_manifest["version"] = "0.6.1" + new_manifest["version_name"] = "v0.6.1" + zips = { + "0.6.0": _automation_zip(old_manifest), + "0.6.1": _automation_zip(new_manifest), + } + latest = {"tag": "0.6.0"} + fetched: list[str] = [] + + def fake_fetch_bytes(url: str) -> bytes: + fetched.append(url) + return zips[latest["tag"]] + + def fake_fetch_json(url: str) -> dict: + return {"tag_name": latest["tag"]} + + with _in_temp_cwd(): + with patch("nopecha_extension.patcher._fetch_bytes", fake_fetch_bytes), patch( + "nopecha_extension.patcher._fetch_json", fake_fetch_json + ): + ext = Nopecha(api_key="sub_test_key") + path = Path(ext.load(with_command_line_option=False)) + (path / MARKER).write_text("old-cache", encoding="utf-8") + latest["tag"] = "0.6.1" + ext.load(with_command_line_option=False) + marker = (path / MARKER).read_text(encoding="utf-8") + written = json.loads((path / "manifest.json").read_text(encoding="utf-8")) + + self.assertEqual(marker, "from-github-automation-zip") + self.assertEqual(written["version_name"], "v0.6.1") + self.assertEqual(written["nopecha"]["key"], "sub_test_key") + self.assertGreaterEqual(len(fetched), 2) + + def test_load_redownloads_when_cached_manifest_has_no_version_name(self): + stale_manifest = json.loads(json.dumps(AUTOMATION_MANIFEST)) + stale_manifest["version"] = "0.6.1" + stale_manifest.pop("version_name", None) + zips = [_automation_zip(stale_manifest), _automation_zip()] + fetched: list[str] = [] + + def fake_fetch_bytes(url: str) -> bytes: + fetched.append(url) + return zips[min(len(fetched) - 1, 1)] + + with _in_temp_cwd(): + with patch("nopecha_extension.patcher._fetch_bytes", fake_fetch_bytes), patch( + "nopecha_extension.patcher._fetch_json", + return_value={"tag_name": "0.6.1"}, + ): + ext = Nopecha(api_key="sub_test_key") + path = Path(ext.load(with_command_line_option=False)) + (path / MARKER).write_text("old-cache", encoding="utf-8") + ext.load(with_command_line_option=False) + marker = (path / MARKER).read_text(encoding="utf-8") + + self.assertEqual(len(fetched), 2) + self.assertEqual(marker, "from-github-automation-zip") + + def test_load_pinned_version_fetches_that_release(self): + zip_bytes = _automation_zip() + fetched: list[str] = [] + + def fake_fetch_bytes(url: str) -> bytes: + fetched.append(url) + return zip_bytes + + with _in_temp_cwd(): + with patch("nopecha_extension.patcher._fetch_bytes", fake_fetch_bytes): + ext = Nopecha(api_key="sub_test_key", version="0.6.1") + path = ext.load(with_command_line_option=False) + written = json.loads( + (Path(path) / "manifest.json").read_text(encoding="utf-8") + ) + + self.assertEqual(fetched, [ + "https://github.com/NopeCHALLC/nopecha-extension/releases/download/" + "0.6.1/chromium_automation.zip" + ]) + self.assertEqual(written["nopecha"]["key"], "sub_test_key") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_automation_manifest_key.py b/tests/test_automation_manifest_key.py index 22f3701..ec03234 100644 --- a/tests/test_automation_manifest_key.py +++ b/tests/test_automation_manifest_key.py @@ -139,6 +139,49 @@ def test_spaced_key_is_stored_without_stripping(self): written = json.loads(manifest_path.read_text(encoding="utf-8")) self.assertEqual(written["nopecha"]["key"], api_key) + def test_update_files_enables_all_captcha_types(self): + api_key = "already-set" + manifest = json.loads(json.dumps(AUTOMATION_MANIFEST)) + manifest["nopecha"] = { + "key": api_key, + "keys": [], + "enabled": False, + "disabled_hosts": [], + "hcaptcha_auto_solve": True, + "hcaptcha_auto_open": False, + "recaptcha_auto_solve": False, + "recaptcha_auto_open": False, + "awscaptcha_auto_solve": False, + "awscaptcha_auto_open": False, + "funcaptcha_auto_solve": False, + "funcaptcha_auto_open": False, + "geetest_auto_solve": False, + "geetest_auto_open": False, + "lemincaptcha_auto_solve": False, + "lemincaptcha_auto_open": False, + "perimeterx_auto_solve": False, + "textcaptcha_auto_solve": False, + "turnstile_auto_solve": False, + "hcaptcha_solve_delay_time": 3000, + } + with tempfile.TemporaryDirectory() as tmp: + extension_dir = Path(tmp) + manifest_path = self._make_extension(extension_dir, manifest) + report = Nopecha(api_key=api_key, extension_path=extension_dir).update_files() + written = json.loads(manifest_path.read_text(encoding="utf-8")) + self._assert_scripts_untouched(extension_dir) + + self.assertEqual(report["modified"], ["manifest.json"]) + self.assertEqual(written["nopecha"]["key"], api_key) + self.assertEqual(written["nopecha"]["keys"], []) + self.assertEqual(written["nopecha"]["disabled_hosts"], []) + self.assertEqual(written["nopecha"]["hcaptcha_solve_delay_time"], 3000) + self.assertIs(written["nopecha"]["enabled"], True) + self.assertEqual(written["key"], AUTOMATION_MANIFEST["key"]) + for name, value in written["nopecha"].items(): + if name.endswith("_auto_solve") or name.endswith("_auto_open"): + self.assertIs(value, True, name) + def test_missing_or_non_dict_nopecha_settings_become_a_dict(self): cases = ( {k: v for k, v in AUTOMATION_MANIFEST.items() if k != "nopecha"}, @@ -154,7 +197,10 @@ def test_missing_or_non_dict_nopecha_settings_become_a_dict(self): self.assertEqual(written["nopecha"]["key"], "sub_test_key") self.assertEqual(written["key"], AUTOMATION_MANIFEST["key"]) if manifest.get("nopecha") == "not-a-dict": - self.assertEqual(written["nopecha"], {"key": "sub_test_key"}) + self.assertEqual( + written["nopecha"], + {"enabled": True, "key": "sub_test_key"}, + ) def test_extension_path_resolves_absolute_and_relative_directories(self): with tempfile.TemporaryDirectory() as tmp: From 912bd0aee003fb86c0cda28fb49525457b01638c Mon Sep 17 00:00:00 2001 From: 4EYES44 Date: Sat, 17 Oct 2026 11:05:40 +0300 Subject: [PATCH 2/2] Normalize pinned version tags so download URLs match GitHub releases. A v-prefixed or blank version passed the cache check but requested a 404 tag URL. Co-authored-by: Cursor --- nopecha_extension/patcher.py | 16 +++++++--- tests/test_automation_build_download.py | 39 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/nopecha_extension/patcher.py b/nopecha_extension/patcher.py index dc38c59..99a4d13 100644 --- a/nopecha_extension/patcher.py +++ b/nopecha_extension/patcher.py @@ -250,9 +250,16 @@ def _cached_version_name(self) -> str | None: return name.strip() return None + def _pinned_release_tag(self) -> str | None: + if not isinstance(self.version, str): + return None + tag = _normalized_version(self.version) + return tag or None + def _desired_tag(self) -> str: - if self.version: - return self.version + tag = self._pinned_release_tag() + if tag is not None: + return tag return _latest_release_tag() def _cache_is_stale(self) -> bool: @@ -262,8 +269,9 @@ def _cache_is_stale(self) -> bool: return _normalized_version(cached) != _normalized_version(self._desired_tag()) def _automation_zip_url(self) -> str: - if self.version: - return _AUTOMATION_ZIP_TAG.format(tag=self.version) + tag = self._pinned_release_tag() + if tag is not None: + return _AUTOMATION_ZIP_TAG.format(tag=tag) return _AUTOMATION_ZIP_LATEST def download(self) -> None: diff --git a/tests/test_automation_build_download.py b/tests/test_automation_build_download.py index 2556933..ec64d4a 100644 --- a/tests/test_automation_build_download.py +++ b/tests/test_automation_build_download.py @@ -187,6 +187,45 @@ def fake_fetch_bytes(url: str) -> bytes: ]) self.assertEqual(written["nopecha"]["key"], "sub_test_key") + def test_load_pinned_v_prefixed_version_fetches_unprefixed_release_tag(self): + zip_bytes = _automation_zip() + fetched: list[str] = [] + + def fake_fetch_bytes(url: str) -> bytes: + fetched.append(url) + return zip_bytes + + with _in_temp_cwd(): + with patch("nopecha_extension.patcher._fetch_bytes", fake_fetch_bytes): + ext = Nopecha(api_key="sub_test_key", version="v0.6.1") + ext.load(with_command_line_option=False) + + self.assertEqual(fetched, [ + "https://github.com/NopeCHALLC/nopecha-extension/releases/download/" + "0.6.1/chromium_automation.zip" + ]) + + def test_load_whitespace_only_version_fetches_latest_automation_build(self): + zip_bytes = _automation_zip() + fetched: list[str] = [] + + def fake_fetch_bytes(url: str) -> bytes: + fetched.append(url) + return zip_bytes + + with _in_temp_cwd(): + with patch("nopecha_extension.patcher._fetch_bytes", fake_fetch_bytes), patch( + "nopecha_extension.patcher._fetch_json", + return_value={"tag_name": "0.6.1"}, + ): + ext = Nopecha(api_key="sub_test_key", version=" ") + ext.load(with_command_line_option=False) + + self.assertEqual(fetched, [ + "https://github.com/NopeCHALLC/nopecha-extension/releases/latest/download/" + "chromium_automation.zip" + ]) + if __name__ == "__main__": unittest.main()