Answer stability round 1: 0 🔴, 10 🟡 (0 misread); share one REST client and env-file reader, read each issue into a checked value, convert descriptions last, and simplify the hard places the change touched

This commit is contained in:
2026-11-14 19:40:36 +01:00
parent d008dc09f2
commit 8ee67ed2b7
16 changed files with 501 additions and 283 deletions
+101 -88
View File
@@ -1,75 +1,72 @@
"""A plan kept as the child issues of one Jira Cloud epic, read over Jira's REST API.
An item is an open child issue. Its ID is the issue's number, so the epic's children all lie in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores.
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores.
The store only reads so far: every write is a Failure."""
import base64
import concurrent.futures
import dataclasses
import http.client
import json
import pathlib
import re
import typing
import urllib.error
import urllib.parse
import urllib.request
from adf_codec.convert import adf_to_markdown
from plan_store.markdown_edits import bold_cell
from project_config.settings import Epic
from release_plan.todo_table import EXEMPTIONS, is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
from failure import Failure
from release_plan.todo_table import is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
from mattermost_dm.dm import parse_env
from rest_client import json_request
from release_plan.release import parsed, Release, tagged
from plan_store.stores import Plan, Written
from rest_client.env_file import read_env
# One pair of keys for Jira and Confluence, which one Atlassian account's API token opens both.
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}.
PROPERTY = "plan-item"
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
# Seconds each connect and each read may wait.
TIMEOUT = 30
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
# The adf-codec containers run at once: each description is one run.
CONVERSIONS = 8
# The adf-codec containers run at once, each converting one description: one heavy slot's CPUs.
CONVERSIONS = 4
READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira"
# Sends a request with the Authorization header given, the body as JSON, and returns the JSON answer, or a Failure saying why there is none.
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[dict[str, typing.Any]], str | Failure]
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Refuses every redirect, which Jira's API never sends: urllib would resend the credentials to the new location, even one off https."""
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
return None
OPENER = urllib.request.build_opener(NoRedirect)
def http_json(method: str, url: str, authorization: str, body: object) -> object:
"""The JSON that url answers; a Failure naming the request where it answers an error, breaks HTTP or answers something other than JSON, and saying so where the site cannot be reached."""
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
request = urllib.request.Request(url, json.dumps(body).encode(), {"Authorization": authorization, "Content-Type": "application/json", "Accept": "application/json"}, method=method)
try:
with OPENER.open(request, timeout=TIMEOUT) as response:
raw = response.read()
except urllib.error.HTTPError as failure:
with failure:
return Failure(f"{request_name} answered {failure.code}: {failure.reason}")
except http.client.HTTPException as failure:
return Failure(f"{request_name} got a broken answer: {failure!r}")
except (OSError, ValueError) as failure:
return Failure(f"cannot be reached: {getattr(failure, 'reason', failure)}")
try:
return json.loads(raw)
except ValueError:
return Failure(f"{request_name} answered with something other than JSON")
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
@dataclasses.dataclass(frozen=True)
class Issue:
"""A child issue as Jira answered it, checked to hold what an item is read from."""
key: str
summary: str
description: dict[str, typing.Any] | None
fix_versions: tuple[str, ...]
# The key of each issue this one "is blocked by".
blockers: tuple[str, ...]
# PROPERTY's value; an empty object where the issue holds none.
scores: object
@property
def number(self) -> int:
return number(self.key)
@dataclasses.dataclass(frozen=True)
@@ -92,13 +89,11 @@ class JiraPlan:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
issues = children(self.epic, authorization, self.http)
if isinstance(issues, Failure):
return Failure(f"{self.epic.site}: {issues.reason}")
try:
return plan_of(issues, self.epic, self.to_markdown)
except (AttributeError, KeyError, TypeError):
return Failure(f"{self.epic.site} answered issues in another shape than Jira Cloud's REST API version 3 documents")
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
issues = [issue_of(raw) for raw in answered]
return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
return Failure(READ_ONLY)
@@ -111,31 +106,26 @@ class JiraPlan:
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file's KEY=value lines hold."""
try:
mode = env_file.stat().st_mode
text = env_file.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{env_file} does not exist; it needs {' and '.join(KEYS)}")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read {env_file}: {failure}")
if mode & 0o077:
return Failure(f"{env_file} holds an API token, so only its owner may read it; run chmod 600 {env_file}")
values = parse_env(text)
if missing := [key for key in KEYS if not values.get(key)]:
return Failure(f"{env_file} lacks {' and '.join(missing)}")
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def children(epic: Epic, authorization: str, http: Http) -> list[dict[str, typing.Any]] | Failure:
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
"""The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan."""
# The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart.
seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None)
if isinstance(seen, Failure):
return Failure(f"cannot read the epic {epic.key}: {seen.reason}")
body: dict[str, object] = {
"jql": f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC',
"fields": ["summary", "description", "fixVersions", "issuelinks"],
"properties": [PROPERTY],
"maxResults": PAGE,
}
found: list[dict[str, typing.Any]] = []
found: list[object] = []
for _ in range(MAX_PAGES):
page = http("POST", f"{epic.site}/rest/api/3/search/jql", authorization, body)
if isinstance(page, Failure):
@@ -149,48 +139,71 @@ def children(epic: Epic, authorization: str, http: Http) -> list[dict[str, typin
return Failure(f"the search for {epic.key}'s children did not end within {MAX_PAGES} pages")
def plan_of(issues: list[dict[str, typing.Any]], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure:
"""The plan the issues hold, in their order. Raises AttributeError, KeyError or TypeError where an issue is not in the shape Jira documents."""
def issue_of(raw: object) -> Issue | Failure:
"""The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how."""
key = raw.get("key") if isinstance(raw, dict) else None
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
return Failure("the search answered an issue without an issue key")
try:
fields = typing.cast(dict[str, typing.Any], raw)["fields"]
blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by")
issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {}))
except (AttributeError, KeyError, TypeError) as failure:
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers):
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key is of another type")
return issue
def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure:
"""The plan the issues hold, in their order."""
project = epic.key.rpartition("-")[0]
if strangers := [issue["key"] for issue in issues if not re.fullmatch(rf"{re.escape(project)}-[0-9]+", issue["key"])]:
if strangers := [issue.key for issue in issues if issue.key.rpartition("-")[0] != project]:
return Failure(f"{strangers[0]} is a child of {epic.key} in another Jira project, and an item's ID is its number in {project}; move it into {project} or out of the epic")
ids = {number(issue["key"]) for issue in issues}
with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool:
details = list(pool.map(lambda issue: detail(issue, to_markdown), issues))
items = [item(issue, ids, text) for issue, text in zip(issues, details)]
return next((found for found in items if isinstance(found, Failure)), None) or Plan([found for found in items if isinstance(found, Item)])
ids = {issue.number for issue in issues}
items = [item(issue, project, ids) for issue in issues]
if failed := next((found for found in items if isinstance(found, Failure)), None):
return failed
# The descriptions convert last, since each costs a container run, which a read that fails doesn't need.
texts = details(issues, to_markdown)
if isinstance(texts, Failure):
return texts
return Plan([dataclasses.replace(found, detail=texts.get(found.id, "")) for found in items if isinstance(found, Item)])
def number(key: str) -> int:
return int(key.rpartition("-")[2])
def detail(issue: dict[str, typing.Any], to_markdown: ToMarkdown) -> str | Failure:
"""The issue's description as markdown; empty where it has none."""
description = issue["fields"]["description"]
if description is None:
return ""
text = to_markdown(description)
return Failure(f"{issue['key']}'s description: {text.reason}") if isinstance(text, Failure) else text.strip()
def details(issues: list[Issue], to_markdown: ToMarkdown) -> dict[int, str] | Failure:
"""Each described issue's description as markdown, under the issue's number. The first converts alone, since that run builds the codec's image where the machine has none; the rest convert CONVERSIONS at a time."""
described = [(issue, issue.description) for issue in issues if issue.description is not None]
texts: list[str | Failure] = [to_markdown(description) for _, description in described[:1]]
if not any(isinstance(text, Failure) for text in texts):
with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool:
texts += pool.map(to_markdown, [description for _, description in described[1:]])
found = {}
for (issue, _), text in zip(described, texts):
if isinstance(text, Failure):
return Failure(f"{issue.key}'s description: {text.reason}")
found[issue.number] = text.strip()
return found
def item(issue: dict[str, typing.Any], ids: set[int], text: str | Failure) -> Item | Failure:
"""The item an issue holds, blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
if isinstance(text, Failure):
return text
key, fields = issue["key"], issue["fields"]
release = earliest_release([version["name"] for version in fields["fixVersions"]])
def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
"""The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
release = earliest_release(issue.fix_versions)
if release is None:
# Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan.
return Failure(f"{key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
blockers = [number(link["inwardIssue"]["key"]) for link in fields["issuelinks"] if link["type"]["inward"] == "is blocked by" and "inwardIssue" in link and link["inwardIssue"]["key"].rpartition("-")[0] == key.rpartition("-")[0]]
scored = scores(key, issue.get("properties", {}).get(PROPERTY, {}))
return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
return scored
return Item(number(key), release, scored[2], bold_cell(fields["summary"].strip()), scored[0], scored[1], tuple(sorted(set(blockers) & ids)), text)
blockers = {number(key) for key in issue.blockers if key.rpartition("-")[0] == project}
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
def earliest_release(names: list[str]) -> Release | None:
def earliest_release(names: tuple[str, ...]) -> Release | None:
"""The earliest release among Fix Versions named as a semver version, with a leading v or without; None where none is."""
releases = [release for name in names if (release := parsed(name) or tagged(name))]
return min(releases, default=None)
@@ -209,5 +222,5 @@ def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.A
return moves
exempt = named.get("Exempt", "")
if not is_exempt(exempt):
return Failure(f"item {key}'s Exempt {exempt!r} is not one a todo.md's items table takes")
return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}")
return levels, moves, exempt
+2 -2
View File
@@ -1,6 +1,6 @@
"""The one way a tool reads or writes a project's plan: through the store its config names.
The config's `plan` setting names the backend. A path names a markdown file, todo.md. A Jira epic names its child issues, which `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store.
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store.
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import dataclasses
@@ -44,7 +44,7 @@ class Written:
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend to the same behaviour. A write that fails leaves the plan as it was."""
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` only reads until todo.md's item 352. A write that fails leaves the plan as it was."""
@property
def label(self) -> str:
+85 -20
View File
@@ -3,6 +3,7 @@ import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
@@ -14,6 +15,7 @@ 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]:
@@ -42,13 +44,24 @@ class JiraPlan(unittest.TestCase):
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[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, document: dict[str, object]) -> str | Failure:
self.converted.append(document)
return text_of(document)
def store(self) -> jira_epic.JiraPlan:
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of)
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)}], []
@@ -66,7 +79,7 @@ class JiraPlan(unittest.TestCase):
self.read()
method, url, authorization, body = self.calls[0]
self.assertEqual((method, url), ("POST", SEARCH))
self.assertEqual(authorization, "Basic " + base64.b64encode(b"me@example.com:s3cret").decode())
self.assertEqual(authorization, AUTHORIZATION)
self.assertEqual(body, {
"jql": 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC',
"fields": ["summary", "description", "fixVersions", "issuelinks"],
@@ -74,6 +87,12 @@ class JiraPlan(unittest.TestCase):
"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.")))
@@ -96,15 +115,16 @@ class JiraPlan(unittest.TestCase):
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")):
item, = self.items(issue("ABC-34", versions=versions))
self.assertEqual(item.release, release_of("0.9.1"), versions)
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",)):
failure = self.read(issue("ABC-34", versions=versions))
self.assertIsInstance(failure, Failure)
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
self.assertIn("Fix Version", failure.reason) # type: ignore[union-attr]
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"))
@@ -113,9 +133,13 @@ class JiraPlan(unittest.TestCase):
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"):
failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type]
self.assertIsInstance(failure, Failure, scores)
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
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")]}]
@@ -126,12 +150,33 @@ class JiraPlan(unittest.TestCase):
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("https://acme.atlassian.net: 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):
for page in ([], {"issues": "none"}, {"issues": [{"key": "ABC-1"}]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [issue("ABC-1", summary=None)]}): # type: ignore[arg-type]
self.pages, self.calls = [page], []
self.assertIsInstance(self.store().read(), Failure, page)
for page in ([], {"issues": "none"}, {"issues": ["ABC-1"]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [{"key": "abc", "fields": {}}]}):
with self.subTest(page=page):
self.pages, self.calls = [page], []
self.assertIsInstance(self.store().read(), Failure)
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 | {"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_each_description_once_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(len(self.converted), 3)
def test_a_first_description_the_codec_refuses_converts_no_other(self):
calls: list[object] = []
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: calls.append(document) or Failure("no docker")) # type: ignore[func-returns-value]
self.pages = [{"issues": [issue("ABC-1", description=adf("One.")), issue("ABC-2", description=adf("Two."))]}]
self.assertEqual(store.read(), Failure("ABC-1's description: no docker"))
self.assertEqual(len(calls), 1)
def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self):
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: Failure("adf-codec refused"))
@@ -143,12 +188,12 @@ class JiraPlan(unittest.TestCase):
failure = self.read()
self.assertIsInstance(failure, Failure)
self.assertIn("ATLASSIAN_API_TOKEN", failure.reason) # type: ignore[union-attr]
self.assertEqual(self.calls, [])
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.assertIsInstance(self.read(), Failure)
self.assertEqual(self.calls, [])
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()
@@ -161,12 +206,32 @@ class JiraPlan(unittest.TestCase):
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)):
self.assertIsInstance(written, Failure)
self.assertEqual(self.calls, [])
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()