420 lines
28 KiB
Python
420 lines
28 KiB
Python
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
|
|
|
|
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"}}
|
|
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": "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 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))
|
|
|
|
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 = url.partition("?fields=")[2].split(",")
|
|
return {"key": held["key"], "fields": {name: held["fields"][name] for name in asked}} # type: ignore[index]
|
|
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"] = DONE # type: ignore[index]
|
|
self.transitioned.append(body["transition"]["id"])
|
|
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)
|
|
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 = {"name": "Task"} if parent == "ABC-12" 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")
|
|
key = f"ABC-{len(self.issues) + 100}"
|
|
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": []}, "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):
|
|
def assign(self, store: JiraEpic, key: str, name: str) -> None: # type: ignore[override]
|
|
self.jira.change(key, assignee={"accountId": "5b10a2844c20165700ede21g", "displayName": name})
|
|
|
|
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_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: KeyError('status')"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: TypeError('list indices must be integers or slices, not str')")):
|
|
self.jira.answers[("GET", EPIC_STATUS)] = answer
|
|
self.assertEqual(self.new_store().closed(), Failure(reason))
|
|
|
|
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_without_asking_for_issue_types(self) -> None:
|
|
self.new_store().file("ABC-12", "Count the runs.", "", ())
|
|
self.assertNotIn(("GET", ISSUE_TYPES), self.jira.calls)
|
|
|
|
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", "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_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()
|