:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
"""Tests for GitHub review normalization used by the PR approval agent."""
import re
import subprocess
from pathlib import Path
import pytest
import gates
import github
from github import (
CommitProvenance,
_git_diff_files,
_normalize_discussion_for_prompt,
_normalize_reviews_for_prompt,
_reaction_emoji,
_trusted_reactor_predicate,
ensure_commits,
git_touched_paths,
is_bot_author,
parse_provenance_trailers,
write_pr_diff,
)
from policy import DenyException
def test_normalize_reviews_marks_current_head_and_preserves_stale_reviews() -> None:
head_sha = "072cdd75592bfd0bf0c016209385f20f85a45201"
current_review = {
"user": {"login": "copilot-pull-request-reviewer", "type": "Bot"},
"state": "COMMENTED",
"body": "Current head concern",
"commit_id": head_sha,
"submitted_at": "2026-04-07T20:14:03Z",
"author_association": "BOT",
}
stale_review = {
"user": {"login": "greptile-apps", "type": "Bot"},
"state": "COMMENTED",
"body": "Older concern",
"commit_id": "3c51bb8de4c73929c5266986118a14b966cb6831",
"submitted_at": "2026-04-07T20:02:32Z",
"author_association": "BOT",
}
normalized = _normalize_reviews_for_prompt([current_review, stale_review], head_sha)
assert normalized == [
{
"user": "copilot-pull-request-reviewer",
"state": "COMMENTED",
"body": "Current head concern",
"commit_id": head_sha,
"is_current_head": True,
"submitted_at": "2026-04-07T20:14:03Z",
},
{
"user": "greptile-apps",
"state": "COMMENTED",
"body": "Older concern",
"commit_id": "3c51bb8de4c73929c5266986118a14b966cb6831",
"is_current_head": False,
"submitted_at": "2026-04-07T20:02:32Z",
},
]
@pytest.mark.parametrize(
"author_association,user_type,expected_count",
[
pytest.param("MEMBER", "User", 1, id="member-reviewer"),
pytest.param("OWNER", "User", 1, id="owner-reviewer"),
pytest.param("COLLABORATOR", "User", 1, id="collaborator-reviewer"),
pytest.param("BOT", "User", 1, id="bot-association"),
pytest.param("NONE", "Bot", 1, id="bot-user-type"),
pytest.param("NONE", "User", 0, id="untrusted-reviewer"),
],
)
def test_normalize_reviews_filters_by_trust_source(
author_association: str, user_type: str, expected_count: int
) -> None:
normalized = _normalize_reviews_for_prompt(
[
{
"user": {"login": "reviewer", "type": user_type},
"state": "COMMENTED",
"body": "Review body",
"commit_id": "abc123",
"submitted_at": "2026-04-07T20:14:03Z",
"author_association": author_association,
}
],
"abc123",
)
assert len(normalized) == expected_count
class _Result:
def __init__(self, returncode: int) -> None:
self.returncode = returncode
@pytest.mark.parametrize(
"present, expected_fetches",
[
pytest.param({"HEAD_SHA", "BASE_SHA"}, [], id="both-present-no-fetch"),
pytest.param({"BASE_SHA"}, ["pull/9/head"], id="head-missing-fetches-pr-head"),
pytest.param({"HEAD_SHA"}, ["query-validations"], id="base-missing-fetches-base-branch"),
pytest.param(set(), ["pull/9/head", "query-validations"], id="both-missing-fetches-both"),
],
)
def test_ensure_commits_fetches_missing_head_and_base(
monkeypatch: pytest.MonkeyPatch, present: set[str], expected_fetches: list[str]
) -> None:
"""Stacked PRs target a parent branch, so the base commit may not be
reachable from the master checkout. ensure_commits fetches whatever is
missing — head via the pull ref, base via the base branch name."""
fetched: list[str] = []
def fake_run(cmd: list[str], **kwargs: object) -> _Result:
if cmd[:3] == ["git", "cat-file", "-t"]:
return _Result(0 if cmd[3] in present else 1)
if "fetch" in cmd:
fetched.append(cmd[-1])
return _Result(0)
return _Result(0)
monkeypatch.setattr(github.subprocess, "run", fake_run)
ensure_commits(
pr_number=9,
head_sha="HEAD_SHA",
base_ref="query-validations",
base_sha="BASE_SHA",
repo_root=Path("/repo"),
)
assert fetched == expected_fetches
def _git(cwd: Path, *args: str) -> str:
result = subprocess.run(["git", "-C", str(cwd), *args], capture_output=True, text=True, check=True)
return result.stdout.strip()
@pytest.mark.parametrize(
"old_path, new_path, denied",
[
("models/flow.py", "flow.py", []),
("apps/billing/old.yaml", "apps/billing/new.yaml", []),
("apps/billing/old\tname.yaml", "apps/billing/new\nname.yaml", []),
("apps/billing/service.py", "apps/plain/values.yaml", ["billing"]),
],
)
def test_touched_paths_carry_both_rename_names_unquoted(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, old_path: str, new_path: str, denied: list[str]
) -> None:
repo = tmp_path / "repo"
_git(tmp_path, "init", "--quiet", "-b", "main", str(repo))
_git(repo, "config", "user.name", "t")
_git(repo, "config", "user.email", "[email protected]")
(repo / old_path).parent.mkdir(parents=True)
(repo / old_path).write_text("\n".join(f"line {i}" for i in range(20)) + "\n")
_git(repo, "add", ".")
_git(repo, "commit", "--quiet", "-m", "root")
base = _git(repo, "rev-parse", "HEAD")
(repo / new_path).parent.mkdir(parents=True, exist_ok=True)
_git(repo, "mv", old_path, new_path)
(repo / "odd\nname.py").write_text("x\n")
_git(repo, "add", "--all")
_git(repo, "commit", "--quiet", "-m", "move")
head = _git(repo, "rev-parse", "HEAD")
touched = git_touched_paths(base, head, repo)
assert sorted(touched) == sorted([old_path, new_path, "odd\nname.py"])
files = _git_diff_files(base, head, repo)
assert {f["filename"]: f for f in files} == {
new_path: {"filename": new_path, "additions": 0, "deletions": 0, "binary": False, "status": "R100"},
"odd\nname.py": {"filename": "odd\nname.py", "additions": 1, "deletions": 0, "binary": False, "status": "A"},
}
exceptions = {"billing": (DenyException(keyword="billing", path_prefixes=("apps/",), extensions=(".yaml",)),)}
monkeypatch.setattr(gates, "DENY_EXCEPTIONS", gates._compile_deny_exceptions(gates._DENY_PATTERN_DEFS, exceptions))
assert gates.detect_deny_categories([*(f["filename"] for f in files), *touched]) == denied
def test_shallow_checkout_diffs_from_the_given_merge_base(tmp_path: Path) -> None:
# The hosted sandbox holds only the PR head and the merge base, each at depth 1, so git cannot
# compute base...head there. With the merge base given, the file list and the diff text must
# match what a full-history checkout reports for base...head.
origin = tmp_path / "origin"
_git(tmp_path, "init", "--quiet", "-b", "main", str(origin))
_git(origin, "config", "user.name", "t")
_git(origin, "config", "user.email", "[email protected]")
(origin / "kept.py").write_text("old\n")
(origin / "gone.py").write_text("bye\n")
_git(origin, "add", ".")
_git(origin, "commit", "--quiet", "-m", "root")
merge_base = _git(origin, "rev-parse", "HEAD")
_git(origin, "checkout", "--quiet", "-b", "feature")
(origin / "kept.py").write_text("new\n")
(origin / "gone.py").unlink()
(origin / "added.py").write_text("hi\n")
_git(origin, "add", "--all")
_git(origin, "commit", "--quiet", "-m", "feature")
head = _git(origin, "rev-parse", "HEAD")
_git(origin, "checkout", "--quiet", "main")
(origin / "base_only.py").write_text("drift\n")
_git(origin, "add", ".")
_git(origin, "commit", "--quiet", "-m", "base drift")
base_tip = _git(origin, "rev-parse", "HEAD")
shallow = tmp_path / "shallow"
_git(tmp_path, "init", "--quiet", str(shallow))
for sha in (head, merge_base):
_git(shallow, "fetch", "--quiet", "--depth=1", f"file://{origin}", sha)
_git(shallow, "-c", "advice.detachedHead=false", "checkout", "--quiet", head)
expected = _git_diff_files(base_tip, head, origin)
assert {f["filename"]: f["status"] for f in expected} == {"added.py": "A", "gone.py": "D", "kept.py": "M"}
assert _git_diff_files(base_tip, head, shallow, merge_base) == expected
with pytest.raises(RuntimeError):
_git_diff_files(base_tip, head, shallow)
full_diff = write_pr_diff(base_tip, head, origin)
shallow_diff = write_pr_diff(base_tip, head, shallow, merge_base)
assert shallow_diff.read_text() == full_diff.read_text()
@pytest.mark.parametrize(
"login,expected_count",
[
pytest.param("stamphog[bot]", 0, id="own-refuse-comment-review"),
pytest.param("github-actions[bot]", 0, id="own-approve-review"),
pytest.param("greptile-apps[bot]", 1, id="other-bot-kept"),
],
)
def test_normalize_reviews_excludes_stamphogs_own_prior_reviews(login: str, expected_count: int) -> None:
# Feeding stamphog's own stale reviews back into the prompt makes the next
# run read them as third-party claims about state that no longer matches —
# it then suspects tampering and refuses forever.
normalized = _normalize_reviews_for_prompt(
[
{
"user": {"login": login, "type": "Bot"},
"state": "COMMENTED",
"body": "Refusing: reviews in flight",
"commit_id": "abc123",
"submitted_at": "2026-04-07T20:14:03Z",
"author_association": "NONE",
}
],
"abc123",
)
assert len(normalized) == expected_count
@pytest.mark.parametrize(
"login,user_type,author_association,expected_count",
[
pytest.param("stamphog[bot]", "Bot", "NONE", 0, id="own-refuse-comment-excluded"),
pytest.param("github-actions[bot]", "Bot", "NONE", 0, id="own-approve-identity-excluded"),
pytest.param("greptile-apps[bot]", "Bot", "NONE", 1, id="other-bot-kept"),
pytest.param("alice", "User", "MEMBER", 1, id="trusted-member-kept"),
pytest.param("owner", "User", "OWNER", 1, id="trusted-owner-kept"),
# A drive-by external commenter must not reach the prompt: the
# maintainer-hold norm makes an untrusted "please hold" both griefable
# and forgeable, so discussion gets the same trust gate as reviews.
pytest.param("outsider", "User", "NONE", 0, id="untrusted-external-excluded"),
],
)
def test_normalize_discussion_filters_by_trust_and_own_comments(
login: str, user_type: str, author_association: str, expected_count: int
) -> None:
normalized = _normalize_discussion_for_prompt(
[
{
"user": {"login": login, "type": user_type},
"author_association": author_association,
"body": "a comment",
"created_at": "2026-04-07T20:14:03Z",
}
]
)
assert len(normalized) == expected_count
@pytest.mark.parametrize(
"content,expected",
[
pytest.param("+1", "👍", id="rest-thumbs-up"),
pytest.param("THUMBS_UP", "👍", id="graphql-thumbs-up"),
pytest.param("-1", "👎", id="rest-thumbs-down"),
pytest.param("EYES", "👀", id="graphql-eyes"),
pytest.param("sparkle", "sparkle", id="unknown-passthrough"),
],
)
def test_reaction_emoji_normalizes_rest_and_graphql(content: str, expected: str) -> None:
assert _reaction_emoji(content) == expected
@pytest.mark.parametrize(
"login,expected",
[
pytest.param("prauthor", False, id="author-self-reaction"),
pytest.param("ghost", False, id="deleted-user"),
pytest.param("", False, id="empty-login"),
pytest.param("greptile-apps[bot]", True, id="allowlisted-bot"),
pytest.param("inkeep[bot]", False, id="unlisted-bot"),
pytest.param("teammate", True, id="org-member"),
pytest.param("outsider", False, id="external-non-member"),
],
)
def test_trusted_reactor_predicate_gates_untrusted_and_author(
monkeypatch: pytest.MonkeyPatch, login: str, expected: bool
) -> None:
monkeypatch.setattr(github, "_is_org_member", lambda org, member: member == "teammate")
is_trusted = _trusted_reactor_predicate("PostHog/posthog", author="prauthor")
assert is_trusted(login) is expected
@pytest.mark.parametrize(
"user,expected",
[
pytest.param({"login": "mendral-app[bot]", "type": "Bot"}, True, id="github-app-type"),
pytest.param({"login": "dependabot[bot]", "type": "Bot"}, True, id="dependabot"),
pytest.param({"login": "some-tool[bot]", "type": "User"}, True, id="bot-suffix-misreported-type"),
pytest.param({"login": "posthog-bot", "type": "User"}, True, id="machine-user"),
pytest.param({"login": "POSTHOG-BOT", "type": "User"}, True, id="machine-user-case-insensitive"),
pytest.param({"login": "alice", "type": "User"}, False, id="human"),
pytest.param({}, False, id="missing-user"),
],
)
def test_is_bot_author(user: dict, expected: bool) -> None:
assert is_bot_author(user) is expected
@pytest.mark.parametrize(
"log_output,expected",
[
pytest.param(
"fix: resolve login redirect loop\n\n"
"Generated-By: PostHog Desktop\n"
"Task-Id: a95947d1-6e11-4565-9922-1f857cc6f6fe\n\x1e\n",
CommitProvenance(
commit_count=1,
agent_commit_count=1,
generated_by=("PostHog Desktop",),
task_ids=("a95947d1-6e11-4565-9922-1f857cc6f6fe",),
),
id="single-agent-commit",
),
pytest.param(
"fix: handle empty cohort\n\x1e\nchore: bump deps\n\x1e\n",
CommitProvenance(commit_count=2, agent_commit_count=0, generated_by=(), task_ids=()),
id="human-only-commits",
),
pytest.param(
"feat: add export\n\nGenerated-By: PostHog Desktop\nTask-Id: task-1\n\x1e\n"
"fix: review feedback\n\x1e\n"
"fix: more feedback\n\nGenerated-By: PostHog Desktop\nTask-Id: task-2\n\x1e\n",
CommitProvenance(
commit_count=3,
agent_commit_count=2,
generated_by=("PostHog Desktop",),
task_ids=("task-1", "task-2"),
),
id="mixed-commits-dedupe-generator-collect-task-ids",
),
pytest.param(
"feat(insights): retention export (#71452)\n\n"
"* feat: first pass\n\n"
"Generated-By: PostHog Desktop\n"
"Task-Id: task-1\n\n"
"* fix: address review\n\x1e\n",
CommitProvenance(
commit_count=1, agent_commit_count=1, generated_by=("PostHog Desktop",), task_ids=("task-1",)
),
id="squash-style-message-with-embedded-trailers",
),
pytest.param(
"chore: retry task\n\ngenerated-by: posthog code\ntask-id: task-9\n\x1e\n",
CommitProvenance(
commit_count=1, agent_commit_count=1, generated_by=("posthog code",), task_ids=("task-9",)
),
id="case-insensitive-trailers",
),
pytest.param(
"",
CommitProvenance(commit_count=0, agent_commit_count=0, generated_by=(), task_ids=()),
id="empty-log-output",
),
],
)
def test_parse_provenance_trailers(log_output: str, expected: CommitProvenance) -> None:
# The provenance dimension (agent-authored % of PRs) is derived entirely
# from these trailers — a parsing regression zeroes it silently rather
# than failing anything, so the shapes git actually emits are locked here.
assert parse_provenance_trailers(log_output) == expected
def _worst_case_node_count(query: str) -> int:
# Mirrors GitHub's pre-execution node-limit check: each connection requests
# `first` nodes multiplied by the `first` of every ancestor connection.
total = 0
multipliers = [1]
pending = 1
for match in re.finditer(r"first:\s*(\d+)|[{}]", query):
if match.group(1):
pending = int(match.group(1))
total += multipliers[-1] * pending
elif match.group(0) == "{":
multipliers.append(multipliers[-1] * pending)
pending = 1
else:
multipliers.pop()
return total
def test_review_threads_query_stays_under_github_node_limit() -> None:
# GitHub rejects any GraphQL query whose worst-case node count exceeds
# 500,000 before executing it, which hard-fails the review on every PR.
assert _worst_case_node_count(github._REVIEW_THREADS_QUERY) < 500_000
@pytest.mark.parametrize(
"login,expected_users",
[
pytest.param("stamphog[bot]", ["greptile-apps[bot]"], id="own-inline-comment-excluded"),
pytest.param("github-actions[bot]", ["greptile-apps[bot]"], id="own-approve-identity-excluded"),
pytest.param(
"copilot-pull-request-reviewer[bot]",
["copilot-pull-request-reviewer[bot]", "greptile-apps[bot]"],
id="other-bot-kept",
),
],
)
def test_fetch_threads_excludes_stamphogs_own_inline_comments(
monkeypatch: pytest.MonkeyPatch, login: str, expected_users: list[str]
) -> None:
# Stamphog's earlier verdicts fed back through inline comments read as
# third-party claims about a stale snapshot — later runs then suspect
# impersonation and refuse forever, exactly like stale top-level reviews.
def fake_graphql(query: str, variables: dict | None = None) -> dict:
def comment(user: str) -> dict:
return {
"author": {"login": user, "__typename": "Bot"},
"authorAssociation": "NONE",
"body": f"comment from {user}",
"databaseId": 1,
"replyTo": None,
"reactions": {"nodes": []},
}
return {
"data": {
"repository": {
"pullRequest": {
"reactions": {"nodes": []},
"reviewThreads": {
"pageInfo": {"hasNextPage": False, "endCursor": None},
"nodes": [
{
"isResolved": False,
"isOutdated": False,
"path": "posthog/api/insight.py",
"line": 42,
"comments": {
"pageInfo": {"hasNextPage": False},
"nodes": [comment(login), comment("greptile-apps[bot]")],
},
}
],
},
}
}
}
}
monkeypatch.setattr(github, "_gh_graphql", fake_graphql)
monkeypatch.setattr(github, "_is_org_member", lambda org, member: False)
comments, _ = github._fetch_threads_and_reactions("PostHog/posthog", 1, author="alice")
assert [c["user"] for c in comments] == expected_users