244 lines
13 KiB
Python
244 lines
13 KiB
Python
import base64
|
|
import pathlib
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
import unittest.mock
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from project_config.settings import Epic
|
|
from failure import Failure
|
|
from plan_store import jira_epic
|
|
from plan_store.stores import Plan
|
|
from adf_codec.convert import Refused
|
|
from release_plan.release import release_of
|
|
|
|
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
|
|
SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
|
|
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
|
|
|
|
|
|
def issue(key: str, summary: str = "Count the runs.", versions: tuple[str, ...] = ("0.1.0",), scores: dict[str, object] | None = None, blocked_by: tuple[str, ...] = (), description: object = None, blocks: tuple[str, ...] = ()) -> dict[str, object]:
|
|
links = [{"type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by]
|
|
links += [{"type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": blocked}} for blocked in blocks]
|
|
return {
|
|
"key": key,
|
|
"fields": {"summary": summary, "description": description, "fixVersions": [{"name": name} for name in versions], "issuelinks": links},
|
|
"properties": {} if scores is None else {jira_epic.PROPERTY: scores},
|
|
}
|
|
|
|
|
|
def adf(text: str) -> dict[str, object]:
|
|
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
|
|
|
|
|
|
def text_of(document: dict[str, object]) -> str | Failure:
|
|
"""Stands in for the adf-codec shim: the text of the one paragraph adf builds."""
|
|
return document["content"][0]["content"][0]["text"] + "\n" # type: ignore[index]
|
|
|
|
|
|
class JiraPlan(unittest.TestCase):
|
|
def setUp(self) -> None:
|
|
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
|
|
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
|
|
self.env.chmod(0o600)
|
|
self.pages: list[object] = []
|
|
self.calls: list[tuple[str, str, str, object]] = []
|
|
self.epic: object = {"key": "ABC-12"}
|
|
self.epic_calls: list[tuple[str, str, str, object]] = []
|
|
self.converted: list[list[dict[str, object]]] = []
|
|
|
|
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
|
"""Stands in for Jira: answers self.epic to the request for the epic, and the next of self.pages to each search."""
|
|
if method == "GET":
|
|
self.epic_calls.append((method, url, authorization, body))
|
|
return self.epic
|
|
self.calls.append((method, url, authorization, body))
|
|
return self.pages[len(self.calls) - 1]
|
|
|
|
def to_markdown(self, documents: list[dict[str, object]]) -> list[str] | Refused | Failure:
|
|
self.converted.append(documents)
|
|
return [text_of(document) for document in documents]
|
|
|
|
def store(self) -> jira_epic.JiraPlan:
|
|
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown)
|
|
|
|
def read(self, *issues: dict[str, object]) -> Plan | Failure:
|
|
self.pages, self.calls = [{"issues": list(issues)}], []
|
|
return self.store().read()
|
|
|
|
def items(self, *issues: dict[str, object]):
|
|
plan = self.read(*issues)
|
|
assert isinstance(plan, Plan), plan
|
|
return plan.items
|
|
|
|
def test_an_epic_with_no_open_child_reads_as_an_empty_plan(self):
|
|
self.assertEqual(self.read(), Plan([]))
|
|
|
|
def test_asks_for_the_epics_open_children_in_backlog_order_with_basic_auth(self):
|
|
self.read()
|
|
method, url, authorization, body = self.calls[0]
|
|
self.assertEqual((method, url), ("POST", SEARCH))
|
|
self.assertEqual(authorization, AUTHORIZATION)
|
|
self.assertEqual(body, {
|
|
"jql": 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC',
|
|
"fields": ["summary", "description", "fixVersions", "issuelinks"],
|
|
"properties": ["plan-item"],
|
|
"maxResults": 100,
|
|
})
|
|
|
|
def test_an_epic_that_cannot_be_read_fails_the_read_before_any_search(self):
|
|
self.epic = Failure("GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it.")
|
|
self.assertEqual(self.read(), Failure("cannot read the epic ABC-12: GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it."))
|
|
self.assertEqual(self.epic_calls, [("GET", "https://acme.atlassian.net/rest/api/3/issue/ABC-12?fields=summary", AUTHORIZATION, None)])
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_an_issue_reads_as_an_item_under_its_number(self):
|
|
scores = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "owner"}
|
|
item, = self.items(issue("ABC-34", "Count the runs.", ("0.1.0",), scores, description=adf("Why it counts.")))
|
|
self.assertEqual((item.id, item.release, item.tagline, item.detail), (34, release_of("0.1.0"), "**Count the runs.**", "Why it counts."))
|
|
self.assertEqual((item.scores, item.moves, item.exempt, item.blocked_by), ({"L": 1, "E": 2, "I": 3, "S": 1}, (("1", 9),), "owner", ()))
|
|
|
|
def test_keeps_jiras_order_whatever_the_releases_and_scores(self):
|
|
found = self.items(issue("ABC-40", versions=("0.2.0",)), issue("ABC-7", versions=("0.1.0",)), issue("ABC-21", versions=("0.3.0",)))
|
|
self.assertEqual([item.id for item in found], [40, 7, 21])
|
|
|
|
def test_an_issue_nobody_scored_reads_without_scores(self):
|
|
bare = issue("ABC-35")
|
|
del bare["properties"]
|
|
for item in self.items(issue("ABC-34"), bare):
|
|
with self.subTest(item=item.id):
|
|
self.assertEqual((item.scores, item.moves, item.exempt, item.detail, item.likelihood), ({}, (), "", "", 0))
|
|
|
|
def test_an_issue_is_blocked_by_each_blocker_still_in_the_plan(self):
|
|
blocked, _ = self.items(issue("ABC-34", blocked_by=("ABC-35", "ABC-2", "OTHER-9"), blocks=("ABC-35",)), issue("ABC-35", blocks=("ABC-34",)))
|
|
self.assertEqual(blocked.blocked_by, (35,))
|
|
|
|
def test_the_release_is_the_earliest_fix_version_with_or_without_a_v(self):
|
|
for versions in (("v1.2.0", "0.9.1", "Later"), ("1.2.0", "v0.9.1")):
|
|
with self.subTest(versions=versions):
|
|
item, = self.items(issue("ABC-34", versions=versions))
|
|
self.assertEqual(item.release, release_of("0.9.1"))
|
|
|
|
def test_an_issue_with_no_semver_fix_version_fails_the_read_naming_it(self):
|
|
for versions in ((), ("Sprint 4",)):
|
|
with self.subTest(versions=versions):
|
|
failure = self.read(issue("ABC-33", description=adf("Why.")), issue("ABC-34", versions=versions))
|
|
self.assertEqual(failure, Failure("ABC-34 names no Fix Version that is a semver version, such as 1.2.0; set one in Jira"))
|
|
self.assertEqual(self.converted, [])
|
|
|
|
def test_a_child_in_another_jira_project_fails_the_read_naming_it(self):
|
|
failure = self.read(issue("ABC-34"), issue("OTHER-5"))
|
|
self.assertIsInstance(failure, Failure)
|
|
self.assertIn("OTHER-5", failure.reason) # type: ignore[union-attr]
|
|
|
|
def test_scores_out_of_format_fail_the_read_naming_the_issue(self):
|
|
for scores in ({"L": 9}, {"L": "high"}, {"Moves": "everything"}, {"Exempt": "because"}, "L 3"):
|
|
with self.subTest(scores=scores):
|
|
failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type]
|
|
self.assertIsInstance(failure, Failure)
|
|
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
|
|
|
|
def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self):
|
|
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security"))
|
|
|
|
def test_reads_every_page(self):
|
|
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
|
|
plan = self.store().read()
|
|
self.assertEqual([item.id for item in plan.items], [1, 2]) # type: ignore[union-attr]
|
|
self.assertNotIn("nextPageToken", self.calls[0][3]) # type: ignore[operator]
|
|
self.assertEqual(self.calls[1][3]["nextPageToken"], "t1") # type: ignore[index]
|
|
|
|
def test_a_failing_request_fails_the_read(self):
|
|
self.pages = [Failure("POST /rest/api/3/search/jql answered 401: no")]
|
|
self.assertEqual(self.store().read(), Failure("POST /rest/api/3/search/jql answered 401: no"))
|
|
|
|
def test_an_answer_in_another_shape_fails_the_read(self):
|
|
no_page, no_key = "the search answered something other than a page of issues", "the search answered an issue without an issue key"
|
|
for page, reason in (([], no_page), ({"issues": "none"}, no_page), ({"issues": ["ABC-1"]}, no_key), ({"issues": [{"key": 7, "fields": {}}]}, no_key), ({"issues": [{"key": "abc", "fields": {}}]}, no_key)):
|
|
with self.subTest(page=page):
|
|
self.pages, self.calls = [page], []
|
|
self.assertEqual(self.store().read(), Failure(reason))
|
|
|
|
def test_a_search_that_never_names_a_last_page_fails_the_read(self):
|
|
self.pages = [{"issues": [], "nextPageToken": "more"}] * 2
|
|
with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 2):
|
|
self.assertEqual(self.store().read(), Failure("the search for ABC-12's children did not end within 2 pages"))
|
|
|
|
def test_an_issue_in_another_shape_fails_the_read_naming_it(self):
|
|
good = issue("ABC-1")
|
|
for wrong in ({"key": "ABC-1"}, issue("ABC-1", summary=None), issue("ABC-1", description="text"), good | {"fields": good["fields"] | {"fixVersions": [{"name": 7}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator]
|
|
with self.subTest(wrong=wrong):
|
|
failure = self.read(wrong) # type: ignore[arg-type]
|
|
self.assertIsInstance(failure, Failure)
|
|
self.assertTrue(failure.reason.startswith("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: "), failure) # type: ignore[union-attr]
|
|
|
|
def test_converts_every_description_in_one_run_and_none_for_an_issue_without_one(self):
|
|
found = self.items(issue("ABC-1", description=adf("One.")), issue("ABC-2"), issue("ABC-3", description=adf("Three.")), issue("ABC-4", description=adf("Four.")))
|
|
self.assertEqual([item.detail for item in found], ["One.", "", "Three.", "Four."])
|
|
self.assertEqual(self.converted, [[adf("One."), adf("Three."), adf("Four.")]])
|
|
|
|
def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self):
|
|
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")))
|
|
self.pages = [{"issues": [issue("ABC-33", description=adf("x")), issue("ABC-34"), issue("ABC-35", description=adf("y"))]}]
|
|
self.assertEqual(store.read(), Failure("ABC-35's description: adf-codec refused"))
|
|
|
|
def test_a_codec_that_cannot_run_fails_the_read(self):
|
|
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"))
|
|
self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}]
|
|
self.assertEqual(store.read(), Failure("cannot convert the descriptions of ABC-12's children to markdown: docker is not installed"))
|
|
|
|
def test_an_env_file_without_the_credentials_fails_before_any_request(self):
|
|
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\n")
|
|
failure = self.read()
|
|
self.assertIsInstance(failure, Failure)
|
|
self.assertIn("ATLASSIAN_API_TOKEN", failure.reason) # type: ignore[union-attr]
|
|
self.assertEqual(self.calls + self.epic_calls, [])
|
|
|
|
def test_an_env_file_others_may_read_fails_before_any_request(self):
|
|
self.env.chmod(0o644)
|
|
self.assertEqual(self.read(), Failure(f"{self.env} holds an API token, so only its owner may read it; run chmod 600 {self.env}"))
|
|
self.assertEqual(self.calls + self.epic_calls, [])
|
|
|
|
def test_a_missing_env_file_fails(self):
|
|
self.env.unlink()
|
|
self.assertIsInstance(self.read(), Failure)
|
|
|
|
def test_no_failure_holds_the_token(self):
|
|
self.pages = [{"issues": [issue("OTHER-5")]}]
|
|
self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr]
|
|
|
|
def test_every_write_fails_since_the_store_only_reads(self):
|
|
store = self.store()
|
|
for written in (store.add({}, ""), store.edit(34, {"L": "2"}, None), store.finish(34)):
|
|
with self.subTest(written=written):
|
|
self.assertEqual(written, Failure("a plan in Jira is only read so far: file, edit and finish its issues in Jira"))
|
|
self.assertEqual(self.calls + self.epic_calls, [])
|
|
|
|
def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self):
|
|
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
|
|
|
|
|
|
class Requests(unittest.TestCase):
|
|
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
|
|
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
|
|
self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []})
|
|
sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message)
|
|
|
|
def test_reads_jiras_messages_from_an_error_answer(self):
|
|
cases = (
|
|
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
|
|
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
|
|
({"errorMessages": "One.", "errors": ["Two."]}, ""),
|
|
({"errorMessages": [7, "One."]}, "One."),
|
|
(["One."], ""),
|
|
)
|
|
for answer, message in cases:
|
|
with self.subTest(answer=answer):
|
|
self.assertEqual(jira_epic.error_message(answer), message)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|