aprender-test-lib 0.29.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
//! Test Sharding for Distributed Execution (Feature G.5)
//!
//! Enables parallel test execution across multiple machines in CI/CD pipelines.
//! Implements deterministic test distribution for reproducible sharding.

use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

/// Shard configuration for distributed test execution
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShardConfig {
    /// Current shard index (1-based)
    pub current: u32,
    /// Total number of shards
    pub total: u32,
}

impl ShardConfig {
    /// Create a new shard configuration
    ///
    /// # Panics
    ///
    /// Panics if `current` is 0, greater than `total`, or `total` is 0.
    #[must_use]
    pub fn new(current: u32, total: u32) -> Self {
        assert!(total > 0, "Total shards must be greater than 0");
        assert!(
            current > 0,
            "Current shard must be 1-based (greater than 0)"
        );
        assert!(
            current <= total,
            "Current shard ({current}) cannot exceed total ({total})"
        );

        Self { current, total }
    }

    /// Parse shard config from CLI string format "N/M"
    ///
    /// # Errors
    ///
    /// Returns error if format is invalid
    pub fn parse(s: &str) -> Result<Self, ShardParseError> {
        let parts: Vec<&str> = s.split('/').collect();
        if parts.len() != 2 {
            return Err(ShardParseError::InvalidFormat(s.to_string()));
        }

        let current = parts[0]
            .parse::<u32>()
            .map_err(|_| ShardParseError::InvalidNumber(parts[0].to_string()))?;
        let total = parts[1]
            .parse::<u32>()
            .map_err(|_| ShardParseError::InvalidNumber(parts[1].to_string()))?;

        if total == 0 {
            return Err(ShardParseError::ZeroTotal);
        }
        if current == 0 {
            return Err(ShardParseError::ZeroCurrent);
        }
        if current > total {
            return Err(ShardParseError::CurrentExceedsTotal { current, total });
        }

        Ok(Self { current, total })
    }

    /// Check if a test at given index should run on this shard
    ///
    /// Uses modulo distribution for even test distribution.
    #[must_use]
    pub fn should_run_index(&self, test_index: usize) -> bool {
        (test_index % self.total as usize) + 1 == self.current as usize
    }

    /// Check if a test with given name should run on this shard
    ///
    /// Uses deterministic hash-based distribution for stable assignment.
    #[must_use]
    pub fn should_run_name(&self, test_name: &str) -> bool {
        let hash = Self::hash_test_name(test_name);
        (hash % self.total as u64) + 1 == self.current as u64
    }

    /// Compute deterministic hash for test name
    fn hash_test_name(name: &str) -> u64 {
        let mut hasher = DefaultHasher::new();
        name.hash(&mut hasher);
        hasher.finish()
    }

    /// Filter a list of tests to only those that should run on this shard
    #[must_use]
    pub fn filter_tests<'a>(&self, tests: &'a [&str]) -> Vec<&'a str> {
        tests
            .iter()
            .filter(|name| self.should_run_name(name))
            .copied()
            .collect()
    }

    /// Filter tests by index
    #[must_use]
    pub fn filter_by_index<T: Clone>(&self, items: &[T]) -> Vec<T> {
        items
            .iter()
            .enumerate()
            .filter(|(idx, _)| self.should_run_index(*idx))
            .map(|(_, item)| item.clone())
            .collect()
    }

    /// Get estimated test count for this shard
    #[must_use]
    pub fn estimated_count(&self, total_tests: usize) -> usize {
        let base = total_tests / self.total as usize;
        let remainder = total_tests % self.total as usize;
        if self.current as usize <= remainder {
            base + 1
        } else {
            base
        }
    }

    /// Validate that all shards together cover all tests exactly once
    #[must_use]
    pub fn validate_coverage(total_tests: usize, total_shards: u32) -> bool {
        let mut covered = vec![false; total_tests];

        for shard in 1..=total_shards {
            let config = ShardConfig::new(shard, total_shards);
            for (idx, is_covered) in covered.iter_mut().enumerate() {
                if config.should_run_index(idx) {
                    if *is_covered {
                        return false; // Double coverage
                    }
                    *is_covered = true;
                }
            }
        }

        covered.iter().all(|&c| c)
    }
}

impl Default for ShardConfig {
    fn default() -> Self {
        Self {
            current: 1,
            total: 1,
        }
    }
}

impl std::fmt::Display for ShardConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", self.current, self.total)
    }
}

/// Errors that can occur when parsing shard configuration
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShardParseError {
    /// Invalid format (expected "N/M")
    InvalidFormat(String),
    /// Invalid number in shard spec
    InvalidNumber(String),
    /// Total shards cannot be zero
    ZeroTotal,
    /// Current shard cannot be zero (1-based)
    ZeroCurrent,
    /// Current shard exceeds total
    CurrentExceedsTotal {
        /// Current shard number
        current: u32,
        /// Total shard count
        total: u32,
    },
}

impl std::fmt::Display for ShardParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidFormat(s) => {
                write!(
                    f,
                    "Invalid shard format '{s}', expected 'N/M' (e.g., '1/4')"
                )
            }
            Self::InvalidNumber(s) => write!(f, "Invalid number in shard spec: '{s}'"),
            Self::ZeroTotal => write!(f, "Total shards cannot be zero"),
            Self::ZeroCurrent => write!(f, "Current shard must be 1-based (cannot be 0)"),
            Self::CurrentExceedsTotal { current, total } => {
                write!(f, "Current shard ({current}) exceeds total ({total})")
            }
        }
    }
}

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

/// Sharded test runner
#[derive(Debug, Clone)]
pub struct ShardedRunner {
    config: ShardConfig,
    test_names: Vec<String>,
}

impl ShardedRunner {
    /// Create a new sharded runner
    #[must_use]
    pub fn new(config: ShardConfig) -> Self {
        Self {
            config,
            test_names: Vec::new(),
        }
    }

    /// Add tests to the runner
    pub fn add_tests(&mut self, tests: impl IntoIterator<Item = impl Into<String>>) {
        for test in tests {
            self.test_names.push(test.into());
        }
    }

    /// Get tests assigned to this shard
    #[must_use]
    pub fn assigned_tests(&self) -> Vec<&str> {
        self.test_names
            .iter()
            .filter(|name| self.config.should_run_name(name))
            .map(String::as_str)
            .collect()
    }

    /// Get shard configuration
    #[must_use]
    pub fn config(&self) -> ShardConfig {
        self.config
    }

    /// Get total test count
    #[must_use]
    pub fn total_tests(&self) -> usize {
        self.test_names.len()
    }

    /// Get assigned test count
    #[must_use]
    pub fn assigned_count(&self) -> usize {
        self.assigned_tests().len()
    }
}

/// Report for merged shard results
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ShardReport {
    /// Shard configuration used
    pub shard: Option<ShardConfig>,
    /// Number of tests run
    pub tests_run: usize,
    /// Number of tests passed
    pub tests_passed: usize,
    /// Number of tests failed
    pub tests_failed: usize,
    /// Number of tests skipped
    pub tests_skipped: usize,
    /// Duration in milliseconds
    pub duration_ms: u64,
    /// Failed test names
    pub failed_tests: Vec<String>,
}

impl ShardReport {
    /// Create a new empty report
    #[must_use]
    pub fn new(shard: ShardConfig) -> Self {
        Self {
            shard: Some(shard),
            ..Default::default()
        }
    }

    /// Check if all tests passed
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.tests_failed == 0
    }

    /// Merge multiple shard reports
    #[must_use]
    pub fn merge(reports: &[ShardReport]) -> Self {
        let mut merged = Self::default();

        for report in reports {
            merged.tests_run += report.tests_run;
            merged.tests_passed += report.tests_passed;
            merged.tests_failed += report.tests_failed;
            merged.tests_skipped += report.tests_skipped;
            merged.duration_ms = merged.duration_ms.max(report.duration_ms);
            merged.failed_tests.extend(report.failed_tests.clone());
        }

        merged
    }

    /// Export to JSON
    #[must_use]
    pub fn to_json(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
    }
}

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

    // =========================================================================
    // Hâ‚€-SHARD-01: ShardConfig creation
    // =========================================================================

    #[test]
    fn h0_shard_01_config_new() {
        let config = ShardConfig::new(1, 4);
        assert_eq!(config.current, 1);
        assert_eq!(config.total, 4);
    }

    #[test]
    fn h0_shard_02_config_display() {
        let config = ShardConfig::new(2, 5);
        assert_eq!(format!("{config}"), "2/5");
    }

    #[test]
    #[should_panic(expected = "Total shards must be greater than 0")]
    fn h0_shard_03_config_zero_total_panics() {
        let _ = ShardConfig::new(1, 0);
    }

    #[test]
    #[should_panic(expected = "Current shard must be 1-based")]
    fn h0_shard_04_config_zero_current_panics() {
        let _ = ShardConfig::new(0, 4);
    }

    #[test]
    #[should_panic(expected = "cannot exceed total")]
    fn h0_shard_05_config_current_exceeds_total_panics() {
        let _ = ShardConfig::new(5, 4);
    }

    // =========================================================================
    // Hâ‚€-SHARD-06: Parse from string
    // =========================================================================

    #[test]
    fn h0_shard_06_parse_valid() {
        let config = ShardConfig::parse("2/4").unwrap();
        assert_eq!(config.current, 2);
        assert_eq!(config.total, 4);
    }

    #[test]
    fn h0_shard_07_parse_invalid_format() {
        let err = ShardConfig::parse("2-4").unwrap_err();
        assert!(matches!(err, ShardParseError::InvalidFormat(_)));
    }

    #[test]
    fn h0_shard_08_parse_invalid_number() {
        let err = ShardConfig::parse("abc/4").unwrap_err();
        assert!(matches!(err, ShardParseError::InvalidNumber(_)));
    }

    #[test]
    fn h0_shard_09_parse_zero_total() {
        let err = ShardConfig::parse("1/0").unwrap_err();
        assert!(matches!(err, ShardParseError::ZeroTotal));
    }

    #[test]
    fn h0_shard_10_parse_zero_current() {
        let err = ShardConfig::parse("0/4").unwrap_err();
        assert!(matches!(err, ShardParseError::ZeroCurrent));
    }

    #[test]
    fn h0_shard_11_parse_current_exceeds_total() {
        let err = ShardConfig::parse("5/4").unwrap_err();
        assert!(matches!(err, ShardParseError::CurrentExceedsTotal { .. }));
    }

    // =========================================================================
    // Hâ‚€-SHARD-12: Test distribution by index
    // =========================================================================

    #[test]
    fn h0_shard_12_should_run_index_shard1of4() {
        let config = ShardConfig::new(1, 4);
        assert!(config.should_run_index(0)); // 0 % 4 = 0, +1 = 1
        assert!(!config.should_run_index(1)); // 1 % 4 = 1, +1 = 2
        assert!(!config.should_run_index(2)); // 2 % 4 = 2, +1 = 3
        assert!(!config.should_run_index(3)); // 3 % 4 = 3, +1 = 4
        assert!(config.should_run_index(4)); // 4 % 4 = 0, +1 = 1
    }

    #[test]
    fn h0_shard_13_should_run_index_shard2of4() {
        let config = ShardConfig::new(2, 4);
        assert!(!config.should_run_index(0));
        assert!(config.should_run_index(1));
        assert!(!config.should_run_index(2));
        assert!(!config.should_run_index(3));
        assert!(!config.should_run_index(4));
        assert!(config.should_run_index(5));
    }

    #[test]
    fn h0_shard_14_all_shards_cover_all_tests() {
        // 10 tests distributed across 4 shards
        let mut covered = [false; 10];

        for shard in 1..=4 {
            let config = ShardConfig::new(shard, 4);
            for idx in 0..10 {
                if config.should_run_index(idx) {
                    assert!(!covered[idx], "Test {idx} covered twice");
                    covered[idx] = true;
                }
            }
        }

        assert!(covered.iter().all(|&c| c), "All tests must be covered");
    }

    // =========================================================================
    // Hâ‚€-SHARD-15: Test distribution by name (hash-based)
    // =========================================================================

    #[test]
    fn h0_shard_15_should_run_name_deterministic() {
        let config = ShardConfig::new(1, 4);
        let result1 = config.should_run_name("test_foo");
        let result2 = config.should_run_name("test_foo");
        assert_eq!(result1, result2, "Same name should give same result");
    }

    #[test]
    fn h0_shard_16_filter_tests_by_name() {
        let config = ShardConfig::new(1, 2);
        let tests = vec!["test_a", "test_b", "test_c", "test_d"];
        let filtered = config.filter_tests(&tests);

        // Should get roughly half the tests
        assert!(!filtered.is_empty());
        assert!(filtered.len() <= tests.len());
    }

    #[test]
    fn h0_shard_17_all_shards_cover_all_names() {
        let tests = vec!["test_1", "test_2", "test_3", "test_4", "test_5"];
        let mut covered = vec![false; tests.len()];

        for shard in 1..=3 {
            let config = ShardConfig::new(shard, 3);
            for (idx, test) in tests.iter().enumerate() {
                if config.should_run_name(test) {
                    covered[idx] = true;
                }
            }
        }

        assert!(covered.iter().all(|&c| c), "All tests must be covered");
    }

    // =========================================================================
    // Hâ‚€-SHARD-18: Filter by index
    // =========================================================================

    #[test]
    fn h0_shard_18_filter_by_index() {
        let config = ShardConfig::new(1, 2);
        let items = vec!["a", "b", "c", "d"];
        let filtered = config.filter_by_index(&items);

        // Shard 1 of 2 gets indices 0, 2
        assert_eq!(filtered, vec!["a", "c"]);
    }

    #[test]
    fn h0_shard_19_filter_by_index_shard2() {
        let config = ShardConfig::new(2, 2);
        let items = vec!["a", "b", "c", "d"];
        let filtered = config.filter_by_index(&items);

        // Shard 2 of 2 gets indices 1, 3
        assert_eq!(filtered, vec!["b", "d"]);
    }

    // =========================================================================
    // Hâ‚€-SHARD-20: Estimated count
    // =========================================================================

    #[test]
    fn h0_shard_20_estimated_count_even() {
        let config = ShardConfig::new(1, 4);
        assert_eq!(config.estimated_count(100), 25);
    }

    #[test]
    fn h0_shard_21_estimated_count_uneven() {
        // 10 tests / 3 shards = 3 each + 1 remainder
        let config1 = ShardConfig::new(1, 3);
        let config2 = ShardConfig::new(2, 3);
        let config3 = ShardConfig::new(3, 3);

        let total =
            config1.estimated_count(10) + config2.estimated_count(10) + config3.estimated_count(10);
        assert_eq!(total, 10);
    }

    // =========================================================================
    // Hâ‚€-SHARD-22: Validate coverage
    // =========================================================================

    #[test]
    fn h0_shard_22_validate_coverage_success() {
        assert!(ShardConfig::validate_coverage(100, 4));
        assert!(ShardConfig::validate_coverage(10, 3));
        assert!(ShardConfig::validate_coverage(7, 7));
    }

    // =========================================================================
    // Hâ‚€-SHARD-23: ShardedRunner
    // =========================================================================

    #[test]
    fn h0_shard_23_runner_new() {
        let config = ShardConfig::new(1, 4);
        let runner = ShardedRunner::new(config);
        assert_eq!(runner.config(), config);
        assert_eq!(runner.total_tests(), 0);
    }

    #[test]
    fn h0_shard_24_runner_add_tests() {
        let config = ShardConfig::new(1, 2);
        let mut runner = ShardedRunner::new(config);
        runner.add_tests(vec!["test_a", "test_b", "test_c"]);

        assert_eq!(runner.total_tests(), 3);
        assert!(runner.assigned_count() > 0);
    }

    #[test]
    fn h0_shard_25_runner_assigned_tests() {
        let config = ShardConfig::new(1, 2);
        let mut runner = ShardedRunner::new(config);
        runner.add_tests(vec!["test_a", "test_b", "test_c", "test_d"]);

        let assigned = runner.assigned_tests();
        assert!(!assigned.is_empty());
        assert!(assigned.len() <= 4);
    }

    // =========================================================================
    // Hâ‚€-SHARD-26: ShardReport
    // =========================================================================

    #[test]
    fn h0_shard_26_report_new() {
        let config = ShardConfig::new(1, 4);
        let report = ShardReport::new(config);
        assert_eq!(report.shard, Some(config));
        assert_eq!(report.tests_run, 0);
    }

    #[test]
    fn h0_shard_27_report_is_success() {
        let mut report = ShardReport::default();
        report.tests_passed = 10;
        report.tests_failed = 0;
        assert!(report.is_success());

        report.tests_failed = 1;
        assert!(!report.is_success());
    }

    #[test]
    fn h0_shard_28_report_merge() {
        let mut r1 = ShardReport::default();
        r1.tests_run = 10;
        r1.tests_passed = 9;
        r1.tests_failed = 1;
        r1.duration_ms = 1000;

        let mut r2 = ShardReport::default();
        r2.tests_run = 10;
        r2.tests_passed = 10;
        r2.tests_failed = 0;
        r2.duration_ms = 500;

        let merged = ShardReport::merge(&[r1, r2]);
        assert_eq!(merged.tests_run, 20);
        assert_eq!(merged.tests_passed, 19);
        assert_eq!(merged.tests_failed, 1);
        assert_eq!(merged.duration_ms, 1000); // Max duration
    }

    #[test]
    fn h0_shard_29_report_to_json() {
        let report = ShardReport::new(ShardConfig::new(1, 2));
        let json = report.to_json();
        assert!(json.contains("tests_run"));
        assert!(json.contains("shard"));
    }

    // =========================================================================
    // Hâ‚€-SHARD-30: Default config
    // =========================================================================

    #[test]
    fn h0_shard_30_default_config() {
        let config = ShardConfig::default();
        assert_eq!(config.current, 1);
        assert_eq!(config.total, 1);
        // Default should run all tests
        assert!(config.should_run_index(0));
        assert!(config.should_run_index(100));
    }

    // =========================================================================
    // Additional coverage tests for edge cases
    // =========================================================================

    #[test]
    fn h0_shard_31_parse_invalid_total_number() {
        // Test parsing with invalid second number (total)
        let err = ShardConfig::parse("1/abc").unwrap_err();
        assert!(matches!(err, ShardParseError::InvalidNumber(_)));
        if let ShardParseError::InvalidNumber(s) = &err {
            assert_eq!(s, "abc");
        }
    }

    #[test]
    fn h0_shard_32_parse_too_many_slashes() {
        let err = ShardConfig::parse("1/2/3").unwrap_err();
        assert!(matches!(err, ShardParseError::InvalidFormat(_)));
    }

    #[test]
    fn h0_shard_33_parse_single_number() {
        let err = ShardConfig::parse("5").unwrap_err();
        assert!(matches!(err, ShardParseError::InvalidFormat(_)));
    }

    #[test]
    fn h0_shard_34_error_display_invalid_format() {
        let err = ShardParseError::InvalidFormat("bad".to_string());
        let msg = format!("{err}");
        assert!(msg.contains("Invalid shard format"));
        assert!(msg.contains("bad"));
        assert!(msg.contains("N/M"));
    }

    #[test]
    fn h0_shard_35_error_display_invalid_number() {
        let err = ShardParseError::InvalidNumber("xyz".to_string());
        let msg = format!("{err}");
        assert!(msg.contains("Invalid number"));
        assert!(msg.contains("xyz"));
    }

    #[test]
    fn h0_shard_36_error_display_zero_total() {
        let err = ShardParseError::ZeroTotal;
        let msg = format!("{err}");
        assert!(msg.contains("Total shards cannot be zero"));
    }

    #[test]
    fn h0_shard_37_error_display_zero_current() {
        let err = ShardParseError::ZeroCurrent;
        let msg = format!("{err}");
        assert!(msg.contains("must be 1-based"));
    }

    #[test]
    fn h0_shard_38_error_display_current_exceeds_total() {
        let err = ShardParseError::CurrentExceedsTotal {
            current: 10,
            total: 5,
        };
        let msg = format!("{err}");
        assert!(msg.contains("10"));
        assert!(msg.contains('5'));
        assert!(msg.contains("exceeds"));
    }

    #[test]
    fn h0_shard_39_error_is_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(ShardParseError::InvalidFormat("test".to_string()));
        // Verify it implements std::error::Error
        assert!(!err.to_string().is_empty());
    }

    #[test]
    fn h0_shard_40_validate_coverage_with_zero_tests() {
        // Edge case: zero tests should be valid (trivially covered)
        assert!(ShardConfig::validate_coverage(0, 4));
    }

    #[test]
    fn h0_shard_41_validate_coverage_single_shard() {
        assert!(ShardConfig::validate_coverage(100, 1));
    }

    #[test]
    fn h0_shard_42_report_merge_with_failed_tests() {
        let mut r1 = ShardReport::default();
        r1.tests_run = 5;
        r1.tests_passed = 4;
        r1.tests_failed = 1;
        r1.failed_tests = vec!["test_a".to_string(), "test_b".to_string()];
        r1.duration_ms = 100;

        let mut r2 = ShardReport::default();
        r2.tests_run = 5;
        r2.tests_passed = 3;
        r2.tests_failed = 2;
        r2.failed_tests = vec!["test_c".to_string()];
        r2.duration_ms = 200;

        let merged = ShardReport::merge(&[r1, r2]);
        assert_eq!(merged.tests_run, 10);
        assert_eq!(merged.tests_passed, 7);
        assert_eq!(merged.tests_failed, 3);
        assert_eq!(merged.failed_tests.len(), 3);
        assert!(merged.failed_tests.contains(&"test_a".to_string()));
        assert!(merged.failed_tests.contains(&"test_b".to_string()));
        assert!(merged.failed_tests.contains(&"test_c".to_string()));
        assert_eq!(merged.duration_ms, 200); // max of 100 and 200
    }

    #[test]
    fn h0_shard_43_report_merge_empty() {
        let merged = ShardReport::merge(&[]);
        assert_eq!(merged.tests_run, 0);
        assert_eq!(merged.tests_passed, 0);
        assert_eq!(merged.tests_failed, 0);
        assert!(merged.is_success()); // No failures = success
    }

    #[test]
    fn h0_shard_44_report_with_skipped_tests() {
        let mut report = ShardReport::default();
        report.tests_run = 10;
        report.tests_passed = 8;
        report.tests_failed = 0;
        report.tests_skipped = 2;

        assert!(report.is_success());
        assert_eq!(report.tests_skipped, 2);
    }

    #[test]
    fn h0_shard_45_report_merge_skipped() {
        let mut r1 = ShardReport::default();
        r1.tests_skipped = 3;

        let mut r2 = ShardReport::default();
        r2.tests_skipped = 2;

        let merged = ShardReport::merge(&[r1, r2]);
        assert_eq!(merged.tests_skipped, 5);
    }

    #[test]
    fn h0_shard_46_estimated_count_more_shards_than_tests() {
        // 3 tests across 10 shards
        let config1 = ShardConfig::new(1, 10);
        let config2 = ShardConfig::new(4, 10);
        let config10 = ShardConfig::new(10, 10);

        // Shards 1-3 get 1 test each, shards 4-10 get 0
        assert_eq!(config1.estimated_count(3), 1);
        assert_eq!(config2.estimated_count(3), 0);
        assert_eq!(config10.estimated_count(3), 0);
    }

    #[test]
    fn h0_shard_47_filter_tests_empty_list() {
        let config = ShardConfig::new(1, 2);
        let tests: Vec<&str> = vec![];
        let filtered = config.filter_tests(&tests);
        assert!(filtered.is_empty());
    }

    #[test]
    fn h0_shard_48_filter_by_index_empty() {
        let config = ShardConfig::new(1, 2);
        let items: Vec<i32> = vec![];
        let filtered = config.filter_by_index(&items);
        assert!(filtered.is_empty());
    }

    #[test]
    fn h0_shard_49_runner_add_tests_from_strings() {
        let config = ShardConfig::new(1, 2);
        let mut runner = ShardedRunner::new(config);

        // Test with owned Strings
        runner.add_tests(vec!["test_1".to_string(), "test_2".to_string()]);
        assert_eq!(runner.total_tests(), 2);
    }

    #[test]
    fn h0_shard_50_runner_multiple_add_calls() {
        let config = ShardConfig::new(1, 2);
        let mut runner = ShardedRunner::new(config);

        runner.add_tests(vec!["test_a", "test_b"]);
        runner.add_tests(vec!["test_c"]);

        assert_eq!(runner.total_tests(), 3);
    }

    #[test]
    fn h0_shard_51_config_clone_and_eq() {
        let config1 = ShardConfig::new(2, 4);
        let config2 = config1;
        assert_eq!(config1, config2);

        let config3 = ShardConfig::new(3, 4);
        assert_ne!(config1, config3);
    }

    #[test]
    fn h0_shard_52_hash_test_name_consistency() {
        // Verify same name always produces same hash distribution
        let config = ShardConfig::new(1, 100);

        let mut results = Vec::new();
        for _ in 0..10 {
            results.push(config.should_run_name("consistent_test_name"));
        }

        // All results should be identical
        assert!(results.iter().all(|&r| r == results[0]));
    }

    #[test]
    fn h0_shard_53_different_names_different_distribution() {
        // Different names should (eventually) go to different shards
        let tests = vec![
            "test_alpha",
            "test_beta",
            "test_gamma",
            "test_delta",
            "test_epsilon",
            "test_zeta",
            "test_eta",
            "test_theta",
        ];

        // With 4 shards, different tests should distribute
        let mut shard_counts = [0usize; 4];
        for test in &tests {
            for shard in 1..=4 {
                let config = ShardConfig::new(shard, 4);
                if config.should_run_name(test) {
                    shard_counts[shard as usize - 1] += 1;
                    break;
                }
            }
        }

        // Each test goes to exactly one shard
        let total: usize = shard_counts.iter().sum();
        assert_eq!(total, tests.len());
    }

    #[test]
    fn h0_shard_54_report_json_contains_all_fields() {
        let config = ShardConfig::new(1, 2);
        let mut report = ShardReport::new(config);
        report.tests_run = 10;
        report.tests_passed = 8;
        report.tests_failed = 2;
        report.tests_skipped = 0;
        report.duration_ms = 1234;
        report.failed_tests = vec!["fail_1".to_string(), "fail_2".to_string()];

        let json = report.to_json();
        assert!(json.contains("\"tests_run\": 10"));
        assert!(json.contains("\"tests_passed\": 8"));
        assert!(json.contains("\"tests_failed\": 2"));
        assert!(json.contains("\"tests_skipped\": 0"));
        assert!(json.contains("\"duration_ms\": 1234"));
        assert!(json.contains("fail_1"));
        assert!(json.contains("fail_2"));
    }

    #[test]
    fn h0_shard_55_validate_coverage_large_test_count() {
        // Verify coverage validation with larger numbers
        assert!(ShardConfig::validate_coverage(1000, 16));
        assert!(ShardConfig::validate_coverage(999, 16));
    }

    #[test]
    fn h0_shard_56_shard_config_debug() {
        let config = ShardConfig::new(3, 7);
        let debug = format!("{config:?}");
        assert!(debug.contains("ShardConfig"));
        assert!(debug.contains("current: 3"));
        assert!(debug.contains("total: 7"));
    }

    #[test]
    fn h0_shard_57_shard_parse_error_clone() {
        let err1 = ShardParseError::InvalidFormat("test".to_string());
        let err2 = err1.clone();
        assert_eq!(err1, err2);
    }

    #[test]
    fn h0_shard_58_sharded_runner_debug() {
        let config = ShardConfig::new(1, 2);
        let runner = ShardedRunner::new(config);
        let debug = format!("{runner:?}");
        assert!(debug.contains("ShardedRunner"));
    }

    #[test]
    fn h0_shard_59_sharded_runner_clone() {
        let config = ShardConfig::new(1, 2);
        let mut runner = ShardedRunner::new(config);
        runner.add_tests(vec!["test_a", "test_b"]);

        let cloned = runner.clone();
        assert_eq!(runner.total_tests(), cloned.total_tests());
        assert_eq!(runner.config(), cloned.config());
    }

    #[test]
    fn h0_shard_60_shard_report_clone() {
        let config = ShardConfig::new(1, 2);
        let mut report = ShardReport::new(config);
        report.tests_run = 5;
        report.failed_tests = vec!["fail".to_string()];

        let cloned = report.clone();
        assert_eq!(report.tests_run, cloned.tests_run);
        assert_eq!(report.failed_tests, cloned.failed_tests);
    }
}