849 lines
51 KiB
Python
849 lines
51 KiB
Python
import base64
|
|
import dataclasses
|
|
import pathlib
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from project_config.settings import DEFAULT_FLOOR, Epic, Finish
|
|
from plan.todo_table import EXEMPTIONS
|
|
from failure import Failure
|
|
from plan_store import jira_epic
|
|
from plan_store.plans import Plan, Written
|
|
from plan import ranking
|
|
from adf_codec.convert import Refused
|
|
from 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 link_id(blocked: str, blocker: str) -> str:
|
|
"""The id Jira gives the link that says blocked is blocked by blocker."""
|
|
return f"{blocked}<{blocker}"
|
|
|
|
|
|
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 = [{"id": link_id(key, blocker), "type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by]
|
|
links += [{"id": link_id(blocked, key), "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, scoring=Stated())
|
|
|
|
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("item ABC-34's Exempt 'because' is not empty or one of decision, defect, owner, principle, question, security; ABC-34 holds it in its issue property plan-item"))
|
|
|
|
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
|
|
self.assertEqual(dataclasses.replace(self.store(), max_pages=2).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": [{"id": "1", "type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"id": "1", "type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-2"}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"id": 7, "type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-2"}}]}}, 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")), scoring=Stated())
|
|
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"), scoring=Stated())
|
|
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_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 it 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"}
|
|
RANK = "https://acme.atlassian.net/rest/agile/1.0/issue/rank"
|
|
# Goal 1 weighs 1 and goal 2, a maintain goal, 0.5, so under the formula V / 2**S, FIELDS scores 9 / 2 = 4.5.
|
|
README = "# P\n\n## Goals\n\n**Void:** code health, since a test project has no code to read.\n\n1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n\n## Audience\n\nMe.\n"
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Stated:
|
|
"""Stands in for the scoring a project's config states, with the goal weights README gives."""
|
|
formula: str = "V / 2**S"
|
|
bar: float = 1
|
|
|
|
def read(self) -> ranking.Scoring | Failure:
|
|
return ranking.config_scoring(self.formula, self.bar, README, "", "", DEFAULT_FLOOR)
|
|
|
|
|
|
def filed(key: str, moves: str = "1 by 9", s: int = 1, exempt: str = "") -> dict[str, object]:
|
|
"""An open child the loop filed, which scores 9 / 2**s with moves "1 by 9"."""
|
|
return issue(key, scores=PROPERTY | {"Moves": moves, "S": s, "Exempt": exempt})
|
|
|
|
|
|
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"}}]
|
|
self.ranked: object = None
|
|
self.scoring = Stated()
|
|
|
|
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, self.linked to a new link and self.ranked to a rank."""
|
|
self.calls.append((method, url, body))
|
|
assert authorization == AUTHORIZATION
|
|
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions, RANK: self.ranked}.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, scoring=self.scoring).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([call for call in self.calls if call[1] != SEARCH and "/issue/ABC-12" not in call[1]], [("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"}, "the item to file's L '9' is not a whole number from 1 to 4"),
|
|
({"Exempt": "whim"}, f"the item to file's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
|
({"Blocked by": "ABC-34"}, "the item to file'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.scoring = Stated(bar=0)
|
|
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 to file's Release '' is not a semver 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 name 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, [])
|
|
|
|
def test_an_item_under_the_bar_fails_before_any_request(self):
|
|
self.assertEqual(self.add(FIELDS | {"Moves": "2 by 1", "S": "3"}), Failure("the item to file scores 0.1, under the bar 1; don't file it, or mark it with a reason the bar doesn't apply"))
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_the_bar_holds_the_score_rounded_to_one_decimal(self):
|
|
for formula, bar, filed_ in (("0.96", 1, True), ("0.6", 0.7, False)):
|
|
with self.subTest(formula=formula, bar=bar):
|
|
self.scoring = Stated(formula=formula, bar=bar)
|
|
self.assertEqual(self.add() == Written(40), filed_)
|
|
|
|
def test_an_exempt_item_under_the_bar_files(self):
|
|
self.assertEqual(self.add(FIELDS | {"Moves": "", "Exempt": "owner"}), Written(40))
|
|
|
|
def test_an_item_that_names_a_goal_the_goals_file_lacks_fails_before_any_request(self):
|
|
self.assertEqual(self.add(FIELDS | {"Moves": "3 by 1"}), Failure("the item to file cites goal 3, which the goals file's ## Goals does not number"))
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_an_item_without_every_score_fails_before_any_request(self):
|
|
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "S"}), Failure("the item to file has no S: score it on L, E, I and S"))
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_a_formula_that_does_not_parse_fails_before_any_request(self):
|
|
self.scoring = Stated(formula="V +")
|
|
self.assertEqual(self.add(), Failure("cannot score the item to file: the formula 'V +' does not parse"))
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_a_formula_that_gives_the_item_no_finite_score_fails_before_any_request(self):
|
|
self.scoring = Stated(formula="1 ** (1 / (S - S))")
|
|
self.assertEqual(self.add(), Failure("the formula gives the item to file no finite score"))
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_ranks_the_item_just_before_the_first_issue_the_loop_filed_that_scores_lower(self):
|
|
# ABC-30 and ABC-33 are a person's, ABC-31 a security finding, and ABC-32 scores as much as the new item.
|
|
self.open = [issue("ABC-30"), filed("ABC-31", s=4, exempt="security"), filed("ABC-32"), issue("ABC-33", scores={"L": 1, "E": 1, "I": 1, "S": 4, "Moves": "1 by 1"}), filed("ABC-34", s=2), filed("ABC-35", s=3)]
|
|
self.assertEqual(self.add(), Written(40))
|
|
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-34"}])
|
|
self.assertEqual([method for method, url, _ in self.calls if url == RANK], ["PUT"])
|
|
|
|
def test_ranks_a_security_finding_just_before_the_first_issue_the_loop_filed_that_isnt_one(self):
|
|
self.open = [issue("ABC-30"), filed("ABC-31", exempt="security"), filed("ABC-32"), filed("ABC-33", s=4)]
|
|
self.assertEqual(self.add(FIELDS | {"Exempt": "security", "S": "4"}), Written(40))
|
|
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-32"}])
|
|
|
|
def test_ranks_a_question_just_before_the_first_issue_the_loop_filed_that_isnt_one(self):
|
|
self.open = [filed("ABC-31", exempt="question"), filed("ABC-32", s=4, exempt="security")]
|
|
self.assertEqual(self.add(FIELDS | {"Exempt": "question"}), Written(40))
|
|
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-32"}])
|
|
|
|
def test_leaves_the_item_last_where_no_issue_the_loop_filed_scores_lower(self):
|
|
self.open = [issue("ABC-30", scores={}), filed("ABC-31"), filed("ABC-32", s=2, exempt="security")]
|
|
self.assertEqual(self.add(), Written(40))
|
|
self.assertEqual(self.sent(RANK), [])
|
|
|
|
def test_a_rank_jira_refuses_leaves_the_item_filed_with_a_note(self):
|
|
self.open = [filed("ABC-34", s=2)]
|
|
refusals = (
|
|
(Failure("PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"), "PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"),
|
|
({"entries": [{"issueKey": "ABC-40", "status": 400, "errors": ["Rank is not configured"]}]}, "Rank is not configured"),
|
|
({"entries": [{"status": 200}, {"status": 400}, {"status": 404, "errors": ["gone", "locked"]}]}, "Jira answered 400; gone; locked"),
|
|
)
|
|
for answer, reason in refusals:
|
|
with self.subTest(answer=answer):
|
|
self.ranked = answer
|
|
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it before ABC-34: {reason}; rank it in Jira",)))
|
|
|
|
def test_an_issue_the_loop_filed_that_does_not_score_leaves_the_item_filed_unranked_with_a_note(self):
|
|
unscored = {name: value for name, value in PROPERTY.items() if name != "S"}
|
|
for open_, reason in (
|
|
(filed("ABC-34", moves="3 by 1", s=2), "ABC-34 cites goal 3, which the goals file's ## Goals does not number"),
|
|
(issue("ABC-34", scores=unscored), "ABC-34 holds no S"),
|
|
(issue("ABC-34", scores=PROPERTY | {"L": 11}), "item ABC-34's L '11' is not a whole number from 1 to 4; ABC-34 holds it in its issue property plan-item"),
|
|
):
|
|
with self.subTest(reason=reason):
|
|
self.calls.clear()
|
|
self.open = [open_]
|
|
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it: {reason}; rank it in Jira",)))
|
|
self.assertEqual(self.sent(RANK), [])
|
|
|
|
|
|
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
|
|
|
|
|
|
COMMENT = "Scored for planning: a small change to one module."
|
|
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at ABC-34 before editing the item again"
|
|
|
|
|
|
class Editing(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]] = []
|
|
# The loop filed ABC-34. A person filed ABC-35, which nobody scored, and ABC-36, which holds scores.
|
|
self.open: list[object] = [issue("ABC-34", scores=PROPERTY), issue("ABC-35"), issue("ABC-36", scores={"L": 3, "E": 1, "I": 1, "S": 2})]
|
|
self.edited: object = None
|
|
self.commented: object = {"id": "10100"}
|
|
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}]
|
|
self.linked: object = None
|
|
self.unlinked: object = None
|
|
|
|
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.edited to an edit, self.commented to a new comment, self.linked to a new link and self.unlinked to a deleted one."""
|
|
self.calls.append((method, url, body))
|
|
assert authorization == AUTHORIZATION
|
|
if method == "PUT":
|
|
return self.edited
|
|
if method == "DELETE":
|
|
return self.unlinked
|
|
if url == LINKS:
|
|
return self.linked
|
|
return self.commented if url.endswith("/comment") else {SEARCH: {"issues": self.open}, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
|
|
|
|
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
|
|
return adf(markdown)
|
|
|
|
def edit(self, id_: int, fields: dict[str, str], detail: str | None = None, comment: str | None = None):
|
|
return jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: [text_of(document) for document in documents], self.to_adf, scoring=Stated()).edit(id_, fields, detail, comment)
|
|
|
|
def writes(self) -> list[tuple[str, str, object]]:
|
|
"""Each request that changes Jira, in order."""
|
|
return [call for call in self.calls if call[0] in ("PUT", "DELETE") or call[1].endswith(("/comment", "/issueLink"))]
|
|
|
|
def test_sets_the_summary_description_and_scores_of_an_issue_the_loop_filed_in_one_request(self):
|
|
self.assertEqual(self.edit(34, {"Tagline": "**Count every run.**", "L": "2", "Moves": ""}, "Why it counts."), Written(34))
|
|
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {
|
|
"fields": {"summary": "Count every run.", "description": adf("Why it counts.")},
|
|
"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2, "Moves": ""}}],
|
|
})])
|
|
|
|
def test_sends_only_what_the_edit_names(self):
|
|
self.edit(34, {"Tagline": "Count every run."})
|
|
self.edit(34, {"E": "3"})
|
|
self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}])
|
|
|
|
def test_a_detail_unchanged_since_the_read_leaves_the_description_as_jira_holds_it(self):
|
|
# Jira's own spacing paragraph and localIds, which a description converted back from markdown would lose.
|
|
held = {"type": "doc", "version": 1, "content": [{"type": "paragraph", "attrs": {"localId": "p-1"}, "content": [{"type": "text", "text": "Why it counts."}]}, {"type": "paragraph", "attrs": {"localId": "p-2"}}]}
|
|
self.open = [issue("ABC-34", scores=PROPERTY, description=held)]
|
|
self.assertEqual(self.edit(34, {"L": "2"}, "Why it counts.\n"), Written(34))
|
|
self.assertEqual(self.edit(34, {}, "Why it counts."), Written(34))
|
|
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2}}]})])
|
|
|
|
def test_an_edited_detail_replaces_the_description(self):
|
|
self.open = [issue("ABC-34", scores=PROPERTY, description=adf("Why it counts."))]
|
|
self.edit(34, {}, "Why it counts twice.")
|
|
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": adf("Why it counts twice.")}})])
|
|
|
|
def test_an_empty_detail_removes_the_description(self):
|
|
self.open = [issue("ABC-34", scores=PROPERTY, description=adf("Why it counts."))]
|
|
self.edit(34, {}, " \n")
|
|
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": None}})])
|
|
|
|
def test_an_edit_of_the_release_sets_the_fix_version_as_the_project_spells_it(self):
|
|
self.assertEqual(self.edit(34, {"Release": "0.2.0"}), Written(34))
|
|
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"fixVersions": [{"name": "v0.2.0"}]}})])
|
|
|
|
def test_an_edit_of_the_release_and_the_tagline_sends_both(self):
|
|
self.edit(34, {"Release": "0.2.0", "Tagline": "Count every run."})
|
|
self.assertEqual(self.writes()[0][2], {"fields": {"summary": "Count every run.", "fixVersions": [{"name": "v0.2.0"}]}})
|
|
|
|
def test_an_empty_tagline_fails_before_any_write(self):
|
|
self.assertEqual(self.edit(34, {"Tagline": "** **"}), Failure("the item has no tagline"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_a_release_the_project_has_no_fix_version_for_fails_before_any_write(self):
|
|
self.assertEqual(self.edit(34, {"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 name a release it has"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_an_exempt_that_becomes_or_stops_being_security_adds_or_removes_the_label(self):
|
|
self.edit(34, {"Exempt": "security"})
|
|
self.open = [issue("ABC-34", scores=PROPERTY | {"Exempt": "security"})]
|
|
self.edit(34, {"Exempt": "owner"})
|
|
self.edit(34, {"Exempt": "security"})
|
|
self.assertEqual([body.get("update") for _, _, body in self.writes()], [{"labels": [{"add": "security"}]}, {"labels": [{"remove": "security"}]}, None]) # type: ignore[attr-defined]
|
|
|
|
def test_scores_an_issue_a_person_filed_and_comments_why(self):
|
|
self.assertEqual(self.edit(35, {"L": "2", "E": "2", "I": "3", "S": "3", "Moves": "1 by 4"}, None, COMMENT), Written(35))
|
|
self.assertEqual(self.writes(), [
|
|
("PUT", f"{ISSUES}/ABC-35", {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}}]}),
|
|
("POST", f"{ISSUES}/ABC-35/comment", {"body": adf(COMMENT)}),
|
|
])
|
|
|
|
def test_rescores_a_persons_issue_that_holds_scores_keeping_the_rest(self):
|
|
self.edit(36, {"L": "2"}, None, COMMENT)
|
|
self.assertEqual(self.writes()[0][2], {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""}}]})
|
|
|
|
def test_a_persons_issue_is_never_labelled(self):
|
|
self.edit(36, {"Exempt": "security"}, None, COMMENT)
|
|
self.assertNotIn("update", self.writes()[0][2]) # type: ignore[operator]
|
|
|
|
def test_scoring_a_persons_issue_without_a_comment_fails_before_any_write(self):
|
|
for comment in (None, "", " \n"):
|
|
with self.subTest(comment=comment):
|
|
self.assertEqual(self.edit(35, {"L": "2"}, None, comment), Failure("a person filed ABC-35, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_what_a_person_wrote_or_planned_is_never_edited(self):
|
|
for fields, detail in (({"Tagline": "Count every run."}, None), ({}, "Why."), ({}, ""), ({"Release": "0.2.0"}, None), ({"Tagline": "Count.", "Release": "0.2.0", "L": "1"}, "")):
|
|
with self.subTest(fields=fields, detail=detail):
|
|
self.assertEqual(self.edit(36, fields, detail, COMMENT), Failure("a person filed ABC-36, so the loop sets only its scores: change its summary, description, links and Fix Version in Jira"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_scoring_an_unscored_issue_in_part_fails_before_any_write(self):
|
|
self.assertEqual(self.edit(35, {"L": "2", "E": "2"}, None, COMMENT), Failure("ABC-35 would hold some of L, E, I, S and not the rest: set them together"))
|
|
self.assertEqual(self.edit(35, {"Exempt": "question"}, None, COMMENT), Written(35))
|
|
self.assertEqual(len(self.writes()), 2)
|
|
|
|
def test_a_comment_on_an_edit_of_the_loops_own_issue_is_posted_too(self):
|
|
self.edit(34, {"L": "2"}, None, COMMENT)
|
|
self.assertEqual(self.writes()[1], ("POST", f"{ISSUES}/ABC-34/comment", {"body": adf(COMMENT)}))
|
|
|
|
def test_a_comment_jira_refuses_leaves_the_edit_made_with_a_note(self):
|
|
self.commented = Failure("HTTP 403")
|
|
self.assertEqual(self.edit(36, {"L": "2"}, None, COMMENT), Written(36, ("edited ABC-36, but cannot post the comment: HTTP 403; post it in Jira",)))
|
|
|
|
def test_links_each_new_blocker_to_an_issue_the_loop_filed(self):
|
|
self.assertEqual(self.edit(34, {"Blocked by": "35, 36"}), Written(34))
|
|
self.assertEqual(self.writes(), [("POST", LINKS, {"type": {"name": "Blocks"}, "inwardIssue": {"key": f"ABC-{blocker}"}, "outwardIssue": {"key": "ABC-34"}}) for blocker in (35, 36)])
|
|
|
|
def test_links_a_blocker_named_twice_once(self):
|
|
self.edit(34, {"Blocked by": "35, 35"})
|
|
self.assertEqual([body["inwardIssue"]["key"] for _, _, body in self.writes()], ["ABC-35"]) # type: ignore[index]
|
|
|
|
def test_deletes_the_link_of_each_blocker_the_edit_drops_and_makes_none_for_one_it_keeps(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"))
|
|
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Written(34))
|
|
self.assertEqual(self.writes(), [("DELETE", f"{LINKS}/{link_id('ABC-34', 'ABC-36')}", None)])
|
|
|
|
def test_an_empty_blocked_by_deletes_every_link_the_issue_holds(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"), blocks=("ABC-35",))
|
|
self.assertEqual(self.edit(34, {"Blocked by": ""}), Written(34))
|
|
self.assertEqual(self.writes(), [("DELETE", f"{LINKS}/{link_id('ABC-34', blocker)}", None) for blocker in ("ABC-35", "ABC-36")])
|
|
|
|
def test_a_link_to_an_issue_that_is_no_open_child_is_never_deleted(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "OPS-9", "ABC-99"))
|
|
self.assertEqual(self.edit(34, {"Blocked by": "36"}), Written(34))
|
|
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("POST", LINKS), ("DELETE", f"{LINKS}/{link_id('ABC-34', 'ABC-35')}")])
|
|
|
|
def test_an_edit_that_names_no_blocked_by_leaves_the_links_as_they_are(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35",))
|
|
self.edit(34, {"L": "2"})
|
|
self.assertEqual([method for method, _, _ in self.writes()], ["PUT"])
|
|
|
|
def test_a_blocked_by_the_issue_already_holds_writes_nothing(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"))
|
|
self.assertEqual(self.edit(34, {"Blocked by": "36, 35"}), Written(34))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_a_blocker_swapped_for_another_deletes_one_link_and_makes_one(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35",))
|
|
self.edit(34, {"Blocked by": "36"})
|
|
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("POST", LINKS), ("DELETE", f"{LINKS}/{link_id('ABC-34', 'ABC-35')}")])
|
|
|
|
def test_changes_the_links_after_the_edit_and_before_the_comment(self):
|
|
self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "35"}, None, COMMENT), Written(34))
|
|
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("PUT", f"{ISSUES}/ABC-34"), ("POST", LINKS), ("POST", f"{ISSUES}/ABC-34/comment")])
|
|
|
|
def test_a_failed_edit_makes_no_link(self):
|
|
self.edited = Failure("HTTP 400")
|
|
self.assertIsInstance(self.edit(34, {"L": "2", "Blocked by": "35"}), Failure)
|
|
self.assertEqual([method for method, _, _ in self.writes()], ["PUT"])
|
|
|
|
def test_a_link_jira_refuses_leaves_the_edit_made_with_a_note_and_the_other_links_changed(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-36",))
|
|
self.linked = Failure("HTTP 403")
|
|
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Written(34, ("edited ABC-34, but cannot link it as blocked by ABC-35: HTTP 403; link it in Jira",)))
|
|
self.assertEqual([method for method, _, _ in self.writes()], ["POST", "DELETE"])
|
|
|
|
def test_a_link_jira_refuses_to_delete_leaves_a_note_and_the_comment_posted(self):
|
|
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"))
|
|
self.unlinked = Failure("HTTP 404")
|
|
self.assertEqual(self.edit(34, {"Blocked by": ""}, None, COMMENT), Written(34, ("edited ABC-34, but cannot delete the link that makes it blocked by ABC-35: HTTP 404; delete it in Jira", "edited ABC-34, but cannot delete the link that makes it blocked by ABC-36: HTTP 404; delete it in Jira")))
|
|
self.assertEqual(self.writes()[-1][1], f"{ISSUES}/ABC-34/comment")
|
|
|
|
def test_a_blocker_that_is_no_open_child_fails_before_any_write(self):
|
|
self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "35, 40"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 40 to be blocked by"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_a_blocker_that_makes_the_issue_wait_for_itself_fails_before_any_write(self):
|
|
self.open[1] = issue("ABC-35", scores=PROPERTY, blocked_by=("ABC-34",))
|
|
self.open[2] = issue("ABC-36", scores=PROPERTY, blocked_by=("ABC-35",))
|
|
self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "36"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12: item 34 would be blocked by itself through 35, 36; drop one of the blockers"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_the_loop_names_its_items_by_number_not_by_key(self):
|
|
self.open += [issue("ABC-9", scores=PROPERTY, blocked_by=("ABC-10",)), issue("ABC-10", scores=PROPERTY, blocked_by=("ABC-34",))]
|
|
failure = self.edit(34, {"Blocked by": "9"})
|
|
self.assertTrue(failure.reason.endswith("through 9, 10; drop one of the blockers")) # type: ignore[union-attr]
|
|
|
|
def test_a_loop_the_plan_holds_without_the_issue_does_not_stop_its_edit(self):
|
|
self.open[1] = issue("ABC-35", scores=PROPERTY, blocked_by=("ABC-36",))
|
|
self.open[2] = issue("ABC-36", scores=PROPERTY, blocked_by=("ABC-35",))
|
|
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Written(34))
|
|
self.assertEqual([method for method, _, _ in self.writes()], ["POST"])
|
|
|
|
def test_a_blocked_by_out_of_format_or_naming_the_issue_itself_fails_before_any_write(self):
|
|
for cell in ("ABC-35", "35,36", "34"):
|
|
with self.subTest(cell=cell):
|
|
self.assertIsInstance(self.edit(34, {"Blocked by": cell}), Failure)
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_the_links_of_an_issue_a_person_filed_are_never_changed(self):
|
|
for id_ in (35, 36):
|
|
with self.subTest(id_=id_):
|
|
self.assertEqual(self.edit(id_, {"Blocked by": "34"}, None, COMMENT), Failure(f"a person filed ABC-{id_}, so the loop sets only its scores: change its summary, description, links and Fix Version in Jira"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_edited(self):
|
|
self.assertEqual(self.edit(40, {"L": "2"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 40"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_each_field_out_of_format_fails_before_any_write_saying_how(self):
|
|
for fields, detail, reason in (
|
|
({"L": "9"}, None, "item ABC-34's L '9' is not a whole number from 1 to 4"),
|
|
({"Moves": "much"}, None, "item ABC-34's Moves 'much' is not"),
|
|
({"Exempt": "tired"}, None, f"item ABC-34's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
|
({"Release": "soon"}, None, "item ABC-34's Release 'soon' is not a semver version, such as 1.2.0"),
|
|
({"Tagline": " "}, None, "the item has no tagline"),
|
|
({"Tagline": "Count\nruns."}, None, "the tagline holds a line break; keep it on one line"),
|
|
({}, "## Why", "the detail holds a ## or ### heading"),
|
|
):
|
|
with self.subTest(fields=fields, detail=detail):
|
|
failed = self.edit(34, fields, detail)
|
|
self.assertIsInstance(failed, Failure)
|
|
self.assertIn(reason, failed.reason)
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_a_detail_or_a_comment_that_does_not_convert_fails_before_any_write(self):
|
|
self.to_adf = lambda markdown: Failure("the codec is down") # type: ignore[method-assign]
|
|
self.assertEqual(self.edit(34, {}, "Why."), Failure("cannot convert the item's detail to a Jira description: the codec is down"))
|
|
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure("cannot convert the comment to a Jira comment: the codec is down"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_an_edit_jira_refuses_fails_with_jiras_reason_and_posts_no_comment(self):
|
|
self.edited = Failure("HTTP 400: Summary is too long")
|
|
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure(f"cannot edit ABC-34: HTTP 400: Summary is too long; {PERHAPS_EDITED}"))
|
|
self.assertEqual(len(self.writes()), 1)
|
|
|
|
def test_an_issue_in_another_shape_or_a_search_that_fails_fails_the_edit(self):
|
|
self.open = [{"key": "ABC-34", "fields": {}}]
|
|
self.assertIn("ABC-34 is not in the shape", self.edit(34, {"L": "2"}).reason)
|
|
self.open = [issue("ABC-34", scores=["odd"])] # type: ignore[arg-type]
|
|
self.assertEqual(self.edit(34, {"L": "2"}), Failure("ABC-34's issue property plan-item is not a JSON object"))
|
|
self.assertEqual(self.writes(), [])
|
|
|
|
def test_a_missing_env_file_fails_before_any_request(self):
|
|
self.env.unlink()
|
|
self.assertIsInstance(self.edit(34, {"L": "2"}), Failure)
|
|
self.assertEqual(self.calls, [])
|
|
|
|
def test_what_it_edits_reads_back_as_the_item(self):
|
|
self.edit(34, {"Tagline": "Count every run.", "S": "4"}, "Why it counts.")
|
|
body = self.writes()[0][2]
|
|
held = issue("ABC-34", summary=body["fields"]["summary"], scores=body["properties"][0]["value"], description=body["fields"]["description"]) # type: ignore[index]
|
|
self.open = [held]
|
|
plan = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: [text_of(document) for document in documents], scoring=Stated()).read()
|
|
assert isinstance(plan, Plan), plan
|
|
self.assertEqual((plan.items[0].tagline, plan.items[0].scores["S"], plan.items[0].scores["L"], plan.items[0].detail), ("**Count every run.**", 4, 1, "Why it counts."))
|
|
|
|
|
|
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
|
|
self.search_refused: Failure | None = 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, or self.search_refused where set, 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 == SEARCH and self.search_refused:
|
|
return self.search_refused
|
|
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, scoring=Stated()).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_search_jira_refuses_fails_the_finish_before_any_move(self):
|
|
self.search_refused = Failure("HTTP 500")
|
|
self.assertEqual(self.finish(), Failure("HTTP 500"))
|
|
self.assertEqual(self.posts(), [])
|
|
|
|
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': move the issue in Jira to a status that has it, or name in `jira-finish-transition` one that leads to a done status"))
|
|
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_two_transitions_share_the_name_and_the_one_to_the_status_is_made(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):
|
|
odd = [transition(31, "Mark as done", "Done"), transition("31", None, "Done"), transition("31", "Mark as done", ["Done"]), transition("31", "Mark as done", "Done", 4), {"id": "31", "name": "Mark as done", "to": "Done"}, {"id": "31", "name": "Mark as done", "to": {"name": "Done"}}, "odd"] # type: ignore[arg-type]
|
|
for answered in ([], {"transitions": "none"}, *({"transitions": [each]} for each in 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; unless Jira refused the request, the issue may have moved: look at ABC-34 before finishing the item again"))
|
|
|
|
def test_a_missing_env_file_fails_before_any_request(self):
|
|
self.env.unlink()
|
|
self.assertIsInstance(self.finish(), Failure)
|
|
self.assertEqual(self.calls, [])
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|