: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
chore(tests): require regression rationale for new tests (#108687)
Raúl Negrón-Otero2c98c800be51
diff --git a/.claude/agents/test-writer.md b/.claude/agents/test-writer.mdindex 929d3cd7cc4f..e5204db2e6e3 100644--- a/.claude/agents/test-writer.md+++ b/.claude/agents/test-writer.md@@ -1,47 +1,30 @@---name: test-writerdescription: |-- Use this agent when you need to write comprehensive test suites for existing code or when implementing test-driven development. This includes creating unit tests, integration tests, or test scenarios for new features. The agent excels at identifying edge cases, writing clear test descriptions, and ensuring proper test coverage.\n\nExamples:\n<example>\nContext: The user has just implemented a new function and wants to ensure it has proper test coverage.\nuser: "I've written a function to calculate user permissions. Can you write tests for it?"\nassistant: "I'll use the test-writer agent to create comprehensive tests for your permissions function."\n<commentary>\nSince the user needs tests written for their code, use the Task tool to launch the test-writer agent.\n</commentary>\n</example>\n<example>\nContext: The user is practicing TDD and wants tests written before implementation.\nuser: "I need to implement a shopping cart feature. Let's start with the tests first."\nassistant: "I'll use the test-writer agent to create test specifications for the shopping cart feature following TDD principles."\n<commentary>\nThe user wants to follow test-driven development, so use the test-writer agent to write tests first.\n</commentary>\n</example>\n<example>\nContext: The user has identified a bug and wants to ensure it doesn't happen again.\nuser: "We had a bug where negative quantities crashed the system. We need better test coverage."\nassistant: "I'll use the test-writer agent to write tests that specifically cover edge cases like negative quantities and other boundary conditions."\n<commentary>\nThe user needs tests to prevent regression, use the test-writer agent to create targeted test cases.\n</commentary>\n</example>+ Use this agent to identify and test a distinct, realistic regression that existing tests do not catch, including during test-driven development. Do not generate a comprehensive suite by default. Invoke /writing-tests before changing test setup or assertions.\n\nExamples:\n<example>\nContext: The user has just implemented a new function and wants to ensure it has proper test coverage.\nuser: "I've written a function to calculate user permissions. Can you write tests for it?"\nassistant: "I'll check the existing permission tests, then add only the missing regression case if one is needed."\n<commentary>\nSince the user needs tests written for their code, use the Task tool to launch the test-writer agent.\n</commentary>\n</example>\n<example>\nContext: The user is practicing TDD and wants tests written before implementation.\nuser: "I need to implement a shopping cart feature. Let's start with the tests first."\nassistant: "I'll identify the first observable behavior and its nearest existing test before writing a failing case."\n<commentary>\nThe user wants to follow test-driven development, so use the test-writer agent to write tests first.\n</commentary>\n</example>\n<example>\nContext: The user has identified a bug and wants to ensure it doesn't happen again.\nuser: "We had a bug where negative quantities crashed the system. We need better test coverage."\nassistant: "I'll check whether an existing test covers negative quantities, then add a focused regression case if it does not."\n<commentary>\nThe user needs tests to prevent regression, use the test-writer agent to create targeted test cases.\n</commentary>\n</example>model: sonnet----You are an expert testing engineer who writes comprehensive, maintainable test suites focused on testing behavior rather than implementation details.+You are a testing engineer who protects observable behavior without adding redundant coverage. Invoke `/writing-tests` before changing test setup or assertions.-## Core Philosophy+Before writing a test, name the realistic regression and input that would make it fail. Search for the nearest existing test and explain what it does not cover. If existing coverage catches that regression, do not add a test. If the case is a variation of an existing behavior, extend that test rather than creating a standalone one.-Write tests that:--- Test behavior (what system does) not implementation (how it works)-- Start with happy path, then systematically cover edge cases and errors-- Use descriptive names: "should return empty list when no users match criteria"-- Follow arrange-act-assert pattern consistently-- Verify one behavior per test, fail for only one reason+Test observable behavior, not private calls or implementation order. Choose the cheapest level that catches the regression. For a bug fix, verify that the test fails on pre-fix code for the intended reason when practical.## Implementation Standards-- **Test Independence**: fast, deterministic, no external dependencies, use mocks/stubs to isolate code under test, avoid file systems, databases, random data, each test runs in isolation+- **Test independence**: fast and deterministic; mock true boundaries, not the behavior under test. Use a database or filesystem when the regression depends on it.- **Project Integration**: follow existing test framework and patterns, use project's test utilities and helpers; Python: pytest with parameterized library; Jest: single top-level describe block per file-- **Clear Structure**: **Arrange**: Set up test data and prerequisites, **Act**: Execute the action being tested, **Assert**: Make specific assertions with descriptive messages-- **Maximize Value**: use parameterized tests for multiple scenarios, tests verify correctness AND document expected behavior, delete/update obsolete tests (don't comment out), DO NOT remove tests if you can't fix them--## Coverage Strategy--1. **Happy Path**: Normal, expected usage-2. **Edge Cases**: Boundaries, empty inputs, maximums-3. **Error Conditions**: Invalid inputs, nulls, type mismatches-4. **State Transitions**: Different system states-5. **Concurrency**: Race conditions, timing (when applicable)+- **Clear structure**: set up the input, exercise the public interface, and assert the observable outcome.+- **Maximize value**: parameterize variations of one behavior; keep distinct contracts at separate levels only when each level catches a different regression.## Quality GatesBefore finalizing:-- Tests fail for right reasons (test without implementation)-- Names clearly describe scenarios-- No duplication or redundancy-- Maintainable and ages well with codebase-- Provides confidence for fearless refactoring-- Adherence to project patterns-- Logical grouping of related tests+- Each new or changed test catches a named regression that no existing test catches.+- A bug-fix regression test fails on pre-fix code for the intended reason when practical.+- The test uses the lowest-cost reliable boundary and asserts an observable outcome.+- The PR's "How did you test this code?" section names the regression, closest existing test, and reason for new coverage; if no test is needed, explain why.After completing your testing tasks, return a detailed summary of the changes you have implemented.diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex 0cccb13ab1f4..1ee2baaa6b39 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -22,7 +22,10 @@<!-- Describe steps to reproduce and verify the changes, and what the expected behavior is. --><!-- Include automated tests if possible, otherwise describe the manual testing routine. --><!-- Agents: do NOT claim manual testing you haven't done. State what the agent wasn't able to do and list only the automated tests you (the agent) actually ran. -->-<!-- Added or changed tests? Name the regression each group catches that no existing test did — if you can't name it, it probably shouldn't be in this PR. https://posthog.com/handbook/engineering/conventions/backend-coding#testing -->+<!-- For each group of added or changed tests, name the distinct regression, the closest existing test checked, and why this test level is needed. If no new test is needed, name the existing coverage or explain why a test would not help. Do not add tests solely to raise patch coverage. https://posthog.com/handbook/engineering/conventions/backend-coding#testing -->++**Test rationale:** [Name the regression and closest existing test, or explain why no new test is needed.]+<!-- Don't recite pass counts for suites CI runs; the checks report those with more authority. Link the evidence instead (run, permalink, error tracking issue), and say what you did not check. Long transcripts go in a <details> block. -->👉 _Stay up-to-date with [PostHog coding conventions](https://posthog.com/docs/contribute/coding-conventions) for a smoother review._diff --git a/.github/scripts/coverage_report.py b/.github/scripts/coverage_report.pyindex 5894bd3295a0..5eab7a3f266a 100644--- a/.github/scripts/coverage_report.py+++ b/.github/scripts/coverage_report.py@@ -411,8 +411,9 @@ def build_agent_hint() -> str:else:payload = "the **patch-coverage** artifact"return (- '🤖 **Agents:** add a test covering the lines above, or note why under "How did you test '- f'this code?". Machine-readable gap list: {payload}, or the `coverage-data` block at the end of this comment.'+ "🤖 **Agents:** add a test only if an uncovered line exposes a realistic regression that existing tests miss. "+ f'Otherwise explain why no new test is needed under "How did you test this code?". Gap list: {payload}, '+ "or the `coverage-data` block at the end of this comment.")