Files
stack/tests/api/test_diag_ci.py
kert 1c08090147
All checks were successful
CI / lint (push) Successful in 1m14s
CI / notebooks-smoke (push) Successful in 1m45s
Deploy / changes (push) Successful in 17s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / api (push) Has been skipped
Deploy / bcda (push) Has been skipped
Deploy / llm (push) Has been skipped
Deploy / mc (push) Has been skipped
Deploy / report (push) Successful in 15s
CI / test (push) Successful in 4m2s
fix(test): cover the CI issue filer so the 99% gate holds
The filer added 51 statements and coverage fell to 98.48%. That rounds to
98, so --cov-fail-under=99 failed the test job. These tests execute the
missed branches.
2026-11-16 15:59:49 -05:00

856 lines
28 KiB
Python

"""Tests for the backend-agnostic CI failure reporter."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
class TestFileCiFailure:
"""file_ci_failure builds correct issue title and body."""
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_files_issue_with_correct_title(self, mock_cls, mock_token):
mock_client = MagicMock()
mock_client.create_issue.return_value = {"number": 999}
mock_client.resolve_labels.return_value = [1]
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
result = file_ci_failure(
workflow="Deploy",
job="build-scan-report",
run="42",
sha="abc12345def67890",
ref="refs/heads/main",
)
assert result is not None
assert result["number"] == 999
call_args = mock_client.create_issue.call_args
issue_body = call_args[0][2]
assert "Deploy" in issue_body["title"]
assert "build-scan-report" in issue_body["title"]
assert "abc12345" in issue_body["title"]
assert "#42" in issue_body["title"]
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_body_includes_metadata(self, mock_cls, mock_token):
mock_client = MagicMock()
mock_client.create_issue.return_value = {"number": 1}
mock_client.resolve_labels.return_value = []
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
file_ci_failure(
workflow="CI",
job="lint-test",
run="99",
sha="deadbeef",
ref="refs/heads/feature",
)
issue_body = mock_client.create_issue.call_args[0][2]
body = issue_body["body"]
assert "CI" in body
assert "lint-test" in body
assert "#99" in body
assert "deadbeef" in body
assert "refs/heads/feature" in body
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_resolves_pipeline_label(self, mock_cls, mock_token):
mock_client = MagicMock()
mock_client.create_issue.return_value = {"number": 2}
mock_client.resolve_labels.return_value = [5, 10]
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
file_ci_failure(
workflow="Deploy",
job="build",
run="1",
sha="aaa",
ref="",
)
label_call = mock_client.resolve_labels.call_args
label_names = label_call[0][2]
assert "ci" in label_names
assert "pipeline:deploy" in label_names
@patch("api.diag.ci._get_token", return_value="")
def test_no_token_returns_none(self, mock_token):
from api.diag.ci import file_ci_failure
result = file_ci_failure(
workflow="CI",
job="test",
run="1",
sha="aaa",
ref="",
)
assert result is None
class TestCLI:
"""CLI entry point parses args correctly."""
@patch("api.diag.ci.file_ci_failure")
def test_main_calls_file_ci_failure(self, mock_file):
mock_file.return_value = {"number": 1}
import sys
from api.diag.ci import main
old_argv = sys.argv
sys.argv = [
"ci",
"--workflow",
"CI",
"--job",
"lint-test",
"--run",
"5",
"--sha",
"abc123",
"--ref",
"refs/heads/main",
]
try:
code = main()
finally:
sys.argv = old_argv
assert code == 0
mock_file.assert_called_once()
kwargs = mock_file.call_args[1]
assert kwargs["workflow"] == "CI"
assert kwargs["job"] == "lint-test"
assert kwargs["run"] == "5"
assert kwargs["sha"] == "abc123"
class TestWorkflowGeneration:
"""Generated workflows contain failure steps."""
def test_gitea_workflows_have_failure_steps(self):
from pathlib import Path
wf_dir = Path(__file__).resolve().parents[2] / ".gitea" / "workflows"
skip = {"renovate.yml"} # external bot, no failure filing
for yml in wf_dir.glob("*.yml"):
if yml.name in skip:
continue
content = yml.read_text()
assert "File failure issue" in content, f"{yml.name} missing failure step"
assert "Close resolved issue" in content, f"{yml.name} missing close step"
assert "src/api/diag/ci.py" in content, f"{yml.name} missing filer"
class TestGetToken:
def test_returns_gitea_token_from_env(self, monkeypatch) -> None:
monkeypatch.setenv("GITEA_TOKEN", "env-token")
from api.diag.ci import _get_token
assert _get_token() == "env-token"
def test_falls_back_to_conf_secret(self, monkeypatch) -> None:
monkeypatch.delenv("GITEA_TOKEN", raising=False)
# Force the conf.secret import path to return a value.
import sys
import types
from api.diag.ci import _get_token
fake_conf = types.ModuleType("conf")
fake_conf.secret = lambda key, env: "conf-token"
monkeypatch.setitem(sys.modules, "conf", fake_conf)
assert _get_token() == "conf-token"
def test_returns_empty_when_conf_unavailable(self, monkeypatch) -> None:
"""ImportError on conf import → falls through to '' return."""
monkeypatch.delenv("GITEA_TOKEN", raising=False)
import sys
from api.diag.ci import _get_token
real_import = (
__builtins__["__import__"]
if isinstance(__builtins__, dict)
else __builtins__.__import__
)
def fake_import(name, *a, **kw):
if name == "conf":
raise ImportError("conf unavailable")
return real_import(name, *a, **kw)
monkeypatch.setattr("builtins.__import__", fake_import)
monkeypatch.delitem(sys.modules, "conf", raising=False)
assert _get_token() == ""
def test_returns_empty_when_no_token(self, monkeypatch) -> None:
monkeypatch.delenv("GITEA_TOKEN", raising=False)
from unittest.mock import patch
from api.diag.ci import _get_token
with patch("api.diag.ci._get_token", return_value=""):
assert _get_token.__module__ == "api.diag.ci"
class TestFileCiFailureGithubAction:
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_github_action_env_added_to_body(self, mock_cls, mock_token, monkeypatch):
"""GITHUB_ACTION env var triggers step line in body."""
monkeypatch.setenv("GITHUB_ACTION", "my-step-name")
mock_client = MagicMock()
mock_client.create_issue.return_value = {"number": 10}
mock_client.resolve_labels.return_value = []
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
result = file_ci_failure(
workflow="CI",
job="test",
run="1",
sha="abc",
ref="",
)
assert result is not None
issue_body = mock_client.create_issue.call_args[0][2]
assert "my-step-name" in issue_body["body"]
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_exception_in_create_issue_returns_none(self, mock_cls, mock_token):
"""Exception during Gitea API call returns None."""
mock_client = MagicMock()
mock_client.create_issue.side_effect = Exception("API error")
mock_client.resolve_labels.return_value = []
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
result = file_ci_failure(
workflow="CI",
job="test",
run="1",
sha="abc",
ref="",
)
assert result is None
class TestCLIFailure:
@patch("api.diag.ci.file_ci_failure")
def test_main_returns_1_when_no_result(self, mock_file):
mock_file.return_value = None
import sys
from api.diag.ci import main
old_argv = sys.argv
sys.argv = [
"ci",
"--workflow",
"CI",
"--job",
"test",
"--run",
"1",
"--sha",
"abc",
]
try:
code = main()
finally:
sys.argv = old_argv
assert code == 1
def _issue(
number: int, workflow: str = "CI", job: str = "test", body: str = "old"
) -> dict:
return {
"number": number,
"title": f"ci/{workflow}/{job} failed (#{number} @ aaaaaaaa)",
"body": body,
}
class TestMatch:
def test_title_prefix_matches_legacy_issues(self):
from api.diag.ci import _is_match
issue = _issue(4)
assert _is_match(issue, "CI", "test")
assert not _is_match(issue, "CI", "testing")
assert not _is_match(issue, "Deploy", "test")
def test_marker_does_not_match_a_longer_job(self):
from api.diag.ci import _is_match
body = "`ci-key:CI/testing` — do not edit"
issue = {"number": 1, "title": "something else", "body": body}
assert _is_match(issue, "CI", "testing")
assert not _is_match(issue, "CI", "test")
def test_spaced_workflow_name(self):
from api.diag.ci import _is_match
issue = _issue(8, "Notebooks Integration", "notebooks-integration")
assert _is_match(issue, "Notebooks Integration", "notebooks-integration")
assert not _is_match(issue, "Notebooks", "Integration")
class TestDedupeAndClose:
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_comments_instead_of_filing_a_duplicate(self, mock_cls, mock_token):
mock_client = MagicMock()
mock_client.list_issues.return_value = [_issue(10), _issue(12)]
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
result = file_ci_failure(
workflow="CI",
job="test",
run="40",
sha="deadbeefcafebabe",
ref="refs/heads/main",
)
assert result is not None
assert result["number"] == 12
mock_client.create_issue.assert_not_called()
note = mock_client.comment_issue.call_args_list[0].args[3]
assert "#40" in note
assert "deadbeef" in note
assert "refs/heads/main" in note
updated = mock_client.update_issue.call_args_list[0].args
assert updated[2] == 12
assert "#40" in updated[3]["title"]
assert "ci-key:CI/test" in updated[3]["body"]
# The older issue is closed as a duplicate, not left open.
closed = mock_client.update_issue.call_args_list[1].args
assert closed[2] == 10
assert closed[3] == {"state": "closed"}
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_scans_every_page(self, mock_cls, mock_token):
page1 = [_issue(n, "Other", "job") for n in range(1, 51)]
page2 = [_issue(77)]
mock_client = MagicMock()
mock_client.list_issues.side_effect = [page1, page2]
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
result = file_ci_failure(
workflow="CI",
job="test",
run="8",
sha="abc12345ffff",
ref="refs/heads/main",
)
assert result is not None and result["number"] == 77
mock_client.create_issue.assert_not_called()
assert mock_client.list_issues.call_count == 2
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_close_closes_every_open_match(self, mock_cls, mock_token):
mock_client = MagicMock()
mock_client.list_issues.return_value = [_issue(3), _issue(9)]
mock_cls.return_value = mock_client
from api.diag.ci import close_ci_failure
result = close_ci_failure(
workflow="CI",
job="test",
run="41",
sha="abc12345ffff",
ref="refs/heads/main",
)
assert result == {"closed": [3, 9]}
mock_client.create_issue.assert_not_called()
notes = [c.args[3] for c in mock_client.comment_issue.call_args_list]
assert all("abc12345" in note for note in notes)
states = [c.args[3] for c in mock_client.update_issue.call_args_list]
assert states == [{"state": "closed"}, {"state": "closed"}]
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_close_with_nothing_open(self, mock_cls, mock_token):
mock_client = MagicMock()
mock_client.list_issues.return_value = []
mock_cls.return_value = mock_client
from api.diag.ci import close_ci_failure
result = close_ci_failure(workflow="CI", job="test", run="1", sha="abc", ref="")
assert result == {"closed": []}
mock_client.comment_issue.assert_not_called()
@patch("api.diag.ci._get_token", return_value="")
def test_close_without_token(self, mock_token):
from api.diag.ci import close_ci_failure
assert (
close_ci_failure(workflow="CI", job="test", run="1", sha="abc", ref="")
is None
)
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_dedupe_leaves_the_newest(self, mock_cls, mock_token):
mock_client = MagicMock()
mock_client.list_issues.return_value = [_issue(2), _issue(5), _issue(8)]
mock_cls.return_value = mock_client
from api.diag.ci import dedupe_ci_failure
result = dedupe_ci_failure(workflow="CI", job="test")
assert result == {"closed": [2, 5]}
kept = mock_client.update_issue.call_args_list[0].args
assert kept[2] == 8
assert "ci-key:CI/test" in kept[3]["body"]
assert "state" not in kept[3]
closed_ids = [c.args[2] for c in mock_client.comment_issue.call_args_list]
assert closed_ids == [2, 5]
class TestApiBase:
def test_env_wins(self, monkeypatch):
monkeypatch.setenv("GITEA_API_BASE", "http://127.0.0.1:3000/api/v1/")
from api.diag.ci import _api_base
assert _api_base() == "http://127.0.0.1:3000/api/v1"
def test_compose_url_when_git_resolves(self, monkeypatch):
monkeypatch.delenv("GITEA_API_BASE", raising=False)
monkeypatch.delenv("GITEA_API_URL", raising=False)
monkeypatch.setattr("api.diag.ci.socket.getaddrinfo", lambda *a, **k: [()])
import tomllib
from pathlib import Path
from api.diag.ci import _api_base
data = tomllib.loads(Path("stack.toml").read_text())
assert _api_base() == data["services"]["git"].rstrip("/") + "/api/v1"
def test_public_url_when_git_does_not_resolve(self, monkeypatch):
monkeypatch.delenv("GITEA_API_BASE", raising=False)
monkeypatch.delenv("GITEA_API_URL", raising=False)
def _down(*_a, **_k):
raise OSError("no such host")
monkeypatch.setattr("api.diag.ci.socket.getaddrinfo", _down)
import tomllib
from pathlib import Path
from api.diag.ci import _api_base
data = tomllib.loads(Path("stack.toml").read_text())
assert _api_base() == f"https://git.{data['platform']['domain']}/api/v1"
class TestUrllibClient:
def test_list_issues_sends_the_token_and_query(self, monkeypatch):
captured: dict = {}
class _Resp:
def read(self):
return b'[{"number": 1}]'
def __enter__(self):
return self
def __exit__(self, *_a):
return False
def _urlopen(req, timeout=30):
captured["url"] = req.full_url
captured["auth"] = req.get_header("Authorization")
captured["method"] = req.get_method()
return _Resp()
monkeypatch.setattr("api.diag.ci.urllib.request.urlopen", _urlopen)
from api.diag.ci import _UrllibGitea
client = _UrllibGitea("sekret", "http://git:3000/api/v1")
assert client.list_issues(
"homelab", "stack", state="open", type="issues", limit=50, page=2
) == [{"number": 1}]
assert captured["method"] == "GET"
assert captured["auth"] == "token sekret"
assert captured["url"].startswith(
"http://git:3000/api/v1/repos/homelab/stack/issues?"
)
assert "state=open" in captured["url"]
assert "page=2" in captured["url"]
def test_http_error_raises(self, monkeypatch):
import urllib.error
def _urlopen(req, timeout=30):
raise urllib.error.HTTPError(req.full_url, 500, "nope", hdrs=None, fp=None)
monkeypatch.setattr("api.diag.ci.urllib.request.urlopen", _urlopen)
from api.diag.ci import _UrllibGitea
client = _UrllibGitea("sekret", "http://git:3000/api/v1")
try:
client.create_issue("homelab", "stack", {"title": "x"})
except RuntimeError as exc:
assert "500" in str(exc)
else:
raise AssertionError("expected RuntimeError")
class TestCloseCLI:
@patch("api.diag.ci.close_ci_failure")
@patch("api.diag.ci.file_ci_failure")
def test_close_flag(self, mock_file, mock_close):
mock_close.return_value = {"closed": [4]}
import sys
from api.diag.ci import main
old = sys.argv
sys.argv = [
"ci",
"--close",
"--workflow",
"CI",
"--job",
"test",
"--run",
"9",
"--sha",
"abc12345",
]
try:
code = main()
finally:
sys.argv = old
assert code == 0
mock_file.assert_not_called()
assert mock_close.call_args[1]["run"] == "9"
@patch("api.diag.ci.dedupe_ci_failure")
def test_dedupe_flag_does_not_require_a_run(self, mock_dedupe):
mock_dedupe.return_value = {"closed": []}
import sys
from api.diag.ci import main
old = sys.argv
sys.argv = ["ci", "--dedupe", "--workflow", "CI", "--job", "test"]
try:
code = main()
finally:
sys.argv = old
assert code == 0
mock_dedupe.assert_called_once()
def test_run_and_sha_are_required(self):
import sys
from api.diag.ci import main
old = sys.argv
sys.argv = ["ci", "--workflow", "CI", "--job", "test"]
try:
try:
main()
except SystemExit as exc:
assert exc.code == 2
else:
raise AssertionError("expected SystemExit")
finally:
sys.argv = old
class TestMarkerAndFallback:
def test_with_marker_leaves_a_marked_body_alone(self):
from api.diag.ci import _with_marker
body = "note\n\n`ci-key:CI/test` — do not edit."
assert _with_marker(body, "CI", "test") == body
def test_missing_stack_toml_uses_the_public_default(self, monkeypatch):
monkeypatch.delenv("GITEA_API_BASE", raising=False)
monkeypatch.delenv("GITEA_API_URL", raising=False)
from pathlib import Path
from api.diag.ci import _api_base
real = Path.is_file
def _missing(self: Path) -> bool:
if self.name == "stack.toml":
return False
return real(self)
monkeypatch.setattr(Path, "is_file", _missing)
assert _api_base() == "https://git.fhirworx.io/api/v1"
def test_connect_uses_urllib_when_the_project_client_fails(self, monkeypatch):
monkeypatch.setenv("GITEA_API_BASE", "http://127.0.0.1:3000/api/v1")
def _boom(_token: str) -> object:
raise ImportError("no httpx")
monkeypatch.setattr("api.diag.ci._gitea_client", _boom)
from api.diag.ci import _connect, _UrllibGitea
assert isinstance(_connect("tok"), _UrllibGitea)
class TestOpenMatches:
def test_skips_pull_requests_and_non_dicts(self):
from api.diag.ci import _open_matches
client = MagicMock()
client.list_issues.return_value = [
"nope",
{
"number": 1,
"title": "ci/CI/test failed",
"pull_request": {"merged": False},
},
_issue(4),
]
found = _open_matches(client, "homelab", "stack", "CI", "test")
assert [issue["number"] for issue in found] == [4]
def test_stops_after_the_page_cap(self, caplog):
import logging
from api.diag.ci import _MAX_PAGES, _open_matches
page = [{"number": i, "title": "unrelated", "body": ""} for i in range(50)]
client = MagicMock()
client.list_issues.return_value = page
with caplog.at_level(logging.WARNING, logger="api.diag.ci"):
found = _open_matches(client, "homelab", "stack", "CI", "test")
assert found == []
assert client.list_issues.call_count == _MAX_PAGES
assert "Stopped after 20 pages" in caplog.text
class TestFailurePaths:
@patch("api.diag.ci._connect", side_effect=RuntimeError("down"))
@patch("api.diag.ci._get_token", return_value="fake-token")
def test_connect_failure_returns_none(self, _token, _connect):
from api.diag.ci import close_ci_failure, dedupe_ci_failure, file_ci_failure
kwargs = {
"workflow": "CI",
"job": "test",
"run": "1",
"sha": "abc",
"ref": "refs/heads/main",
}
assert file_ci_failure(**kwargs) is None
assert close_ci_failure(**kwargs) is None
assert dedupe_ci_failure(workflow="CI", job="test") is None
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_close_returns_none_when_a_number_is_missing(self, mock_cls, _token):
mock_client = MagicMock()
mock_client.list_issues.return_value = [
{"number": 0, "title": "ci/CI/test failed", "body": ""}
]
mock_cls.return_value = mock_client
from api.diag.ci import close_ci_failure
assert (
close_ci_failure(
workflow="CI", job="test", run="1", sha="abc", ref="refs/heads/main"
)
is None
)
mock_client.comment_issue.assert_not_called()
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_close_returns_none_when_the_api_fails(self, mock_cls, _token):
mock_client = MagicMock()
mock_client.list_issues.return_value = [_issue(3)]
mock_client.comment_issue.side_effect = RuntimeError("nope")
mock_cls.return_value = mock_client
from api.diag.ci import close_ci_failure
assert (
close_ci_failure(
workflow="CI", job="test", run="1", sha="abc", ref="refs/heads/main"
)
is None
)
@patch("api.diag.ci._get_token", return_value="")
def test_dedupe_without_token(self, _token):
from api.diag.ci import dedupe_ci_failure
assert dedupe_ci_failure(workflow="CI", job="test") is None
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_dedupe_with_nothing_open(self, mock_cls, _token):
mock_client = MagicMock()
mock_client.list_issues.return_value = []
mock_cls.return_value = mock_client
from api.diag.ci import dedupe_ci_failure
assert dedupe_ci_failure(workflow="CI", job="test") == {"closed": []}
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_dedupe_returns_none_when_the_api_fails(self, mock_cls, _token):
mock_client = MagicMock()
mock_client.list_issues.return_value = [_issue(8)]
mock_client.update_issue.side_effect = RuntimeError("nope")
mock_cls.return_value = mock_client
from api.diag.ci import dedupe_ci_failure
assert dedupe_ci_failure(workflow="CI", job="test") is None
@patch("api.diag.ci._get_token", return_value="fake-token")
@patch("api.clients.gitea.GiteaClient")
def test_repeat_note_names_the_step(self, mock_cls, _token, monkeypatch):
monkeypatch.setenv("GITHUB_ACTION", "file-failure")
mock_client = MagicMock()
mock_client.list_issues.return_value = [_issue(4)]
mock_cls.return_value = mock_client
from api.diag.ci import file_ci_failure
file_ci_failure(
workflow="CI",
job="test",
run="2",
sha="abc12345",
ref="refs/heads/main",
)
note = mock_client.comment_issue.call_args.args[3]
assert "file-failure" in note
def _json_response(payload: bytes):
class _Resp:
def read(self) -> bytes:
return payload
def __enter__(self) -> _Resp:
return self
def __exit__(self, *_a: object) -> bool:
return False
return _Resp()
class TestUrllibBranches:
def test_close_is_a_noop(self):
from api.diag.ci import _UrllibGitea
assert _UrllibGitea("t", "http://git").close() is None
def test_list_issues_rejects_a_non_list(self, monkeypatch):
monkeypatch.setattr(
"api.diag.ci.urllib.request.urlopen",
lambda req, timeout=30: _json_response(b"null"),
)
from api.diag.ci import _UrllibGitea
client = _UrllibGitea("sekret", "http://git:3000/api/v1")
try:
client.list_issues("homelab", "stack")
except RuntimeError as exc:
assert "not a list" in str(exc)
else:
raise AssertionError("expected RuntimeError")
def test_mutations_round_trip(self, monkeypatch):
seen: dict = {}
def _urlopen(req, timeout=30):
seen["method"] = req.get_method()
seen["url"] = req.full_url
return _json_response(b'{"number": 9, "id": 9}')
monkeypatch.setattr("api.diag.ci.urllib.request.urlopen", _urlopen)
from api.diag.ci import _UrllibGitea
client = _UrllibGitea("sekret", "http://git:3000/api/v1/")
assert client.create_issue("homelab", "stack", {"title": "t"})["number"] == 9
assert seen["method"] == "POST"
assert client.comment_issue("homelab", "stack", 9, "hi")["id"] == 9
assert seen["url"].endswith("/issues/9/comments")
assert (
client.update_issue("homelab", "stack", 9, {"state": "closed"})["number"]
== 9
)
assert seen["method"] == "PATCH"
def test_mutations_reject_a_non_object(self, monkeypatch):
monkeypatch.setattr(
"api.diag.ci.urllib.request.urlopen",
lambda req, timeout=30: _json_response(b"[]"),
)
from api.diag.ci import _UrllibGitea
client = _UrllibGitea("sekret", "http://git:3000/api/v1")
calls = (
lambda: client.create_issue("o", "r", {"title": "t"}),
lambda: client.comment_issue("o", "r", 1, "hi"),
lambda: client.update_issue("o", "r", 1, {"state": "closed"}),
)
for call in calls:
try:
call()
except RuntimeError as exc:
assert "failed" in str(exc)
else:
raise AssertionError("expected RuntimeError")
def test_resolve_labels(self, monkeypatch):
payloads = iter(
[
b"null",
b'[{"name": "ci", "id": 3}, {"name": "skip"}, "nope"]',
]
)
def _urlopen(req, timeout=30):
return _json_response(next(payloads))
monkeypatch.setattr("api.diag.ci.urllib.request.urlopen", _urlopen)
from api.diag.ci import _UrllibGitea
client = _UrllibGitea("sekret", "http://git:3000/api/v1")
assert client.resolve_labels("o", "r", ["ci"]) == []
assert client.resolve_labels("o", "r", ["ci", "missing"]) == [3]