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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
TestGenius AI — Prompt Builder
|
| 3 |
+
================================
|
| 4 |
+
Builds structured, context-rich prompts for the LLM to generate high-quality test cases.
|
| 5 |
+
Each prompt type is tailored to the input source (requirements, API spec, code, flow).
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
from typing import Dict, List, Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
SYSTEM_PROMPT = """You are TestGenius, an expert QA engineer and test automation specialist with 15 years of experience.
|
| 13 |
+
Your task is to generate comprehensive, production-ready test cases.
|
| 14 |
+
|
| 15 |
+
RULES:
|
| 16 |
+
1. Generate REAL, RUNNABLE test code — not pseudocode or descriptions.
|
| 17 |
+
2. Include ALL necessary imports at the top of each file.
|
| 18 |
+
3. Use proper test naming: test_<what>_<scenario>_<expected_result>
|
| 19 |
+
4. Cover: happy path, edge cases, boundary values, error scenarios, security.
|
| 20 |
+
5. Add docstrings explaining WHAT each test verifies and WHY it matters.
|
| 21 |
+
6. Use proper assertions (not just print statements).
|
| 22 |
+
7. Include setup/teardown fixtures where appropriate.
|
| 23 |
+
8. Generate at least 8-15 test cases per input.
|
| 24 |
+
9. Group tests logically into test classes or describe blocks.
|
| 25 |
+
10. For API tests: include request headers, auth tokens, proper status code checks.
|
| 26 |
+
11. For edge cases: test null/empty inputs, max lengths, special characters, concurrent access.
|
| 27 |
+
12. For security: test SQL injection, XSS, auth bypass, IDOR.
|
| 28 |
+
|
| 29 |
+
OUTPUT FORMAT:
|
| 30 |
+
- Wrap each test file in a markdown code block with the language specified.
|
| 31 |
+
- Start each file with a comment: # File: <filename>
|
| 32 |
+
- Separate multiple files clearly.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def build_requirements_prompt(requirements: str, framework: str, language: str, test_types: List[str]) -> str:
|
| 37 |
+
"""Build prompt for generating tests from product requirements."""
|
| 38 |
+
return f"""Analyze the following product requirements and generate comprehensive test cases.
|
| 39 |
+
|
| 40 |
+
## Product Requirements:
|
| 41 |
+
{requirements}
|
| 42 |
+
|
| 43 |
+
## Generation Config:
|
| 44 |
+
- Test framework: {framework}
|
| 45 |
+
- Language: {language}
|
| 46 |
+
- Test types to generate: {', '.join(test_types)}
|
| 47 |
+
|
| 48 |
+
## Instructions:
|
| 49 |
+
1. Extract all testable features and user stories from the requirements.
|
| 50 |
+
2. For each feature, generate:
|
| 51 |
+
- Happy path tests (normal usage)
|
| 52 |
+
- Edge case tests (boundary values, empty inputs, special chars)
|
| 53 |
+
- Negative tests (invalid inputs, unauthorized access)
|
| 54 |
+
- Integration tests (feature interactions)
|
| 55 |
+
3. Name tests descriptively: test_<feature>_<scenario>_<expected_behavior>
|
| 56 |
+
4. Include proper setup fixtures for any required state.
|
| 57 |
+
5. Add assertions that verify BOTH success AND failure conditions.
|
| 58 |
+
|
| 59 |
+
Generate the complete test file(s) now:"""
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def build_api_spec_prompt(spec: Dict, endpoints: List[Dict], framework: str, language: str, test_types: List[str]) -> str:
|
| 63 |
+
"""Build prompt for generating tests from OpenAPI specification."""
|
| 64 |
+
|
| 65 |
+
# Summarize endpoints
|
| 66 |
+
endpoint_summary = ""
|
| 67 |
+
for ep in endpoints[:20]: # Limit to prevent token overflow
|
| 68 |
+
endpoint_summary += f"\n- {ep['method']} {ep['path']}: {ep.get('summary', 'No description')}"
|
| 69 |
+
if ep.get('parameters'):
|
| 70 |
+
params = [p.get('name', '') for p in ep['parameters'][:5]]
|
| 71 |
+
endpoint_summary += f"\n Parameters: {', '.join(params)}"
|
| 72 |
+
if ep.get('request_body'):
|
| 73 |
+
endpoint_summary += f"\n Has request body: Yes"
|
| 74 |
+
if ep.get('responses'):
|
| 75 |
+
codes = list(ep['responses'].keys())[:4]
|
| 76 |
+
endpoint_summary += f"\n Response codes: {', '.join(codes)}"
|
| 77 |
+
|
| 78 |
+
# Include schemas if available
|
| 79 |
+
schemas_str = ""
|
| 80 |
+
schemas = spec.get("components", {}).get("schemas", {})
|
| 81 |
+
if schemas:
|
| 82 |
+
schema_names = list(schemas.keys())[:10]
|
| 83 |
+
schemas_str = f"\n\nData Models: {', '.join(schema_names)}"
|
| 84 |
+
for name in schema_names[:5]:
|
| 85 |
+
props = schemas[name].get("properties", {})
|
| 86 |
+
if props:
|
| 87 |
+
schemas_str += f"\n {name}: {', '.join(list(props.keys())[:8])}"
|
| 88 |
+
|
| 89 |
+
return f"""Analyze this API specification and generate comprehensive API test cases.
|
| 90 |
+
|
| 91 |
+
## API Info:
|
| 92 |
+
- Title: {spec.get('info', {}).get('title', 'Unknown API')}
|
| 93 |
+
- Version: {spec.get('info', {}).get('version', '1.0')}
|
| 94 |
+
- Base URL: {spec.get('servers', [{}])[0].get('url', 'http://localhost:8000') if spec.get('servers') else 'http://localhost:8000'}
|
| 95 |
+
|
| 96 |
+
## Endpoints:{endpoint_summary}
|
| 97 |
+
{schemas_str}
|
| 98 |
+
|
| 99 |
+
## Security:
|
| 100 |
+
{json.dumps(spec.get('components', {}).get('securitySchemes', {}), indent=2)[:500] if spec.get('components', {}).get('securitySchemes') else 'None specified'}
|
| 101 |
+
|
| 102 |
+
## Generation Config:
|
| 103 |
+
- Framework: {framework}
|
| 104 |
+
- Language: {language}
|
| 105 |
+
- Test types: {', '.join(test_types)}
|
| 106 |
+
|
| 107 |
+
## Instructions:
|
| 108 |
+
1. Generate tests for EACH endpoint listed above.
|
| 109 |
+
2. For each endpoint, include:
|
| 110 |
+
- Success case (valid request → expected response)
|
| 111 |
+
- Invalid input (missing required fields, wrong types)
|
| 112 |
+
- Authentication (no token, invalid token, expired token)
|
| 113 |
+
- Edge cases (empty body, max payload size, special characters)
|
| 114 |
+
- Security (SQL injection in parameters, XSS in string fields)
|
| 115 |
+
3. Use proper HTTP client (httpx for Python, axios/fetch for JS).
|
| 116 |
+
4. Assert response status codes AND response body structure.
|
| 117 |
+
5. Include test fixtures for auth tokens and base URL.
|
| 118 |
+
|
| 119 |
+
Generate the complete test file(s) now:"""
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def build_code_analysis_prompt(code: str, filename: str, framework: str, language: str, test_types: List[str]) -> str:
|
| 123 |
+
"""Build prompt for generating unit tests from source code."""
|
| 124 |
+
return f"""Analyze this source code and generate comprehensive unit tests.
|
| 125 |
+
|
| 126 |
+
## Source File: {filename}
|
| 127 |
+
|
| 128 |
+
```{language}
|
| 129 |
+
{code}
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
## Generation Config:
|
| 133 |
+
- Framework: {framework}
|
| 134 |
+
- Language: {language}
|
| 135 |
+
- Test types: {', '.join(test_types)}
|
| 136 |
+
|
| 137 |
+
## Instructions:
|
| 138 |
+
1. Identify ALL functions/methods/classes in the code.
|
| 139 |
+
2. For each function, generate tests for:
|
| 140 |
+
- Normal inputs → expected outputs (happy path)
|
| 141 |
+
- Edge cases: empty inputs, None/null, zero, negative numbers, empty strings, empty lists
|
| 142 |
+
- Boundary values: MAX_INT, very long strings, single character
|
| 143 |
+
- Error cases: invalid types, missing arguments
|
| 144 |
+
- If the function has side effects: mock dependencies and verify calls
|
| 145 |
+
3. Use proper mocking for external dependencies (databases, APIs, file system).
|
| 146 |
+
4. Test both return values AND raised exceptions.
|
| 147 |
+
5. Include parameterized tests where appropriate (@pytest.mark.parametrize or test.each).
|
| 148 |
+
|
| 149 |
+
Generate the complete test file(s) now:"""
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def build_frontend_flow_prompt(flow: str, framework: str, language: str, test_types: List[str]) -> str:
|
| 153 |
+
"""Build prompt for generating E2E tests from frontend flow description."""
|
| 154 |
+
return f"""Analyze this frontend user flow and generate comprehensive E2E test cases.
|
| 155 |
+
|
| 156 |
+
## User Flow Description:
|
| 157 |
+
{flow}
|
| 158 |
+
|
| 159 |
+
## Generation Config:
|
| 160 |
+
- Framework: {framework}
|
| 161 |
+
- Language: {language}
|
| 162 |
+
- Test types: {', '.join(test_types)}
|
| 163 |
+
|
| 164 |
+
## Instructions:
|
| 165 |
+
1. Break the flow into discrete user actions (click, type, navigate, submit).
|
| 166 |
+
2. For each action, generate tests for:
|
| 167 |
+
- Happy path (user completes flow successfully)
|
| 168 |
+
- Validation errors (required fields empty, invalid formats)
|
| 169 |
+
- Edge cases (special characters, very long inputs, rapid clicking)
|
| 170 |
+
- Error states (network failure, server error, timeout)
|
| 171 |
+
- Accessibility (keyboard navigation, screen reader)
|
| 172 |
+
3. Use proper selectors (data-testid preferred, then aria-label, then CSS).
|
| 173 |
+
4. Include proper waits (waitForSelector, not arbitrary timeouts).
|
| 174 |
+
5. Test responsive behavior if mentioned in the flow.
|
| 175 |
+
|
| 176 |
+
Generate the complete test file(s) now:"""
|