Enterprise agent platform for building, deploying, and operating AI teammates.
import base64
import itertools
import json
from unittest.mock import Mock
import pytest
from xagent.web.tools.mcp import github
class MockResponse:
def __init__(
self,
json_data=None,
status_code: int = 200,
content: bytes = b"{}",
headers: dict | None = None,
):
self._json_data = json_data if json_data is not None else {}
self.status_code = status_code
self.content = content if json_data is None else json.dumps(json_data).encode()
self.headers = headers or {}
def json(self):
return self._json_data
@pytest.fixture(autouse=True)
def _credentials(monkeypatch):
monkeypatch.setenv("GITHUB_ACCESS_TOKEN", "access-token")
def test_headers_require_access_token(monkeypatch):
monkeypatch.delenv("GITHUB_ACCESS_TOKEN")
with pytest.raises(ValueError, match="GITHUB_ACCESS_TOKEN"):
github._headers()
def test_headers_include_bearer_token_and_api_version():
assert github._headers() == {
"Authorization": "Bearer access-token",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
def test_parse_repo_splits_owner_and_name():
assert github._parse_repo("octocat/Hello-World") == ("octocat", "Hello-World")
def test_parse_repo_strips_surrounding_whitespace():
assert github._parse_repo(" octocat/Hello-World ") == ("octocat", "Hello-World")
@pytest.mark.parametrize(
"value",
[
"octocat",
"",
"octocat/",
"/Hello-World",
"owner//repo",
"owner/repo/extra",
"/octocat/Hello-World/",
],
)
def test_parse_repo_rejects_malformed_input(value):
"""Extra/leading/trailing slashes must be rejected outright, not
silently repaired into a subtly wrong (owner, name) pair."""
with pytest.raises(ValueError, match="owner/repo"):
github._parse_repo(value)
@pytest.mark.parametrize(
"value",
[
"owner?x=y/repo", # query-string injection via the owner segment
"owner/repo#frag", # fragment injection via the name segment
"../owner", # dot-segment traversal attempt as the owner
"owner/..", # dot-segment traversal attempt as the name
],
)
def test_parse_repo_rejects_injection_attempts(value):
"""owner/name each pass _parse_repo's single-slash shape check but must
still be rejected by per-segment validation -- these are exactly one
"/" apart with non-empty parts, so only the character-level guard in
_encode_path_component catches them."""
with pytest.raises(ValueError, match="not allowed"):
github._parse_repo(value)
@pytest.mark.parametrize("value", ["", ".", "..", "a/b", "a?b", "a#b"])
def test_encode_path_component_rejects_forbidden_values(value):
with pytest.raises(ValueError, match="not allowed"):
github._encode_path_component(value, field="test")
@pytest.mark.parametrize("value", [" ", " ", "\t"])
def test_encode_path_component_rejects_whitespace_only_values(value):
"""A whitespace-only value is truthy and would otherwise pass through
to be percent-encoded ("%20") and reach GitHub as a literal owner/repo
name -- _require_nonblank already rejects this shape for other string
fields; owner/repo shouldn't be the exception."""
with pytest.raises(ValueError, match="not allowed"):
github._encode_path_component(value, field="test")
@pytest.mark.parametrize("value", [" . ", " .. ", "\t.\t", "\n..\n"])
def test_encode_path_component_rejects_whitespace_padded_dot_segments(value):
"""A dot-segment check against the raw value only catches an exact "."
or ".." -- a whitespace-padded one (" . ", " .. ") is neither purely
whitespace (so the whitespace-only check doesn't catch it) nor an
exact match (so the dot-segment check doesn't either), and would
otherwise reach GitHub as a percent-encoded but still nonsense
owner/repo segment."""
with pytest.raises(ValueError, match="not allowed"):
github._encode_path_component(value, field="test")
def test_encode_path_component_percent_encodes_space_in_owner_or_repo_name():
"""_encode_path_component (owner/repo names) only rejects '/', '?', '#',
and dot-segments -- a space is not forbidden, so it must be
percent-encoded rather than sent raw, same as any other unreserved-but-
not-URL-safe character."""
assert github._encode_path_component("my org", field="test") == "my%20org"
@pytest.mark.parametrize("value", ["", ".", ".."])
def test_encode_file_path_segment_rejects_forbidden_values(value):
with pytest.raises(ValueError, match="not allowed"):
github._encode_file_path_segment(value, field="path")
def test_encode_file_path_segment_allows_and_encodes_question_mark_and_hash():
"""Unlike _encode_path_component (owner/repo), '?' and '#' are legitimate
filename characters -- they must be percent-encoded rather than rejected,
since the encoded form can't be reinterpreted as a query/fragment once
it reaches the URL."""
assert github._encode_file_path_segment("why?.md", field="path") == "why%3F.md"
assert github._encode_file_path_segment("issue#1.txt", field="path") == (
"issue%231.txt"
)
def test_encode_file_path_segment_percent_encodes_reserved_characters():
assert github._encode_file_path_segment("my notes.md", field="path") == (
"my%20notes.md"
)
def test_request_raises_with_message_on_error(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Not Found"}, status_code=404
)
),
)
with pytest.raises(RuntimeError, match="Not Found"):
github._request("GET", "/repos/octocat/missing")
@pytest.mark.parametrize("status_code", [502, 503])
def test_request_raises_fallback_message_on_5xx_without_message_field(
monkeypatch, status_code
):
"""GitHub's 5xx responses commonly carry no "message" field (or no
JSON body at all) -- the fallback f"GitHub API error (status {code})"
string must fire, not a raw KeyError/AttributeError or an empty
message. Zero test in this suite previously supplied a 5xx status."""
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={}, status_code=status_code)),
)
with pytest.raises(RuntimeError, match=f"status {status_code}"):
github._request("GET", "/repos/octocat/Hello-World")
def test_request_raises_fallback_message_on_5xx_with_non_json_body(monkeypatch):
"""A 5xx response with a non-JSON (e.g. HTML) body must not raise a
raw ValueError from response.json() -- it must fall back to the same
generic status message."""
class NonJsonResponse(MockResponse):
def json(self):
raise ValueError("Expecting value: line 1 column 1 (char 0)")
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=NonJsonResponse(status_code=503, content=b"<html>...")),
)
with pytest.raises(RuntimeError, match="status 503"):
github._request("GET", "/repos/octocat/Hello-World")
def test_request_folds_validation_errors_into_message(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"message": "Validation Failed",
"errors": [{"field": "title", "message": "cannot be blank"}],
},
status_code=422,
)
),
)
with pytest.raises(RuntimeError, match="cannot be blank"):
github._request("POST", "/repos/octocat/Hello-World/issues")
def test_request_caps_a_large_validation_errors_list(monkeypatch):
"""A large 422 validation-error list must be capped the same way
jira.py/intercom.py cap their own error text, not joined in full into
the raised exception and landed verbatim in the model's context."""
long_errors = [{"field": f"field_{i}", "message": "x" * 50} for i in range(50)]
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Validation Failed", "errors": long_errors},
status_code=422,
)
),
)
with pytest.raises(RuntimeError) as exc_info:
github._request("POST", "/repos/octocat/Hello-World/issues")
message = str(exc_info.value)
assert len(message) <= github.MAX_ERROR_RESPONSE_TEXT_CHARS + len("... [truncated]")
assert message.endswith("... [truncated]")
def test_request_returns_empty_dict_on_no_content(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(status_code=204, content=b"")),
)
assert github._request("DELETE", "/repos/octocat/Hello-World") == {}
def test_request_raw_includes_rate_limit_metadata_in_error(monkeypatch):
"""Retry-After/X-RateLimit-* headers must not be silently dropped -- a
rate limit or transient server error would otherwise be indistinguishable
from a validation/permission failure in the raised message."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "API rate limit exceeded"},
status_code=403,
headers={
"Retry-After": "60",
"X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": "1699999999",
},
)
),
)
with pytest.raises(RuntimeError) as excinfo:
github._request("GET", "/repos/octocat/Hello-World/issues")
assert "retry_after=60s" in str(excinfo.value)
assert "rate_limit_reset=1699999999" in str(excinfo.value)
def test_request_raw_omits_rate_limit_metadata_when_not_rate_limited(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Not Found"}, status_code=404
)
),
)
with pytest.raises(RuntimeError) as excinfo:
github._request("GET", "/repos/octocat/missing")
assert "retry_after" not in str(excinfo.value)
assert "rate_limit_reset" not in str(excinfo.value)
def test_request_raw_retries_get_once_on_bounded_429(monkeypatch):
mock_request = Mock(
side_effect=[
MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": "1"},
),
MockResponse(json_data={"ok": True}, status_code=200),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
response = github._request_raw("GET", "/repos/octocat/Hello-World")
assert response.status_code == 200
assert mock_request.call_count == 2
sleep_mock.assert_called_once_with(1)
def test_request_raw_does_not_retry_429_with_missing_retry_after(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"}, status_code=429
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("GET", "/repos/octocat/Hello-World")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_does_not_retry_429_via_reset_header_fallback(monkeypatch):
"""The X-RateLimit-Reset fallback added for 403 rate limits is gated on
is_rate_limited_403, not just "status is 429 or 403" -- a 429 with no
Retry-After must keep its existing, documented fail-fast behavior even
if X-RateLimit-Reset happens to be present, rather than silently
gaining a new, untested retry path."""
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "1000"},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
monkeypatch.setattr(github, "_wall_clock", lambda: 995.0)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("GET", "/repos/octocat/Hello-World")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_does_not_retry_429_with_non_numeric_retry_after(monkeypatch):
"""A non-numeric Retry-After (e.g. an RFC 7231 HTTP-date, which int()
rejects) must fail closed -- no retry -- rather than raising out of
_request_raw itself."""
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": "Wed, 19 Aug 2026 07:00:05 GMT"},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("GET", "/repos/octocat/Hello-World")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_does_not_retry_a_second_429(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": "1"},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
monkeypatch.setattr(github, "_sleep", Mock())
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("GET", "/repos/octocat/Hello-World")
assert mock_request.call_count == 2
def test_request_raw_does_not_retry_429_on_write(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": "1"},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("POST", "/repos/octocat/Hello-World/issues")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_does_not_retry_429_with_excessive_retry_after(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": str(github.MAX_RETRY_AFTER_SECONDS + 1)},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("GET", "/repos/octocat/Hello-World")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_retries_get_once_on_403_with_retry_after(monkeypatch):
"""GitHub's secondary/abuse-detection rate limit answers 403, not 429,
and commonly carries Retry-After -- this must retry the same as a 429
would, not fail fast as a permission error."""
mock_request = Mock(
side_effect=[
MockResponse(
json_data={"message": "secondary rate limit"},
status_code=403,
headers={"Retry-After": "1"},
),
MockResponse(json_data={"ok": True}, status_code=200),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
response = github._request_raw("GET", "/repos/octocat/Hello-World")
assert response.status_code == 200
assert mock_request.call_count == 2
sleep_mock.assert_called_once_with(1)
def test_request_raw_retries_get_once_on_403_with_exhausted_rate_limit(monkeypatch):
"""GitHub's primary rate limit (quota exhausted) also answers 403, but
usually without Retry-After -- only X-RateLimit-Remaining: 0 and an
X-RateLimit-Reset epoch timestamp. The wait must be derived from that
reset time instead of being skipped for lack of Retry-After."""
mock_request = Mock(
side_effect=[
MockResponse(
json_data={"message": "rate limit exceeded"},
status_code=403,
headers={"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "1000"},
),
MockResponse(json_data={"ok": True}, status_code=200),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
monkeypatch.setattr(github, "_wall_clock", lambda: 995.0)
response = github._request_raw("GET", "/repos/octocat/Hello-World")
assert response.status_code == 200
assert mock_request.call_count == 2
sleep_mock.assert_called_once_with(5)
def test_request_raw_retries_immediately_on_retry_after_zero(monkeypatch):
"""Retry-After: "0" is a legitimate "retry right now" signal, not "no
information" -- treating a computed wait of exactly 0 the same as
"no Retry-After given" would skip a retry the response just said was
safe to make immediately."""
mock_request = Mock(
side_effect=[
MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": "0"},
),
MockResponse(json_data={"ok": True}, status_code=200),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
response = github._request_raw("GET", "/repos/octocat/Hello-World")
assert response.status_code == 200
assert mock_request.call_count == 2
sleep_mock.assert_called_once_with(0)
def test_request_raw_retries_immediately_on_reset_already_past(monkeypatch):
"""An X-RateLimit-Reset that has already elapsed (clock skew, or the
quota replenishing between the original request and this check) must
retry immediately, not be treated as "no reset info" and fail fast."""
mock_request = Mock(
side_effect=[
MockResponse(
json_data={"message": "rate limit exceeded"},
status_code=403,
headers={"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "1000"},
),
MockResponse(json_data={"ok": True}, status_code=200),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
monkeypatch.setattr(github, "_wall_clock", lambda: 1005.0)
response = github._request_raw("GET", "/repos/octocat/Hello-World")
assert response.status_code == 200
assert mock_request.call_count == 2
sleep_mock.assert_called_once_with(0)
def test_request_raw_does_not_retry_403_with_reset_beyond_bound(monkeypatch):
"""A primary rate limit whose reset is minutes/hours away (the common
case for a fully exhausted quota) must fail fast, not sleep for it --
same MAX_RETRY_AFTER_SECONDS bound as Retry-After already enforces."""
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limit exceeded"},
status_code=403,
headers={
"X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": str(1000 + github.MAX_RETRY_AFTER_SECONDS + 1),
},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
monkeypatch.setattr(github, "_wall_clock", lambda: 1000.0)
with pytest.raises(RuntimeError, match="rate limit exceeded"):
github._request_raw("GET", "/repos/octocat/Hello-World")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_does_not_retry_a_genuine_permission_denied_403(monkeypatch):
"""A real permission-denied 403 carries neither Retry-After nor
X-RateLimit-Remaining: 0 -- it must fail immediately, not be retried
into the same denial."""
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "Must have admin rights to Repository."},
status_code=403,
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="Must have admin rights"):
github._request_raw("GET", "/repos/octocat/Hello-World")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_does_not_retry_403_on_write(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=403,
headers={"Retry-After": "1"},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("POST", "/repos/octocat/Hello-World/issues")
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_allow_retry_false_skips_403_retry(monkeypatch):
"""Same reasoning as the 429 case just below: a caller running its own
wall-clock budget (github_list_issues) must not have this rate-limit
retry's sleep run invisibly inside a single call."""
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=403,
headers={"Retry-After": "1"},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("GET", "/repos/octocat/Hello-World", allow_retry=False)
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_request_raw_allow_retry_false_skips_429_retry(monkeypatch):
"""github_list_issues opts out of the retry: its sleep + second attempt
run inside _request_raw, invisible to the caller's aggregate deadline,
and a mid-pagination 429 already has a better path there (an immediate
resumable partial via truncation_reason="request_failed")."""
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": "1"},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
with pytest.raises(RuntimeError, match="rate limited"):
github._request_raw("GET", "/repos/octocat/Hello-World", allow_retry=False)
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
def test_list_issues_does_not_sleep_on_mid_pagination_429(monkeypatch):
"""End-to-end pin of the allow_retry=False opt-out: a 429 on page 2
must produce the prompt resumable partial, not an in-call sleep that
blows the aggregate deadline."""
first_page = [{"number": 1, "title": "issue 1", "labels": []}]
mock_request = Mock(
side_effect=[
MockResponse(
json_data=first_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
),
MockResponse(
json_data={"message": "rate limited"},
status_code=429,
headers={"Retry-After": "1"},
),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
sleep_mock = Mock()
monkeypatch.setattr(github, "_sleep", sleep_mock)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=100))
# "partial", not "success": a page request genuinely failed (a rate
# limit here) partway through -- a caller branching only on status
# must not mistake this for a clean, trustworthy result.
assert result["status"] == "partial"
assert result["truncated"] is True
assert result["truncation_reason"] == "request_failed"
assert result["next_page"] == 2
assert mock_request.call_count == 2 # no third (retry) request
sleep_mock.assert_not_called()
@pytest.mark.parametrize(
"limit, expected",
[
(0, 1),
(1, 1),
(30, 30),
(100, 100),
(101, 100),
(-5, 1),
("not-a-number", 30), # falls back to the default, then clamps
],
)
def test_clamp_limit_boundaries(limit, expected):
assert github._clamp_limit(limit) == expected
def test_clamp_limit_uses_the_caller_supplied_default():
assert github._clamp_limit("not-a-number", default=20) == 20
def test_validate_positive_number_rejects_none_with_named_error():
"""int(None) raises a bare, unnamed TypeError -- this must still surface
as the function's own named ValueError like every other rejection here,
not leak the raw builtin exception (only reachable via a direct Python
call, since FastMCP's schema would reject a missing/null argument first)."""
with pytest.raises(ValueError, match="issue_number must be a positive integer"):
github._validate_positive_number(None, field="issue_number")
def test_validate_positive_number_rejects_non_integral_float():
"""int(2.9) truncates to 2 rather than raising -- without an explicit
check, github_get_issue(repo, 2.9) would silently fetch issue 2
instead of rejecting the non-integer input."""
with pytest.raises(ValueError, match="issue_number must be a positive integer"):
github._validate_positive_number(2.9, field="issue_number")
def test_validate_positive_number_accepts_whole_number_float():
assert github._validate_positive_number(3.0, field="issue_number") == 3
def test_search_repositories_falls_back_to_its_own_documented_default(monkeypatch):
"""A non-numeric limit reaching _clamp_limit (bypassing FastMCP's int
schema via a direct call) must fall back to this tool's own documented
default (20), not the generic 30 most other tools use."""
mock_request = Mock(
return_value=MockResponse(json_data={"total_count": 0, "items": []})
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_search_repositories("stars:>1", limit="not-a-number")
assert mock_request.call_args.kwargs["params"]["per_page"] == 20
def test_search_code_falls_back_to_its_own_documented_default(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"total_count": 0, "items": []})
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_search_code("def parse", limit="not-a-number")
assert mock_request.call_args.kwargs["params"]["per_page"] == 20
def test_link_header_rels_returns_empty_set_for_missing_header():
assert github._link_header_rels(None) == set()
assert github._link_header_rels("") == set()
def test_link_header_rels_parses_multiple_quoted_links():
header = (
'<https://api.github.com/x?page=2>; rel="next", '
'<https://api.github.com/x?page=5>; rel="last"'
)
assert github._link_header_rels(header) == {"next", "last"}
def test_link_header_rels_accepts_unquoted_rel_token():
"""GitHub always quotes rel, but RFC 8288 also permits an unquoted
token -- a spec-compliant but differently-formatted response (e.g. from
a proxy) must not be silently parsed as having no rels at all."""
assert github._link_header_rels("<https://api.github.com/x?page=2>; rel=next") == {
"next"
}
def test_link_header_rels_lowercases_rel_values():
"""Rel values are case-insensitive per RFC 8288 -- an upper/mixed-case
variant must still satisfy callers' `"next" in ...` checks."""
assert github._link_header_rels(
'<https://api.github.com/x?page=2>; REL="Next"'
) == {"next"}
def test_link_header_rels_ignores_malformed_header():
assert github._link_header_rels("this is not a link header") == set()
def test_link_header_rels_splits_multi_value_rel():
"""RFC 8288 allows a single quoted rel to carry multiple, whitespace-
separated relation types (e.g. the last page also being "next" for a
single-page result) -- it must not be treated as one opaque token."""
header = '<https://api.github.com/x?page=1>; rel="next last"'
assert github._link_header_rels(header) == {"next", "last"}
def test_link_header_rels_does_not_match_rel_text_inside_uri():
"""A target URI that happens to contain the literal text "rel=" must
not be mistaken for the rel parameter itself."""
header = '<https://example.com/x?rel=foo>; rel="next"'
assert github._link_header_rels(header) == {"next"}
def test_link_header_rels_handles_case_insensitive_header_lookup():
"""requests' Response.headers is a case-insensitive mapping -- a
lower-cased "link" header key must still be found by callers using
response.headers.get("Link")."""
headers = {"link": '<https://api.github.com/x?page=2>; rel="next"'}
import requests as _requests
case_insensitive_headers = _requests.structures.CaseInsensitiveDict(headers)
assert github._link_header_rels(case_insensitive_headers.get("Link")) == {"next"}
def test_search_repositories_returns_summaries(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"total_count": 1,
"items": [
{
"full_name": "octocat/Hello-World",
"description": "demo",
"private": False,
"default_branch": "main",
"stargazers_count": 5,
"open_issues_count": 1,
"html_url": "https://github.com/octocat/Hello-World",
"language": "Python",
"updated_at": "2026-01-01T00:00:00Z",
}
],
}
)
),
)
result = json.loads(github.github_search_repositories("Hello-World"))
assert result["status"] == "success"
assert result["total_count"] == 1
assert result["repositories"][0]["full_name"] == "octocat/Hello-World"
assert result["incomplete_results"] is False
def test_search_repositories_flags_incomplete_results(monkeypatch):
"""GitHub can answer a 200 with incomplete_results=true when its search
index times out -- dropping that flag would let a caller mistake a
partial result for an exhaustive one."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"total_count": 500, "items": [], "incomplete_results": True}
)
),
)
result = json.loads(github.github_search_repositories("stars:>1"))
assert result["status"] == "success"
assert result["incomplete_results"] is True
def test_search_repositories_rejects_non_object_item(monkeypatch):
"""A non-object item in the search results (same class of gap as the
issues pagination and directory-listing hardening) must not reach the
unguarded _summarize_repo() call below."""
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={"total_count": 1, "items": [None]})),
)
result = json.loads(github.github_search_repositories("stars:>1"))
assert result["status"] == "error"
assert "non-object item" in result["message"]
def test_search_repositories_rejects_non_dict_body(monkeypatch):
"""A 200 body that parses to a non-dict (e.g. a bare list) must not
reach result.get("items"), which would surface as an unhelpful
AttributeError -- same error class the item guards exist to prevent."""
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(github.github_search_repositories("stars:>1"))
assert result["status"] == "error"
assert "non-object value" in result["message"]
assert "attribute" not in result["message"]
def test_search_code_rejects_non_dict_body(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(github.github_search_code("def parse"))
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_list_tools_tolerate_next_page_none_feedback(monkeypatch):
"""A caller mechanically feeding a previous response's next_page back
(null when not truncated) must get a normal page-1 result, not a
field-nameless TypeError from int(None)."""
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={"total_count": 0, "items": []})),
)
result = json.loads(github.github_search_repositories("stars:>1", page=None))
assert result["status"] == "success"
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
issues = json.loads(
github.github_list_issues("octocat/Hello-World", page=None, skip=None)
)
assert issues["status"] == "success"
pulls = json.loads(
github.github_list_pull_requests("octocat/Hello-World", page=None)
)
assert pulls["status"] == "success"
commits = json.loads(github.github_list_commits("octocat/Hello-World", page=None))
assert commits["status"] == "success"
def test_search_repositories_sends_query_and_clamps_over_limit(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"total_count": 0, "items": []})
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_search_repositories("org:openai stars:>100", limit=500)
assert mock_request.call_args.kwargs["method"] == "GET"
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/search/repositories"
)
assert mock_request.call_args.kwargs["params"] == {
"q": "org:openai stars:>100",
"per_page": github.MAX_PER_PAGE,
"page": 1,
}
assert mock_request.call_args.kwargs["timeout"] == github.DEFAULT_TIMEOUT_SECONDS
@pytest.mark.parametrize("query", ["", " "])
def test_search_repositories_rejects_blank_query(monkeypatch, query):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_search_repositories(query))
assert result["status"] == "error"
mock_request.assert_not_called()
def test_search_repositories_reports_truncated_when_more_pages_exist(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"total_count": 500, "items": []},
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
),
)
result = json.loads(github.github_search_repositories("stars:>1"))
assert result["status"] == "success"
assert result["truncated"] is True
assert result["truncation_reason"] == "more_pages"
assert result["next_page"] == 2
def test_search_repositories_falls_back_to_item_count_on_null_total_count(
monkeypatch,
):
""".get("total_count", default)'s default only fires when the key is
absent -- an explicit "total_count": null must still fall back to the
item count, not surface as None."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"total_count": None, "items": [{"full_name": "a/b"}]}
)
),
)
result = json.loads(github.github_search_repositories("stars:>1"))
assert result["total_count"] == 1
def test_search_repositories_not_truncated_when_link_header_has_no_next_rel(
monkeypatch,
):
"""Every existing truncated-case fixture sets rel="next"; every
non-truncated case omits the Link header entirely -- neither
distinguishes "no next rel" from "any Link header at all". A Link
header with only rel="last"/"prev" (the last page of a paginated
result) must not be mistaken for a continuation."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"total_count": 2, "items": []},
headers={
"Link": (
'<https://api.github.com/x?page=1>; rel="prev", '
'<https://api.github.com/x?page=1>; rel="first"'
)
},
)
),
)
result = json.loads(github.github_search_repositories("stars:>1"))
assert result["status"] == "success"
assert result["truncated"] is False
assert result.get("next_page") is None
def test_search_repositories_sends_requested_page(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"total_count": 0, "items": []})
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_search_repositories("stars:>1", page=3)
assert mock_request.call_args.kwargs["params"]["page"] == 3
def test_get_current_user_returns_profile(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={
"login": "octocat",
"id": 1,
"name": "The Octocat",
"email": "[email protected]",
"company": "GitHub",
"bio": "",
"public_repos": 8,
"followers": 100,
"following": 9,
"html_url": "https://github.com/octocat",
}
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_get_current_user())
assert result["status"] == "success"
assert result["user"]["login"] == "octocat"
assert result["user"]["email"] == "[email protected]"
assert mock_request.call_args.kwargs["url"].endswith("/user")
def test_get_current_user_returns_error_payload_on_failure(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Bad credentials"}, status_code=401
)
),
)
result = json.loads(github.github_get_current_user())
assert result["status"] == "error"
assert "Bad credentials" in result["message"]
def test_get_current_user_rejects_non_object_response(monkeypatch):
"""A malformed/proxy-mangled response (e.g. a bare list) must not
reach the unguarded .get() calls below, which would surface as an
unhelpful `'list' object has no attribute 'get'`."""
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(github.github_get_current_user())
assert result["status"] == "error"
assert "non-object value" in result["message"]
assert "attribute" not in result["message"]
def test_get_repository_returns_summary(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"full_name": "octocat/Hello-World"})
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_get_repository("octocat/Hello-World"))
assert result["status"] == "success"
assert result["repository"]["full_name"] == "octocat/Hello-World"
assert mock_request.call_args.kwargs["url"].endswith("/repos/octocat/Hello-World")
def test_get_repository_rejects_non_object_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(github.github_get_repository("octocat/Hello-World"))
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_get_repository_rejects_malformed_repo(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_get_repository("not-a-repo"))
assert result["status"] == "error"
mock_request.assert_not_called()
def test_list_issues_excludes_pull_requests(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{"number": 1, "title": "a real issue", "labels": []},
{
"number": 2,
"title": "actually a PR",
"labels": [],
"pull_request": {"url": "https://api.github.com/x"},
},
]
)
),
)
result = json.loads(github.github_list_issues("octocat/Hello-World"))
assert result["status"] == "success"
numbers = [issue["number"] for issue in result["issues"]]
assert numbers == [1]
def test_list_issues_normalizes_dict_labels(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{
"number": 1,
"title": "labeled",
"labels": [{"name": "bug"}, "enhancement"],
}
]
)
),
)
result = json.loads(github.github_list_issues("octocat/Hello-World"))
assert result["issues"][0]["labels"] == ["bug", "enhancement"]
def test_list_issues_sends_non_default_state_and_labels(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data=[]))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_issues(
"octocat/Hello-World", state="closed", labels="bug,urgent", limit=5, page=2
)
assert mock_request.call_args.kwargs["method"] == "GET"
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/repos/octocat/Hello-World/issues"
)
assert mock_request.call_args.kwargs["timeout"] == github.DEFAULT_TIMEOUT_SECONDS
assert mock_request.call_args.kwargs["headers"]["Authorization"] == (
"Bearer access-token"
)
assert mock_request.call_args.kwargs["params"] == {
"state": "closed",
"per_page": github.MAX_PER_PAGE,
"page": 2,
"labels": "bug,urgent",
}
def test_list_issues_rejects_invalid_state(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_list_issues("octocat/Hello-World", state="merged")
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_list_issues_follows_pages_when_first_page_is_all_pull_requests(monkeypatch):
"""A PR-heavy (or all-PR) first page must not be reported as "no more
issues" -- github_list_issues has to keep paging until it either fills
the requested limit or GitHub runs out of pages (confirmed here via the
Link header, since the second page is genuinely the last one)."""
first_page = [
{
"number": i,
"title": f"pr {i}",
"labels": [],
"pull_request": {"url": "https://api.github.com/x"},
}
for i in range(1, github.MAX_PER_PAGE + 1)
]
second_page = [{"number": 200, "title": "a real issue", "labels": []}]
mock_request = Mock(
side_effect=[
MockResponse(
json_data=first_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
),
MockResponse(json_data=second_page), # no Link header -- last page
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=5))
assert result["status"] == "success"
assert [issue["number"] for issue in result["issues"]] == [200]
assert result["truncated"] is False
assert result["next_page"] is None
assert mock_request.call_count == 2
first_call, second_call = mock_request.call_args_list
assert first_call.kwargs["params"]["page"] == 1
assert second_call.kwargs["params"]["page"] == 2
def test_list_issues_reports_truncated_when_limit_reached_mid_page(monkeypatch):
page = [{"number": i, "title": f"issue {i}", "labels": []} for i in range(1, 11)]
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=page)),
)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=3))
assert result["status"] == "success"
assert len(result["issues"]) == 3
assert result["truncated"] is True
assert result["truncation_reason"] == "item_limit"
# A mid-page limit hit resumes the SAME page, skipping the raw items
# already consumed from it.
assert result["next_page"] == 1
assert result["next_skip"] == 3
def test_list_issues_skip_resumes_exactly_where_a_mid_page_cut_left_off(monkeypatch):
"""Round-trip: the next_page/next_skip a truncated call returns must let
a follow-up call pick up the remaining items from the same page."""
page = [{"number": i, "title": f"issue {i}", "labels": []} for i in range(1, 11)]
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=page)),
)
first = json.loads(github.github_list_issues("octocat/Hello-World", limit=3))
assert [issue["number"] for issue in first["issues"]] == [1, 2, 3]
assert first["next_page"] == 1
assert first["next_skip"] == 3
second = json.loads(
github.github_list_issues(
"octocat/Hello-World",
limit=3,
page=first["next_page"],
skip=first["next_skip"],
)
)
assert [issue["number"] for issue in second["issues"]] == [4, 5, 6]
assert second["next_page"] == 1
assert second["next_skip"] == 6
def test_list_issues_nonzero_skip_does_not_carry_over_to_a_later_real_page(
monkeypatch,
):
"""`page_skip` must reset to 0 once execution moves past the resumed
page -- all existing nonzero-skip tests mock only a single page, and
all existing multi-page tests (via a real Link header) start at
skip=0, so nothing exercises "resume with skip>0" together with "a
real second page fetched via the Link header". A regression that kept
applying start_skip to every page would silently drop start_skip
items from page 2 as well."""
first_page = [
{"number": i, "title": f"issue {i}", "labels": []} for i in range(1, 6)
]
second_page = [
{"number": i, "title": f"issue {i}", "labels": []} for i in range(6, 9)
]
monkeypatch.setattr(
github.requests,
"request",
Mock(
side_effect=[
MockResponse(
json_data=first_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
),
MockResponse(json_data=second_page),
]
),
)
result = json.loads(
github.github_list_issues("octocat/Hello-World", page=1, skip=2, limit=100)
)
assert result["status"] == "success"
# First 2 of page 1 (numbers 1-2) skipped per the resume cursor; all of
# page 2 (numbers 6-8) must be present, not skipped a second time.
assert [issue["number"] for issue in result["issues"]] == [3, 4, 5, 6, 7, 8]
def test_list_issues_trailing_prs_after_limit_do_not_count_as_truncation(monkeypatch):
"""Hitting the limit with only pull requests left on the final page is
not a truncation -- PRs are excluded from the result anyway, so nothing
the caller asked for was left behind."""
page = [
{"number": 1, "title": "issue 1", "labels": []},
{"number": 2, "title": "issue 2", "labels": []},
{
"number": 3,
"title": "pr 3",
"labels": [],
"pull_request": {"url": "https://api.github.com/x"},
},
]
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=page)), # no Link header
)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=2))
assert result["status"] == "success"
assert len(result["issues"]) == 2
assert result["truncated"] is False
assert result["truncation_reason"] is None
assert result["next_page"] is None
def test_list_issues_trailing_prs_after_limit_still_offer_next_page(monkeypatch):
"""Same trailing-PRs-only shape, but with a next page confirmed by the
Link header: the page-boundary continuation is lossless (no real issue
was left behind on this page), so next_page must be offered."""
page = [
{"number": 1, "title": "issue 1", "labels": []},
{
"number": 2,
"title": "pr 2",
"labels": [],
"pull_request": {"url": "https://api.github.com/x"},
},
]
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
),
)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=1))
assert result["status"] == "success"
assert len(result["issues"]) == 1
assert result["truncated"] is True
assert result["truncation_reason"] == "more_pages"
assert result["next_page"] == 2
def test_list_issues_full_final_page_without_next_link_is_not_truncated(monkeypatch):
"""A page that happens to come back exactly MAX_PER_PAGE long is not
itself proof more pages exist -- only the Link header's absent "next"
rel proves this genuinely was the last page. Regression test for the
previous length-based heuristic falsely marking this truncated."""
page = [
{"number": i, "title": f"issue {i}", "labels": []}
for i in range(1, github.MAX_PER_PAGE + 1)
]
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=page)), # no Link header
)
result = json.loads(
github.github_list_issues("octocat/Hello-World", limit=github.MAX_PER_PAGE)
)
assert result["status"] == "success"
assert len(result["issues"]) == github.MAX_PER_PAGE
assert result["truncated"] is False
assert result["truncation_reason"] is None
assert result["next_page"] is None
def test_list_issues_empty_page_with_next_link_still_reports_truncated(monkeypatch):
"""An empty page normally means the previous page's Link header already
said there's no more -- but if a malformed/unusual response still
reports hasNextPage on an empty page, that must not be silently
treated as a complete result."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[],
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
),
)
result = json.loads(github.github_list_issues("octocat/Hello-World"))
assert result["status"] == "success"
assert result["issues"] == []
assert result["truncated"] is True
assert result["truncation_reason"] == "more_pages"
assert result["next_page"] == 2
def test_list_issues_preserves_partial_results_on_malformed_json_body(monkeypatch):
"""A malformed 200 JSON body on page 2+ must be treated the same as a
request-level failure -- it must not escape the per-page handler and
discard issues already collected from earlier pages."""
first_page = [
{"number": i, "title": f"issue {i}", "labels": []} for i in range(1, 3)
]
class MalformedJsonResponse(MockResponse):
def json(self):
raise ValueError("Expecting value: line 1 column 1 (char 0)")
mock_request = Mock(
side_effect=[
MockResponse(
json_data=first_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
),
MalformedJsonResponse(content=b"not json"),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=100_000))
assert result["status"] == "partial"
assert len(result["issues"]) == 2
assert result["truncated"] is True
assert result["truncation_reason"] == "request_failed"
assert result["next_page"] == 2
assert "Expecting value" in result["error"]
def test_list_issues_preserves_partial_results_on_non_list_page(monkeypatch):
"""A valid-JSON but non-list page body (e.g. an object) must be treated
like a request-level failure, not iterated -- iterating a dict yields
its string keys, which would raise inside _summarize_issue() outside
any try, discarding issues already collected from earlier pages."""
first_page = [
{"number": i, "title": f"issue {i}", "labels": []} for i in range(1, 3)
]
mock_request = Mock(
side_effect=[
MockResponse(
json_data=first_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
),
MockResponse(json_data={"message": "not a list"}),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=100_000))
assert result["status"] == "partial"
assert len(result["issues"]) == 2
assert result["truncated"] is True
assert result["truncation_reason"] == "request_failed"
assert result["next_page"] == 2
assert "non-list page" in result["error"]
def test_list_issues_preserves_partial_results_on_non_object_item(monkeypatch):
"""A page that is a valid list but contains a non-object entry (e.g.
`[null]`) must not let that entry reach `"pull_request" in issue` or
`_summarize_issue()`, which would raise and discard every issue already
collected -- it should stop before the bad entry and offer a
continuation that resumes right after it."""
page_with_bad_item = [
{"number": 1, "title": "issue 1", "labels": []},
None,
{"number": 2, "title": "issue 2", "labels": []},
]
mock_request = Mock(return_value=MockResponse(json_data=page_with_bad_item))
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=100_000))
assert result["status"] == "partial"
assert len(result["issues"]) == 1
assert result["issues"][0]["number"] == 1
assert result["truncated"] is True
assert result["truncation_reason"] == "bad_item"
assert result["next_page"] == 1
assert result["next_skip"] == 2
assert "non-object item" in result["error"]
# Resuming from the offered cursor skips the bad item and picks up the
# remaining real issue.
mock_request.side_effect = [MockResponse(json_data=page_with_bad_item)]
resumed = json.loads(
github.github_list_issues(
"octocat/Hello-World",
limit=100_000,
page=result["next_page"],
skip=result["next_skip"],
)
)
assert resumed["status"] == "success"
assert [issue["number"] for issue in resumed["issues"]] == [2]
def test_list_issues_handles_non_object_item_after_the_limit_is_reached(monkeypatch):
"""A non-object item that appears AFTER the limit-cutting issue (rather
than before it) is reached only by the `hit_limit_mid_page` trailing-PR
lookahead, not the main per-item loop -- that lookahead must not raise
on it either, or it would discard every issue already collected on this
call, same as the before-the-limit case already covered above."""
page = [
{"number": 1, "title": "issue 1", "labels": []},
None,
]
mock_request = Mock(return_value=MockResponse(json_data=page))
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=1))
assert result["status"] == "success"
assert [issue["number"] for issue in result["issues"]] == [1]
# Conservatively treated as "not confirmed to be a pull request", so
# truncation is reported rather than the result being mistaken for
# complete.
assert result["truncated"] is True
assert result["truncation_reason"] == "item_limit"
assert result["next_page"] == 1
assert result["next_skip"] == 1
def test_list_issues_stops_at_max_pages_and_reports_truncated(monkeypatch):
"""When every page is entirely pull requests and the Link header still
reports more pages exist, the outer loop must still terminate at
MAX_ISSUE_PAGES (not loop forever) and report truncated with the page
to continue from."""
pr_only_page = [
{
"number": i,
"title": f"pr {i}",
"labels": [],
"pull_request": {"url": "https://api.github.com/x"},
}
for i in range(1, github.MAX_PER_PAGE + 1)
]
mock_request = Mock(
return_value=MockResponse(
json_data=pr_only_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=5))
assert result["status"] == "success"
assert result["issues"] == []
assert result["truncated"] is True
assert result["truncation_reason"] == "max_pages"
assert result["next_page"] == github.MAX_ISSUE_PAGES + 1
def test_list_issues_stops_when_aggregate_time_budget_is_exceeded(monkeypatch):
"""MAX_ISSUE_PAGES only bounds request COUNT -- a slow or PR-heavy repo
could otherwise hold the call open for MAX_ISSUE_PAGES *
DEFAULT_TIMEOUT_SECONDS (up to 5 minutes). The aggregate wall-clock
budget must cut it short with a resumable partial result instead."""
first_page = [
{
"number": i,
"title": f"pr {i}",
"labels": [],
"pull_request": {"url": "https://api.github.com/x"},
}
for i in range(1, github.MAX_PER_PAGE + 1)
]
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=first_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
),
)
# Call order: deadline baseline, page 1's request-timeout calc (still
# within budget), page 2's pre-request budget check (already exhausted).
# Repeats the last value forever rather than a fixed-length iter, so an
# unrelated code change adding one more clock read fails on its own
# assertion instead of a StopIteration from this test's plumbing.
clock = itertools.chain(
[0.0, 0.0], itertools.repeat(github.MAX_ISSUE_LIST_SECONDS + 1)
)
monkeypatch.setattr(github, "_monotonic", lambda: next(clock))
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=5))
# "partial", not "success": the budget ran out before the requested
# count was collected, same as a mid-pagination request fault -- a
# caller branching only on status must not mistake this for a clean,
# complete page (C1).
assert result["status"] == "partial"
assert result["issues"] == []
assert result["truncated"] is True
assert result["truncation_reason"] == "deadline"
assert result["next_page"] == 2
assert result["next_skip"] == 0
def test_list_issues_caps_request_timeout_to_remaining_budget(monkeypatch):
"""Near the aggregate deadline, an individual request's own timeout
must shrink to what's left of the budget -- otherwise a single
in-flight request could still run the full DEFAULT_TIMEOUT_SECONDS and
overshoot the aggregate budget before the next page's pre-request check
ever gets a chance to act on it."""
single_issue_page = [{"number": 1, "title": "issue", "labels": []}]
mock_request = Mock(
return_value=MockResponse(
json_data=single_issue_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
# Call order: deadline baseline, page 1's request-timeout calc, page 2's
# pre-request budget check, page 2's request-timeout calc (5s left).
# Repeats the last value forever rather than a fixed-length iter, so an
# unrelated code change adding one more clock read fails on its own
# assertion instead of a StopIteration from this test's plumbing.
clock = itertools.chain(
[0.0, 0.0], itertools.repeat(github.MAX_ISSUE_LIST_SECONDS - 5)
)
monkeypatch.setattr(github, "_monotonic", lambda: next(clock))
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=2))
assert result["status"] == "success"
assert mock_request.call_count == 2
second_call = mock_request.call_args_list[1]
assert second_call.kwargs["timeout"] == 5.0
def test_list_issues_starts_from_specified_page(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data=[{"number": 1, "title": "issue", "labels": []}]
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_issues("octocat/Hello-World", page=3)
assert mock_request.call_args.kwargs["params"]["page"] == 3
def test_list_issues_returns_next_page_when_more_full_pages_remain(monkeypatch):
page = [
{"number": i, "title": f"issue {i}", "labels": []}
for i in range(1, github.MAX_PER_PAGE + 1)
]
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=page,
headers={"Link": '<https://api.github.com/x?page=6>; rel="next"'},
)
),
)
result = json.loads(
github.github_list_issues(
"octocat/Hello-World", limit=github.MAX_PER_PAGE, page=5
)
)
assert result["status"] == "success"
assert result["truncated"] is True
assert result["truncation_reason"] == "more_pages"
assert result["next_page"] == 6
def test_list_issues_preserves_partial_results_on_mid_pagination_failure(monkeypatch):
"""A rate limit (or any transient error) on page 2+ must not discard the
issues already collected from page 1, matching slack.py's channel
listing precedent for the same failure mode."""
# A full (100-item), half-PR page whose Link header reports a next page
# -- the requested limit (clamped to 100) isn't satisfied by the 50 real
# issues it yields, so the loop must actually attempt page 2 (which then
# fails) instead of stopping after page 1.
first_page = [
{
"number": i,
"title": f"item {i}",
"labels": [],
**(
{"pull_request": {"url": "https://api.github.com/x"}}
if i % 2 == 0
else {}
),
}
for i in range(1, github.MAX_PER_PAGE + 1)
]
mock_request = Mock(
side_effect=[
MockResponse(
json_data=first_page,
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
),
MockResponse(json_data={"message": "rate limited"}, status_code=429),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_issues("octocat/Hello-World", limit=100_000))
assert result["status"] == "partial"
assert len(result["issues"]) == github.MAX_PER_PAGE // 2
assert result["truncated"] is True
assert result["truncation_reason"] == "request_failed"
# The failed page is the continuation point -- page 1's Link header
# confirmed page 2 exists, so a retry can resume there. Nothing on that
# page has been consumed yet, so next_skip is 0.
assert result["next_page"] == 2
assert result["next_skip"] == 0
assert "rate limited" in result["error"]
assert mock_request.call_count == 2
def test_list_issues_reraises_on_first_page_failure(monkeypatch):
"""A failure with nothing collected yet must still surface as an error
(not a "successful" empty list), same as before pagination was added."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Not Found"}, status_code=404
)
),
)
result = json.loads(github.github_list_issues("octocat/missing-repo"))
assert result["status"] == "error"
assert "Not Found" in result["message"]
def test_get_issue_flags_pull_request(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"number": 5,
"title": "a PR",
"labels": [],
"pull_request": {"url": "https://api.github.com/x"},
}
)
),
)
result = json.loads(github.github_get_issue("octocat/Hello-World", 5))
assert result["issue"]["is_pull_request"] is True
def test_get_issue_builds_exact_url(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"number": 42, "title": "x", "labels": []})
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_get_issue("octocat/Hello-World", 42)
assert mock_request.call_args.kwargs["method"] == "GET"
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/repos/octocat/Hello-World/issues/42"
)
@pytest.mark.parametrize("issue_number", [0, -1])
def test_get_issue_rejects_non_positive_number(monkeypatch, issue_number):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_get_issue("octocat/Hello-World", issue_number))
assert result["status"] == "error"
mock_request.assert_not_called()
def test_get_issue_rejects_non_object_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(github.github_get_issue("octocat/Hello-World", 1))
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_create_issue_splits_comma_separated_labels(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"number": 10, "title": "new issue", "labels": []}
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_issue(
"octocat/Hello-World", "new issue", body="details", labels="bug, urgent"
)
)
assert result["status"] == "success"
sent = mock_request.call_args.kwargs["json"]
assert sent["title"] == "new issue"
assert sent["body"] == "details"
assert sent["labels"] == ["bug", "urgent"]
def test_create_issue_omits_body_when_not_provided(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"number": 10, "title": "x", "labels": []})
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_create_issue("octocat/Hello-World", "new issue")
sent = mock_request.call_args.kwargs["json"]
assert "body" not in sent
assert "labels" not in sent
@pytest.mark.parametrize("title", ["", " "])
def test_create_issue_rejects_blank_title(monkeypatch, title):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_create_issue("octocat/Hello-World", title))
assert result["status"] == "error"
mock_request.assert_not_called()
def test_create_issue_surfaces_github_error_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"message": "Validation Failed",
"errors": [{"field": "title", "message": "cannot be blank"}],
},
status_code=422,
)
),
)
result = json.loads(github.github_create_issue("octocat/Hello-World", "new issue"))
assert result["status"] == "error"
assert "cannot be blank" in result["message"]
def test_create_issue_rejects_non_object_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(github.github_create_issue("octocat/Hello-World", "new issue"))
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_comment_on_issue_posts_body(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"id": 99, "html_url": "https://github.com/x/x/issues/1#c99"}
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_comment_on_issue("octocat/Hello-World", 1, "looks good")
)
assert result["status"] == "success"
assert result["comment_id"] == 99
assert mock_request.call_args.kwargs["json"] == {"body": "looks good"}
assert mock_request.call_args.kwargs["url"].endswith(
"/repos/octocat/Hello-World/issues/1/comments"
)
def test_comment_on_issue_rejects_non_object_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(
github.github_comment_on_issue("octocat/Hello-World", 1, "looks good")
)
assert result["status"] == "error"
assert "non-object value" in result["message"]
@pytest.mark.parametrize("body", ["", " "])
def test_comment_on_issue_rejects_blank_body(monkeypatch, body):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_comment_on_issue("octocat/Hello-World", 1, body))
assert result["status"] == "error"
mock_request.assert_not_called()
@pytest.mark.parametrize("issue_number", [0, -1])
def test_comment_on_issue_rejects_non_positive_number(monkeypatch, issue_number):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_comment_on_issue("octocat/Hello-World", issue_number, "hi")
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_list_pull_requests_returns_summaries(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{
"number": 3,
"title": "fix bug",
"head": {"ref": "fix-branch"},
"base": {"ref": "main"},
}
]
)
),
)
result = json.loads(github.github_list_pull_requests("octocat/Hello-World"))
assert result["status"] == "success"
assert result["pull_requests"][0]["head"] == "fix-branch"
assert result["pull_requests"][0]["base"] == "main"
assert result["truncated"] is False
assert result["next_page"] is None
def test_list_pull_requests_derives_merged_from_merged_at(monkeypatch):
"""The list-PRs endpoint never includes a "merged" key (only the
single-PR GET does), but it does include "merged_at" -- without
falling back to that, a genuinely merged PR would always report
merged: null from this tool."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{
"number": 1,
"title": "merged pr",
"merged_at": "2026-01-01T00:00:00Z",
},
{
"number": 2,
"title": "open pr",
"merged_at": None,
},
]
)
),
)
result = json.loads(github.github_list_pull_requests("octocat/Hello-World"))
assert result["pull_requests"][0]["merged"] is True
assert result["pull_requests"][1]["merged"] is False
def test_get_pull_request_prefers_actual_merged_field(monkeypatch):
"""The single-PR GET endpoint returns "merged" directly -- it must be
used as-is rather than derived from merged_at. The fixture is
deliberately contradictory (merged=False but merged_at set): a
regression that always derived from merged_at would report True here."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"number": 1,
"merged": False,
"merged_at": "2026-01-01T00:00:00Z",
}
)
),
)
result = json.loads(github.github_get_pull_request("octocat/Hello-World", 1))
assert result["pull_request"]["merged"] is False
def test_summarize_pull_request_reports_unknown_when_both_keys_absent(monkeypatch):
"""A degraded payload carrying neither "merged" nor "merged_at" must
report null ("unknown"), not a confident false."""
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={"number": 1, "title": "pr"})),
)
result = json.loads(github.github_get_pull_request("octocat/Hello-World", 1))
assert result["pull_request"]["merged"] is None
def test_list_pull_requests_reports_truncated_when_more_pages_exist(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[{"number": 1, "title": "pr", "head": {}, "base": {}}],
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
),
)
result = json.loads(github.github_list_pull_requests("octocat/Hello-World"))
assert result["status"] == "success"
assert result["truncated"] is True
assert result["truncation_reason"] == "more_pages"
assert result["next_page"] == 2
def test_list_pull_requests_rejects_non_object_item(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[None])),
)
result = json.loads(github.github_list_pull_requests("octocat/Hello-World"))
assert result["status"] == "error"
assert "non-object item" in result["message"]
def test_list_pull_requests_rejects_non_list_body(monkeypatch):
"""A truthy-but-non-list body (e.g. `{}`) isn't caught by the
`response.content else []` fallback (only an EMPTY body triggers it),
and `all(...)` over an empty dict's zero keys is vacuously true -- so
without a top-level type check this would silently report a
successful empty result instead of the malformed response it actually
was."""
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={})),
)
result = json.loads(github.github_list_pull_requests("octocat/Hello-World"))
assert result["status"] == "error"
assert "non-list value" in result["message"]
def test_list_pull_requests_rejects_invalid_state(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_list_pull_requests("octocat/Hello-World", state="merged")
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_list_pull_requests_sends_non_default_state_and_limit(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data=[]))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_pull_requests("octocat/Hello-World", state="closed", limit=5)
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/repos/octocat/Hello-World/pulls"
)
assert mock_request.call_args.kwargs["params"] == {
"state": "closed",
"per_page": 5,
"page": 1,
}
def test_list_pull_requests_sends_requested_page(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data=[]))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_pull_requests("octocat/Hello-World", page=3)
assert mock_request.call_args.kwargs["params"]["page"] == 3
def test_get_pull_request_returns_summary(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={"number": 3, "merged": False})),
)
result = json.loads(github.github_get_pull_request("octocat/Hello-World", 3))
assert result["status"] == "success"
assert result["pull_request"]["number"] == 3
def test_get_pull_request_builds_exact_url(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data={"number": 9}))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_get_pull_request("octocat/Hello-World", 9)
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/repos/octocat/Hello-World/pulls/9"
)
@pytest.mark.parametrize("pull_number", [0, -1])
def test_get_pull_request_rejects_non_positive_number(monkeypatch, pull_number):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_get_pull_request("octocat/Hello-World", pull_number)
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_get_pull_request_rejects_non_object_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(github.github_get_pull_request("octocat/Hello-World", 1))
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_create_pull_request_sends_head_and_base(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"number": 7, "title": "add feature"})
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_pull_request(
"octocat/Hello-World", "add feature", "feature-branch", "main"
)
)
assert result["status"] == "success"
sent = mock_request.call_args.kwargs["json"]
assert sent == {"title": "add feature", "head": "feature-branch", "base": "main"}
@pytest.mark.parametrize(
"title, head, base",
[
("", "feature-branch", "main"),
("add feature", "", "main"),
("add feature", "feature-branch", ""),
(" ", "feature-branch", "main"),
],
)
def test_create_pull_request_rejects_blank_required_fields(
monkeypatch, title, head, base
):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_pull_request("octocat/Hello-World", title, head, base)
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_create_pull_request_surfaces_github_error_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"message": "Validation Failed",
"errors": [{"field": "base", "message": "base branch not found"}],
},
status_code=422,
)
),
)
result = json.loads(
github.github_create_pull_request(
"octocat/Hello-World", "add feature", "feature-branch", "missing-branch"
)
)
assert result["status"] == "error"
assert "base branch not found" in result["message"]
def test_create_pull_request_rejects_non_object_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[])),
)
result = json.loads(
github.github_create_pull_request(
"octocat/Hello-World", "add feature", "feature-branch", "main"
)
)
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_get_file_contents_decodes_base64_file(monkeypatch):
encoded = base64.b64encode(b"print('hi')\n").decode()
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "main.py",
"sha": "abc123",
"size": 12,
"encoding": "base64",
"content": encoded,
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "main.py")
)
assert result["status"] == "success"
assert result["type"] == "file"
assert result["content"] == "print('hi')\n"
assert result["encoding"] == "utf-8"
def test_get_file_contents_returns_raw_base64_for_non_utf8_content(monkeypatch):
"""A binary (non-UTF-8) file must not be silently corrupted into
replacement characters while still reporting success -- return the
original base64 with an explicit encoding marker instead."""
binary_bytes = b"\x89PNG\r\n\x1a\n\x00\x01\xff\xfe"
encoded = base64.b64encode(binary_bytes).decode()
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "image.png",
"sha": "def456",
"size": len(binary_bytes),
"encoding": "base64",
"content": encoded,
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "image.png")
)
assert result["status"] == "success"
assert result["encoding"] == "base64"
assert result["content"] == encoded
assert "�" not in result["content"]
def test_get_file_contents_preserves_newline_wrapped_base64(monkeypatch):
"""GitHub wraps the base64 body with a newline every ~60 characters --
the strict decoder must strip that whitespace rather than reject it as
invalid alphabet input."""
encoded = base64.b64encode(b"a" * 90).decode()
wrapped = "\n".join(encoded[i : i + 60] for i in range(0, len(encoded), 60))
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "main.py",
"encoding": "base64",
"content": wrapped,
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "main.py")
)
assert result["status"] == "success"
assert result["content"] == "a" * 90
def test_get_file_contents_rejects_malformed_base64(monkeypatch):
"""Permissive (validate=False) decoding would otherwise turn
non-alphabet content into silently truncated/empty bytes while still
reporting success -- it must surface as an explicit error instead."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "main.py",
"encoding": "base64",
"content": "!!!!",
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "main.py")
)
assert result["status"] == "error"
assert "invalid base64" in result["message"]
def test_get_file_contents_rejects_non_string_content_field(monkeypatch):
"""A non-string, non-null `content` (e.g. an int from a malformed
response) must not reach _decode_base64_content(), which only expects
a string and would otherwise raise an uncaught TypeError instead of a
clean error message."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "main.py",
"encoding": "base64",
"content": 12345,
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "main.py")
)
assert result["status"] == "error"
assert "non-string content" in result["message"]
def test_get_file_contents_treats_null_content_as_empty(monkeypatch):
"""content: null (explicit JSON null, distinct from the key being
absent) must still fall back to an empty read, not be rejected as a
malformed non-string type."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "empty.txt",
"encoding": "utf-8",
"content": None,
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "empty.txt")
)
assert result["status"] == "success"
assert result["content"] == ""
def test_get_file_contents_flags_legacy_submodule_shape(monkeypatch):
"""A submodule can be returned with the legacy type="file" plus
submodule_git_url and no real content -- it must not be reported as a
successful empty file read."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "vendor/lib",
"sha": "abc123",
"submodule_git_url": "https://github.com/octocat/lib.git",
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "vendor/lib")
)
assert result["status"] == "success"
assert result["type"] == "submodule"
assert result["submodule_git_url"] == "https://github.com/octocat/lib.git"
def test_get_file_contents_directory_flags_submodule_entries(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{"name": "main.py", "path": "src/main.py", "type": "file"},
{
"name": "lib",
"path": "vendor/lib",
"type": "file",
"submodule_git_url": "https://github.com/octocat/lib.git",
},
]
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "vendor")
)
submodule_entry = next(e for e in result["entries"] if e["name"] == "lib")
assert submodule_entry["type"] == "submodule"
assert submodule_entry["submodule_git_url"] == "https://github.com/octocat/lib.git"
def test_get_file_contents_sends_ref_param_when_provided(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "main.py",
"encoding": "utf-8",
"content": "hi",
}
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_get_file_contents(
"octocat/Hello-World", "main.py", ref="feature-branch"
)
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/repos/octocat/Hello-World/contents/main.py"
)
assert mock_request.call_args.kwargs["params"] == {"ref": "feature-branch"}
def test_get_file_contents_omits_ref_param_when_not_provided(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "main.py",
"encoding": "utf-8",
"content": "hi",
}
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_get_file_contents("octocat/Hello-World", "main.py")
assert mock_request.call_args.kwargs["params"] == {}
def test_get_file_contents_lists_directory(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{"name": "main.py", "path": "src/main.py", "type": "file"},
{"name": "lib", "path": "src/lib", "type": "dir"},
]
)
),
)
result = json.loads(github.github_get_file_contents("octocat/Hello-World", "src"))
assert result["status"] == "success"
assert result["type"] == "directory"
assert len(result["entries"]) == 2
def test_get_file_contents_rejects_non_object_directory_entry(monkeypatch):
"""A non-object entry (e.g. a malformed API response) must not reach
the unguarded entry.get() calls below, which would surface as an
unhelpful `'str' object has no attribute 'get'` instead of identifying
what GitHub actually returned -- same class of gap as the issues
pagination hardening."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{"name": "main.py", "path": "src/main.py", "type": "file"},
None,
]
)
),
)
result = json.loads(github.github_get_file_contents("octocat/Hello-World", "src"))
assert result["status"] == "error"
assert "non-object item" in result["message"]
assert "directory listing" in result["message"]
def test_get_file_contents_rejects_non_file_type(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={"type": "symlink"})),
)
result = json.loads(github.github_get_file_contents("octocat/Hello-World", "link"))
assert result["status"] == "error"
assert "symlink" in result["message"]
def test_get_file_contents_reports_404(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Not Found"}, status_code=404
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "missing.py")
)
assert result["status"] == "error"
assert "Not Found" in result["message"]
def test_get_file_contents_falls_back_to_utf8_for_unrecognized_encoding(monkeypatch):
"""GitHub's Contents API only documents "base64"/"none" for `encoding`
-- an unrecognized value must fall through to the plain-text branch
(treating `content` as already-decoded text) rather than erroring or
silently dropping the field."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "main.py",
"encoding": "some-unrecognized-value",
"content": "already plain text",
}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "main.py")
)
assert result["status"] == "success"
assert result["content"] == "already plain text"
assert result["encoding"] == "utf-8"
def test_get_file_contents_accepts_empty_path_for_repo_root(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data=[{"name": "README.md", "path": "README.md", "type": "file"}]
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_get_file_contents("octocat/Hello-World", ""))
assert result["status"] == "success"
assert mock_request.call_args.kwargs["url"].endswith("/contents/")
@pytest.mark.parametrize(
"path",
[
"/src/main.py",
"src/main.py/",
"src//main.py",
"/",
"//",
"src/../etc", # dot-segment traversal attempt within a path
],
)
def test_get_file_contents_rejects_malformed_path(path, monkeypatch):
"""Leading/trailing/consecutive slashes and dot-segments must be
rejected outright, not silently interpolated into a malformed request
URL. '?'/'#' are deliberately not tested here -- unlike owner/repo,
those are legitimate filename characters; see the percent-encoding
test below."""
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_get_file_contents("octocat/Hello-World", path))
assert result["status"] == "error"
assert "not allowed" in result["message"]
mock_request.assert_not_called()
def test_get_file_contents_percent_encodes_path_segments(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "my notes.md",
"encoding": "utf-8",
"content": "hi",
}
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "docs/my notes.md")
)
assert result["status"] == "success"
assert mock_request.call_args.kwargs["url"].endswith("/contents/docs/my%20notes.md")
def test_get_file_contents_percent_encodes_question_mark_and_hash_in_path(monkeypatch):
"""Regression test: '?'/'#' in a filename must be percent-encoded and
the request allowed to proceed, not rejected as if they were injection
attempts (they were previously indistinguishable from the owner/repo
validator's stricter rule)."""
mock_request = Mock(
return_value=MockResponse(
json_data={
"type": "file",
"path": "docs/why?.md",
"encoding": "utf-8",
"content": "hi",
}
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "docs/why?.md")
)
assert result["status"] == "success"
assert mock_request.call_args.kwargs["url"].endswith("/contents/docs/why%3F.md")
def test_get_file_contents_reports_error_for_oversized_file(monkeypatch):
"""encoding == "none" means GitHub omitted the content because the file
exceeds the Contents API's size limit -- this must surface as an error,
not a silent empty-string "success"."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"type": "file", "path": "big.bin", "encoding": "none"}
)
),
)
result = json.loads(
github.github_get_file_contents("octocat/Hello-World", "big.bin")
)
assert result["status"] == "error"
assert "too large" in result["message"]
def test_get_file_contents_flags_directory_at_the_1000_entry_cap(monkeypatch):
entries = [
{"name": f"file{i}.py", "path": f"src/file{i}.py", "type": "file"}
for i in range(1000)
]
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=entries)),
)
result = json.loads(github.github_get_file_contents("octocat/Hello-World", "src"))
assert result["status"] == "success"
assert result["truncated"] is True
assert result["truncation_reason"] == "entry_cap"
# Unlike the list tools, there's no page/cursor to offer here (the
# Contents API has none for directories) -- the remediation is a
# message instead of an actionable continuation field.
assert "Trees API" in result["message"]
def test_get_file_contents_directory_under_cap_is_not_truncated(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[{"name": "main.py", "path": "src/main.py", "type": "file"}]
)
),
)
result = json.loads(github.github_get_file_contents("octocat/Hello-World", "src"))
assert result["status"] == "success"
assert result["truncated"] is False
assert result["truncation_reason"] is None
assert "message" not in result
def test_list_commits_returns_summaries(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[
{
"sha": "deadbeef",
"commit": {
"message": "fix bug",
"author": {"name": "Alice", "date": "2026-01-01T00:00:00Z"},
},
"html_url": "https://github.com/x/x/commit/deadbeef",
}
]
)
),
)
result = json.loads(github.github_list_commits("octocat/Hello-World"))
assert result["status"] == "success"
assert result["commits"][0]["message"] == "fix bug"
assert result["commits"][0]["author"] == "Alice"
assert result["truncated"] is False
assert result["next_page"] is None
def test_list_commits_reports_truncated_when_more_pages_exist(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data=[{"sha": "deadbeef", "commit": {}, "html_url": "https://x"}],
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
),
)
result = json.loads(github.github_list_commits("octocat/Hello-World"))
assert result["status"] == "success"
assert result["truncated"] is True
assert result["truncation_reason"] == "more_pages"
assert result["next_page"] == 2
def test_list_commits_rejects_non_object_item(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[None])),
)
result = json.loads(github.github_list_commits("octocat/Hello-World"))
assert result["status"] == "error"
assert "non-object item" in result["message"]
def test_list_commits_rejects_non_list_body(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={})),
)
result = json.loads(github.github_list_commits("octocat/Hello-World"))
assert result["status"] == "error"
assert "non-list value" in result["message"]
def test_list_commits_sends_path_and_clamps_over_limit(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data=[]))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_commits("octocat/Hello-World", path="src/main.py", limit=500)
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/repos/octocat/Hello-World/commits"
)
assert mock_request.call_args.kwargs["params"] == {
"per_page": github.MAX_PER_PAGE,
"page": 1,
"path": "src/main.py",
}
def test_list_commits_omits_path_param_when_not_provided(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data=[]))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_commits("octocat/Hello-World")
assert "path" not in mock_request.call_args.kwargs["params"]
@pytest.mark.parametrize("path", ["..", "src//main.py", "/src/main.py", "src/main.py/"])
def test_list_commits_rejects_malformed_path(monkeypatch, path):
"""path is sent as a query param, not path-interpolated, so this isn't
an injection risk -- but an empty segment or a bare dot-segment isn't
a real path, and github_get_file_contents already rejects the
identical shape of input up front instead of letting it reach GitHub
unvalidated."""
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_list_commits("octocat/Hello-World", path=path))
assert result["status"] == "error"
mock_request.assert_not_called()
def test_list_commits_allows_question_mark_and_hash_in_path(monkeypatch):
"""Unlike owner/repo, a real file path can legitimately contain '?'
or '#' -- must not be rejected the way a malformed path is."""
mock_request = Mock(return_value=MockResponse(json_data=[]))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_commits("octocat/Hello-World", path="docs/why?.md")
assert mock_request.call_args.kwargs["params"]["path"] == "docs/why?.md"
def test_list_commits_sends_requested_page(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data=[]))
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_list_commits("octocat/Hello-World", page=4)
assert mock_request.call_args.kwargs["params"]["page"] == 4
def test_search_code_falls_back_to_item_count_on_null_total_count(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"total_count": None,
"items": [{"name": "main.py", "path": "src/main.py"}],
}
)
),
)
result = json.loads(github.github_search_code("def parse"))
assert result["total_count"] == 1
def test_search_code_returns_items(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={
"total_count": 1,
"items": [
{
"name": "main.py",
"path": "src/main.py",
"repository": {"full_name": "octocat/Hello-World"},
"html_url": "https://github.com/x/x/blob/main/src/main.py",
}
],
}
)
),
)
result = json.loads(github.github_search_code("def parse"))
assert result["status"] == "success"
assert result["items"][0]["repository"] == "octocat/Hello-World"
assert result["incomplete_results"] is False
def test_search_code_flags_incomplete_results(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"total_count": 500, "items": [], "incomplete_results": True}
)
),
)
result = json.loads(github.github_search_code("def parse"))
assert result["status"] == "success"
assert result["incomplete_results"] is True
def test_search_code_rejects_non_object_item(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data={"total_count": 1, "items": [None]})),
)
result = json.loads(github.github_search_code("def parse"))
assert result["status"] == "error"
assert "non-object item" in result["message"]
def test_search_code_sends_query_and_clamps_over_limit(monkeypatch):
mock_request = Mock(
return_value=MockResponse(json_data={"total_count": 0, "items": []})
)
monkeypatch.setattr(github.requests, "request", mock_request)
github.github_search_code("repo:octocat/Hello-World def parse", limit=500)
assert mock_request.call_args.kwargs["url"] == (
f"{github.GITHUB_BASE_URL}/search/code"
)
assert mock_request.call_args.kwargs["params"] == {
"q": "repo:octocat/Hello-World def parse",
"per_page": github.MAX_PER_PAGE,
"page": 1,
}
@pytest.mark.parametrize("query", ["", " "])
def test_search_code_rejects_blank_query(monkeypatch, query):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_search_code(query))
assert result["status"] == "error"
mock_request.assert_not_called()
def test_search_code_reports_truncated_when_more_pages_exist(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"total_count": 500, "items": []},
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
),
)
result = json.loads(github.github_search_code("def parse"))
assert result["status"] == "success"
assert result["truncated"] is True
assert result["truncation_reason"] == "more_pages"
assert result["next_page"] == 2
def test_tool_returns_error_payload_on_missing_token(monkeypatch):
monkeypatch.delenv("GITHUB_ACCESS_TOKEN")
result = json.loads(github.github_get_repository("octocat/Hello-World"))
assert result["status"] == "error"
assert "GITHUB_ACCESS_TOKEN" in result["message"]
@pytest.mark.parametrize(
"call",
[
lambda: github.github_get_repository("octocat/Hello-World"),
lambda: github.github_get_issue("octocat/Hello-World", 1),
lambda: github.github_comment_on_issue("octocat/Hello-World", 1, "hi"),
lambda: github.github_get_pull_request("octocat/Hello-World", 1),
lambda: github.github_list_pull_requests("octocat/Hello-World"),
lambda: github.github_list_commits("octocat/Hello-World"),
lambda: github.github_search_code("def parse"),
lambda: github.github_search_repositories("stars:>1"),
lambda: github.github_get_file_contents("octocat/Hello-World", "README.md"),
lambda: github.github_list_issues("octocat/Hello-World"),
lambda: github.github_create_branch("octocat/Hello-World", "feature", "main"),
lambda: github.github_create_or_update_file(
"octocat/Hello-World", "README.md", "hi", "docs: update"
),
],
ids=[
"get_repository",
"get_issue",
"comment_on_issue",
"get_pull_request",
"list_pull_requests",
"list_commits",
"search_code",
"search_repositories",
"get_file_contents",
"list_issues",
"create_branch",
"create_or_update_file",
],
)
def test_tool_wrapper_surfaces_error_response(monkeypatch, call):
"""Drive a GitHub error response through each tool wrapper itself (not
only through the shared _request/_request_raw helpers) -- pin that every
one reports status: "error" with the upstream message, not an unhandled
exception or a silently-swallowed failure."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Service Unavailable"}, status_code=503
)
),
)
result = json.loads(call())
assert result["status"] == "error"
assert "Service Unavailable" in result["message"]
def test_create_branch_resolves_default_branch_and_posts_ref(monkeypatch):
mock_request = Mock(
side_effect=[
MockResponse(json_data={"default_branch": "main"}),
MockResponse(json_data={"object": {"sha": "a" * 40}}),
MockResponse(
json_data={"ref": "refs/heads/feature", "object": {"sha": "a" * 40}},
status_code=201,
),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_create_branch("octocat/Hello-World", "feature"))
assert result["status"] == "success"
assert result["branch"] == "feature"
assert result["from_ref"] == "main"
assert result["sha"] == "a" * 40
calls = mock_request.call_args_list
assert [c.kwargs["method"] for c in calls] == ["GET", "GET", "POST"]
assert calls[0].kwargs["url"].endswith("/repos/octocat/Hello-World")
assert (
calls[1].kwargs["url"].endswith("/repos/octocat/Hello-World/git/ref/heads/main")
)
assert calls[2].kwargs["url"].endswith("/repos/octocat/Hello-World/git/refs")
assert calls[2].kwargs["json"] == {"ref": "refs/heads/feature", "sha": "a" * 40}
def test_create_branch_uses_explicit_from_ref_without_repo_lookup(monkeypatch):
mock_request = Mock(
side_effect=[
MockResponse(json_data={"object": {"sha": "b" * 40}}),
MockResponse(
json_data={"ref": "refs/heads/hotfix/x", "object": {"sha": "b" * 40}},
status_code=201,
),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "hotfix/x", "release/v1")
)
assert result["status"] == "success"
assert result["from_ref"] == "release/v1"
calls = mock_request.call_args_list
assert len(calls) == 2
assert calls[0].kwargs["url"].endswith("/git/ref/heads/release/v1")
assert calls[1].kwargs["json"]["ref"] == "refs/heads/hotfix/x"
def test_create_branch_rejects_invalid_from_ref(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "x", "release/v1 rc")
)
assert result["status"] == "error"
assert "from_ref" in result["message"]
mock_request.assert_not_called()
def test_create_branch_percent_encodes_from_ref_with_reserved_chars(monkeypatch):
mock_request = Mock(
side_effect=[
MockResponse(json_data={"object": {"sha": "c" * 40}}),
MockResponse(
json_data={"ref": "refs/heads/x", "object": {}}, status_code=201
),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "x", "release/v1+rc")
)
assert result["status"] == "success"
url = mock_request.call_args_list[0].kwargs["url"]
assert url.endswith("/git/ref/heads/release/v1%2Brc")
@pytest.mark.parametrize(
"branch",
[
"",
" ",
"refs/heads/feature",
"/leading",
"trailing/",
"a//b",
"..",
"a/../b",
"has space",
"a?b",
"a:b",
"a~b",
"a^b",
"a*b",
"a[b",
"a\\b",
"a.lock",
"a/b.lock",
"a@{b",
"@",
"a..b",
".hidden",
"a/.hidden",
"trailing.",
"a/trailing.",
"a\x01b",
"a\x7fb",
],
)
def test_create_branch_rejects_invalid_branch_names(monkeypatch, branch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", branch, "main")
)
assert result["status"] == "error"
mock_request.assert_not_called()
@pytest.mark.parametrize(
"branch",
[
"release/1.0.0",
"foo./bar", # trailing "." mid-name is valid -- only the whole
# name, i.e. the LAST segment, may not end in "."
"feat/ünïcode",
"a#b", # "#" is a legal git ref character
"a/b/c/d",
],
)
def test_create_branch_accepts_tricky_but_valid_branch_names(monkeypatch, branch):
"""The rejection-parametrize test above has no acceptance counterpart,
so an over-strict rule (e.g. the previous per-segment trailing-dot bug,
which wrongly rejected "foo./bar") would go uncaught."""
mock_request = Mock(
side_effect=[
MockResponse(json_data={"object": {"sha": "d" * 40}}),
MockResponse(
json_data={"ref": f"refs/heads/{branch}", "object": {"sha": "e" * 40}},
status_code=201,
),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", branch, "main")
)
assert result["status"] == "success"
assert result["branch"] == branch
def test_create_branch_reports_existing_branch_with_hint(monkeypatch):
"""Empirically confirmed against the live API: POST .../git/refs
answers an existing ref with 422 "Reference already exists", not 409 --
GitHub's own docs (and this connector's first implementation) claimed
409, which real requests contradict."""
mock_request = Mock(
side_effect=[
MockResponse(json_data={"object": {"sha": "d" * 40}}),
MockResponse(
json_data={"message": "Reference already exists"}, status_code=422
),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", "main")
)
assert result["status"] == "error"
assert "Reference already exists" in result["message"]
assert "github_create_or_update_file" in result["message"]
def test_create_branch_surfaces_unrelated_422_without_hint(monkeypatch):
"""422 is this endpoint's generic validation-failure/spam code, distinct
from the "already exists" case above by message content, not status --
a differently-worded 422 must not be mistaken for "branch already
exists"."""
mock_request = Mock(
side_effect=[
MockResponse(json_data={"object": {"sha": "d" * 40}}),
MockResponse(json_data={"message": "Validation Failed"}, status_code=422),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", "main")
)
assert result["status"] == "error"
assert result["message"] == "Validation Failed"
def test_create_branch_reports_404_on_missing_ref_with_hint(monkeypatch):
mock_request = Mock(
side_effect=[
MockResponse(json_data={"message": "Not Found"}, status_code=404),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", "main")
)
assert result["status"] == "error"
assert "Not Found" in result["message"]
assert "octocat/Hello-World" in result["message"]
assert "main" in result["message"]
assert mock_request.call_count == 1
def test_create_branch_reports_404_on_missing_repo_with_hint(monkeypatch):
"""The default-branch lookup (from_ref omitted) is a separate GET from
the ref lookup covered above -- pin its own 404 handling."""
mock_request = Mock(
return_value=MockResponse(json_data={"message": "Not Found"}, status_code=404)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_create_branch("octocat/Hello-World", "feature"))
assert result["status"] == "error"
assert "Not Found" in result["message"]
assert "octocat/Hello-World" in result["message"]
assert mock_request.call_count == 1
def test_create_branch_rejects_non_string_from_ref(monkeypatch):
"""A None from_ref used to crash with AttributeError inside a bare
from_ref.strip() call (direct Python calls, as every test here makes,
bypass FastMCP's schema validation) -- must raise a clean ValueError
instead."""
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", None)
)
assert result["status"] == "error"
assert "from_ref" in result["message"]
mock_request.assert_not_called()
def test_create_branch_rejects_whitespace_only_from_ref(monkeypatch):
"""A whitespace-only from_ref used to be silently treated as "not
provided" (from_ref.strip() is falsy) instead of being rejected --
same "reject rather than repair" fix already applied to sha."""
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", " ")
)
assert result["status"] == "error"
assert "from_ref" in result["message"]
mock_request.assert_not_called()
def test_create_branch_validates_default_branch_as_from_ref(monkeypatch):
"""The GitHub-supplied default_branch fallback is now validated
identically to an explicit from_ref, so a failure is labeled
"from_ref" -- not the generic "path" _encode_file_path would raise it
as without this."""
mock_request = Mock(return_value=MockResponse(json_data={"default_branch": "a..b"}))
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_create_branch("octocat/Hello-World", "feature"))
assert result["status"] == "error"
assert "from_ref" in result["message"]
assert mock_request.call_count == 1
def test_create_branch_rejects_missing_default_branch(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data={"full_name": "x/y"}))
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_create_branch("octocat/Hello-World", "feature"))
assert result["status"] == "error"
assert "default branch" in result["message"]
assert mock_request.call_count == 1
def test_create_branch_rejects_missing_source_sha(monkeypatch):
mock_request = Mock(return_value=MockResponse(json_data={"object": {}}))
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", "main")
)
assert result["status"] == "error"
assert "no commit sha" in result["message"]
assert mock_request.call_count == 1
def test_create_branch_rejects_non_object_response(monkeypatch):
mock_request = Mock(
side_effect=[
MockResponse(json_data={"object": {"sha": "e" * 40}}),
MockResponse(json_data=[], status_code=201),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", "main")
)
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_create_or_update_file_strips_padded_path(monkeypatch):
"""A path with incidental leading/trailing whitespace (easy for an LLM
caller to emit) must resolve to the real file, not a differently-named
stray one -- _require_nonblank alone doesn't strip, so this would
otherwise create " test.txt" next to the intended "test.txt"."""
mock_request = Mock(
return_value=MockResponse(
json_data={"content": {"path": "test.txt"}, "commit": {}}, status_code=201
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", " test.txt\n", "x", "msg"
)
)
assert result["status"] == "success"
assert mock_request.call_args.kwargs["url"].endswith("/contents/test.txt")
def test_create_or_update_file_strips_padded_message(monkeypatch):
"""Same class of surprise as the path strip above, applied to the
commit message: an unstripped value would otherwise bake a stray
leading/trailing space into the commit shown in `git log`."""
mock_request = Mock(
return_value=MockResponse(
json_data={"content": {}, "commit": {}}, status_code=201
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", "x", " chore: ship\n"
)
)
assert result["status"] == "success"
assert mock_request.call_args.kwargs["json"]["message"] == "chore: ship"
def test_create_or_update_file_sends_base64_content_and_reports_created(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={
"content": {
"path": "docs/README.md",
"sha": "f" * 40,
"html_url": "https://github.com/octocat/Hello-World/blob/main/docs/README.md",
},
"commit": {
"sha": "0" * 40,
"html_url": "https://github.com/octocat/Hello-World/commit/000",
},
},
status_code=201,
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "docs/README.md", "Production Ready\n", "docs: ship"
)
)
assert result["status"] == "success"
assert result["action"] == "created"
assert result["path"] == "docs/README.md"
assert result["content_sha"] == "f" * 40
assert result["commit_sha"] == "0" * 40
assert result["branch"] is None
kwargs = mock_request.call_args.kwargs
assert kwargs["method"] == "PUT"
assert kwargs["url"].endswith("/repos/octocat/Hello-World/contents/docs/README.md")
assert kwargs["json"] == {
"message": "docs: ship",
"content": base64.b64encode(b"Production Ready\n").decode("ascii"),
}
def test_create_or_update_file_reports_updated_with_sha_and_branch(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"content": {"path": "test.txt", "sha": "1" * 40}, "commit": {}},
status_code=200,
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World",
"test.txt",
"Production Ready",
"chore: mark ready",
branch="release/v1",
sha="9" * 40,
)
)
assert result["status"] == "success"
assert result["action"] == "updated"
assert result["branch"] == "release/v1"
sent = mock_request.call_args.kwargs["json"]
assert sent["branch"] == "release/v1"
assert sent["sha"] == "9" * 40
assert sent["content"] == base64.b64encode(b"Production Ready").decode("ascii")
@pytest.mark.parametrize(
"sha",
[
" ",
" " + "9" * 40,
"9" * 40 + " ",
"9" * 39,
"9" * 41,
"g" * 40,
"9" * 40 + "\n",
"ABCDEF1234567890ABCDEF1234567890ABCDEF12",
],
)
def test_create_or_update_file_rejects_malformed_sha(monkeypatch, sha):
"""A malformed sha is rejected outright rather than silently stripped
or truncated into something that happens to look valid -- a caller bug
that produces a padded/truncated/wrong-case sha should surface here,
not be coerced into either a request GitHub 409s on, or (pre-fix) a
silently-stripped whitespace-only sha treated as "no sha" at all."""
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "test.txt", "x", "msg", sha=sha
)
)
assert result["status"] == "error"
assert "sha" in result["message"]
mock_request.assert_not_called()
def test_create_or_update_file_allows_empty_content(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"content": {}, "commit": {}}, status_code=200
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "empty.txt", "", "chore: truncate", sha="2" * 40
)
)
assert result["status"] == "success"
assert mock_request.call_args.kwargs["json"]["content"] == ""
def test_create_or_update_file_normalizes_base64_input(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"content": {}, "commit": {}}, status_code=201
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
# "hello world", newline-wrapped the way GitHub emits base64 content.
wrapped = "aGVs\nbG8gd29y\nbGQ="
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World",
"bin.dat",
wrapped,
"chore: add blob",
content_encoding="base64",
)
)
assert result["status"] == "success"
assert mock_request.call_args.kwargs["json"]["content"] == base64.b64encode(
b"hello world"
).decode("ascii")
@pytest.mark.parametrize("content", ["!!!!", "abc", "aGVsbG8"])
def test_create_or_update_file_rejects_malformed_base64_input(monkeypatch, content):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "bin.dat", content, "msg", content_encoding="base64"
)
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_create_or_update_file_rejects_unknown_content_encoding(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", "x", "msg", content_encoding="latin-1"
)
)
assert result["status"] == "error"
assert "content_encoding" in result["message"]
mock_request.assert_not_called()
def test_create_or_update_file_rejects_non_string_branch(monkeypatch):
"""A None branch used to crash with AttributeError inside a bare
branch.strip() call (direct Python calls, as every test here makes,
bypass FastMCP's schema validation) -- must raise a clean ValueError
instead."""
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", "x", "msg", branch=None
)
)
assert result["status"] == "error"
assert "branch" in result["message"]
mock_request.assert_not_called()
def test_create_or_update_file_rejects_whitespace_only_branch(monkeypatch):
"""A whitespace-only branch used to be silently treated as "not
provided" (branch.strip() is falsy) instead of being rejected -- same
"reject rather than repair" fix already applied to sha."""
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", "x", "msg", branch=" "
)
)
assert result["status"] == "error"
assert "branch" in result["message"]
mock_request.assert_not_called()
def test_create_or_update_file_rejects_non_string_sha(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", "x", "msg", sha=123
)
)
assert result["status"] == "error"
assert "sha" in result["message"]
mock_request.assert_not_called()
def test_create_or_update_file_rejects_oversized_utf8_content(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
oversized = "a" * (github._CONTENTS_API_MAX_BYTES + 1)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", oversized, "msg"
)
)
assert result["status"] == "error"
assert "1MB" in result["message"]
mock_request.assert_not_called()
def test_create_or_update_file_rejects_oversized_base64_content(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
oversized_raw = b"a" * (github._CONTENTS_API_MAX_BYTES + 1)
oversized_b64 = base64.b64encode(oversized_raw).decode("ascii")
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World",
"a.txt",
oversized_b64,
"msg",
content_encoding="base64",
)
)
assert result["status"] == "error"
assert "1MB" in result["message"]
mock_request.assert_not_called()
def test_create_or_update_file_accepts_content_at_exactly_the_size_limit(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"content": {}, "commit": {}}, status_code=201
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
exactly_at_limit = "a" * github._CONTENTS_API_MAX_BYTES
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", exactly_at_limit, "msg"
)
)
assert result["status"] == "success"
@pytest.mark.parametrize(
"path, message",
[
("", "msg"),
(" ", "msg"),
("a.txt", ""),
("a.txt", " "),
],
)
def test_create_or_update_file_rejects_blank_required_fields(
monkeypatch, path, message
):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file("octocat/Hello-World", path, "x", message)
)
assert result["status"] == "error"
mock_request.assert_not_called()
@pytest.mark.parametrize(
"path", ["../secret", "a//b", "/leading", "trailing/", "a/./b"]
)
def test_create_or_update_file_rejects_malformed_path(monkeypatch, path):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file("octocat/Hello-World", path, "x", "msg")
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_create_or_update_file_rejects_invalid_branch_name(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", "x", "msg", branch="refs/heads/main"
)
)
assert result["status"] == "error"
mock_request.assert_not_called()
def test_create_or_update_file_percent_encodes_path_segments(monkeypatch):
mock_request = Mock(
return_value=MockResponse(
json_data={"content": {}, "commit": {}}, status_code=201
)
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "dir name/file#1?.txt", "x", "msg"
)
)
assert result["status"] == "success"
assert mock_request.call_args.kwargs["url"].endswith(
"/contents/dir%20name/file%231%3F.txt"
)
def test_create_or_update_file_hints_when_sha_missing_for_existing_file(monkeypatch):
"""Empirically confirmed against the live API: a missing sha on an
existing file is 422, not 409 -- 409 is reserved for a stale sha (see
the sibling test below)."""
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Invalid request: sha wasn't supplied."},
status_code=422,
)
),
)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "test.txt", "x", "msg"
)
)
assert result["status"] == "error"
assert "wasn't supplied" in result["message"]
assert "github_get_file_contents" in result["message"]
def test_create_or_update_file_hints_when_sha_is_stale(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "test.txt does not match " + "3" * 40},
status_code=409,
)
),
)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "test.txt", "x", "msg", sha="4" * 40
)
)
assert result["status"] == "error"
assert "does not match" in result["message"]
assert "re-read" in result["message"]
def test_create_or_update_file_surfaces_unrelated_github_error_without_hint(
monkeypatch,
):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Internal Server Error"}, status_code=500
)
),
)
result = json.loads(
github.github_create_or_update_file("octocat/Hello-World", "a.txt", "x", "msg")
)
assert result["status"] == "error"
assert result["message"] == "Internal Server Error"
def test_create_or_update_file_reports_403_with_generic_hint(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Forbidden"}, status_code=403
)
),
)
result = json.loads(
github.github_create_or_update_file("octocat/Hello-World", "a.txt", "x", "msg")
)
assert result["status"] == "error"
assert "Forbidden" in result["message"]
assert "rate-limited" in result["message"]
assert "workflow" not in result["message"]
def test_create_or_update_file_reports_403_with_workflow_scope_hint(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Forbidden"}, status_code=403
)
),
)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", ".github/workflows/ci.yml", "x", "msg"
)
)
assert result["status"] == "error"
assert "workflow" in result["message"]
def test_create_branch_reports_403_with_generic_hint(monkeypatch):
mock_request = Mock(
side_effect=[
MockResponse(json_data={"object": {"sha": "d" * 40}}),
MockResponse(json_data={"message": "Forbidden"}, status_code=403),
]
)
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_create_branch("octocat/Hello-World", "feature", "main")
)
assert result["status"] == "error"
assert "Forbidden" in result["message"]
assert "rate-limited" in result["message"]
def test_create_or_update_file_reports_404_with_repo_only_hint(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Not Found"}, status_code=404
)
),
)
result = json.loads(
github.github_create_or_update_file("octocat/Hello-World", "a.txt", "x", "msg")
)
assert result["status"] == "error"
assert "Not Found" in result["message"]
assert "octocat/Hello-World" in result["message"]
assert "branch" not in result["message"]
def test_create_or_update_file_reports_404_with_branch_hint(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(
return_value=MockResponse(
json_data={"message": "Branch not found"}, status_code=404
)
),
)
result = json.loads(
github.github_create_or_update_file(
"octocat/Hello-World", "a.txt", "x", "msg", branch="missing-branch"
)
)
assert result["status"] == "error"
assert "octocat/Hello-World" in result["message"]
assert "missing-branch" in result["message"]
def test_create_or_update_file_rejects_non_object_response(monkeypatch):
monkeypatch.setattr(
github.requests,
"request",
Mock(return_value=MockResponse(json_data=[], status_code=201)),
)
result = json.loads(
github.github_create_or_update_file("octocat/Hello-World", "a.txt", "x", "msg")
)
assert result["status"] == "error"
assert "non-object value" in result["message"]
def test_create_or_update_file_never_retries_on_rate_limit(monkeypatch):
"""A write rejected by a rate limit must not be replayed -- if the first
PUT did reach GitHub, a retry would commit twice."""
mock_request = Mock(
return_value=MockResponse(
json_data={"message": "API rate limit exceeded"},
status_code=429,
headers={"Retry-After": "1"},
)
)
sleep_mock = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
monkeypatch.setattr(github, "_sleep", sleep_mock)
result = json.loads(
github.github_create_or_update_file("octocat/Hello-World", "a.txt", "x", "msg")
)
assert result["status"] == "error"
assert "rate limit" in result["message"]
assert mock_request.call_count == 1
sleep_mock.assert_not_called()
# --- release tooling -------------------------------------------------------
API = "https://api.github.com/repos/octocat/Hello-World"
SHA = "a" * 40
OTHER_SHA = "b" * 40
def _routes(monkeypatch, routes):
"""Mock requests.request with a (METHOD, path-after-repo) -> response map.
A value may be a MockResponse, a list of them (consumed in order, for
paginated routes) or an exception. Unmapped routes fail the test loudly.
"""
calls = []
def fake(method, url, **kwargs):
assert url.startswith(API), url
key = (method, url[len(API) :])
calls.append((key, kwargs))
assert key in routes, f"unexpected request {key}"
value = routes[key]
if isinstance(value, list):
value = value.pop(0)
return value
monkeypatch.setattr(github.requests, "request", fake)
return calls
def _err(status, message="boom", **kwargs):
return MockResponse(json_data={"message": message}, status_code=status, **kwargs)
def _check(name, status="completed", conclusion="success"):
return {
"name": name,
"status": status,
"conclusion": conclusion,
"html_url": f"https://github.com/x/{name}",
}
def _status_routes(statuses=(), checks=(), combined_state="pending"):
return {
("GET", "/commits/main/status"): MockResponse(
json_data={
"sha": SHA,
"state": combined_state,
"total_count": len(statuses),
"statuses": list(statuses),
}
),
("GET", "/commits/main/check-runs"): MockResponse(
json_data={"total_count": len(checks), "check_runs": list(checks)}
),
}
def _ref_status(**kwargs):
return json.loads(github.github_get_ref_status("octocat/Hello-World", "main"))
def test_ref_status_all_green(monkeypatch):
_routes(
monkeypatch,
_status_routes(
statuses=[{"context": "ci/legacy", "state": "success"}],
checks=[_check("lint"), _check("test", conclusion="skipped")],
combined_state="success",
),
)
result = _ref_status()
assert result["status"] == "success"
assert result["state"] == "success"
assert result["sha"] == SHA
assert result["check_runs"] == {
"total": 2,
"success": 2,
"failing": 0,
"pending": 0,
}
assert result["statuses"]["success"] == 1
assert result["failing"] == [] and result["pending"] == []
def test_ref_status_failure_beats_pending_and_success(monkeypatch):
_routes(
monkeypatch,
_status_routes(
checks=[
_check("lint"),
_check("build", status="in_progress", conclusion=None),
_check("test", conclusion="failure"),
]
),
)
result = _ref_status()
assert result["state"] == "failure"
assert [c["name"] for c in result["failing"]] == ["test"]
assert result["failing"][0]["url"] == "https://github.com/x/test"
assert [c["name"] for c in result["pending"]] == ["build"]
@pytest.mark.parametrize(
"conclusion", ["failure", "timed_out", "cancelled", "startup_failure"]
)
def test_ref_status_failing_check_conclusions(monkeypatch, conclusion):
_routes(monkeypatch, _status_routes(checks=[_check("x", conclusion=conclusion)]))
assert _ref_status()["state"] == "failure"
def test_ref_status_legacy_status_failure_and_error(monkeypatch):
_routes(
monkeypatch,
_status_routes(
statuses=[{"context": "ci/a", "state": "error", "target_url": "http://a"}],
checks=[_check("lint")],
),
)
result = _ref_status()
assert result["state"] == "failure"
assert result["failing"][0] == {
"kind": "status",
"name": "ci/a",
"state": "error",
"url": "http://a",
}
def test_ref_status_pending_when_anything_unfinished(monkeypatch):
_routes(
monkeypatch,
_status_routes(
statuses=[{"context": "ci/a", "state": "pending"}],
checks=[_check("lint")],
),
)
assert _ref_status()["state"] == "pending"
def test_ref_status_action_required_is_not_green(monkeypatch):
_routes(
monkeypatch, _status_routes(checks=[_check("x", conclusion="action_required")])
)
assert _ref_status()["state"] == "pending"
def test_ref_status_none_when_no_checks_or_statuses(monkeypatch):
# GitHub reports an empty combined status as "pending"; it must not leak.
_routes(monkeypatch, _status_routes())
result = _ref_status()
assert result["state"] == "none"
assert result["check_runs"]["total"] == 0
def test_ref_status_paginates_check_runs_and_clamps_pages(monkeypatch):
routes = _status_routes()
next_link = {"Link": '<https://api.github.com/x?page=2>; rel="next"'}
routes[("GET", "/commits/main/check-runs")] = [
MockResponse(json_data={"check_runs": [_check(f"c{i}")]}, headers=next_link)
for i in range(github.MAX_CHECK_RUN_PAGES)
]
calls = _routes(monkeypatch, routes)
result = _ref_status()
pages = [c[1]["params"]["page"] for c in calls if c[0][1].endswith("check-runs")]
assert pages == list(range(1, github.MAX_CHECK_RUN_PAGES + 1))
assert result["truncated"] is True
# Unseen checks may still fail: an all-green prefix is not reported green.
assert result["state"] == "pending"
def test_ref_status_follows_next_page_to_the_end(monkeypatch):
routes = _status_routes()
routes[("GET", "/commits/main/check-runs")] = [
MockResponse(
json_data={"check_runs": [_check("a")]},
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
),
MockResponse(json_data={"check_runs": [_check("b", conclusion="failure")]}),
]
_routes(monkeypatch, routes)
result = _ref_status()
assert result["truncated"] is False
assert result["check_runs"]["total"] == 2
assert result["state"] == "failure"
def test_ref_status_caps_reported_names_but_not_counts(monkeypatch):
checks = [_check(f"c{i}", conclusion="failure") for i in range(40)]
_routes(monkeypatch, _status_routes(checks=checks))
result = _ref_status()
assert result["check_runs"]["failing"] == 40
assert len(result["failing"]) == github.MAX_REPORTED_CHECKS
def test_ref_status_404_and_403(monkeypatch):
_routes(monkeypatch, {("GET", "/commits/main/status"): _err(404, "Not Found")})
result = _ref_status()
assert result["status"] == "error" and "not found" in result["message"]
_routes(monkeypatch, {("GET", "/commits/main/status"): _err(403, "Forbidden")})
assert _ref_status()["status"] == "error"
def test_ref_status_rejects_bad_ref(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_get_ref_status("octocat/Hello-World", "a b"))
assert result["status"] == "error"
mock_request.assert_not_called()
# latest release
def test_latest_release_returns_summary_without_body(monkeypatch):
_routes(
monkeypatch,
{
("GET", "/releases/latest"): MockResponse(
json_data={
"id": 7,
"tag_name": "v1.2.0",
"name": "v1.2.0",
"body": "notes",
"published_at": "2026-01-01T00:00:00Z",
"html_url": "https://github.com/x/releases/v1.2.0",
}
)
},
)
result = json.loads(github.github_get_latest_release("octocat/Hello-World"))
assert result["status"] == "success"
assert result["release"]["tag"] == "v1.2.0"
assert result["release"]["published_at"] == "2026-01-01T00:00:00Z"
assert "body" not in result["release"]
assert result["tags"] == []
def test_latest_release_none_yet_is_not_an_error(monkeypatch):
_routes(
monkeypatch,
{
("GET", "/releases/latest"): _err(404, "Not Found"),
("GET", ""): MockResponse(json_data={"full_name": "octocat/Hello-World"}),
("GET", "/tags"): MockResponse(
json_data=[{"name": "v0.3.0", "commit": {"sha": SHA}}]
),
},
)
result = json.loads(github.github_get_latest_release("octocat/Hello-World", 5))
assert result["status"] == "success"
assert result["release"] is None
assert result["tags"] == [{"name": "v0.3.0", "sha": SHA}]
def test_latest_release_missing_repo_is_an_error(monkeypatch):
_routes(
monkeypatch,
{
("GET", "/releases/latest"): _err(404, "Not Found"),
("GET", ""): _err(404, "Not Found"),
},
)
result = json.loads(github.github_get_latest_release("octocat/Hello-World"))
assert result["status"] == "error"
assert "not found" in result["message"]
def test_latest_release_clamps_tag_limit(monkeypatch):
calls = _routes(
monkeypatch,
{
("GET", "/releases/latest"): MockResponse(json_data={"tag_name": "v1"}),
("GET", "/tags"): MockResponse(json_data=[]),
},
)
github.github_get_latest_release("octocat/Hello-World", 5000)
assert calls[1][1]["params"] == {"per_page": 100}
def test_latest_release_403(monkeypatch):
_routes(monkeypatch, {("GET", "/releases/latest"): _err(403, "Forbidden")})
assert (
json.loads(github.github_get_latest_release("octocat/Hello-World"))["status"]
== "error"
)
# create release
def _release_payload(**extra):
return {
"id": 99,
"tag_name": "v1.0.0",
"name": "v1.0.0",
"body": "## What's Changed\n- stuff",
"draft": False,
"prerelease": False,
"html_url": "https://github.com/octocat/Hello-World/releases/tag/v1.0.0",
**extra,
}
def _create_routes(overrides=None):
routes = {
("GET", ""): MockResponse(json_data={"default_branch": "main"}),
("GET", "/commits/main"): MockResponse(json_data={"sha": SHA}),
("GET", "/git/ref/tags/v1.0.0"): _err(404, "Not Found"),
("POST", "/releases"): MockResponse(
json_data=_release_payload(), status_code=201
),
}
routes.update(overrides or {})
return routes
def _create(**kwargs):
return json.loads(
github.github_create_release("octocat/Hello-World", "v1.0.0", **kwargs)
)
def test_create_release_new_tag_uses_default_branch_sha(monkeypatch):
calls = _routes(monkeypatch, _create_routes())
result = _create()
assert result["status"] == "success"
assert result["tag"] == "v1.0.0"
assert result["sha"] == SHA
assert result["tag_created"] is True
assert result["release"]["html_url"].endswith("/v1.0.0")
assert "What's Changed" in result["release"]["body"]
post = calls[-1]
assert post[0] == ("POST", "/releases")
assert post[1]["json"] == {
"tag_name": "v1.0.0",
"name": "v1.0.0",
"draft": False,
"prerelease": False,
"generate_release_notes": True,
"target_commitish": SHA,
}
def test_create_release_explicit_target_and_options(monkeypatch):
routes = _create_routes()
routes[("GET", "/commits/release/1.x")] = MockResponse(json_data={"sha": OTHER_SHA})
calls = _routes(monkeypatch, routes)
result = _create(
target="release/1.x",
name="One",
body="hi",
generate_release_notes=False,
draft=True,
prerelease=True,
)
assert result["sha"] == OTHER_SHA
assert not any(c[0] == ("GET", "") for c in calls) # no default-branch lookup
assert calls[-1][1]["json"] == {
"tag_name": "v1.0.0",
"name": "One",
"body": "hi",
"draft": True,
"prerelease": True,
"generate_release_notes": False,
"target_commitish": OTHER_SHA,
}
def test_create_release_refuses_tag_pointing_elsewhere(monkeypatch):
calls = _routes(
monkeypatch,
_create_routes(
{
("GET", "/git/ref/tags/v1.0.0"): MockResponse(
json_data={"object": {"sha": OTHER_SHA, "type": "commit"}}
)
}
),
)
result = _create()
assert result["status"] == "error"
assert "already exists" in result["message"]
assert OTHER_SHA in result["message"]
assert not any(c[0][0] == "POST" for c in calls)
def test_create_release_refuses_when_tag_already_has_release(monkeypatch):
calls = _routes(
monkeypatch,
_create_routes(
{
("GET", "/git/ref/tags/v1.0.0"): MockResponse(
json_data={"object": {"sha": SHA, "type": "commit"}}
),
("GET", "/releases/tags/v1.0.0"): MockResponse(
json_data=_release_payload()
),
}
),
)
result = _create()
assert result["status"] == "error"
assert "already has a release" in result["message"]
assert not any(c[0][0] == "POST" for c in calls)
def test_create_release_for_existing_tag_at_target_without_release(monkeypatch):
calls = _routes(
monkeypatch,
_create_routes(
{
("GET", "/git/ref/tags/v1.0.0"): MockResponse(
json_data={"object": {"sha": SHA, "type": "commit"}}
),
("GET", "/releases/tags/v1.0.0"): _err(404, "Not Found"),
}
),
)
result = _create()
assert result["status"] == "success"
assert result["tag_created"] is False
assert "target_commitish" not in calls[-1][1]["json"]
def test_create_release_peels_annotated_tag(monkeypatch):
_routes(
monkeypatch,
_create_routes(
{
("GET", "/git/ref/tags/v1.0.0"): MockResponse(
json_data={"object": {"sha": "t" * 40, "type": "tag"}}
),
("GET", "/git/tags/" + "t" * 40): MockResponse(
json_data={"object": {"sha": SHA, "type": "commit"}}
),
("GET", "/releases/tags/v1.0.0"): _err(404, "Not Found"),
}
),
)
assert _create()["status"] == "success"
@pytest.mark.parametrize(
"tag", ["", " ", "refs/tags/v1", "v1 0", "v1..0", "v1:0", "/v1"]
)
def test_create_release_rejects_invalid_tag(monkeypatch, tag):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_create_release("octocat/Hello-World", tag))
assert result["status"] == "error"
mock_request.assert_not_called()
def test_create_release_unknown_target_404(monkeypatch):
routes = _create_routes()
routes[("GET", "/commits/nope")] = _err(404, "No commit found for SHA: nope")
_routes(monkeypatch, routes)
result = _create(target="nope")
assert result["status"] == "error"
assert "not found" in result["message"]
def test_create_release_403_is_a_write_error(monkeypatch):
_routes(
monkeypatch, _create_routes({("POST", "/releases"): _err(403, "Forbidden")})
)
result = _create()
assert result["status"] == "error"
assert "push access" in result["message"]
def test_create_release_422_is_labeled(monkeypatch):
_routes(
monkeypatch,
_create_routes({("POST", "/releases"): _err(422, "Validation Failed")}),
)
result = _create()
assert result["status"] == "error"
assert "rejected the release" in result["message"]
def test_create_release_rejects_non_bool_flags(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = _create(draft="yes")
assert result["status"] == "error"
mock_request.assert_not_called()
# update release
def test_update_release_by_id_sends_only_given_fields(monkeypatch):
calls = _routes(
monkeypatch,
{
("PATCH", "/releases/99"): MockResponse(
json_data=_release_payload(body="new")
)
},
)
result = json.loads(
github.github_update_release("octocat/Hello-World", "99", body="new")
)
assert result["status"] == "success"
assert result["release"]["body"] == "new"
assert calls[0][1]["json"] == {"body": "new"}
def test_update_release_by_tag_looks_up_id(monkeypatch):
calls = _routes(
monkeypatch,
{
("GET", "/releases/tags/v1.0.0"): MockResponse(json_data={"id": 99}),
("PATCH", "/releases/99"): MockResponse(json_data=_release_payload()),
},
)
result = json.loads(
github.github_update_release(
"octocat/Hello-World", "v1.0.0", name="N", prerelease=False
)
)
assert result["status"] == "success"
assert calls[1][1]["json"] == {"name": "N", "prerelease": False}
def test_update_release_requires_a_field(monkeypatch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(github.github_update_release("octocat/Hello-World", "99"))
assert result["status"] == "error"
assert "Nothing to update" in result["message"]
mock_request.assert_not_called()
def test_update_release_empty_body_is_a_valid_update(monkeypatch):
calls = _routes(
monkeypatch,
{("PATCH", "/releases/5"): MockResponse(json_data=_release_payload())},
)
github.github_update_release("octocat/Hello-World", "5", body="")
assert calls[0][1]["json"] == {"body": ""}
@pytest.mark.parametrize(
"status,needle", [(404, "not found"), (403, "push access"), (422, "rejected")]
)
def test_update_release_error_mapping(monkeypatch, status, needle):
_routes(monkeypatch, {("PATCH", "/releases/5"): _err(status, "x")})
result = json.loads(
github.github_update_release("octocat/Hello-World", "5", body="b")
)
assert result["status"] == "error"
assert needle in result["message"]
# workflow runs
def _run(i, **extra):
return {
"id": i,
"name": "Publish",
"event": "push",
"status": "completed",
"conclusion": "success",
"head_branch": "v1.0.0",
"head_sha": SHA,
"html_url": f"https://github.com/x/actions/runs/{i}",
"created_at": "2026-11-05T00:00:00Z",
**extra,
}
def test_workflow_runs_returns_summaries_and_sends_filters(monkeypatch):
calls = _routes(
monkeypatch,
{
("GET", "/actions/runs"): MockResponse(
json_data={"total_count": 1, "workflow_runs": [_run(1)]}
)
},
)
result = json.loads(
github.github_list_workflow_runs(
"octocat/Hello-World",
branch_or_tag="v1.0.0",
head_sha=SHA,
event="push",
limit=5,
)
)
assert result["status"] == "success"
assert result["runs"][0]["name"] == "Publish"
assert result["runs"][0]["conclusion"] == "success"
assert result["truncated"] is False
assert calls[0][1]["params"] == {
"per_page": 5,
"page": 1,
"branch": "v1.0.0",
"head_sha": SHA,
"event": "push",
}
def test_workflow_runs_clamps_limit_and_reports_next_page(monkeypatch):
calls = _routes(
monkeypatch,
{
("GET", "/actions/runs"): MockResponse(
json_data={"workflow_runs": []},
headers={"Link": '<https://api.github.com/x?page=2>; rel="next"'},
)
},
)
result = json.loads(
github.github_list_workflow_runs("octocat/Hello-World", limit=9999)
)
assert calls[0][1]["params"]["per_page"] == 100
assert result["truncated"] is True and result["next_page"] == 2
@pytest.mark.parametrize(
"kwargs",
[{"head_sha": "xyz"}, {"event": "Push Event"}, {"branch_or_tag": "a b"}],
)
def test_workflow_runs_reject_bad_filters(monkeypatch, kwargs):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
result = json.loads(
github.github_list_workflow_runs("octocat/Hello-World", **kwargs)
)
assert result["status"] == "error"
mock_request.assert_not_called()
@pytest.mark.parametrize("status", [403, 404])
def test_workflow_runs_error_mapping(monkeypatch, status):
_routes(monkeypatch, {("GET", "/actions/runs"): _err(status, "x")})
result = json.loads(github.github_list_workflow_runs("octocat/Hello-World"))
assert result["status"] == "error"
# --- update submodule ------------------------------------------------------
HEAD = "1" * 40
TREE = "2" * 40
NEW_TREE = "3" * 40
NEW_COMMIT = "4" * 40
OLD_SUB = "5" * 40
NEW_SUB = "6" * 40
GITMODULES = (
'[submodule "other"]\n\tpath = other\n\turl = https://github.com/o/other.git\n'
'[submodule "xagent"]\n\tpath = xagent\n\turl = [email protected]:xorbitsai/xagent.git\n'
)
def _sub_routes(overrides=None, entry=None, gitmodules=GITMODULES):
entry = entry or {
"path": "xagent",
"mode": "160000",
"type": "commit",
"sha": OLD_SUB,
}
routes = {
("GET", ""): MockResponse(json_data={"default_branch": "main"}),
("GET", "/git/ref/heads/main"): MockResponse(
json_data={"object": {"sha": HEAD}}
),
("GET", f"/git/commits/{HEAD}"): MockResponse(
json_data={"tree": {"sha": TREE}}
),
("GET", f"/git/trees/{TREE}"): MockResponse(
json_data={
"tree": [
{
"path": "README.md",
"mode": "100644",
"type": "blob",
"sha": "e" * 40,
},
entry,
]
}
),
("GET", "/git/ref/heads/bump/xagent"): _err(404, "Not Found"),
("POST", "/git/trees"): MockResponse(
json_data={"sha": NEW_TREE}, status_code=201
),
("POST", "/git/commits"): MockResponse(
json_data={"sha": NEW_COMMIT}, status_code=201
),
("POST", "/git/refs"): MockResponse(
json_data={"ref": "refs/heads/bump/xagent"}, status_code=201
),
("GET", "/contents/.gitmodules"): MockResponse(
json_data={
"encoding": "base64",
"content": base64.b64encode(gitmodules.encode()).decode(),
}
),
}
routes.update(overrides or {})
return routes
def _bump(**kwargs):
args = {"path": "xagent", "sha": NEW_SUB, "branch": "bump/xagent"}
args.update(kwargs)
return json.loads(github.github_update_submodule("octocat/Hello-World", **args))
def _posts(calls):
return [c for c in calls if c[0][0] == "POST"]
def test_update_submodule_happy_path(monkeypatch):
calls = _routes(monkeypatch, _sub_routes())
result = _bump()
assert result["status"] == "success"
assert result["updated"] is True
assert (result["old_sha"], result["new_sha"]) == (OLD_SUB, NEW_SUB)
assert result["commit_sha"] == NEW_COMMIT
assert result["branch"] == "bump/xagent"
assert result["compare_url"] == (
f"https://github.com/xorbitsai/xagent/compare/{OLD_SUB}...{NEW_SUB}"
)
posts = {c[0][1]: c[1]["json"] for c in _posts(calls)}
assert posts["/git/trees"] == {
"base_tree": TREE,
"tree": [
{"path": "xagent", "mode": "160000", "type": "commit", "sha": NEW_SUB}
],
}
assert posts["/git/commits"] == {
"message": f"chore: bump xagent to {NEW_SUB[:8]}",
"tree": NEW_TREE,
"parents": [HEAD],
}
assert posts["/git/refs"] == {"ref": "refs/heads/bump/xagent", "sha": NEW_COMMIT}
def test_update_submodule_custom_base_message_and_uppercase_sha(monkeypatch):
routes = _sub_routes()
routes[("GET", "/git/ref/heads/release/1")] = routes.pop(
("GET", "/git/ref/heads/main")
)
calls = _routes(monkeypatch, routes)
result = _bump(
base="release/1", message="custom", sha=NEW_SUB.upper().replace("6", "A")
)
assert result["status"] == "success"
assert result["new_sha"] == "a" * 40
assert not any(c[0] == ("GET", "") for c in calls)
assert [
c[1]["json"]["message"] for c in _posts(calls) if c[0][1] == "/git/commits"
] == ["custom"]
def test_update_submodule_compare_url_is_optional(monkeypatch):
for routes in (
_sub_routes({("GET", "/contents/.gitmodules"): _err(404, "Not Found")}),
_sub_routes(gitmodules="garbage"),
_sub_routes(
gitmodules='[submodule "x"]\n\tpath = xagent\n\turl = https://gitlab.com/o/x.git\n'
),
):
_routes(monkeypatch, routes)
result = _bump()
assert result["status"] == "success"
assert result["compare_url"] is None
def test_update_submodule_nested_path(monkeypatch):
routes = _sub_routes()
routes[("GET", f"/git/trees/{TREE}")] = MockResponse(
json_data={
"tree": [
{"path": "libs", "mode": "040000", "type": "tree", "sha": "7" * 40}
]
}
)
routes[("GET", f"/git/trees/{'7' * 40}")] = MockResponse(
json_data={
"tree": [
{"path": "xagent", "mode": "160000", "type": "commit", "sha": OLD_SUB}
]
}
)
calls = _routes(monkeypatch, routes)
result = _bump(path="libs/xagent")
assert result["status"] == "success"
tree_post = next(c for c in _posts(calls) if c[0][1] == "/git/trees")
assert tree_post[1]["json"]["tree"][0]["path"] == "libs/xagent"
@pytest.mark.parametrize(
"entry",
[
{"path": "xagent", "mode": "100644", "type": "blob", "sha": "e" * 40},
{"path": "xagent", "mode": "040000", "type": "tree", "sha": "e" * 40},
],
)
def test_update_submodule_refuses_non_submodule(monkeypatch, entry):
calls = _routes(monkeypatch, _sub_routes(entry=entry))
result = _bump()
assert result["status"] == "error"
assert "not a submodule" in result["message"]
assert _posts(calls) == []
def test_update_submodule_missing_path(monkeypatch):
calls = _routes(monkeypatch, _sub_routes())
result = _bump(path="nope")
assert result["status"] == "error"
assert "does not exist" in result["message"]
assert _posts(calls) == []
def test_update_submodule_noop_when_already_at_sha(monkeypatch):
calls = _routes(monkeypatch, _sub_routes())
result = _bump(sha=OLD_SUB)
assert result["status"] == "success"
assert result["updated"] is False
assert "already at" in result["message"]
assert _posts(calls) == []
def test_update_submodule_refuses_existing_branch_before_writing(monkeypatch):
calls = _routes(
monkeypatch,
_sub_routes(
{
("GET", "/git/ref/heads/bump/xagent"): MockResponse(
json_data={"object": {}}
)
}
),
)
result = _bump()
assert result["status"] == "error"
assert "already exists" in result["message"]
assert _posts(calls) == []
def test_update_submodule_branch_race_422(monkeypatch):
_routes(
monkeypatch,
_sub_routes({("POST", "/git/refs"): _err(422, "Reference already exists")}),
)
result = _bump()
assert result["status"] == "error"
assert "already exists" in result["message"]
@pytest.mark.parametrize("sha", ["", "abc123", "g" * 40, "6" * 41, None])
def test_update_submodule_rejects_bad_sha(monkeypatch, sha):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
assert _bump(sha=sha)["status"] == "error"
mock_request.assert_not_called()
@pytest.mark.parametrize("branch", ["", "a b", "refs/heads/x", "a..b"])
def test_update_submodule_rejects_bad_branch(monkeypatch, branch):
mock_request = Mock()
monkeypatch.setattr(github.requests, "request", mock_request)
assert _bump(branch=branch)["status"] == "error"
mock_request.assert_not_called()
def test_update_submodule_404_on_base(monkeypatch):
_routes(
monkeypatch,
_sub_routes({("GET", "/git/ref/heads/main"): _err(404, "Not Found")}),
)
result = _bump()
assert result["status"] == "error"
assert "not found" in result["message"]
@pytest.mark.parametrize(
"route,status,needle",
[
("/git/trees", 403, "push access"),
("/git/commits", 403, "push access"),
("/git/refs", 403, "push access"),
("/git/trees", 422, "rejected the submodule update"),
("/git/commits", 404, "Not Found"),
],
)
def test_update_submodule_write_error_mapping(monkeypatch, route, status, needle):
_routes(monkeypatch, _sub_routes({("POST", route): _err(status, "Not Found")}))
result = _bump()
assert result["status"] == "error"
assert needle in result["message"]