Hold the Jira backend's fake to credentials, JQL, fields and issue types, and test its failures

This commit is contained in:
2026-11-18 10:17:45 +01:00
parent 6b07e19c34
commit 61ed465e99
4 changed files with 90 additions and 32 deletions
+7 -3
View File
@@ -1,4 +1,5 @@
"""What every backend of an epic's plan must hold, as tests. A backend's test case inherits EpicStoreContract and unittest.TestCase, builds an epic with no issues in new_store, and changes an issue as a person would in the tracker in assign and close."""
import re
import typing
from do_epic.backend.protocol import EpicIssue, EpicStore
@@ -47,10 +48,13 @@ class EpicStoreContract:
self.assertEqual([(issue.key, issue.parent) for issue in read], [(first, store.epic), (task, first), (second, store.epic)])
self.assertEqual((read[1].summary, read[1].labels, read[1].detail), ("Count them in the api.", ("api",), ""))
def test_files_each_issue_under_its_own_key(self) -> None:
def test_files_each_issue_under_its_own_key_in_the_epics_project(self) -> None:
store = self.new_store()
keys = {self.filed(store, store.epic, "Count the runs."), self.filed(store, store.epic, "Count the runs.")}
self.assertEqual(len(keys), 2)
child = self.filed(store, store.epic, "Count the runs.")
keys = [child, self.filed(store, store.epic, "Count the runs."), self.filed(store, child, "Count them in the api.")]
self.assertEqual(len(set(keys)), 3)
project = store.epic.rpartition("-")[0]
self.assertEqual([re.fullmatch(f"{project}-[1-9][0-9]*", key) is not None for key in keys], [True] * 3)
def test_reads_the_assignee_and_a_done_status(self) -> None:
store = self.new_store()
+1 -1
View File
@@ -5,10 +5,10 @@ import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from project_config.settings import Epic
from do_epic.backend.protocol import EpicIssue, unfit
from failure import Failure
from plan_store.jira_epic import ISSUE_KEY, ISSUE_TYPE, project_of, searched
from project_config.settings import Epic
FIELDS = ["summary", "description", "labels", "assignee", "status", "parent"]
# How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes.
+1 -1
View File
@@ -5,8 +5,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from do_epic.backend.contract import EpicStoreContract
from do_epic.backend.fake import MemoryEpic
from failure import Failure
from do_epic.backend.fake import MemoryEpic
class MemoryEpicContract(EpicStoreContract, unittest.TestCase):
+81 -27
View File
@@ -1,19 +1,28 @@
import base64
import dataclasses
import pathlib
import re
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from do_epic.backend.contract import EpicStoreContract
from do_epic.backend.jira import JiraEpic
from failure import Failure
from project_config.settings import Epic
from do_epic.backend.contract import EpicStoreContract
from failure import Failure
from plan_store import jira_epic
from do_epic.backend.jira import JiraEpic
from adf_codec.convert import Refused
SITE = "https://acme.atlassian.net"
EPIC = Epic(SITE, "ABC-12")
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
EPIC_URL = f"{SITE}/rest/api/3/issue/ABC-12?fields=summary"
ISSUE_TYPES = f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes"
SEARCH = f"{SITE}/rest/api/3/search/jql"
ISSUES = f"{SITE}/rest/api/3/issue"
TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}}
TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]}
@@ -29,41 +38,46 @@ def to_markdown(documents: list[dict[str, object]]) -> list[str]:
@dataclasses.dataclass
class FakeJira:
"""Jira Cloud's REST API as JiraEpic calls it, holding issues as Jira answers them, in rank order, and answering a search two issues a page."""
"""Jira Cloud's REST API as JiraEpic calls it, holding issues as Jira answers them, in rank order, and answering a search two issues a page, with only the fields it asks for. Where answers holds a method and URL, that call answers what it holds."""
issues: list[dict[str, object]] = dataclasses.field(default_factory=list)
refuses: str | None = None
answers: dict[tuple[str, str], object] = dataclasses.field(default_factory=dict)
calls: list[tuple[str, str]] = dataclasses.field(default_factory=list)
def __call__(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url))
if self.refuses and method == "POST" and url.endswith("/issue"):
return Failure(self.refuses)
if method == "GET" and url == f"{SITE}/rest/api/3/issue/ABC-12?fields=summary":
if authorization != AUTHORIZATION:
return Failure("Jira answered 401")
if (method, url) in self.answers:
return self.answers[method, url]
if method == "GET" and url == EPIC_URL:
return {"key": "ABC-12"}
if method == "GET" and url == f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes":
if method == "GET" and url == ISSUE_TYPES:
return TYPES
if method == "POST" and url == f"{SITE}/rest/api/3/search/jql":
if method == "POST" and url == SEARCH:
return self.page(body)
if method == "POST" and url == f"{SITE}/rest/api/3/issue":
if method == "POST" and url == ISSUES:
return self.created(body)
return Failure(f"Jira answered 404 for {method} {url}")
def page(self, body: object) -> object:
assert isinstance(body, dict)
parents = re.findall(r'"([A-Z]+-[0-9]+)"', body["jql"])
found = [issue for issue in self.issues if issue["fields"]["parent"]["key"] in parents] # type: ignore[index]
matched = re.fullmatch(r'parent in \(("[A-Z]+-[0-9]+"(?:, "[A-Z]+-[0-9]+")*)\) ORDER BY Rank ASC', body["jql"])
if matched is None:
return Failure("Jira answered 400: the JQL is not valid")
parents = re.findall(r'"([A-Z]+-[0-9]+)"', matched[1])
found = [{"key": issue["key"], "fields": {name: value for name, value in issue["fields"].items() if name in body.get("fields", [])}} for issue in self.issues if issue["fields"]["parent"]["key"] in parents] # type: ignore[index, attr-defined]
start = int(body.get("nextPageToken", 0))
return {"issues": found[start:start + 2]} | ({"nextPageToken": str(start + 2)} if start + 2 < len(found) else {})
def created(self, body: object) -> object:
assert isinstance(body, dict)
fields = body["fields"]
parent = next((issue for issue in self.issues if issue["key"] == fields["parent"]["key"]), None)
subtask = fields["issuetype"] == {"id": "10003"}
if fields["parent"]["key"] != "ABC-12" and (parent is None or not subtask):
return Failure("Jira answered 400: the parent cannot hold this issue type")
parent = fields["parent"]["key"]
kind = {"name": "Task"} if parent == "ABC-12" else {"id": "10003"} if any(issue["key"] == parent for issue in self.issues) else None
if fields["project"] != {"key": "ABC"} or kind is None or fields["issuetype"] != kind:
return Failure("Jira answered 400: the project, parent or issue type is not valid")
key = f"ABC-{len(self.issues) + 100}"
self.issues.append({"key": key, "fields": {"summary": fields["summary"], "description": fields.get("description"), "labels": fields["labels"], "assignee": None, "status": TO_DO, "parent": {"key": fields["parent"]["key"]}}})
self.issues.append({"key": key, "fields": {"summary": fields["summary"], "description": fields.get("description"), "labels": fields["labels"], "assignee": None, "status": TO_DO, "parent": {"key": parent}}})
return {"id": "1", "key": key}
def change(self, key: str, **fields: object) -> None:
@@ -102,18 +116,58 @@ class Jira(Case):
def test_files_a_child_without_asking_for_issue_types(self) -> None:
self.new_store().file("ABC-12", "Count the runs.", "", ())
self.assertNotIn(("GET", f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes"), self.jira.calls)
self.assertNotIn(("GET", ISSUE_TYPES), self.jira.calls)
def test_a_refused_filing_says_the_issue_may_exist(self) -> None:
self.jira.refuses = "Jira answered 503"
self.assertEqual(self.new_store().file("ABC-12", "Count the runs.", "", ()), Failure("cannot file the issue under ABC-12: Jira answered 503; unless Jira refused the request, the issue may exist: look under ABC-12 before filing it again"))
def test_a_refused_filing_or_one_answered_without_a_key_says_the_issue_may_exist(self) -> None:
for answer, reason in ((Failure("Jira answered 503"), "cannot file the issue under ABC-12: Jira answered 503"), ({"id": "1"}, "Jira answered the new issue without an issue key")):
with self.subTest(answer=answer):
self.jira.answers[("POST", ISSUES)] = answer
self.assertEqual(self.new_store().file("ABC-12", "Count the runs.", "", ()), Failure(f"{reason}; unless Jira refused the request, the issue may exist: look under ABC-12 before filing it again"))
def test_a_detail_the_codec_refuses_files_nothing(self) -> None:
store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it"))
self.assertEqual(store.file("ABC-12", "Count the runs.", "Why.", ()), Failure("cannot convert the detail to a Jira description: adf-codec refused it"))
self.assertEqual(self.jira.issues, [])
def test_files_no_sub_task_where_the_project_has_no_sub_task_type_or_its_types_cannot_be_read(self) -> None:
store = self.new_store()
child = store.file("ABC-12", "Count the runs.", "", ())
for answer, reason in ((Failure("Jira answered 403"), "cannot read ABC's issue types: Jira answered 403"), ({"issueTypes": [{"id": "10001", "subtask": False}]}, "ABC has no sub-task issue type; turn sub-tasks on in Jira"), ({}, "ABC has no sub-task issue type; turn sub-tasks on in Jira")):
with self.subTest(answer=answer):
self.jira.answers[("GET", ISSUE_TYPES)] = answer
self.assertEqual(store.file(str(child), "A task.", "", ()), Failure(reason))
self.assertEqual(len(self.jira.issues), 1)
def test_an_issue_in_another_shape_fails_the_read(self) -> None:
self.jira.issues.append({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}}})
read = self.new_store().read()
self.assertIsInstance(read, Failure)
assert isinstance(read, Failure)
self.assertTrue(read.reason.startswith("ABC-34 is not in the shape Jira Cloud's REST API version 3 documents"), read.reason)
valid = {"summary": "Count the runs.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": {"key": "ABC-12"}}
shape = "ABC-34 is not in the shape Jira Cloud's REST API version 3 documents"
for raw, reason in (
("ABC-34", "the search answered an issue without an issue key"),
({"fields": valid}, "the search answered an issue without an issue key"),
({"key": "abc-34", "fields": valid}, "the search answered an issue without an issue key"),
({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}}}, shape + ": KeyError('assignee')"),
({"key": "ABC-34", "fields": valid | {"labels": [3]}}, shape + ": a label, its assignee, status, parent or description holds another kind of value"),
({"key": "ABC-34", "fields": valid | {"description": "text"}}, shape + ": a label, its assignee, status, parent or description holds another kind of value"),
):
with self.subTest(raw=raw):
self.jira.answers[("POST", SEARCH)] = {"issues": [raw]}
self.assertEqual(self.new_store().read(), Failure(reason))
def test_a_description_the_codec_cannot_convert_fails_the_read(self) -> None:
self.new_store().file("ABC-12", "Count the runs.", "Why.", ())
for converted, reason in ((Refused(0, Failure("a table cell holds a list")), "ABC-100's description: a table cell holds a list"), (Failure("docker is not running"), "cannot convert the descriptions of ABC-12's issues to markdown: docker is not running")):
with self.subTest(converted=converted):
self.assertEqual(JiraEpic(EPIC, self.env_file, self.jira, lambda documents: converted, to_adf).read(), Failure(reason))
def test_a_search_that_does_not_end_names_the_issues_it_sought(self) -> None:
store = self.new_store()
children = [store.file("ABC-12", "Count the runs.", "", ()) for _ in range(2)]
for _ in range(3):
store.file(str(children[0]), "A task.", "", ())
with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 1):
self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages"))
store.file("ABC-12", "Count the runs.", "", ())
self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages"))
def test_an_epic_the_account_cannot_see_fails_the_read(self) -> None:
store = JiraEpic(Epic(SITE, "ABC-99"), self.env_file, self.jira, to_markdown, to_adf)