cuke-dedup 0.14.0

Static analysis for duplicate and reusable Cucumber step definitions
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
use cuke_dedup::analysis::{analyze, analyze_with_diagnostics};
use cuke_dedup::config::{Config, ConfigOverrides, ReporterKind};
use cuke_dedup::discovery::{SourceFile, SourceLanguage};
use cuke_dedup::model::SourceLocation;
use cuke_dedup::model::{AnalysisResult, Rule, Severity};
use cuke_dedup::modes::{BaselineFile, BASELINE_SCHEMA_VERSION};
use cuke_dedup::reporters::{
    render_html, render_json, render_jsonl, render_sarif, write_terminal, ExecutionMetrics,
    ReportContext,
};
use cuke_dedup::source_adapter::{
    Extraction, ExtractionDiagnostic, ExtractionDiagnosticLevel, SourceAdapter,
    SourceAdapterRegistration, SourceParameterType, SOURCE_ADAPTER_REGISTRY,
};
use cuke_dedup::typescript;
use std::collections::BTreeMap;
use std::fs;
use std::path::PathBuf;

/// The registered adapter for `language`, for tests that drive extraction directly.
fn registered_adapter(language: SourceLanguage) -> &'static dyn SourceAdapter {
    SOURCE_ADAPTER_REGISTRY
        .iter()
        .map(|registration| registration.adapter)
        .find(|adapter| adapter.language() == language)
        .expect("an adapter is registered for the language")
}

/// Checks external adapters retain session constructors, auto traits, default capabilities, and legacy extraction delegation.
#[test]
fn extraction_session_preserves_public_constructors_auto_traits_and_adapter_defaults() {
    use cuke_dedup::source_adapter::SourceExtractionSession;
    use std::panic::{RefUnwindSafe, UnwindSafe};
    /// Requires session types to satisfy the public thread-safety, pinning, and unwind-safety trait bounds at compile time.
    fn assert_auto_traits<T: Send + Sync + Unpin + UnwindSafe + RefUnwindSafe>() {}
    assert_auto_traits::<SourceExtractionSession>();

    struct ExternalAdapter;
    impl SourceAdapter for ExternalAdapter {
        /// Returns the external test adapter's stable name.
        fn name(&self) -> &'static str {
            "external"
        }
        /// Identifies the external test adapter as JavaScript.
        fn language(&self) -> SourceLanguage {
            SourceLanguage::JavaScript
        }
        /// Returns a sentinel failure to verify default session delegation reaches the external adapter.
        fn extract(&self, _: &str, _: &SourceFile) -> anyhow::Result<Extraction> {
            anyhow::bail!("external adapter reached")
        }
    }
    let project = tempfile::tempdir().unwrap();
    let file = SourceFile {
        path: project.path().join("steps.js"),
        language: SourceLanguage::JavaScript,
    };
    let adapter: &dyn SourceAdapter = &ExternalAdapter;
    assert!(adapter.discover_by_default());
    assert!(!adapter.supports_indirect_usage());
    assert_eq!(adapter.inspect_source(&file, &[]), None);
    let configured = BTreeMap::from([("custom".to_owned(), "[a-z]+".to_owned())]);
    assert_eq!(
        adapter.resolve_parameter_types(Vec::new(), &configured),
        (configured.clone(), Vec::new())
    );
    let declaration = SourceParameterType::new(
        Some("custom".to_owned()),
        Some(".+".to_owned()),
        SourceLocation::new(PathBuf::from("steps.js"), 1, 1, 1, 2),
    );
    let (patterns, diagnostics) = adapter.resolve_parameter_types(vec![declaration], &configured);
    assert!(patterns.is_empty());
    assert!(!diagnostics.is_empty());
    for mut session in [
        SourceExtractionSession::default(),
        SourceExtractionSession::new(project.path()),
        SourceExtractionSession::with_registrations(project.path(), &["Setup".into()]),
    ] {
        assert_eq!(
            adapter
                .extract_with_session("", &file, &mut session)
                .unwrap_err()
                .to_string(),
            "external adapter reached"
        );
    }
}

/// Maps known reporter variants to names and accommodates future non-exhaustive variants.
fn reporter_name(reporter: ReporterKind) -> &'static str {
    match reporter {
        ReporterKind::Terminal => "terminal",
        ReporterKind::Json => "json",
        ReporterKind::Jsonl => "jsonl",
        ReporterKind::Html => "html",
        ReporterKind::Sarif => "sarif",
        _ => "future reporter",
    }
}

/// Checks diagnostic analysis preserves a definition after a regex limit while strict analysis returns that limit as an error.
#[test]
fn external_callers_can_preserve_partial_results_and_operational_diagnostics() {
    let definitions = typescript::extract(
        "Given(/a{1000000}/, () => work());",
        &SourceFile {
            path: PathBuf::from("steps.ts"),
            language: SourceLanguage::TypeScript,
        },
    )
    .unwrap();
    let directory = tempfile::tempdir().unwrap();
    let config = Config::load(directory.path(), ConfigOverrides::default()).unwrap();

    let outcome = analyze_with_diagnostics(definitions.clone(), Vec::new(), &config).unwrap();
    assert_eq!(outcome.result.definitions.len(), 1);
    assert_eq!(outcome.incomplete.len(), 1);
    assert!(outcome.incomplete[0].contains("regex resource limit"));

    let error = analyze(definitions, Vec::new(), &config).unwrap_err();
    assert!(error.to_string().contains("regex resource limit"));
}

/// Checks sessionless extraction resolves a local registration re-export within the nearest package boundary.
#[test]
fn sessionless_file_extraction_uses_the_nearest_package_boundary() {
    let directory = tempfile::tempdir().unwrap();
    fs::write(directory.path().join("package.json"), "{}").unwrap();
    fs::write(
        directory.path().join("support.ts"),
        "export { Given } from '@cucumber/cucumber';\n",
    )
    .unwrap();
    let steps = directory.path().join("nested/deeper/steps.ts");
    fs::create_dir_all(steps.parent().unwrap()).unwrap();
    fs::write(
        &steps,
        "import { Given } from '../../support';\nGiven('nested public API step', () => work());\n",
    )
    .unwrap();

    let definitions = typescript::extract_file(&SourceFile {
        path: steps,
        language: SourceLanguage::TypeScript,
    })
    .unwrap();

    assert_eq!(definitions.len(), 1);
    assert_eq!(definitions[0].matcher, "nested public API step");
}

/// Checks external callers can construct configuration, metrics, diagnostics, baselines, and adapter registrations through public APIs.
#[test]
fn extensible_public_outputs_use_stable_constructors() {
    let overrides = ConfigOverrides {
        config_file: None,
        definitions: None,
        features: None,
        exclude: None,
        exclude_defaults: None,
        include_hidden: None,
        reporters: Some(vec![ReporterKind::Json]),
        output: None,
        threshold: None,
        require_features: None,
        no_metrics: None,
        rules: BTreeMap::<Rule, Severity>::new(),
    };
    assert_eq!(overrides.reporters, Some(vec![ReporterKind::Json]));

    let metrics = ExecutionMetrics::new(1, 2, 1.0, 2.0, 3.0);
    assert_eq!(metrics.files_discovered, 3);

    let diagnostic = ExtractionDiagnostic::new(
        ExtractionDiagnosticLevel::Warning,
        SourceLocation::new("steps.ts", 1, 1, 1, 2),
        "dynamic matcher",
    );
    let extraction = Extraction::new(Vec::new(), vec![diagnostic]);
    assert_eq!(extraction.diagnostics.len(), 1);

    let baseline = BaselineFile::new(BTreeMap::from([("finding".to_owned(), 1)]));
    assert_eq!(baseline.fingerprints["finding"], 1);

    let default_baseline = BaselineFile::default();
    assert_eq!(default_baseline.schema_version, BASELINE_SCHEMA_VERSION);
    assert!(default_baseline.fingerprints.is_empty());

    let registration =
        SourceAdapterRegistration::new(".custom", SOURCE_ADAPTER_REGISTRY[0].adapter);
    assert_eq!(registration.suffix, ".custom");

    let all_rules: &[Rule] = Rule::ALL;
    let duplication_rules: &[Rule] = Rule::DUPLICATION_THRESHOLD;
    assert!(all_rules.len() > duplication_rules.len());

    assert_eq!(reporter_name(ReporterKind::Json), "json");
}

/// Checks every public renderer accepts one report context with its configured duplication threshold.
#[test]
fn report_context_is_the_single_public_rendering_entry_point() {
    let root = PathBuf::from("/repo");
    let result = AnalysisResult::new(Vec::new(), Vec::new(), Vec::new());
    let context = ReportContext::new(&result, &root, 5.0);

    assert!(render_json(&context)
        .unwrap()
        .contains("\"threshold\": 5.0"));
    assert!(render_jsonl(&context)
        .unwrap()
        .contains("\"type\":\"summary\""));
    assert!(render_html(&context).unwrap().contains("<!doctype html>"));
    assert!(render_sarif(&context)
        .unwrap()
        .contains("\"version\": \"2.1.0\""));

    let mut terminal = Vec::new();
    write_terminal(&context, &mut terminal).unwrap();
    assert!(String::from_utf8(terminal)
        .unwrap()
        .contains("Analyzed 0 definitions"));
}

/// Checks lowercase global registrations require explicit session configuration before they extract definitions.
#[test]
fn configured_registrations_enable_lowercase_global_step_names() {
    use cuke_dedup::source_adapter::SourceExtractionSession;

    let project = tempfile::tempdir().unwrap();
    let file = SourceFile {
        path: project.path().join("steps.ts"),
        language: SourceLanguage::TypeScript,
    };
    let adapter = registered_adapter(SourceLanguage::TypeScript);
    let source = "given('a lowercase global step', () => work());";

    // Lowercase `given`/`when`/`then` are not ambient globals: a bare call with no import and no
    // configuration registers nothing, so the analyzer never invents a step from an unrelated
    // lowercase helper.
    let mut plain = SourceExtractionSession::new(project.path());
    assert!(adapter
        .extract_with_session(source, &file, &mut plain)
        .unwrap()
        .definitions
        .is_empty());

    // The `registrations` configuration is the documented opt-in: naming `given` there enables it
    // as a bare global registration name.
    let mut configured =
        SourceExtractionSession::with_registrations(project.path(), &["given".into()]);
    assert_eq!(
        adapter
            .extract_with_session(source, &file, &mut configured)
            .unwrap()
            .definitions
            .len(),
        1
    );
}

/// Checks local registration barrels resolve through CommonJS and ESM while missing or malformed bindings remain empty.
#[test]
fn local_commonjs_and_esm_barrel_imports_resolve_registrations_in_process() {
    use cuke_dedup::source_adapter::SourceExtractionSession;

    let project = tempfile::tempdir().unwrap();
    fs::write(project.path().join("package.json"), "{}").unwrap();
    fs::write(
        project.path().join("barrel.js"),
        "const { Given } = require('@cucumber/cucumber');\nmodule.exports = { Given };\n",
    )
    .unwrap();
    let adapter = registered_adapter(SourceLanguage::JavaScript);
    let file = SourceFile {
        path: project.path().join("steps.js"),
        language: SourceLanguage::JavaScript,
    };
    let extract = |source: &str| {
        let mut session = SourceExtractionSession::new(project.path());
        adapter
            .extract_with_session(source, &file, &mut session)
            .unwrap()
            .definitions
            .len()
    };

    // A project-local barrel resolves whether imported through CommonJS `require` or an ESM
    // specifier — the two importer paths share one resolution helper.
    assert_eq!(
        extract(
            "const { Given: reg } = require('./barrel');\nreg('cjs a', () => {});\nreg('cjs b', () => {});"
        ),
        2
    );
    assert_eq!(
        extract(
            "import { Given as reg } from './barrel';\nreg('esm a', () => {});\nreg('esm b', () => {});"
        ),
        2
    );
    // A `require` with no specifier, and one of an unresolvable local module, register nothing.
    assert_eq!(extract("const missing = require();\n"), 0);
    assert_eq!(
        extract("const { Given: reg } = require('./nope');\nreg('x', () => {});"),
        0
    );
    // Error-recovered declarations with no name or value register nothing and never panic.
    assert_eq!(extract("const = 5;\nvar ;\nlet x;"), 0);
}

/// Checks a CommonJS local barrel preserves Playwright-BDD factory registration extraction.
#[test]
fn local_barrel_re_exporting_the_bdd_factory_resolves_through_require() {
    use cuke_dedup::source_adapter::SourceExtractionSession;

    let project = tempfile::tempdir().unwrap();
    fs::write(project.path().join("package.json"), "{}").unwrap();
    // A local barrel re-exporting Playwright-BDD's `createBdd` factory. Destructuring it from a
    // local `require` must enter the factory path, exactly as an ESM import would, or the steps it
    // creates are missed.
    fs::write(
        project.path().join("barrel.js"),
        "const { createBdd } = require('playwright-bdd');\nmodule.exports = { createBdd };\n",
    )
    .unwrap();
    let adapter = registered_adapter(SourceLanguage::JavaScript);
    let file = SourceFile {
        path: project.path().join("steps.js"),
        language: SourceLanguage::JavaScript,
    };
    let mut session = SourceExtractionSession::new(project.path());
    let definitions = adapter
        .extract_with_session(
            "const { createBdd } = require('./barrel');\nconst { Given } = createBdd();\nGiven('a step', () => {});\nGiven('a step', () => {});",
            &file,
            &mut session,
        )
        .unwrap()
        .definitions;
    assert_eq!(definitions.len(), 2);
}

/// Checks typed incomplete diagnostics retain their kind independently of message wording.
#[test]
fn adapters_can_classify_diagnostics_without_language_specific_messages() {
    use cuke_dedup::source_adapter::ExtractionDiagnosticKind;
    let diagnostic = ExtractionDiagnostic::with_kind(
        ExtractionDiagnosticKind::Incomplete,
        ExtractionDiagnosticLevel::Warning,
        SourceLocation::new("steps.rb", 1, 1, 1, 1),
        "external glue unavailable",
    );
    assert_eq!(diagnostic.kind, ExtractionDiagnosticKind::Incomplete);
    assert_eq!(diagnostic.message, "external glue unavailable");
}

/// Checks Ruby usage metadata enables precise unused findings while legacy analysis preserves conservative incompleteness.
#[test]
fn ruby_usage_metadata_and_legacy_analysis_remain_conservative() {
    let root = tempfile::tempdir().unwrap();
    let config = Config::load(root.path(), ConfigOverrides::default()).unwrap();
    let file = SourceFile {
        path: root.path().join("steps.rb"),
        language: SourceLanguage::Ruby,
    };
    let extracted = registered_adapter(SourceLanguage::Ruby).extract(
        "Given('target') { first() }; Then('unused') { second() }; def helper; step 'target'; end", &file).unwrap();
    let features = cuke_dedup::gherkin::extract(
        "Feature: usage\n Scenario: other\n  Given other\n",
        &root.path().join("suite.feature"),
    )
    .unwrap();
    let legacy =
        analyze_with_diagnostics(extracted.definitions.clone(), features.clone(), &config).unwrap();
    assert!(!legacy.incomplete.is_empty());
    assert!(!legacy
        .result
        .findings
        .iter()
        .any(|f| f.rule == Rule::UnusedDefinition));
    let mut usage = extracted.indirect_usage.unwrap();
    let known = cuke_dedup::analysis::analyze_with_step_usage(
        extracted.definitions.clone(),
        features.clone(),
        &config,
        &usage,
    )
    .unwrap();
    let unused: Vec<_> = known
        .result
        .findings
        .iter()
        .filter(|f| f.rule == Rule::UnusedDefinition)
        .collect();
    assert_eq!(unused.len(), 1);
    assert!(unused[0].message.contains("`unused`"));
    assert!(known.incomplete.is_empty());
    usage.extend(None);
    assert!(usage.unknown);
}

/// External callers over Ruby extraction: an over-limit Ruby regex remains in the extracted
/// definitions without a misleading syntax diagnostic. Analysis keeps the neighbouring finding
/// with the regex resource-limit diagnostic, while an unsupported syntax control retains a typed
/// extraction diagnostic. Strict `analyze` rejects the limit, and every public renderer takes the
/// Ruby result through one report context.
#[test]
fn ruby_extraction_flows_through_the_public_diagnostic_analysis_and_report_api() {
    use cuke_dedup::source_adapter::ExtractionDiagnosticKind;
    let root = tempfile::tempdir().unwrap();
    let file = SourceFile {
        path: root.path().join("steps.rb"),
        language: SourceLanguage::Ruby,
    };
    let source = format!(
        "Given('kept') {{ kept }}\nGiven('kept') {{ other }}\n\nGiven(/{}/) {{ work }}\n",
        "a".repeat(1024 * 1024 + 1)
    );
    let extracted = registered_adapter(SourceLanguage::Ruby)
        .extract(&source, &file)
        .unwrap();
    assert_eq!(extracted.definitions.len(), 3);
    assert!(extracted.diagnostics.is_empty());
    let unsupported = registered_adapter(SourceLanguage::Ruby)
        .extract("Given(/^a++$/) { work }\n", &file)
        .unwrap();
    let diagnostic = unsupported.diagnostics.first().unwrap();
    assert_eq!(diagnostic.kind, ExtractionDiagnosticKind::Incomplete);
    assert_eq!(diagnostic.level, ExtractionDiagnosticLevel::Warning);
    assert_eq!(
        (diagnostic.location.line, diagnostic.location.column),
        (1, 1)
    );
    assert!(diagnostic
        .message
        .contains("supported static matching subset"));

    let config = Config::load(root.path(), ConfigOverrides::default()).unwrap();
    let outcome =
        analyze_with_diagnostics(extracted.definitions.clone(), Vec::new(), &config).unwrap();
    assert_eq!(outcome.result.definitions.len(), 3);
    assert!(outcome
        .incomplete
        .iter()
        .any(|message| message.contains("steps.rb:4:1 exceeds")
            && message.contains("regex resource limit")));
    assert_eq!(outcome.result.findings.len(), 1);
    assert_eq!(outcome.result.findings[0].rule, Rule::DuplicateMatcher);
    let error = analyze(extracted.definitions, Vec::new(), &config).unwrap_err();
    assert!(error.to_string().contains("regex resource limit"));

    let context = ReportContext::new(&outcome.result, root.path(), 5.0);
    assert!(render_json(&context)
        .unwrap()
        .contains("\"path\": \"steps.rb\""));
    assert!(render_jsonl(&context)
        .unwrap()
        .contains("\"type\":\"summary\""));
    assert!(render_html(&context).unwrap().contains("steps.rb:1:1"));
    assert!(render_sarif(&context)
        .unwrap()
        .contains("\"uri\": \"steps.rb\""));
    let mut terminal = Vec::new();
    write_terminal(&context, &mut terminal).unwrap();
    let terminal = String::from_utf8(terminal).unwrap();
    assert!(terminal.contains("Analyzed 3 definitions"));
    assert!(terminal.contains("steps.rb:1:1"));
}