185 lines
9.5 KiB
Python
185 lines
9.5 KiB
Python
import json
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from failure import Failure
|
|
from test_env import isolated_env
|
|
from chunk_pr.main import step
|
|
|
|
TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr"
|
|
GITHUB = "git@github.com:me/project.git"
|
|
GITEA = "ssh://git@gitea.example.org:22/me/project.git"
|
|
HEAD = "c0ffee"
|
|
PUSH = ["git", "push", "--quiet", "--set-upstream", "origin", "item-7"]
|
|
GH_LIST = ["gh", "pr", "list", "--head", "item-7", "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"]
|
|
TEA_LIST = ["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]
|
|
GH_SETTINGS = ["gh", "repo", "view", "--json", "mergeCommitAllowed,rebaseMergeAllowed,squashMergeAllowed"]
|
|
TEA_SETTINGS = ["tea", "api", "repos/{owner}/{repo}"]
|
|
|
|
|
|
class Checkout:
|
|
"""A fake run in a checkout of branch item-7 at commit HEAD, cloned from the GitHub or Gitea origin it is given, with main as origin's default branch.
|
|
|
|
Pull request #12 from item-7 is open at HEAD from the start where it is given open=True, and otherwise once a create has run. The repository allows the merge methods in allowed, by the forge's setting names: a merge commit unless given others. It records every command run, and fails the other forge's commands."""
|
|
|
|
def __init__(self, origin: str, open: bool, allowed: tuple[str, ...] = ("mergeCommitAllowed", "allow_merge_commits")):
|
|
self.github = origin == GITHUB
|
|
self.open = open
|
|
self.allowed = allowed
|
|
self.ran: list[list[str]] = []
|
|
self.answers: dict[tuple[str, ...], str | Failure] = {
|
|
("git", "remote", "get-url", "origin"): f"{origin}\n",
|
|
("git", "symbolic-ref", "--short", "HEAD"): "item-7\n",
|
|
("git", "rev-parse", "HEAD"): f"{HEAD}\n",
|
|
("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"): "origin/main\n",
|
|
}
|
|
|
|
def __call__(self, command: list[str]) -> str | Failure:
|
|
self.ran.append(command)
|
|
if command[0] == ("tea" if self.github else "gh"):
|
|
return Failure(f"{command[0]} on the wrong forge")
|
|
if tuple(command) in self.answers:
|
|
return self.answers[tuple(command)]
|
|
if command[2:3] == ["create"]:
|
|
self.open = True
|
|
if command == GH_LIST:
|
|
return f"12\t{HEAD}\tfalse\n" if self.open else ""
|
|
if command == TEA_LIST:
|
|
return json.dumps([{"number": 12, "head": {"ref": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else [])
|
|
if command in (GH_SETTINGS, TEA_SETTINGS):
|
|
return json.dumps({setting: True for setting in self.allowed})
|
|
return ""
|
|
|
|
def acted(self) -> list[list[str]]:
|
|
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
|
|
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS]
|
|
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
|
|
|
|
|
|
class Open(unittest.TestCase):
|
|
def test_github_pushes_and_opens_a_draft_into_the_default_branch(self):
|
|
checkout = Checkout(GITHUB, open=False)
|
|
opened = step(["open", "ABC-1 - Do it", "The body."], checkout)
|
|
self.assertEqual(checkout.acted(), [PUSH, ["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "ABC-1 - Do it", "--body", "The body."]])
|
|
self.assertEqual(opened, "Opened draft pull request #12.")
|
|
|
|
def test_gitea_opens_a_draft_with_tea(self):
|
|
checkout = Checkout(GITEA, open=False)
|
|
self.assertEqual(step(["open", "Do it"], checkout), "Opened draft pull request #12.")
|
|
self.assertEqual(checkout.acted(), [PUSH, ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--description", ""]])
|
|
|
|
def test_an_open_pull_request_is_kept(self):
|
|
checkout = Checkout(GITEA, open=True)
|
|
self.assertEqual(step(["open", "Do it"], checkout), "Pull request #12 is open already.")
|
|
self.assertEqual(checkout.acted(), [PUSH])
|
|
|
|
def test_on_the_default_branch_it_refuses_and_pushes_nothing(self):
|
|
checkout = Checkout(GITEA, open=False)
|
|
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
|
|
self.assertIsInstance(step(["open", "Do it"], checkout), Failure)
|
|
self.assertEqual(checkout.acted(), [])
|
|
|
|
def test_a_title_of_more_than_one_line_or_a_second_body_is_refused_before_anything_runs(self):
|
|
for argv in (["open", "Do it\nand more"], ["open", " "], ["open", "Do it", "Body", "More"]):
|
|
with self.subTest(argv):
|
|
checkout = Checkout(GITHUB, open=False)
|
|
self.assertIsInstance(step(argv, checkout), Failure)
|
|
self.assertEqual(checkout.ran, [])
|
|
|
|
def test_a_failed_listing_after_the_create_is_returned(self):
|
|
checkout = Checkout(GITHUB, open=False)
|
|
checkout.answers[("gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--body", "")] = Failure("gh pr create: done")
|
|
self.assertEqual(step(["open", "Do it"], checkout), Failure("gh pr create: done"))
|
|
checkout = Checkout(GITHUB, open=False)
|
|
listings = iter(["", Failure("gh pr list: offline")])
|
|
original = checkout.__call__
|
|
checkout_call = lambda command: next(listings) if command == GH_LIST else original(command)
|
|
self.assertEqual(step(["open", "Do it"], checkout_call), Failure("gh pr list: offline"))
|
|
|
|
|
|
class Ready(unittest.TestCase):
|
|
def test_github_marks_it_ready(self):
|
|
checkout = Checkout(GITHUB, open=True)
|
|
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
|
|
self.assertEqual(checkout.acted(), [["gh", "pr", "ready", "12"]])
|
|
|
|
def test_gitea_marks_it_ready_with_tea(self):
|
|
checkout = Checkout(GITEA, open=True)
|
|
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
|
|
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--ready"]])
|
|
|
|
def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self):
|
|
checkout = Checkout(GITHUB, open=False)
|
|
ready = step(["ready"], checkout)
|
|
self.assertIsInstance(ready, Failure)
|
|
self.assertIn("item-7", ready.reason)
|
|
self.assertEqual(checkout.acted(), [])
|
|
|
|
def test_a_failed_ready_or_git_call_is_returned(self):
|
|
checkout = Checkout(GITEA, open=True)
|
|
checkout.answers[("tea", "pulls", "edit", "12", "--ready")] = Failure("tea pulls edit: denied")
|
|
self.assertEqual(step(["ready"], checkout), Failure("tea pulls edit: denied"))
|
|
checkout = Checkout(GITEA, open=True)
|
|
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = Failure("git symbolic-ref: HEAD is detached")
|
|
self.assertEqual(step(["ready"], checkout), Failure("git symbolic-ref: HEAD is detached"))
|
|
self.assertEqual(checkout.acted(), [])
|
|
|
|
|
|
class Merge(unittest.TestCase):
|
|
def test_without_the_gate_passed_it_refuses_before_anything_runs(self):
|
|
checkout = Checkout(GITHUB, open=True)
|
|
self.assertIsInstance(step(["merge"], checkout), Failure)
|
|
self.assertEqual(checkout.ran, [])
|
|
|
|
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
|
|
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
|
|
self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (merge).")
|
|
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
|
|
|
def test_github_without_merge_commits_rebases(self):
|
|
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed"))
|
|
step(["merge", "--gate-passed"], checkout)
|
|
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
|
|
|
|
def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self):
|
|
checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge"))
|
|
self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (fast-forward-only).")
|
|
self.assertEqual(checkout.acted(), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
|
|
|
|
def test_a_repository_allowing_no_known_method_is_refused_unmerged(self):
|
|
checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",))
|
|
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
|
|
self.assertEqual(checkout.acted(), [])
|
|
|
|
def test_a_forge_failure_is_returned(self):
|
|
checkout = Checkout(GITHUB, open=True)
|
|
checkout.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved")
|
|
self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("gh pr merge: head moved"))
|
|
checkout = Checkout(GITHUB, open=True)
|
|
checkout.answers[tuple(GH_SETTINGS)] = "not json"
|
|
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
|
|
|
|
def test_a_failed_settings_read_is_returned_unmerged(self):
|
|
for origin, settings in ((GITHUB, GH_SETTINGS), (GITEA, TEA_SETTINGS)):
|
|
with self.subTest(origin):
|
|
checkout = Checkout(origin, open=True)
|
|
checkout.answers[tuple(settings)] = Failure("settings: denied")
|
|
self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("settings: denied"))
|
|
self.assertEqual(checkout.acted(), [])
|
|
|
|
|
|
class Launcher(unittest.TestCase):
|
|
def test_help_exits_0_and_a_wrong_step_exits_1(self):
|
|
self.assertEqual(subprocess.run([str(TOOL), "--help"], capture_output=True, env=isolated_env()).returncode, 0)
|
|
wrong = subprocess.run([str(TOOL), "close"], capture_output=True, encoding="utf-8", env=isolated_env())
|
|
self.assertEqual((wrong.returncode, wrong.stdout), (1, ""))
|
|
self.assertIn("usage", wrong.stderr)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|