diff --git a/README.md b/README.md index 7ab135c..16ab57d 100644 --- a/README.md +++ b/README.md @@ -134,11 +134,45 @@ except `GET /health` needs the pairing token when `PLUGIN_TOKEN` is set. | `GET /template?platform=` | example `.monkeytester/build-.sh` | | `GET /repos//[?branch=]` | check a repo (and branch) | | `GET /repos///branches` | the repo's branches | -| `GET /repos///cases?ref=` | test cases on a ref | +| `GET /repos///cases?ref=` | test cases on a ref, the build scripts present, and each case's `DEVICE` lines (`devices`, 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 | +### Cases and their DEVICE lines + +`GET /repos///cases?ref=` answers: + +```json +{ + "repo": "owner/App", + "ref": "master", + "cases": ["login", "onboarding"], + "recipes": {"android": true, "ios": true}, + "devices": { + "login": ["ios, physical", "android, virtual = MT_Pixel"], + "onboarding": [] + } +} +``` + +A case is a folder `mt-tests//` holding `INSTRUCTION.txt`. `devices` maps +each case to the raw text after `DEVICE:` on every `DEVICE` line in that file's +header, in file order, trimmed. A case without a `DEVICE` line maps to `[]`. The +header is the run of `KEY: value` lines at the top of the file (`MODE`, +`CLEAR_DATA`, `REINSTALL_APP`, `DEVICE`; the key is case-insensitive; blank +lines and `#` lines are allowed) and ends at the first other line, the same way +the MonkeyTester runner reads it. The plugin passes the values through without +interpreting them; the viewer parses them. + +The plugin reads every `INSTRUCTION.txt` as a git blob named by the branch's +tree, in parallel, and caches the result by blob sha, so a later listing only +reads files that changed. On GitHub, when the recursive tree is truncated, the +contents-API answers it already makes carry the files, so no extra request is +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. + `/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 diff --git a/build_plugin.py b/build_plugin.py index a70969d..b7348ff 100644 --- a/build_plugin.py +++ b/build_plugin.py @@ -429,7 +429,7 @@ def start_build(self, data): raise PluginError(f"this host can't build {', '.join(cant)} (it builds: {builds})") cfg = self.configured(need_viewer=True) src = self.source(cfg) - info = source_call(src.list_cases, cfg, repo, branch) + info = source_call(src.list_cases, cfg, repo, branch, False) # no devices: recipes only missing = [p for p in platforms if (info.get("recipes") or {}).get(p) is False] if missing: raise PluginError(f"{branch} has no {', '.join(RECIPES[p] for p in missing)} " diff --git a/sources/__init__.py b/sources/__init__.py index 1f27f79..26d5107 100644 --- a/sources/__init__.py +++ b/sources/__init__.py @@ -8,7 +8,10 @@ check_token(forge_url, token) -> the token's user login check_repo(cfg, repo, branch) -> contract GET /repos// body list_branches(cfg, repo) -> contract GET /repos///branches body - list_cases(cfg, repo, ref) -> contract GET /repos///cases body + list_cases(cfg, repo, ref, devices=True) + -> contract GET /repos///cases body; + devices=False skips reading the cases' + INSTRUCTION.txt (no `devices` key) clone_url(cfg, repo) -> the git URL to fetch from git_auth_config(cfg, repo) -> [(git config key, value)] carrying the token, passed per command via GIT_CONFIG_* env, @@ -20,7 +23,11 @@ """ from __future__ import annotations +import base64 +import binascii import re +import threading +from concurrent.futures import ThreadPoolExecutor PLATFORMS = ("android", "ios") RECIPES = {"android": ".monkeytester/build-android.sh", "ios": ".monkeytester/build-ios.sh"} @@ -57,6 +64,114 @@ def cases_from_tree(entries): return sorted(cases) +# Header keys of INSTRUCTION.txt (MonkeyTester's test runner, +# _parse_instruction_header_keys). The header ends at the first line that is +# not blank, not a # comment and not `: value`. +INSTRUCTION_HEADER_KEYS = ("mode", "clear_data", "reinstall_app", "device") +DEVICE_FETCH_WORKERS = 8 +_DEVICE_CACHE_MAX = 4096 +_device_cache = {} # blob sha -> [DEVICE values]; blobs are content-addressed +_device_cache_lock = threading.Lock() + + +def device_lines(content): + """The raw values after `DEVICE:` in an INSTRUCTION.txt header, in file + order, whitespace-trimmed. Not interpreted: the viewer parses them. + + Mirrors the runner's header parser: the key is case-insensitive and the + header stops at the first line that isn't blank, a # comment or a known + `KEY: value` line.""" + values = [] + for line in content.strip().split("\n"): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + key, sep, value = stripped.partition(":") + key = key.strip().lower() + if not sep or key not in INSTRUCTION_HEADER_KEYS: + break + if key == "device": + values.append(value.strip()) + return values + + +def decode_text(raw): + """File bytes -> text the way the runner reads them (UTF-8; bad bytes replaced).""" + return raw.decode("utf-8", "replace") + + +def instruction_blobs(entries): + """{case: blob sha} for mt-tests//INSTRUCTION.txt in a git tree listing.""" + blobs = {} + for entry in entries or []: + if not isinstance(entry, dict): + continue + parts = (entry.get("path") or "").split("/") + if len(parts) == 3 and parts[0] == CASES_DIR and parts[2] == "INSTRUCTION.txt" \ + and entry.get("type") == "blob" and CASE_RE.match(parts[1]) and entry.get("sha"): + blobs[parts[1]] = entry["sha"] + return blobs + + +def _cached_devices(sha): + with _device_cache_lock: + return _device_cache.get(sha) + + +def _cache_devices(sha, values): + with _device_cache_lock: + if len(_device_cache) >= _DEVICE_CACHE_MAX: + _device_cache.clear() + _device_cache[sha] = values + + +def case_devices(blobs, fetch_blob): + """{case: [DEVICE values]} for {case: blob sha}, or None when any + INSTRUCTION.txt couldn't be read (the response then leaves `devices` out, + which the contract reads as "unknown"). + + fetch_blob(sha) -> file bytes, or None on failure. Blobs not cached yet + are fetched in parallel; results are cached by blob sha (a sha always + names the same content, so a cached answer can't go stale).""" + out, missing = {}, {} + for case, sha in blobs.items(): + cached = _cached_devices(sha) + if cached is not None: + out[case] = list(cached) + else: + missing.setdefault(sha, []).append(case) + + def read(sha): + try: + raw = fetch_blob(sha) + except SourceError: + return sha, None + return sha, None if raw is None else device_lines(decode_text(raw)) + + if missing: + workers = min(DEVICE_FETCH_WORKERS, len(missing)) + with ThreadPoolExecutor(max_workers=workers) as pool: + for sha, values in pool.map(read, list(missing)): + if values is None: + return None + _cache_devices(sha, values) + for case in missing[sha]: + out[case] = list(values) + return dict(sorted(out.items())) + + +def decode_base64_content(payload): + """File bytes from a contents/blobs API answer ({"content", "encoding": + "base64"}), or None when it carries no base64 content.""" + if not isinstance(payload, dict) or payload.get("encoding") != "base64" \ + or not isinstance(payload.get("content"), str): + return None + try: + return base64.b64decode(payload["content"]) + except (ValueError, binascii.Error): + return None + + def recipes_from_tree(entries): """{platform: bool}: which build scripts a git tree listing holds.""" blobs = {e.get("path") for e in entries or [] if isinstance(e, dict) and e.get("type") == "blob"} diff --git a/sources/gitea.py b/sources/gitea.py index 57c5977..ffc4682 100644 --- a/sources/gitea.py +++ b/sources/gitea.py @@ -14,7 +14,8 @@ import urllib.parse import urllib.request -from sources import PLATFORMS, RECIPES, SourceError, cases_from_tree, override_url, recipes_from_tree, require_http +from sources import (PLATFORMS, RECIPES, SourceError, case_devices, cases_from_tree, decode_base64_content, + instruction_blobs, override_url, recipes_from_tree, require_http) KIND = "gitea" LABEL = "Gitea" @@ -188,8 +189,20 @@ def list_branches(cfg, repo): return {"repo": repo, "default": default, "branches": names} -def list_cases(cfg, repo, ref): - """{repo, ref, cases, recipes} for that branch. Unknown branch -> not_found.""" +def _read_blob(cfg, repo, sha): + """A blob's bytes (GET /repos/{o}/{r}/git/blobs/{sha}), or None on failure.""" + status, payload = _get(cfg, f"{_repo_path(repo)}/git/blobs/{_ref(sha)}") + if status != 200: + return None + return decode_base64_content(payload) + + +def list_cases(cfg, repo, ref, devices=True): + """{repo, ref, cases, recipes[, devices]} for that branch. Unknown branch -> not_found. + + devices: {case: [raw DEVICE values]} from each case's INSTRUCTION.txt + header, read in parallel as blobs named by the tree (cached by blob sha). + Left out when devices=False or when a file couldn't be read.""" entries = [] for page in range(1, TREE_MAX_PAGES + 1): status, payload = _get(cfg, f"{_repo_path(repo)}/git/trees/{_ref(ref)}", @@ -203,4 +216,12 @@ def list_cases(cfg, repo, ref): entries += payload.get("tree") or [] if not payload.get("truncated"): break - return {"repo": repo, "ref": ref, "cases": cases_from_tree(entries), "recipes": recipes_from_tree(entries)} + cases = cases_from_tree(entries) + out = {"repo": repo, "ref": ref, "cases": cases, "recipes": recipes_from_tree(entries)} + if devices: + blobs = instruction_blobs(entries) + found = case_devices({case: blobs[case] for case in cases if case in blobs}, + lambda sha: _read_blob(cfg, repo, sha)) + if found is not None and set(found) == set(cases): + out["devices"] = found + return out diff --git a/sources/github.py b/sources/github.py index a159029..63b2ac5 100644 --- a/sources/github.py +++ b/sources/github.py @@ -21,8 +21,8 @@ import urllib.parse import urllib.request -from sources import (CASE_RE, CASES_DIR, PLATFORMS, RECIPES, SourceError, cases_from_tree, override_url, - recipes_from_tree, require_http) +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) KIND = "github" LABEL = "GitHub" @@ -229,25 +229,41 @@ def _branch_commit(cfg, repo, ref): def _cases_from_contents(cfg, repo, sha): """Fallback when the recursive tree is truncated: list mt-tests/ and check - each folder for INSTRUCTION.txt through the contents API.""" + each folder for INSTRUCTION.txt through the contents API. + + Returns (cases, {case: (blob sha, file bytes or None)}): the contents API + answer already carries the file, so `devices` costs no extra request here.""" status, payload = _call(cfg, "GET", f"/repos/{repo}/contents/{CASES_DIR}", params={"ref": sha}) if status == 404: - return [] + return [], {} if status != 200 or not isinstance(payload, list): raise _refused(f"Listing {CASES_DIR}/ failed", status, payload) dirs = sorted(e["name"] for e in payload if isinstance(e, dict) and e.get("type") == "dir" and CASE_RE.match(e.get("name") or "")) - cases = [] + cases, files = [], {} for name in dirs[:MAX_FALLBACK_CASES]: status, entry = _call(cfg, "GET", f"/repos/{repo}/contents/{CASES_DIR}/{_q(name)}/INSTRUCTION.txt", params={"ref": sha}) if status == 200 and isinstance(entry, dict) and entry.get("type") == "file": cases.append(name) - return cases + files[name] = (entry.get("sha") or "", decode_base64_content(entry)) + return cases, files + + +def _read_blob(cfg, repo, blob_sha): + """A blob's bytes (GET /repos/{o}/{r}/git/blobs/{sha}), or None on failure.""" + status, payload = _call(cfg, "GET", f"/repos/{repo}/git/blobs/{_q(blob_sha)}") + if status != 200: + return None + return decode_base64_content(payload) + +def list_cases(cfg, repo, ref, devices=True): + """{repo, ref, cases, recipes[, devices]} for one branch. Unknown branch -> not_found. -def list_cases(cfg, repo, ref): - """{repo, ref, cases, recipes} for one branch. Unknown branch -> not_found.""" + devices: {case: [raw DEVICE values]} from each case's INSTRUCTION.txt + header, read in parallel as blobs named by the tree (cached by blob sha). + Left out when devices=False or when a file couldn't be read.""" sha, tree_sha = _branch_commit(cfg, repo, ref) status, payload = _call(cfg, "GET", f"/repos/{repo}/git/trees/{_q(tree_sha or sha)}", params={"recursive": "1"}) @@ -255,9 +271,20 @@ def list_cases(cfg, repo, ref): raise _refused(f"Reading the tree of {ref} failed", status, payload) entries = payload.get("tree") or [] if payload.get("truncated"): - cases = _cases_from_contents(cfg, repo, sha or ref) + cases, files = _cases_from_contents(cfg, repo, sha or ref) recipes = {p: has_file(cfg, repo, RECIPES[p], sha or ref) for p in PLATFORMS} + blobs = {case: blob for case, (blob, _) in files.items()} + inline = {blob: raw for blob, raw in files.values() if blob and raw is not None} else: cases = cases_from_tree(entries) recipes = recipes_from_tree(entries) - return {"repo": repo, "ref": ref, "cases": cases, "recipes": recipes} + blobs, inline = instruction_blobs(entries), {} + out = {"repo": repo, "ref": ref, "cases": cases, "recipes": recipes} + if devices: + found = None + if all(blobs.get(case) for case in cases): + found = case_devices({case: blobs[case] for case in cases}, + lambda blob: inline[blob] if blob in inline else _read_blob(cfg, repo, blob)) + if found is not None: + out["devices"] = found + return out diff --git a/tests/fake_gitea.py b/tests/fake_gitea.py index 7a4b0a0..46de5d0 100644 --- a/tests/fake_gitea.py +++ b/tests/fake_gitea.py @@ -7,6 +7,8 @@ (//.git/info/refs) so tests can see the credentials git sent, and answers it 404. No network access beyond 127.0.0.1. """ +import base64 +import hashlib import json import threading import urllib.parse @@ -27,21 +29,30 @@ def __init__(self): self.repos = {} self.tree_page_size = 1000 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) 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}) def add_repo(self, repo, branches, default="master"): - """branches: {name: [file paths]}.""" + """branches: {name: [file paths]} or {name: {file path: text}}.""" self.repos[repo] = {"default": default, "branches": branches} -def tree_entries(files): +def tree_entries(files, blobs=None): + """Tree entries; with file texts (a dict) blob shas are content-addressed + like git and the texts are registered in `blobs`.""" dirs, out = set(), [] for path in files: parts = path.split("/") for i in range(1, len(parts)): dirs.add("/".join(parts[:i])) - out.append({"path": path, "mode": "100644", "type": "blob", "sha": "b" * 40, "size": 10}) + blob = "b" * 40 + if isinstance(files, dict): + blob = hashlib.sha1(("blob:" + files[path]).encode()).hexdigest() + if blobs is not None: + blobs[blob] = files[path] + out.append({"path": path, "mode": "100644", "type": "blob", "sha": blob, "size": 10}) out += [{"path": d, "mode": "040000", "type": "tree", "sha": "t" * 40} for d in dirs] return sorted(out, key=lambda e: e["path"]) @@ -112,12 +123,20 @@ def do_GET(self): if any(f.startswith(fpath + "/") for f in branches[ref]): return self.reply(200, [{"type": "dir", "name": "x"}]) return self.reply(404, {"message": "GetContentsOrList", "errors": []}) + if rest[:2] == ["git", "blobs"] and len(rest) == 3: + if st.fail_blobs: + return self.reply(500, {"message": "boom"}) + if rest[2] not in st.blobs: + return self.reply(404, {"message": "object does not exist"}) + raw = st.blobs[rest[2]].encode() + return self.reply(200, {"sha": rest[2], "size": len(raw), "encoding": "base64", + "content": base64.b64encode(raw).decode(), "url": "http://gitea/blob"}) if rest[:2] == ["git", "trees"]: ref = "/".join(rest[2:]) if ref not in branches: # Gitea 1.27: GetTreeBySHA -> 400 "sha not found []" return self.reply(400, {"message": f"sha not found [{ref}]", "url": "http://gitea/api/swagger"}) - tree = tree_entries(branches[ref]) + tree = tree_entries(branches[ref], st.blobs) page = int(query.get("page", ["1"])[0]) per = min(int(query.get("per_page", ["1000"])[0]), st.tree_page_size) start, end = per * (page - 1), per * page diff --git a/tests/fake_github.py b/tests/fake_github.py index 56c1bb3..a411eca 100644 --- a/tests/fake_github.py +++ b/tests/fake_github.py @@ -8,6 +8,7 @@ request (//.git/info/refs) and answers it 404. No network access: it binds 127.0.0.1 on a free port. """ +import base64 import hashlib import json import threading @@ -29,6 +30,8 @@ def __init__(self): self.requests = [] # (method, path, query dict, lower-cased headers dict) self.git_requests = [] # (path, lower-cased headers dict) 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.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) @@ -47,7 +50,7 @@ def stop(self): self.server.server_close() def add_repo(self, repo, default="master", branches=None, truncated=False, users=None): - """branches: {name: [file paths]}.""" + """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"}} @@ -67,14 +70,23 @@ def _resolve(self, repo, ref): return name, files return None - @staticmethod - def _tree_entries(files): + def blob_sha(self, path, files): + """A file's blob sha: content-addressed like git when the branch gives + file texts (and registered in self.blobs), else derived from the path.""" + if isinstance(files, dict): + blob = sha("blob:" + files[path]) + self.blobs[blob] = files[path] + return blob + return sha(path) + + def _tree_entries(self, files): dirs, out = set(), [] for path in files: parts = path.split("/") for i in range(1, len(parts)): dirs.add("/".join(parts[:i])) - out.append({"path": path, "mode": "100644", "type": "blob", "sha": sha(path), "size": 10}) + out.append({"path": path, "mode": "100644", "type": "blob", "sha": self.blob_sha(path, files), + "size": 10}) out += [{"path": d, "mode": "040000", "type": "tree", "sha": sha(d)} for d in dirs] return sorted(out, key=lambda e: e["path"]) @@ -156,6 +168,14 @@ def _route(self, parts, query, user): if info["truncated"]: return self._send(200, {"sha": rest[2], "tree": entries[:2], "truncated": True}) return self._send(200, {"sha": rest[2], "tree": entries, "truncated": False}) + if len(rest) == 3 and rest[:2] == ["git", "blobs"]: + if fake.fail_blobs: + return self._send(500, {"message": "Server Error"}) + if rest[2] not in fake.blobs: + return self._send(404, {"message": "Not Found"}) + raw = fake.blobs[rest[2]].encode() + return self._send(200, {"sha": rest[2], "size": len(raw), "encoding": "base64", + "content": base64.encodebytes(raw).decode()}) if rest and rest[0] == "contents": path = "/".join(rest[1:]) found = fake._resolve(repo, query.get("ref") or info["default_branch"]) @@ -163,9 +183,11 @@ def _route(self, parts, query, user): return self._send(404, {"message": "No commit found for the ref"}) files = found[1] if path in files: + text = files[path] if isinstance(files, dict) else "" return self._send(200, {"type": "file", "name": path.split("/")[-1], "path": path, - "sha": sha(path), "size": 10, "encoding": "base64", - "content": ""}) + "sha": fake.blob_sha(path, files), "size": len(text), + "encoding": "base64", + "content": base64.encodebytes(text.encode()).decode()}) children = {} for f in files: if f.startswith(path + "/"): diff --git a/tests/test_build_local.py b/tests/test_build_local.py index e53279a..95c82d0 100644 --- a/tests/test_build_local.py +++ b/tests/test_build_local.py @@ -630,6 +630,146 @@ def test_branches_default_first_github(self): self.assertEqual(sorted(body["branches"]), sorted(FIXTURE_BRANCHES)) +# ─── `devices` on GET /repos///cases (DEVICE lines of INSTRUCTION.txt) ─── + +DEVICE_CASE_FILES = { + "README.md": "app", ANDROID_RECIPE: ANDROID_OK, IOS_RECIPE: IOS_OK, + "mt-tests/onboarding/INSTRUCTION.txt": ("# which devices\n" + "MODE: once\n" + "DEVICE: ios, physical\n" + "\n" + "device: android, virtual = MT_Pixel \n" + "Open the app.\n" + "DEVICE: ios, virtual\n"), + "mt-tests/login/INSTRUCTION.txt": "DEVICE: ios, physical\nDEVICE: android, virtual = MT_Pixel\nLog in.\n", + "mt-tests/plain/INSTRUCTION.txt": "Just steps, no header.\nDEVICE: ios, physical\n", + "mt-tests/twin/INSTRUCTION.txt": "DEVICE: ios, physical\nDEVICE: android, virtual = MT_Pixel\nLog in.\n", +} +DEVICES_WANTED = { + "login": ["ios, physical", "android, virtual = MT_Pixel"], + "onboarding": ["ios, physical", "android, virtual = MT_Pixel"], + "plain": [], + "twin": ["ios, physical", "android, virtual = MT_Pixel"], +} + + +class DeviceLinesUnitTests(unittest.TestCase): + def test_values_in_file_order_trimmed_and_raw(self): + text = "DEVICE: iOS, Virtual = iPhone 16 Pro, iPhone SE\n Device : android, physical \nsteps" + self.assertEqual(sources.device_lines(text), + ["iOS, Virtual = iPhone 16 Pro, iPhone SE", "android, physical"]) + + def test_header_allows_blank_comment_and_other_keys(self): + text = "\n# comment\nMODE: once\nCLEAR_DATA: first\n\nDEVICE: ios, physical\nREINSTALL_APP: true\nDEVICE: x\n" + self.assertEqual(sources.device_lines(text), ["ios, physical", "x"]) + + def test_header_stops_at_first_non_header_line(self): + self.assertEqual(sources.device_lines("Tap Start.\nDEVICE: ios, physical\n"), []) + self.assertEqual(sources.device_lines("DEVICE: a\nNOTE: hi\nDEVICE: b\n"), ["a"]) + self.assertEqual(sources.device_lines("DEVICE ios\nDEVICE: b\n"), []) + + def test_no_device_line_or_empty_file(self): + self.assertEqual(sources.device_lines("MODE: once\nsteps\n"), []) + self.assertEqual(sources.device_lines(""), []) + + def test_crlf_and_empty_value(self): + self.assertEqual(sources.device_lines("DEVICE: ios, physical\r\nDEVICE:\r\nsteps\r\n"), + ["ios, physical", ""]) + + def test_case_devices_dedupes_and_caches_by_blob_sha(self): + sources._device_cache.clear() + fetched = [] + + def fetch(sha): + fetched.append(sha) + return {"s1": b"DEVICE: ios, physical\n", "s2": b"steps\n"}[sha] + + self.assertEqual(sources.case_devices({"b": "s1", "a": "s1", "c": "s2"}, fetch), + {"a": ["ios, physical"], "b": ["ios, physical"], "c": []}) + self.assertEqual(sorted(fetched), ["s1", "s2"]) + self.assertEqual(sources.case_devices({"x": "s1"}, fetch), {"x": ["ios, physical"]}) + self.assertEqual(len(fetched), 2) + + def test_case_devices_is_none_when_a_file_cannot_be_read(self): + sources._device_cache.clear() + self.assertIsNone(sources.case_devices({"a": "s1", "b": "s2"}, + lambda sha: b"DEVICE: x" if sha == "s1" else None)) + + +class CaseDevicesApiTests(PluginCase): + """devices on the cases route, for both code hosts.""" + + def setUp(self): + super().setUp() + sources._device_cache.clear() + self.addCleanup(sources._device_cache.clear) + self.gs.add_repo(REPO, {"master": dict(DEVICE_CASE_FILES)}) + self.gh.add_repo(REPO, default="master", branches={"master": dict(DEVICE_CASE_FILES)}) + self.start_plugin() + + def gitea_blob_calls(self): + return [c for c in self.gs.calls if "/git/blobs/" in c[1]] + + def test_gitea_cases_carry_devices(self): + self.configure() + status, body = self.call("GET", f"/repos/{REPO}/cases?ref=master") + self.assertEqual(status, 200, body) + self.assertEqual(body["cases"], ["login", "onboarding", "plain", "twin"]) + self.assertEqual(body["devices"], DEVICES_WANTED) + # login and twin have the same content (one blob): 3 reads, not 4. + self.assertEqual(len(self.gitea_blob_calls()), 3) + status, again = self.call("GET", f"/repos/{REPO}/cases?ref=master") + self.assertEqual(again["devices"], DEVICES_WANTED) + self.assertEqual(len(self.gitea_blob_calls()), 3, "second listing is served from the blob cache") + + def test_gitea_unreadable_file_leaves_devices_out(self): + self.configure() + self.gs.fail_blobs = True + status, body = self.call("GET", f"/repos/{REPO}/cases?ref=master") + self.assertEqual(status, 200, body) + self.assertEqual(body["cases"], ["login", "onboarding", "plain", "twin"]) + self.assertNotIn("devices", body) + + def test_branch_without_cases_has_empty_devices(self): + self.configure() + self.gs.add_repo(REPO, {"master": {"README.md": "x", ANDROID_RECIPE: ANDROID_OK}}) + status, body = self.call("GET", f"/repos/{REPO}/cases?ref=master") + self.assertEqual((body["cases"], body["devices"]), ([], {})) + + def test_build_request_does_not_read_instruction_files(self): + self.configure() + status, body = self.call("POST", "/builds", {"repo": REPO, "branch": "master", "platforms": ["android"], + "cases": [], "request_id": "build_dev000000000"}) + self.assertEqual(status, 201, body) + self.assertEqual(self.gitea_blob_calls(), []) + + def test_github_cases_carry_devices(self): + self.configure_gh() + status, body = self.call("GET", f"/repos/{REPO}/cases?ref=master") + self.assertEqual(status, 200, body) + self.assertEqual(body["devices"], DEVICES_WANTED) + self.assertEqual(len(self.gh.calls("GET", "/git/blobs/")), 3) + self.call("GET", f"/repos/{REPO}/cases?ref=master") + self.assertEqual(len(self.gh.calls("GET", "/git/blobs/")), 3) + + def test_github_unreadable_file_leaves_devices_out(self): + self.configure_gh() + self.gh.fail_blobs = True + status, body = self.call("GET", f"/repos/{REPO}/cases?ref=master") + self.assertEqual(status, 200, body) + self.assertEqual(body["cases"], ["login", "onboarding", "plain", "twin"]) + self.assertNotIn("devices", body) + + def test_github_truncated_tree_uses_contents_answers(self): + self.configure_gh() + self.gh.add_repo("ci-bot/Trunc-App", default="master", branches={"master": dict(DEVICE_CASE_FILES)}, + truncated=True) + status, body = self.call("GET", "/repos/ci-bot/Trunc-App/cases?ref=master") + self.assertEqual(status, 200, body) + self.assertEqual(body["devices"], DEVICES_WANTED) + self.assertEqual(self.gh.calls("GET", "/git/blobs/"), [], "the contents answers already hold the files") + + class FixtureCase(PluginCase): """PluginCase plus fixture git repos served as file:// clones (no git server)."""