omnicoach 0.3.0

Lightweight, high-signal static analysis and command linter for Python and Rust
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
//! Flags sibling test functions that repeat the same leading setup statements.

use crate::code_lint::ast::{self, ParsedFile, TestFunctionSetup};
use crate::code_lint::contract::{CodeRule, RuleTarget};
use crate::diagnostic::{Diagnostic, Language, RuleName, ViolationTemplate, violation_template};
use crate::rule_declaration::{
    Classification, Consensus, CountOption, Declaration, Example, ImpactedQuality,
    LanguageDefaults, Precision, Reference, RuleDoc, RuleOptions, Topic,
};
use std::collections::HashMap;
use std::path::Path;

const MIN_TESTS: CountOption = CountOption {
    key: "min-tests",
    doc: "Minimum test functions in a scope sharing the same leading setup prefix to be flagged. \
          Values below 2 behave as 2.",
    default: LanguageDefaults::new(3, &[]),
};

const MIN_STATEMENTS: CountOption = CountOption {
    key: "min-statements",
    doc: "Minimum leading non-assertion setup statements shared across test functions to be \
          flagged. Values below 1 behave as 1.",
    default: LanguageDefaults::new(3, &[]),
};

const TEMPLATE: ViolationTemplate = violation_template! {
    summary: "Test `{function}` duplicates {count} leading setup statements with {duplicates}.",
    rationale: "Repeating the same arrange statements across sibling tests obscures which inputs differ in each scenario and requires updating every copy when construction changes.",
    suggestion: {
        Python => "Extract shared immutable values into module constants, or extract mutable setup into a helper function or `@pytest.fixture` and pass only the scenario-specific inputs in each test.",
        Rust => "Extract shared immutable values into `const` items, or extract mutable setup into a helper function and pass only the scenario-specific inputs in each test.",
    },
};

/// The rule's declaration.
pub const RULE: CodeRule<(CountOption, CountOption)> = CodeRule {
    declaration: Declaration {
        name: RuleName("duplicated-test-setup"),
        template: &TEMPLATE,
        languages: &[Language::Python, Language::Rust],
        options: RuleOptions::code_rule((MIN_TESTS, MIN_STATEMENTS)),
        classification: Classification {
            topics: &[Topic::TESTING],
            precision: Precision::Heuristic,
            consensus: Consensus::Opinionated,
            impacted_quality: ImpactedQuality::Maintainability,
        },
        doc: RuleDoc {
            summary: "Flags sibling test functions that repeat the same leading setup statements.",
            what_it_does: indoc::indoc! {r"
                Groups direct test functions in each module, Python `class`, or Rust `mod` scope
                and extracts each test's leading non-assertion setup statements (skipping a
                leading Python docstring and nested function, class, or Rust local item
                declarations).

                Flags the first test function in a group when at least `min-tests` test functions
                in the same scope begin with the same `min-statements` (or more) setup
                statements."},
            why_is_this_bad: indoc::indoc! {r"
                When several tests begin with the same block of boilerplate construction, readers
                have to compare lines character by character to see what actually differs between
                scenarios, and any constructor or schema change breaks every copy at once.

                Extract shared immutable values into module constants, or extract a creation helper
                or fixture with sensible defaults so each test passes only the values relevant to
                the behavior it verifies."},
            known_problems: Some(indoc::indoc! {r"
                - Only identical leading statements are matched; setup statements that appear in a
                  different order or use different local variable names are not grouped together.
                - Imported helper calls that perform assertions without an `assert_` or `_assert_`
                  prefix are classified as setup statements."}),
            references: &[
                Reference {
                    title: "Software Engineering at Google, ch. 12: Shared Setup",
                    url: "https://abseil.io/resources/swe-book/html/ch12.html",
                },
                Reference {
                    title: "xUnit Test Patterns: Creation Method",
                    url: "http://xunitpatterns.com/Creation%20Method.html",
                },
            ],
            examples: &[
                Example {
                    language: Language::Python,
                    flagged: indoc::indoc! {r#"
                        def test_admin_can_delete():
                            db = InMemoryDatabase()
                            repo = UserRepository(db)
                            service = AuthService(repo)
                            assert service.can_delete("admin")

                        def test_guest_cannot_delete():
                            db = InMemoryDatabase()
                            repo = UserRepository(db)
                            service = AuthService(repo)
                            assert not service.can_delete("guest")

                        def test_editor_cannot_delete():
                            db = InMemoryDatabase()
                            repo = UserRepository(db)
                            service = AuthService(repo)
                            assert not service.can_delete("editor")
                    "#},
                    flagged_span: "test_admin_can_delete",
                    fixed: indoc::indoc! {r#"
                        def make_auth_service() -> AuthService:
                            db = InMemoryDatabase()
                            repo = UserRepository(db)
                            return AuthService(repo)

                        def test_admin_can_delete():
                            service = make_auth_service()
                            assert service.can_delete("admin")

                        def test_guest_cannot_delete():
                            service = make_auth_service()
                            assert not service.can_delete("guest")

                        def test_editor_cannot_delete():
                            service = make_auth_service()
                            assert not service.can_delete("editor")
                    "#},
                },
                Example {
                    language: Language::Rust,
                    flagged: indoc::indoc! {r#"
                        #[test]
                        fn test_admin_can_delete() {
                            let db = InMemoryDatabase::new();
                            let repo = UserRepository::new(db);
                            let service = AuthService::new(repo);
                            assert!(service.can_delete("admin"));
                        }

                        #[test]
                        fn test_guest_cannot_delete() {
                            let db = InMemoryDatabase::new();
                            let repo = UserRepository::new(db);
                            let service = AuthService::new(repo);
                            assert!(!service.can_delete("guest"));
                        }

                        #[test]
                        fn test_editor_cannot_delete() {
                            let db = InMemoryDatabase::new();
                            let repo = UserRepository::new(db);
                            let service = AuthService::new(repo);
                            assert!(!service.can_delete("editor"));
                        }
                    "#},
                    flagged_span: "test_admin_can_delete",
                    fixed: indoc::indoc! {r#"
                        fn make_auth_service() -> AuthService {
                            let db = InMemoryDatabase::new();
                            let repo = UserRepository::new(db);
                            AuthService::new(repo)
                        }

                        #[test]
                        fn test_admin_can_delete() {
                            let service = make_auth_service();
                            assert!(service.can_delete("admin"));
                        }

                        #[test]
                        fn test_guest_cannot_delete() {
                            let service = make_auth_service();
                            assert!(!service.can_delete("guest"));
                        }

                        #[test]
                        fn test_editor_cannot_delete() {
                            let service = make_auth_service();
                            assert!(!service.can_delete("editor"));
                        }
                    "#},
                },
            ],
        },
    },
    target: RuleTarget::TestsOnly,
    check: check_file,
};

fn check_file(
    rule: &CodeRule<(CountOption, CountOption)>,
    path: &Path,
    file: &ParsedFile,
    (min_tests, min_statements): (usize, usize),
) -> Vec<Diagnostic> {
    let effective_min_tests = min_tests.max(2);
    let effective_min_statements = min_statements.max(1);
    let mut diagnostics = Vec::new();

    for scope in ast::collect_test_setup_scopes(file) {
        let mut index_by_prefix: HashMap<Vec<String>, usize> = HashMap::new();
        let mut groups: Vec<Vec<TestFunctionSetup<'_>>> = Vec::new();
        for func in scope {
            if func.leading_setup_statements.len() < effective_min_statements {
                continue;
            }
            let prefix = func.leading_setup_statements[..effective_min_statements].to_vec();
            let group_idx = *index_by_prefix.entry(prefix).or_insert_with(|| {
                groups.push(Vec::new());
                groups.len() - 1
            });
            groups[group_idx].push(func);
        }

        for group in groups {
            if group.len() < effective_min_tests {
                continue;
            }
            let shared_count = shared_prefix_length(&group);
            let duplicates = group[1..]
                .iter()
                .map(|func| format!("`{}`", func.name))
                .collect::<Vec<_>>()
                .join(", ");
            diagnostics.push(rule.diagnostic_at_node(
                path,
                &group[0].name_node,
                &[
                    ("function", &group[0].name),
                    ("count", &shared_count.to_string()),
                    ("duplicates", &duplicates),
                ],
            ));
        }
    }

    diagnostics
}

fn shared_prefix_length(group: &[TestFunctionSetup<'_>]) -> usize {
    let Some(first) = group.first() else {
        return 0;
    };
    first
        .leading_setup_statements
        .iter()
        .enumerate()
        .take_while(|(idx, statement)| {
            group[1..].iter().all(|other| {
                other
                    .leading_setup_statements
                    .get(*idx)
                    .is_some_and(|candidate| candidate == *statement)
            })
        })
        .count()
}

#[cfg(test)]
crate::test_utils::rule_test!(
    RULE,
    {
        Python => {
            pass: [
                below_min_tests_threshold_allowed => r#"
                    def test_admin_can_delete():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        service = AuthService(repo)
                        assert service.can_delete("admin")

                    def test_guest_cannot_delete():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        service = AuthService(repo)
                        assert not service.can_delete("guest")
                "#,
                below_min_statements_threshold_allowed => r#"
                    def test_admin_role():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        user = repo.create("admin")
                        assert user.is_admin

                    def test_guest_role():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        user = repo.create("guest")
                        assert not user.is_admin

                    def test_editor_role():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        user = repo.create("editor")
                        assert not user.is_admin
                "#,
                helper_function_exempt => r"
                    def build_alpha():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        service = AuthService(repo)
                        return service

                    def build_beta():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        service = AuthService(repo)
                        return service

                    def build_gamma():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        service = AuthService(repo)
                        return service
                ",
                leading_docstring_not_counted_as_setup => r#"
                    def test_first():
                        """Shared test docstring."""
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.count() == 0

                    def test_second():
                        """Shared test docstring."""
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.is_empty()

                    def test_third():
                        """Shared test docstring."""
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.all() == []
                "#,
                nested_function_not_counted_as_setup => r"
                    def test_first():
                        def helper():
                            return 1
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.count() == 0

                    def test_second():
                        def helper():
                            return 1
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.is_empty()

                    def test_third():
                        def helper():
                            return 1
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.all() == []
                ",
                nested_class_not_counted_as_setup => r"
                    def test_first():
                        class Stub:
                            pass
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.count() == 0

                    def test_second():
                        class Stub:
                            pass
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.is_empty()

                    def test_third():
                        class Stub:
                            pass
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.all() == []
                ",
                assertions_not_counted_as_setup => r"
                    def test_first():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.count() == 0

                    def test_second():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.count() == 0

                    def test_third():
                        db = InMemoryDatabase()
                        repo = UserRepository(db)
                        assert repo.count() == 0
                ",
                separate_test_classes_do_not_pool_across_scopes => r#"
                    class TestAdminAuth:
                        def test_can_delete(self):
                            db = InMemoryDatabase()
                            repo = UserRepository(db)
                            service = AuthService(repo)
                            assert service.can_delete("admin")

                        def test_can_create(self):
                            db = InMemoryDatabase()
                            repo = UserRepository(db)
                            service = AuthService(repo)
                            assert service.can_create("admin")

                    class TestGuestAuth:
                        def test_cannot_delete(self):
                            db = InMemoryDatabase()
                            repo = UserRepository(db)
                            service = AuthService(repo)
                            assert not service.can_delete("guest")
                "#,
            ],
            fail: [
                three_class_test_methods_sharing_setup => r#"
                    class TestOrderService:
                        def test_submit_order(self):
                            clock = FakeClock()
                            ledger = InMemoryLedger()
                            service = OrderService(clock, ledger)
                            assert service.submit("item")

                        def test_cancel_order(self):
                            clock = FakeClock()
                            ledger = InMemoryLedger()
                            service = OrderService(clock, ledger)
                            assert service.cancel("item")

                        def test_refund_order(self):
                            clock = FakeClock()
                            ledger = InMemoryLedger()
                            service = OrderService(clock, ledger)
                            assert service.refund("item")
                "# => "test_submit_order",
                narrowing_guard_included_in_setup_prefix => r#"
                    def test_profile_email(repo):
                        user = repo.find_by_id("u1")
                        assert user is not None
                        profile = user.load_profile()
                        assert profile.email == "a@example.com"

                    def test_profile_name(repo):
                        user = repo.find_by_id("u1")
                        assert user is not None
                        profile = user.load_profile()
                        assert profile.name == "Alice"

                    def test_profile_active(repo):
                        user = repo.find_by_id("u1")
                        assert user is not None
                        profile = user.load_profile()
                        assert profile.is_active
                "# => "test_profile_email",
            ],
        },
        Rust => {
            pass: [
                below_min_tests_threshold_allowed => r#"
                    #[test]
                    fn test_admin_can_delete() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let service = AuthService::new(repo);
                        assert!(service.can_delete("admin"));
                    }

                    #[test]
                    fn test_guest_cannot_delete() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let service = AuthService::new(repo);
                        assert!(!service.can_delete("guest"));
                    }
                "#,
                below_min_statements_threshold_allowed => r#"
                    #[test]
                    fn test_admin_role() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let user = repo.create("admin");
                        assert!(user.is_admin());
                    }

                    #[test]
                    fn test_guest_role() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let user = repo.create("guest");
                        assert!(!user.is_admin());
                    }

                    #[test]
                    fn test_editor_role() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let user = repo.create("editor");
                        assert!(!user.is_admin());
                    }
                "#,
                helper_function_exempt => r"
                    fn build_alpha() -> AuthService {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let service = AuthService::new(repo);
                        service
                    }

                    fn build_beta() -> AuthService {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let service = AuthService::new(repo);
                        service
                    }

                    fn build_gamma() -> AuthService {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        let service = AuthService::new(repo);
                        service
                    }
                ",
                local_item_declarations_not_counted_as_setup => r"
                    #[test]
                    fn test_first() {
                        struct Dummy;
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        assert_eq!(repo.count(), 0);
                    }

                    #[test]
                    fn test_second() {
                        struct Dummy;
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        assert!(repo.is_empty());
                    }

                    #[test]
                    fn test_third() {
                        struct Dummy;
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        assert_eq!(repo.items().len(), 0);
                    }
                ",
                assertions_not_counted_as_setup => r"
                    #[test]
                    fn test_first() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        assert_eq!(repo.count(), 0);
                    }

                    #[test]
                    fn test_second() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        assert_eq!(repo.count(), 0);
                    }

                    #[test]
                    fn test_third() {
                        let db = InMemoryDatabase::new();
                        let repo = UserRepository::new(db);
                        assert_eq!(repo.count(), 0);
                    }
                ",
                separate_test_modules_do_not_pool_across_scopes => r#"
                    mod admin_tests {
                        #[test]
                        fn test_can_delete() {
                            let db = InMemoryDatabase::new();
                            let repo = UserRepository::new(db);
                            let service = AuthService::new(repo);
                            assert!(service.can_delete("admin"));
                        }

                        #[test]
                        fn test_can_create() {
                            let db = InMemoryDatabase::new();
                            let repo = UserRepository::new(db);
                            let service = AuthService::new(repo);
                            assert!(service.can_create("admin"));
                        }
                    }

                    mod guest_tests {
                        #[test]
                        fn test_cannot_delete() {
                            let db = InMemoryDatabase::new();
                            let repo = UserRepository::new(db);
                            let service = AuthService::new(repo);
                            assert!(!service.can_delete("guest"));
                        }
                    }
                "#,
            ],
            fail: [
                three_module_tests_sharing_setup => r#"
                    mod order_tests {
                        #[test]
                        fn test_submit_order() {
                            let clock = FakeClock::new();
                            let ledger = InMemoryLedger::new();
                            let service = OrderService::new(clock, ledger);
                            assert!(service.submit("item"));
                        }

                        #[test]
                        fn test_cancel_order() {
                            let clock = FakeClock::new();
                            let ledger = InMemoryLedger::new();
                            let service = OrderService::new(clock, ledger);
                            assert!(service.cancel("item"));
                        }

                        #[test]
                        fn test_refund_order() {
                            let clock = FakeClock::new();
                            let ledger = InMemoryLedger::new();
                            let service = OrderService::new(clock, ledger);
                            assert!(service.refund("item"));
                        }
                    }
                "# => "test_submit_order",
            ],
        }
    }
);