From 28bb5e2d75abee854e3613f8ef5110edeac80ac0 Mon Sep 17 00:00:00 2001 From: Ivan Antsileuski Date: Tue, 24 Nov 2026 15:32:14 +0300 Subject: [PATCH] Open a pull request from the integrations bot when the production API spec changes A nightly workflow fetches https://scraper.geonode.io/openapi.json, filters it with filter_spec.py and compares it with openapi.json. When they differ it regenerates the client, classifies the change with oasdiff and keeps one pull request on bot/openapi-sync up to date, labelled breaking or additive, with an entry under [Unreleased]. Nothing is published: releases stay with the Publish workflow. The bot token is minted only for the final push, after the generator and the other third-party tools have run. While that pull request is open, commits by people on the branch are kept, so test fixes for a breaking change survive the next night. Regeneration is now byte-for-byte stable: postprocess_generated.py trims the trailing whitespace the generator leaves, the uv.lock that `uv run` writes is ignored, and the repo-owned `servers` entry is kept so Configuration() still defaults to production. A new test guards that default. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/sync-openapi.yml | 174 ++++++++++++++++++ .gitignore | 2 + CONTRIBUTING.md | 2 + scripts/postprocess_generated.py | 15 ++ scripts/sync_openapi.py | 273 +++++++++++++++++++++++++++++ tests/test_default_host.py | 6 + tests/test_sync_openapi.py | 163 +++++++++++++++++ 7 files changed, 635 insertions(+) create mode 100644 .github/workflows/sync-openapi.yml create mode 100644 scripts/sync_openapi.py create mode 100644 tests/test_default_host.py create mode 100644 tests/test_sync_openapi.py diff --git a/.github/workflows/sync-openapi.yml b/.github/workflows/sync-openapi.yml new file mode 100644 index 0000000..24e955f --- /dev/null +++ b/.github/workflows/sync-openapi.yml @@ -0,0 +1,174 @@ +name: Sync API spec + +# Nightly: compare openapi.json with production and keep one pull request from the +# integrations bot up to date. Nothing is published; releases stay with Publish. +on: + schedule: + - cron: "17 2 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: sync-openapi + cancel-in-progress: false + +env: + SPEC_URL: https://scraper.geonode.io/openapi.json + SYNC_BRANCH: bot/openapi-sync + UV_VERSION: "0.13.7" + OASDIFF_VERSION: "1.35.0" + OASDIFF_SHA256: a8023002fcb2eaa7f5758148a9303cb63d33b939886df312268bc0fc7b939140 + +defaults: + run: + shell: bash + +jobs: + sync: + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + # No credentials are kept in .git/config while third-party tools run; the bot token is minted only to push. + - uses: actions/checkout@v4 + with: + ref: main + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install uv and oasdiff + run: | + python -m pip install "uv==${UV_VERSION}" + archive="oasdiff_${OASDIFF_VERSION}_linux_amd64.tar.gz" + curl -sSfL -o "$RUNNER_TEMP/$archive" \ + "https://github.com/oasdiff/oasdiff/releases/download/v${OASDIFF_VERSION}/$archive" + echo "${OASDIFF_SHA256} $RUNNER_TEMP/$archive" | sha256sum -c - + mkdir -p "$RUNNER_TEMP/oasdiff" + tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP/oasdiff" + echo "$RUNNER_TEMP/oasdiff" >> "$GITHUB_PATH" + + - name: Compare with production + id: sync + run: | + cp openapi.json "$RUNNER_TEMP/openapi.before.json" + python scripts/sync_openapi.py --source "$SPEC_URL" --summary "$RUNNER_TEMP/summary.md" >> "$GITHUB_OUTPUT" + + - name: Regenerate the SDK + if: steps.sync.outputs.changed == 'true' + run: bash scripts/generate.sh + + - name: Classify the change + id: classify + if: steps.sync.outputs.changed == 'true' + run: | + before="$RUNNER_TEMP/openapi.before.json" + oasdiff changelog "$before" openapi.json > "$RUNNER_TEMP/oasdiff-changelog.txt" 2>&1 \ + || echo "oasdiff changelog failed; see the workflow log." >> "$RUNNER_TEMP/oasdiff-changelog.txt" + # Any non-zero exit counts as breaking, so a person always looks when oasdiff is unsure. + if oasdiff breaking "$before" openapi.json --fail-on ERR > "$RUNNER_TEMP/oasdiff-breaking.txt" 2>&1; then + echo "kind=additive" >> "$GITHUB_OUTPUT" + else + echo "kind=breaking" >> "$GITHUB_OUTPUT" + fi + + - name: Get an integrations bot token + id: app-token + if: steps.sync.outputs.changed == 'true' + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ vars.INTEGRATIONS_BOT_APP_ID }} + private-key: ${{ secrets.INTEGRATIONS_BOT_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - name: Open or update the pull request + if: steps.sync.outputs.changed == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + BOT_LOGIN: ${{ steps.app-token.outputs.app-slug }}[bot] + KIND: ${{ steps.classify.outputs.kind }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + git remote set-url origin "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + pr=$(gh pr list --head "$SYNC_BRANCH" --state open --json number --jq '.[0].number // empty') + + remote_sha="" + if git ls-remote --exit-code --heads origin "$SYNC_BRANCH" > /dev/null; then + git fetch --quiet origin "$SYNC_BRANCH" + remote_sha=$(git rev-parse FETCH_HEAD) + # While the pull request is open, commits by anyone but the bot (as author or committer) are kept. + if [ -n "$pr" ]; then + people=$(git log --format='%an|%cn' "origin/main..$remote_sha" | grep -vxF "$BOT_LOGIN|$BOT_LOGIN" || true) + if [ -n "$people" ]; then + echo "::notice::Pull request #$pr has commits from people, so $SYNC_BRANCH is left as is until it is merged or closed." + echo "Skipped: pull request #$pr has commits from people." >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + fi + fi + + bot_id=$(gh api "/users/${BOT_LOGIN}" --jq .id) + git config user.name "$BOT_LOGIN" + git config user.email "${bot_id}+${BOT_LOGIN}@users.noreply.github.com" + git checkout -B "$SYNC_BRANCH" + git add -A + git commit --quiet -m "Sync API spec with production" + if [ -n "$pr" ] && [ -n "$remote_sha" ] && git diff --quiet "$remote_sha" HEAD; then + echo "Pull request #$pr already has these changes." >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + git push --quiet --force-with-lease="$SYNC_BRANCH:$remote_sha" origin "$SYNC_BRANCH" + + { + cat "$RUNNER_TEMP/summary.md" + echo "## oasdiff: $KIND" + echo + echo '```text' + head -c 20000 "$RUNNER_TEMP/oasdiff-breaking.txt" + echo '```' + echo + echo "
Full oasdiff changelog" + echo + echo '```text' + head -c 30000 "$RUNNER_TEMP/oasdiff-changelog.txt" + echo '```' + echo + echo "
" + echo + echo "Opened by the nightly [Sync API spec]($RUN_URL) workflow." + } | head -c 60000 > "$RUNNER_TEMP/body.md" + + existing=$(gh label list --limit 500 --json name --jq '.[].name') + for spec in "api-sync:1d76db" "breaking:d73a4a" "additive:0e8a16"; do + label=${spec%%:*} + if ! grep -qxF "$label" <<< "$existing"; then + gh label create "$label" --color "${spec##*:}" --description "Nightly API spec sync" \ + || echo "::warning::Could not create the $label label" + fi + done + # Attach only labels that exist, so a missing label cannot stop the pull request from opening. + existing=$(gh label list --limit 500 --json name --jq '.[].name') + create_args=(); edit_args=() + for label in api-sync "$KIND"; do + if grep -qxF "$label" <<< "$existing"; then + create_args+=(--label "$label"); edit_args+=(--add-label "$label") + else + echo "::warning::The $label label is missing; add it to the pull request by hand" + fi + done + other=additive + if [ "$KIND" = additive ]; then other=breaking; fi + if grep -qxF "$other" <<< "$existing"; then edit_args+=(--remove-label "$other"); fi + if [ -z "$pr" ]; then + gh pr create --base main --head "$SYNC_BRANCH" --title "Sync API spec with production" \ + --body-file "$RUNNER_TEMP/body.md" "${create_args[@]}" + else + gh pr edit "$pr" --body-file "$RUNNER_TEMP/body.md" "${edit_args[@]}" + fi + echo "Sync pull request updated: $KIND." >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index 9f76101..2d6d4fa 100644 --- a/.gitignore +++ b/.gitignore @@ -68,6 +68,8 @@ target/ # OpenAPI generator bookkeeping .openapi-generator/FILES geonode_scraper_sdk_README.md +# scripts/generate.sh runs the generator through `uv run`, which writes a lock file this repo does not track +uv.lock # Local development and credentials .venv/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 37b48dd..ab057bd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,8 @@ The tests use local fixtures and mocks; they do not require an API key. Never in The runtime client is generated from `openapi.json`. Update the contract and generation/postprocessing scripts when changing generated behavior, and add a focused regression test. To regenerate, run `bash scripts/generate.sh`. It uses the included contract and the generator version recorded in `.openapi-generator/VERSION`. Install `uv` (recommended) or the matching `openapi-generator-cli` and a Java runtime first, plus Python 3 for filtering and postprocessing. +Every night the `Sync API spec` workflow compares `openapi.json` with production (`scripts/sync_openapi.py`), regenerates the client and keeps one pull request from the integrations bot up to date, on the `bot/openapi-sync` branch. It is labelled `breaking` or `additive` by oasdiff and adds a changelog entry under `[Unreleased]`. Review it like any other pull request. When a breaking change fails the tests, push the fixes to that branch: the workflow leaves a branch with commits from people alone until its pull request is merged or closed. Merging publishes nothing. To run the same comparison locally, use `python3 scripts/sync_openapi.py` and then `bash scripts/generate.sh`. + ## Reports and releases For bugs, include the package version, runtime version, a minimal reproduction and expected behavior. Security reports belong in [SECURITY.md](SECURITY.md), not a public issue. Maintainers publish releases with the `Publish` workflow in GitHub Actions. diff --git a/scripts/postprocess_generated.py b/scripts/postprocess_generated.py index 2041967..d77f6b8 100755 --- a/scripts/postprocess_generated.py +++ b/scripts/postprocess_generated.py @@ -30,6 +30,16 @@ def apply_replacements(path: Path, replacements: list[tuple[str, str]]) -> bool: return True +def normalize_whitespace(path: Path) -> bool: + """Drop trailing spaces and end the file with exactly one newline, as the committed sources do.""" + original = path.read_text() + updated = "\n".join(line.rstrip(" \t") for line in original.split("\n")).rstrip("\n") + "\n" + if updated == original: + return False + path.write_text(updated) + return True + + def main() -> None: changed_files: list[Path] = [] @@ -150,6 +160,11 @@ def main() -> None: if apply_replacements(path, replacements): changed_files.append(path) + # The generator leaves trailing spaces and blank lines; trimming them keeps regeneration diffs to real changes. + trimmed = sum(normalize_whitespace(path) for path in sorted((SDK_DIR / "geonode_scraper_sdk").rglob("*.py"))) + if trimmed: + print(f"Trimmed trailing whitespace in {trimmed} generated files.") + if changed_files: print("Postprocessed generated Python SDK files:") for path in changed_files: diff --git a/scripts/sync_openapi.py b/scripts/sync_openapi.py new file mode 100644 index 0000000..64c4282 --- /dev/null +++ b/scripts/sync_openapi.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Bring openapi.json in line with the production API spec. + +Fetches the spec (a URL or a local file), strips internal-only paths with +openapi-generator/filter_spec.py and compares the result with the committed +openapi.json. When they differ, it rewrites openapi.json, adds an entry under +``## [Unreleased]`` in CHANGELOG.md and can write a Markdown summary of the +differences for a pull request. Regenerating the SDK is left to +scripts/generate.sh. + +The last line on stdout is ``changed=true`` or ``changed=false``, so a GitHub +Actions step can append it to ``$GITHUB_OUTPUT``. Everything else goes to stderr. + +Usage: + python3 scripts/sync_openapi.py [--source URL_OR_PATH] [--summary PATH] [--date YYYY-MM-DD] +""" + +from __future__ import annotations + +import argparse +import datetime as dt +import importlib.util +import json +import sys +import urllib.request +from dataclasses import dataclass, field, fields +from pathlib import Path +from typing import Callable + +REPO_ROOT = Path(__file__).resolve().parents[1] +SPEC_FILE = REPO_ROOT / "openapi.json" +CHANGELOG_FILE = REPO_ROOT / "CHANGELOG.md" +FILTER_SCRIPT = REPO_ROOT / "openapi-generator" / "filter_spec.py" +DEFAULT_SOURCE = "https://scraper.geonode.io/openapi.json" +UNRELEASED_HEADING = "## [Unreleased]" +METHODS = ("get", "put", "post", "delete", "patch") +# Top-level keys this repo sets itself: the API spec has no `servers`, and without it the client defaults to localhost. +REPO_OWNED_KEYS = ("servers",) + + +@dataclass +class SpecDiff: + """What a reader of the SDK would notice between two filtered specs.""" + + added_operations: list[str] = field(default_factory=list) + removed_operations: list[str] = field(default_factory=list) + added_parameters: list[str] = field(default_factory=list) + removed_parameters: list[str] = field(default_factory=list) + added_schemas: list[str] = field(default_factory=list) + removed_schemas: list[str] = field(default_factory=list) + added_fields: list[str] = field(default_factory=list) + removed_fields: list[str] = field(default_factory=list) + added_enum_values: list[str] = field(default_factory=list) + removed_enum_values: list[str] = field(default_factory=list) + newly_required: list[str] = field(default_factory=list) + no_longer_required: list[str] = field(default_factory=list) + added_responses: list[str] = field(default_factory=list) + removed_responses: list[str] = field(default_factory=list) + + def is_empty(self) -> bool: + return not any(getattr(self, f.name) for f in fields(self)) + + +# (attribute, label in the pull request summary, label in the changelog or None to leave it out) +_ROWS = ( + ("added_operations", "New endpoints", "New endpoints"), + ("removed_operations", "Removed endpoints", "Removed endpoints"), + ("added_parameters", "New request parameters", "New request parameters"), + ("removed_parameters", "Removed request parameters", "Removed request parameters"), + ("added_schemas", "New models", "New models"), + ("removed_schemas", "Removed models", "Removed models"), + ("added_fields", "New model fields", "New model fields"), + ("removed_fields", "Removed model fields", "Removed model fields"), + ("added_enum_values", "New enum values", "New enum values"), + ("removed_enum_values", "Removed enum values", "Removed enum values"), + ("newly_required", "Fields that became required", "Fields that became required"), + ("no_longer_required", "Fields that became optional", "Fields that became optional"), + ("added_responses", "New documented response codes", None), + ("removed_responses", "Removed documented response codes", None), +) + + +def load_filter() -> Callable[[dict], dict]: + module_spec = importlib.util.spec_from_file_location("filter_spec", FILTER_SCRIPT) + if module_spec is None or module_spec.loader is None: + raise RuntimeError(f"Cannot load {FILTER_SCRIPT}") + module = importlib.util.module_from_spec(module_spec) + module_spec.loader.exec_module(module) + return module.filter_spec + + +def fetch(source: str) -> dict: + if source.startswith(("https://", "http://")): + request = urllib.request.Request(source, headers={"User-Agent": "geonode-sdk-openapi-sync"}) + with urllib.request.urlopen(request, timeout=60) as response: + return json.load(response) + return json.loads(Path(source).read_text(encoding="utf-8")) + + +def dump(spec: dict) -> str: + """Serialise the way filter_spec.py does, so an unchanged spec compares equal byte for byte.""" + return json.dumps(spec, indent=4, sort_keys=True, ensure_ascii=False) + "\n" + + +def check_plausible(old: dict, new: dict) -> None: + """Refuse a spec that looks broken rather than changed, so a bad deploy cannot wipe the SDK.""" + if "openapi" not in new or not isinstance(new.get("paths"), dict): + raise SystemExit("The fetched document is not an OpenAPI spec") + old_count, new_count = len(old.get("paths", {})), len(new["paths"]) + if new_count * 2 < old_count: + raise SystemExit(f"The fetched spec has {new_count} paths, down from {old_count}; refusing to sync") + + +def _operations(spec: dict) -> dict[str, dict]: + operations = {} + for path, item in spec.get("paths", {}).items(): + for method, operation in item.items(): + if method in METHODS and isinstance(operation, dict): + operations[f"{method.upper()} {path}"] = operation + return operations + + +def _parameter_names(operation: dict) -> set[str]: + return {p["name"] for p in operation.get("parameters", []) if isinstance(p, dict) and "name" in p} + + +def _enum_values(schema: dict) -> list[str]: + """Allowed values of a schema, including the `anyOf: [{enum}, {type: null}]` form of optional fields.""" + values: list[str] = [] + for part in [schema, *schema.get("anyOf", []), *schema.get("oneOf", [])]: + if isinstance(part, dict): + values += [str(v) for v in part.get("enum") or []] + if "const" in part: + values.append(str(part["const"])) + return values + + +def _diff_values(before: list[str], after: list[str], where: str) -> tuple[list[str], list[str]]: + added = [f"`{v}` in `{where}`" for v in after if v not in before] + removed = [f"`{v}` in `{where}`" for v in before if v not in after] + return added, removed + + +def compare(old: dict, new: dict) -> SpecDiff: + diff = SpecDiff() + + old_ops, new_ops = _operations(old), _operations(new) + diff.added_operations = [f"`{op}`" for op in sorted(new_ops.keys() - old_ops.keys())] + diff.removed_operations = [f"`{op}`" for op in sorted(old_ops.keys() - new_ops.keys())] + for op in sorted(old_ops.keys() & new_ops.keys()): + before, after = _parameter_names(old_ops[op]), _parameter_names(new_ops[op]) + diff.added_parameters += [f"`{name}` on `{op}`" for name in sorted(after - before)] + diff.removed_parameters += [f"`{name}` on `{op}`" for name in sorted(before - after)] + codes_before = set(old_ops[op].get("responses", {})) + codes_after = set(new_ops[op].get("responses", {})) + diff.added_responses += [f"`{code}` on `{op}`" for code in sorted(codes_after - codes_before)] + diff.removed_responses += [f"`{code}` on `{op}`" for code in sorted(codes_before - codes_after)] + + old_schemas = old.get("components", {}).get("schemas", {}) + new_schemas = new.get("components", {}).get("schemas", {}) + diff.added_schemas = [f"`{name}`" for name in sorted(new_schemas.keys() - old_schemas.keys())] + diff.removed_schemas = [f"`{name}`" for name in sorted(old_schemas.keys() - new_schemas.keys())] + for name in sorted(old_schemas.keys() & new_schemas.keys()): + before, after = old_schemas[name], new_schemas[name] + props_before, props_after = before.get("properties") or {}, after.get("properties") or {} + diff.added_fields += [f"`{name}.{prop}`" for prop in sorted(props_after.keys() - props_before.keys())] + diff.removed_fields += [f"`{name}.{prop}`" for prop in sorted(props_before.keys() - props_after.keys())] + added, removed = _diff_values(_enum_values(before), _enum_values(after), name) + for prop in sorted(props_before.keys() & props_after.keys()): + before_values, after_values = _enum_values(props_before[prop]), _enum_values(props_after[prop]) + more, fewer = _diff_values(before_values, after_values, f"{name}.{prop}") + added, removed = added + more, removed + fewer + diff.added_enum_values += added + diff.removed_enum_values += removed + required_before, required_after = set(before.get("required") or []), set(after.get("required") or []) + diff.newly_required += [f"`{name}.{prop}`" for prop in sorted(required_after - required_before)] + diff.no_longer_required += [f"`{name}.{prop}`" for prop in sorted(required_before - required_after)] + + return diff + + +def changelog_entry(diff: SpecDiff) -> list[str]: + # No date here: the same spec must give the same commit on any night, so an unchanged sync pull request is left alone. + lines = ["- Synced with the production API spec."] + listed = False + for attr, _, label in _ROWS: + items = getattr(diff, attr) + if label and items: + lines.append(f" - {label}: {', '.join(items)}.") + listed = True + if not listed: + lines.append(" - Descriptions, types or constraints changed; see the API reference.") + return lines + + +def add_changelog_entry(changelog: str, entry: list[str]) -> str: + """Put the entry first under ``## [Unreleased]``, keeping any notes already there.""" + lines = changelog.splitlines() + if UNRELEASED_HEADING not in lines: + raise SystemExit(f"CHANGELOG.md has no '{UNRELEASED_HEADING}' heading") + start = lines.index(UNRELEASED_HEADING) + 1 + while start < len(lines) and not lines[start].strip(): + start += 1 + rest = lines[start:] + gap = [""] if rest and not rest[0].startswith("- ") else [] + return "\n".join(lines[: lines.index(UNRELEASED_HEADING) + 1] + ["", *entry, *gap, *rest]) + "\n" + + +def summary_markdown(diff: SpecDiff, source: str, date: str) -> str: + out = [ + "## What changed in the API spec", + "", + f"Source: `{source}`, fetched on {date} (UTC) and filtered with `openapi-generator/filter_spec.py`.", + "", + ] + if diff.is_empty(): + out.append("Only descriptions, types or constraints changed: no endpoint, parameter, model or enum value.") + else: + out += ["| Change | Items |", "| --- | --- |"] + out += [f"| {label} | {', '.join(getattr(diff, attr))} |" for attr, label, _ in _ROWS if getattr(diff, attr)] + out += [ + "", + "## Before merging", + "", + "- CI runs on this pull request. If a breaking change fails the tests, fix them in this branch: " + "the nightly sync does not overwrite commits pushed by people.", + "- Removed parameters or fields can break `geonode-scraper-tools-core`, which calls this SDK. " + "Release a fixed tools-core before releasing this SDK.", + "- Merging publishes nothing. A release is a separate version pull request and the manual Publish workflow.", + "", + ] + return "\n".join(out) + + +def _write(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="\n") as fh: + fh.write(text) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--source", default=DEFAULT_SOURCE, help="URL or file of the full API spec") + parser.add_argument("--summary", type=Path, help="write a Markdown summary of the differences here") + parser.add_argument("--date", default=dt.datetime.now(dt.timezone.utc).date().isoformat()) + args = parser.parse_args(argv) + + old_text = SPEC_FILE.read_text(encoding="utf-8") + new_spec = load_filter()(fetch(args.source)) + old_spec = json.loads(old_text) + check_plausible(old_spec, new_spec) + for key in REPO_OWNED_KEYS: + if key in old_spec: + new_spec[key] = old_spec[key] + new_text = dump(new_spec) + + if new_text == old_text: + print("openapi.json already matches the source spec", file=sys.stderr) + print("changed=false") + return 0 + + diff = compare(old_spec, new_spec) + new_changelog = add_changelog_entry(CHANGELOG_FILE.read_text(encoding="utf-8"), changelog_entry(diff)) + _write(SPEC_FILE, new_text) + _write(CHANGELOG_FILE, new_changelog) + if args.summary: + _write(args.summary, summary_markdown(diff, args.source, args.date)) + print("openapi.json updated; run scripts/generate.sh next", file=sys.stderr) + print("changed=true") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_default_host.py b/tests/test_default_host.py new file mode 100644 index 0000000..530c17c --- /dev/null +++ b/tests/test_default_host.py @@ -0,0 +1,6 @@ +import geonode_scraper_sdk + + +def test_configuration_defaults_to_the_production_api(): + # The host comes from `servers` in openapi.json; a regeneration that loses it points the client at localhost. + assert geonode_scraper_sdk.Configuration().host == "https://scraper.geonode.io" diff --git a/tests/test_sync_openapi.py b/tests/test_sync_openapi.py new file mode 100644 index 0000000..152f335 --- /dev/null +++ b/tests/test_sync_openapi.py @@ -0,0 +1,163 @@ +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "sync_openapi.py" + + +@pytest.fixture(scope="module") +def sync(): + spec = importlib.util.spec_from_file_location("sync_openapi", SCRIPT) + module = importlib.util.module_from_spec(spec) + # dataclasses look the defining module up in sys.modules + sys.modules[spec.name] = module + spec.loader.exec_module(module) + yield module + sys.modules.pop(spec.name, None) + + +def make_spec(paths, schemas=None): + return {"openapi": "3.1.0", "info": {"title": "t", "version": "1"}, "paths": paths, + "components": {"schemas": schemas or {}}} + + +def jobs_list(*params): + return {"get": {"parameters": [{"name": p, "in": "query"} for p in params], "responses": {"200": {}}}} + + +OLD = make_spec( + {"/v1/extract/jobs": jobs_list("job_id", "url"), "/v1/extract": {"post": {"responses": {"200": {}}}}}, + {"ErrorCode": {"enum": ["TIMEOUT"]}, "Job": {"properties": {"id": {}, "url": {}}}, "Gone": {}}, +) +NEW = make_spec( + { + "/v1/extract/jobs": jobs_list("job_id"), + "/v1/extract": {"post": {"responses": {"200": {}, "403": {}}}}, + "/v1/google/search/light": {"post": {"responses": {"200": {}}}}, + }, + {"ErrorCode": {"enum": ["TIMEOUT", "TARGET_BLOCKED"]}, "Job": {"properties": {"id": {}, "status": {}}}}, +) + + +def test_compare_lists_what_an_sdk_user_would_notice(sync): + diff = sync.compare(OLD, NEW) + + assert diff.added_operations == ["`POST /v1/google/search/light`"] + assert diff.removed_operations == [] + assert diff.removed_parameters == ["`url` on `GET /v1/extract/jobs`"] + assert diff.added_responses == ["`403` on `POST /v1/extract`"] + assert diff.removed_schemas == ["`Gone`"] + assert diff.added_fields == ["`Job.status`"] + assert diff.removed_fields == ["`Job.url`"] + assert diff.added_enum_values == ["`TARGET_BLOCKED` in `ErrorCode`"] + + +def test_compare_of_identical_specs_is_empty(sync): + assert sync.compare(OLD, OLD).is_empty() + + +def test_compare_sees_enum_values_inside_an_optional_field(sync): + def search(*engines): + engine = {"anyOf": [{"enum": list(engines), "type": "string"}, {"type": "null"}]} + return make_spec({}, {"SearchRequest": {"properties": {"engine": engine}}}) + + diff = sync.compare(search("brave", "naver"), search("yahoo", "naver")) + + assert diff.added_enum_values == ["`yahoo` in `SearchRequest.engine`"] + assert diff.removed_enum_values == ["`brave` in `SearchRequest.engine`"] + + +def test_compare_lists_fields_that_changed_required(sync): + before = make_spec({}, {"Job": {"properties": {"id": {}, "url": {}}, "required": ["id"]}}) + after = make_spec({}, {"Job": {"properties": {"id": {}, "url": {}}, "required": ["url"]}}) + + diff = sync.compare(before, after) + + assert diff.newly_required == ["`Job.url`"] + assert diff.no_longer_required == ["`Job.id`"] + + +def test_changelog_entry_leaves_response_codes_to_the_pull_request(sync): + entry = sync.changelog_entry(sync.compare(OLD, NEW)) + + assert entry[0] == "- Synced with the production API spec." + assert " - Removed request parameters: `url` on `GET /v1/extract/jobs`." in entry + assert not any("403" in line for line in entry) + + +@pytest.mark.parametrize( + ("unreleased", "expected"), + [ + ("## [Unreleased]\n\n## [0.6.2] - 2026-10-28\n", "## [Unreleased]\n\n- new\n\n## [0.6.2] - 2026-10-28\n"), + ("## [Unreleased]\n\n- old\n\n## [0.6.2]\n", "## [Unreleased]\n\n- new\n- old\n\n## [0.6.2]\n"), + ("## [Unreleased]\n", "## [Unreleased]\n\n- new\n"), + ], +) +def test_changelog_entry_goes_first_under_unreleased(sync, unreleased, expected): + assert sync.add_changelog_entry("# Changelog\n\n" + unreleased, ["- new"]) == "# Changelog\n\n" + expected + + +def test_changelog_without_unreleased_heading_is_refused(sync): + with pytest.raises(SystemExit): + sync.add_changelog_entry("# Changelog\n\n## [0.6.2]\n", ["- new"]) + + +def test_spec_that_lost_most_paths_is_refused(sync): + with pytest.raises(SystemExit, match="refusing"): + sync.check_plausible(NEW, make_spec({"/health": {"get": {}}})) + + +@pytest.fixture +def repo(sync, tmp_path, monkeypatch): + spec_file, changelog = tmp_path / "openapi.json", tmp_path / "CHANGELOG.md" + spec_file.write_text(sync.dump(OLD), encoding="utf-8") + changelog.write_text("# Changelog\n\n## [Unreleased]\n\n## [0.6.2]\n", encoding="utf-8") + monkeypatch.setattr(sync, "SPEC_FILE", spec_file) + monkeypatch.setattr(sync, "CHANGELOG_FILE", changelog) + monkeypatch.setattr(sync, "load_filter", lambda: lambda spec: spec) + return tmp_path + + +def test_main_leaves_files_alone_when_nothing_changed(sync, repo, capsys): + (repo / "source.json").write_text(json.dumps(OLD), encoding="utf-8") + before = (repo / "CHANGELOG.md").read_text(encoding="utf-8") + + assert sync.main(["--source", str(repo / "source.json")]) == 0 + + assert capsys.readouterr().out.strip().splitlines()[-1] == "changed=false" + assert (repo / "CHANGELOG.md").read_text(encoding="utf-8") == before + + +def test_main_rewrites_spec_changelog_and_summary(sync, repo, capsys): + (repo / "source.json").write_text(json.dumps(NEW), encoding="utf-8") + + sync.main(["--source", str(repo / "source.json"), "--summary", str(repo / "summary.md"), "--date", "2026-11-24"]) + + assert capsys.readouterr().out.strip().splitlines()[-1] == "changed=true" + assert json.loads((repo / "openapi.json").read_text(encoding="utf-8")) == NEW + assert "- Synced with the production API spec." in (repo / "CHANGELOG.md").read_text(encoding="utf-8") + assert "| New endpoints | `POST /v1/google/search/light` |" in (repo / "summary.md").read_text(encoding="utf-8") + + +def test_main_keeps_the_servers_this_repo_sets(sync, repo): + servers = [{"url": "https://scraper.geonode.io", "description": "Production"}] + (repo / "openapi.json").write_text(sync.dump({**OLD, "servers": servers}), encoding="utf-8") + (repo / "source.json").write_text(json.dumps(NEW), encoding="utf-8") + + sync.main(["--source", str(repo / "source.json")]) + + assert json.loads((repo / "openapi.json").read_text(encoding="utf-8"))["servers"] == servers + + +def test_main_writes_nothing_when_the_changelog_has_no_unreleased_heading(sync, repo): + (repo / "CHANGELOG.md").write_text("# Changelog\n\n## [0.6.2]\n", encoding="utf-8") + (repo / "source.json").write_text(json.dumps(NEW), encoding="utf-8") + spec_before = (repo / "openapi.json").read_text(encoding="utf-8") + + with pytest.raises(SystemExit): + sync.main(["--source", str(repo / "source.json")]) + + assert (repo / "openapi.json").read_text(encoding="utf-8") == spec_before