Inferensys

Prompt

Test Coverage Gap from Diff Prompt

A practical prompt playbook for using Test Coverage Gap from Diff Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Identify untested logic paths, missing edge cases, and regression risks in a code diff by reasoning over existing test files.

This prompt is designed for QA engineers and developers who need to identify untested logic paths, missing edge cases, and regression risks before merging a pull request. It takes a code diff and the content of existing test files as input and produces a prioritized list of recommended new test cases. Use this prompt in CI/CD pipelines as a pre-merge gate, during manual code review to guide testing effort, or as part of a test planning workflow.

This prompt does not execute tests or measure code coverage metrics; it performs a static reasoning pass over the diff and existing tests to surface gaps that a coverage tool might miss, such as missing assertions for side effects, unvalidated error branches, and boundary conditions. The ideal input includes the full unified diff of the proposed changes and the relevant test file contents. For best results, provide the test files that correspond to the modified source files, not the entire test suite. The prompt works best with diffs under 2,000 lines; for larger changes, split the diff by module or component and run the prompt separately for each.

Do not use this prompt as a replacement for dynamic coverage instrumentation or mutation testing. It cannot detect gaps that require runtime profiling, such as race conditions that only manifest under load or integration paths that span multiple services. It also cannot verify that existing tests actually assert the correct behavior—only that they appear to exercise a code path. For high-risk changes, always pair this prompt's output with actual coverage reports and a manual review of test assertion quality. The prompt's recommendations are starting points for test authoring, not a certified safety net.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Test Coverage Gap from Diff Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your workflow before integrating it into a CI/CD pipeline.

01

Good Fit: Pre-Merge QA Gate

Use when: A pull request modifies core logic and you need to identify untested paths before merging. The prompt excels at comparing the diff against existing test files to surface missing edge cases. Guardrail: Run this as a non-blocking advisory check in CI. Always require a QA engineer to confirm the suggested gaps are real before writing new tests.

02

Bad Fit: Greenfield Projects Without Tests

Avoid when: The repository has no existing test suite or test patterns. The prompt relies on analyzing existing test files to detect gaps; without a baseline, it will hallucinate coverage expectations or produce generic, unactionable suggestions. Guardrail: Gate execution behind a check that at least one test file exists in the changed module's directory tree.

03

Required Input: Diff Plus Test Context

Risk: Feeding only a diff without the corresponding test files forces the model to guess what is already covered, leading to false positives and wasted engineering time. Guardrail: Always include the full content of relevant test files alongside the diff. Use a script to automatically bundle test files from the same module or package as the changed source files.

04

Operational Risk: Over-Prioritization of Trivial Gaps

Risk: The model may flag missing tests for getters, setters, or logging statements with the same urgency as untested critical business logic, overwhelming the team. Guardrail: Add a severity constraint in the prompt to classify gaps as 'Critical', 'Advisory', or 'Low' based on logic complexity. Filter the output to show only Critical and Advisory items in the PR comment.

05

Operational Risk: Stale Test Assumptions

Risk: If the provided test files are from an outdated branch, the model will identify gaps that have already been filled, eroding trust in the automation. Guardrail: Always pull test file content from the same commit SHA as the diff. Integrate this check into your CI workflow so the prompt context is always branch-consistent.

06

Bad Fit: Complex Integration or E2E Scenarios

Avoid when: The primary testing gap involves multi-service interactions, database state, or asynchronous workflows. The prompt analyzes unit-level logic paths and will miss gaps that only manifest at the integration layer. Guardrail: Use this prompt only for unit and module-level gap analysis. Pair it with a separate integration test coverage tool for end-to-end paths.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that analyzes a code diff against existing test files to identify untested logic paths and recommend new test cases.

This prompt template is the core instruction set for the Test Coverage Gap from Diff workflow. It is designed to be pasted into your prompt layer, wired into a CI/CD pipeline, or used in a manual review tool. The template forces the model to reason about what changed, what is tested, and what remains exposed. Replace each square-bracket placeholder with the actual diff, test files, and output constraints before execution. The prompt is structured to produce a machine-readable JSON report, making it suitable for automated ingestion by test generation tools or QA dashboards.

text
You are a QA automation engineer reviewing a code change. Your task is to analyze the provided code diff against the existing test files and identify untested logic paths, missing edge cases, and regression risks.

## INPUT
- Code Diff: [CODE_DIFF]
- Existing Test Files: [TEST_FILES]
- Change Context (optional): [CHANGE_CONTEXT]

## CONSTRAINTS
- Only flag logic paths that are introduced or modified by the diff.
- Do not flag pre-existing untested code unless the diff makes it riskier.
- For each finding, reference the specific file and line range from the diff.
- If a risk is high-severity (potential data loss, security, crash), mark it as `severity: critical`.
- If the existing tests already cover a path, do not include it.

## OUTPUT_SCHEMA
Return a single JSON object with the following structure:
{
  "summary": "string (1-2 sentence overview of coverage gaps found)",
  "gaps": [
    {
      "id": "string (unique gap identifier, e.g., GAP-001)",
      "file": "string (file path from diff)",
      "lines": "string (line range, e.g., L45-L52)",
      "untested_logic": "string (description of the untested path or condition)",
      "risk": "string (severity: critical | high | medium | low)",
      "suggested_test": "string (description of a specific test case to add)",
      "existing_coverage_note": "string (why existing tests miss this, referencing specific test files if possible)"
    }
  ],
  "regression_risks": [
    {
      "area": "string (affected component or feature)",
      "risk_description": "string (what could break and how)",
      "related_gap_ids": ["string (list of gap IDs contributing to this risk)"]
    }
  ]
}

## INSTRUCTIONS
1. Parse the diff to identify all added or modified logic branches, conditions, loops, and exception handlers.
2. Cross-reference each identified logic path against the provided test files. Look for direct coverage and edge-case coverage.
3. For any path without adequate coverage, create a gap entry with a clear description and a concrete, implementable test suggestion.
4. Group related gaps into regression risk entries where multiple untested paths could interact to cause a failure.
5. If no gaps are found, return an empty gaps array and a summary stating that existing tests appear to cover the change.
6. Do not hallucinate test files or coverage that is not provided in the input.

After pasting this template, the primary adaptation points are the [CODE_DIFF] and [TEST_FILES] placeholders. The diff should be a unified diff format for best results. The test files should include the full content of relevant test suites, not just file names. If your test suite is large, pre-filter to files that import or reference the changed modules to keep context within token limits. The [CHANGE_CONTEXT] placeholder is optional but recommended for complex changes—use it to provide the PR description, linked issue, or developer intent. The output schema is designed for direct parsing; validate the JSON structure before forwarding results to your test generation pipeline. For high-risk repositories, always route severity: critical findings to a human QA lead for confirmation before acting on them.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Test Coverage Gap from Diff Prompt. Each variable must be supplied at runtime or configured in the harness. Missing or malformed inputs are the most common cause of low-quality output.

PlaceholderPurposeExampleValidation Notes

[DIFF]

The unified diff or code change to analyze for test coverage gaps

git diff main...feature-branch

Must be non-empty text. Validate line count > 0. Reject binary diffs. Truncate if > 50k characters and log warning.

[EXISTING_TESTS]

Current test files, test suite listing, or coverage report for the affected code paths

pytest --collect-only output or directory listing of test/unit/*.py

Must be non-empty. If null, prompt should still run but output must flag 'no test context provided' and reduce confidence. Validate format matches expected test framework.

[LANGUAGE]

Programming language of the diff to guide test framework and pattern recommendations

python

Must match a supported language list: python, javascript, typescript, java, go, rust, ruby, csharp. Reject unsupported values with clear error message.

[TEST_FRAMEWORK]

Target test framework for generating test case syntax

pytest

Must be a recognized framework for [LANGUAGE]. If null, prompt should infer from [EXISTING_TESTS] or default to the most common framework for [LANGUAGE].

[COVERAGE_THRESHOLD]

Minimum coverage percentage or risk tolerance level for prioritization

80

Must be integer 0-100 or one of: low, medium, high. If null, default to medium. Controls how aggressively the prompt flags borderline gaps.

[RISK_CONTEXT]

Optional deployment context or criticality level to weight gap severity

payment-processing-module

Free text. If null, prompt should assume moderate risk and note that risk weighting is default. Max 500 characters. Used to elevate gaps in high-risk paths.

[OUTPUT_FORMAT]

Desired output structure for downstream ingestion

json

Must be one of: json, markdown, sarif. If null, default to json. Controls schema applied to output validation. SARIF requires line-number mapping from diff.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Test Coverage Gap from Diff Prompt into a CI/CD pipeline or local pre-commit workflow with validation, retries, and human review gates.

The Test Coverage Gap from Diff Prompt is designed to be called programmatically as a step in your CI/CD pipeline, typically after a pull request is opened and the diff is available but before the change is merged. The harness must supply the raw unified diff as [DIFF] and the relevant test file contents as [TEST_CONTEXT]. The model returns a structured JSON payload containing a list of recommended test cases, each with a target logic path, suggested test name, and a risk priority. This output should be validated against a defined JSON schema before being posted as a comment on the PR or surfaced in your review dashboard.

To implement this, wrap the prompt call in a script that first extracts the diff from git diff origin/main...HEAD and gathers test files matching the changed source paths. The prompt should be sent to a capable model like claude-sonnet-4-20250514 or gpt-4o with response_format set to json_schema matching your expected output structure. Implement a retry loop with exponential backoff for transient API failures, but limit to three attempts. After receiving the response, run a strict validator that checks: (1) the JSON parses correctly, (2) each recommended test case has a non-empty logic_path, test_name, and priority field, and (3) priority values are within the allowed enum [CRITICAL, HIGH, MEDIUM, LOW]. If validation fails, append the validation errors to the prompt context and retry once. For high-risk repositories (e.g., payments, auth, safety-critical systems), always require a human to approve or dismiss each finding before the PR can be merged—this is not a replacement for human QA judgment.

Log every prompt call, response, and validation result to your observability stack with the PR ID, commit SHA, and model version as metadata. This enables trace analysis when a gap is missed and a regression reaches production. Avoid running this prompt on diffs larger than 10,000 lines without chunking by file or module; large diffs dilute the model's attention and produce lower-quality gap analysis. If the diff is too large, split it by changed module and run the prompt per module, then merge and deduplicate the results. The next step after implementing this harness is to build a regression test suite that measures the prompt's recall against known historical regressions where a test gap was the root cause.

IMPLEMENTATION TABLE

Expected Output Contract

The model must return a structured JSON object. Validate each field before ingesting the response into a test generation pipeline or QA dashboard.

Field or ElementType or FormatRequiredValidation Rule

test_recommendations

Array of objects

Must be a non-empty array. Reject if empty or not present.

test_recommendations[].id

String (kebab-case)

Must match pattern ^[a-z]+(-[a-z]+)*$. Reject on collision within the array.

test_recommendations[].title

String

Length must be between 10 and 120 characters. Must not be a duplicate of another title in the array.

test_recommendations[].priority

Enum: critical, high, medium, low

Must be one of the four allowed values. Reject any other string.

test_recommendations[].gap_type

Enum: missing_unit_test, missing_integration_test, missing_edge_case, missing_regression_test

Must be one of the four allowed values. Reject if type does not match a gap described in the diff analysis.

test_recommendations[].affected_code

Array of strings

Each string must reference a function name, method, or class present in the provided [DIFF]. Reject if any reference is hallucinated.

test_recommendations[].suggested_test_logic

String

Must be a non-empty string describing the test setup, execution, and assertion. Length must be between 20 and 500 characters.

test_recommendations[].existing_coverage_note

String or null

If null, no existing test was found. If a string, it must reference a specific test file or suite name from the provided [TEST_SUITE_CONTEXT].

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using a prompt to detect test coverage gaps from a diff, and how to guard against it.

01

Hallucinated Test Paths

What to watch: The model invents plausible but non-existent functions, modules, or edge cases that look like real test recommendations. Guardrail: Require the output to map every recommended test to a specific line range in the diff. Validate that referenced symbols exist in the codebase.

02

Ignoring Existing Coverage

What to watch: The prompt recommends tests for logic that is already covered by existing test files not visible in the diff context. Guardrail: Always provide the relevant existing test files as part of the input context. Add an explicit instruction to cross-reference recommendations against provided test files and exclude already-covered paths.

03

Missing Implicit Edge Cases

What to watch: The model focuses only on the happy path and explicit conditionals in the diff, missing null inputs, empty collections, boundary values, or type coercion edge cases. Guardrail: Include a checklist of edge-case categories (null, empty, boundary, type mismatch) in the prompt's [CONSTRAINTS] and require the output to address each category explicitly.

04

Context Window Truncation

What to watch: Large diffs or extensive test files exceed the context window, causing the model to silently drop critical code sections and produce incomplete analysis. Guardrail: Implement a pre-processing step that chunks the diff by module or file. Run the prompt per-chunk and merge results. Add a token-count check before calling the model.

05

Vague or Non-Actionable Suggestions

What to watch: The output contains generic advice like 'add more tests' or 'test edge cases' without specific inputs, expected outputs, or setup steps. Guardrail: Enforce a strict [OUTPUT_SCHEMA] that requires each recommendation to include: test name, specific input values, expected behavior, and the diff line range it targets. Validate the schema on every response.

06

Misidentifying Test vs. Production Code

What to watch: The model confuses test files for production code or vice versa, leading to recommendations to test the test framework itself. Guardrail: Explicitly label file paths as 'source' or 'test' in the input context. Add a constraint to only recommend tests for source files and to ignore changes within test directories.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Test Coverage Gap from Diff Prompt output before integrating it into a CI/CD pipeline or QA workflow. Each criterion targets a specific failure mode common to coverage gap analysis.

CriterionPass StandardFailure SignalTest Method

Gap-to-Code Traceability

Every recommended test case references a specific file path and function or logical block from the [DIFF].

Recommendations are generic ('add more tests for the API') without linking to a changed code location.

Parse output for code_reference fields. Assert all references exist in the [DIFF] using a substring match.

Existing Test Collision Check

No recommended test case duplicates an existing test case found in the provided [EXISTING_TESTS].

Output suggests testing a function or scenario that already has an explicit test case in the provided context.

Embed output test descriptions and existing test descriptions. Compute cosine similarity; flag pairs above a 0.85 threshold for manual review.

Edge Case Coverage

At least 70% of recommended test cases target boundary conditions, null/empty inputs, or exception paths, not just happy paths.

All recommendations are for standard positive test cases (e.g., 'test that it returns 200').

Classify each recommendation as happy_path or edge_case using a secondary LLM call. Assert edge_case ratio >= 0.7.

Regression Risk Prioritization

Each finding includes a risk_level field (high/medium/low) and the top 3 items are high-risk.

All findings are marked medium or the ordering appears random without a clear risk rationale.

Validate risk_level is an enum. Assert output[:3].risk_level == 'high'. Manually review if the top 3 are not related to auth, data mutation, or critical path changes.

Output Schema Validity

The output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and non-null.

JSON parsing fails, required fields like test_name or rationale are missing, or fields contain the wrong type.

Validate against the JSON Schema using a standard library (e.g., jsonschema in Python). Reject on failure.

Actionable Test Logic

Each recommendation includes a concrete assertion or verification step, not just a vague test title.

The test_logic field contains only a title like 'Test error handling' without specifying the input or expected outcome.

Check len(test_logic) > 50 characters and that it contains a verb phrase indicating a specific check (e.g., 'assert', 'verify', 'check').

No Hallucinated Dependencies

The output does not invent library functions, API endpoints, or file paths not present in the [DIFF] or [CODEBASE_CONTEXT].

A recommendation suggests testing a function or module that does not exist in the provided context.

Extract all code references. For each, grep the [DIFF] and [CODEBASE_CONTEXT]. Flag any reference with zero matches for human review.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single diff file. Skip the test file context initially—just ask the model to infer what tests should exist from the code changes. Use a simple markdown output format instead of strict JSON.

code
Analyze this diff and list the top 5 missing test cases:

[DIFF]

Watch for

  • The model will hallucinate test file names it hasn't seen
  • Edge case suggestions will be generic ("test null input") without code-specific detail
  • No severity ranking—you'll need to triage manually
  • No validation that suggested tests actually cover the changed lines
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.