480 lines
27 KiB
Python
480 lines
27 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, Finish
|
|
from release_plan.todo_table import EXEMPTIONS
|
|
from failure import Failure
|
|
from plan_store import jira_epic
|
|
from plan_store.stores import Plan, Written
|
|
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_edit_fails_since_the_store_does_not_edit_yet(self):
|
|
self.assertEqual(self.store().edit(34, {"L": "2"}, None), Failure("a plan in Jira is read, filed into and finished so far: edit 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))
|
|
|
|
|
|
ISSUES = "https://acme.atlassian.net/rest/api/3/issue"
|
|
LINKS = "https://acme.atlassian.net/rest/api/3/issueLink"
|
|
VERSIONS = "https://acme.atlassian.net/rest/api/3/project/ABC/versions"
|
|
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under ABC-12 before filing the item again"
|
|
FIELDS = {"Release": "0.1.0", "Tagline": "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", "Moves": "1 by 9"}
|
|
PROPERTY = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "", "Filed by": "loop"}
|
|
|
|
|
|
class Filing(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.calls: list[tuple[str, str, object]] = []
|
|
self.open: list[dict[str, object]] = []
|
|
self.created: object = {"id": "10040", "key": "ABC-40"}
|
|
self.linked: object = None
|
|
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}, "odd", {"name": ["0.1.0"]}, {"name": {"en": "0.1.0"}}]
|
|
|
|
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
|
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.created to a new issue and self.linked to a new link."""
|
|
self.calls.append((method, url, body))
|
|
assert authorization == AUTHORIZATION
|
|
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
|
|
|
|
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
|
|
return adf(markdown)
|
|
|
|
def add(self, fields: dict[str, str] = FIELDS, detail: str = ""):
|
|
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf).add(fields, detail)
|
|
|
|
def sent(self, url: str) -> list[object]:
|
|
return [body for _, sent_to, body in self.calls if sent_to == url]
|
|
|
|
def test_files_the_item_as_a_task_under_the_epic_marked_as_the_loops(self):
|
|
self.assertEqual(self.add(), Written(40))
|
|
self.assertEqual(self.calls, [("GET", VERSIONS, None), ("POST", ISSUES, {
|
|
"fields": {"project": {"key": "ABC"}, "parent": {"key": "ABC-12"}, "issuetype": {"name": "Task"}, "summary": "Count the runs.", "fixVersions": [{"name": "0.1.0"}]},
|
|
"properties": [{"key": "plan-item", "value": PROPERTY}],
|
|
})])
|
|
|
|
def test_a_bold_tagline_is_filed_plain(self):
|
|
self.add(FIELDS | {"Tagline": "**Count the runs.**"})
|
|
self.assertEqual(self.sent(ISSUES)[0]["fields"]["summary"], "Count the runs.") # type: ignore[index]
|
|
|
|
def test_the_detail_is_the_description_as_adf(self):
|
|
self.add(detail="Why it counts.")
|
|
self.assertEqual(self.sent(ISSUES)[0]["fields"]["description"], adf("Why it counts.")) # type: ignore[index]
|
|
|
|
def test_a_security_finding_is_labelled_security(self):
|
|
self.add(FIELDS | {"Exempt": "security"})
|
|
sent, = self.sent(ISSUES)
|
|
self.assertEqual((sent["fields"]["labels"], sent["properties"][0]["value"]["Exempt"]), (["security"], "security")) # type: ignore[index]
|
|
|
|
def test_no_other_item_is_labelled(self):
|
|
self.add(FIELDS | {"Exempt": "owner"})
|
|
self.assertNotIn("labels", self.sent(ISSUES)[0]["fields"]) # type: ignore[index]
|
|
|
|
def test_links_the_issue_as_blocked_by_each_blocker_once_filed(self):
|
|
self.open = [issue("ABC-34"), issue("ABC-35")]
|
|
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 35"}), Written(40))
|
|
self.assertEqual([(method, url) for method, url, _ in self.calls][-3:], [("POST", ISSUES), ("POST", LINKS), ("POST", LINKS)])
|
|
self.assertEqual(self.sent(LINKS), [{"type": {"name": "Blocks"}, "inwardIssue": {"key": f"ABC-{blocker}"}, "outwardIssue": {"key": "ABC-40"}} for blocker in (34, 35)])
|
|
|
|
def test_a_blocker_that_is_no_open_child_fails_before_anything_is_filed(self):
|
|
self.open = [issue("ABC-34")]
|
|
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 36"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 36 to be blocked by"))
|
|
self.assertEqual(self.sent(ISSUES), [])
|
|
|
|
def test_a_field_out_of_format_fails_before_any_request(self):
|
|
cases = ({"L": "9"}, {"Release": "soon"}, {"Release": ""}, {"Moves": "much"}, {"Exempt": "whim"}, {"Blocked by": "ABC-34"}, {"Tagline": "Count\nthe runs."}, {"Tagline": " "})
|
|
for change in cases:
|
|
with self.subTest(change=change):
|
|
self.assertIsInstance(self.add(FIELDS | change), Failure)
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_each_field_out_of_format_fails_saying_how(self):
|
|
cases = (
|
|
({"Tagline": "** **"}, "the item has no tagline"),
|
|
({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"),
|
|
({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
|
({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
|
|
)
|
|
for change, reason in cases:
|
|
with self.subTest(change=change):
|
|
self.assertEqual(self.add(FIELDS | change), Failure(reason))
|
|
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Tagline"}), Failure("the item has no tagline"))
|
|
|
|
def test_an_item_without_moves_files_with_none(self):
|
|
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Moves"}), Written(40))
|
|
self.assertEqual(self.sent(ISSUES)[0]["properties"][0]["value"]["Moves"], "") # type: ignore[index]
|
|
|
|
def test_a_field_the_plan_does_not_have_is_a_programming_error(self):
|
|
with self.assertRaises(ValueError):
|
|
self.add(FIELDS | {"Colour": "red"})
|
|
|
|
def test_an_item_without_a_release_fails_naming_the_field(self):
|
|
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0"))
|
|
|
|
def test_a_detail_that_does_not_convert_fails_before_any_request(self):
|
|
self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign]
|
|
self.assertEqual(self.add(detail="Why."), Failure("cannot convert the item's detail to a Jira description: docker is not running"))
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_an_item_jira_refuses_fails_with_jiras_reason(self):
|
|
self.created = Failure("POST /rest/api/3/issue answered 400: Version name '0.1.0' is not valid")
|
|
self.assertEqual(self.add(), Failure(f"cannot file the item under ABC-12: POST /rest/api/3/issue answered 400: Version name '0.1.0' is not valid; {PERHAPS_FILED}"))
|
|
|
|
def test_an_answer_that_names_no_issue_of_the_epics_project_fails(self):
|
|
for answer in ({}, {"key": 7}, {"key": "OTHER-5"}, ["ABC-40"]):
|
|
with self.subTest(answer=answer):
|
|
self.created = answer
|
|
self.assertEqual(self.add(), Failure(f"Jira answered the new issue without an issue key in ABC; {PERHAPS_FILED}"))
|
|
|
|
def test_a_link_jira_refuses_leaves_the_item_filed_with_a_note_and_the_other_links_made(self):
|
|
refusal = "POST /rest/api/3/issueLink answered 404: No issue link type with name 'Blocks' found."
|
|
self.open, self.linked = [issue("ABC-34"), issue("ABC-35")], Failure(refusal)
|
|
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 35"}), Written(40, tuple(f"filed ABC-40, but cannot link it as blocked by ABC-{blocker}: {refusal}; link it in Jira" for blocker in (34, 35))))
|
|
self.assertEqual(len(self.sent(LINKS)), 2)
|
|
|
|
def test_files_under_the_fix_version_as_the_project_spells_it(self):
|
|
self.assertEqual(self.add(FIELDS | {"Release": "0.2.0"}), Written(40))
|
|
self.assertEqual(self.sent(ISSUES)[0]["fields"]["fixVersions"], [{"name": "v0.2.0"}]) # type: ignore[index]
|
|
|
|
def test_a_release_the_project_has_no_fix_version_for_fails_before_anything_is_filed(self):
|
|
for versions in ([{"name": "0.1.0"}], {"name": "0.3.0"}, [], 7):
|
|
with self.subTest(versions=versions):
|
|
self.versions = versions
|
|
self.assertEqual(self.add(FIELDS | {"Release": "0.3.0"}), Failure("the Jira project ABC has no Fix Version 0.3.0 or v0.3.0; create it in Jira, or file the item under a release it has"))
|
|
self.assertEqual(self.sent(ISSUES), [])
|
|
|
|
def test_fix_versions_that_cannot_be_read_fail_before_anything_is_filed(self):
|
|
self.versions = Failure("GET /rest/api/3/project/ABC/versions answered 403: Forbidden")
|
|
self.assertEqual(self.add(), Failure("cannot read ABC's Fix Versions: GET /rest/api/3/project/ABC/versions answered 403: Forbidden"))
|
|
self.assertEqual(self.sent(ISSUES), [])
|
|
|
|
def test_what_it_files_reads_back_as_the_item(self):
|
|
self.add(FIELDS | {"Exempt": "owner"}, "Why it counts.")
|
|
sent, = self.sent(ISSUES)
|
|
raw = {"key": "ABC-40", "fields": sent["fields"] | {"issuelinks": []}, "properties": {entry["key"]: entry["value"] for entry in sent["properties"]}} # type: ignore[index, operator, union-attr]
|
|
filed = jira_epic.issue_of(raw)
|
|
assert isinstance(filed, jira_epic.Issue), filed
|
|
plan = jira_epic.plan_of([filed], EPIC, lambda documents: [text_of(document) for document in documents])
|
|
assert isinstance(plan, Plan), plan
|
|
item, = plan.items
|
|
self.assertEqual((item.id, item.release, item.exempt, item.tagline, item.moves, item.detail), (40, release_of("0.1.0"), "owner", "**Count the runs.**", (("1", 9),), "Why it counts."))
|
|
self.assertEqual({name: item.scores[name] for name in "LEIS"}, {"L": 1, "E": 2, "I": 3, "S": 1})
|
|
|
|
def test_a_missing_env_file_fails_before_any_request(self):
|
|
self.env.unlink()
|
|
self.assertIsInstance(self.add(), Failure)
|
|
self.assertEqual(self.calls, [])
|
|
|
|
|
|
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
|
|
|
|
|
|
def transition(id_: str, name: str, status: str, category: str = "done") -> dict[str, object]:
|
|
return {"id": id_, "name": name, "to": {"name": status, "statusCategory": {"key": category}}}
|
|
|
|
|
|
class Finishing(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.calls: list[tuple[str, str, object]] = []
|
|
self.open = [issue("ABC-34"), issue("ABC-35")]
|
|
self.transitions: object = {"transitions": [transition("11", "Start", "In Progress", "indeterminate"), transition("31", "Mark as done", "Done")]}
|
|
self.moved: object = None
|
|
|
|
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
|
"""Stands in for Jira: answers the epic, self.open to the search, self.transitions for ABC-34's transitions and self.moved to a transition of it."""
|
|
self.calls.append((method, url, body))
|
|
assert authorization == AUTHORIZATION
|
|
if url == TRANSITIONS:
|
|
return self.transitions if method == "GET" else self.moved
|
|
return {SEARCH: {"issues": self.open}}.get(url, {"key": "ABC-12"})
|
|
|
|
def finish(self, id_: int = 34, by: Finish | None = Finish("Mark as done", "Done")):
|
|
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, finish_by=by).finish(id_)
|
|
|
|
def posts(self) -> list[tuple[str, str, object]]:
|
|
return [call for call in self.calls if call[0] == "POST" and call[1] != SEARCH]
|
|
|
|
def test_moves_the_issue_by_the_transition_the_config_names(self):
|
|
self.assertEqual(self.finish(), Written(34))
|
|
self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})])
|
|
|
|
def test_a_config_that_names_no_transition_fails_before_any_request(self):
|
|
self.assertEqual(self.finish(by=None), Failure("the config names no transition to finish an item by: set `jira-finish-transition` and `jira-finish-status`, as `project-config --help` shows"))
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_moved(self):
|
|
self.assertEqual(self.finish(36), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 36"))
|
|
self.assertEqual(self.posts(), [])
|
|
|
|
def test_a_transition_the_issue_does_not_have_fails_naming_those_it_has(self):
|
|
self.assertEqual(self.finish(by=Finish("Close", "Done")), Failure("ABC-34 has no transition 'Close' from its status, only 'Start' to 'In Progress' and 'Mark as done' to 'Done': set `jira-finish-transition` to one of them"))
|
|
self.assertEqual(self.posts(), [])
|
|
|
|
def test_a_transition_that_leads_to_another_status_fails(self):
|
|
self.assertEqual(self.finish(by=Finish("Mark as done", "Closed")), Failure("ABC-34's transition 'Mark as done' leads to the status 'Done', not to 'Closed', which `jira-finish-status` names"))
|
|
self.assertEqual(self.posts(), [])
|
|
|
|
def test_picks_among_transitions_of_one_name_the_one_to_the_status(self):
|
|
self.transitions = {"transitions": [transition("30", "Close", "Rejected"), transition("31", "Close", "Done")]}
|
|
self.assertEqual(self.finish(by=Finish("Close", "Done")), Written(34))
|
|
self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})])
|
|
|
|
def test_a_status_jira_does_not_count_as_done_fails_since_the_item_would_stay_in_the_plan(self):
|
|
self.assertEqual(self.finish(by=Finish("Start", "In Progress")), Failure("ABC-34's transition 'Start' leads to the status 'In Progress', which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status"))
|
|
self.assertEqual(self.posts(), [])
|
|
|
|
def test_an_issue_with_no_transition_fails_saying_so(self):
|
|
self.transitions = {"transitions": []}
|
|
self.assertEqual(self.finish(), Failure("ABC-34 has no transition 'Mark as done' from its status, nor any other the account may make"))
|
|
|
|
def test_transitions_that_cannot_be_read_fail(self):
|
|
self.transitions = Failure("HTTP 403")
|
|
self.assertEqual(self.finish(), Failure("cannot read ABC-34's transitions: HTTP 403"))
|
|
|
|
def test_transitions_in_another_shape_fail(self):
|
|
for answered in ([], {"transitions": "none"}, {"transitions": [{"id": 31, "name": "Mark as done", "to": {"name": "Done"}}]}, {"transitions": ["odd"]}):
|
|
with self.subTest(answered=answered):
|
|
self.transitions = answered
|
|
self.assertEqual(self.finish(), Failure("Jira answered ABC-34's transitions in a shape other than the one it documents"))
|
|
|
|
def test_a_move_jira_refuses_fails_with_jiras_reason(self):
|
|
self.moved = Failure("HTTP 400: Resolution is required")
|
|
self.assertEqual(self.finish(), Failure("cannot move ABC-34 by 'Mark as done': HTTP 400: Resolution is required"))
|
|
|
|
def test_a_missing_env_file_fails_before_any_request(self):
|
|
self.env.unlink()
|
|
self.assertIsInstance(self.finish(), Failure)
|
|
self.assertEqual(self.calls, [])
|
|
|
|
|
|
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()
|