File size: 20,362 Bytes
bdc8c47
 
 
 
 
 
 
 
 
 
1c7f70e
bdc8c47
b823b0d
bdc8c47
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7f70e
b823b0d
bdc8c47
 
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
 
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
b823b0d
bdc8c47
 
 
 
cc39ae7
bdc8c47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc39ae7
 
 
 
 
 
 
 
 
bdc8c47
 
b823b0d
 
 
02d086e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b823b0d
02d086e
 
b823b0d
 
 
 
02d086e
b823b0d
 
 
 
 
 
 
 
 
 
bdc8c47
 
 
b823b0d
bdc8c47
 
 
 
 
 
 
 
35f09a0
b823b0d
 
bdc8c47
 
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
b823b0d
bdc8c47
 
 
b823b0d
bdc8c47
 
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
b823b0d
 
bdc8c47
 
 
 
 
 
 
 
b823b0d
 
 
 
 
 
 
 
 
bdc8c47
 
 
6aa3dd7
b823b0d
 
bdc8c47
 
 
 
 
 
 
 
 
 
 
 
 
 
b823b0d
 
 
 
 
 
 
 
 
bdc8c47
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
 
 
 
 
 
 
 
 
b823b0d
 
 
 
 
 
 
 
 
bdc8c47
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
 
 
 
 
 
6aa3dd7
35f09a0
 
bbd4ce0
605a49e
35f09a0
02d086e
b823b0d
 
 
 
 
 
 
 
605a49e
b823b0d
 
6aa3dd7
b823b0d
 
 
02d086e
 
 
 
 
6aa3dd7
605a49e
6aa3dd7
b823b0d
35f09a0
605a49e
6aa3dd7
605a49e
b823b0d
 
 
 
 
 
 
605a49e
02d086e
605a49e
 
b823b0d
 
 
 
 
 
 
605a49e
35f09a0
 
 
 
b823b0d
35f09a0
 
 
6aa3dd7
35f09a0
6aa3dd7
 
35f09a0
605a49e
35f09a0
 
 
 
 
 
 
 
605a49e
6aa3dd7
 
b823b0d
 
605a49e
6aa3dd7
02d086e
b823b0d
 
 
 
 
 
 
 
605a49e
b823b0d
 
 
 
 
 
 
 
02d086e
 
 
 
 
 
b823b0d
605a49e
cc2c168
b823b0d
 
 
02d086e
 
 
 
 
 
 
b823b0d
605a49e
 
 
 
 
b823b0d
605a49e
cc2c168
b823b0d
605a49e
 
 
 
cc2c168
ee403e4
 
b823b0d
 
 
 
 
 
 
 
 
 
cc2c168
b823b0d
 
 
 
 
605a49e
cc2c168
b823b0d
 
 
cc2c168
b823b0d
 
 
 
 
 
 
cc2c168
 
b823b0d
cc2c168
 
 
 
 
 
 
 
 
b823b0d
 
 
 
 
 
 
cc2c168
b823b0d
 
cc2c168
6aa3dd7
 
 
cc2c168
6aa3dd7
 
b823b0d
cc2c168
b823b0d
605a49e
b823b0d
 
cc2c168
 
 
b823b0d
 
 
cc2c168
6aa3dd7
 
605a49e
bdc8c47
 
 
 
b823b0d
 
 
 
 
 
 
 
 
 
bdc8c47
 
b823b0d
 
 
 
 
bdc8c47
 
 
 
 
b823b0d
bdc8c47
 
 
 
 
 
 
 
b823b0d
 
 
 
 
 
 
 
 
 
bdc8c47
 
b823b0d
bdc8c47
b823b0d
 
 
bdc8c47
b823b0d
 
bdc8c47
 
 
 
 
 
 
 
 
 
 
b823b0d
 
bdc8c47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc39ae7
 
bdc8c47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a224f7
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
import { Component, inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatListModule } from '@angular/material/list';
import { MatChipsModule } from '@angular/material/chips';
import { MatCardModule } from '@angular/material/card';
import { ApiService } from '../../services/api.service';
import { AuthService } from '../../services/auth.service';
import { HttpClient } from '@angular/common/http';

interface TestResult {
  name: string;
  status: 'PASS' | 'FAIL' | 'RUNNING' | 'SKIP';
  duration_ms?: number;
  error?: string;
  details?: string;
}

interface TestCategory {
  name: string;
  displayName: string;
  tests: TestCase[];
  selected: boolean;
  expanded: boolean;
}

interface TestCase {
  name: string;
  category: string;
  selected: boolean;
  testFn: () => Promise<TestResult>;
}

@Component({
  selector: 'app-test',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatProgressBarModule,
    MatCheckboxModule,
    MatButtonModule,
    MatIconModule,
    MatExpansionModule,
    MatListModule,
    MatChipsModule,
    MatCardModule
  ],
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
  private apiService = inject(ApiService);
  private authService = inject(AuthService);
  private http = inject(HttpClient);

  running = false;
  currentTest: string = '';
  testResults: TestResult[] = [];
  
  categories: TestCategory[] = [
    {
      name: 'auth',
      displayName: 'Authentication Tests',
      tests: [],
      selected: true,
      expanded: false
    },
    {
      name: 'api',
      displayName: 'API Endpoint Tests',
      tests: [],
      selected: true,
      expanded: false
    },
    {
      name: 'validation',
      displayName: 'Validation Tests',
      tests: [],
      selected: true,
      expanded: false
    },
    {
      name: 'integration',
      displayName: 'Integration Tests',
      tests: [],
      selected: true,
      expanded: false
    }
  ];

  allSelected = false;

  get selectedTests(): TestCase[] {
    return this.categories
      .filter(c => c.selected)
      .flatMap(c => c.tests);
  }

  get totalTests(): number {
    return this.categories.reduce((sum, c) => sum + c.tests.length, 0);
  }

  get passedTests(): number {
    return this.testResults.filter(r => r.status === 'PASS').length;
  }

  get failedTests(): number {
    return this.testResults.filter(r => r.status === 'FAIL').length;
  }

  get progress(): number {
    if (this.testResults.length === 0) return 0;
    return (this.testResults.length / this.selectedTests.length) * 100;
  }

  ngOnInit() {
    this.initializeTests();
    this.updateAllSelected();
  }

  updateAllSelected() {
    this.allSelected = this.categories.length > 0 && this.categories.every(c => c.selected);
  }

  onCategorySelectionChange() {
    this.updateAllSelected();
  }

  // Helper method to ensure authentication
  private async ensureAuth(): Promise<boolean> {
    try {
      // Check if we already have a valid token
      const token = this.authService.getToken();
      if (token) {
        // Try to make a simple authenticated request to verify token is still valid
        try {
          await this.apiService.getEnvironment().toPromise();
          return true;
        } catch (error: any) {
          if (error.status === 401) {
            // Token expired, need to re-login
            this.authService.logout();
          } else {
            // Other error, assume auth is ok
            return true;
          }
        }
      }
  
      // Login with test credentials
      const response = await this.http.post('/api/login', {
        username: 'admin',
        password: 'admin'
      }).toPromise() as any;
  
      if (response?.token) {
        this.authService.setToken(response.token);
        this.authService.setUsername(response.username);
        return true;
      }
      return false;
    } catch {
      return false;
    }
  }
  initializeTests() {
    // Authentication Tests
    this.addTest('auth', 'Login with valid credentials', async () => {
      const start = Date.now();
      try {
        const response = await this.http.post('/api/login', {
          username: 'admin',
          password: 'admin'
        }).toPromise() as any;
        
        return {
          name: 'Login with valid credentials',
          status: response?.token ? 'PASS' : 'FAIL',
          duration_ms: Date.now() - start,
          details: response?.token ? 'Successfully authenticated' : 'No token received'
        };
      } catch (error) {
        return {
          name: 'Login with valid credentials',
          status: 'FAIL',
          error: 'Login failed',
          duration_ms: Date.now() - start
        };
      }
    });

    this.addTest('auth', 'Login with invalid credentials', async () => {
      const start = Date.now();
      try {
        await this.http.post('/api/login', {
          username: 'admin',
          password: 'wrong_password_12345'
        }).toPromise();
        
        return {
          name: 'Login with invalid credentials',
          status: 'FAIL',
          error: 'Expected 401 but got success',
          duration_ms: Date.now() - start
        };
      } catch (error: any) {
        return {
          name: 'Login with invalid credentials',
          status: error.status === 401 ? 'PASS' : 'FAIL',
          duration_ms: Date.now() - start,
          details: error.status === 401 ? 'Correctly rejected invalid credentials' : `Unexpected status: ${error.status}`
        };
      }
    });

    // API Endpoint Tests
    this.addTest('api', 'GET /api/environment', async () => {
      const start = Date.now();
      try {
        if (!await this.ensureAuth()) {
          return {
            name: 'GET /api/environment',
            status: 'SKIP',
            error: 'Authentication failed',
            duration_ms: Date.now() - start
          };
        }

        const response = await this.apiService.getEnvironment().toPromise();
        return {
          name: 'GET /api/environment',
          status: response?.work_mode ? 'PASS' : 'FAIL',
          duration_ms: Date.now() - start,
          details: response?.work_mode ? `Work mode: ${response.work_mode}` : 'No work mode returned'
        };
      } catch (error) {
        return {
          name: 'GET /api/environment',
          status: 'FAIL',
          error: 'Failed to get environment',
          duration_ms: Date.now() - start
        };
      }
    });

    this.addTest('api', 'GET /api/projects', async () => {
      const start = Date.now();
      try {
        if (!await this.ensureAuth()) {
          return {
            name: 'GET /api/projects',
            status: 'SKIP',
            error: 'Authentication failed',
            duration_ms: Date.now() - start
          };
        }

        const response = await this.apiService.getProjects().toPromise();
        return {
          name: 'GET /api/projects',
          status: Array.isArray(response) ? 'PASS' : 'FAIL',
          duration_ms: Date.now() - start,
          details: Array.isArray(response) ? `Retrieved ${response.length} projects` : 'Invalid response format'
        };
      } catch (error) {
        return {
          name: 'GET /api/projects',
          status: 'FAIL',
          error: 'Failed to get projects',
          duration_ms: Date.now() - start
        };
      }
    });

    this.addTest('api', 'GET /api/apis', async () => {
      const start = Date.now();
      try {
        if (!await this.ensureAuth()) {
          return {
            name: 'GET /api/apis',
            status: 'SKIP',
            error: 'Authentication failed',
            duration_ms: Date.now() - start
          };
        }

        const response = await this.apiService.getAPIs().toPromise();
        return {
          name: 'GET /api/apis',
          status: Array.isArray(response) ? 'PASS' : 'FAIL',
          duration_ms: Date.now() - start,
          details: Array.isArray(response) ? `Retrieved ${response.length} APIs` : 'Invalid response format'
        };
      } catch (error) {
        return {
          name: 'GET /api/apis',
          status: 'FAIL',
          error: 'Failed to get APIs',
          duration_ms: Date.now() - start
        };
      }
    });

    // Integration Tests
    this.addTest('integration', 'Create and delete project', async () => {
      const start = Date.now();
      let projectId: number | undefined = undefined;
    
      try {
        // Ensure we're authenticated
        if (!await this.ensureAuth()) {
          return {
            name: 'Create and delete project',
            status: 'SKIP',
            error: 'Authentication failed',
            duration_ms: Date.now() - start
          };
        }
    
        // Create test project
        const testProjectName = `test_project_${Date.now()}`;
        const createResponse = await this.apiService.createProject({
          name: testProjectName,
          caption: 'Test Project for Integration Test',
          icon: 'folder',
          description: 'This is a test project',
          default_language: 'Turkish',
          supported_languages: ['tr'],
          timezone: 'Europe/Istanbul',
          region: 'tr-TR'
        }).toPromise() as any;
    
        if (!createResponse?.id) {
          throw new Error('Project creation failed - no ID returned');
        }
    
        projectId = createResponse.id;
    
        // Verify project was created
        const projects = await this.apiService.getProjects().toPromise() as any[];
        const createdProject = projects.find(p => p.id === projectId);
        
        if (!createdProject) {
          throw new Error('Created project not found in project list');
        }
    
        // Delete project
        await this.apiService.deleteProject(projectId!).toPromise();
    
        // Verify project was soft deleted
        const projectsAfterDelete = await this.apiService.getProjects().toPromise() as any[];
        const deletedProject = projectsAfterDelete.find(p => p.id === projectId);
        
        if (deletedProject) {
          throw new Error('Project still visible after deletion');
        }
    
        return {
          name: 'Create and delete project',
          status: 'PASS',
          duration_ms: Date.now() - start,
          details: `Successfully created and deleted project: ${testProjectName}`
        };
      } catch (error: any) {
        // Try to clean up if project was created
        if (projectId !== undefined) {
          try {
            await this.apiService.deleteProject(projectId).toPromise();
          } catch {}
        }
    
        return {
          name: 'Create and delete project',
          status: 'FAIL',
          error: error.message || 'Test failed',
          duration_ms: Date.now() - start
        };
      }
    });
    
    this.addTest('integration', 'API used in intent cannot be deleted', async () => {
      const start = Date.now();
      let testApiName: string | undefined;
      let testProjectId: number | undefined;
    
      try {
        // Ensure we're authenticated
        if (!await this.ensureAuth()) {
          return {
            name: 'API used in intent cannot be deleted',
            status: 'SKIP',
            error: 'Authentication failed',
            duration_ms: Date.now() - start
          };
        }
    
        // 1. Create test API
        testApiName = `test_api_${Date.now()}`;
        await this.apiService.createAPI({
          name: testApiName,
          url: 'https://test.example.com/api',
          method: 'POST',
          timeout_seconds: 10,
          headers: { 'Content-Type': 'application/json' },
          body_template: {},
          retry: {
            retry_count: 3,
            backoff_seconds: 2,
            strategy: 'static'
          }
        }).toPromise();
    
        // 2. Create test project
        const testProjectName = `test_project_${Date.now()}`;
        const createProjectResponse = await this.apiService.createProject({
          name: testProjectName,
          caption: 'Test Project',
          icon: 'folder',
          description: 'Test project for API deletion test',
          default_language: 'Turkish',
          supported_languages: ['tr'],
          timezone: 'Europe/Istanbul',
          region: 'tr-TR'
        }).toPromise() as any;
    
        if (!createProjectResponse?.id) {
          throw new Error('Project creation failed');
        }
    
        testProjectId = createProjectResponse.id;
    
        // 3. Get the first version
        const version = createProjectResponse.versions[0];
        if (!version) {
          throw new Error('No version found in created project');
        }
    
        // 4. Update the version to add an intent that uses our API
        // testProjectId is guaranteed to be a number here
        await this.apiService.updateVersion(testProjectId!, version.id, {
          caption: version.caption,
          general_prompt: 'Test prompt',
          llm: version.llm,
          intents: [{
            name: 'test-intent',
            caption: 'Test Intent',
            locale: 'tr-TR',
            detection_prompt: 'Test detection',
            examples: ['test example'],
            parameters: [],
            action: testApiName,
            fallback_timeout_prompt: 'Timeout',
            fallback_error_prompt: 'Error'
          }],
          last_update_date: version.last_update_date
        }).toPromise();
    
        // 5. Try to delete the API - this should fail with 400
        try {
          await this.apiService.deleteAPI(testApiName).toPromise();
          
          // If deletion succeeded, test failed
          return {
            name: 'API used in intent cannot be deleted',
            status: 'FAIL',
            error: 'API was deleted even though it was in use',
            duration_ms: Date.now() - start
          };
        } catch (deleteError: any) {
          // Check if we got the expected 400 error
          const errorMessage = deleteError.error?.detail || deleteError.message || '';
          const isExpectedError = deleteError.status === 400 && 
                                 errorMessage.includes('API is used');
          
          if (!isExpectedError) {
            console.error('Delete API Error Details:', {
              status: deleteError.status,
              error: deleteError.error,
              message: errorMessage
            });
          }
          
          return {
            name: 'API used in intent cannot be deleted',
            status: isExpectedError ? 'PASS' : 'FAIL',
            duration_ms: Date.now() - start,
            details: isExpectedError 
              ? 'Correctly prevented deletion of API in use' 
              : `Unexpected error: Status ${deleteError.status}, Message: ${errorMessage}`
          };
        }
      } catch (setupError: any) {
        return {
          name: 'API used in intent cannot be deleted',
          status: 'FAIL',
          error: `Test setup failed: ${setupError.message || setupError}`,
          duration_ms: Date.now() - start
        };
      } finally {
        // Cleanup: first delete project, then API
        try {
          if (testProjectId !== undefined) {
            await this.apiService.deleteProject(testProjectId).toPromise();
          }
        } catch {}
        
        try {
          if (testApiName) {
            await this.apiService.deleteAPI(testApiName).toPromise();
          }
        } catch {}
      }
    });
    
    // Validation Tests
    this.addTest('validation', 'Regex validation - valid pattern', async () => {
      const start = Date.now();
      try {
        if (!await this.ensureAuth()) {
          return {
            name: 'Regex validation - valid pattern',
            status: 'SKIP',
            error: 'Authentication failed',
            duration_ms: Date.now() - start
          };
        }

        const response = await this.apiService.validateRegex('^[A-Z]{3}$', 'ABC').toPromise() as any;
        return {
          name: 'Regex validation - valid pattern',
          status: response?.valid && response?.matches ? 'PASS' : 'FAIL',
          duration_ms: Date.now() - start,
          details: response?.valid && response?.matches 
            ? 'Pattern matched successfully' 
            : 'Pattern did not match or validation failed'
        };
      } catch (error) {
        return {
          name: 'Regex validation - valid pattern',
          status: 'FAIL',
          error: 'Validation endpoint failed',
          duration_ms: Date.now() - start
        };
      }
    });

    this.addTest('validation', 'Regex validation - invalid pattern', async () => {
      const start = Date.now();
      try {
        if (!await this.ensureAuth()) {
          return {
            name: 'Regex validation - invalid pattern',
            status: 'SKIP',
            error: 'Authentication failed',
            duration_ms: Date.now() - start
          };
        }

        const response = await this.apiService.validateRegex('[invalid', 'test').toPromise() as any;
        return {
          name: 'Regex validation - invalid pattern',
          status: !response?.valid ? 'PASS' : 'FAIL',
          duration_ms: Date.now() - start,
          details: !response?.valid 
            ? 'Correctly identified invalid regex' 
            : 'Failed to identify invalid regex'
        };
      } catch (error: any) {
        // Some errors are expected for invalid regex
        return {
          name: 'Regex validation - invalid pattern',
          status: 'PASS',
          duration_ms: Date.now() - start,
          details: 'Correctly rejected invalid regex'
        };
      }
    });

    // Update test counts
    this.categories.forEach(cat => {
      const originalName = cat.displayName.split(' (')[0];
      cat.displayName = `${originalName} (${cat.tests.length} tests)`;
    });
  }

  private addTest(category: string, name: string, testFn: () => Promise<TestResult>) {
    const cat = this.categories.find(c => c.name === category);
    if (cat) {
      cat.tests.push({
        name,
        category,
        selected: true,
        testFn
      });
    }
  }

  toggleAll() {
    this.allSelected = !this.allSelected;
    this.categories.forEach(c => c.selected = this.allSelected);
  }

  async runAllTests() {
    this.categories.forEach(c => c.selected = true);
    await this.runTests();
  }

  async runSelectedTests() {
    await this.runTests();
  }

  async runTests() {
    if (this.running) return;

    this.running = true;
    this.testResults = [];
    this.currentTest = '';

    const testsToRun = this.selectedTests;

    for (const test of testsToRun) {
      this.currentTest = test.name;
      
      try {
        const result = await test.testFn();
        this.testResults.push(result);
      } catch (error: any) {
        this.testResults.push({
          name: test.name,
          status: 'FAIL',
          error: error.message || 'Unexpected error'
        });
      }

      // Small delay between tests
      await new Promise(resolve => setTimeout(resolve, 100));
    }

    this.running = false;
    this.currentTest = '';
  }

  stopTests() {
    this.running = false;
    this.currentTest = '';
  }

  getTestResult(testName: string): TestResult | undefined {
    return this.testResults.find(r => r.name === testName);
  }

  getCategoryResults(category: TestCategory): { passed: number; failed: number; total: number } {
    const categoryResults = this.testResults.filter(r => 
      category.tests.some(t => t.name === r.name)
    );

    return {
      passed: categoryResults.filter(r => r.status === 'PASS').length,
      failed: categoryResults.filter(r => r.status === 'FAIL').length,
      total: category.tests.length
    };
  }
}