diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py index 5d940053..eabc59ed 100644 --- a/bin/atlassian/jira.py +++ b/bin/atlassian/jira.py @@ -154,6 +154,18 @@ def project_of(key: str) -> str: return key.rpartition("-")[0] +def edit_issue(site: str, key: str, body: dict[str, typing.Any], authorization: str, http: Http) -> None | Failure: + """Sends an edit of the issue named key: its fields, its updates and its issue properties in one request, or the Failure Jira answered. Jira refuses an edit that holds neither fields nor update, so such an edit sets each property through the property's own endpoint, one request each, and stops at the first that fails.""" + if "fields" in body or "update" in body: + answer = http("PUT", f"{site}/rest/api/3/issue/{key}", authorization, body) + return answer if isinstance(answer, Failure) else None + for entry in body.get("properties", []): + answer = http("PUT", f"{site}/rest/api/3/issue/{key}/properties/{entry['key']}", authorization, entry["value"]) + if isinstance(answer, Failure): + return answer + return None + + def rank_refusal(site: str, key: str, before: str, authorization: str, http: Http) -> str | None: """Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors.""" answer = http("PUT", f"{site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before}) diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py index 0e086c59..5db09715 100644 --- a/bin/atlassian/test_jira.py +++ b/bin/atlassian/test_jira.py @@ -109,3 +109,35 @@ class TheRefusalOfAnIssueType(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class AnIssueEdit(unittest.TestCase): + def setUp(self) -> None: + self.calls: list[tuple[str, str, object]] = [] + self.answer: object = None + + def http(self, method: str, url: str, authorization: str, body: object) -> object: + self.calls.append((method, url, body)) + return self.answer + + def edit(self, body: dict[str, object]) -> None | Failure: + return jira.edit_issue("https://acme.atlassian.net", "ABC-1", body, "Basic x", self.http) + + def test_sends_fields_update_and_properties_in_one_request(self): + body = {"fields": {"summary": "Count."}, "update": {"labels": [{"add": "security"}]}, "properties": [{"key": "plan", "value": {"L": 2}}]} + self.assertIsNone(self.edit(body)) + self.assertEqual(self.calls, [("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1", body)]) + + def test_sets_each_property_of_an_edit_without_fields_or_update_through_the_property_endpoint(self): + # Jira's edit refuses such a body: "one of 'fields' or 'update' required". + self.assertIsNone(self.edit({"properties": [{"key": "plan", "value": {"L": 2}}, {"key": "seen", "value": True}]})) + self.assertEqual(self.calls, [ + ("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/plan", {"L": 2}), + ("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/seen", True), + ]) + + def test_a_request_jira_refuses_is_its_failure_and_sets_no_later_property(self): + self.answer = Failure("Jira answered 503") + self.assertEqual(self.edit({"fields": {"summary": "Count."}}), Failure("Jira answered 503")) + self.assertEqual(self.edit({"properties": [{"key": "plan", "value": {}}, {"key": "seen", "value": True}]}), Failure("Jira answered 503")) + self.assertEqual(len(self.calls), 2) diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 269580ce..2a664a84 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -7,7 +7,7 @@ from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown from plan_store.jira_epic import BLOCKS, FILED_BY, scores as held_scores, PROPERTY from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_REVIEW_TYPE -from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped +from atlassian.jira import DONE, edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label from failure import Failure from do_epic.backend.jira_status import moved_by, moved_to @@ -195,7 +195,7 @@ class JiraEpic: posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{key}/comment", authorization, {"body": body}) if isinstance(posted, Failure): return Failure(f"cannot comment on {key} to tell its team the scores: {posted.reason}") - put = self.http("PUT", f"{self.epic.site}/rest/api/3/issue/{key}", authorization, {"properties": [{"key": PROPERTY, "value": held | scores | {MOVES: moves}}]}) + put = edit_issue(self.epic.site, key, {"properties": [{"key": PROPERTY, "value": held | scores | {MOVES: moves}}]}, authorization, self.http) return Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: {put.reason}") if isinstance(put, Failure) else None def start_issue(self, key: str) -> str | None | Failure: diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 5da2d0ea..68840910 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -119,12 +119,13 @@ class FakeJira: 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.startswith(f"{ISSUES}/{issue['key']}/properties/")), None)): + held.setdefault("properties", {})[url.rpartition("/")[2]] = body # type: ignore[attr-defined] + return None 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 + if "fields" not in body and "update" not in body: + return Failure("Jira answered 400: one of 'fields' or 'update' required") added = [change["add"] for change in body["update"]["labels"]] held["fields"]["labels"] = sorted({*held["fields"]["labels"], *added}) # type: ignore[index] return None @@ -286,9 +287,9 @@ class Jira(Case): 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.jira.answers[("PUT", f"{ISSUES}/{key}/properties/plan-item")] = 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}")] + del self.jira.answers[("PUT", f"{ISSUES}/{key}/properties/plan-item")] # 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.")) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index a0b984e2..5e0c8082 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -13,7 +13,7 @@ from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SH from plan_store.markdown_edits import bold_cell, plain, unfit_text from plan_store.plans import cells, no_item, Plan, Written from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION -from atlassian.jira import entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, Link, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped +from atlassian.jira import edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, Link, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped from failure import Failure from plan.release import parsed, Release, tagged from plan import ranking @@ -198,7 +198,7 @@ class JiraPlan: return isinstance(texts, list) and texts[0].strip() == detail.strip() def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: - """Sets the fields and the detail in one request, so Jira takes all of those or none, then changes the issue's links one request at a time, and then posts comment on the issue. `revision_of` says what an edit may set. + """Sets the fields, the detail and the scores in one request, so Jira takes all of those or none, or sets the scores alone as `edit_issue` says, then changes the issue's links one request at a time, and then posts comment on the issue. `revision_of` says what an edit may set. A link change or a comment Jira refuses leaves the edit made, so the write counts as landed, and a note says what to do by hand.""" authorization = basic_auth(self.env_file) @@ -237,7 +237,7 @@ class JiraPlan: return version body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}} url = f"{self.epic.site}/rest/api/3/issue/{key}" - edited = self.http("PUT", url, authorization, body) if body else None + edited = edit_issue(self.epic.site, key, body, authorization, self.http) if body else None if isinstance(edited, Failure): return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}") notes = self.relinked(issue, revision.blockers, open_keys, authorization) diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 1300921f..4611484e 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -540,7 +540,8 @@ class Editing(unittest.TestCase): def test_sends_only_what_the_edit_names(self): self.edit(34, {"Tagline": "Count every run."}) self.edit(34, {"E": "3"}) - self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}]) + self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, PROPERTY | {"E": 3}]) + self.assertEqual(self.writes()[1][1], f"{ISSUES}/ABC-34/properties/plan-item") def test_a_detail_unchanged_since_the_read_leaves_the_description_as_jira_holds_it(self): # Jira's own spacing paragraph and localIds, which a description converted back from markdown would lose. @@ -548,7 +549,7 @@ class Editing(unittest.TestCase): self.open = [issue("ABC-34", scores=PROPERTY, description=held)] self.assertEqual(self.edit(34, {"L": "2"}, "Why it counts.\n"), Written(34)) self.assertEqual(self.edit(34, {}, "Why it counts."), Written(34)) - self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2}}]})]) + self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34/properties/plan-item", PROPERTY | {"L": 2})]) def test_an_edited_detail_replaces_the_description(self): self.open = [issue("ABC-34", scores=PROPERTY, description=adf("Why it counts."))] @@ -586,17 +587,18 @@ class Editing(unittest.TestCase): def test_scores_an_issue_a_person_filed_and_comments_why(self): self.assertEqual(self.edit(35, {"L": "2", "E": "2", "I": "3", "S": "3", "Moves": "1 by 4"}, None, COMMENT), Written(35)) self.assertEqual(self.writes(), [ - ("PUT", f"{ISSUES}/ABC-35", {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}}]}), + ("PUT", f"{ISSUES}/ABC-35/properties/plan-item", {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}), ("POST", f"{ISSUES}/ABC-35/comment", {"body": adf(COMMENT)}), ]) def test_rescores_a_persons_issue_that_holds_scores_keeping_the_rest(self): self.edit(36, {"L": "2"}, None, COMMENT) - self.assertEqual(self.writes()[0][2], {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""}}]}) + self.assertEqual(self.writes()[0][1:], (f"{ISSUES}/ABC-36/properties/plan-item", {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""})) def test_a_persons_issue_is_never_labelled(self): self.edit(36, {"Exempt": "security"}, None, COMMENT) - self.assertNotIn("update", self.writes()[0][2]) # type: ignore[operator] + # Labelling would take an edit of the issue itself; scores alone go to its property. + self.assertEqual([url for _, url, _ in self.writes()], [f"{ISSUES}/ABC-36/properties/plan-item", f"{ISSUES}/ABC-36/comment"]) def test_scoring_a_persons_issue_without_a_comment_fails_before_any_write(self): for comment in (None, "", " \n"): @@ -663,7 +665,7 @@ class Editing(unittest.TestCase): def test_changes_the_links_after_the_edit_and_before_the_comment(self): self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "35"}, None, COMMENT), Written(34)) - self.assertEqual([(method, url) for method, url, _ in self.writes()], [("PUT", f"{ISSUES}/ABC-34"), ("POST", LINKS), ("POST", f"{ISSUES}/ABC-34/comment")]) + self.assertEqual([(method, url) for method, url, _ in self.writes()], [("PUT", f"{ISSUES}/ABC-34/properties/plan-item"), ("POST", LINKS), ("POST", f"{ISSUES}/ABC-34/comment")]) def test_a_failed_edit_makes_no_link(self): self.edited = Failure("HTTP 400")