testing-conventions 0.0.131

Enforce testing conventions in libraries (Python, TypeScript, and Rust).
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
use std::ffi::OsString;
use std::path::PathBuf;

use testing_conventions::isolation::find_violations;
use testing_conventions::run;

fn fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/isolation")
        .join(name)
}

/// Exit code of `unit lint --language rust <fixture>`. `--config` names the fixture's own
/// file — usually absent, meaning nothing is exempt — so that `--config`'s CWD-relative
/// default cannot pull this crate's config in over a fixture tree.
fn iso_exit(fixture_name: &str) -> i32 {
    let argv: Vec<OsString> = vec![
        "testing-conventions".into(),
        "unit".into(),
        "lint".into(),
        "--language".into(),
        "rust".into(),
        "--config".into(),
        fixture(fixture_name)
            .join("testing-conventions.toml")
            .into_os_string(),
        fixture(fixture_name).into_os_string(),
    ];
    run(argv).expect("a readable tree should not error")
}

/// `true` when scanning `fixture_name` yields an `no-out-of-module-call` violation
/// in the file ending `file_suffix`.
fn flagged(fixture_name: &str, file_suffix: &str) -> bool {
    find_violations(fixture(fixture_name), fixture(fixture_name))
        .expect("walking a readable tree should succeed")
        .iter()
        .any(|v| v.rule == "no-out-of-module-call" && v.file.ends_with(file_suffix))
}

#[test]
fn red_flags_first_party_cross_module_call() {
    assert!(
        flagged("unit/red", "cross_module.rs"),
        "`crate::store::load()` in a unit test must be flagged"
    );
}

#[test]
fn red_flags_effectful_std_call() {
    assert!(
        flagged("unit/red", "effectful_std.rs"),
        "`std::net::TcpStream::connect(...)` in a unit test must be flagged"
    );
}

#[test]
fn red_flags_a_spawned_process() {
    assert!(
        flagged("unit/red", "spawned_process.rs"),
        "`std::process::Command::new(...)` in a unit test must be flagged"
    );
}

#[test]
fn clean_allows_a_process_unique_temp_name() {
    assert!(
        !flagged("unit/clean", "unique_temp_name.rs"),
        "`std::process::id` reports the runner's own PID, so it names a temp directory the \
         way `env::temp_dir` does rather than reading ambient state"
    );
}

#[test]
fn clean_allows_a_fixture_read() {
    assert!(
        !flagged("unit/clean", "fixture_read.rs"),
        "`std::fs` and `std::env::temp_dir` build the tree a private walker needs, and the \
         inline module is the only tier that can reach a private item"
    );
}

#[test]
fn red_flags_external_crate_call() {
    assert!(
        flagged("unit/red", "external_crate.rs"),
        "`rand::random()` in a unit test must be flagged"
    );
}

#[test]
fn red_flags_ancestor_module_reach() {
    assert!(
        flagged("unit/red", "ancestor.rs"),
        "`super::super::util::help()` in a unit test must be flagged"
    );
}

#[test]
fn clean_reports_no_violations() {
    let violations = find_violations(fixture("unit/clean"), fixture("unit/clean"))
        .expect("walking a readable tree should succeed");
    assert!(
        violations.is_empty(),
        "the clean fixture is well-isolated (super:: + injected double + Cursor); got {violations:?}"
    );
}

#[test]
fn red_exits_nonzero() {
    assert_eq!(iso_exit("unit/red"), 1);
}

#[test]
fn clean_exits_zero() {
    assert_eq!(iso_exit("unit/clean"), 0);
}

#[test]
fn pure_construction_reports_no_violations() {
    let violations = find_violations(fixture("unit/pure"), fixture("unit/pure")).unwrap();
    assert!(violations.is_empty(), "got {violations:?}");
}

#[test]
fn pure_allowlist_keeps_effectful_and_glob_reaches_red() {
    let violations =
        find_violations(fixture("unit/pure_negative"), fixture("unit/pure_negative")).unwrap();
    let messages = violations
        .iter()
        .map(|v| v.message.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    for path in [
        "clap::*",
        "syn::parse::*",
        "std::process::Command",
        "std::os::unix::process::*",
        "toml::to_string",
        "zip::ZipWriter::new_append",
        "std::env::var",
        "std::thread::sleep",
    ] {
        assert!(messages.contains(path), "missing {path}: {messages}");
    }
    assert!(
        !messages.contains("clap::Command::new"),
        "pure call flagged: {messages}"
    );
}

#[test]
fn cfg_not_test_module_is_not_linted_as_test_code() {
    let violations = find_violations(fixture("unit/cfg_not_test"), fixture("unit/cfg_not_test"))
        .expect("walking a readable tree should succeed");
    assert!(
        violations.is_empty(),
        "production code under `#[cfg(not(test))]` must not be linted as a unit test; got {violations:?}"
    );
}

#[test]
fn cfg_not_test_exits_zero() {
    assert_eq!(iso_exit("unit/cfg_not_test"), 0);
}

/// `true` when scanning `fixture_name` yields a `no-out-of-module-import`
/// violation in the file ending `file_suffix`.
fn import_flagged(fixture_name: &str, file_suffix: &str) -> bool {
    find_violations(fixture(fixture_name), fixture(fixture_name))
        .expect("walking a readable tree should succeed")
        .iter()
        .any(|v| v.rule == "no-out-of-module-import" && v.file.ends_with(file_suffix))
}

#[test]
fn imports_red_flags_first_party_glob() {
    assert!(
        import_flagged("imports/red", "first_party_glob.rs"),
        "`use crate::other::*` in a unit test must be flagged"
    );
}

#[test]
fn imports_red_flags_first_party_named() {
    assert!(
        import_flagged("imports/red", "first_party_named.rs"),
        "`use crate::other::Thing` in a unit test must be flagged"
    );
}

#[test]
fn imports_red_flags_external_crate() {
    assert!(
        import_flagged("imports/red", "external_named.rs"),
        "`use rand::Rng` in a unit test must be flagged"
    );
}

#[test]
fn imports_red_flags_effectful_std() {
    assert!(
        import_flagged("imports/red", "effectful_std.rs"),
        "`use std::net` in a unit test must be flagged"
    );
}

#[test]
fn imports_clean_allows_the_filesystem() {
    assert!(
        !import_flagged("unit/clean", "fixture_read.rs"),
        "`use std::fs` follows the call: a unit test may build the tree it walks"
    );
}

#[test]
fn imports_clean_reports_no_violations() {
    let violations = find_violations(fixture("imports/clean"), fixture("imports/clean"))
        .expect("walking a readable tree should succeed");
    assert!(
        violations.is_empty(),
        "the clean fixture imports only super:: and pure std; got {violations:?}"
    );
}

#[test]
fn imports_red_exits_nonzero() {
    assert_eq!(iso_exit("imports/red"), 1);
}

#[test]
fn imports_clean_exits_zero() {
    assert_eq!(iso_exit("imports/clean"), 0);
}

#[test]
fn isolation_requires_language() {
    let err =
        run(["testing-conventions", "unit", "lint", "src"]).expect_err("--language is required");
    let clap_err = err
        .downcast_ref::<clap::Error>()
        .expect("a missing required flag should surface as a clap::Error");
    assert_eq!(
        clap_err.kind(),
        clap::error::ErrorKind::MissingRequiredArgument
    );
}

/// Exit code of `unit lint --language rust --config <config> <fixture>`.
fn iso_exit_config(fixture_name: &str, config_rel: &str) -> i32 {
    let argv: Vec<OsString> = vec![
        "testing-conventions".into(),
        "unit".into(),
        "lint".into(),
        "--language".into(),
        "rust".into(),
        "--config".into(),
        fixture(config_rel).into_os_string(),
        fixture(fixture_name).into_os_string(),
    ];
    run(argv).expect("a readable tree should not error")
}

#[test]
fn waived_out_of_module_call_exits_zero() {
    assert_eq!(
        iso_exit_config("unit/waived", "unit/waived/testing-conventions.toml"),
        0
    );
}

#[test]
fn stale_exempt_entry_errors() {
    let argv: Vec<OsString> = vec![
        "testing-conventions".into(),
        "unit".into(),
        "lint".into(),
        "--language".into(),
        "rust".into(),
        "--config".into(),
        fixture("unit/stale_exempt.toml").into_os_string(),
        fixture("unit/waived").into_os_string(),
    ];
    assert!(
        run(argv).is_err(),
        "a stale exempt entry must error, not silently pass"
    );
}

#[test]
fn local_build_crate_neither_aborts_nor_false_flags() {
    let violations = find_violations(fixture("unit/local_build"), fixture("unit/local_build"))
        .expect("a locally-built crate must not abort the rule on a tests/ or target/ file");
    assert!(
        violations.is_empty(),
        "target/ and tests/ must be skipped, so nothing is flagged; got {violations:?}"
    );
}

#[test]
fn local_build_crate_exits_zero() {
    assert_eq!(iso_exit("unit/local_build"), 0);
}

/// Every violation line in `fixture_name`'s file ending `file_suffix`.
fn lines_in(fixture_name: &str, file_suffix: &str) -> Vec<usize> {
    find_violations(fixture(fixture_name), fixture(fixture_name))
        .expect("walking a readable tree should succeed")
        .iter()
        .filter(|v| v.file.ends_with(file_suffix))
        .map(|v| v.line)
        .collect()
}

/// Exit code of `unit lint --language rust <fixture>/<sub>`, naming the fixture's own config.
fn iso_exit_subdir(fixture_name: &str, sub: &str) -> i32 {
    let argv: Vec<OsString> = vec![
        "testing-conventions".into(),
        "unit".into(),
        "lint".into(),
        "--language".into(),
        "rust".into(),
        "--config".into(),
        fixture(fixture_name)
            .join("testing-conventions.toml")
            .into_os_string(),
        fixture(fixture_name).join(sub).into_os_string(),
    ];
    run(argv).expect("a readable tree should not error")
}

#[test]
fn scanning_src_still_reads_the_crate_manifest() {
    let violations = find_violations(fixture("unit/red").join("src"), fixture("unit/red"))
        .expect("walking a readable tree should succeed");
    assert!(
        violations
            .iter()
            .any(|v| v.file.ends_with("external_crate.rs")),
        "`rand::random()` must stay flagged when the scan path is `src/`; got {violations:?}"
    );
}

#[test]
fn scanning_src_exits_nonzero() {
    assert_eq!(
        iso_exit_subdir("unit/red", "src"),
        1,
        "pointing the gate one level down must not turn a red tree green"
    );
}

#[test]
fn an_exempt_path_stays_crate_root_relative_from_src() {
    assert_eq!(
        iso_exit_subdir("unit/waived", "src"),
        0,
        "`path = \"src/widget.rs\"` must resolve from either scan path — the exempt root \
         is the crate root, not the scan path"
    );
}

#[test]
fn a_reach_inside_assert_is_caught() {
    let lines = lines_in("unit/macro_body", "asserted.rs");
    assert!(
        lines.contains(&14),
        "`assert!(crate::other::load())` hides a first-party reach in a token body; got {lines:?}"
    );
}

#[test]
fn a_direct_and_an_asserted_reach_agree() {
    let lines = lines_in("unit/macro_body", "asserted.rs");
    assert!(
        lines.contains(&9) && lines.contains(&14),
        "the direct and macro-wrapped forms of the same reach must both be flagged; got {lines:?}"
    );
}

#[test]
fn an_external_reach_among_assert_eq_args_is_caught() {
    let lines = lines_in("unit/macro_body", "asserted.rs");
    assert!(
        lines.contains(&19),
        "every comma-separated argument is a written expression, including the format \
         arguments; got {lines:?}"
    );
}

#[test]
fn a_quoted_template_is_not_a_reach() {
    let lines = lines_in("unit/macro_body", "quoted.rs");
    assert!(
        lines.is_empty(),
        "`quote!` tokens are a template for code emitted elsewhere, not a call made here; \
         got {lines:?}"
    );
}

#[test]
fn an_import_inside_an_item_body_macro_is_caught() {
    let imports: Vec<_> = find_violations(fixture("unit/macro_body"), fixture("unit/macro_body"))
        .expect("walking a readable tree should succeed")
        .into_iter()
        .filter(|v| v.rule == "no-out-of-module-import" && v.file.ends_with("item_body.rs"))
        .collect();
    assert!(
        !imports.is_empty(),
        "a macro body that parses as items still carries a written `use`; got {imports:?}"
    );
}

#[test]
fn macro_body_exits_nonzero() {
    assert_eq!(iso_exit("unit/macro_body"), 1);
}

#[test]
fn this_crate_has_no_out_of_module_command_reaches() {
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let reaches: Vec<_> = find_violations(&root, &root)
        .unwrap()
        .into_iter()
        .filter(|v| v.message.contains("crate::command"))
        .collect();
    assert!(
        reaches.is_empty(),
        "tests/workflow.rs covers the real command tree, so no inline test needs to \
         build one; got {reaches:?}"
    );
}