-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai-debug-config.js
More file actions
327 lines (277 loc) · 9.58 KB
/
ai-debug-config.js
File metadata and controls
327 lines (277 loc) · 9.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// ai-debug-config.js
/**
* AI-Powered Debugging Configuration for Playwright
* This module provides advanced debugging capabilities using AI insights
*/
class AIDebugger {
constructor() {
this.debugSessions = new Map();
this.errorPatterns = new Map();
this.performanceMetrics = new Map();
}
/**
* Start an AI debugging session
* @param {string} testName
* @param {import('@playwright/test').Page} page
*/
async startDebugSession(testName, page) {
const sessionId = `${testName}-${Date.now()}`;
const session = {
id: sessionId,
testName,
startTime: Date.now(),
page,
events: [],
screenshots: [],
networkRequests: [],
consoleMessages: []
};
// Listen to page events for AI analysis
page.on('console', (msg) => {
session.consoleMessages.push({
type: msg.type(),
text: msg.text(),
timestamp: Date.now()
});
});
page.on('response', (response) => {
session.networkRequests.push({
url: response.url(),
status: response.status(),
timestamp: Date.now()
});
});
page.on('pageerror', (error) => {
session.events.push({
type: 'error',
message: error.message,
stack: error.stack,
timestamp: Date.now()
});
});
this.debugSessions.set(sessionId, session);
return sessionId;
}
/**
* Analyze test failure with AI insights
* @param {string} sessionId
* @param {Error} error
*/
async analyzeFailure(sessionId, error) {
const session = this.debugSessions.get(sessionId);
if (!session) return;
const analysis = {
errorType: this.classifyError(error),
suggestions: this.generateSuggestions(error, session),
patterns: this.detectPatterns(session),
timeline: this.buildTimeline(session),
networkIssues: this.analyzeNetworkRequests(session.networkRequests),
consoleErrors: this.filterCriticalConsoleMessages(session.consoleMessages)
};
console.log('🤖 AI Failure Analysis Report:');
console.log('================================');
console.log(`Test: ${session.testName}`);
console.log(`Error Type: ${analysis.errorType}`);
console.log(`Duration: ${Date.now() - session.startTime}ms`);
console.log('');
console.log('🔍 AI Suggestions:');
analysis.suggestions.forEach((suggestion, index) => {
console.log(` ${index + 1}. ${suggestion}`);
});
if (analysis.networkIssues.length > 0) {
console.log('');
console.log('🌐 Network Issues Detected:');
analysis.networkIssues.forEach(issue => {
console.log(` - ${issue}`);
});
}
if (analysis.consoleErrors.length > 0) {
console.log('');
console.log('⚠️ Critical Console Messages:');
analysis.consoleErrors.forEach(msg => {
console.log(` - ${msg.type}: ${msg.text}`);
});
}
return analysis;
}
/**
* Classify error types using AI patterns
* @param {Error} error
*/
classifyError(error) {
const message = error.message.toLowerCase();
if (message.includes('timeout')) {
return 'TIMEOUT_ERROR';
} else if (message.includes('not found') || message.includes('not visible')) {
return 'ELEMENT_NOT_FOUND';
} else if (message.includes('navigation') || message.includes('goto')) {
return 'NAVIGATION_ERROR';
} else if (message.includes('network') || message.includes('fetch')) {
return 'NETWORK_ERROR';
} else if (message.includes('assertion') || message.includes('expect')) {
return 'ASSERTION_FAILURE';
} else {
return 'UNKNOWN_ERROR';
}
}
/**
* Generate AI-powered suggestions based on error analysis
* @param {Error} error
* @param {Object} session
*/
generateSuggestions(error, session) {
const errorType = this.classifyError(error);
const suggestions = [];
switch (errorType) {
case 'TIMEOUT_ERROR':
suggestions.push('Increase timeout values for slow-loading elements');
suggestions.push('Add explicit waits for specific conditions');
suggestions.push('Check for loading indicators that might need to disappear');
suggestions.push('Verify network requests are completing successfully');
break;
case 'ELEMENT_NOT_FOUND':
suggestions.push('Verify the element selector is correct and up-to-date');
suggestions.push('Check if the element is inside an iframe');
suggestions.push('Wait for the element to appear before interacting');
suggestions.push('Use more robust locator strategies (data-testid, role-based)');
break;
case 'NAVIGATION_ERROR':
suggestions.push('Verify the URL is correct and accessible');
suggestions.push('Check for redirects or authentication requirements');
suggestions.push('Ensure the server is running and responsive');
break;
case 'NETWORK_ERROR':
suggestions.push('Check network connectivity and server status');
suggestions.push('Verify API endpoints are responding correctly');
suggestions.push('Add retry logic for flaky network requests');
break;
case 'ASSERTION_FAILURE':
suggestions.push('Review the expected vs actual values');
suggestions.push('Check if timing issues are affecting the assertion');
suggestions.push('Add debugging output to understand the current state');
break;
default:
suggestions.push('Enable debug mode for more detailed error information');
suggestions.push('Check browser console for additional error details');
suggestions.push('Add try-catch blocks to isolate the failing operation');
}
// Add context-specific suggestions
if (session.page && session.page.url().includes('saucedemo')) {
suggestions.push('For SauceDemo: Verify user credentials and account status');
suggestions.push('Check if the specific user type has known limitations');
}
return suggestions;
}
/**
* Detect patterns in test failures
* @param {Object} session
*/
detectPatterns(session) {
const patterns = [];
// Check for repeated network failures
const failedRequests = session.networkRequests.filter(req => req.status >= 400);
if (failedRequests.length > 2) {
patterns.push(`Multiple network failures detected (${failedRequests.length} requests)`);
}
// Check for console error patterns
const errorMessages = session.consoleMessages.filter(msg => msg.type === 'error');
if (errorMessages.length > 0) {
patterns.push(`Browser console errors detected (${errorMessages.length} errors)`);
}
// Check timing patterns
const duration = Date.now() - session.startTime;
if (duration > 30000) {
patterns.push('Test took unusually long to execute');
}
return patterns;
}
/**
* Build a timeline of events for analysis
* @param {Object} session
*/
buildTimeline(session) {
const timeline = [];
// Add all events with timestamps
session.events.forEach(event => {
timeline.push({
time: event.timestamp - session.startTime,
type: 'event',
description: `${event.type}: ${event.message}`
});
});
// Add network requests
session.networkRequests.forEach(req => {
timeline.push({
time: req.timestamp - session.startTime,
type: 'network',
description: `${req.status} ${req.url}`
});
});
// Sort by timestamp
timeline.sort((a, b) => a.time - b.time);
return timeline;
}
/**
* Analyze network requests for issues
* @param {Array} requests
*/
analyzeNetworkRequests(requests) {
const issues = [];
const failedRequests = requests.filter(req => req.status >= 400);
if (failedRequests.length > 0) {
issues.push(`${failedRequests.length} failed network requests`);
}
const slowRequests = requests.filter(req => {
// This is a simplified check - in real implementation, you'd track request duration
return req.url.includes('slow') || req.status === 504;
});
if (slowRequests.length > 0) {
issues.push(`${slowRequests.length} potentially slow requests`);
}
return issues;
}
/**
* Filter critical console messages
* @param {Array} messages
*/
filterCriticalConsoleMessages(messages) {
return messages.filter(msg =>
msg.type === 'error' ||
(msg.type === 'warning' && msg.text.includes('deprecated'))
);
}
/**
* Generate performance insights
* @param {string} sessionId
*/
async generatePerformanceInsights(sessionId) {
const session = this.debugSessions.get(sessionId);
if (!session) return;
const insights = {
testDuration: Date.now() - session.startTime,
networkRequestCount: session.networkRequests.length,
errorCount: session.consoleMessages.filter(m => m.type === 'error').length,
recommendations: []
};
if (insights.testDuration > 30000) {
insights.recommendations.push('Consider optimizing test execution time');
}
if (insights.networkRequestCount > 20) {
insights.recommendations.push('High number of network requests detected');
}
if (insights.errorCount > 0) {
insights.recommendations.push('Browser console errors should be investigated');
}
return insights;
}
/**
* Clean up debug session
* @param {string} sessionId
*/
endDebugSession(sessionId) {
this.debugSessions.delete(sessionId);
}
}
// Export singleton instance
const aiDebugger = new AIDebugger();
module.exports = { aiDebugger, AIDebugger };