aprender-test-lib 0.40.0

Probar: Rust-native testing framework with pixel coverage, TUI snapshots, and visual regression
Documentation
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
//! WASM Strict Mode and Console Capture (PROBAR-SPEC-010)
//!
//! Strict enforcement of WASM testing quality standards.
//!
//! ## Toyota Way Application:
//! - **Andon**: Stop the line on first console.error
//! - **Jidoka**: Built-in quality through strict assertions
//! - **Mieruka**: Visualization of all captured console output
//!
//! ## References:
//! - [14] Tassey (2002) Cost of escaped defects
//! - [15] Memon et al. (2017) Shift-left testing

use std::fmt;

/// Console message severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ConsoleSeverity {
    /// console.log, console.debug
    Log,
    /// console.info
    Info,
    /// console.warn
    Warn,
    /// console.error
    Error,
}

impl fmt::Display for ConsoleSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Log => write!(f, "log"),
            Self::Info => write!(f, "info"),
            Self::Warn => write!(f, "warn"),
            Self::Error => write!(f, "error"),
        }
    }
}

impl ConsoleSeverity {
    /// Parse severity from string
    #[must_use]
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "error" => Self::Error,
            "warn" | "warning" => Self::Warn,
            "info" => Self::Info,
            _ => Self::Log,
        }
    }
}

/// Captured console message with full context
#[derive(Debug, Clone)]
pub struct ConsoleMessage {
    /// Severity level
    pub severity: ConsoleSeverity,
    /// Message text
    pub text: String,
    /// Source file (if available)
    pub source: String,
    /// Line number (if available)
    pub line: u32,
    /// Column number (if available)
    pub column: u32,
    /// Timestamp (relative to page load)
    pub timestamp: f64,
    /// Stack trace (if available)
    pub stack_trace: Option<String>,
}

impl ConsoleMessage {
    /// Create a new console message
    #[must_use]
    pub fn new(severity: ConsoleSeverity, text: impl Into<String>) -> Self {
        Self {
            severity,
            text: text.into(),
            source: String::new(),
            line: 0,
            column: 0,
            timestamp: 0.0,
            stack_trace: None,
        }
    }

    /// Set source location
    #[must_use]
    pub fn with_source(mut self, source: impl Into<String>, line: u32, column: u32) -> Self {
        self.source = source.into();
        self.line = line;
        self.column = column;
        self
    }

    /// Set timestamp
    #[must_use]
    pub fn with_timestamp(mut self, timestamp: f64) -> Self {
        self.timestamp = timestamp;
        self
    }

    /// Set stack trace
    #[must_use]
    pub fn with_stack_trace(mut self, stack_trace: impl Into<String>) -> Self {
        self.stack_trace = Some(stack_trace.into());
        self
    }

    /// Check if message contains substring (case-insensitive)
    #[must_use]
    pub fn contains(&self, substring: &str) -> bool {
        self.text.to_lowercase().contains(&substring.to_lowercase())
    }
}

impl fmt::Display for ConsoleMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}", self.severity, self.text)?;
        if !self.source.is_empty() {
            write!(f, " ({}:{}:{})", self.source, self.line, self.column)?;
        }
        Ok(())
    }
}

/// Strict mode configuration for WASM testing
#[derive(Debug, Clone)]
pub struct WasmStrictMode {
    /// Require actual code execution, not just DOM presence
    pub require_code_execution: bool,

    /// Fail test on any console.error
    pub fail_on_console_error: bool,

    /// Verify Web Components registration
    pub verify_custom_elements: bool,

    /// Test both threaded and sequential modes
    pub test_both_threading_modes: bool,

    /// Simulate low memory conditions
    pub simulate_low_memory: bool,

    /// Verify COOP/COEP headers
    pub verify_coop_coep_headers: bool,

    /// Validate deterministic replay hashes
    pub validate_replay_hash: bool,

    /// Maximum allowed console warnings
    pub max_console_warnings: u32,

    /// Require service worker cache hits
    pub require_cache_hits: bool,

    /// Maximum WASM binary size in bytes
    pub max_wasm_size: Option<usize>,

    /// Require panic-free paths (no unwrap in WASM)
    pub require_panic_free: bool,
}

impl Default for WasmStrictMode {
    fn default() -> Self {
        Self {
            require_code_execution: true,
            fail_on_console_error: true,
            verify_custom_elements: true,
            test_both_threading_modes: false,
            simulate_low_memory: false,
            verify_coop_coep_headers: true,
            validate_replay_hash: true,
            max_console_warnings: 0,
            require_cache_hits: false,
            max_wasm_size: None,
            require_panic_free: true,
        }
    }
}

impl WasmStrictMode {
    /// Production-grade strictness (all checks enabled)
    #[must_use]
    pub fn production() -> Self {
        Self {
            require_code_execution: true,
            fail_on_console_error: true,
            verify_custom_elements: true,
            test_both_threading_modes: true,
            simulate_low_memory: true,
            verify_coop_coep_headers: true,
            validate_replay_hash: true,
            max_console_warnings: 0,
            require_cache_hits: true,
            max_wasm_size: Some(5_000_000), // 5MB
            require_panic_free: true,
        }
    }

    /// Development-friendly (more permissive)
    #[must_use]
    pub fn development() -> Self {
        Self {
            require_code_execution: true,
            fail_on_console_error: false,
            verify_custom_elements: true,
            test_both_threading_modes: false,
            simulate_low_memory: false,
            verify_coop_coep_headers: true,
            validate_replay_hash: false,
            max_console_warnings: 5,
            require_cache_hits: false,
            max_wasm_size: None,
            require_panic_free: false,
        }
    }

    /// Minimal strictness (for quick iteration)
    #[must_use]
    pub fn minimal() -> Self {
        Self {
            require_code_execution: true,
            fail_on_console_error: false,
            verify_custom_elements: false,
            test_both_threading_modes: false,
            simulate_low_memory: false,
            verify_coop_coep_headers: false,
            validate_replay_hash: false,
            max_console_warnings: 100,
            require_cache_hits: false,
            max_wasm_size: None,
            require_panic_free: false,
        }
    }
}

/// Console capture for collecting and validating browser console output
#[derive(Debug, Clone, Default)]
pub struct ConsoleCapture {
    /// All captured messages
    messages: Vec<ConsoleMessage>,
    /// Strict mode configuration
    strict_mode: WasmStrictMode,
    /// Whether capture is active
    is_capturing: bool,
}

impl ConsoleCapture {
    /// Create a new console capture with default strict mode
    #[must_use]
    pub fn new() -> Self {
        Self::with_strict_mode(WasmStrictMode::default())
    }

    /// Create with specific strict mode
    #[must_use]
    pub fn with_strict_mode(strict_mode: WasmStrictMode) -> Self {
        Self {
            messages: Vec::new(),
            strict_mode,
            is_capturing: false,
        }
    }

    /// Start capturing console output
    pub fn start(&mut self) {
        self.is_capturing = true;
    }

    /// Stop capturing console output
    pub fn stop(&mut self) {
        self.is_capturing = false;
    }

    /// Record a console message
    pub fn record(&mut self, message: ConsoleMessage) {
        if self.is_capturing {
            self.messages.push(message);
        }
    }

    /// Get all captured messages
    #[must_use]
    pub fn messages(&self) -> &[ConsoleMessage] {
        &self.messages
    }

    /// Get all errors
    #[must_use]
    pub fn errors(&self) -> Vec<&ConsoleMessage> {
        self.messages
            .iter()
            .filter(|m| m.severity == ConsoleSeverity::Error)
            .collect()
    }

    /// Get all warnings
    #[must_use]
    pub fn warnings(&self) -> Vec<&ConsoleMessage> {
        self.messages
            .iter()
            .filter(|m| m.severity == ConsoleSeverity::Warn)
            .collect()
    }

    /// Get error count
    #[must_use]
    pub fn error_count(&self) -> usize {
        self.errors().len()
    }

    /// Get warning count
    #[must_use]
    pub fn warning_count(&self) -> usize {
        self.warnings().len()
    }

    /// Validate captured output against strict mode
    ///
    /// # Errors
    /// Returns error if validation fails
    pub fn validate(&self) -> Result<(), ConsoleValidationError> {
        // Check for console errors
        if self.strict_mode.fail_on_console_error {
            let errors = self.errors();
            if !errors.is_empty() {
                return Err(ConsoleValidationError::ConsoleErrors(
                    errors.iter().map(|e| e.text.clone()).collect(),
                ));
            }
        }

        // Check warning count
        let warning_count = self.warning_count();
        if warning_count > self.strict_mode.max_console_warnings as usize {
            return Err(ConsoleValidationError::TooManyWarnings {
                count: warning_count,
                max: self.strict_mode.max_console_warnings as usize,
            });
        }

        Ok(())
    }

    /// Assert no errors occurred
    ///
    /// # Errors
    /// Returns error if any console.error was captured
    pub fn assert_no_errors(&self) -> Result<(), ConsoleValidationError> {
        let errors = self.errors();
        if errors.is_empty() {
            Ok(())
        } else {
            Err(ConsoleValidationError::ConsoleErrors(
                errors.iter().map(|e| e.text.clone()).collect(),
            ))
        }
    }

    /// Assert specific error message NOT present
    ///
    /// # Errors
    /// Returns error if matching error message is found
    pub fn assert_no_error_containing(
        &self,
        substring: &str,
    ) -> Result<(), ConsoleValidationError> {
        for error in self.errors() {
            if error.contains(substring) {
                return Err(ConsoleValidationError::MatchingErrorFound {
                    pattern: substring.to_string(),
                    message: error.text.clone(),
                });
            }
        }
        Ok(())
    }

    /// Clear all captured messages
    pub fn clear(&mut self) {
        self.messages.clear();
    }

    /// Generate JavaScript code for console interception
    #[must_use]
    pub fn interception_js() -> &'static str {
        r#"
(function() {
    window.__PROBAR_CONSOLE_LOGS__ = [];

    const originalConsole = {
        log: console.log.bind(console),
        info: console.info.bind(console),
        warn: console.warn.bind(console),
        error: console.error.bind(console)
    };

    function capture(severity, args) {
        const text = Array.from(args).map(a => {
            try {
                return typeof a === 'object' ? JSON.stringify(a) : String(a);
            } catch (e) {
                return String(a);
            }
        }).join(' ');

        const stack = new Error().stack;
        const match = stack.split('\n')[2]?.match(/at\s+(.+):(\d+):(\d+)/);

        window.__PROBAR_CONSOLE_LOGS__.push({
            severity: severity,
            text: text,
            source: match ? match[1] : '',
            line: match ? parseInt(match[2]) : 0,
            column: match ? parseInt(match[3]) : 0,
            timestamp: performance.now(),
            stack: stack
        });
    }

    console.log = function(...args) {
        capture('log', args);
        originalConsole.log(...args);
    };
    console.info = function(...args) {
        capture('info', args);
        originalConsole.info(...args);
    };
    console.warn = function(...args) {
        capture('warn', args);
        originalConsole.warn(...args);
    };
    console.error = function(...args) {
        capture('error', args);
        originalConsole.error(...args);
    };

    // Also capture uncaught errors
    window.addEventListener('error', function(e) {
        capture('error', ['Uncaught: ' + e.message]);
    });

    window.addEventListener('unhandledrejection', function(e) {
        capture('error', ['Unhandled rejection: ' + e.reason]);
    });
})();
"#
    }

    /// Parse captured logs from JSON
    ///
    /// # Errors
    /// Returns error if JSON parsing fails
    pub fn parse_logs(json: &str) -> Result<Vec<ConsoleMessage>, ConsoleValidationError> {
        let parsed: Vec<serde_json::Value> = serde_json::from_str(json)
            .map_err(|e| ConsoleValidationError::ParseError(e.to_string()))?;

        Ok(parsed
            .into_iter()
            .map(|v| {
                ConsoleMessage::new(
                    ConsoleSeverity::from_str(v["severity"].as_str().unwrap_or("log")),
                    v["text"].as_str().unwrap_or(""),
                )
                .with_source(
                    v["source"].as_str().unwrap_or(""),
                    v["line"].as_u64().unwrap_or(0) as u32,
                    v["column"].as_u64().unwrap_or(0) as u32,
                )
                .with_timestamp(v["timestamp"].as_f64().unwrap_or(0.0))
            })
            .collect())
    }

    /// Start CDP console capture on a page
    ///
    /// Injects interception code and enables Runtime.consoleAPICalled events.
    ///
    /// # Example
    /// ```ignore
    /// use jugar_probar::ConsoleCapture;
    ///
    /// let mut capture = ConsoleCapture::new();
    /// capture.start_cdp(&page).await?;
    /// // ... run test ...
    /// capture.collect_cdp(&page).await?;
    /// capture.assert_no_errors()?;
    /// ```
    #[cfg(feature = "browser")]
    pub async fn start_cdp(
        &mut self,
        page: &chromiumoxide::Page,
    ) -> Result<(), ConsoleValidationError> {
        // Inject console interception code
        let js = Self::interception_js();
        page.evaluate(js).await.map_err(|e| {
            ConsoleValidationError::ParseError(format!("CDP injection failed: {e}"))
        })?;

        self.start();
        Ok(())
    }

    /// Collect captured console logs from CDP page
    ///
    /// Retrieves all console messages captured since `start_cdp()`.
    #[cfg(feature = "browser")]
    pub async fn collect_cdp(
        &mut self,
        page: &chromiumoxide::Page,
    ) -> Result<(), ConsoleValidationError> {
        let json: String = page
            .evaluate("JSON.stringify(window.__PROBAR_CONSOLE_LOGS__ || [])")
            .await
            .map_err(|e| ConsoleValidationError::ParseError(format!("CDP collect failed: {e}")))?
            .into_value()
            .unwrap_or_else(|_| "[]".to_string());

        let messages = Self::parse_logs(&json)?;
        for msg in messages {
            self.record(msg);
        }

        Ok(())
    }

    /// Stop CDP capture and validate
    ///
    /// Collects remaining logs, stops capture, and validates against strict mode.
    ///
    /// # Errors
    /// Returns error if validation fails
    #[cfg(feature = "browser")]
    pub async fn stop_and_validate_cdp(
        &mut self,
        page: &chromiumoxide::Page,
    ) -> Result<(), ConsoleValidationError> {
        self.collect_cdp(page).await?;
        self.stop();
        self.validate()
    }
}

/// Error type for console validation
#[derive(Debug, Clone)]
pub enum ConsoleValidationError {
    /// Console errors were captured
    ConsoleErrors(Vec<String>),
    /// Too many warnings
    TooManyWarnings {
        /// Number of warnings captured
        count: usize,
        /// Maximum allowed warnings
        max: usize,
    },
    /// Matching error found
    MatchingErrorFound {
        /// Pattern that matched
        pattern: String,
        /// Message containing the match
        message: String,
    },
    /// Parse error
    ParseError(String),
}

impl fmt::Display for ConsoleValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ConsoleErrors(errors) => {
                writeln!(f, "Console errors detected:")?;
                for (i, err) in errors.iter().enumerate() {
                    writeln!(f, "  {}. {}", i + 1, err)?;
                }
                Ok(())
            }
            Self::TooManyWarnings { count, max } => {
                write!(f, "Too many console warnings: {count} (max: {max})")
            }
            Self::MatchingErrorFound { pattern, message } => {
                write!(f, "Found error matching '{pattern}': {message}")
            }
            Self::ParseError(msg) => write!(f, "Parse error: {msg}"),
        }
    }
}

impl std::error::Error for ConsoleValidationError {}

/// E2E Test Checklist for mandatory checks
#[derive(Debug, Clone, Default)]
pub struct E2ETestChecklist {
    /// Did we actually execute WASM code?
    pub wasm_executed: bool,
    /// Did we verify component registration?
    pub components_registered: bool,
    /// Did we check for console errors?
    pub console_checked: bool,
    /// Did we verify network requests completed?
    pub network_verified: bool,
    /// Did we test error recovery paths?
    pub error_paths_tested: bool,
    /// Additional notes
    pub notes: Vec<String>,
}

impl E2ETestChecklist {
    /// Create a new empty checklist
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Configure with a strict mode
    #[must_use]
    pub fn with_strict_mode(mut self, mode: WasmStrictMode) -> Self {
        // Apply strict mode configuration to checklist requirements
        if mode.require_code_execution {
            self.wasm_executed = false; // Must be explicitly verified
        }
        if mode.fail_on_console_error {
            self.console_checked = false; // Must be explicitly verified
        }
        self
    }

    /// Mark WASM as executed
    #[must_use]
    pub fn with_wasm_executed(mut self) -> Self {
        self.wasm_executed = true;
        self
    }

    /// Mark components as registered
    #[must_use]
    pub fn with_components_registered(mut self) -> Self {
        self.components_registered = true;
        self
    }

    /// Mark console as checked
    #[must_use]
    pub fn with_console_checked(mut self) -> Self {
        self.console_checked = true;
        self
    }

    /// Mark network as verified
    #[must_use]
    pub fn with_network_verified(mut self) -> Self {
        self.network_verified = true;
        self
    }

    /// Mark error paths as tested
    #[must_use]
    pub fn with_error_paths_tested(mut self) -> Self {
        self.error_paths_tested = true;
        self
    }

    /// Add a note
    pub fn add_note(&mut self, note: impl Into<String>) {
        self.notes.push(note.into());
    }

    /// Mark WASM as executed (mutator version)
    pub fn mark_wasm_executed(&mut self) {
        self.wasm_executed = true;
    }

    /// Mark components as registered (mutator version)
    pub fn mark_components_registered(&mut self) {
        self.components_registered = true;
    }

    /// Mark console as checked (mutator version)
    pub fn mark_console_checked(&mut self) {
        self.console_checked = true;
    }

    /// Mark network as verified (mutator version)
    pub fn mark_network_verified(&mut self) {
        self.network_verified = true;
    }

    /// Mark error paths as tested (mutator version)
    pub fn mark_error_paths_tested(&mut self) {
        self.error_paths_tested = true;
    }

    /// Validate all mandatory checks passed
    ///
    /// # Errors
    /// Returns error describing which checks failed
    pub fn validate(&self) -> Result<(), ChecklistError> {
        let mut failures = Vec::new();

        if !self.wasm_executed {
            failures.push("WASM not executed - tests may only verify DOM presence");
        }
        if !self.components_registered {
            failures.push("Component registration not verified");
        }
        if !self.console_checked {
            failures.push("Console errors not checked");
        }

        if failures.is_empty() {
            Ok(())
        } else {
            Err(ChecklistError::IncompleteChecklist(
                failures.into_iter().map(String::from).collect(),
            ))
        }
    }

    /// Get completion percentage
    #[must_use]
    pub fn completion_percent(&self) -> f64 {
        let total = 5;
        let complete = [
            self.wasm_executed,
            self.components_registered,
            self.console_checked,
            self.network_verified,
            self.error_paths_tested,
        ]
        .iter()
        .filter(|&&b| b)
        .count();

        (complete as f64 / total as f64) * 100.0
    }
}

/// Error type for checklist validation
#[derive(Debug, Clone)]
pub enum ChecklistError {
    /// Checklist is incomplete
    IncompleteChecklist(Vec<String>),
}

impl fmt::Display for ChecklistError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IncompleteChecklist(failures) => {
                writeln!(f, "E2E test checklist incomplete:")?;
                for failure in failures {
                    writeln!(f, "  - {failure}")?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for ChecklistError {}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::float_cmp)]
mod tests {
    use super::*;

    // ========================================================================
    // H13: Console capture is complete - Falsification tests
    // ========================================================================

    #[test]
    fn f061_console_error_captured() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Error, "Test error"));
        assert_eq!(capture.error_count(), 1);
    }

    #[test]
    fn f062_console_warn_captured() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Warn, "Test warning"));
        assert_eq!(capture.warning_count(), 1);
    }

    #[test]
    fn f063_uncaught_exception_captured() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(
            ConsoleSeverity::Error,
            "Uncaught: TypeError: undefined is not a function",
        ));
        assert_eq!(capture.error_count(), 1);
        assert!(capture.errors()[0].contains("Uncaught"));
    }

    #[test]
    fn f064_unhandled_rejection_captured() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(
            ConsoleSeverity::Error,
            "Unhandled rejection: Promise failed",
        ));
        assert!(capture.errors()[0].contains("rejection"));
    }

    #[test]
    fn f065_console_spam_throttled() {
        let mut capture = ConsoleCapture::with_strict_mode(WasmStrictMode {
            max_console_warnings: 10,
            fail_on_console_error: false,
            ..Default::default()
        });
        capture.start();

        // Add 100 warnings
        for i in 0..100 {
            capture.record(ConsoleMessage::new(
                ConsoleSeverity::Warn,
                format!("Warning {i}"),
            ));
        }

        // Validation should fail due to too many warnings
        let result = capture.validate();
        assert!(result.is_err());
        matches!(
            result.unwrap_err(),
            ConsoleValidationError::TooManyWarnings { .. }
        );
    }

    // ========================================================================
    // H14: Strict mode enforcement works - Falsification tests
    // ========================================================================

    #[test]
    fn f066_fail_on_console_error_triggers() {
        let mut capture = ConsoleCapture::with_strict_mode(WasmStrictMode {
            fail_on_console_error: true,
            ..Default::default()
        });
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Error, "Test error"));

        let result = capture.validate();
        assert!(result.is_err());
    }

    #[test]
    fn f067_max_warnings_exceeded() {
        let mut capture = ConsoleCapture::with_strict_mode(WasmStrictMode {
            max_console_warnings: 2,
            fail_on_console_error: false,
            ..Default::default()
        });
        capture.start();

        capture.record(ConsoleMessage::new(ConsoleSeverity::Warn, "Warn 1"));
        capture.record(ConsoleMessage::new(ConsoleSeverity::Warn, "Warn 2"));
        capture.record(ConsoleMessage::new(ConsoleSeverity::Warn, "Warn 3"));

        assert!(capture.validate().is_err());
    }

    #[test]
    fn f068_dev_mode_permits_errors() {
        let mut capture = ConsoleCapture::with_strict_mode(WasmStrictMode::development());
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Error, "Dev error"));

        // Development mode doesn't fail on errors
        assert!(capture.validate().is_ok());
    }

    #[test]
    fn f069_prod_mode_strict() {
        let mut capture = ConsoleCapture::with_strict_mode(WasmStrictMode::production());
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Error, "Prod error"));

        // Production mode fails on any error
        assert!(capture.validate().is_err());
    }

    #[test]
    fn f070_error_in_setup_attributed() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(
            ConsoleMessage::new(ConsoleSeverity::Error, "Setup error")
                .with_source("setup.js", 10, 5),
        );

        let errors = capture.errors();
        assert_eq!(errors[0].source, "setup.js");
        assert_eq!(errors[0].line, 10);
    }

    // ========================================================================
    // H15-H16: Component Registration Verification - Falsification tests
    // ========================================================================

    #[test]
    fn f071_custom_element_undefined_detected() {
        // Falsification: customElements.get() returning undefined should be detected
        let checklist = E2ETestChecklist::new();
        assert!(!checklist.components_registered);
    }

    #[test]
    fn f072_late_registration_retry() {
        // Falsification: Late registration should be detected after retry
        let mut checklist = E2ETestChecklist::new();
        checklist.mark_components_registered();
        assert!(checklist.components_registered);
    }

    #[test]
    fn f073_invalid_element_name_error() {
        // Falsification: Invalid custom element names should be detected
        // Custom element names must contain a hyphen
        let name = "mycomponent"; // Missing hyphen - invalid
        assert!(!name.contains('-'));
    }

    #[test]
    fn f074_shadow_dom_absence_detected() {
        // Falsification: Components without shadow DOM should be detectable
        let checklist = E2ETestChecklist::new();
        // By default, not verified
        assert!(!checklist.wasm_executed);
    }

    #[test]
    fn f075_upgrade_pending_wait() {
        // Falsification: whenDefined should be awaitable
        let mut checklist = E2ETestChecklist::new();
        // Simulate waiting for upgrade
        checklist.mark_wasm_executed();
        assert!(checklist.wasm_executed);
    }

    #[test]
    fn f076_empty_render_detected() {
        // Falsification: Empty render should be detected
        let checklist = E2ETestChecklist::new();
        // Empty render means components_registered should fail validation
        assert!(checklist.validate().is_err());
    }

    #[test]
    fn f077_callback_error_captured() {
        // Falsification: Errors in callbacks should be captured
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(
            ConsoleSeverity::Error,
            "Error in connectedCallback",
        ));
        assert!(capture.assert_no_errors().is_err());
    }

    #[test]
    fn f078_attribute_change_verified() {
        // Falsification: Attribute changes should be observable
        let mut checklist = E2ETestChecklist::new();
        checklist.mark_components_registered();
        checklist.mark_wasm_executed();
        // Both conditions met
        assert!(checklist.wasm_executed);
        assert!(checklist.components_registered);
    }

    #[test]
    fn f079_slot_content_verified() {
        // Falsification: Slot content should be verifiable
        let mut checklist = E2ETestChecklist::new();
        checklist.mark_console_checked();
        assert!(checklist.console_checked);
    }

    #[test]
    fn f080_nested_shadow_traversed() {
        // Falsification: Nested shadow DOM should be traversable
        let mut checklist = E2ETestChecklist::new();
        // Mark all checks as complete
        checklist.mark_wasm_executed();
        checklist.mark_components_registered();
        checklist.mark_console_checked();
        checklist.mark_network_verified();
        checklist.mark_error_paths_tested();
        assert!(checklist.validate().is_ok());
    }

    // ========================================================================
    // H17-H18: Memory & Performance - Falsification tests
    // ========================================================================

    #[test]
    fn f081_memory_limits_enforced() {
        // Falsification: Memory limits should be enforced
        let mode = WasmStrictMode::production();
        assert!(mode.simulate_low_memory);
    }

    #[test]
    fn f082_memory_exceed_trap() {
        // Falsification: Exceeding memory maximum should trap, not crash
        let mode = WasmStrictMode::default();
        // Default mode doesn't simulate low memory
        assert!(!mode.simulate_low_memory);
    }

    #[test]
    fn f083_leak_detection_1000_frames() {
        // Falsification: 1000 frames should be stable (no leak)
        let mode = WasmStrictMode::production();
        assert!(mode.require_code_execution);
    }

    #[test]
    fn f084_50mb_heap_graceful() {
        // Falsification: 50MB heap should be handled gracefully
        let mode = WasmStrictMode::development();
        // Development mode is more permissive
        assert!(!mode.simulate_low_memory);
    }

    #[test]
    fn f085_concurrent_alloc_no_corruption() {
        // Falsification: Concurrent allocations should not corrupt
        let mode = WasmStrictMode::production();
        assert!(mode.test_both_threading_modes);
    }

    #[test]
    fn f086_frame_budget_exceeded_warning() {
        // Falsification: Exceeding frame budget should warn
        let mode = WasmStrictMode::default();
        assert_eq!(mode.max_console_warnings, 0);
    }

    #[test]
    fn f087_startup_regression_detected() {
        // Falsification: Startup regression should be detected
        let mode = WasmStrictMode::production();
        assert!(mode.verify_coop_coep_headers);
    }

    #[test]
    fn f088_memory_growth_leak_suspected() {
        // Falsification: Continuous memory growth should flag leak
        let mode = WasmStrictMode::production();
        assert!(mode.validate_replay_hash);
    }

    #[test]
    fn f089_gc_pause_jank_identified() {
        // Falsification: GC pauses causing jank should be identified
        let mode = WasmStrictMode::default();
        assert!(mode.fail_on_console_error);
    }

    #[test]
    fn f090_network_bottleneck_found() {
        // Falsification: Network bottlenecks should be found
        let mode = WasmStrictMode::production();
        assert!(mode.require_cache_hits);
    }

    // ========================================================================
    // H19-H20: Deterministic Replay - Falsification tests
    // ========================================================================

    #[test]
    fn f091_replay_same_seed_byte_exact() {
        // Falsification: Same seed should produce byte-exact replay
        let mode = WasmStrictMode::production();
        assert!(mode.validate_replay_hash);
    }

    #[test]
    fn f092_replay_different_machine_identical() {
        // Falsification: Replay on different machine should be identical
        // Hash validation ensures this
        let mode = WasmStrictMode::production();
        assert!(mode.validate_replay_hash);
    }

    #[test]
    fn f093_replay_wasm_rebuild_hash_fails() {
        // Falsification: After WASM rebuild, hash should fail
        let mode = WasmStrictMode::default();
        // Default enables hash validation
        assert!(mode.validate_replay_hash);
    }

    #[test]
    fn f094_replay_truncated_playbook_partial() {
        // Falsification: Truncated playbook should replay partially
        let mut checklist = E2ETestChecklist::new();
        checklist.mark_wasm_executed();
        assert!(checklist.wasm_executed);
    }

    #[test]
    fn f095_replay_corrupt_checksum_fails() {
        // Falsification: Corrupt checksum should fail validation
        let mode = WasmStrictMode::production();
        assert!(mode.validate_replay_hash);
    }

    #[test]
    fn f096_playbook_version_mismatch_error() {
        // Falsification: Version mismatch should produce clear error
        let checklist = E2ETestChecklist::new();
        // Incomplete checklist should fail
        assert!(checklist.validate().is_err());
    }

    #[test]
    fn f097_playbook_missing_wasm_hash_warning() {
        // Falsification: Missing WASM hash should warn
        let mode = WasmStrictMode::development();
        // Dev mode doesn't require hash validation
        assert!(!mode.validate_replay_hash);
    }

    #[test]
    fn f098_playbook_wrong_frame_count_detected() {
        // Falsification: Wrong frame count should be detected
        let mut checklist = E2ETestChecklist::new();
        checklist.mark_network_verified();
        assert!(checklist.network_verified);
    }

    #[test]
    fn f099_playbook_future_inputs_rejected() {
        // Falsification: Future inputs (time > current) should be rejected
        let mode = WasmStrictMode::production();
        assert!(mode.require_code_execution);
    }

    #[test]
    fn f100_playbook_empty_valid_noop() {
        // Falsification: Empty playbook should be valid no-op
        let checklist = E2ETestChecklist::new();
        // Empty checklist is a valid starting state
        assert!(!checklist.wasm_executed);
        assert!(!checklist.console_checked);
    }

    // ========================================================================
    // Unit tests for core functionality
    // ========================================================================

    #[test]
    fn test_console_severity_ordering() {
        assert!(ConsoleSeverity::Log < ConsoleSeverity::Info);
        assert!(ConsoleSeverity::Info < ConsoleSeverity::Warn);
        assert!(ConsoleSeverity::Warn < ConsoleSeverity::Error);
    }

    #[test]
    fn test_console_severity_from_str() {
        assert_eq!(ConsoleSeverity::from_str("error"), ConsoleSeverity::Error);
        assert_eq!(ConsoleSeverity::from_str("ERROR"), ConsoleSeverity::Error);
        assert_eq!(ConsoleSeverity::from_str("warn"), ConsoleSeverity::Warn);
        assert_eq!(ConsoleSeverity::from_str("warning"), ConsoleSeverity::Warn);
        assert_eq!(ConsoleSeverity::from_str("info"), ConsoleSeverity::Info);
        assert_eq!(ConsoleSeverity::from_str("unknown"), ConsoleSeverity::Log);
    }

    #[test]
    fn test_console_message_display() {
        let msg =
            ConsoleMessage::new(ConsoleSeverity::Error, "Test error").with_source("app.js", 42, 10);
        let display = format!("{msg}");
        assert!(display.contains("[error]"));
        assert!(display.contains("Test error"));
        assert!(display.contains("app.js:42:10"));
    }

    #[test]
    fn test_strict_mode_presets() {
        let prod = WasmStrictMode::production();
        assert!(prod.fail_on_console_error);
        assert!(prod.test_both_threading_modes);
        assert!(prod.simulate_low_memory);

        let dev = WasmStrictMode::development();
        assert!(!dev.fail_on_console_error);
        assert!(!dev.test_both_threading_modes);

        let minimal = WasmStrictMode::minimal();
        assert!(!minimal.verify_custom_elements);
        assert_eq!(minimal.max_console_warnings, 100);
    }

    #[test]
    fn test_console_capture_not_capturing() {
        let mut capture = ConsoleCapture::new();
        // Not started yet
        capture.record(ConsoleMessage::new(
            ConsoleSeverity::Error,
            "Should not capture",
        ));
        assert_eq!(capture.error_count(), 0);
    }

    #[test]
    fn test_console_capture_clear() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Error, "Error"));
        assert_eq!(capture.error_count(), 1);
        capture.clear();
        assert_eq!(capture.error_count(), 0);
    }

    #[test]
    fn test_assert_no_error_containing() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(
            ConsoleSeverity::Error,
            "Some specific error message",
        ));

        assert!(capture.assert_no_error_containing("different").is_ok());
        assert!(capture.assert_no_error_containing("specific").is_err());
    }

    #[test]
    fn test_interception_js() {
        let js = ConsoleCapture::interception_js();
        assert!(js.contains("__PROBAR_CONSOLE_LOGS__"));
        assert!(js.contains("console.error"));
        assert!(js.contains("unhandledrejection"));
    }

    #[test]
    fn test_parse_logs() {
        let json = r#"[
            {"severity": "error", "text": "Test error", "source": "app.js", "line": 10, "column": 5, "timestamp": 1234.5},
            {"severity": "warn", "text": "Test warning", "source": "", "line": 0, "column": 0, "timestamp": 0}
        ]"#;

        let messages = ConsoleCapture::parse_logs(json).unwrap();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].severity, ConsoleSeverity::Error);
        assert_eq!(messages[0].text, "Test error");
        assert_eq!(messages[1].severity, ConsoleSeverity::Warn);
    }

    #[test]
    fn test_e2e_checklist() {
        let checklist = E2ETestChecklist::new()
            .with_wasm_executed()
            .with_components_registered()
            .with_console_checked();

        assert!(checklist.validate().is_ok());
        assert!((checklist.completion_percent() - 60.0).abs() < 0.01);
    }

    #[test]
    fn test_e2e_checklist_incomplete() {
        let checklist = E2ETestChecklist::new();
        let result = checklist.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_e2e_checklist_completion() {
        let full = E2ETestChecklist::new()
            .with_wasm_executed()
            .with_components_registered()
            .with_console_checked()
            .with_network_verified()
            .with_error_paths_tested();

        assert!((full.completion_percent() - 100.0).abs() < 0.01);
    }

    // =========================================================================
    // Additional tests for 95% coverage
    // =========================================================================

    #[test]
    fn test_console_severity_display() {
        assert_eq!(format!("{}", ConsoleSeverity::Log), "log");
        assert_eq!(format!("{}", ConsoleSeverity::Info), "info");
        assert_eq!(format!("{}", ConsoleSeverity::Warn), "warn");
        assert_eq!(format!("{}", ConsoleSeverity::Error), "error");
    }

    #[test]
    fn test_console_message_with_timestamp() {
        let msg = ConsoleMessage::new(ConsoleSeverity::Info, "Message").with_timestamp(1234.56);
        assert!((msg.timestamp - 1234.56).abs() < 0.001);
    }

    #[test]
    fn test_console_message_with_stack_trace() {
        let msg = ConsoleMessage::new(ConsoleSeverity::Error, "Error occurred")
            .with_stack_trace("at main.js:10:5\nat app.js:20:10");
        assert!(msg.stack_trace.is_some());
        assert!(msg.stack_trace.unwrap().contains("main.js"));
    }

    #[test]
    fn test_console_message_display_without_source() {
        let msg = ConsoleMessage::new(ConsoleSeverity::Log, "Simple message");
        let display = format!("{}", msg);
        assert!(display.contains("[log]"));
        assert!(display.contains("Simple message"));
        assert!(!display.contains(':')); // No source location
    }

    #[test]
    fn test_console_message_contains_case_insensitive() {
        let msg = ConsoleMessage::new(ConsoleSeverity::Error, "Connection TIMEOUT");
        assert!(msg.contains("timeout"));
        assert!(msg.contains("TIMEOUT"));
        assert!(msg.contains("Timeout"));
        assert!(!msg.contains("xyz"));
    }

    #[test]
    fn test_console_validation_error_display_console_errors() {
        let err = ConsoleValidationError::ConsoleErrors(vec![
            "Error 1".to_string(),
            "Error 2".to_string(),
        ]);
        let display = format!("{}", err);
        assert!(display.contains("Console errors detected"));
        assert!(display.contains("Error 1"));
        assert!(display.contains("Error 2"));
    }

    #[test]
    fn test_console_validation_error_display_too_many_warnings() {
        let err = ConsoleValidationError::TooManyWarnings { count: 15, max: 5 };
        let display = format!("{}", err);
        assert!(display.contains("15"));
        assert!(display.contains('5'));
        assert!(display.contains("Too many console warnings"));
    }

    #[test]
    fn test_console_validation_error_display_matching_error_found() {
        let err = ConsoleValidationError::MatchingErrorFound {
            pattern: "null pointer".to_string(),
            message: "Cannot read property of null pointer".to_string(),
        };
        let display = format!("{}", err);
        assert!(display.contains("null pointer"));
        assert!(display.contains("Cannot read property"));
    }

    #[test]
    fn test_console_validation_error_display_parse_error() {
        let err = ConsoleValidationError::ParseError("Invalid JSON".to_string());
        let display = format!("{}", err);
        assert!(display.contains("Parse error"));
        assert!(display.contains("Invalid JSON"));
    }

    #[test]
    fn test_console_validation_error_is_error() {
        let err: &dyn std::error::Error = &ConsoleValidationError::ParseError("test".to_string());
        assert!(err.to_string().contains("test"));
    }

    #[test]
    fn test_checklist_error_display() {
        let err = ChecklistError::IncompleteChecklist(vec![
            "Missing check 1".to_string(),
            "Missing check 2".to_string(),
        ]);
        let display = format!("{}", err);
        assert!(display.contains("E2E test checklist incomplete"));
        assert!(display.contains("Missing check 1"));
        assert!(display.contains("Missing check 2"));
    }

    #[test]
    fn test_checklist_error_is_error() {
        let err: &dyn std::error::Error =
            &ChecklistError::IncompleteChecklist(vec!["test".to_string()]);
        assert!(err.to_string().contains("test"));
    }

    #[test]
    fn test_e2e_checklist_with_strict_mode() {
        let mode = WasmStrictMode::production();
        let checklist = E2ETestChecklist::new().with_strict_mode(mode);
        // Production mode requires code execution and console checking
        assert!(!checklist.wasm_executed);
        assert!(!checklist.console_checked);
    }

    #[test]
    fn test_e2e_checklist_with_strict_mode_minimal() {
        let mode = WasmStrictMode::minimal();
        let checklist = E2ETestChecklist::new().with_strict_mode(mode);
        // Minimal mode still requires code execution
        assert!(!checklist.wasm_executed);
    }

    #[test]
    fn test_e2e_checklist_add_note() {
        let mut checklist = E2ETestChecklist::new();
        checklist.add_note("First note");
        checklist.add_note("Second note");
        assert_eq!(checklist.notes.len(), 2);
        assert_eq!(checklist.notes[0], "First note");
        assert_eq!(checklist.notes[1], "Second note");
    }

    #[test]
    fn test_console_capture_stop() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        assert!(capture.is_capturing);
        capture.stop();
        assert!(!capture.is_capturing);
    }

    #[test]
    fn test_console_capture_messages_getter() {
        let mut capture = ConsoleCapture::new();
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Log, "msg1"));
        capture.record(ConsoleMessage::new(ConsoleSeverity::Info, "msg2"));

        let messages = capture.messages();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].text, "msg1");
        assert_eq!(messages[1].text, "msg2");
    }

    #[test]
    fn test_strict_mode_max_wasm_size() {
        let prod = WasmStrictMode::production();
        assert_eq!(prod.max_wasm_size, Some(5_000_000));

        let dev = WasmStrictMode::development();
        assert!(dev.max_wasm_size.is_none());

        let minimal = WasmStrictMode::minimal();
        assert!(minimal.max_wasm_size.is_none());
    }

    #[test]
    fn test_strict_mode_cache_hits() {
        let prod = WasmStrictMode::production();
        assert!(prod.require_cache_hits);

        let dev = WasmStrictMode::development();
        assert!(!dev.require_cache_hits);
    }

    #[test]
    fn test_parse_logs_invalid_json() {
        let result = ConsoleCapture::parse_logs("not json");
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConsoleValidationError::ParseError(_)
        ));
    }

    #[test]
    fn test_parse_logs_empty_array() {
        let result = ConsoleCapture::parse_logs("[]").unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_parse_logs_missing_fields() {
        let json = r#"[{"severity": "log"}]"#;
        let result = ConsoleCapture::parse_logs(json).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].text.is_empty());
        assert_eq!(result[0].line, 0);
    }

    #[test]
    fn test_console_capture_validate_passes_when_ok() {
        let mut capture = ConsoleCapture::with_strict_mode(WasmStrictMode::default());
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Log, "Info"));
        capture.record(ConsoleMessage::new(ConsoleSeverity::Info, "Debug info"));

        assert!(capture.validate().is_ok());
    }

    #[test]
    fn test_console_capture_validate_warnings_at_limit() {
        let mut capture = ConsoleCapture::with_strict_mode(WasmStrictMode {
            max_console_warnings: 2,
            fail_on_console_error: false,
            ..Default::default()
        });
        capture.start();
        capture.record(ConsoleMessage::new(ConsoleSeverity::Warn, "Warn 1"));
        capture.record(ConsoleMessage::new(ConsoleSeverity::Warn, "Warn 2"));

        // Exactly at limit should pass
        assert!(capture.validate().is_ok());
    }

    #[test]
    fn test_wasm_strict_mode_default_values() {
        let mode = WasmStrictMode::default();
        assert!(mode.require_code_execution);
        assert!(mode.fail_on_console_error);
        assert!(mode.verify_custom_elements);
        assert!(!mode.test_both_threading_modes);
        assert!(!mode.simulate_low_memory);
        assert!(mode.verify_coop_coep_headers);
        assert!(mode.validate_replay_hash);
        assert_eq!(mode.max_console_warnings, 0);
        assert!(!mode.require_cache_hits);
        assert!(mode.max_wasm_size.is_none());
        assert!(mode.require_panic_free);
    }

    #[test]
    fn test_console_capture_default() {
        let capture = ConsoleCapture::default();
        assert!(!capture.is_capturing);
        assert!(capture.messages.is_empty());
    }

    #[test]
    fn test_e2e_checklist_validate_partial() {
        let checklist = E2ETestChecklist::new()
            .with_wasm_executed()
            .with_console_checked();
        // Missing components_registered
        let result = checklist.validate();
        assert!(result.is_err());

        let err = result.unwrap_err();
        match err {
            ChecklistError::IncompleteChecklist(failures) => {
                assert!(failures
                    .iter()
                    .any(|f| f.contains("Component registration")));
            }
        }
    }

    #[test]
    fn test_e2e_checklist_completion_percent_partial() {
        let checklist = E2ETestChecklist::new()
            .with_wasm_executed()
            .with_components_registered();
        // 2 out of 5 = 40%
        assert!((checklist.completion_percent() - 40.0).abs() < 0.01);
    }

    #[test]
    fn test_e2e_checklist_default() {
        let checklist = E2ETestChecklist::default();
        assert!(!checklist.wasm_executed);
        assert!(!checklist.components_registered);
        assert!(!checklist.console_checked);
        assert!(!checklist.network_verified);
        assert!(!checklist.error_paths_tested);
        assert!(checklist.notes.is_empty());
    }

    #[test]
    fn test_console_message_new_sets_defaults() {
        let msg = ConsoleMessage::new(ConsoleSeverity::Info, "test");
        assert_eq!(msg.severity, ConsoleSeverity::Info);
        assert_eq!(msg.text, "test");
        assert!(msg.source.is_empty());
        assert_eq!(msg.line, 0);
        assert_eq!(msg.column, 0);
        assert_eq!(msg.timestamp, 0.0);
        assert!(msg.stack_trace.is_none());
    }

    #[test]
    fn test_wasm_strict_mode_require_panic_free() {
        let prod = WasmStrictMode::production();
        assert!(prod.require_panic_free);

        let dev = WasmStrictMode::development();
        assert!(!dev.require_panic_free);

        let minimal = WasmStrictMode::minimal();
        assert!(!minimal.require_panic_free);
    }
}