Files
nessarandClaude Opus 5.5 400ac154f9
CI / core (pull_request) Successful in 1m18s
Ignore the files Gitea lists when it creates a draft (#61)
On a private test repository, a stable whose tag only existed locally
stopped before publishing: Gitea 28.1 lists unrelated files in its reply
to the draft creation when it does not have the tag yet, and the command
tried to remove them (HTTP 404, nothing published). A new draft has no
files, so only a draft found by its tag is emptied. Record the stable
run: refusals, an older main commit, a local-only tag, reruns, the next
beta and the channel queries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:44:45 +01:00

303 lines
14 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Refusals, numbering and reruns of scripts/publish, against a fake Gitea and a temporary Git repository.
Run: python3 scripts/test_publish.py (Python 3.11+, git, OpenSSL 3).
"""
import base64
import copy
import hashlib
import importlib.machinery
import importlib.util
import itertools
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
loader = importlib.machinery.SourceFileLoader("publish", str(Path(__file__).with_name("publish")))
pb = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
loader.exec_module(pb)
class FakeGitea:
"""The Releases API as scripts/publish uses it. Tags are created in the current repository."""
def __init__(self):
self.releases, self.blobs, self.ids = [], {}, itertools.count(1)
self.failing_upload, self.tag_conflict, self.checks = None, False, {}
self.lose = None # (method, path prefix) of the next call whose reply is lost once it took effect.
def call(self, method, path, body=None, data=None):
reply = self.handle(method, path, body, data)
if self.lose and method == self.lose[0] and path.startswith(self.lose[1]):
self.lose = None
raise TimeoutError("reply lost")
return reply
def handle(self, method, path, body, data):
parts = path.split("?")[0].split("/")[1:]
if method == "GET" and parts[0] == "commits":
return 200, {"state": self.checks.get(parts[1], "success")}
if method == "GET" and parts[:2] == ["releases", "tags"]:
found = [r for r in self.releases if r["tag_name"] == parts[2]]
return (200, copy.deepcopy(found[0])) if found else (404, "release not found")
if method == "POST" and parts == ["tags"]:
if self.tag_conflict or pb.tagged_commit(body["tag_name"]):
return 409, "tag already exists"
subprocess.run(["git", "tag", body["tag_name"], body["target"]], check=True)
return 201, {}
if method == "POST" and parts == ["releases"]:
release = {"id": next(self.ids), "tag_name": body["tag_name"], "target": body.get("target_commitish"),
"draft": body["draft"], "prerelease": body["prerelease"], "assets": []}
self.releases.append(release)
# Gitea 28.1 lists unrelated files in this reply when it does not have the tag yet.
return 201, {**copy.deepcopy(release), "assets": [{"id": 0, "name": "unrelated.png"}]}
release = next(r for r in self.releases if r["id"] == int(parts[1]))
if method == "POST":
name = path.split("name=")[1]
if name == self.failing_upload:
return 500, "connection reset"
url = f"https://gitea.test/{release['tag_name']}/{name}"
self.blobs[url] = data
release["assets"].append({"id": next(self.ids), "name": name, "browser_download_url": url})
return 201, {}
if method == "DELETE":
if all(a["id"] != int(parts[3]) for a in release["assets"]):
return 404, "not found"
release["assets"] = [a for a in release["assets"] if a["id"] != int(parts[3])]
return 204, None
if method == "PATCH":
release.update(body)
return 200, copy.deepcopy(release)
def fetch(self, url):
return self.blobs[url]
class Publish(unittest.TestCase):
def setUp(self):
work = tempfile.TemporaryDirectory()
self.addCleanup(work.cleanup)
self.addCleanup(os.chdir, os.getcwd())
os.chdir(work.name)
self.key = Path(work.name) / "key.pem"
subprocess.run(["openssl", "genpkey", "-algorithm", "ED25519", "-out", self.key], check=True)
os.mkdir("repo")
os.chdir("repo")
subprocess.run(["git", "init", "-q"], check=True)
self.gitea, self.builds = FakeGitea(), []
def commit(self, target="1.1.0", branches=("develop",)):
Path("Cargo.toml").write_text(f'[workspace.package]\nversion = "{target}"\n')
subprocess.run(["git", "add", "Cargo.toml"], check=True)
subprocess.run(["git", "-c", "user.name=CI", "-c", "user.email=ci@test", "commit", "-q",
"--allow-empty", "-m", "change"], check=True)
for branch in branches:
subprocess.run(["git", "update-ref", f"refs/remotes/origin/{branch}", "HEAD"], check=True)
return pb.git("rev-parse", "HEAD")
def build(self, commit, version, out, key):
"""Sign a stand-in release the way scripts/package does."""
self.builds.append(version)
out.mkdir()
channel = pb.channel(version)
package = out / pb.package_file(version)
package.write_bytes(f"{commit} {version}".encode())
(out / f"ArenaTracker-{channel}-Setup.exe").write_bytes(b"setup")
manifest = out / f"release-{channel}.json"
manifest.write_text(json.dumps({
"app": "ArenaTracker", "target": "win-x64", "channel": channel, "version": version,
"commit": commit, "package": package.name,
"sha256": base64.b64encode(hashlib.sha256(package.read_bytes()).digest()).decode(),
}) + "\n")
subprocess.run(["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", key, "-in", manifest,
"-out", manifest.with_suffix(".sig")], check=True)
def beta(self, commit):
pb.release_beta(self.gitea, commit, self.build, self.key)
def stable(self, commit):
pb.release_stable(self.gitea, commit, self.build, self.key)
def published(self):
"""Tag → commit of each Release a client sees, each checked complete and signed."""
seen = {}
for release in self.gitea.releases:
if not release["draft"]:
commit = pb.tagged_commit(release["tag_name"])
# Gitea creates a tag missing on its side at the target, else on the default branch.
self.assertEqual(release["target"], commit)
pb.check(self.gitea, release, commit, release["tag_name"][1:], self.key)
seen[release["tag_name"]] = commit
return seen
def test_each_push_gets_the_next_number_and_a_rerun_reuses_it(self):
first = self.commit()
self.beta(first)
self.beta(first)
self.commit()
last = self.commit()
self.beta(last) # One push bringing two commits.
self.assertEqual(self.published(), {"v1.1.0-beta.1": first, "v1.1.0-beta.2": last})
self.assertEqual(self.builds, ["1.1.0-beta.1", "1.1.0-beta.2"])
def test_a_commit_whose_checks_did_not_pass_publishes_nothing(self):
commit = self.commit()
self.gitea.checks[commit] = "pending"
with self.assertRaisesRegex(ValueError, "contrôles CI"):
self.beta(commit)
self.assertEqual((self.builds, pb.git("tag")), ([], ""))
def test_a_commit_not_pushed_to_develop_publishes_nothing(self):
self.commit()
local = self.commit(branches=())
with self.assertRaisesRegex(ValueError, "pas dans develop"):
self.beta(local)
self.assertEqual((self.builds, pb.git("tag")), ([], ""))
def test_an_older_commit_published_last_publishes_nothing(self):
older = self.commit()
newer = self.commit()
self.beta(newer)
self.beta(older)
self.assertEqual(self.published(), {"v1.1.0-beta.1": newer})
self.assertEqual(self.builds, ["1.1.0-beta.1"])
def test_a_rerun_completes_an_interrupted_publication_under_its_number(self):
interrupted = self.commit()
self.gitea.failing_upload = "release-beta.sig"
with self.assertRaisesRegex(ValueError, "500"):
self.beta(interrupted)
self.assertEqual(self.published(), {})
self.gitea.failing_upload = None
later = self.commit()
self.beta(later)
self.beta(interrupted)
self.assertEqual(self.published(), {"v1.1.0-beta.1": interrupted, "v1.1.0-beta.2": later})
self.assertEqual(len(self.gitea.releases), 2)
def test_a_new_cycle_starts_its_own_series(self):
old = self.commit("1.1.0")
self.beta(old)
new = self.commit("1.2.0")
self.beta(new)
self.assertEqual(self.published(), {"v1.1.0-beta.1": old, "v1.2.0-beta.1": new})
def test_a_released_target_publishes_nothing(self):
commit = self.commit()
subprocess.run(["git", "tag", "v1.1.0", commit], check=True)
with self.assertRaisesRegex(ValueError, "déjà publiée"):
self.beta(commit)
self.assertEqual((self.builds, self.gitea.releases), ([], []))
def test_a_failed_build_publishes_nothing(self):
def broken(*args):
raise subprocess.CalledProcessError(1, "scripts/package")
with self.assertRaises(subprocess.CalledProcessError):
pb.release_beta(self.gitea, self.commit(), broken, self.key)
self.assertEqual((pb.git("tag"), self.gitea.releases), ("", []))
def test_a_number_taken_meanwhile_is_not_shared(self):
self.gitea.tag_conflict = True
with self.assertRaisesRegex(ValueError, "409"):
self.beta(self.commit())
self.assertEqual(self.gitea.releases, [])
def test_a_different_published_release_is_never_replaced(self):
commit = self.commit()
self.beta(commit)
self.gitea.blobs["https://gitea.test/v1.1.0-beta.1/ArenaTracker-1.1.0-beta.1-beta-full.nupkg"] = b"other"
with self.assertRaisesRegex(ValueError, "rien n’est remplacé"):
self.beta(commit)
self.assertEqual(self.builds, ["1.1.0-beta.1"])
def test_a_stable_is_published_at_a_main_commit_that_need_not_be_the_last(self):
released = self.commit(branches=("develop", "main"))
self.commit(branches=("develop", "main"))
self.stable(released)
self.stable(released)
self.assertEqual(self.published(), {"v1.1.0": released})
self.assertEqual(self.builds, ["1.1.0"])
self.assertEqual({asset["name"] for asset in self.gitea.releases[0]["assets"]}, {
"ArenaTracker-stable-Setup.exe", "release-stable.json", "release-stable.sig",
"ArenaTracker-1.1.0-stable-full.nupkg"})
def test_a_commit_only_on_develop_publishes_no_stable(self):
self.commit(branches=("develop", "main"))
with self.assertRaisesRegex(ValueError, "pas dans main"):
self.stable(self.commit())
self.assertEqual((self.builds, pb.git("tag")), ([], ""))
def test_a_prerelease_or_invalid_version_publishes_no_stable(self):
for version in ("1.1.0-beta.1", "1.1", "01.1.0"):
with self.subTest(version), self.assertRaisesRegex(ValueError, "X.Y.Z"):
self.stable(self.commit(version, ("main",)))
self.assertEqual((self.builds, pb.git("tag")), ([], ""))
def test_a_main_commit_whose_checks_did_not_pass_publishes_no_stable(self):
commit = self.commit(branches=("main",))
self.gitea.checks[commit] = "failure"
with self.assertRaisesRegex(ValueError, "contrôles CI"):
self.stable(commit)
self.assertEqual((self.builds, pb.git("tag")), ([], ""))
def test_a_stable_tag_is_never_moved(self):
first = self.commit(branches=("main",))
self.stable(first)
with self.assertRaisesRegex(ValueError, "ne se déplace pas"):
self.stable(self.commit(branches=("main",)))
self.assertEqual(self.published(), {"v1.1.0": first})
def test_a_published_stable_marked_as_prerelease_is_not_reused(self):
commit = self.commit(branches=("main",))
self.stable(commit)
self.gitea.releases[0]["prerelease"] = True
with self.assertRaisesRegex(ValueError, "mal marquée"):
self.stable(commit)
def test_a_rerun_completes_an_interrupted_stable(self):
commit = self.commit(branches=("main",))
self.gitea.failing_upload = "release-stable.sig"
with self.assertRaisesRegex(ValueError, "500"):
self.stable(commit)
self.assertEqual(self.published(), {})
self.gitea.failing_upload = None
self.stable(commit)
self.assertEqual(self.published(), {"v1.1.0": commit})
self.assertEqual(len(self.gitea.releases), 1)
def test_a_rerun_checks_a_creation_whose_reply_was_lost(self):
commits = {}
for target, lost in (("1.1.0", ("POST", "/tags")), ("1.2.0", ("POST", "/releases")),
("1.3.0", ("PATCH", "/releases"))):
commits[f"v{target}"] = self.commit(target, ("main",))
self.gitea.lose = lost
with self.assertRaises(TimeoutError):
self.stable(commits[f"v{target}"])
self.stable(commits[f"v{target}"])
self.assertEqual(self.published(), commits)
self.assertEqual(len(self.gitea.releases), 3)
self.assertEqual(self.builds, ["1.1.0", "1.1.0", "1.2.0", "1.2.0", "1.3.0"])
def test_the_stable_leaves_its_betas_and_closes_their_cycle(self):
commit = self.commit(branches=("develop", "main"))
self.beta(commit)
self.stable(commit)
self.assertEqual(self.published(), {"v1.1.0-beta.1": commit, "v1.1.0": commit})
with self.assertRaisesRegex(ValueError, "déjà publiée"):
self.beta(self.commit())
def test_a_build_that_is_not_the_tagged_version_publishes_nothing(self):
def other_commit(commit, version, out, key):
self.build("0" * 40, version, out, key)
with self.assertRaisesRegex(ValueError, "La compilation"):
pb.release_stable(self.gitea, self.commit(branches=("main",)), other_commit, self.key)
self.assertEqual((pb.git("tag"), self.gitea.releases), ("", []))
if __name__ == "__main__":
unittest.main()