diff --git a/.github/workflows/sync-openapi.yml b/.github/workflows/sync-openapi.yml index a759940..621431b 100644 --- a/.github/workflows/sync-openapi.yml +++ b/.github/workflows/sync-openapi.yml @@ -80,6 +80,23 @@ jobs: echo "kind=breaking" >> "$GITHUB_OUTPUT" fi + # Public repos cloned outside the workspace, so nothing here can end up in the bot's commit. + - name: List what the integrations lack + if: steps.sync.outputs.changed == 'true' + continue-on-error: true + timeout-minutes: 5 + env: + GIT_TERMINAL_PROMPT: "0" + run: | + dir="$RUNNER_TEMP/integrations" + mkdir -p "$dir" + for repo in integration-n8n integration-make integration-zapier; do + git clone --quiet --depth 1 "https://github.com/geonodecom/$repo.git" "$dir/$repo" \ + || echo "::warning::Could not clone geonodecom/$repo" + done + python scripts/integration_gaps.py --before "$RUNNER_TEMP/openapi.before.json" --after openapi.json \ + --sources "$dir" --out "$RUNNER_TEMP/integrations.md" + - name: Get an integrations bot token id: app-token if: steps.sync.outputs.changed == 'true' @@ -117,18 +134,6 @@ jobs: 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" if [ -s "$RUNNER_TEMP/sync-notes.md" ]; then @@ -137,6 +142,16 @@ jobs: head -c 10000 "$RUNNER_TEMP/sync-notes.md" echo fi + # Before the oasdiff blocks, so the 60,000-byte cut below reaches them first. + if [ -s "$RUNNER_TEMP/integrations.md" ]; then + cat "$RUNNER_TEMP/integrations.md" + echo + else + echo "## Integrations: n8n, Make, Zapier" + echo + echo "The integration check did not run; see [the workflow log]($RUN_URL)." + echo + fi echo "## oasdiff: $KIND" echo echo '```text' @@ -152,7 +167,26 @@ jobs: echo "" echo echo "Opened by the nightly [Sync API spec]($RUN_URL) workflow." - } | head -c 60000 > "$RUNNER_TEMP/body.md" + } > "$RUNNER_TEMP/body.full.md" + # Cut from a file: piping into head would end the writer with SIGPIPE, which fails this step. + head -c 60000 "$RUNNER_TEMP/body.full.md" > "$RUNNER_TEMP/body.md" + + 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 + # The code is the same, but the integrations section may have changed since. + if gh pr edit "$pr" --body-file "$RUNNER_TEMP/body.md"; then + echo "Pull request #$pr already has these changes; its description was refreshed." >> "$GITHUB_STEP_SUMMARY" + else + echo "::warning::Could not refresh the description of pull request #$pr" + fi + exit 0 + fi + git push --quiet --force-with-lease="$SYNC_BRANCH:$remote_sha" origin "$SYNC_BRANCH" existing=$(gh label list --limit 500 --json name --jq '.[].name') for spec in "api-sync:1d76db" "breaking:d73a4a" "additive:0e8a16"; do diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fde65e6..f7504fa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ 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`, kept in step with the one in [geonodecom/sdk-typescript](https://github.com/geonodecom/sdk-typescript)), 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; its "Needs attention" section lists what postprocessing could not do on its own, such as a hand edit whose generated code changed. 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`. +Every night the `Sync API spec` workflow compares `openapi.json` with production (`scripts/sync_openapi.py`, kept in step with the one in [geonodecom/sdk-typescript](https://github.com/geonodecom/sdk-typescript)), 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; its "Needs attention" section lists what postprocessing could not do on its own, such as a hand edit whose generated code changed. Its "Integrations" section lists what the change removes that the hand-written n8n, Make and Zapier integrations still use, and what it adds that they lack (`scripts/integration_gaps.py`, kept in step with the one in [geonodecom/sdk-typescript](https://github.com/geonodecom/sdk-typescript); read from their source, so a pointer rather than a verdict). With clones of the three repositories in one directory, `python3 scripts/integration_gaps.py --after openapi.json --sources
[`'\"])(?P[^`'\"]*)(?P=q)" + ), + re.compile( + r"\b(?:url|path):\s*(?P [`'\"])(?P[^`'\"]*)(?P=q)\s*,\s*method:\s*['\"](?P [A-Za-z]+)['\"]" + ), +) +# Any string or template literal holding an API path, such as a polling URL built as `/v1/crawl/${jobId}`. +LITERAL = re.compile(r"[`'\"][^`'\"\n]*?(/v1/[^`'\"\s]*)[`'\"]") +VARIABLE_RESOURCE = re.compile(r"^/v1/\$\{[^}]+\}") + + +def norm(path: str) -> str: + """Path with its query dropped and every placeholder ({id}, ${id}, {{id}}) written as {}.""" + path = re.sub(r"\$\{[^}]*\}|\{\{[^}]*\}\}|\{[^}]*\}", "{}", path.split("?")[0]) + return path.rstrip("/") or "/" + + +@dataclass +class Usage: + calls: set[tuple[str | None, str]] = field(default_factory=set) # (method or None when unknown, normalized path) + query: dict[str, set[str]] = field(default_factory=dict) # Make only: "METHOD path" -> query keys it sends + files: list[tuple[str, str, set[tuple[str | None, str]]]] = field(default_factory=list) # name, text, calls + text: str = "" + commit: str = "" + error: str = "" + + def calls_op(self, method: str, path: str) -> bool: + return (method, norm(path)) in self.calls + + def may_send(self, method: str, path: str, name: str) -> bool: + """A field with this name declared in a file that calls the endpoint, or in a declarations-only file named + after its resource (n8n's `ExtractDescription.ts`).""" + resource = path.split("/")[2] if path.startswith("/v1/") else "" + return any( + ((method, norm(path)) in calls or (not calls and resource and resource in file_name.lower())) + and declares_field(text, name) + for file_name, text, calls in self.files + ) + + +def read_make(root: Path) -> Usage: + usage = Usage() + prefix = urlparse(json.loads((root / "base.imljson").read_text(encoding="utf-8-sig"))["baseUrl"]).path.rstrip("/") + for file in sorted(root.rglob("api.imljson")): + data = json.loads(file.read_text(encoding="utf-8-sig")) + for call in data if isinstance(data, list) else [data]: + url = str(call.get("url", "")) + if "{{parameters.url}}" in url: # the generic "make an API call" module reaches any endpoint + continue + path = norm(urlparse(url).path if url.startswith("http") else prefix + url) + method = str(call.get("method", "GET")).upper() + usage.calls.add((method, path)) + keys = set() + for qs in (call.get("qs"), (call.get("pagination") or {}).get("qs")): + if isinstance(qs, dict): + keys |= set(qs) + usage.query.setdefault(f"{method} {path}", set()).update(keys) + usage.text = "\n".join(f.read_text(encoding="utf-8-sig", errors="replace") for f in sorted(root.rglob("*.imljson"))) + return usage + + +def add_calls(calls: set[tuple[str | None, str]], method: str, url: str, named: set[str]) -> None: + path = url[url.find("/v1/") :] + if VARIABLE_RESOURCE.match(path): + targets = [VARIABLE_RESOURCE.sub(f"/v1/{r}", path, count=1) for r in named] + else: + targets = [path] + for target in targets: + calls.add((method.upper(), norm(target))) + + +def read_code(root: Path, patterns: list[str], resources: set[str]) -> Usage: + usage = Usage() + texts = [] + for pattern in patterns: + for file in sorted(root.glob(pattern)): + if "sample" in file.name or "node_modules" in file.parts: + continue + text = file.read_text(errors="replace") + texts.append(text) + # For `/v1/${jobType}/...`, the resources this file names as strings (Zapier's job types). + named = {r for r in resources if re.search(rf"['\"]{re.escape(r)}['\"]", text)} + calls: set[tuple[str | None, str]] = set() + in_requests = [] + for request in REQUESTS: + for match in request.finditer(text): + if "/v1/" in match["url"]: + add_calls(calls, match["method"], match["url"], named) + in_requests.append(match.span("url")) + # Any other path written without a method is a status or polling URL, so a GET. + for match in LITERAL.finditer(text): + if not any(start <= match.start(1) < end for start, end in in_requests): + add_calls(calls, "GET", match.group(1), named) + usage.calls |= calls + usage.files.append((file.name, text, calls)) + usage.text = "\n".join(texts) + return usage + + +def read_integrations(sources: Path, resources: set[str]) -> dict[str, Usage]: + readers = { + "n8n": lambda root: read_code(root, ["nodes/**/*.ts", "credentials/*.ts"], resources), + "Make": read_make, + "Zapier": lambda root: read_code( + root, ["creates/*.js", "searches/*.js", "triggers/*.js", "lib/*.js", "*.js"], resources + ), + } + result = {} + for name, repo in REPOS.items(): + root = sources / repo + try: + usage = readers[name](root) if root.is_dir() else Usage(error="not cloned") + except Exception as exc: # noqa: BLE001 - one unreadable integration must not hide the others + usage = Usage(error=f"{type(exc).__name__}: {exc}") + if not usage.error and not usage.calls: + usage.error = "no API calls found; its layout may have changed" + if root.is_dir(): + git = subprocess.run( + ["git", "-C", str(root), "rev-parse", "--short", "HEAD"], capture_output=True, text=True + ) + usage.commit = git.stdout.strip() + result[name] = usage + return result + + +def public(path: str) -> bool: + return path != "/health" and not path.startswith("/v1/internal/") + + +def operations(spec: dict) -> dict[tuple[str, str], dict]: + return { + (method.upper(), path): op + for path, item in spec.get("paths", {}).items() + if public(path) + for method, op in item.items() + if method in METHODS + } + + +def deref(spec: dict, node: dict) -> tuple[str | None, dict]: + """The schema a $ref points at, with its components name, or the node itself.""" + if isinstance(node, dict) and str(node.get("$ref", "")).startswith("#/components/"): + parts = node["$ref"][2:].split("/") + target = spec + for part in parts: + target = target.get(part, {}) + return parts[-1], target + return None, node + + +def query_params(spec: dict, path: str, method: str) -> set[str]: + item = spec["paths"][path] + params = list(item.get("parameters", [])) + list(item[method.lower()].get("parameters", [])) + return {p["name"] for p in (deref(spec, p)[1] for p in params) if p.get("in") == "query"} + + +def request_enums(spec: dict) -> dict[str, set[str]]: + """Enum values a client can send, keyed like `SearchRequest.engine` or `GET /v1/x ?param`.""" + found: dict[str, set[str]] = {} + seen: set[str] = set() + + def enums_of(node: dict) -> set[str]: + values = set(map(str, node.get("enum", []))) + for child in [node.get("items", {}), *node.get("anyOf", []), *node.get("oneOf", [])]: + if isinstance(child, dict) and child and "$ref" not in child: + values |= enums_of(child) + return values + + def visit(label: str, node: dict) -> None: + name, schema = deref(spec, node) + if name: + if name in seen: + return + seen.add(name) + label = name + if values := enums_of(schema): + found.setdefault(label, set()).update(values) + for prop, child in schema.get("properties", {}).items(): + visit(f"{label}.{prop}", child) + for child in [ + schema.get("items", {}), + *schema.get("anyOf", []), + *schema.get("oneOf", []), + *schema.get("allOf", []), + ]: + if isinstance(child, dict) and child: + visit(label, child) + + for (method, path), op in operations(spec).items(): + for media in (op.get("requestBody", {}).get("content") or {}).values(): + visit(f"{method} {path}", media.get("schema", {})) + params = list(spec["paths"][path].get("parameters", [])) + list(op.get("parameters", [])) + for param in (deref(spec, p)[1] for p in params): + if param.get("in") == "query": + visit(f"{method} {path} ?{param['name']}", param.get("schema", {})) + return found + + +def mentions(text: str, value: str) -> bool: + return re.search(rf"[`'\"]{re.escape(value)}[`'\"]", text) is not None + + +def declares_field(text: str, name: str) -> bool: + """An input field with this name, as n8n (`name: 'x'`) and Zapier (`key: 'x'`) declare them.""" + return re.search(rf"\b(?:name|key):\s*['\"]{re.escape(name)}['\"]", text) is not None + + +def report(after: dict, usages: dict[str, Usage], before: dict | None = None) -> str: + names = list(REPOS) + after_ops = operations(after) + out = ["## Integrations: n8n, Make, Zapier", ""] + read = [f"geonodecom/{REPOS[n]} `{usages[n].commit or 'unknown'}`" for n in names] + out += [ + f"Read from the default branches: {', '.join(read)}. Make is read from its module definitions, n8n and " + "Zapier from their source code, so this points at likely gaps rather than proving them. Response fields, " + "headers and webhook payloads are not checked. The bot does not change the integrations.", + "", + ] + readable = [n for n in names if not usages[n].error] + + if before is not None: + # Keyed by the normalized path, so renaming `{job_id}` to `{crawl_id}` is not a removal. + old = {(m, norm(p)): p for m, p in operations(before)} + new = {(m, norm(p)): p for m, p in after_ops} + lines = [] + for key in sorted(set(old) - set(new), key=lambda k: (k[1], k[0])): + method, path = key[0], old[key] + who = [n for n in readable if usages[n].calls_op(method, path)] + if who: + verb = "calls" if len(who) == 1 else "call" + lines.append(f"- `{method} {path}` is gone: {', '.join(who)} still {verb} it.") + for key in sorted(set(old) & set(new), key=lambda k: (k[1], k[0])): + method, path = key[0], new[key] + for param in sorted(query_params(before, old[key], method) - query_params(after, path, method)): + sends, maybe = [], [] + for n in readable: + if not usages[n].calls_op(method, path): + continue + if n == "Make": + if param in usages[n].query.get(f"{method} {norm(path)}", set()): + sends.append(n) + elif usages[n].may_send(method, path, param): + maybe.append(n) + parts = ([f"{', '.join(sends)} still sends it"] if sends else []) + ( + [f"{', '.join(maybe)} may still send it (a `{param}` field next to that call)"] if maybe else [] + ) + if parts: + lines.append(f"- `{method} {path}` no longer takes `{param}`: {'; '.join(parts)}.") + old_enums, new_enums = request_enums(before), request_enums(after) + # Only fields that still exist: a whole removed endpoint is reported above. + for label in sorted(set(old_enums) & set(new_enums)): + for value in sorted(old_enums[label] - new_enums[label]): + who = [n for n in readable if mentions(usages[n].text, value)] + if who: + verb = "offers" if len(who) == 1 else "offer" + lines.append(f"- `{value}` is no longer allowed in `{label}`: {', '.join(who)} still {verb} it.") + out += ["**Removed by this sync and still used**", ""] + (lines or ["Nothing."]) + [""] + + rows = [] + for key in sorted(set(new) - set(old), key=lambda k: (k[1], k[0])): + method, path = key[0], new[key] + rows.append([f"`{method} {path}`"] + [mark(usages[n], usages[n].calls_op(method, path)) for n in names]) + # New values of fields that existed before; a new endpoint's own fields come with its row above. + for label in sorted(set(new_enums) & set(old_enums)): + for value in sorted(new_enums[label] - old_enums[label]): + rows.append( + [f"`{value}` in `{label}`"] + [mark(usages[n], mentions(usages[n].text, value)) for n in names] + ) + out += ["**New in this sync**", ""] + out += table(["New", *names], rows) if rows else ["Nothing new for them to pick up."] + out += [""] + + unreadable = [f"{n} ({usages[n].error})" for n in names if usages[n].error] + if unreadable: + out += [f"**Could not read:** {'; '.join(unreadable)}.", ""] + + ops = sorted(after_ops, key=lambda op: (op[1], op[0])) + counts = ", ".join(f"{n} {sum(usages[n].calls_op(m, p) for m, p in ops)} of {len(ops)}" for n in readable) + full = table( + ["Endpoint", *names], + [[f"`{m} {p}`"] + [mark(usages[n], usages[n].calls_op(m, p)) for n in names] for m, p in ops], + ) + if before is not None: + out += [f" ", ""] + else: + out += [f"**Every endpoint** ({counts})", "", *full, ""] + return "\n".join(out) + + +def mark(usage: Usage, used: bool) -> str: + if usage.error: + return "?" + return "✓" if used else "—" + + +def table(header: list[str], rows: list[list[str]]) -> list[str]: + return ["| " + " | ".join(header) + " |", "|" + " --- |" * len(header)] + [ + "| " + " | ".join(r) + " |" for r in rows + ] + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--after", type=Path, required=True, help="the spec after the sync (openapi.json)") + parser.add_argument("--before", type=Path, help="the spec before the sync; without it, only today's coverage") + parser.add_argument("--sources", type=Path, required=True, help="directory with the three integration clones") + parser.add_argument("--out", type=Path, help="write the Markdown here instead of printing it") + args = parser.parse_args(argv) + + after = json.loads(args.after.read_text(encoding="utf-8")) + before = json.loads(args.before.read_text(encoding="utf-8")) if args.before else None + specs = [after] + ([before] if before else []) + resources = {path.split("/")[2] for spec in specs for _, path in operations(spec) if path.startswith("/v1/")} + usages = read_integrations(args.sources, resources) + for name, usage in usages.items(): + if usage.error: + # On stdout when the report goes to a file, where Actions reads workflow commands. + print(f"::warning::Could not read {name}: {usage.error}", file=sys.stdout if args.out else sys.stderr) + text = report(after, usages, before) + if args.out: + args.out.write_text(text, encoding="utf-8") + else: + print(text) + + +if __name__ == "__main__": + main() diff --git a/tests/test_integration_gaps.py b/tests/test_integration_gaps.py new file mode 100644 index 0000000..fa541d5 --- /dev/null +++ b/tests/test_integration_gaps.py @@ -0,0 +1,285 @@ +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +# The same test file lives in sdk-python (tests/) and sdk-typescript (scripts/tests/). +REPO = next(p for p in Path(__file__).resolve().parents if (p / "scripts" / "integration_gaps.py").is_file()) +SCRIPT = REPO / "scripts" / "integration_gaps.py" + + +@pytest.fixture(scope="module") +def gaps(): + spec = importlib.util.spec_from_file_location("integration_gaps", SCRIPT) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + yield module + sys.modules.pop(spec.name, None) + + +def op(*params, body=None): + operation = {"parameters": [{"name": p, "in": "query", "schema": {"type": "string"}} for p in params]} + if body: + operation["requestBody"] = { + "content": {"application/json": {"schema": {"$ref": f"#/components/schemas/{body}"}}} + } + return operation + + +def spec(engines, paths): + return { + "openapi": "3.1.0", + "paths": paths, + "components": { + "schemas": { + "SearchRequest": {"properties": {"query": {"type": "string"}, "engine": {"enum": engines}}}, + "LightRequest": {"properties": {"device": {"enum": ["desktop", "mobile"]}}}, + } + }, + } + + +BEFORE = spec( + ["brave", "duckduckgo"], + { + "/health": {"get": op()}, + "/v1/extract": {"post": op()}, + "/v1/extract/jobs": {"get": op("url", "status")}, + "/v1/search": {"post": op(body="SearchRequest")}, + "/v1/search/jobs": {"get": op("query", "status")}, + "/v1/crawl/{job_id}": {"get": op(), "delete": op()}, + "/v1/batch/jobs": {"get": op()}, + "/v1/map/jobs": {"get": op()}, + "/v1/internal/statistics": {"get": op()}, + }, +) +AFTER = spec( + ["duckduckgo", "yahoo"], + { + **BEFORE["paths"], + "/v1/extract/jobs": {"get": op("status")}, + "/v1/search/jobs": {"get": op("status")}, + "/v1/google/search/light": {"post": op(body="LightRequest")}, + }, +) + + +def write(root: Path, files: dict[str, str]) -> None: + for name, text in files.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text(text, encoding="utf-8") + + +@pytest.fixture +def sources(tmp_path): + write(tmp_path / "integration-make", {"base.imljson": json.dumps({"baseUrl": "https://scraper.geonode.io/v1"})}) + # Make files may start with a byte order mark. + (tmp_path / "integration-make/modules/list/api.imljson").parent.mkdir(parents=True) + (tmp_path / "integration-make/modules/list/api.imljson").write_text( + "" + json.dumps({"url": "/extract/jobs", "method": "GET", "qs": {"url": "{{parameters.url}}"}}), + encoding="utf-8", + ) + write(tmp_path / "integration-make", {"modules/raw/api.imljson": json.dumps({"url": "{{parameters.url}}"})}) + write( + tmp_path / "integration-n8n", + { + "nodes/Api/Api.node.ts": ( + "await request.call(this, { method: 'POST', url: '/v1/extract', body });\n" + "const jobUrl = `/v1/crawl/${jobId}`;\n" + "return request.call(this, { method: 'GET', url: '/v1/search/jobs', qs });\n" + ), + "nodes/Api/descriptions/SearchDescription.ts": ( + "{ displayName: 'Query', name: 'query', type: 'string' },\n{ name: 'Brave', value: 'brave' },\n" + ), + }, + ) + write( + tmp_path / "integration-zapier", + { + "triggers/job_completed.js": ( + "const EVENTS = { extract_completed: 'extract', batch_completed: 'batch' };\n" + "await request(z, bundle, { method: 'GET', path: `/v1/${jobType}/jobs` });\n" + ), + "creates/extract_url.js": ( + "{ key: 'url', label: 'URL' }\nrequest(z, b, { method: 'POST', path: '/v1/extract' });\n" + ), + "lib/samples.js": "module.exports = { url: '/v1/map/jobs' };\n", + }, + ) + return tmp_path + + +@pytest.fixture +def usages(gaps, sources): + return gaps.read_integrations(sources, {"extract", "search", "crawl", "batch", "map", "google"}) + + +def test_make_is_read_from_its_module_definitions(usages): + make = usages["Make"] + + assert make.calls == {("GET", "/v1/extract/jobs")} # the raw "make an API call" module is not coverage + assert make.query["GET /v1/extract/jobs"] == {"url"} + + +def test_code_integrations_count_status_urls_as_gets_and_expand_named_job_types(usages): + n8n, zapier = usages["n8n"], usages["Zapier"] + + assert n8n.calls_op("GET", "/v1/crawl/{job_id}") and not n8n.calls_op("DELETE", "/v1/crawl/{job_id}") + assert zapier.calls_op("GET", "/v1/extract/jobs") and zapier.calls_op("GET", "/v1/batch/jobs") + assert not zapier.calls_op("GET", "/v1/map/jobs") # not a job type in that file, and samples are skipped + + +def test_report_lists_what_the_sync_removes_and_adds(gaps, usages): + text = gaps.report(AFTER, usages, BEFORE) + removed = text.split("**Removed by this sync and still used**")[1].split("**New in this sync**")[0] + + assert "`GET /v1/extract/jobs` no longer takes `url`: Make still sends it." in removed + assert "Zapier" not in removed # its `url` field belongs to the extract form, not to the job list + assert "`GET /v1/search/jobs` no longer takes `query`: n8n may still send it" in removed + assert "`brave` is no longer allowed in `SearchRequest.engine`: n8n still offers it." in removed + assert "| `POST /v1/google/search/light` | — | — | — |" in text + assert "| `yahoo` in `SearchRequest.engine` | — | — | — |" in text + assert "desktop" not in text # values of a new endpoint's own fields come with its row + assert "/health" not in text and "/internal/" not in text + assert "Every endpoint ({counts})
", "", *full, "", "Every endpoint (n8n 3 of " in text + + +def test_an_integration_that_cannot_be_read_is_named_and_marked_unknown(gaps, sources): + import shutil + + shutil.rmtree(sources / "integration-zapier") + usages = gaps.read_integrations(sources, {"extract"}) + text = gaps.report(AFTER, usages, BEFORE) + + assert "**Could not read:** Zapier (not cloned)." in text + assert "| `POST /v1/extract` | ✓ | — | ? |" in text + + +def test_a_layout_change_that_finds_no_calls_is_reported(gaps, sources): + for file in (sources / "integration-n8n").rglob("*.ts"): + file.write_text("// moved elsewhere\n", encoding="utf-8") + + usages = gaps.read_integrations(sources, {"extract"}) + + assert usages["n8n"].error == "no API calls found; its layout may have changed" + + +def test_without_a_previous_spec_it_shows_todays_coverage(gaps, usages): + text = gaps.report(AFTER, usages) + + assert "**Removed by this sync" not in text and "
" not in text + assert text.count("| `") == len(gaps.operations(AFTER)) + + +def test_main_writes_the_section(gaps, sources, tmp_path): + (tmp_path / "before.json").write_text(json.dumps(BEFORE), encoding="utf-8") + (tmp_path / "after.json").write_text(json.dumps(AFTER), encoding="utf-8") + out = tmp_path / "integrations.md" + + gaps.main(["--before", str(tmp_path / "before.json"), "--after", str(tmp_path / "after.json"), + "--sources", str(sources), "--out", str(out)]) # fmt: skip + + assert out.read_text(encoding="utf-8").startswith("## Integrations: n8n, Make, Zapier") + + +def test_a_renamed_placeholder_is_not_a_removal(gaps, usages): + after = json.loads(json.dumps(AFTER)) + after["paths"]["/v1/crawl/{crawl_id}"] = after["paths"].pop("/v1/crawl/{job_id}") + + text = gaps.report(after, usages, BEFORE) + + assert "is gone" not in text + assert "`GET /v1/crawl/{crawl_id}`" in text + + +def test_a_path_inside_a_request_object_takes_only_its_method(gaps, tmp_path): + write( + tmp_path / "integration-zapier", + { + "triggers/hook.js": ( + "await request(z, bundle, { method: 'POST', path: '/v1/webhooks' });\n" + "await request(z, bundle, { path: `/v1/webhooks/${id}`, method: 'DELETE' });\n" + ) + }, + ) + + zapier = gaps.read_integrations(tmp_path, {"webhooks"})["Zapier"] + + assert zapier.calls == {("POST", "/v1/webhooks"), ("DELETE", "/v1/webhooks/{}")} + + +def test_a_removed_resource_still_expands_a_job_type_variable(gaps, sources, tmp_path): + after = json.loads(json.dumps(AFTER)) + del after["paths"]["/v1/batch/jobs"] + (tmp_path / "before.json").write_text(json.dumps(BEFORE), encoding="utf-8") + (tmp_path / "after.json").write_text(json.dumps(after), encoding="utf-8") + out = tmp_path / "out.md" + + gaps.main(["--before", str(tmp_path / "before.json"), "--after", str(tmp_path / "after.json"), + "--sources", str(sources), "--out", str(out)]) # fmt: skip + + assert "- `GET /v1/batch/jobs` is gone: Zapier still calls it." in out.read_text(encoding="utf-8") + + +def test_spec_walk_follows_refs_without_looping(gaps): + spec = { + "paths": { + "/v1/things": { + "parameters": [{"$ref": "#/components/parameters/Url"}], + "get": { + "parameters": [{"name": "status", "in": "query", "schema": {"$ref": "#/components/schemas/S"}}] + }, + "post": op(body="Node"), + } + }, + "components": { + "parameters": {"Url": {"name": "url", "in": "query", "schema": {"type": "string"}}}, + "schemas": { + "S": {"enum": ["a", "b"]}, + "Node": { + "allOf": [{"properties": {"kind": {"enum": ["x"]}, "child": {"$ref": "#/components/schemas/Node"}}}] + }, + }, + }, + } + + assert gaps.query_params(spec, "/v1/things", "GET") == {"url", "status"} + assert gaps.request_enums(spec) == {"S": {"a", "b"}, "Node.kind": {"x"}} + + +def test_make_query_includes_pagination(gaps, tmp_path): + write( + tmp_path / "integration-make", + { + "base.imljson": json.dumps({"baseUrl": "https://scraper.geonode.io/v1"}), + "modules/jobs/api.imljson": json.dumps( + {"url": "/batch/jobs", "qs": {"status": "x"}, "pagination": {"qs": {"page": "{{pagination.page}}"}}} + ), + }, + ) + + make = gaps.read_integrations(tmp_path, set())["Make"] + + assert make.query["GET /v1/batch/jobs"] == {"status", "page"} + + +def test_status_url_keys_are_not_request_urls(gaps, tmp_path): + write(tmp_path / "integration-n8n", {"nodes/A.node.ts": "return { status_url: '/v1/batch/x', method: 'POST' };\n"}) + + n8n = gaps.read_integrations(tmp_path, {"batch"})["n8n"] + + assert n8n.calls == {("GET", "/v1/batch/x")} + + +def test_enum_walk_reads_path_level_query_parameters(gaps): + spec = { + "paths": { + "/v1/things": {"parameters": [{"name": "kind", "in": "query", "schema": {"enum": ["a"]}}], "get": op()} + }, + "components": {"schemas": {}}, + } + + assert gaps.request_enums(spec) == {"GET /v1/things ?kind": {"a"}}