Files
claude-config/bin/do_epic/backend/test_jira.py
T

263 lines
16 KiB
Python

import base64
import dataclasses
import pathlib
import re
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from project_config.settings import Epic
from do_epic.backend.contract import EpicStoreContract
from failure import Failure
from plan_store import jira_epic
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"}}
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)
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 == 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 == f"{ISSUES}/{issue['key']}?fields=parent"), None)):
return {"key": held["key"], "fields": {"parent": held["fields"]["parent"]}} # type: ignore[index]
if method == "POST" and url == ISSUES:
return self.created(body)
if method == "PUT" and url == RANK:
return self.ranked(body)
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 one issue named just before or just after another, and answers no body, as Jira does for a rank it made."""
assert isinstance(body, dict)
[key], other = body["issues"], body.get("rankBeforeIssue") or body["rankAfterIssue"]
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"] == other) + ("rankAfterIssue" in body), 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)
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 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_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"}}}, 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": 7}}]}, {"issuelinks": [linked | {"inwardIssue": {"key": "ABC-x"}}]},
))),
({"key": "ABC-34", "fields": {key: value for key, value in valid.items() if key != "issuelinks"}}, shape + ": KeyError('issuelinks')"),
({"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 + ": AttributeError(\"'NoneType' object has no attribute 'get'\")"),
):
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 = self.new_store()
children = [store.file("ABC-12", "Count the runs.", "", ()) for _ in range(2)]
for _ in range(3):
store.file(str(children[0]), "A task.", "", ())
with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 1):
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"}}})
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"))
self.jira.answers[("GET", f"{ISSUES}/ABC-78?fields=parent")] = ["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_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")] = 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()