We are designing a system that uses LLMs (Large Language Models) and static analysis to generate test cases for code. The system should include:
- Prompt design for the LLM to generate test cases.
- Verification of the generated test cases (ensuring they are valid and meaningful).
- Deduplication (avoiding redundant test cases).
- Integration into a developer workflow (how developers use and interact with the system).
Steps:
-
Prompt Design:
- We need to provide the LLM with context about the code under test (function/method, class, etc.) and ask for test cases.
- The prompt should include:
- The code snippet (function/method, class, etc.) to be tested.
- The programming language and any relevant frameworks (e.g., JUnit for Java, pytest for Python).
- Instructions to generate test cases that cover edge cases, typical use cases, and error conditions.
- Format of the output (e.g., a list of test functions with assertions, or a structured format like JSON).
Example prompt for a Python function:
You are an expert software tester. Given the following Python function, write a set of unit test cases using pytest that cover:
- Typical input-output scenarios.
- Edge cases (empty input, large input, boundary values, etc.).
- Error conditions (invalid input types, out-of-range values, etc.).
Code:
def factorial(n: int) -> int:
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
result = 1
for i in range(1, n+1):
result *= i
return result
Output format: List of test function names and their corresponding test code (as strings). Each test should be independent and use assertions.
Example test function:
def test_factorial_zero():
assert factorial(0) == 1
Generate 5-10 test cases.
-
Verification:
- After generating test cases, we need to verify that they are correct and that they actually test the intended behavior.
- We can use static analysis to:
a) Check syntax of the generated test code.
b) Ensure that the test cases are using the correct API (e.g., the function name, parameters, and assertions are valid for the given framework).
c) Optionally, we can run the test cases on the original code (if the code is available and we have an environment) to see if they pass or fail as expected.
- However, note that we are generating test cases for a given code snippet, and we might not have the entire project context. So, we rely on static analysis of the test code and the original code to ensure consistency.
Steps for verification:
a) Parse the generated test code and the original code with a parser for the language (e.g., ast for Python, javaparser for Java).
b) Check that all function calls in the test code refer to existing functions in the original code (or in the test's context, if we are generating tests for a module that might have imports).
c) Check that the assertions are using the correct comparison operators and that the expected values are of the correct type.
d) If the original code has type annotations (like in the example), we can check that the test cases are providing arguments of the correct type.
-
Deduplication:
- The LLM might generate test cases that are very similar or even identical.
- We can use a combination of techniques:
a) Compare the test code strings (after normalizing whitespace and comments) for exact duplicates.
b) Use semantic equivalence: two test cases might be different in code but test the same condition. This is harder. We can try to use static analysis to extract the conditions being tested (e.g., the input values and the expected output) and then group by these conditions.
c) For simplicity, we might start with string-based deduplication and then consider more advanced techniques if needed.
-
Developer Workflow:
- How does the developer use this tool?
- We can imagine a few ways:
a) A command-line tool that takes a file (or a code snippet) and outputs a set of test cases.
b) An IDE plugin that allows the developer to select a function and generate tests.
c) A web interface where the developer pastes code and gets test cases.
Proposed workflow:
- Developer writes code (a function, method, or class) and wants to generate tests.
- Developer runs the tool (via CLI, IDE, or web) and provides the code snippet and optionally the surrounding context (imports, class definition, etc.).
- The tool constructs a prompt and sends it to the LLM.
- The LLM returns a set of test cases.
- The tool verifies and deduplicates the test cases.
- The tool returns the cleaned test cases to the developer.
- The developer reviews, adjusts, and integrates the tests into their test suite.
We should also allow the developer to specify:
- The testing framework (pytest, unittest, JUnit, etc.)
- The number of test cases.
- Any specific scenarios to focus on (e.g., "focus on boundary conditions").
Implementation Plan:
We'll break the system into modules:
- Prompt Builder: Takes the code snippet, language, framework, and any user specifications and builds the prompt.
- LLM Client: Sends the prompt to the LLM and gets the response.
- Test Parser: Parses the LLM response into individual test cases (as code strings).
- Verifier: Uses static analysis to verify each test case (syntax, API usage, type consistency).
- Deduplicator: Removes duplicate test cases (by string and/or by semantic conditions).
- Output Formatter: Formats the final set of test cases for the developer (e.g., as a code block, or as a file).
We also need to handle errors and edge cases in the LLM response (like the LLM generating non-test code, or generating tests in the wrong format).
Let's design a simple version for Python with pytest.
Steps in code:
Step 1: Prompt Builder for Python function.
Step 2: LLM call (we can use an API like OpenAI's GPT, or a local model).
Step 3: Parse the response. The LLM is instructed to output test functions as code blocks. We can extract by looking for "def test_..." or by using a code block marker if we instruct the LLM to use markdown.
Step 4: For each test function string:
- Parse with ast.parse to check syntax.
- Check that the function name starts with "test_" (or whatever convention the framework uses).
- Check that the function calls the target function (by name) with the correct number of arguments (if we can infer from the original function's signature).
- Check that the assertions are using the correct form (e.g., assert statements).
Step 5: Deduplication:
- We can compute a hash of the test code after removing comments and normalizing whitespace.
- Alternatively, we can extract the set of inputs and expected outputs and compare. But note that two tests might have the same input but different assertions? That would be a different test. So we compare the entire test code.
Step 6: Output the list of test cases.
However, note that the LLM might generate tests that are not independent (e.g., using a global state). We can also check for that by looking for imports and global variables, but that's more advanced.
Let's write a simple version for the example function.
We assume the LLM returns:
def test_factorial_zero():
assert factorial(0) == 1
def test_factorial_one():
assert factorial(1) == 1
def test_factorial_positive():
assert factorial(5) == 120
def test_factorial_negative():
with pytest.raises(ValueError):
factorial(-1)
But note: the LLM might generate tests that use pytest but we didn't specify. We should include in the prompt to use the specified framework.
Let's design the prompt to be flexible for different frameworks.
For the example, we'll use pytest.
We can have a template for the prompt:
You are an expert software tester. Given the following {language} code, write a set of unit test cases using {framework} that cover:
- Typical input-output scenarios.
- Edge cases (empty input, large input, boundary values, etc.).
- Error conditions (invalid input types, out-of-range values, etc.).
Code:
{code}
Output format: List of test function names and their corresponding test code (as strings). Each test should be independent and use assertions.
Example test function for {framework}:
{example_test}
Generate {num_tests} test cases.
We can fill in the example_test based on the framework.
For pytest, example_test:
"def test_function_name():\n assert function_name(arg1, arg2) == expected"
For JUnit (Java), it would be different.
We'll start with Python and pytest.
Implementation:
We'll write a class TestGenerator that has:
__init__(self, llm_client, framework='pytest', language='python')
generate_tests(self, code, num_tests=5, focus=None)
Steps in generate_tests:
- Build prompt.
- Call LLM.
- Parse response into test code strings.
- Verify each test.
- Deduplicate.
- Return list of test code strings.
Verification for pytest tests:
We can write a function verify_pytest_test(test_code, original_function_name, original_signature):
- Parse the test_code with ast.
- Check that there is a function definition with a name starting with 'test_'.
- Check that inside the function, there is at least one call to `original_function_name` (or if the function is imported, we might have a different name? We assume the test is in the same module and the function is in the global scope. This is a simplification.)
But note: the test might import the function from a module. We don't have the full context. So we might skip the check for the function call if we cannot resolve the import. Alternatively, we can require that the code provided includes the necessary imports.
For simplicity, we assume the code snippet is self-contained (including imports) and the test code will be run in the same context.
So we can check:
- The test code must be syntactically valid.
- The test function must have the correct name pattern.
- The test function must call the target function (by name) at least once? Not necessarily, but if it doesn't then it's not testing the function. So we require at least one call to the target function.
However, what if the test is for a class method? Then we need to check for method calls on an instance. This gets complex.
Given the complexity, we might limit to functions for now.
Alternatively, we can do:
- Extract the function name from the provided code (if it's a function definition). Then in the test code, look for calls to that function name.
For the example, we have factorial. We look for factorial( in the test code.
But note: the test might use an alias? We don't handle that.
Let's keep it simple: we look for the exact function name in the test code.
Steps for verification:
def verify_test(test_code, target_function_name):
try:
tree = ast.parse(test_code)
except SyntaxError:
return False
# Find all function definitions in the test code.
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
# Check that this function body contains a call to the target function.
call_found = False
for subnode in ast.walk(node):
if isinstance(subnode, ast.Call):
# Check if the called function's name matches target_function_name.
if isinstance(subnode.func, ast.Name) and subnode.func.id == target_function_name:
call_found = True
if not call_found:
return False
return True
But note: the test code might have multiple test functions. We want to verify each one.
So we split the test code by function definitions? Actually, the LLM might generate multiple test functions in one code block. We want to split them and verify each.
Alternatively, we can parse the entire test_code and then check each function definition that starts with 'test_'.
However, what if the test code has helper functions that don't start with 'test_'? We ignore those.
But what if the test function is defined inside a class? Then we need to look for methods in a class. For pytest, test classes are also allowed (with class names starting with Test). We don't handle that in this simple version.
Given the time, let's stick to function-style tests.
Deduplication:
We can compute a hash of the normalized test code for each test function and then remove duplicates.
Normalization: remove comments, extra whitespace.
We can do:
def normalize_test_code(test_code):
# Remove comments and docstrings? We can use ast to get the code without comments? Or just string operations.
# Alternatively, we can use the ast to unparse (if available) but that might change formatting.
# For simplicity, we remove single-line comments and multi-line strings that are not docstrings? This is tricky.
# Instead, we can use the ast to get the structure and then generate a canonical string? That's complex.
# Let's do a simple normalization: remove all comments (lines starting with #) and then strip each line and remove empty lines.
lines = []
for line in test_code.split('\n'):
# Remove inline comments? We can split by '#' and take the first part.
line = line.split('#')[0].rstrip()
if line:
lines.append(line)
return '\n'.join(lines)
Then hash that.
But note: two tests that are logically the same might have different variable names? We don't handle that.
We are only doing string-based deduplication.
Finally, we return the list of test code strings (each being a test function or a set of test functions?).
Actually, the LLM might return multiple test functions in one response. We want to split them and then deduplicate and verify each.
How to split? We can look for function definitions that start with 'test_'. But note that the LLM might output:
def test_1():
...
def test_2():
...
So we can split by def test_ and then add back the def test_ to each part.
But what if there's a helper function? We don't want to split helper functions. We can look for the pattern of a function definition that starts with 'test_' and then take until the next function definition at the same indentation level.
Alternatively, we can parse the entire code and extract all function definitions that start with 'test_'.
Let's do:
tree = ast.parse(test_code)
test_functions = []
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
# Extract the source code for this function.
# We can use ast.get_source_segment if we have the original source, but we have the test_code string.
# We can use the line numbers: node.lineno and node.end_lineno.
lines = test_code.split('\n')
function_lines = lines[node.lineno-1:node.end_lineno]
test_functions.append('\n'.join(function_lines))
Then we verify and deduplicate on these individual test functions.
But note: the test_code might have a class with test methods. We don't handle that.
Given the complexity, we might assume the LLM generates only function-style tests.
Let's adjust the prompt to only generate function-style tests.
So, in the prompt we say: "Write each test as a separate function that starts with 'test_'."
Then we can split by def test_ and then reconstruct.
Alternatively, we can split by the pattern:
pattern = r'(?=def test_)'
But that would split before each test function, and we lose the first one. We can do:
test_functions = []
current = []
for line in test_code.split('\n'):
if line.startswith('def test_') and current:
test_functions.append('\n'.join(current))
current = [line]
else:
current.append(line)
if current:
test_functions.append('\n'.join(current))
But this doesn't handle indentation. What if the test function is inside a class? We said we don't handle that.
So we assume no classes.
Alternatively, we can use the ast method and only look for top-level function definitions.
Let's do:
tree = ast.parse(test_code)
test_functions = []
for node in tree.body:
if isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
# We assume the entire function is in the node, so we can get the source by line numbers.
lines = test_code.split('\n')
function_lines = lines[node.lineno-1:node.end_lineno]
test_functions.append('\n'.join(function_lines))
This will only get top-level functions.
Now, we verify each test function in test_functions.
Then we deduplicate by normalizing and hashing.
Finally, we return the list of test function code strings.
But what about the imports? The test code might have imports at the top. We are splitting by function, so we lose the imports.
We need to keep the imports. So we should not split the test code into separate functions? Instead, we can keep the entire test code as one string and then verify and deduplicate by test function? But then deduplication would be on the entire test file? That's not what we want.
Alternatively, we can extract the test functions and then when we output, we output all the test functions together with the necessary imports.
How to get the imports? We can extract all top-level import statements and then prepend them to each test function? But then we might duplicate imports.
Alternatively, we can output the entire test code (with all test functions and the necessary imports) and then deduplicate by test function? But then if two test functions are the same but in different files, we only want one.
We are generating test cases for one function. So we want a set of test functions for that function.
We can do:
Step 1: Parse the entire test_code string and extract:
- All top-level imports (and maybe from ... import ...)
- All test functions (top-level functions starting with 'test_').
Step 2: For deduplication, we only deduplicate the test functions (without the imports). Then when we output, we output the imports once and then all the unique test functions.
But note: two test functions might be the same but use different imports? We assume the imports are the same for all test functions. So we take the imports from the first test code block? Actually, the LLM might generate different imports for different test functions? We hope not.
We can extract the imports from the entire response and then use them for all test functions.
Alternatively, we can group by the set of imports? That's complex.
Let's assume the LLM generates a consistent set of imports for all test functions. We take the imports from the first test function's file (the entire response) and then use that for all.
So:
entire_test_code = llm_response
tree = ast.parse(entire_test_code)
imports = []
test_functions = []
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
imports.append(ast.get_source_segment(entire_test_code, node))
elif isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
test_functions.append(ast.get_source_segment(entire_test_code, node))
Then we deduplicate the test_functions.
Then we output:
'\n'.join(imports) + '\n\n' + '\n\n'.join(unique_test_functions)
But note: the imports might be interspersed with other code (like helper functions). We only take the top-level imports and hope that the test functions don't require any other top-level code.
This is getting complex.
Given the time, let's simplify:
We'll assume the LLM generates only test functions (and the necessary imports at the top). We'll extract the entire code, then split by test function (using the ast method for top-level functions) and then deduplicate the test functions. Then we'll take the imports from the entire code (by taking all the import statements at the top until the first function definition) and then append the deduplicated test functions.
How to get the imports at the top? We can take all the nodes before the first function definition (or any non-import, non-docstring node). But note there might be comments and blank lines.
Alternatively, we can take the entire code and remove the test functions, then what's left should be the imports and maybe other code (like helper functions). We don't want helper functions? We might.
Given the complexity, let's assume the LLM generates only test functions and the necessary imports. We'll take the entire code and then split the test functions. Then we'll remove the test functions from the original code to get the "header" (imports and maybe other code). Then we output the header and then the deduplicated test functions.
Steps:
entire_code = llm_response
tree = ast.parse(entire_code)
imports_and_header = []
test_functions = []
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
imports_and_header.append(ast.get_source_segment(entire_code, node))
elif isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
test_functions.append(ast.get_source_segment(entire_code, node))
else:
# If there's a non-import, non-test function node, we also include it in the header?
# But note: there might be helper functions. We want to keep them.
imports_and_header.append(ast.get_source_segment(entire_code, node))
Then we deduplicate test_functions.
Then output:
header = '\n'.join(imports_and_header)
tests = '\n\n'.join(unique_test_functions)
final_output = header + '\n\n' + tests
But wait, we are including non-test, non-import nodes in the header. That might be helper functions. We want to keep them.
However, when we deduplicate, we are only deduplicating the test functions. The helper functions are kept once (in the header). But what if the same helper function is defined multiple times? We don't deduplicate that.
This is acceptable.
Now, we need to verify each test function.
Verification function for a single test function (string):
def verify_test_function(test_function_code, target_function_name):
try:
tree = ast.parse(test_function_code)
except SyntaxError:
return False
# Check that the function name starts with 'test_'
func_def = tree.body[0]
if not isinstance(func_def, ast.FunctionDef) or not func_def.name.startswith('test_'):
return False
# Check that the function body contains a call to target_function_name.
call_found = False
for node in ast.walk(func_def):
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id == target_function_name:
call_found = True
return call_found
But note: the test function might call the target function via an alias? We don't handle that.
Also, the target function might be a method of a class? We don't handle that.
We are only handling simple functions.
Given the constraints, we'll proceed with this.
Now, let's code accordingly.
However, note: the LLM might generate test functions that are not in the same module? For example, if the target function is my_module.factorial, then the test might call my_module.factorial. We are only checking for the name factorial. We can adjust the prompt to not use module prefixes? Or we can extract the function name from the code.
How to get the target function name?
We are given a code snippet. We assume the code snippet defines a function. We can parse the code and get the function name.
Steps:
original_tree = ast.parse(code)
# Find the first function definition? Or we can let the user specify the function name?
# We can also support class methods, but for now, let's assume the code defines a function.
function_name = None
for node in original_tree.body:
if isinstance(node, ast.FunctionDef):
function_name = node.name
break
If we don't find a function, we can look for a class and then a method? But let's not.
So we require that the code snippet contains exactly one function definition? Or we take the first one.
Alternatively, we can have the user specify the function name.
For simplicity, we'll take the first function definition in the code.
Now, what if the code defines multiple functions? We are generating tests for which one? We can generate tests for each? That might be too much.
We'll change the prompt to say: "Given the function <function_name> ..." but we don't know the function name? We can extract it.
Alternatively, we can ask the user to provide the function name.
Let's change the design: the user provides a code snippet and the function name (or we try to extract it). We'll try to extract the first function.
But note: the code might be a class with methods. We don't handle that.
We'll limit to single function.
Steps:
1. Parse the provided code and get the first function name.
2. Build the prompt with that function name and the code.
3. In verification, we check for calls to that function name.
But what if the function is inside a class? Then the call would be on an instance. We don't handle that.
Given the time, we'll stick to top-level functions.
Let's code accordingly.
We'll write the following functions:
def extract_function_name(code):
tree = ast.parse(code)
for node in tree.body:
if isinstance(node, ast.FunctionDef):
return node.name
return None
def build_prompt(code, language='python', framework='pytest', num_tests=5, example_test=None):
if example_test is None:
if framework == 'pytest':
example_test = "def test_function_name():\n assert function_name(arg) == expected"
else:
# Default example
example_test = "def test_function_name():\n assert function_name(arg) == expected"
function_name = extract_function_name(code)
if function_name is None:
raise ValueError("No function found in the provided code.")
prompt = f"""
You are an expert software tester. Given the following {language} code, write a set of unit test cases using {framework} that cover:
- Typical input-output scenarios.
- Edge cases (empty input, large input, boundary values, etc.).
- Error conditions (invalid input types, out-of-range values, etc.).
Code:
{code}
Output format: List of test function names and their corresponding test code (as strings). Each test should be independent and use assertions.
Example test function for {framework}:
{example_test}
Generate {num_tests} test cases.
"""
return prompt, function_name
def parse_llm_response(response):
# We assume the response is a code block with multiple test functions.
# We parse with ast and extract the top-level test functions and the imports.
try:
tree = ast.parse(response)
except SyntaxError:
# Maybe the response is not entirely valid Python? We can try to extract code blocks.
# We'll assume the response is a code block and try to parse it.
# If it fails, return empty.
return [], []
imports_and_header = []
test_functions = []
for node in tree.body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
imports_and_header.append(ast.get_source_segment(response, node))
elif isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
test_functions.append(ast.get_source_segment(response, node))
else:
# Keep other top-level nodes (like helper functions) in the header.
imports_and_header.append(ast.get_source_segment(response, node))
return imports_and_header, test_functions
def verify_test_functions(test_functions, target_function_name):
verified = []
for test_func in test_functions:
if verify_test_function(test_func, target_function_name):
verified.append(test_func)
return verified
def deduplicate_test_functions(test_functions):
normalized = [normalize_test_code(tf) for tf in test_functions]
seen = set()
unique = []
for i, norm in enumerate(normalized):
if norm not in seen:
seen.add(norm)
unique.append(test_functions[i])
return unique
def normalize_test_code(test_code):
# Remove comments and extra whitespace.
lines = []
for line in test_code.split('\n'):
# Remove inline comments
line = line.split('#')[0].rstrip()
if line:
lines.append(line)
return '\n'.join(lines)
def generate_tests(code, llm_client, num_tests=5, framework='pytest'):
prompt, function_name = build_prompt(code, framework=framework, num_tests=num_tests)
response = llm_client.generate(prompt) # This is a placeholder for the actual LLM call.
imports_and_header, test_functions = parse_llm_response(response)
verified_test_functions = verify_test_functions(test_functions, function_name)
unique_test_functions = deduplicate_test_functions(verified_test_functions)
# Combine the header and the unique test functions.
header = '\n'.join(imports_and_header)
tests = '\n\n'.join(unique_test_functions)
if header and tests:
return header + '\n\n' + tests
elif header:
return header
else:
return tests
This is a simplified version.
We assume the LLM response is a single code block with multiple test functions and possibly imports and helper functions.
However, note: the LLM might return the tests in a markdown code block. We need to extract the code from the markdown. We can adjust the prompt to not use markdown? Or we can strip markdown.
Let's adjust the prompt to output only code, without markdown.
Alternatively, we can change the parse_llm_response to look for code blocks.
We'll change the prompt to say: "Output only the test code, without any additional text or markdown formatting."
Then we can try to parse the entire response as code.
But if the LLM ignores the instruction, we might get extra text. We can try to extract the first code block.
We'll do:
If the response contains a code block (like ```python ... ```), we extract the code inside.
We can use:
import re
match = re.search(r'```(?:python)?\n(.*?)```', response, re.DOTALL)
if match:
code = match.group(1)
else:
code = response
Then parse code.
Let's adjust:
def parse_llm_response(response):
# Extract code block if present.
code_block_match = re.search(r'```(?:python)?\n(.*?)```', response, re.DOTALL)
if code_block_match:
code = code_block_match.group(1)
else:
code = response
try:
tree = ast.parse(code)
except SyntaxError:
return [], []
... rest as above ...
Now, what about the function name? We are extracting the first function from the provided code. But what if the provided code is a class? We don't handle that.
We'll leave it as is.
This is a basic implementation.
For the developer workflow, we can wrap this in a CLI:
test-generator --file <file> [--num 5] [--framework pytest] [--output tests.py]
Or as an IDE plugin.
We'll leave the integration details to the developer.
This is a starting point.
Let's note the limitations:
- Only handles top-level functions.
- Only checks for direct calls to the function by name.
- No handling of classes, methods, or modules.
- Deduplication is by string, not by semantic.
- Verification is limited to syntax and presence of the function call.
We can improve in the future.
Now, let's write the code accordingly.
We'll write the code for the TestGenerator class.
Note: We are using ast which is Python-specific. For other languages, we would need different parsers.
We are only doing Python for now.
Let's code.
I'll design a comprehensive LLM-powered test case synthesizer that combines generative AI with static analysis for robust, maintainable test generation. Here's the complete system architecture:
System Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Developer Workflow │
├─────────────┬─────────────┬──────────────┬───────────────┤
│ IDE/CLI │ Review │ Iteration │ Integration │
└─────────────┴─────────────┴──────────────┴───────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Test Synthesis Engine │
├─────────────┬─────────────┬──────────────┬───────────────┤
│ Prompt │ Static │ Verification│ Deduplication│
│ Engine │ Analysis │ & Validation│ Engine │
└─────────────┴─────────────┴──────────────┴───────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ LLM Gateway & Orchestration │
├─────────────────────────────────────────────────────────────┤
│ Model Selection │ Context Management │ Fallback Logic │
└─────────────────────────────────────────────────────────────┘
1. Prompt Design System
Multi-Stage Prompt Template
prompt_template = """
# Role
You are a senior software engineer specializing in test-driven development and static analysis.
# Context
{code_context}
{static_analysis_results}
{existing_tests}
# Task
Generate {test_count} test cases for {target_entity} that:
1. Cover identified edge cases from static analysis
2. Include boundary conditions and error paths
3. Maintain test isolation and determinism
4. Follow {testing_framework} conventions
# Requirements
- Each test must be independently executable
- Include descriptive test names following convention: test_{scenario}_when_{condition}
- Add assertions that validate both positive and negative cases
- Use {mock_framework} for external dependencies
- Target coverage: {coverage_goals}
# Output Format
```{test_language}
{test_template}
Static Analysis Notes
{sa_highlights}
Constraints
- Maximum complexity per test: Cyclomatic complexity < 10
- No shared state between tests
- All mocks/stubs must be properly cleaned up
"""
### **Dynamic Prompt Components**
| Component | Source | Purpose |
|-----------|--------|---------|
| **Code Context** | AST/parse tree | Relevant code snippets, signatures |
| **Static Analysis** | SA tool output (SonarQube, CodeQL) | Edge cases, null paths, security issues |
| **Existing Tests** | Current test suite | Avoid duplication, learn patterns |
| **Framework Specs** | Config file | Framework-specific conventions |
| **Coverage Gaps** | Coverage report (JaCoCo, Istanbul) | Targeted scenarios |
### **Prompt Variants by Scenario**
```yaml
unit_test:
focus: "function/method boundaries"
constraints: ["no integration", "mock all dependencies"]
integration_test:
focus: "component interactions"
constraints: ["real dependencies", "test data management"]
security_test:
focus: "OWASP Top 10 patterns"
constraints: ["malicious inputs", "privilege escalation"]
2. Static Analysis Integration Layer
Analysis Pipeline
Code → AST Parse → Control Flow Graph →
Data Flow Analysis → Taint Analysis →
Path Feasibility → Testable Scenarios
Key Static Analysis Outputs
{
"edge_cases": [
{
"type": "null_handling",
"location": "UserService.validateEmail:23",
"scenario": "email = null",
"expected": "IllegalArgumentException"
},
{
"type": "boundary",
"location": "PaymentProcessor.calculateTax:45",
"scenario": "amount = 999999999.99",
"expected": "arithmetic overflow"
}
],
"complexity_hotspots": [
"OrderRouter.decidePath: cyclomatic=12",
"AuthMiddleware.validate: cognitive=15"
],
"security_issues": [
"SQL injection risk in QueryBuilder: line 78",
"Unvalidated redirect in Controller: line 112"
],
"dataflow_anomalies": [
"UserInput → executeQuery (untrusted → dangerous sink)",
"CookieData → session.set (missing validation)"
]
}
Tool Integration
- Java: SpotBugs + ErrorProne + Checkstyle
- JavaScript/TS: ESLint + TypeScript compiler + SonarJS
- Python: Pylint + Bandit + Pyright
- Multi-language: Semgrep (rule-based), CodeQL (semantic)
3. Verification & Validation System
Three-Stage Verification
Stage 1: Syntactic & Semantic Validation
def verify_test_syntax(test_code: str, framework: str) -> ValidationResult:
# Parse test code
try:
tree = ast.parse(test_code) # Language-specific parser
except SyntaxError as e:
return ValidationResult(valid=False, error=f"Syntax error: {e}")
# Framework compliance check
if framework == "pytest":
assert has_pytest_marks(tree)
assert uses_fixtures_correctly(tree)
# API contract validation
if not validate_mock_usage(tree, production_code_ast):
return ValidationResult(valid=False, error="Mock mismatch")
return ValidationResult(valid=True)
Stage 2: Behavioral Validation (Lightweight Execution)
def validate_test_behavior(test_code: str, target_function: str):
# Run in isolated sandbox
with temp_directory() as tmp:
# 1. Compile test
# 2. Run with coverage instrumentation
# 3. Execute only target test
result = subprocess.run(
["pytest", "-v", "--cov=target_module", test_file],
capture_output=True,
timeout=10
)
# Validate:
# - Test passes/fails as expected
# - No unexpected exceptions
# - Coverage of target path achieved
# - No side effects (DB, network)
return BehavioralValidationResult(
passed=result.returncode == 0,
coverage_target_met=check_coverage(result.coverage_data),
no_leakage=check_resource_cleanup()
)
Stage 3: Property-Based Cross-Check
def cross_validate_with_properties(test_case: TestCase):
# Generate property from test assertion
property = extract_property(test_case)
# Use quickcheck/hypothesis to validate property
for _ in range(100):
input_data = generate_valid_input()
if not property(input_data):
return False, f"Property violated with {input_data}"
return True, "Property holds"
4. Intelligent Deduplication Engine
Multi-Level Deduplication Strategy
class DeduplicationEngine:
def __init__(self):
self.similarity_thresholds = {
"exact": 1.0, # Identical AST
"semantic": 0.85, # Same behavior, different code
"structural": 0.7 # Similar structure, different values
}
def deduplicate(self, new_tests: List[Test], existing_tests: List[Test]):
# Level 1: Exact duplicate detection (AST hash)
exact_dups = self.find_exact_duplicates(new_tests)
# Level 2: Semantic equivalence (symbolic execution)
semantic_dups = self.find_semantic_duplicates(new_tests, existing_tests)
# Level 3: Structural similarity (tree edit distance)
structural_similar = self.find_structural_similar(new_tests)
# Level 4: Test input space coverage overlap
coverage_overlap = self.analyze_coverage_overlap(new_tests)
return self.merge_and_rank(
remove_duplicates(new_tests, exact_dups + semantic_dups),
coverage_overlap
)
Deduplication Techniques
- AST Normalization & Hashing: Canonicalize AST, compute hash
- Symbolic Execution: Compare path constraints
- Test Input Space Analysis: Use coverage feedback to compare input domains
- Mutation Analysis: If tests kill same mutants, they're equivalent
Similarity Metrics
def calculate_test_similarity(test1: Test, test2: Test) -> float:
weights = {
"setup_similarity": 0.2,
"input_similarity": 0.4,
"assertion_similarity": 0.3,
"coverage_overlap": 0.1
}
score = 0
for factor, weight in weights.items():
score += weight * self.compare_factor(test1, test2, factor)
return score
5. Developer Workflow Integration
IDE Plugin Architecture (VS Code Example)
// Extension entry point
class TestSynthesizerProvider {
async provideTestCompletion(
document: TextDocument,
position: Position
): Promise<CompletionItem[]> {
const code = document.getText();
const ast = parse(code);
const focusedNode = getNodeAtPosition(ast, position);
// Trigger synthesis on specific gestures
if (this.shouldSynthesize(focusedNode)) {
return [
{
label: "✨ Generate Tests",
kind: CompletionItemKind.Snippet,
insertText: await this.generateTests(focusedNode)
}
];
}
}
}
CLI Interface
# Generate tests for specific function
$ test-synth generate \
--file src/service/UserService.ts \
--function validateEmail \
--framework jest \
--count 5 \
--focus "edge-cases,security"
# Review and accept/reject
$ test-synth review --interactive
# Batch generation with quality gates
$ test-synth batch --dir src/ --min-coverage 80 --max-tests 20
Workflow Steps
-
Trigger: Developer triggers via:
- IDE quick action (Cmd+Shift+T)
- CLI command on file/function
- Pre-commit hook (auto-suggest)
- CI/CD pipeline (coverage gap filling)
-
Analysis: System performs:
graph LR
A[Code Selection] → B[Static Analysis]
B → C[Prompt Construction]
C → D[LLM Generation]
D → E[Verification]
E → F[Deduplication]
F → G[Quality Scoring]
-
Review: Generated tests appear in:
- Side panel with diff view
- Inline suggestions (codion)
- PR comment threads
- Quality metrics dashboard
-
Acceptance Options:
- ✅ Accept all
- ✏️ Edit in-place
- 🔄 Regenerate with new constraints
- ❌ Reject with feedback
- 📊 View coverage impact
-
Integration:
- Auto-format and add to test file
- Update test metadata (tags, priorities)
- Commit with conventional message
- Update coverage reports
6. Quality Assurance & Metrics
Automatic Quality Gates
quality_gates:
- name: "Compilation"
check: "tests_compile"
threshold: 1.0
- name: "Execution"
check: "tests_pass_standalone"
threshold: 1.0
- name: "Coverage Impact"
check: "new_coverage >= 5%"
threshold: 0.05
- name: "Duplication"
check: "duplicate_rate < 0.1"
threshold: 0.1
- name: "Complexity"
check: "avg_cyclomatic < 8"
threshold: 8
Feedback Learning Loop
class FeedbackLearner:
def __init__(self):
self.feedback_db = FeedbackDatabase()
self.prompt_optimizer = PromptOptimizer()
def record_feedback(self, test_id: str, accepted: bool, edits: List[Edit]):
# Store what was changed vs generated
self.feedback_db.record(test_id, accepted, edits)
# Analyze patterns:
# - Which prompts produce most accepted tests?
# - What edits are most common?
# - Which SA findings need better prompts?
self.prompt_optimizer.adjust_based_on_feedback()
7. Implementation Roadmap
Phase 1: MVP (4 weeks)
- Basic prompt engineering for 1 language (Python)
- Simple AST-based verification
- String-based deduplication
- CLI interface
Phase 2: Enhanced (6 weeks)
- Multi-language support (Java, JS/TS)
- Integration with 2+ SA tools
- IDE plugin (VS Code)
- Behavioral validation
Phase 3: Production (8 weeks)
- Property-based validation
- Advanced deduplication (semantic)
- CI/CD integration
- Feedback learning system
- Team deployment guides
8. Example: End-to-End Flow
Input Code:
def process_payment(amount: float, currency: str, user_id: Optional[int] = None):
if amount <= 0:
raise ValueError("Amount must be positive")
if not re.match(r'^[A-Z]{3}$', currency):
raise InvalidCurrencyError(f"Invalid currency: {currency}")
if user_id and not user_exists(user_id):
raise UserNotFoundError(f"User {user_id} not found")
return PaymentGateway.charge(amount, currency, user_id)
Static Analysis Output:
{
"edge_cases": [
"amount = 0.001 (minimum float)",
"currency = 'usd' (lowercase)",
"user_id = None",
"user_id = -1 (negative)"
],
"security": [
"regex DoS risk with complex currency patterns"
]
}
Generated Test (After Deduplication & Verification):
import pytest
from unittest.mock import patch
def test_process_payment_negative_amount():
"""Test that negative amount raises ValueError"""
with pytest.raises(ValueError, match="Amount must be positive"):
process_payment(-100.0, "USD")
def test_process_payment_invalid_currency_case():
"""Test lowercase currency raises InvalidCurrencyError"""
with pytest.raises(InvalidCurrencyError):
process_payment(100.0, "usd")
def test_process_payment_zero_amount_edge():
"""Test boundary: zero amount rejection"""
with pytest.raises(ValueError):
process_payment(0.0, "USD")
def test_process_payment_nonexistent_user():
"""Test user validation with mocking"""
with patch('__main__.user_exists', return_value=False):
with pytest.raises(UserNotFoundError):
process_payment(100.0, "USD", user_id=99999)
@pytest.mark.parametrize("amount,currency", [
(0.001, "USD"), # Minimum float
(999999999.99, "EUR"), # Maximum reasonable
])
def test_process_payment_boundary_values(amount, currency):
"""Test boundary amount values with valid currency"""
assert process_payment(amount, currency) is not None
9. Monitoring & Observability
Key Metrics Dashboard:
- Test generation acceptance rate
- Coverage improvement per generated test
- Time-to-review for generated tests
- Duplication rate in test suite
- LLM token efficiency (tests/token)
- SA finding-to-test coverage
Alerting:
- ↓ Acceptance rate < 60%
- ↑ Duplication rate > 15%
- Generated tests failing in CI
- SA findings without test coverage
10. Deployment Considerations
Environment Requirements
dependencies:
- python>=3.9
- tree-sitter (for multi-language parsing)
- semgrep/sarif-tools (SA integration)
- pytest/jest/xyz (test runners)
- docker (sandboxing)
llm_config:
fallback_models: ["gpt-4-turbo", "claude-3", "codellama"]
cache_strategy: "semantic_similarity"
rate_limiting: true
Security Considerations
- Run LLM in isolated VPC/subnet
- Sanitize all code before LLM (remove secrets)
- Sandbox test execution (firejail/docker)
- Audit trail for all generated code
- License compliance checking
Conclusion
This system provides:
- Context-aware generation using static analysis insights
- Rigorous verification through syntactic, semantic, and behavioral checks
- Intelligent deduplication preserving test diversity
- Seamless developer integration across IDE/CLI/CI
- Continuous improvement via feedback loops
Key Innovation: The tight integration of static analysis before generation (pre-prompting) and after generation (verification) creates a closed-loop system that produces higher-quality, more maintainable tests than either approach alone.
Would you like me to elaborate on any specific component or provide implementation details for a particular language/framework combination?