125 lines
5.8 KiB
Python
125 lines
5.8 KiB
Python
import dataclasses
|
|
import pathlib
|
|
import re
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
|
|
|
from do_epic.backend.contract import EpicStoreContract
|
|
from do_epic.backend.jira import JiraEpic
|
|
from failure import Failure
|
|
from project_config.settings import Epic
|
|
|
|
SITE = "https://acme.atlassian.net"
|
|
EPIC = Epic(SITE, "ABC-12")
|
|
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, holding issues as Jira answers them, in rank order, and answering a search two issues a page."""
|
|
issues: list[dict[str, object]] = dataclasses.field(default_factory=list)
|
|
refuses: str | None = None
|
|
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 self.refuses and method == "POST" and url.endswith("/issue"):
|
|
return Failure(self.refuses)
|
|
if method == "GET" and url == f"{SITE}/rest/api/3/issue/ABC-12?fields=summary":
|
|
return {"key": "ABC-12"}
|
|
if method == "GET" and url == f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes":
|
|
return TYPES
|
|
if method == "POST" and url == f"{SITE}/rest/api/3/search/jql":
|
|
return self.page(body)
|
|
if method == "POST" and url == f"{SITE}/rest/api/3/issue":
|
|
return self.created(body)
|
|
return Failure(f"Jira answered 404 for {method} {url}")
|
|
|
|
def page(self, body: object) -> object:
|
|
assert isinstance(body, dict)
|
|
parents = re.findall(r'"([A-Z]+-[0-9]+)"', body["jql"])
|
|
found = [issue for issue in self.issues if issue["fields"]["parent"]["key"] in parents] # type: ignore[index]
|
|
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 = next((issue for issue in self.issues if issue["key"] == fields["parent"]["key"]), None)
|
|
subtask = fields["issuetype"] == {"id": "10003"}
|
|
if fields["parent"]["key"] != "ABC-12" and (parent is None or not subtask):
|
|
return Failure("Jira answered 400: the parent cannot hold this issue type")
|
|
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": fields["parent"]["key"]}}})
|
|
return {"id": "1", "key": key}
|
|
|
|
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]
|
|
|
|
|
|
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"}})
|
|
|
|
|
|
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", f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes"), self.jira.calls)
|
|
|
|
def test_a_refused_filing_says_the_issue_may_exist(self) -> None:
|
|
self.jira.refuses = "Jira answered 503"
|
|
self.assertEqual(self.new_store().file("ABC-12", "Count the runs.", "", ()), Failure("cannot file the issue under ABC-12: Jira answered 503; unless Jira refused the request, the issue may exist: look under ABC-12 before filing it again"))
|
|
|
|
def test_an_issue_in_another_shape_fails_the_read(self) -> None:
|
|
self.jira.issues.append({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}}})
|
|
read = self.new_store().read()
|
|
self.assertIsInstance(read, Failure)
|
|
assert isinstance(read, Failure)
|
|
self.assertTrue(read.reason.startswith("ABC-34 is not in the shape Jira Cloud's REST API version 3 documents"), read.reason)
|
|
|
|
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"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|