import base64 import dataclasses import pathlib import re import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) from project_config.settings import Epic, Finish from do_epic.backend.contract import EpicStoreContract from failure import Failure from do_epic.backend.jira import JiraEpic from adf_codec.convert import Refused from do_epic.repo_pick import REVIEW_LABEL from do_epic.backend.jira_start import Start SITE = "https://acme.atlassian.net" EPIC = Epic(SITE, "ABC-12") AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode() EPIC_URL = f"{SITE}/rest/api/3/issue/ABC-12?fields=summary" ISSUE_TYPES = f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes" SEARCH = f"{SITE}/rest/api/3/search/jql" ISSUES = f"{SITE}/rest/api/3/issue" RANK = f"{SITE}/rest/agile/1.0/issue/rank" TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}} DONE = {"name": "Done", "statusCategory": {"key": "done"}} IN_PROGRESS = {"name": "In Progress", "statusCategory": {"key": "indeterminate"}} MYSELF = f"{SITE}/rest/api/3/myself" ME = {"accountId": "712020:do-epic", "displayName": "Do Epic"} ACTIVE_SPRINTS = f"{SITE}/rest/agile/1.0/board/6/sprint?state=active" SPRINT_ISSUES = f"{SITE}/rest/agile/1.0/sprint/77/issue" TRANSITIONS = f"{ISSUES}/ABC-12/transitions" EPIC_COMMENT = f"{ISSUES}/ABC-12/comment" EPIC_STATUS = f"{ISSUES}/ABC-12?fields=status" TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10002", "name": "Feature", "subtask": False}, {"id": "10004", "name": "Chore", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]} def to_adf(markdown: str) -> dict[str, object]: """Stands in for the adf-codec shim: one paragraph holding the markdown.""" return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": markdown}]}]} def to_markdown(documents: list[dict[str, object]]) -> list[str]: return [document["content"][0]["content"][0]["text"] + "\n" for document in documents] # type: ignore[index] @dataclasses.dataclass class FakeJira: """Jira Cloud's REST API as JiraEpic calls it. It holds issues as Jira answers them, in rank order. A search answers two issues a page, with only the fields it asks for. A call whose method and URL are in answers gets the answer held there instead.""" issues: list[dict[str, object]] = dataclasses.field(default_factory=list) answers: dict[tuple[str, str], object] = dataclasses.field(default_factory=dict) calls: list[tuple[str, str]] = dataclasses.field(default_factory=list) comments: dict[str, list[object]] = dataclasses.field(default_factory=dict) # The issue type of each issue created, as the request names it. filed_as: list[object] = dataclasses.field(default_factory=list) # The ID of each transition made. transitioned: list[str] = dataclasses.field(default_factory=list) # The transitions Jira offers an issue that isn't done. workflow: list[dict[str, object]] = dataclasses.field(default_factory=lambda: [{"id": "31", "name": "Mark as done", "to": DONE}]) # The epic's own status, which the transition "Mark as done" moves to DONE. epic_status: dict[str, object] = dataclasses.field(default_factory=lambda: dict(TO_DO)) # The active sprints of board 6, and the issues each request added to sprint 77. sprints: list[object] = dataclasses.field(default_factory=lambda: [{"id": 77, "name": "Sprint 9", "state": "active"}]) sprinted: list[object] = dataclasses.field(default_factory=list) def __call__(self, method: str, url: str, authorization: str, body: object) -> object: self.calls.append((method, url)) if authorization != AUTHORIZATION: return Failure("Jira answered 401") if (method, url) in self.answers: return self.answers[method, url] if method == "GET" and url == EPIC_URL: return {"key": "ABC-12"} if method == "GET" and url == EPIC_STATUS: return {"key": "ABC-12", "fields": {"status": self.epic_status}} if method == "GET" and url == TRANSITIONS: return {"transitions": [] if self.epic_status == DONE else [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "21", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}}]} if method == "POST" and url == TRANSITIONS: assert body == {"transition": {"id": "31"}}, body self.epic_status = DONE return None if method == "POST" and url == EPIC_COMMENT: assert isinstance(body, dict) self.comments.setdefault("ABC-12", []).append(body["body"]) return {"id": "1"} if method == "GET" and url == ISSUE_TYPES: return TYPES if method == "POST" and url == SEARCH: return self.page(body) if method == "GET" and (held := next((issue for issue in self.issues if url.startswith(f"{ISSUES}/{issue['key']}?fields=")), None)): asked, _, properties = url.partition("?fields=")[2].partition("&properties=") return {"key": held["key"], "fields": {name: held["fields"][name] for name in asked.split(",")}} | ({"properties": {name: value for name, value in held.get("properties", {}).items() if name == properties}} if properties else {}) # type: ignore[index, attr-defined] if method == "GET" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)): return {"transitions": [] if held["fields"]["status"] == DONE else self.workflow} # type: ignore[index] if method == "POST" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)): assert isinstance(body, dict) held["fields"]["status"] = next(offer["to"] for offer in self.workflow if offer["id"] == body["transition"]["id"]) # type: ignore[index] self.transitioned.append(body["transition"]["id"]) return None if method == "GET" and url == MYSELF: return ME if method == "PUT" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/assignee"), None)): assert body == {"accountId": ME["accountId"]}, body held["fields"]["assignee"] = ME # type: ignore[index] return None if method == "GET" and url == ACTIVE_SPRINTS: return {"values": self.sprints} if method == "POST" and url == SPRINT_ISSUES: assert isinstance(body, dict) self.sprinted.append(body["issues"]) return None if method == "POST" and url == ISSUES: return self.created(body) if method == "PUT" and url == RANK: return self.ranked(body) if method == "POST" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/comment"), None)): assert isinstance(body, dict) self.comments.setdefault(str(held["key"]), []).append(body["body"]) return {"id": "1"} if method == "PUT" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}"), None)): assert isinstance(body, dict) if "properties" in body: [entry] = body["properties"] held.setdefault("properties", {})[entry["key"]] = entry["value"] # type: ignore[attr-defined] return None added = [change["add"] for change in body["update"]["labels"]] held["fields"]["labels"] = sorted({*held["fields"]["labels"], *added}) # type: ignore[index] return None return Failure(f"Jira answered 404 for {method} {url}") def page(self, body: object) -> object: assert isinstance(body, dict) matched = re.fullmatch(r'parent in \(("[A-Z]+-[0-9]+"(?:, "[A-Z]+-[0-9]+")*)\) ORDER BY Rank ASC', body["jql"]) if matched is None: return Failure("Jira answered 400: the JQL is not valid") parents = re.findall(r'"([A-Z]+-[0-9]+)"', matched[1]) found = [{"key": issue["key"], "fields": {name: value for name, value in issue["fields"].items() if name in body.get("fields", [])}, "properties": {name: value for name, value in issue.get("properties", {}).items() if name in body.get("properties", [])}} for issue in self.issues if issue["fields"]["parent"]["key"] in parents] # type: ignore[index, attr-defined] start = int(body.get("nextPageToken", 0)) return {"issues": found[start:start + 2]} | ({"nextPageToken": str(start + 2)} if start + 2 < len(found) else {}) def created(self, body: object) -> object: assert isinstance(body, dict) fields = body["fields"] parent = fields["parent"]["key"] kind = fields["issuetype"] if parent == "ABC-12" and fields["issuetype"] in [{"name": "Task"}, {"name": "Feature"}, {"name": "Chore"}] else {"id": "10003"} if any(issue["key"] == parent for issue in self.issues) else None if fields["project"] != {"key": "ABC"} or kind is None or fields["issuetype"] != kind: return Failure("Jira answered 400: the project, parent or issue type is not valid") self.filed_as.append(fields["issuetype"]) key = f"ABC-{len(self.issues) + 100}" # The links Jira makes as it creates the issue: the inward issue blocks the new one, which then reads "is blocked by" it. links = [{"id": "1", "type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": add["add"]["inwardIssue"]} for add in body.get("update", {}).get("issuelinks", []) if add["add"]["type"] == {"name": "Blocks"}] self.issues.append({"key": key, "fields": {"summary": fields["summary"], "description": fields.get("description"), "labels": fields["labels"], "assignee": None, "status": TO_DO, "parent": {"key": parent}, "issuelinks": links}, "properties": {entry["key"]: entry["value"] for entry in body["properties"]}}) return {"id": "1", "key": key} def ranked(self, body: object) -> object: """Moves the issue the body names to just before the other issue it names, and answers no body, as Jira does for a rank it made.""" assert isinstance(body, dict) [key], before = body["issues"], body["rankBeforeIssue"] moved = next(issue for issue in self.issues if issue["key"] == key) self.issues.remove(moved) self.issues.insert(next(place for place, issue in enumerate(self.issues) if issue["key"] == before), moved) return None def change(self, key: str, **fields: object) -> None: next(issue for issue in self.issues if issue["key"] == key)["fields"].update(fields) # type: ignore[union-attr] def person_files(self, summary: str) -> str: """Files a child issue as the Jira website does: with no issue property.""" key = f"ABC-{len(self.issues) + 100}" self.issues.append({"key": key, "fields": {"summary": summary, "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": {"key": "ABC-12"}, "issuelinks": []}}) return key def set_property(self, key: str, value: dict[str, object]) -> None: next(issue for issue in self.issues if issue["key"] == key).setdefault("properties", {})["plan-item"] = value # type: ignore[attr-defined, union-attr] class Case(unittest.TestCase): def setUp(self) -> None: folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) self.env_file = pathlib.Path(folder.name) / "jira.env" self.env_file.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n") self.env_file.chmod(0o600) self.jira = FakeJira() def new_store(self) -> JiraEpic: return JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Mark as done", "Done")) class JiraEpicContract(Case, EpicStoreContract): transition = "Mark as done" def assign(self, store: JiraEpic, key: str, name: str) -> None: # type: ignore[override] self.jira.change(key, assignee={"accountId": "5b10a2844c20165700ede21g", "displayName": name}) def account(self, store: JiraEpic) -> str: # type: ignore[override] return ME["displayName"] def comments_on(self, store: JiraEpic, key: str) -> list[str]: # type: ignore[override] return [to_markdown([document])[0].strip() for document in self.jira.comments.get(key, [])] # type: ignore[misc] def close(self, store: JiraEpic, key: str, status: str) -> None: # type: ignore[override] self.jira.change(key, status={"name": status, "statusCategory": {"key": "done"}}) def person_files(self, store: JiraEpic, summary: str) -> str: # type: ignore[override] return self.jira.person_files(summary) def score(self, store: JiraEpic, key: str, scores: dict[str, object]) -> None: # type: ignore[override] held = next(issue for issue in self.jira.issues if issue["key"] == key).get("properties", {}).get("plan-item", {}) # type: ignore[attr-defined, union-attr] self.jira.set_property(key, held | scores) def block(self, store: JiraEpic, key: str, blocker: str) -> None: # type: ignore[override] links = next(issue for issue in self.jira.issues if issue["key"] == key)["fields"]["issuelinks"] # type: ignore[index] links.append({"id": str(len(links) + 1), "type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}}) class Jira(Case): def test_closes_the_epic_by_the_transition_the_settings_name_after_the_summary(self) -> None: self.assertEqual(self.new_store().close("Shipped."), None) self.assertEqual(self.jira.calls[-3:], [("GET", TRANSITIONS), ("POST", EPIC_COMMENT), ("POST", TRANSITIONS)]) def test_posts_no_summary_on_an_epic_it_cannot_close(self) -> None: unnamed = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) wrong_status = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Start", "Done")) no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) unconverted = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it"), Finish("Mark as done", "Done")) for store, reason in ( (unnamed, "do-epic's settings name no transition to close an epic by: set `jira-finish-transition` and `jira-finish-status` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\""), (wrong_status, "ABC-12's transition 'Start' leads to the status 'In Progress', not to 'Done', which `jira-finish-status` names"), (unconverted, "cannot convert the summary to a Jira comment: adf-codec refused it"), ): self.assertEqual(store.close("Shipped."), Failure(reason)) refused = no_such.close("Shipped.") assert isinstance(refused, Failure) self.assertIn("ABC-12 has no transition 'Close' from its status", refused.reason) self.jira.answers[("GET", TRANSITIONS)] = Failure("Jira answered 503") self.assertEqual(self.new_store().close("Shipped."), Failure("cannot read ABC-12's transitions: Jira answered 503")) self.assertEqual((self.jira.comments, self.jira.epic_status), ({}, TO_DO)) def test_says_what_was_posted_where_the_comment_or_the_move_fails(self) -> None: self.jira.answers[("POST", EPIC_COMMENT)] = Failure("Jira answered 503") self.assertEqual(self.new_store().close("Shipped."), Failure("cannot comment on ABC-12: Jira answered 503")) self.assertEqual(self.jira.epic_status, TO_DO) del self.jira.answers[("POST", EPIC_COMMENT)] self.jira.answers[("POST", TRANSITIONS)] = Failure("Jira answered 503") self.assertEqual(self.new_store().close("Shipped."), Failure("posted the summary on ABC-12, but cannot move ABC-12 by 'Mark as done': Jira answered 503; close the epic in Jira rather than posting the summary again")) def test_scores_a_sub_task_of_a_child_but_no_issue_of_another_epic(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(key, str), key task = store.file(key, "Count them in the API.", "", ()) assert isinstance(task, str), task scores = {"L": 2, "E": 1, "I": 2, "S": 3} self.assertIsNone(store.set_scores(task, scores, "", "Scored.")) read = f"{ISSUES}/{key}?fields=parent&properties=plan-item" self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "XYZ-1"}}} refused = store.set_scores(key, scores, "", "Scored.") assert isinstance(refused, Failure), refused self.assertTrue(refused.reason.startswith("cannot read XYZ-1 to score its sub-task: "), refused.reason) for answer in ({"fields": {"parent": {"key": task}}}, {"fields": {"parent": {"key": 12}}}, {"fields": {}}, {"fields": "none"}, []): with self.subTest(answer=answer): self.jira.answers[("GET", read)] = answer self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"{key} is not one of the child issues of the epic ABC-12, so it cannot be scored")) self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "ABC-12"}}, "properties": []} self.assertIsNone(store.set_scores(key, scores, "", "Scored.")) def test_says_how_far_a_scoring_came_where_jira_fails(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(key, str), key scores = {"L": 2, "E": 1, "I": 2, "S": 3} read = f"{ISSUES}/{key}?fields=parent&properties=plan-item" self.jira.answers[("GET", read)] = Failure("Jira answered 503") self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"cannot read {key} to score it: Jira answered 503")) self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "ABC-12"}}, "properties": {"plan-item": "L 2"}} self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"{key}'s issue property plan-item is not a JSON object")) self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "ABC-12"}}, "properties": {"plan-item": {"L": "many"}}} refused = store.set_scores(key, scores, "", "Scored.") assert isinstance(refused, Failure), refused self.assertTrue(refused.reason.startswith(f"cannot score {key}: item {key}'s L 'many'"), refused.reason) self.assertEqual(self.jira.comments.get(key, []), []) del self.jira.answers[("GET", read)] self.jira.answers[("POST", f"{ISSUES}/{key}/comment")] = Failure("Jira answered 503") self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"cannot comment on {key} to tell its team the scores: Jira answered 503")) del self.jira.answers[("POST", f"{ISSUES}/{key}/comment")] self.jira.answers[("PUT", f"{ISSUES}/{key}")] = Failure("Jira answered 503") self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: Jira answered 503")) del self.jira.answers[("PUT", f"{ISSUES}/{key}")] # No scores were set while the comment failed, so the issue is still scored once Jira answers. self.assertIsNone(store.set_scores(key, scores, "", "Scored.")) def test_says_why_the_epics_status_cannot_be_read(self) -> None: for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), ({"fields": {"status": {"statusCategory": {"key": 3}}}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text")): self.jira.answers[("GET", EPIC_STATUS)] = answer self.assertEqual(self.new_store().closed(), Failure(reason)) def starting(self, start: Start = Start("Start", 6)) -> JiraEpic: """A store whose settings name start, on a workflow that has the transition Start to In Progress.""" self.jira.workflow.append({"id": "21", "name": "Start", "to": IN_PROGRESS}) return dataclasses.replace(self.new_store(), start=start) def test_starts_an_issue_by_the_transition_and_into_the_active_sprint_of_the_board_the_settings_name(self) -> None: store = self.starting() key = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(key, str) self.assertIsNone(store.start_issue(key)) self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ME, IN_PROGRESS)) # type: ignore[index] self.assertEqual((self.jira.transitioned, self.jira.sprinted), (["21"], [[key]])) def test_a_starting_sub_tasks_parent_joins_the_sprint_in_its_place(self) -> None: store = self.starting() child = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(child, str) task = store.file(child, "Count them in the api.", "", ()) assert isinstance(task, str) self.assertIsNone(store.start_issue(task)) self.assertEqual(self.jira.sprinted, [[child]]) self.assertEqual([issue["fields"]["status"] for issue in self.jira.issues], [TO_DO, IN_PROGRESS]) # type: ignore[index] def test_an_issue_past_the_start_keeps_its_status_and_one_someone_holds_keeps_its_holder(self) -> None: store = self.starting() key = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(key, str) review = {"name": "Code Review", "statusCategory": {"key": "indeterminate"}} ada = {"accountId": "5b10a2844c20165700ede21g", "displayName": "Ada Berg"} self.jira.change(key, status=review, assignee=ada) self.assertEqual(store.start_issue(key), "Ada Berg") self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ada, review)) # type: ignore[index] self.assertEqual((self.jira.transitioned, self.jira.sprinted), ([], [[key]])) self.assertNotIn(("GET", f"{ISSUES}/{key}/transitions"), self.jira.calls) def test_without_the_settings_a_start_only_assigns(self) -> None: store = self.starting(Start()) key = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(key, str) self.assertIsNone(store.start_issue(key)) self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ME, TO_DO)) # type: ignore[index] self.assertEqual(self.jira.calls[-2:], [("GET", MYSELF), ("PUT", f"{ISSUES}/{key}/assignee")]) def test_a_start_names_each_step_jira_did_not_take_and_makes_the_others(self) -> None: store = self.starting() key = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(key, str) transitions, assignee = f"{ISSUES}/{key}/transitions", f"{ISSUES}/{key}/assignee" for answers, reason in ( ({("GET", f"{ISSUES}/{key}?fields=assignee,status"): Failure("Jira answered 503")}, f"cannot read {key} to start it: Jira answered 503"), ({("GET", f"{ISSUES}/{key}?fields=assignee,status"): {"fields": {"assignee": None}}}, f"{key} is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"), ({("GET", MYSELF): Failure("Jira answered 503")}, f"cannot read which account do-epic works as, to assign {key}: Jira answered 503"), ({("GET", MYSELF): {"displayName": "Do Epic"}}, f"cannot assign {key}: Jira named no account ID for the account do-epic works as"), ({("GET", MYSELF): ["Do Epic"]}, f"cannot assign {key}: Jira named no account ID for the account do-epic works as"), ({("PUT", assignee): Failure("Jira answered 403")}, f"cannot assign {key}: Jira answered 403"), ({("GET", transitions): Failure("Jira answered 503")}, f"cannot read {key}'s transitions: Jira answered 503"), ({("GET", transitions): {"transitions": [{"id": "21"}]}}, f"Jira answered {key}'s transitions in a shape other than the one it documents"), ({("GET", transitions): {"transitions": [{"id": "31", "name": "Mark as done", "to": DONE}]}}, f"{key} has no transition 'Start' from its status 'To Do', only 'Mark as done' to 'Done': set `jira-start-transition` to a transition the issue has before its work starts"), ({("GET", transitions): {"transitions": [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "41", "name": "Wait", "to": TO_DO}]}}, f"{key} has no transition 'Start' from its status 'To Do', only 'Mark as done' to 'Done' and 'Wait' to 'To Do': set `jira-start-transition` to a transition the issue has before its work starts"), ({("GET", transitions): {"transitions": []}}, f"{key} has no transition 'Start' from its status 'To Do', nor any other the account may make"), ({("POST", transitions): Failure("Jira answered 400")}, f"cannot move {key} by 'Start': Jira answered 400"), ({("GET", ACTIVE_SPRINTS): Failure("Jira answered 400")}, f"cannot read the active sprint of board 6, which `jira-sprint-board` names: Jira answered 400"), ({("GET", ACTIVE_SPRINTS): {"values": [{"name": "Sprint 9"}]}}, "Jira answered board 6's sprints in a shape other than the one it documents"), ({("GET", ACTIVE_SPRINTS): [{"id": 77}]}, "Jira answered board 6's sprints in a shape other than the one it documents"), ({("GET", ACTIVE_SPRINTS): {"values": "Sprint 9"}}, "Jira answered board 6's sprints in a shape other than the one it documents"), ({("GET", ACTIVE_SPRINTS): {"values": []}}, f"board 6, which `jira-sprint-board` names, has no active sprint, so {key} doesn't join a sprint"), ({("GET", ACTIVE_SPRINTS): {"values": [{"id": 77}, {"id": 78}]}}, f"board 6, which `jira-sprint-board` names, has 2 active sprints, so {key} doesn't join a sprint"), ({("POST", SPRINT_ISSUES): Failure("Jira answered 403")}, f"cannot add {key} to the active sprint of board 6: Jira answered 403"), ): with self.subTest(reason=reason): self.jira.change(key, status=TO_DO, assignee=None) self.jira.answers, self.jira.sprinted = answers, [] self.assertEqual(store.start_issue(key), Failure(reason)) self.jira.answers = {("PUT", assignee): Failure("Jira answered 403")} self.jira.change(key, status=TO_DO, assignee=None) store.start_issue(key) self.assertEqual((self.jira.issues[0]["fields"]["status"], self.jira.sprinted), (IN_PROGRESS, [[key]])) # type: ignore[index] def test_a_start_that_fails_twice_on_an_issue_someone_holds_names_both_steps_and_the_holder(self) -> None: store = self.starting() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.change(key, assignee={"accountId": "ada", "displayName": "Ada Berg"}) self.jira.answers = {("POST", f"{ISSUES}/{key}/transitions"): Failure("Jira answered 400"), ("POST", SPRINT_ISSUES): Failure("Jira answered 403")} self.assertEqual(store.start_issue(key), Failure(f"cannot move {key} by 'Start': Jira answered 400; cannot add {key} to the active sprint of board 6: Jira answered 403; {key} stays assigned to Ada Berg")) self.jira.answers = {("GET", MYSELF): Failure("Jira answered 503"), ("POST", SPRINT_ISSUES): Failure("Jira answered 403")} self.assertEqual(store.start_issue(key), Failure(f"cannot read which account do-epic works as, to assign {key}: Jira answered 503; cannot add {key} to the active sprint of board 6: Jira answered 403")) self.jira.change(key, assignee=ME) self.jira.answers = {("POST", SPRINT_ISSUES): Failure("Jira answered 403")} self.assertEqual(store.start_issue(key), Failure(f"cannot add {key} to the active sprint of board 6: Jira answered 403")) def test_a_start_says_which_issue_jira_cannot_read_and_refuses_one_outside_the_epic(self) -> None: store = self.starting() child = store.file("ABC-12", "Count the runs.", "", ()) task = store.file(child, "Count them in the api.", "", ()) self.jira.issues.append({"key": "ABC-61", "fields": {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": None, "issuelinks": []}}) self.assertEqual(store.start_issue("ABC-61"), Failure("ABC-61 is not one of the child issues of the epic ABC-12, so it cannot be started")) self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] = Failure("Jira answered 503") self.assertEqual(store.start_issue(task), Failure(f"cannot read {task} to start it: Jira answered 503")) del self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] self.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent,status")] = Failure("Jira answered 503") self.assertEqual(store.start_issue(task), Failure(f"cannot read {child} to start its sub-task: Jira answered 503")) def test_moves_an_issue_by_the_transition_that_leads_to_the_status_named_in_any_case(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) review = {"name": "Code Review", "statusCategory": {"key": "indeterminate"}} self.jira.workflow = [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "51", "name": "Ask for review", "to": review}] self.assertIsNone(store.move_issue(key, "code review")) self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["51"], review)) # type: ignore[index] self.assertIsNone(store.move_issue(key, "Code Review")) self.assertEqual(self.jira.transitioned, ["51"]) def test_moves_an_issue_by_the_transition_named_in_any_case_and_answers_the_status_it_leads_to(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) ready = {"name": "Release Ready", "statusCategory": {"key": "indeterminate"}} self.jira.workflow = [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "61", "name": "Ready for release", "to": ready}] self.assertEqual(store.move_issue_by(key, "ready for release", ("Teach & Learn", "RELEASE READY")), "Release Ready") self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["61"], ready)) # type: ignore[index] def test_an_issue_already_at_a_status_the_transition_may_lead_to_stays_as_it_is(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.issues[0]["fields"]["status"] = {"name": "Release Ready", "statusCategory": {"key": "indeterminate"}} # type: ignore[index] self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done", "release ready")), "Release Ready") self.assertEqual(self.jira.transitioned, []) def test_a_transition_that_leads_to_another_status_than_those_asked_for_is_not_made(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.assertEqual(store.move_issue_by(key, "Mark as done", ("Release Ready", "Teach & Learn")), Failure(f"the transition 'Mark as done' leads {key} to the status 'Done', not to 'Release Ready' or 'Teach & Learn'")) self.assertEqual(self.jira.transitioned, []) def test_a_transition_the_workflow_does_not_offer_fails_naming_what_it_offers(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.assertEqual(store.move_issue_by(key, "Release Ready", ("Release Ready",)), Failure(f"{key} has no transition 'Release Ready' from its status 'To Do', only 'Mark as done' to 'Done'")) self.jira.workflow.append({"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}}) self.assertEqual(store.move_issue_by(key, "Release Ready", ("Release Ready",)), Failure(f"{key} has no transition 'Release Ready' from its status 'To Do', only 'Mark as done' to 'Done' and 'Start' to 'In Progress'")) self.jira.workflow = [] self.assertEqual(store.move_issue_by(key, "Release Ready", ("Release Ready",)), Failure(f"{key} has no transition 'Release Ready' from its status 'To Do', nor any other the account may make")) self.assertEqual(self.jira.transitioned, []) def test_a_move_by_a_transition_that_jira_refuses_or_cannot_be_read_fails_with_the_reason(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.issues.append({"key": "ABC-61", "fields": {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": None, "issuelinks": []}}) self.assertEqual(store.move_issue_by("ABC-61", "Mark as done", ("Done",)), Failure("ABC-61 is not one of the child issues of the epic ABC-12, so it cannot be moved")) transitions = f"{ISSUES}/{key}/transitions" self.jira.answers = {("POST", transitions): Failure("Jira answered 400")} self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot move {key} by 'Mark as done': Jira answered 400")) self.jira.answers = {("GET", transitions): Failure("Jira answered 503")} self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot read {key}'s transitions: Jira answered 503")) self.jira.answers = {("GET", transitions): {"transitions": [{"id": "31"}]}} self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")) self.jira.answers = {("GET", f"{ISSUES}/{key}?fields=parent,status"): Failure("Jira answered 503")} self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot read {key} to move it: Jira answered 503")) self.jira.answers = {("GET", f"{ISSUES}/{key}?fields=status"): Failure("Jira answered 502")} self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot read {key} to move it: Jira answered 502")) def test_a_move_the_workflow_does_not_offer_fails_naming_what_it_offers(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', only 'Mark as done' to 'Done'")) self.jira.workflow.append({"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}}) self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', only 'Mark as done' to 'Done' and 'Start' to 'In Progress'")) self.jira.workflow = [] self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', nor any other the account may make")) self.assertEqual(self.jira.transitioned, []) def test_a_move_jira_cannot_read_or_refuses_fails_saying_which(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) transitions = f"{ISSUES}/{key}/transitions" status = f"{ISSUES}/{key}?fields=status" for answers, reason in ( ({("GET", status): Failure("Jira answered 503")}, f"cannot read {key} to move it: Jira answered 503"), ({("GET", status): {"key": key, "fields": {}}}, f"{key} is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"), ({("GET", transitions): Failure("Jira answered 503")}, f"cannot read {key}'s transitions: Jira answered 503"), ({("GET", transitions): {"transitions": [{"id": "21"}]}}, f"Jira answered {key}'s transitions in a shape other than the one it documents"), ({("POST", transitions): Failure("Jira answered 400")}, f"cannot move {key} to 'Done': Jira answered 400"), ): with self.subTest(reason=reason): self.jira.answers = answers self.assertEqual(store.move_issue(key, "Done"), Failure(reason)) def test_a_move_says_which_issue_jira_cannot_read_and_refuses_one_outside_the_epic(self) -> None: store = self.new_store() child = store.file("ABC-12", "Count the runs.", "", ()) task = store.file(child, "Count them in the api.", "", ()) self.jira.issues.append({"key": "ABC-61", "fields": {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": None, "issuelinks": []}}) self.assertEqual(store.move_issue("ABC-61", "Done"), Failure("ABC-61 is not one of the child issues of the epic ABC-12, so it cannot be moved")) self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] = Failure("Jira answered 503") self.assertEqual(store.move_issue(task, "Done"), Failure(f"cannot read {task} to move it: Jira answered 503")) del self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] self.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent,status")] = Failure("Jira answered 503") self.assertEqual(store.move_issue(task, "Done"), Failure(f"cannot read {child} to move its sub-task: Jira answered 503")) self.assertEqual(self.jira.transitioned, []) def test_finishes_an_issue_by_the_transition_the_settings_name(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.workflow = [{"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}}, {"id": "31", "name": "Mark as done", "to": DONE}] self.assertIsNone(store.finish_issue(key)) self.assertEqual(self.jira.calls[-1], ("POST", f"{ISSUES}/{key}/transitions")) self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["31"], DONE)) # type: ignore[index] def test_finishes_by_the_named_transition_where_several_lead_to_a_done_status(self) -> None: key = self.new_store().file("ABC-12", "Count the runs.", "", ()) self.jira.workflow = [{"id": "31", "name": "Resolve", "to": DONE}, {"id": "41", "name": "Close", "to": {"name": "Closed", "statusCategory": {"key": "done"}}}] self.assertIsNone(JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Closed")).finish_issue(key)) self.assertEqual(self.jira.transitioned, ["41"]) def test_leaves_an_issue_that_is_done_without_asking_for_its_transitions(self) -> None: store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) key = self.new_store().file("ABC-12", "Count the runs.", "", ()) self.jira.change(key, status=DONE) self.assertIsNone(store.finish_issue(key)) self.assertNotIn(("GET", f"{ISSUES}/{key}/transitions"), self.jira.calls) def test_a_finish_names_why_no_move_finishes_the_issue(self) -> None: key = self.new_store().file("ABC-12", "Count the runs.", "", ()) unnamed = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) wrong_status = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Mark as done", "Closed")) no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) self.assertEqual(unnamed.finish_issue(key), Failure("do-epic's settings name no transition to finish an issue by: set `jira-finish-transition` and `jira-finish-status` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"")) self.assertEqual(wrong_status.finish_issue(key), Failure(f"{key}'s transition 'Mark as done' leads to the status 'Done', not to 'Closed', which `jira-finish-status` names")) refused = no_such.finish_issue(key) assert isinstance(refused, Failure) self.assertIn(f"{key} has no transition 'Close' from its status", refused.reason) self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), ([], TO_DO)) # type: ignore[index] def test_refuses_to_finish_a_sub_task_of_an_issue_that_is_no_child_of_the_epic_or_an_issue_without_a_parent(self) -> None: store = self.new_store() for key, parent in (("ABC-50", "ABC-60"), ("ABC-60", "ABC-61"), ("ABC-61", None)): fields = {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": {"key": parent} if parent else None, "issuelinks": []} self.jira.issues.append({"key": key, "fields": fields}) for key in ("ABC-50", "ABC-61"): with self.subTest(key=key): self.assertEqual(store.finish_issue(key), Failure(f"{key} is not one of the child issues of the epic ABC-12, so it cannot be finished")) self.assertNotIn("POST", [method for method, _ in self.jira.calls]) def test_a_finish_jira_refuses_says_so_and_that_the_issue_may_have_moved(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.answers[("POST", f"{ISSUES}/{key}/transitions")] = Failure("Jira answered 400: Resolution is required") self.assertEqual(store.finish_issue(key), Failure(f"cannot move {key} by 'Mark as done': Jira answered 400: Resolution is required; unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again")) def test_a_finish_whose_transitions_jira_cannot_give_or_gives_in_another_shape_fails(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) url = ("GET", f"{ISSUES}/{key}/transitions") self.jira.answers[url] = Failure("Jira answered 503") self.assertEqual(store.finish_issue(key), Failure(f"cannot read {key}'s transitions: Jira answered 503")) for answer in ({"transitions": [{"id": 31}]}, ["Mark as done"], {"transitions": 5}): with self.subTest(answer=answer): self.jira.answers[url] = answer self.assertEqual(store.finish_issue(key), Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")) def test_a_finish_whose_issue_or_parent_jira_cannot_read_says_which(self) -> None: store = self.new_store() child = store.file("ABC-12", "Count the runs.", "", ()) task = store.file(child, "Count them in the api.", "", ()) self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] = Failure("Jira answered 503") self.assertEqual(store.finish_issue(task), Failure(f"cannot read {task} to finish it: Jira answered 503")) del self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] self.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent,status")] = Failure("Jira answered 503") self.assertEqual(store.finish_issue(task), Failure(f"cannot read {child} to finish its sub-task: Jira answered 503")) def test_reads_the_sub_tasks_of_more_children_than_one_search_names(self) -> None: store = self.new_store() children = [store.file("ABC-12", f"Item {n}.", "", ()) for n in range(60)] tasks = [store.file(child, "A task.", "", ()) for child in children] read = store.read() assert isinstance(read, list), read self.assertEqual([issue.key for issue in read], [key for pair in zip(children, tasks) for key in pair]) def test_files_a_child_as_a_task_where_the_settings_name_no_type(self) -> None: self.new_store().file("ABC-12", "Count the runs.", "", ()) self.assertEqual(self.jira.filed_as, [{"name": "Task"}]) def test_files_a_finding_and_a_release_review_as_the_types_the_settings_name(self) -> None: store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, finding_type="Feature", review_type="Chore") store.file("ABC-12", "Count the runs.", "", ("repo:api",)) store.file("ABC-12", "Review api.", "", ("repo:api", REVIEW_LABEL)) self.assertEqual(self.jira.filed_as, [{"name": "Feature"}, {"name": "Chore"}]) def test_does_not_file_anything_where_the_project_lacks_the_type_and_names_the_types_it_has(self) -> None: store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, finding_type="Feature", review_type="Investigation") self.assertEqual(store.file("ABC-12", "Review api.", "", (REVIEW_LABEL,)), Failure("ABC has no issue type 'Investigation' for an issue under an epic; it has Task, Feature and Chore: name one in `jira-review-type`")) self.assertEqual(self.jira.issues, []) def test_names_the_setting_of_a_finding_where_the_project_lacks_its_type(self) -> None: store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, finding_type="Investigation") self.assertEqual(store.file("ABC-12", "Count the runs.", "", ()), Failure("ABC has no issue type 'Investigation' for an issue under an epic; it has Task, Feature and Chore: name one in `jira-finding-type`")) def test_a_filing_jira_fails_or_answers_without_a_key_says_the_issue_may_exist(self) -> None: for answer, reason in ((Failure("Jira answered 503"), "cannot file the issue under ABC-12: Jira answered 503"), ({"id": "1"}, "Jira answered the new issue without an issue key"), (["ABC-100"], "Jira answered the new issue without an issue key")): with self.subTest(answer=answer): self.jira.answers[("POST", ISSUES)] = answer self.assertEqual(self.new_store().file("ABC-12", "Count the runs.", "", ()), Failure(f"{reason}; unless Jira refused the request, the issue may exist: look under ABC-12 before filing it again")) def test_a_detail_the_codec_refuses_leaves_the_epic_as_it_was(self) -> None: store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it")) self.assertEqual(store.file("ABC-12", "Count the runs.", "Why.", ()), Failure("cannot convert the detail to a Jira description: adf-codec refused it")) self.assertEqual(self.jira.issues, []) def test_files_no_sub_task_where_the_project_has_no_sub_task_type_or_its_types_cannot_be_read(self) -> None: store = self.new_store() child = store.file("ABC-12", "Count the runs.", "", ()) for answer, reason in ((Failure("Jira answered 403"), "cannot read ABC's issue types: Jira answered 403"), ({"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}]}, "ABC has no sub-task issue type; turn sub-tasks on in Jira"), ({}, "Jira answered ABC's issue types in a shape its REST API version 3 doesn't document"), ([], "Jira answered ABC's issue types in a shape its REST API version 3 doesn't document")): with self.subTest(answer=answer): self.jira.answers[("GET", ISSUE_TYPES)] = answer self.assertEqual(store.file(str(child), "A task.", "", ()), Failure(reason)) self.assertEqual(len(self.jira.issues), 1) def test_an_issue_in_another_shape_fails_the_read(self) -> None: valid = {"summary": "Count the runs.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": {"key": "ABC-12"}, "issuelinks": []} linked = {"id": "1", "type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-2"}} shape = "ABC-34 is not in the shape Jira Cloud's REST API version 3 documents" for raw, reason in ( ("ABC-34", "the search answered an issue without an issue key"), ({"fields": valid}, "the search answered an issue without an issue key"), ({"key": "abc-34", "fields": valid}, "the search answered an issue without an issue key"), ({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}, "issuelinks": []}}, shape + ": KeyError('labels')"), *((({"key": "ABC-34", "fields": valid | changed}, shape + ": its summary, labels, assignee, status, parent, description or a linked issue's key holds another kind of value") for changed in ( {"summary": 3}, {"labels": "api"}, {"labels": [3]}, {"assignee": {"displayName": 0}}, {"status": {"name": 0, "statusCategory": {"key": "new"}}}, {"parent": {"key": "ABC"}}, {"parent": {"key": 12}}, {"description": "text"}, {"issuelinks": [linked | {"inwardIssue": {"key": "ABC-x"}}]}, ))), ({"key": "ABC-34", "fields": {key: value for key, value in valid.items() if key != "issuelinks"}}, shape + ": its issuelinks are no list"), ({"key": "ABC-34", "fields": valid, "properties": {"plan-item": "L 2"}}, "ABC-34's issue property plan-item is not a JSON object"), ({"key": "ABC-34", "fields": valid, "properties": {"plan-item": {"L": "many"}}}, "item ABC-34's L 'many' is not a whole number from 1 to 4; ABC-34 holds it in its issue property plan-item"), ({"key": "ABC-34", "fields": valid, "properties": None}, shape + ": its properties are no object"), ({"key": "ABC-34", "fields": valid | {"issuelinks": [linked | {"inwardIssue": {"key": 7}}]}}, shape + ": its issuelinks hold a link whose id or whose linked issue's key is no text"), ): with self.subTest(raw=raw): self.jira.answers[("POST", SEARCH)] = {"issues": [raw]} self.assertEqual(self.new_store().read(), Failure(reason)) def test_a_description_the_codec_cannot_convert_fails_the_read(self) -> None: self.new_store().file("ABC-12", "Count the runs.", "Why.", ()) for converted, reason in ((Refused(0, Failure("a table cell holds a list")), "ABC-100's description: a table cell holds a list"), (Failure("docker is not running"), "cannot convert the descriptions of ABC-12's issues to markdown: docker is not running")): with self.subTest(converted=converted): self.assertEqual(JiraEpic(EPIC, self.env_file, self.jira, lambda documents: converted, to_adf).read(), Failure(reason)) def test_a_search_that_does_not_end_names_the_issues_it_sought(self) -> None: store = dataclasses.replace(self.new_store(), max_pages=1) children = [store.file("ABC-12", "Count the runs.", "", ()) for _ in range(2)] for _ in range(3): store.file(str(children[0]), "A task.", "", ()) self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages")) store.file("ABC-12", "Count the runs.", "", ()) self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages")) def test_refuses_to_file_under_another_epics_child_or_an_issue_it_cannot_read(self) -> None: self.jira.issues.append({"key": "ABC-5", "fields": {"parent": {"key": "ABC-1"}, "status": TO_DO}}) store = self.new_store() self.assertEqual(store.file("ABC-5", "Count more.", "", ()), Failure("ABC-5 is neither the epic ABC-12 nor one of its child issues, so nothing can be filed under it")) self.assertEqual(store.file("ABC-77", "Count more.", "", ()), Failure(f"cannot read ABC-77 to file under it: Jira answered 404 for GET {ISSUES}/ABC-77?fields=parent,status")) self.jira.answers[("GET", f"{ISSUES}/ABC-78?fields=parent,status")] = ["ABC-12"] self.assertEqual(store.file("ABC-78", "Count more.", "", ()), Failure("ABC-78 is neither the epic ABC-12 nor one of its child issues, so nothing can be filed under it")) self.assertEqual([call for call in self.jira.calls if call[0] == "POST" and call[1] == ISSUES], []) def test_refuses_to_file_blocked_by_a_sub_task_of_another_epics_child_or_an_issue_it_cannot_read(self) -> None: self.jira.issues.extend([{"key": "ABC-6", "fields": {"parent": {"key": "ABC-7"}, "status": TO_DO}}, {"key": "ABC-5", "fields": {"parent": {"key": "ABC-6"}, "status": TO_DO}}]) store = self.new_store() self.assertEqual(store.file("ABC-12", "Count more.", "", (), "ABC-5"), Failure("ABC-5 is neither a child issue of the epic ABC-12 nor a sub-task of one, so it cannot block a new issue")) self.assertEqual(store.file("ABC-12", "Count more.", "", (), "ABC-77"), Failure(f"cannot read ABC-77 to file blocked by it: Jira answered 404 for GET {ISSUES}/ABC-77?fields=parent,status")) self.jira.answers[("GET", f"{ISSUES}/ABC-6?fields=parent,status")] = Failure("Jira answered 503") self.assertEqual(store.file("ABC-12", "Count more.", "", (), "ABC-5"), Failure("cannot read ABC-6 to file blocked by it: Jira answered 503")) self.assertEqual([call for call in self.jira.calls if call[0] == "POST" and call[1] == ISSUES], []) def test_a_label_jira_refuses_is_not_added(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.answers[("PUT", f"{ISSUES}/{key}")] = Failure("Jira answered 403") self.assertEqual(store.add_label(str(key), "repo:log"), Failure(f"cannot label {key}: Jira answered 403")) read = store.read() assert isinstance(read, list), read self.assertEqual([issue.labels for issue in read], [()]) def test_a_comment_jira_refuses_or_the_codec_cannot_convert_is_not_posted(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) assert isinstance(key, str) self.jira.answers["POST", f"{ISSUES}/{key}/comment"] = Failure("Jira answered 403") self.assertEqual(store.comment(key, "Hello."), Failure(f"cannot comment on {key}: Jira answered 403")) refusing = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda text: Failure("not markdown")) self.assertEqual(refusing.comment(key, "Hello."), Failure("cannot convert the comment to a Jira comment: not markdown")) def test_an_issue_jira_cannot_read_is_not_commented_on(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.answers[("GET", f"{ISSUES}/{key}?fields=parent,status")] = Failure("Jira answered 500") self.assertEqual(store.comment(str(key), "Hello."), Failure(f"cannot read {key} to comment on it: Jira answered 500")) self.assertNotIn(("POST", f"{ISSUES}/{key}/comment"), self.jira.calls) def test_an_issue_jira_cannot_read_is_not_labelled(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.answers[("GET", f"{ISSUES}/{key}?fields=parent,status")] = Failure("Jira answered 500") self.assertEqual(store.add_label(str(key), "repo:log"), Failure(f"cannot read {key} to label it: Jira answered 500")) self.assertNotIn(("PUT", f"{ISSUES}/{key}"), self.jira.calls) def test_an_epic_the_account_cannot_see_fails_the_read(self) -> None: store = JiraEpic(Epic(SITE, "ABC-99"), self.env_file, self.jira, to_markdown, to_adf) self.assertEqual(store.read(), Failure(f"cannot read the epic ABC-99: Jira answered 404 for GET {SITE}/rest/api/3/issue/ABC-99?fields=summary")) def test_a_rank_jira_refuses_fails_with_its_reason_and_ranks_nothing(self) -> None: store = self.new_store() first, second = (store.file("ABC-12", f"Item {n}.", "", ()) for n in range(2)) for answer, reason in ( (Failure("Jira answered 403"), "Jira answered 403"), ({"entries": [{"issueKey": second, "status": 400, "errors": ["Rank is not configured"]}]}, "Rank is not configured"), ): with self.subTest(answer=answer): self.jira.answers[("PUT", RANK)] = answer self.assertEqual(store.rank(str(second), str(first)), Failure(reason)) read = store.read() assert isinstance(read, list), read self.assertEqual([issue.key for issue in read], [first, second]) if __name__ == "__main__": unittest.main()