cqt-agent
Version:
529 lines (479 loc) • 18.9 kB
Markdown
This utility converts analyzed project structure and workflow patterns into comprehensive user stories and test scenarios for automated E2E test generation.
Transform technical project analysis into user-centric stories and scenarios that can be directly converted into executable E2E tests.
- Project workflow analysis from `project-workflow-analyzer.md`
- Discovered routes, components, and API endpoints
- Authentication patterns and user roles
- CRUD operations and business logic flows
```gherkin
Feature: [Business Capability]
As a [User Role]
I want to [Action/Goal]
So that [Business Value]
Scenario: [Specific Use Case]
Given [Initial State/Context]
When [User Action]
Then [Expected Outcome]
And [Additional Validations]
```
```javascript
const guestStories = [
{
feature: "User Registration",
asA: "new user",
iWantTo: "create an account",
soThat: "I can access personalized features",
scenarios: [
// Happy Path Scenarios
"successful registration with valid data",
"successful registration with minimum required fields",
"successful registration with special characters in name",
// Validation Error Scenarios
"registration fails with invalid email format",
"registration fails with weak password",
"registration fails with password confirmation mismatch",
"registration fails with duplicate email",
"registration fails with missing required fields",
"registration fails with email containing SQL injection",
"registration fails with XSS attempts in form fields",
"registration fails with extremely long input values",
"registration fails with unicode characters in inappropriate fields",
// Business Logic Scenarios
"registration requires terms and conditions acceptance",
"registration sends email verification",
"registration handles concurrent duplicate email attempts",
"registration respects rate limiting",
"registration validates against blocked domains",
"registration handles special email formats (plus addressing, subdomains)",
// Edge Cases
"registration with expired verification link",
"registration with already verified email",
"registration during maintenance mode",
"registration with network interruption",
"registration form auto-saves incomplete data",
"registration handles browser back/forward navigation"
]
},
{
feature: "User Authentication",
asA: "registered user",
iWantTo: "log into my account",
soThat: "I can access my personal dashboard",
scenarios: [
// Happy Path Scenarios
"successful login with correct credentials",
"successful login with remember me option",
"successful login redirects to intended page after authentication",
// Authentication Failure Scenarios
"login fails with incorrect email",
"login fails with incorrect password",
"login fails with non-existent email",
"login fails with empty credentials",
"login fails with SQL injection attempts",
"login fails with XSS attempts",
"login fails with case-sensitive email handling",
"login fails with whitespace in credentials",
// Account Security Scenarios
"account locks after multiple failed attempts",
"account lockout displays appropriate message",
"account lockout respects time-based unlock",
"concurrent login attempts are handled properly",
"login tracks and logs security events",
"login prevents brute force attacks",
// Session Management
"login creates secure session",
"login handles existing active sessions",
"login manages multiple device sessions",
"login enforces session timeout",
"login handles session hijacking attempts",
// Password Reset Workflow
"password reset with valid email",
"password reset with invalid email",
"password reset with expired token",
"password reset with used token",
"password reset validates new password strength",
"password reset requires confirmation matching",
"password reset prevents account enumeration"
]
}
];
```
```javascript
const authenticatedStories = [
{
feature: "Profile Management",
asA: "logged-in user",
iWantTo: "manage my profile information",
soThat: "I can keep my account details current",
scenarios: [
"view current profile information",
"update profile with valid data",
"change password successfully",
"upload profile picture"
]
},
{
feature: "Dashboard Navigation",
asA: "authenticated user",
iWantTo: "navigate through the application",
soThat: "I can access different features efficiently",
scenarios: [
"access main dashboard after login",
"navigate to different sections",
"use search functionality",
"logout successfully"
]
}
];
```
```javascript
// Generated dynamically based on discovered entities - Exhaustive Coverage
function generateEntityStories(entity) {
return {
feature: `${entity.name} Management`,
asA: "authorized user",
iWantTo: `manage ${entity.name.toLowerCase()} records`,
soThat: "I can maintain accurate business data",
scenarios: [
// List/View Operations - All States
`view empty list of ${entity.name.toLowerCase()}s with appropriate message`,
`view list of all ${entity.name.toLowerCase()}s with pagination`,
`view list with sorting by all sortable fields`,
`view list with different page sizes`,
`navigate through paginated ${entity.name.toLowerCase()}s`,
`handle loading states while fetching ${entity.name.toLowerCase()}s`,
`handle error states when list fails to load`,
`refresh ${entity.name.toLowerCase()} list after operations`,
// Search and Filter - Comprehensive Coverage
`search ${entity.name.toLowerCase()}s by all searchable fields`,
`search with partial matches and wildcards`,
`search with special characters and unicode`,
`search with empty query returns all results`,
`filter ${entity.name.toLowerCase()}s by single criteria`,
`filter ${entity.name.toLowerCase()}s by multiple criteria`,
`filter with date ranges and numerical ranges`,
`combine search and filter operations`,
`clear search and filter states`,
`handle no results found scenarios`,
`preserve search/filter state during navigation`,
// Create Operations - All Scenarios
`create new ${entity.name.toLowerCase()} with minimum required data`,
`create new ${entity.name.toLowerCase()} with all optional fields`,
`create ${entity.name.toLowerCase()} with file attachments`,
`create ${entity.name.toLowerCase()} with related entity selection`,
`validate all required fields during creation`,
`validate field formats and business rules`,
`handle duplicate ${entity.name.toLowerCase()} creation attempts`,
`handle creation with invalid related entities`,
`handle creation during network failures`,
`prevent creation without proper permissions`,
`cancel creation and handle unsaved changes`,
`auto-save creation form data`,
// Read/View Operations - Detail Coverage
`view ${entity.name.toLowerCase()} details with all fields`,
`view ${entity.name.toLowerCase()} with related entity data`,
`view ${entity.name.toLowerCase()} audit history`,
`view ${entity.name.toLowerCase()} with permission-based field visibility`,
`handle viewing non-existent ${entity.name.toLowerCase()}`,
`handle viewing deleted ${entity.name.toLowerCase()}`,
`handle viewing ${entity.name.toLowerCase()} without read permissions`,
`refresh ${entity.name.toLowerCase()} data automatically`,
`track ${entity.name.toLowerCase()} view analytics`,
// Update Operations - All Variations
`update ${entity.name.toLowerCase()} with valid changes`,
`update ${entity.name.toLowerCase()} with partial field changes`,
`update ${entity.name.toLowerCase()} with file replacements`,
`update ${entity.name.toLowerCase()} related entity associations`,
`validate updates against business rules`,
`handle concurrent update conflicts`,
`prevent updates without proper permissions`,
`track update history and versions`,
`revert ${entity.name.toLowerCase()} to previous version`,
`handle update during network interruptions`,
`cancel updates and restore original data`,
`validate update permissions by field`,
// Delete Operations - Complete Coverage
`delete ${entity.name.toLowerCase()} with confirmation dialog`,
`delete ${entity.name.toLowerCase()} with dependency checks`,
`soft delete ${entity.name.toLowerCase()} with recovery option`,
`hard delete ${entity.name.toLowerCase()} permanently`,
`bulk delete multiple ${entity.name.toLowerCase()}s`,
`prevent deletion without proper permissions`,
`handle deletion of ${entity.name.toLowerCase()} with related data`,
`cancel deletion operation`,
`restore deleted ${entity.name.toLowerCase()} from recycle bin`,
`delete ${entity.name.toLowerCase()} files and attachments`,
// Business Logic Scenarios
`validate ${entity.name.toLowerCase()} against business constraints`,
`handle ${entity.name.toLowerCase()} workflow state transitions`,
`manage ${entity.name.toLowerCase()} approval processes`,
`track ${entity.name.toLowerCase()} modification audit trail`,
`handle ${entity.name.toLowerCase()} data export`,
`handle ${entity.name.toLowerCase()} data import with validation`,
`manage ${entity.name.toLowerCase()} sharing and permissions`,
`handle ${entity.name.toLowerCase()} archival and retention`,
// Error and Edge Cases
`handle ${entity.name.toLowerCase()} operations during maintenance`,
`handle ${entity.name.toLowerCase()} operations with corrupted data`,
`handle ${entity.name.toLowerCase()} operations with database constraints`,
`handle ${entity.name.toLowerCase()} operations during high load`,
`handle ${entity.name.toLowerCase()} operations with expired sessions`,
`prevent unauthorized access to ${entity.name.toLowerCase()}s`,
`handle ${entity.name.toLowerCase()} operations with invalid tokens`,
`handle ${entity.name.toLowerCase()} operations with insufficient storage`
]
};
}
```
```javascript
const workflowStories = [
{
feature: "Order Processing Workflow",
asA: "customer",
iWantTo: "complete a purchase",
soThat: "I can receive the products I need",
scenarios: [
"add items to cart and checkout",
"apply discount codes during checkout",
"complete payment with valid card",
"receive order confirmation",
"track order status updates",
"handle payment failures gracefully"
]
},
{
feature: "Document Management Process",
asA: "business user",
iWantTo: "manage document lifecycle",
soThat: "I can maintain organized records",
scenarios: [
"upload document with metadata",
"categorize and tag documents",
"share document with team members",
"version control for document updates",
"approve document for publication",
"archive expired documents"
]
}
];
```
```javascript
function extractStoriesFromRoutes(routes) {
const stories = [];
routes.forEach(route => {
if (route.path.includes('/login')) {
stories.push(createAuthenticationStory());
} else if (route.path.includes('/register')) {
stories.push(createRegistrationStory());
} else if (route.path.includes('/dashboard')) {
stories.push(createDashboardStory());
} else if (route.path.includes('/:id/edit')) {
const entity = extractEntityFromRoute(route.path);
stories.push(createEditEntityStory(entity));
} else if (route.path.includes('/new')) {
const entity = extractEntityFromRoute(route.path);
stories.push(createCreateEntityStory(entity));
}
});
return stories;
}
```
```javascript
function correlateAPIWithStories(apiEndpoints, stories) {
return stories.map(story => {
story.scenarios = story.scenarios.map(scenario => {
const relatedAPIs = findRelatedAPIs(scenario, apiEndpoints);
return {
...scenario,
apiEndpoints: relatedAPIs,
expectedStatusCodes: deriveExpectedStatusCodes(relatedAPIs),
dataFlow: mapDataFlow(scenario, relatedAPIs)
};
});
return story;
});
}
```
```javascript
function mapComponentInteractions(components, stories) {
return stories.map(story => {
story.scenarios = story.scenarios.map(scenario => {
const interactions = [];
// Extract form interactions
const forms = components.filter(c => c.type === 'form');
forms.forEach(form => {
if (scenario.description.includes(form.purpose)) {
interactions.push({
type: 'form_submission',
component: form.name,
fields: form.fields,
validations: form.validations
});
}
});
// Extract navigation interactions
const navElements = components.filter(c => c.type === 'navigation');
navElements.forEach(nav => {
if (scenario.description.includes('navigate')) {
interactions.push({
type: 'navigation',
component: nav.name,
targets: nav.links
});
}
});
return { ...scenario, interactions };
});
return story;
});
}
```
```javascript
function prioritizeStories(stories, projectAnalysis) {
return stories.map(story => {
let priority = 'medium';
// High priority for authentication
if (story.feature.includes('Authentication') || story.feature.includes('Login')) {
priority = 'critical';
}
// High priority for core business entities
const coreEntities = projectAnalysis.coreBusinessEntities || [];
if (coreEntities.some(entity => story.feature.includes(entity))) {
priority = 'high';
}
// Medium priority for CRUD operations
if (story.scenarios.some(s => s.includes('create') || s.includes('update'))) {
priority = 'medium';
}
// Low priority for edge cases
if (story.scenarios.every(s => s.includes('error') || s.includes('validation'))) {
priority = 'low';
}
return { ...story, priority };
});
}
```
```javascript
function analyzeCoverage(stories, projectAnalysis) {
const coverage = {
routes: calculateRouteCoverage(stories, projectAnalysis.routes),
apis: calculateAPICoverage(stories, projectAnalysis.apiEndpoints),
components: calculateComponentCoverage(stories, projectAnalysis.components),
workflows: calculateWorkflowCoverage(stories, projectAnalysis.businessWorkflows)
};
// Identify gaps
const gaps = {
untestedRoutes: findUntestedRoutes(coverage.routes),
untestedAPIs: findUntestedAPIs(coverage.apis),
missingWorkflows: findMissingWorkflows(coverage.workflows)
};
return { coverage, gaps };
}
```
```json
{
"userStories": [
{
"id": "AUTH_001",
"feature": "User Authentication",
"priority": "critical",
"asA": "registered user",
"iWantTo": "log into my account",
"soThat": "I can access my personal dashboard",
"acceptanceCriteria": [
"User can enter valid credentials",
"System validates credentials against database",
"User is redirected to dashboard on success",
"Error message shown for invalid credentials"
],
"scenarios": [
{
"id": "AUTH_001_01",
"name": "Successful login with valid credentials",
"given": "I am on the login page",
"when": "I enter valid email and password",
"then": "I should be redirected to the dashboard",
"and": ["I should see my user profile", "Navigation menu should be visible"],
"frontend": {
"route": "/login",
"component": "LoginForm",
"interactions": ["fill email field", "fill password field", "click login button"],
"assertions": ["redirect to /dashboard", "user state updated"]
},
"backend": {
"endpoint": "/api/auth/login",
"method": "POST",
"expectedStatus": 200,
"responseValidation": "JWT token present"
}
}
]
}
],
"testSuites": {
"critical": ["AUTH_001", "AUTH_002"],
"high": ["USER_001", "PRODUCT_001"],
"medium": ["PROFILE_001", "SEARCH_001"],
"low": ["ERROR_001", "VALIDATION_001"]
},
"coverage": {
"totalRoutes": 25,
"testedRoutes": 23,
"coveragePercentage": 92
}
}
```
```json
{
"templates": [
{
"type": "authentication",
"pattern": "login_flow",
"steps": [
{ "action": "navigate", "target": "/login" },
{ "action": "fill_form", "fields": ["email", "password"] },
{ "action": "submit", "element": "login-button" },
{ "action": "verify_redirect", "expectedRoute": "/dashboard" }
]
},
{
"type": "crud_create",
"pattern": "entity_creation",
"steps": [
{ "action": "navigate", "target": "/entity/new" },
{ "action": "fill_form", "fields": "dynamic_based_on_entity" },
{ "action": "submit", "element": "save-button" },
{ "action": "verify_success", "assertions": ["success_message", "redirect_to_list"] }
]
}
]
}
```
The extracted user stories feed directly into:
- Test case generation with specific steps
- Mock data requirements
- Test organization structure
- Coverage validation
- Maintenance documentation
This utility bridges the gap between technical project analysis and user-focused test scenarios, enabling truly automated E2E test generation.