UNPKG

testgenius-ai

Version:

🚀 TestGenius AI - The Ultimate E2E Testing Framework for Everyone | No Coding Required • AI-Powered Automation • Beautiful Reports • Zero Complexity

239 lines 10.1 kB
"use strict"; /** * 🧠 Dynamic AI Test Executor - 100% AI-Driven * No static parsing, no hardcoded steps, no predefined flows * Everything is handled by the AI agent dynamically * * Inspired by Endorphin AI's fully dynamic approach */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DynamicAITestExecutor = void 0; const chalk_1 = __importDefault(require("chalk")); const SmartAIAgent_1 = require("./SmartAIAgent"); const SmartAgentConfig_1 = require("./SmartAgentConfig"); const SmartTools_1 = require("../tools/SmartTools"); const CostTracker_1 = require("./CostTracker"); class DynamicAITestExecutor { constructor(config) { this.browser = null; this.smartAgent = null; this.costTracker = null; this.steps = []; this.screenshots = []; this.tokenUsage = []; this.currentSession = null; // Initialize cost tracker if enabled if (config?.costTracking?.enabled) { this.costTracker = new CostTracker_1.CostTracker(config); } } /** * Set browser and initialize Smart AI Agent with tools */ setBrowser(browser) { this.browser = browser; // Initialize Smart AI Agent with all tools this.smartAgent = new SmartAIAgent_1.SmartAIAgent(SmartAgentConfig_1.SMART_AGENT_CONFIG); const smartTools = (0, SmartTools_1.createAllSmartTools)(browser); this.smartAgent.setTools(smartTools); console.log(chalk_1.default.green('🧠 Dynamic AI Test Executor initialized')); console.log(chalk_1.default.blue('🛠️ Smart tools available: Navigation, Click, Fill, Verify, Wait, Screenshot')); console.log(chalk_1.default.blue('💭 AI Agent will handle all test execution dynamically')); } /** * 🚀 Execute test with 100% AI-driven approach * No static parsing, no hardcoded steps, no predefined flows */ async executeTest(test, options = {}) { if (!this.browser || !this.smartAgent) { throw new Error('Browser and Smart AI Agent not initialized. Call setBrowser() first.'); } console.log(chalk_1.default.blue('🧠 Dynamic AI Test Executor starting...\n')); console.log(chalk_1.default.cyan(`🎯 Test: ${test.name}`)); console.log(chalk_1.default.cyan(`📝 Description: ${test.description}`)); const startTime = Date.now(); try { // Handle async test case format dynamically let testData = test.testData || {}; let setupData = {}; let taskDescription; // Execute setup function if provided (AI will handle the setup) if (test.setup && typeof test.setup === 'function') { console.log(chalk_1.default.blue('🔧 Executing dynamic test setup...')); setupData = await test.setup(); console.log(chalk_1.default.green('✅ Dynamic setup completed')); } // Execute data function if provided (AI will use this data) if (test.data && typeof test.data === 'function') { console.log(chalk_1.default.blue('📊 Generating dynamic test data...')); testData = { ...testData, ...(await test.data()) }; console.log(chalk_1.default.green('✅ Dynamic data generated')); } // Get task description (AI will interpret this dynamically) if (typeof test.task === 'function') { console.log(chalk_1.default.blue('📝 Executing dynamic task function...')); taskDescription = await test.task(testData, setupData); } else { taskDescription = test.task; } console.log(chalk_1.default.cyan(`📝 Dynamic Task: ${taskDescription}`)); // Navigate to the site (AI will handle this) if (test.site) { console.log(chalk_1.default.blue(`🌐 Navigating to: ${test.site}`)); await this.browser.url(test.site); await this.browser.pause(2000); this.addStep('Navigate to site', `Successfully navigated to ${test.site}`, 'success'); } // Create dynamic test session for the AI agent const session = { sessionId: `dynamic-session-${Date.now()}`, testName: test.name, startTime: Date.now(), agentHistory: [], totalCost: 0, totalTokens: 0, }; this.currentSession = session; this.smartAgent.setCurrentSession(session); // 🧠 LET THE AI AGENT HANDLE EVERYTHING DYNAMICALLY console.log(chalk_1.default.blue('🧠 AI Agent taking control - no static parsing, no hardcoded steps')); console.log(chalk_1.default.blue('💭 AI will interpret the task and execute it dynamically')); const agentResult = await this.smartAgent.executeTask(taskDescription); // Add AI agent execution to steps this.addStep('AI Agent Dynamic Execution', agentResult.result, agentResult.success ? 'success' : 'failed'); // Track cost and tokens if (this.costTracker && session) { const totalTokenUsage = this.getTotalTokenUsage(); const costMetrics = this.costTracker.calculateCost(totalTokenUsage); const testCostData = { testId: test.id || test.name, sessionId: session.sessionId, costMetrics, executionTime: Date.now() - startTime, success: agentResult.success }; await this.costTracker.trackTestCost(testCostData); } const duration = Date.now() - startTime; console.log(chalk_1.default.green(`✅ Dynamic AI execution completed in ${duration}ms`)); console.log(chalk_1.default.blue(`💰 Total cost: $${session?.totalCost.toFixed(4) || '0.0000'}`)); console.log(chalk_1.default.blue(`🧠 Total tokens: ${session?.totalTokens || 0}`)); return { success: agentResult.success, steps: this.steps, screenshots: this.screenshots, errors: agentResult.success ? [] : [agentResult.result] }; } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error); console.error(chalk_1.default.red(`❌ Dynamic AI execution failed: ${errorMsg}`)); this.addStep('Dynamic AI Execution', `Failed: ${errorMsg}`, 'failed'); return { success: false, steps: this.steps, screenshots: this.screenshots, errors: [errorMsg] }; } } /** * Add execution step (for tracking purposes only) */ addStep(description, result, status) { this.steps.push({ description, result, status, timestamp: new Date(), duration: 0 }); } /** * Get total token usage from AI agent */ getTotalTokenUsage() { const agentStats = this.smartAgent?.getSessionStats(); if (agentStats) { return { promptTokens: agentStats.totalTokens * 0.7, // Estimate completionTokens: agentStats.totalTokens * 0.3, // Estimate totalTokens: agentStats.totalTokens, model: SmartAgentConfig_1.SMART_AGENT_CONFIG.openai.modelName, timestamp: new Date() }; } return { promptTokens: 0, completionTokens: 0, totalTokens: 0, model: 'unknown', timestamp: new Date() }; } /** * Get execution statistics */ async getExecutionStats() { const agentStats = this.smartAgent?.getSessionStats(); return { totalSteps: this.steps.length, successfulSteps: this.steps.filter(s => s.status === 'success').length, failedSteps: this.steps.filter(s => s.status === 'failed').length, totalCost: agentStats?.totalCost || 0, tokenUsage: this.tokenUsage, screenshots: this.screenshots, adaptiveStrategies: [], fastMode: false, cacheStats: { size: 0, hitRate: 0 } }; } /** * Get Smart AI Agent statistics */ getSmartAgentStats() { return this.smartAgent?.getSessionStats() || null; } /** * Clear session and reset */ clearSession() { this.smartAgent?.clearSession(); this.steps = []; this.screenshots = []; this.tokenUsage = []; this.currentSession = null; } /** * Enable/disable Smart AI Agent */ setSmartAgentMode(enabled) { if (!enabled) { throw new Error('Dynamic AI Test Executor requires Smart AI Agent to be enabled'); } console.log(chalk_1.default.blue('🧠 Smart AI Agent is required for dynamic execution')); } /** * Track cost for a test execution (compatibility method) */ async trackTestCost(testId, sessionId, executionTime, success) { if (!this.costTracker) return; const totalTokenUsage = this.getTotalTokenUsage(); const costMetrics = this.costTracker.calculateCost(totalTokenUsage); const testCostData = { testId, sessionId, costMetrics, executionTime, success }; await this.costTracker.trackTestCost(testCostData); } } exports.DynamicAITestExecutor = DynamicAITestExecutor; //# sourceMappingURL=DynamicAITestExecutor.js.map