diff --git a/AGENTS.md b/AGENTS.md index 794ff72..c2acf89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,11 @@ `build-local`, a MonkeyTester build plugin: it implements `BUILD_PLUGIN_API.md` (contract `monkeytester-build-plugin`, kept in the MonkeyTester repo) and builds an app repo's branch on its own host (Android and iOS on a Mac, Android only on Linux), then uploads the result to the -viewer. See README.md (setup, configuration, API) and SECURITY.md (threat model). +viewer. It also implements the optional capability `write_tests` +(`POST /repos///tests`): it opens a pull request adding a test recorded on the +viewer's Devices page, through the code host API only (no local clone), for both Gitea and +GitHub. Everything else only reads the repo. See README.md (setup, configuration, API) and +SECURITY.md (threat model). ## Setup (do this first) README.md → **Install** is the single source for dependencies. The code is Python 3.10+, @@ -15,6 +19,7 @@ runs the tests. `nix run .#tests`, or `python3 -m unittest discover -s tests -v`. They use a fake Gitea, a fake GitHub and a fake viewer in-process, so no real forge or viewer is contacted. Gitea and GitHub here are product features (the code hosts the plugin builds from), not where this repo is hosted. +The fakes also accept the writes `POST /repos///tests` makes (tests/test_write_tests.py). ## Hosting and review workflow This repo isn't tied to one code host: it can live on GitHub, Gitea/Forgejo, GitLab, Bitbucket or a diff --git a/README.md b/README.md index 16ab57d..974bcb6 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,9 @@ cases and to build a branch; the plugin fetches the code from Gitea or GitHub wi a read-only token, runs the app repo's `.monkeytester/build-.sh` scripts here (Android and iOS on a Mac, Android only on Linux) and uploads the built apps to the viewer with the viewer's `submit.py`, so the run attaches to the build. +It can also open a pull request that adds a test recorded on the viewer's Devices +page (`POST /repos///tests`, optional capability `write_tests`; that +one route needs a token that can write, see below). The code-host URL and token live only in this plugin; the viewer never sees the token. A build that fails is not an HTTP error: `GET /builds/` is `200` with @@ -95,6 +98,12 @@ to any repo's `.git/config`, and passed to git only per command via environment. Settings → Applications → Access tokens, - GitHub: a fine-grained token with Contents: read + Metadata: read, or a classic token with the `repo` scope for private repos, + + To let the viewer's **Record test** open pull requests + (`POST /repos///tests`), the token must also write: Gitea + `write:repository`; GitHub fine-grained Contents: read and write + Pull + requests: read and write (a classic `repo` token already can). With a + read-only token builds work as before and that route answers 403 `forbidden`. - the **viewer URL** (prefilled with the address the browser is using) — the plugin uploads to it. The plugin checks the token against the code host (who it belongs to) before @@ -135,6 +144,7 @@ except `GET /health` needs the pairing token when `PLUGIN_TOKEN` is set. | `GET /repos//[?branch=]` | check a repo (and branch) | | `GET /repos///branches` | the repo's branches | | `GET /repos///cases?ref=` | test cases on a ref, the build scripts present, and each case's `DEVICE` lines (`devices`, see below) | +| `POST /repos///tests` | capability `write_tests`: open a pull request adding a recorded test file (see below) | | `POST /builds` | queue a build; `GET /builds/` its status | | `GET /builds//log?offset=` | the build log from `offset` | | `POST /builds//cancel` | stop a queued or running build | @@ -173,6 +183,64 @@ needed. If any file can't be read, `devices` is left out of the answer, which the contract reads as "unknown" (the cases list still comes back). `POST /builds` does not read these files. +### Recorded tests: `POST /repos///tests` + +Optional capability `write_tests` (listed in `/health` `capabilities`; the +contract stays version 1). The viewer's Devices page **Record test** calls it to +add a recorded steps file to a case. Same pairing token as every other route. + +```json +{"base": "master", + "case": "onboarding", + "new_case": false, + "file": "login_recorded.txt", + "content": "AI: CLICK Login button\nWAIT: 2.5\nAI: INPUT Email field \"a@b.c\"\n", + "instruction": "MODE: everytime\n", + "title": "Add recorded test onboarding/login_recorded.txt", + "body": "Recorded on the MonkeyTester Devices page (device , AI plugin )."} +``` + +The plugin checks everything itself before contacting the code host: + +- `case` matches `^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`; `file` matches + `^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\.txt$` and is not `INSTRUCTION.txt`. The file + is written to `mt-tests//`. +- `content` is a non-empty UTF-8 string of at most 256 KiB (413 `too_large` + above). `title` is the commit message and pull request title (default + `Add recorded test /`); `body` is the pull request text. +- `new_case: false`: `mt-tests//INSTRUCTION.txt` must exist on `base`. + `new_case: true`: `mt-tests/` must not exist, and `instruction` + (required, non-empty) is written as `mt-tests//INSTRUCTION.txt` in the + same commit. + +It then creates the branch `mt-record/--` (UTC) +from `base` with ONE commit holding the file(s) and opens a pull request into +`base`: + +```json +{"ok": true, "branch": "mt-record/onboarding-login_recorded-20261202153000", + "pr_url": "https://github.com/o/r/pull/12", "pr_number": 12} +``` + +| Status | `code` | When | +|---|---|---| +| 400 | `bad_request` | a bad name, type or empty field | +| 401 | `unauthorized` | missing or wrong pairing token | +| 403 | `forbidden` | the code host token can't write (the code host's message is in `error`) | +| 404 | `unknown_branch` | `base` doesn't exist | +| 404 | `unknown_case` | `new_case: false` and the case has no `INSTRUCTION.txt` on `base` | +| 409 | `case_exists` | `new_case: true` and `mt-tests/` exists on `base` | +| 409 | `file_exists` | `mt-tests//` exists on `base` (never overwritten) | +| 409 | `not_configured` | no code host token saved | +| 413 | `too_large` | `content` over 256 KiB | + +Errors use the usual `{"error": ..., "code": ...}` body (plus `forge_status` +when the code host answered). On GitHub the commit is made with the git data API +(tree with `base_tree`, commit, ref) and `POST /repos/{o}/{r}/pulls`; on Gitea +with one `POST /repos/{o}/{r}/contents` call carrying `new_branch` (Gitea 1.20 or +later) and `POST /repos/{o}/{r}/pulls`. If opening the pull request fails, the +new branch is deleted again. No local clone is used. + `/docs` reads `README.md` next to `build_plugin.py` at request time. The launchd/systemd units run from the checkout and the Nix flake copies every git-tracked file, so README.md is present in all three; an install without it @@ -189,7 +257,9 @@ secret or configuration. The plugin **runs the scripts of the branch it builds** — run it as a dedicated, never-root user, and only add trusted repos as projects: a repo's build script runs with that user's environment, keychain and SDKs. The forge token is read-only -and stays out of every log and git config. Builds are one-at-a-time; use +unless you want `POST /repos///tests` (it then needs write access, and +can only add files on a new `mt-record/...` branch plus a pull request; the plugin +never pushes to an existing branch) and stays out of every log and git config. Builds are one-at-a-time; use `POST /builds//cancel` to stop a queued or running build (the script's whole process group is terminated), and `GET /builds//log` to watch what it is doing. diff --git a/SECURITY.md b/SECURITY.md index f1fd1cb..82b62dd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -29,7 +29,7 @@ port, bind and auth, and the hardening tiers) lives in the MonkeyTester repo's | Access | `PLUGIN_TOKEN` pairing token on every request except `GET /health`, as `X-Plugin-Token` or `Authorization: Bearer`; compared with `hmac.compare_digest`. | | Bind | `PLUGIN_HOST` defaults to `0.0.0.0` (the viewer reaches the Mac over the LAN). **On any non-loopback bind the token is mandatory**: without `PLUGIN_TOKEN` the plugin exits with status 2 and says how to set it. On `127.0.0.1` / `::1` / `localhost` the token is optional. | | `/health` | Unauthenticated, never contains a secret. Without the token it only answers the contract, plugin name/version, code host kind, platforms, recipes and capabilities (`auth_required: true`); the code host URL/user, viewer URL and queue need the token. It may add `"docs": "/docs"` (README.md is readable); `GET /docs` itself needs the token and is served as HTML under `default-src 'none'` with no scripts, raw HTML in the README escaped. | -| Code host token | Stored in `config.json` (mode 0600, dir 0700); `GET /config` returns only `{configured, last4, saved_at}`. Given to git per command via `GIT_CONFIG_*` environment — never in argv, the remote URL, `.git/config` or a log. | +| Code host token | Read-only is enough for builds. `POST /repos///tests` (capability `write_tests`) needs write access; it only creates a new `mt-record/--` branch with one commit adding `mt-tests//` (and a new case's `INSTRUCTION.txt`) and opens a pull request — names are checked against strict patterns, existing files are never overwritten and no existing branch is pushed to. Stored in `config.json` (mode 0600, dir 0700); `GET /config` returns only `{configured, last4, saved_at}`. Given to git per command via `GIT_CONFIG_*` environment — never in argv, the remote URL, `.git/config` or a log. | | Subprocesses | argv lists only, never `shell=True`. Repo `owner/name`, branch/ref, case names, request ids and build refs are validated against allowlist regexes (no leading `-`, no `..`, no control chars). git commands put `--` before positional values; request/log values passed to `submit.py` use `--flag=value` so they can never become another option. | | git transports | `GIT_ALLOW_PROTOCOL=http:https:ssh` and `protocol.allow=never` (plus per-protocol allows) for the fetch **and submodules**: no `ext::` (runs a command), no `file://`/local paths. The clone URL's scheme is checked before any git command runs. | | Build environment | The plugin's own secrets (`PLUGIN_TOKEN`, `BUILD_LOCAL_IMPORT`, and any `GIT_CONFIG_*` it was started with) are removed from the environment of git, the build scripts and `submit.py`. | diff --git a/build_plugin.py b/build_plugin.py index b7348ff..b3ce724 100644 --- a/build_plugin.py +++ b/build_plugin.py @@ -2,7 +2,9 @@ (BUILD_PLUGIN_API.md, contract_version 1). The viewer's Build & Test page asks this plugin for a repo's branches and test -cases and to build a branch. The plugin reads the repo from Gitea or GitHub with +cases and to build a branch; the Devices page's Record test asks it to open a +pull request adding a recorded test (POST /repos///tests, capability +write_tests). The plugin reads the repo from Gitea or GitHub with a read-only token, fetches the branch with git, runs the app repo's `.monkeytester/build-.sh` here (Android and iOS on a Mac, Android only on Linux) and uploads the apps to the viewer with the viewer's submit.py. @@ -68,7 +70,7 @@ DEFAULT_PORT = 8094 CONTRACT = "monkeytester-build-plugin" CONTRACT_VERSION = 1 -CAPABILITIES = ["logs", "cancel"] +CAPABILITIES = ["logs", "cancel", "write_tests"] DEFAULT_KIND = "gitea" MAX_BODY = 1024 * 1024 REQUEST_TIMEOUT = 60 # seconds a client may take per socket read @@ -85,10 +87,15 @@ BRANCH_RE = re.compile(r"^(?!.*\.\.)(?!/)(?!-)(?!.*//)(?!.*@\{)[^\s~^:?*\[\\\x00-\x1f\x7f]{1,250}(?//tests (capability write_tests) +TEST_CASE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") +TEST_FILE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\.txt$") +MAX_TEST_CONTENT = 256 * 1024 # bytes of UTF-8 STATUS_FOR_CODE = { "bad_request": 400, "unauthorized": 401, "not_found": 404, "not_configured": 409, "forge_refused": 400, "forge_unreachable": 502, "internal": 500, "too_large": 413, + "forbidden": 403, "unknown_branch": 404, "unknown_case": 404, "case_exists": 409, "file_exists": 409, } @@ -290,6 +297,54 @@ def check_branch(branch, what="branch"): return branch +def _utf8_text(value, field, required=True, limit=None): + """A request string checked to be UTF-8-encodable, non-empty when required + and at most `limit` bytes.""" + if value is None and not required: + return "" + if not isinstance(value, str): + raise PluginError(f"{field} must be a string") + try: + size = len(value.encode("utf-8")) + except UnicodeEncodeError: + raise PluginError(f"{field} is not valid UTF-8") from None + if required and not value.strip(): + raise PluginError(f"{field} must not be empty") + if limit is not None and size > limit: + raise PluginError(f"{field} is too large (max {limit} bytes)", "too_large") + return value + + +def check_write_tests(data, now=None): + """The checked POST /repos///tests request, plus the branch to push + (`branch`). Never trusts the viewer: names, sizes and types are all checked + here before the code host is contacted.""" + if not isinstance(data, dict): + raise PluginError("expected a JSON object") + base = check_branch(data.get("base"), "base branch") + case = data.get("case") + if not isinstance(case, str) or not TEST_CASE_RE.match(case): + raise PluginError("case must match ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") + file = data.get("file") + if not isinstance(file, str) or not TEST_FILE_RE.match(file): + raise PluginError("file must match ^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\\.txt$") + if file.lower() == "instruction.txt": + raise PluginError("file must not be INSTRUCTION.txt") + new_case = data.get("new_case", False) + if not isinstance(new_case, bool): + raise PluginError("new_case must be true or false") + content = _utf8_text(data.get("content"), "content", limit=MAX_TEST_CONTENT) + instruction = "" + if new_case: + instruction = _utf8_text(data.get("instruction"), "instruction", limit=MAX_TEST_CONTENT) + title = _utf8_text(data.get("title"), "title", required=False, limit=1024).strip() + title = " ".join(title.split()) or f"Add recorded test {case}/{file}" + body = _utf8_text(data.get("body"), "body", required=False, limit=65536) + return {"base": base, "case": case, "new_case": new_case, "file": file, "content": content, + "instruction": instruction, "title": title, "body": body, + "branch": sources.record_branch(case, file, now)} + + class Plugin: def __init__(self, directory=None, pairing_token=None, platforms=None): directory = Path(directory) if directory else state_dir() @@ -438,6 +493,15 @@ def start_build(self, data): log(f"build {ref} queued: {repo} {branch} {','.join(platforms)} ({request_id})") return {"build_ref": ref, "url": ""} + # POST /repos///tests + def write_tests(self, repo, data): + req = check_write_tests(data) + cfg = self.configured() + src = self.source(cfg) + result = source_call(src.write_tests, cfg, repo, req) + log(f"recorded test {req['case']}/{req['file']} pushed to {repo} {req['branch']}: {result.get('pr_url')}") + return result + def build_status(self, ref): body = self.runner.body(ref) if body is None: @@ -605,6 +669,9 @@ def route(self, method, parts, query): return self.send_text(200, data, headers) elif len(parts) == 3 and parts[0] == "builds" and parts[2] == "cancel" and method == "POST": return self.send_json(200, p.cancel_build(parts[1])) + elif len(parts) == 4 and parts[0] == "repos" and parts[3] == "tests" and method == "POST": + repo = check_repo_name(parts[1], parts[2]) + return self.send_json(200, p.write_tests(repo, self.read_body())) elif len(parts) in (3, 4) and parts[0] == "repos" and method == "GET": repo = check_repo_name(parts[1], parts[2]) sub = parts[3] if len(parts) == 4 else None diff --git a/sources/__init__.py b/sources/__init__.py index 26d5107..2185908 100644 --- a/sources/__init__.py +++ b/sources/__init__.py @@ -1,7 +1,9 @@ -"""Read-only code host access for build-local (BUILD_PLUGIN_API.md). +"""Code host access for build-local (BUILD_PLUGIN_API.md). One module per code host kind (`gitea`, `github`). Every module offers the -same functions, all READ-ONLY (the token only needs to read the repo): +same functions. All but write_tests are READ-ONLY (a read-only token is enough +to list and build); write_tests needs a token that can push a branch and open +a pull request: KIND, LABEL, DEFAULT_URL normalize_url(url) -> the stored forge_url (raises SourceError) @@ -16,6 +18,10 @@ git_auth_config(cfg, repo) -> [(git config key, value)] carrying the token, passed per command via GIT_CONFIG_* env, never written to .git/config or the URL + write_tests(cfg, repo, req) -> contract POST /repos///tests body + ({ok, branch, pr_url, pr_number}); `req` + is the request already checked by + build_plugin.check_write_tests CLONE_URL_OVERRIDE -> tests only: "file:///.../{owner}/{name}.git" `cfg` is the plugin's config dict ({"forge_url", "token", ...}). @@ -27,6 +33,7 @@ import binascii import re import threading +import time from concurrent.futures import ThreadPoolExecutor PLATFORMS = ("android", "ios") @@ -192,6 +199,50 @@ def override_url(template, repo): return template.format(owner=owner, name=name, repo=repo) +# ─── POST /repos///tests (capability write_tests) ─── + +def record_branch(case, file, now=None): + """The branch a recorded test is pushed to: + mt-record/-- (UTC). Runs of dots in the + stem are collapsed to one so the name is always a valid git ref.""" + stem = file[:-len(".txt")] if file.endswith(".txt") else file + stem = re.sub(r"\.{2,}", ".", stem) + stamp = time.strftime("%Y%m%d%H%M%S", time.gmtime(now)) + return f"mt-record/{case}-{stem}-{stamp}" + + +def test_files(req): + """{repo path: text} a write_tests request commits: the test file, plus + INSTRUCTION.txt for a new case.""" + folder = f"{CASES_DIR}/{req['case']}" + files = {f"{folder}/{req['file']}": req["content"]} + if req["new_case"]: + files[f"{folder}/INSTRUCTION.txt"] = req["instruction"] + return files + + +def check_test_paths(req, state): + """The write_tests preconditions on `base`, shared by every source. + + state(path) -> "file", "dir" or None (missing); raises SourceError when the + code host can't answer.""" + folder = f"{CASES_DIR}/{req['case']}" + if req["new_case"]: + if state(folder) is not None: + raise SourceError(f"case {req['case']} already exists on {req['base']}", "case_exists", 409) + elif state(f"{folder}/INSTRUCTION.txt") != "file": + raise SourceError(f"no case {req['case']} on {req['base']} ({folder}/INSTRUCTION.txt missing)", + "unknown_case", 404) + if not req["new_case"] and state(f"{folder}/{req['file']}") is not None: + raise SourceError(f"{folder}/{req['file']} already exists on {req['base']}", "file_exists", 409) + + +def forbidden(label, what, status, message): + """SourceError for a write the code host refused for lack of permission.""" + return SourceError(f"{what}: the {label} token can't write to this repo ({message})", + "forbidden", 403, status) + + def get(kind): """The source module for a forge_kind, or None.""" if kind == "gitea": diff --git a/sources/gitea.py b/sources/gitea.py index ffc4682..b1a3c56 100644 --- a/sources/gitea.py +++ b/sources/gitea.py @@ -1,6 +1,8 @@ -"""Gitea, read-only (build-local source): token check, repo + default branch, branch exists, -branches with paging, cases and build scripts from the git tree. No Actions, -no write access needed. +"""Gitea build-local source: token check, repo + default branch, branch exists, +branches with paging, cases and build scripts from the git tree. No Actions. +All read-only except write_tests (POST /repos///tests), which pushes one +commit on a new branch (POST .../contents, Gitea 1.20+) and opens a pull +request. Gitea API: /api/v1, header `Authorization: token `. git fetch: `//.git` with the same header, scoped to the @@ -9,13 +11,15 @@ """ from __future__ import annotations +import base64 import json import urllib.error import urllib.parse import urllib.request -from sources import (PLATFORMS, RECIPES, SourceError, case_devices, cases_from_tree, decode_base64_content, - instruction_blobs, override_url, recipes_from_tree, require_http) +from sources import (PLATFORMS, RECIPES, SourceError, case_devices, cases_from_tree, check_test_paths, + decode_base64_content, forbidden, instruction_blobs, override_url, recipes_from_tree, + require_http, test_files) KIND = "gitea" LABEL = "Gitea" @@ -33,9 +37,11 @@ # ─── HTTP ─── -def api(url, token, method, path, params=None, timeout=20): +def api(url, token, method, path, params=None, timeout=20, body=None): """Call the Gitea API. Returns (status, parsed JSON or None). + body: sent as JSON when not None. + Raises SourceError(forge_unreachable) when Gitea can't be reached. Never puts the token in a message. """ @@ -43,7 +49,11 @@ def api(url, token, method, path, params=None, timeout=20): if params: full += "?" + urllib.parse.urlencode(params) headers = {"Accept": "application/json", "Authorization": f"token {token}"} - req = urllib.request.Request(require_http(full), headers=headers, method=method) + data = None + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + req = urllib.request.Request(require_http(full), data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310 - require_http: http(s) only status, raw = resp.status, resp.read() @@ -225,3 +235,60 @@ def list_cases(cfg, repo, ref, devices=True): if found is not None and set(found) == set(cases): out["devices"] = found return out + + +# ─── POST /repos///tests (capability write_tests) ─── + +def _path_state(cfg, repo, path, ref): + """"file", "dir" or None (missing) for a path on ref (contents API).""" + quoted = "/".join(_ref(p) for p in path.split("/")) + status, payload = _get(cfg, f"{_repo_path(repo)}/contents/{quoted}", {"ref": ref}) + if status == 404: + return None + if status != 200: + raise refused(f"Checking {path} failed", status, payload) + if isinstance(payload, list): + return "dir" + return "file" if isinstance(payload, dict) and payload.get("type") == "file" else "dir" + + +def _write(cfg, what, path, body): + """A write call: the answer on success; 401/403/404 -> forbidden (the repo + is readable, so a refused write means the token lacks write rights).""" + status, payload = api(cfg["forge_url"], cfg["token"], "POST", path, body=body) + if status in (200, 201) and isinstance(payload, dict): + return payload + if status in (401, 403, 404): + raise forbidden(LABEL, what, status, _message(status, payload)) + raise refused(what, status, payload) + + +def write_tests(cfg, repo, req): + """Push the recorded test (and a new case's INSTRUCTION.txt) as ONE commit + on a new branch from req["base"] and open a pull request into base. + + Unknown base -> unknown_branch; missing case -> unknown_case; existing + case/file -> case_exists/file_exists; refused write -> forbidden.""" + base, branch = req["base"], req["branch"] + status, payload = _get(cfg, f"{_repo_path(repo)}/branches/{_ref(base)}") + if status == 404: + raise SourceError(f"Branch {base} not found in {repo}", "unknown_branch", 404, 404) + if status != 200: + raise refused(f"Reading branch {base} failed", status, payload) + check_test_paths(req, lambda path: _path_state(cfg, repo, path, base)) + files = [{"operation": "create", "path": path, + "content": base64.b64encode(text.encode("utf-8")).decode()} + for path, text in test_files(req).items()] + _write(cfg, f"Creating branch {branch} failed", f"{_repo_path(repo)}/contents", + {"branch": base, "new_branch": branch, "message": req["title"], "files": files}) + try: + pr = _write(cfg, "Opening the pull request failed", f"{_repo_path(repo)}/pulls", + {"title": req["title"], "head": branch, "base": base, "body": req["body"]}) + except SourceError: + # Best effort: don't leave a branch without a pull request behind. + try: + api(cfg["forge_url"], cfg["token"], "DELETE", f"{_repo_path(repo)}/branches/{_ref(branch)}") + except SourceError: + pass + raise + return {"ok": True, "branch": branch, "pr_url": pr.get("html_url") or "", "pr_number": pr.get("number")} diff --git a/sources/github.py b/sources/github.py index 63b2ac5..dd10d07 100644 --- a/sources/github.py +++ b/sources/github.py @@ -1,8 +1,9 @@ -"""GitHub (github.com and GitHub Enterprise Server), read-only (build-local -source): token +"""GitHub (github.com and GitHub Enterprise Server) build-local source: token check, repo + default branch, branch exists, branches with paging, cases and build scripts from the git tree (contents-API fallback when the tree is -truncated). No Actions, no write access needed. +truncated). No Actions. All read-only except write_tests (POST +/repos///tests), which pushes one commit on a new branch through the git +data API (trees, commits, refs) and opens a pull request. forge_url is the REST API base: https://api.github.com for github.com, or https:///api/v3 for GitHub Enterprise Server. normalize_url() turns @@ -22,7 +23,8 @@ import urllib.request from sources import (CASE_RE, CASES_DIR, PLATFORMS, RECIPES, SourceError, case_devices, cases_from_tree, - decode_base64_content, instruction_blobs, override_url, recipes_from_tree, require_http) + check_test_paths, decode_base64_content, forbidden, instruction_blobs, override_url, + recipes_from_tree, require_http, test_files) KIND = "github" LABEL = "GitHub" @@ -66,9 +68,11 @@ def web_base(forge_url): return f"{parsed.scheme}://{parsed.netloc}" -def api(base, token, method, path, params=None, timeout=20): +def api(base, token, method, path, params=None, timeout=20, body=None): """Call the GitHub REST API. Returns (status, parsed JSON or None). + body: sent as JSON when not None. + Raises SourceError(forge_unreachable) when GitHub can't be reached. Never puts the token in a message. """ @@ -82,7 +86,11 @@ def api(base, token, method, path, params=None, timeout=20): } if token: headers["Authorization"] = f"Bearer {token}" - req = urllib.request.Request(require_http(full), headers=headers, method=method) + data = None + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + req = urllib.request.Request(require_http(full), data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310 - require_http: http(s) only status, raw = resp.status, resp.read() @@ -288,3 +296,64 @@ def list_cases(cfg, repo, ref, devices=True): if found is not None: out["devices"] = found return out + + +# ─── POST /repos///tests (capability write_tests) ─── + +def _path_state(cfg, repo, path, ref): + """"file", "dir" or None (missing) for a path on ref (contents API).""" + quoted = "/".join(_q(p) for p in path.split("/")) + status, payload = _call(cfg, "GET", f"/repos/{repo}/contents/{quoted}", params={"ref": ref}) + if status == 404: + return None + if status != 200: + raise _refused(f"Checking {path} failed", status, payload) + if isinstance(payload, list): + return "dir" + return "file" if isinstance(payload, dict) and payload.get("type") == "file" else "dir" + + +def _write(cfg, repo, what, path, body, ok=(201,)): + """A write call: the answer on success; 401/403/404 -> forbidden (the repo + is readable, so a refused write means the token lacks push rights).""" + status, payload = _call(cfg, "POST", path, body=body) + if status in ok and isinstance(payload, dict): + return payload + if status in (401, 403, 404): + raise forbidden(LABEL, what, status, _message(status, payload)) + raise _refused(what, status, payload) + + +def write_tests(cfg, repo, req): + """Push the recorded test (and a new case's INSTRUCTION.txt) as ONE commit + on a new branch from req["base"] and open a pull request into base. + + Unknown base -> unknown_branch; missing case -> unknown_case; existing + case/file -> case_exists/file_exists; refused write -> forbidden.""" + base, branch = req["base"], req["branch"] + try: + sha, tree_sha = _branch_commit(cfg, repo, base) + except SourceError as e: + if e.code != "not_found": + raise + raise SourceError(f"Branch {base} not found in {repo}", "unknown_branch", 404, 404) from None + check_test_paths(req, lambda path: _path_state(cfg, repo, path, sha)) + entries = [{"path": path, "mode": "100644", "type": "blob", "content": text} + for path, text in test_files(req).items()] + tree = _write(cfg, repo, "Creating the tree failed", f"/repos/{repo}/git/trees", + {"base_tree": tree_sha, "tree": entries}) + commit = _write(cfg, repo, "Creating the commit failed", f"/repos/{repo}/git/commits", + {"message": req["title"], "tree": tree.get("sha"), "parents": [sha]}) + _write(cfg, repo, f"Creating branch {branch} failed", f"/repos/{repo}/git/refs", + {"ref": f"refs/heads/{branch}", "sha": commit.get("sha")}) + try: + pr = _write(cfg, repo, "Opening the pull request failed", f"/repos/{repo}/pulls", + {"title": req["title"], "head": branch, "base": base, "body": req["body"]}) + except SourceError: + # Best effort: don't leave a branch without a pull request behind. + try: + _call(cfg, "DELETE", f"/repos/{repo}/git/refs/heads/{branch}") + except SourceError: + pass + raise + return {"ok": True, "branch": branch, "pr_url": pr.get("html_url") or "", "pr_number": pr.get("number")} diff --git a/tests/fake_gitea.py b/tests/fake_gitea.py index 46de5d0..f03871c 100644 --- a/tests/fake_gitea.py +++ b/tests/fake_gitea.py @@ -1,4 +1,4 @@ -"""An in-process fake Gitea (read-only API subset build-local uses). +"""An in-process fake Gitea (the API subset build-local uses). Covers the read-only calls: GET /user, repo, branches (paged), one branch, contents, git @@ -6,6 +6,10 @@ v1.27). It also records git's smart-HTTP discovery request (//.git/info/refs) so tests can see the credentials git sent, and answers it 404. No network access beyond 127.0.0.1. + +Writes (POST /repos/{o}/{r}/tests, capability write_tests): POST .../contents +(ChangeFilesOptions with new_branch), POST .../pulls, DELETE +.../branches/. The READ_ONLY token gets 403 on every write. """ import base64 import hashlib @@ -31,6 +35,9 @@ def __init__(self): self.fail_user = None # HTTP status for GET /user self.fail_blobs = False # answer GET .../git/blobs/ with 500 self.blobs = {} # blob sha -> file text (files given with content) + self.commits = [] # POST .../contents bodies that created a branch + self.pulls = [] # POST .../pulls bodies (+ "number", "repo") + self.fail_pulls = None # HTTP status for POST .../pulls branches = [f"feat/b{i:02d}" for i in range(60)] + ["master", "develop"] self.add_repo(REPO, {b: list(DEFAULT_FILES) for b in branches}) @@ -145,6 +152,63 @@ def do_GET(self): return self.reply(404, {"message": "not found"}) +def _write(self, method): + st = self.state + parsed = urllib.parse.urlparse(self.path) + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"" + st.calls.append((method, parsed.path, {})) + try: + body = json.loads(raw.decode() or "null") + except ValueError: + return self.reply(400, {"message": "bad json"}) + if self.token() not in (GOOD, READ_ONLY): + return self.reply(401, {"message": "token is required"}) + if not parsed.path.startswith("/api/v1/repos/"): + return self.reply(404, {"message": "no route"}) + parts = [urllib.parse.unquote(p) for p in parsed.path[len("/api/v1/repos/"):].split("/")] + repo, rest = "/".join(parts[:2]), parts[2:] + info = st.repos.get(repo) + if info is None: + return self.reply(404, {"message": "not found"}) + if self.token() == READ_ONLY: + return self.reply(403, {"message": "user should have a permission to write to a branch"}) + branches = info["branches"] + if method == "DELETE" and rest and rest[0] == "branches": + branches.pop("/".join(rest[1:]), None) + return self.reply(204) + if method == "POST" and rest == ["contents"]: + base, new = body.get("branch"), body.get("new_branch") + if base not in branches: + return self.reply(404, {"message": "branch does not exist"}) + if new in branches: + return self.reply(409, {"message": "branch already exists"}) + files = dict(branches[base]) if isinstance(branches[base], dict) else {p: "" for p in branches[base]} + for f in body.get("files") or []: + if f.get("operation") != "create": + return self.reply(422, {"message": "unsupported operation"}) + if f["path"] in files: + return self.reply(422, {"message": f"repository file already exists [path: {f['path']}]"}) + files[f["path"]] = base64.b64decode(f["content"]).decode("utf-8") + branches[new] = files + st.commits.append(body) + return self.reply(201, {"files": [], "commit": {"sha": "c" * 40, "message": body.get("message")}}) + if method == "POST" and rest == ["pulls"]: + if st.fail_pulls: + return self.reply(st.fail_pulls, {"message": "pull request refused"}) + if body.get("head") not in branches or body.get("base") not in branches: + return self.reply(404, {"message": "branch not found"}) + number = len(st.pulls) + 1 + st.pulls.append({**body, "number": number, "repo": repo}) + return self.reply(201, {"number": number, "state": "open", + "html_url": f"http://gitea.example/{repo}/pulls/{number}"}) + return self.reply(404, {"message": "not found"}) + + +FakeGitea.do_POST = lambda self: _write(self, "POST") +FakeGitea.do_DELETE = lambda self: _write(self, "DELETE") + + def start(): """(server, url, state).""" state = State() diff --git a/tests/fake_github.py b/tests/fake_github.py index a411eca..c72c527 100644 --- a/tests/fake_github.py +++ b/tests/fake_github.py @@ -1,4 +1,4 @@ -"""In-process fake of the read-only GitHub REST API endpoints build-local uses. +"""In-process fake of the GitHub REST API endpoints build-local uses. Copied from the archived build-github tests (fake_github.py) without the Actions endpoints. Response shapes follow docs.github.com (REST API version @@ -7,6 +7,11 @@ GHES URL handling is exercised too. It records git's smart-HTTP discovery request (//.git/info/refs) and answers it 404. No network access: it binds 127.0.0.1 on a free port. + +Writes (POST /repos/{o}/{r}/tests, capability write_tests): POST git/trees +(inline `content` entries on a base_tree), git/commits, git/refs and pulls, +DELETE git/refs/heads/. Only users in the repo's `writers` may write; +others get 403 like a read-only fine-grained token. """ import base64 import hashlib @@ -32,6 +37,10 @@ def __init__(self): self.lock = threading.Lock() self.blobs = {} # blob sha -> file text (files given with content) self.fail_blobs = False # answer GET .../git/blobs/ with 500 + self.fail_pulls = None # HTTP status for POST .../pulls + self.trees = {} # tree sha -> {path: text} (created by POST git/trees) + self.commits = {} # commit sha -> {"tree", "parents", "message", "files"} + self.pulls = [] # POST .../pulls bodies (+ "number", "repo") self.server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler()) self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True) @@ -49,11 +58,12 @@ def stop(self): self.server.shutdown() self.server.server_close() - def add_repo(self, repo, default="master", branches=None, truncated=False, users=None): + def add_repo(self, repo, default="master", branches=None, truncated=False, users=None, writers=None): """branches: {name: [file paths]} or {name: {file path: text}}.""" branches = branches or {default: [*RECIPES, "README.md"]} self.repos[repo] = {"default_branch": default, "branches": branches, - "truncated": truncated, "users": users or {"ci-bot", "reader"}} + "truncated": truncated, "users": users or {"ci-bot", "reader"}, + "writers": {"ci-bot"} if writers is None else writers} def calls(self, method=None, contains=""): return [r for r in self.requests if (method is None or r[0] == method) and contains in r[1]] @@ -111,6 +121,88 @@ def _send(self, status, body=None): if raw: self.wfile.write(raw) + def do_POST(self): + self._write("POST") + + def do_DELETE(self): + self._write("DELETE") + + def _write(self, method): + parsed = urllib.parse.urlsplit(self.path) + headers = {k.lower(): v for k, v in self.headers.items()} + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"" + fake.requests.append((method, parsed.path, {}, headers)) + try: + body = json.loads(raw.decode() or "null") + except ValueError: + return self._send(400, {"message": "Problems parsing JSON"}) + auth = self.headers.get("Authorization") or "" + user = fake.tokens.get(auth[len("Bearer "):] if auth.startswith("Bearer ") else "") + if not user: + return self._send(401, {"message": "Bad credentials"}) + parts = [urllib.parse.unquote(p) for p in parsed.path[len(PREFIX):].split("/") if p] + if len(parts) < 4 or parts[0] != "repos": + return self._send(404, {"message": "Not Found"}) + repo = f"{parts[1]}/{parts[2]}" + info = fake.repos.get(repo) + if info is None or user not in info["users"]: + return self._send(404, {"message": "Not Found"}) + if user not in info["writers"]: + return self._send(403, {"message": "Resource not accessible by personal access token"}) + with fake.lock: + return self._write_route(method, repo, info, parts[3:], body) + + def _write_route(self, method, repo, info, rest, body): + if method == "DELETE" and rest[:3] == ["git", "refs", "heads"]: + info["branches"].pop("/".join(rest[3:]), None) + return self._send(204) + if method != "POST": + return self._send(404, {"message": "Not Found"}) + if rest == ["git", "trees"]: + base = None + for name, files in info["branches"].items(): + if sha("tree:" + name) == body.get("base_tree"): + base = files + if base is None and body.get("base_tree") in fake.trees: + base = fake.trees[body["base_tree"]] + if base is None: + return self._send(422, {"message": "base_tree is not a valid tree"}) + files = dict(base) if isinstance(base, dict) else {p: "" for p in base} + for entry in body.get("tree") or []: + files[entry["path"]] = entry["content"] + tree = sha("newtree:" + json.dumps(sorted(files.items()))) + fake.trees[tree] = files + return self._send(201, {"sha": tree, "tree": [], "truncated": False}) + if rest == ["git", "commits"]: + if body.get("tree") not in fake.trees: + return self._send(422, {"message": "Tree SHA does not exist"}) + commit = sha(f"commit:{len(fake.commits)}:{body.get('message')}") + fake.commits[commit] = {"tree": body["tree"], "parents": body.get("parents"), + "message": body.get("message"), + "files": fake.trees[body["tree"]]} + return self._send(201, {"sha": commit, "message": body.get("message")}) + if rest == ["git", "refs"]: + ref = body.get("ref") or "" + if not ref.startswith("refs/heads/") or body.get("sha") not in fake.commits: + return self._send(422, {"message": "Invalid request"}) + name = ref[len("refs/heads/"):] + if name in info["branches"]: + return self._send(422, {"message": "Reference already exists"}) + info["branches"][name] = dict(fake.commits[body["sha"]]["files"]) + fake.commits[body["sha"]]["branch"] = name + return self._send(201, {"ref": ref, "object": {"sha": body["sha"], "type": "commit"}}) + if rest == ["pulls"]: + if fake.fail_pulls: + return self._send(fake.fail_pulls, {"message": "Validation Failed"}) + if body.get("head") not in info["branches"] or body.get("base") not in info["branches"]: + return self._send(422, {"message": "Validation Failed"}) + number = len(fake.pulls) + 1 + fake.pulls.append({**body, "number": number, "repo": repo}) + return self._send(201, {"number": number, "state": "open", + "html_url": f"https://github.com/{repo}/pull/{number}"}) + return self._send(404, {"message": "Not Found"}) + def do_GET(self): parsed = urllib.parse.urlsplit(self.path) query = {k: v[-1] for k, v in urllib.parse.parse_qs(parsed.query).items()} diff --git a/tests/test_build_local.py b/tests/test_build_local.py index 95c82d0..f51ad84 100644 --- a/tests/test_build_local.py +++ b/tests/test_build_local.py @@ -301,7 +301,7 @@ def test_health_platforms_and_recipes_match_the_contract(self): self.assertEqual(body["plugin"], {"name": "build-local", "version": build_plugin.PLUGIN_VERSION}) self.assertEqual(body["platforms"], ["android"]) self.assertEqual(body["recipes"], dict(RECIPES)) - self.assertEqual(body["capabilities"], ["logs", "cancel"]) + self.assertEqual(body["capabilities"], ["logs", "cancel", "write_tests"]) self.assertEqual(body["queue"], {"running": None, "waiting": 0}) self.assertIsNone(body["error"]) diff --git a/tests/test_write_tests.py b/tests/test_write_tests.py new file mode 100644 index 0000000..b1a79c6 --- /dev/null +++ b/tests/test_write_tests.py @@ -0,0 +1,246 @@ +"""POST /repos///tests (capability write_tests) against the fake +Gitea and the fake GitHub: one commit on a new mt-record/... branch and a pull +request into `base`. No real forge is contacted. +""" +import re +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +for _p in (str(ROOT), str(Path(__file__).resolve().parent)): + if _p not in sys.path: + sys.path.insert(0, _p) + +import build_plugin # noqa: E402 +import fake_github # noqa: E402 +import sources # noqa: E402 +from fake_gitea import READ_ONLY, REPO # noqa: E402 +from test_build_local import PAIR, PluginCase # noqa: E402 + +CONTENT = 'AI: CLICK Login button\nWAIT: 2.5\nAI: INPUT Email field "a@b.c"\n' +BRANCH_RE = re.compile(r"^mt-record/onboarding-login_recorded-\d{14}$") + + +def request(**over): + body = {"base": "master", "case": "onboarding", "new_case": False, "file": "login_recorded.txt", + "content": CONTENT, "instruction": "MODE: everytime\n", + "title": "Add recorded test onboarding/login_recorded.txt", + "body": "Recorded on the MonkeyTester Devices page (device Pixel, AI plugin AI)."} + body.update(over) + return body + + +class UnitTests(unittest.TestCase): + def test_branch_name(self): + self.assertEqual(sources.record_branch("onboarding", "login_recorded.txt", 0), + "mt-record/onboarding-login_recorded-19700101000000") + self.assertEqual(sources.record_branch("c", "a..b.txt", 0), "mt-record/c-a.b-19700101000000") + self.assertTrue(build_plugin.BRANCH_RE.match(sources.record_branch("c", "x...y.txt", 0))) + + def test_title_defaults_and_is_one_line(self): + req = build_plugin.check_write_tests(request(title=None)) + self.assertEqual(req["title"], "Add recorded test onboarding/login_recorded.txt") + req = build_plugin.check_write_tests(request(title="a\nb c")) + self.assertEqual(req["title"], "a b c") + self.assertEqual(req["instruction"], "") # only used for a new case + + +class WriteTestsMixin: + """Shared cases; subclasses configure one forge and expose files()/pulls.""" + + pairing_token = PAIR + + def post(self, body, headers=None): + return self.call("POST", f"/repos/{REPO}/tests", body, headers=headers) + + def test_health_advertises_write_tests(self): + status, body = self.call("GET", "/health") + self.assertIn("write_tests", body["capabilities"]) + + def test_existing_case_success(self): + status, body = self.post(request()) + self.assertEqual(status, 200, body) + self.assertEqual(set(body), {"ok", "branch", "pr_url", "pr_number"}) + self.assertTrue(body["ok"]) + self.assertRegex(body["branch"], BRANCH_RE) + self.assertEqual(body["pr_number"], 1) + self.assertTrue(body["pr_url"].endswith(f"{REPO}/pull/1") or body["pr_url"].endswith(f"{REPO}/pulls/1")) + files = self.files(body["branch"]) + self.assertEqual(files["mt-tests/onboarding/login_recorded.txt"], CONTENT) + self.assertNotIn("mt-tests/onboarding/login_recorded.txt", self.files("master")) + pr = self.pulls()[0] + self.assertEqual((pr["head"], pr["base"], pr["title"]), + (body["branch"], "master", "Add recorded test onboarding/login_recorded.txt")) + self.assertIn("Devices page", pr["body"]) + self.assertEqual(self.commit_messages(), ["Add recorded test onboarding/login_recorded.txt"]) + + def test_new_case_success_writes_instruction_in_the_same_commit(self): + status, body = self.post(request(case="checkout", new_case=True, file="pay.txt", + title="Add recorded test checkout/pay.txt")) + self.assertEqual(status, 200, body) + self.assertTrue(body["branch"].startswith("mt-record/checkout-pay-")) + files = self.files(body["branch"]) + self.assertEqual(files["mt-tests/checkout/pay.txt"], CONTENT) + self.assertEqual(files["mt-tests/checkout/INSTRUCTION.txt"], "MODE: everytime\n") + self.assertEqual(len(self.commit_messages()), 1) + + def test_file_exists(self): + status, body = self.post(request(file="INSTRUCTION2.txt")) + self.assertEqual(status, 200, body) + # The same file on a base that already has it (the branch just created). + status, body2 = self.post(request(base=body["branch"], file="INSTRUCTION2.txt")) + self.assertEqual((status, body2["code"]), (409, "file_exists"), body2) + self.assertIn("error", body2) + self.assertEqual(len(self.pulls()), 1) + + def test_case_exists(self): + status, body = self.post(request(new_case=True)) + self.assertEqual((status, body["code"]), (409, "case_exists"), body) + self.assertEqual(self.pulls(), []) + + def test_new_case_needs_instruction(self): + for instruction in (None, "", " \n"): + status, body = self.post(request(case="fresh", new_case=True, instruction=instruction)) + self.assertEqual((status, body["code"]), (400, "bad_request"), instruction) + + def test_unknown_case(self): + status, body = self.post(request(case="nope")) + self.assertEqual((status, body["code"]), (404, "unknown_case"), body) + + def test_unknown_branch(self): + status, body = self.post(request(base="no-such-branch")) + self.assertEqual((status, body["code"]), (404, "unknown_branch"), body) + + def test_bad_names_and_content(self): + bad = [ + {"case": "../etc"}, {"case": "-x"}, {"case": "a.b"}, {"case": "a" * 65}, {"case": ""}, + {"case": 5}, {"file": "x.sh"}, {"file": "../x.txt"}, {"file": ".x.txt"}, {"file": "a/b.txt"}, + {"file": "INSTRUCTION.txt"}, {"file": "instruction.txt"}, {"file": "a" * 101 + ".txt"}, + {"base": "a..b"}, {"base": ""}, {"new_case": "yes"}, {"content": ""}, {"content": " \n"}, + {"content": None}, {"content": ["x"]}, {"content": "\ud800"}, {"title": 3}, + ] + for over in bad: + status, body = self.post(request(**over)) + self.assertEqual((status, body["code"]), (400, "bad_request"), over) + status, body = self.post(request(content="x" * (256 * 1024 + 1))) + self.assertEqual((status, body["code"]), (413, "too_large")) + status, body = self.call("POST", "/repos/../x/tests", request()) + self.assertEqual(status, 400) + self.assertEqual(self.pulls(), []) + + def test_content_limit_is_utf8_bytes(self): + status, body = self.post(request(content="é" * (128 * 1024))) # exactly 256 KiB + self.assertEqual(status, 200, body) + status, body = self.post(request(file="b.txt", content="é" * (128 * 1024) + "x")) + self.assertEqual((status, body["code"]), (413, "too_large")) + + def test_pairing_token_missing_or_wrong_is_401(self): + for headers in ({"X-Plugin-Token": ""}, {"X-Plugin-Token": "wrong"}): + status, body = self.post(request(), headers=headers) + self.assertEqual((status, body["code"]), (401, "unauthorized")) + self.assertEqual(self.pulls(), []) + + def test_bearer_pairing_token_works(self): + status, body = self.post(request(), headers={"X-Plugin-Token": "", "Authorization": f"Bearer {PAIR}"}) + self.assertEqual(status, 200, body) + + def test_read_only_token_is_403_forbidden_with_forge_message(self): + self.use_read_only_token() + status, body = self.post(request()) + self.assertEqual((status, body["code"]), (403, "forbidden"), body) + self.assertIn(self.forbidden_message, body["error"]) + self.assertEqual(body["forge_status"], 403) + self.assertEqual(self.pulls(), []) + + def test_failed_pull_request_removes_the_branch(self): + self.fail_pulls(422) + status, body = self.post(request()) + self.assertEqual((status, body["code"]), (400, "forge_refused"), body) + self.assertFalse([b for b in self.branch_names() if b.startswith("mt-record/")]) + + def test_not_configured(self): + self.call("POST", "/config", {"token": None}) + status, body = self.post(request()) + self.assertEqual((status, body["code"]), (409, "not_configured")) + + +class GiteaWriteTests(WriteTestsMixin, PluginCase): + forbidden_message = "user should have a permission to write to a branch" + + def setUp(self): + super().setUp() + self.start_plugin() + status, body = self.configure() + self.assertEqual(status, 200, body) + + def files(self, branch): + files = self.gs.repos[REPO]["branches"][branch] + return files if isinstance(files, dict) else {p: "" for p in files} + + def branch_names(self): + return list(self.gs.repos[REPO]["branches"]) + + def pulls(self): + return self.gs.pulls + + def commit_messages(self): + return [c["message"] for c in self.gs.commits] + + def fail_pulls(self, status): + self.gs.fail_pulls = status + + def use_read_only_token(self): + status, body = self.configure(token=READ_ONLY) + self.assertEqual(status, 200, body) + + def test_one_contents_call_creates_branch_and_files(self): + status, body = self.post(request(case="checkout", new_case=True, file="pay.txt")) + self.assertEqual(status, 200, body) + commit = self.gs.commits[0] + self.assertEqual((commit["branch"], commit["new_branch"]), ("master", body["branch"])) + self.assertEqual(sorted(f["path"] for f in commit["files"]), + ["mt-tests/checkout/INSTRUCTION.txt", "mt-tests/checkout/pay.txt"]) + self.assertTrue(body["pr_url"].endswith(f"{REPO}/pulls/1")) + + +class GithubWriteTests(WriteTestsMixin, PluginCase): + forbidden_message = "Resource not accessible by personal access token" + + def setUp(self): + super().setUp() + self.start_plugin() + status, body = self.configure_gh() + self.assertEqual(status, 200, body) + + def files(self, branch): + files = self.gh.repos[REPO]["branches"][branch] + return files if isinstance(files, dict) else {p: "" for p in files} + + def branch_names(self): + return list(self.gh.repos[REPO]["branches"]) + + def pulls(self): + return self.gh.pulls + + def commit_messages(self): + return [c["message"] for c in self.gh.commits.values()] + + def fail_pulls(self, status): + self.gh.fail_pulls = status + + def use_read_only_token(self): + self.gh.repos[REPO]["writers"] = set() + + def test_commit_parent_is_base_and_pr_url_is_github(self): + status, body = self.post(request()) + self.assertEqual(status, 200, body) + self.assertEqual(body["pr_url"], f"https://github.com/{REPO}/pull/1") + (commit,) = self.gh.commits.values() + self.assertEqual(commit["parents"], [fake_github.sha("master")]) + refs = [r for r in self.gh.calls("POST") if r[1].endswith("/git/refs")] + self.assertEqual(len(refs), 1) + + +if __name__ == "__main__": + unittest.main()