alef 0.67.3

Opinionated polyglot binding generator for Rust libraries
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
#[cfg(test)]
mod not_empty_tests {
    use super::super::assertions::render_assertion;
    use crate::e2e::config::E2eConfig;
    use crate::e2e::field_access::FieldResolver;
    use crate::e2e::fixture::Assertion;
    use std::collections::{HashMap, HashSet};

    fn render_not_empty(field: Option<&str>, result_is_simple: bool) -> String {
        let resolver = FieldResolver::new(
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        );
        let assertion = Assertion {
            assertion_type: "not_empty".to_string(),
            field: field.map(str::to_string),
            ..Default::default()
        };
        let mut out = String::new();
        render_assertion(
            &mut out,
            &assertion,
            "result",
            &resolver,
            result_is_simple,
            &E2eConfig::default(),
            &HashSet::new(),
            &HashMap::new(),
        );
        out
    }

    /// `[].to_s` is `"[]"` — a non-empty String — so measuring the stringified value
    /// made the assertion unfalsifiable on an empty collection.
    #[test]
    fn not_empty_for_ruby_asks_the_value_not_its_string_form() {
        let out = render_not_empty(None, false);
        assert!(!out.contains(".to_s"), "got: {out}");
        assert_eq!(
            out.trim(),
            "expect(result.respond_to?(:empty?) ? !result.empty? : !result.nil?).to be(true)"
        );
    }

    #[test]
    fn not_empty_for_ruby_simple_results_asks_the_value_not_its_string_form() {
        let out = render_not_empty(Some("audio"), true);
        assert!(!out.contains(".to_s"), "got: {out}");
        assert_eq!(
            out.trim(),
            "expect(result.respond_to?(:empty?) ? !result.empty? : !result.nil?).to be(true)"
        );
    }
}

#[cfg(test)]
mod chunk_heading_context_tests {
    use super::super::assertions::render_assertion;
    use crate::e2e::config::E2eConfig;
    use crate::e2e::field_access::FieldResolver;
    use crate::e2e::fixture::Assertion;
    use std::collections::{HashMap, HashSet};

    fn render(field: &str, assertion_type: &str, value: Option<serde_json::Value>) -> String {
        let resolver = FieldResolver::new(
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        );
        let assertion = Assertion {
            assertion_type: assertion_type.to_string(),
            field: Some(field.to_string()),
            value,
            ..Default::default()
        };
        let mut out = String::new();
        render_assertion(
            &mut out,
            &assertion,
            "result",
            &resolver,
            false,
            &E2eConfig::default(),
            &HashSet::new(),
            &HashMap::new(),
        );
        out
    }

    /// Magnus generates a real typed accessor for every non-excluded struct field
    /// (`gen_field_accessor` in the magnus backend), the same mechanism that already lets this
    /// file assert `c.content` and `c.embedding` on a Ruby `Chunk`. `heading_context` is such a
    /// field, so it is reachable exactly like it is for Elixir, C#, Java and TypeScript — the old
    /// unconditional "not available on Ruby Chunk binding" skip was never checking anything.
    #[test]
    fn chunks_have_heading_context_is_asserted_not_skipped() {
        let out = render("chunks_have_heading_context", "is_true", None);
        assert!(!out.contains("skipped"), "got: {out}");
        assert_eq!(
            out.trim(),
            "expect((result.chunks || []).all? { |c| c.metadata && !c.metadata.heading_context.nil? }).to be(true)"
        );
    }

    #[test]
    fn chunks_have_heading_context_is_false_is_asserted_not_skipped() {
        let out = render("chunks_have_heading_context", "is_false", None);
        assert!(!out.contains("skipped"), "got: {out}");
        assert_eq!(
            out.trim(),
            "expect((result.chunks || []).all? { |c| c.metadata && !c.metadata.heading_context.nil? }).to be(false)"
        );
    }

    #[test]
    fn first_chunk_starts_with_heading_is_asserted_not_skipped() {
        let out = render("first_chunk_starts_with_heading", "is_true", None);
        assert!(!out.contains("skipped"), "got: {out}");
        assert_eq!(
            out.trim(),
            "expect(!(result.chunks || []).first&.metadata&.heading_context.nil?).to be(true)"
        );
    }

    /// Negative control for the fix above: a field that genuinely cannot be reached the same
    /// way in Ruby still skips. Magnus's `IntoValue` for a data enum serializes it via
    /// `serde_json::to_value` into a plain Hash (`enum_magnus.rs.jinja`), so a variant accessor
    /// like `.excel` has no Ruby method to call — this skip has a real, checkable cause, unlike
    /// the heading-context one that used to fire unconditionally.
    #[test]
    fn enum_variant_accessor_still_skips_because_ruby_serializes_it_to_a_hash() {
        let out = render("metadata.format.excel", "equals", Some(serde_json::json!("Excel")));
        assert!(out.contains("# skipped:"), "got: {out}");
        assert!(
            out.contains("enum variant accessor 'metadata.format.excel' not available on Ruby (serialized to Hash)"),
            "got: {out}"
        );
    }
}

#[cfg(test)]
mod trait_bridge_tests {
    use super::super::project::render_spec_helper;
    use super::super::stubs::emit_test_backend;
    use crate::core::config::TraitBridgeConfig;
    use crate::core::ir::{MethodDef, ParamDef, TypeRef};
    use crate::e2e::fixture::Fixture;
    use std::collections::HashMap;

    fn make_fixture(id: &str) -> Fixture {
        Fixture {
            docs: None,
            requirements: Vec::new(),
            id: id.to_string(),
            category: None,
            description: "test".to_string(),
            tags: vec![],
            skip: None,
            env: None,
            setup: Vec::new(),
            call: None,
            input: serde_json::Value::Null,
            mock_response: None,
            source: String::new(),
            http: None,
            asyncapi: None,
            websocket: None,
            preserve_input_urls: false,
            assertions: vec![],
            visitor: None,
            args: vec![],
            assertion_recipes: vec![],
        }
    }

    fn make_param(name: &str, ty: TypeRef) -> ParamDef {
        ParamDef {
            name: name.to_string(),
            ty,
            optional: false,
            default: None,
            sanitized: false,
            typed_default: None,
            is_ref: false,
            is_mut: false,
            newtype_wrapper: None,
            original_type: None,
            map_is_ahash: false,
            map_key_is_cow: false,
            vec_inner_is_ref: false,
            map_is_btree: false,
            core_wrapper: crate::core::ir::CoreWrapper::None,
        }
    }

    fn make_method(name: &str, params: Vec<(&str, TypeRef)>, ret: TypeRef, is_async: bool) -> MethodDef {
        MethodDef {
            name: name.to_string(),
            params: params.into_iter().map(|(n, ty)| make_param(n, ty)).collect(),
            return_type: ret,
            is_async,
            is_static: false,
            error_type: None,
            doc: String::new(),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            cfg: None,
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
            version: Default::default(),
        }
    }

    #[test]
    fn spec_helper_stays_generic_for_library_specific_setup() {
        let content = render_spec_helper(
            true,
            false,
            false,
            "../../fixtures",
            "custom_gem",
            "custom_module",
            "127.0.0.1",
            8000,
            &HashMap::new(),
        );

        assert!(
            !content.contains("require 'custom_gem'"),
            "spec helper must not require the generated gem directly:\n{content}"
        );
        assert!(
            !content.contains("CustomModule") && !content.contains("SampleCrate") && !content.contains("sample_crate"),
            "spec helper must avoid library-specific module cleanup:\n{content}"
        );
    }

    /// Genericity test: a synthetic TestTrait with one sync method and Plugin super-trait
    /// must not reference any sample_core-domain names in setup_block or arg_expr.
    #[test]
    fn test_backend_emission_is_generic() {
        let trait_bridge = TraitBridgeConfig {
            trait_name: "TestTrait".to_string(),
            super_trait: Some("SomeSuperTrait".to_string()),
            register_fn: Some("register_test_trait".to_string()),
            ..TraitBridgeConfig::default()
        };

        let do_thing = make_method(
            "do_thing",
            vec![("x", TypeRef::Primitive(crate::core::ir::PrimitiveType::I32))],
            TypeRef::String,
            false,
        );

        let fixture = make_fixture("my_test_fixture");
        let methods = vec![&do_thing];
        let emission = emit_test_backend(&trait_bridge, &methods, &fixture);

        // setup_block must not reference any sample_core-domain trait or method names.
        assert!(
            !emission.setup_block.contains("OcrBackend"),
            "setup_block must not hardcode domain trait names, got:\n{}",
            emission.setup_block
        );
        assert!(
            !emission.setup_block.contains("process_image"),
            "setup_block must not hardcode domain method names, got:\n{}",
            emission.setup_block
        );
        // Must emit the method name from MethodDef.
        assert!(
            emission.setup_block.contains("do_thing"),
            "setup_block must contain the method name 'do_thing', got:\n{}",
            emission.setup_block
        );
        // Must emit Plugin name method when super_trait is set.
        assert!(
            emission.setup_block.contains("name"),
            "setup_block must emit 'name' for super_trait, got:\n{}",
            emission.setup_block
        );
        // arg_expr must reference the fixture id.
        assert!(
            emission.arg_expr.contains("my_test_fixture"),
            "arg_expr must reference fixture id, got: {}",
            emission.arg_expr
        );
    }

    /// Named return types must emit `'{}'` (JSON-safe string), not `TypeName.new`
    /// which would reference an undefined Ruby constant.
    #[test]
    fn test_backend_named_return_emits_json_string() {
        let trait_bridge = TraitBridgeConfig {
            trait_name: "DocumentExtractor".to_string(),
            super_trait: Some("Plugin".to_string()),
            register_fn: Some("register_document_extractor".to_string()),
            ..TraitBridgeConfig::default()
        };

        let extract_bytes = make_method(
            "extract_bytes",
            vec![("content", TypeRef::Bytes), ("mime_type", TypeRef::String)],
            TypeRef::Named("HiddenRecord".to_string()),
            false,
        );

        let fixture = make_fixture("register_document_extractor_trait_bridge");
        let methods = vec![&extract_bytes];
        let emission = emit_test_backend(&trait_bridge, &methods, &fixture);

        assert!(
            emission.setup_block.contains("'{}'"),
            "Named return type must emit '{{}}' not a constructor call, got:\n{}",
            emission.setup_block
        );
        assert!(
            !emission.setup_block.contains("HiddenRecord.new"),
            "setup_block must not reference undefined constant HiddenRecord, got:\n{}",
            emission.setup_block
        );
    }

    /// Backend name must be extracted from fixture.input, not fixture.id.
    #[test]
    fn test_backend_name_from_input() {
        let trait_bridge = TraitBridgeConfig {
            trait_name: "DocumentExtractor".to_string(),
            super_trait: Some("Plugin".to_string()),
            register_fn: Some("register_document_extractor".to_string()),
            ..TraitBridgeConfig::default()
        };

        let extract_bytes = make_method(
            "extract_bytes",
            vec![("content", TypeRef::Bytes)],
            TypeRef::Named("HiddenRecord".to_string()),
            false,
        );

        let mut fixture = make_fixture("register_document_extractor_trait_bridge");
        fixture.input = serde_json::json!({
            "extractor": { "type": "test", "name": "test-extractor" }
        });

        let methods = vec![&extract_bytes];
        let emission = emit_test_backend(&trait_bridge, &methods, &fixture);

        assert!(
            emission.setup_block.contains("test-extractor"),
            "setup_block must use input-derived name 'test-extractor', got:\n{}",
            emission.setup_block
        );
        // The fixture id appears in the variable name (stub_register_...) but
        // the name() method must return the input-derived name, not the fixture id.
        assert!(
            !emission
                .setup_block
                .contains("= 'register_document_extractor_trait_bridge'"),
            "name() method must not return fixture id, got:\n{}",
            emission.setup_block
        );
    }

    /// Snapshot: verify exact setup_block shape for a DocumentExtractor-like bridge.
    #[test]
    fn test_backend_snapshot() {
        let trait_bridge = TraitBridgeConfig {
            trait_name: "DocumentExtractor".to_string(),
            super_trait: Some("Plugin".to_string()),
            register_fn: Some("register_document_extractor".to_string()),
            ..TraitBridgeConfig::default()
        };

        let extract_bytes = make_method(
            "extract_bytes",
            vec![
                ("content", TypeRef::Bytes),
                ("mime_type", TypeRef::String),
                ("config", TypeRef::Named("ExtractionConfig".to_string())),
            ],
            TypeRef::Named("HiddenRecord".to_string()),
            false,
        );

        let mut fixture = make_fixture("register_document_extractor_trait_bridge");
        fixture.input = serde_json::json!({
            "extractor": { "type": "test", "name": "test-extractor" }
        });

        let methods = vec![&extract_bytes];
        let emission = emit_test_backend(&trait_bridge, &methods, &fixture);

        let expected_setup = concat!(
            "stub_register_document_extractor_trait_bridge = Class.new do\n",
            "  def name = 'test-extractor'\n",
            "  def initialize\n",
            "    nil\n",
            "  end\n",
            "  def shutdown\n",
            "    nil\n",
            "  end\n",
            "  def version = '1.0.0'\n",
            "  def extract_bytes(content, mime_type, config) = '{}'\n",
            "end.new\n",
        );
        assert_eq!(emission.setup_block, expected_setup, "setup_block snapshot mismatch");
        assert_eq!(emission.arg_expr, "stub_register_document_extractor_trait_bridge");
    }
}

// `render_gemfile` tests used to live here too (as `gemfile_tests`), duplicating
// `project::tests` (`src/e2e/codegen/ruby/project.rs`) with different fixture
// literals (`my-gem` vs `my_gem`). The two drifted independently: this module's
// copies still asserted the old `~>` pessimistic-range behavior after
// `project::tests` was updated for exact version pinning, and only one side got
// caught. Consolidated into `project::tests`, the single owner of that
// function's tests — see `render_gemfile_registry_uses_exact_pin` and friends
// there. ~keep
#[cfg(test)]
mod app_harness_tests {
    use super::super::project::render_app_harness;

    #[test]
    fn app_harness_rb_contains_eaddrinuse_retry_block() {
        use crate::core::config::e2e::{E2eConfig, HarnessConfig};
        use crate::e2e::fixture::{Fixture, FixtureGroup, HttpExpectedResponse, HttpFixture, HttpHandler, HttpRequest};
        use std::collections::BTreeMap;

        // Build a minimal HTTP fixture so render_app_harness produces server-pattern content.
        let fixture = Fixture {
            docs: None,
            requirements: Vec::new(),
            id: "test_get".to_owned(),
            description: "test fixture".to_owned(),
            category: Some("smoke".to_owned()),
            tags: vec![],
            skip: None,
            env: None,
            setup: Vec::new(),
            call: None,
            input: serde_json::Value::Null,
            mock_response: None,
            visitor: None,
            args: vec![],
            assertion_recipes: vec![],
            assertions: vec![],
            source: "test".to_owned(),
            http: Some(HttpFixture {
                handler: HttpHandler {
                    route: "/test".to_owned(),
                    method: "GET".to_owned(),
                    body_schema: None,
                    parameters: BTreeMap::new(),
                    middleware: None,
                },
                request: HttpRequest {
                    method: "GET".to_owned(),
                    path: "/test".to_owned(),
                    headers: BTreeMap::new(),
                    query_params: BTreeMap::new(),
                    cookies: BTreeMap::new(),
                    body: None,
                    form_data: None,
                    content_type: None,
                },
                expected_response: HttpExpectedResponse {
                    status_code: 200,
                    body: Some(serde_json::json!({"ok": true})),
                    body_partial: None,
                    headers: BTreeMap::new(),
                    validation_errors: None,
                },
            }),
            asyncapi: None,
            websocket: None,
            preserve_input_urls: false,
        };

        let groups = vec![FixtureGroup {
            category: "smoke".to_owned(),
            fixtures: vec![fixture],
        }];
        let e2e_config = E2eConfig {
            harness: HarnessConfig {
                imports: vec!["my_gem".to_owned()],
                ..HarnessConfig::default()
            },
            ..E2eConfig::default()
        };

        let out = render_app_harness(&e2e_config, &groups);

        // The EADDRINUSE retry block must be present in the generated harness
        assert!(
            out.contains("Errno::EADDRINUSE"),
            "expected `Errno::EADDRINUSE` retry block in generated app_harness.rb:\n{out}"
        );
        // The random port selection must be present
        assert!(
            out.contains("rand(40000..60000)") || out.contains("rand("),
            "expected random port selection in generated app_harness.rb:\n{out}"
        );
        // HARNESS_PORT must be printed so spec_helper can read it
        assert!(
            out.contains("HARNESS_PORT="),
            "expected `HARNESS_PORT=` output in generated app_harness.rb:\n{out}"
        );
    }
}

#[cfg(test)]
mod env_setup_tests {
    use super::super::project::render_env_setup;
    use std::collections::HashMap;

    #[test]
    fn empty_env_produces_no_setup_block() {
        let env = HashMap::new();
        let output = render_env_setup(&env);
        assert_eq!(output, "", "empty env must produce empty string");
    }

    #[test]
    fn non_empty_env_produces_sorted_lines() {
        let mut env = HashMap::new();
        env.insert("E2E_ALLOW_PRIVATE_NETWORK".to_string(), "true".to_string());
        env.insert("FOO".to_string(), "bar".to_string());
        env.insert("BAZ".to_string(), "qux".to_string());

        let output = render_env_setup(&env);

        // Lines must be sorted by key
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 3, "expected 3 lines, got: {output}");
        assert!(
            lines[0].contains("BAZ"),
            "first line should be BAZ (alphabetically first), got: {}",
            lines[0]
        );
        assert!(
            lines[1].contains("E2E_ALLOW_PRIVATE_NETWORK"),
            "second line should be E2E_ALLOW_PRIVATE_NETWORK, got: {}",
            lines[1]
        );
        assert!(lines[2].contains("FOO"), "third line should be FOO, got: {}", lines[2]);

        // Each line must use ||= form with proper quoting
        for line in lines {
            assert!(line.contains("||="), "line must use ||= operator: {line}");
        }
    }
}

#[cfg(test)]
mod error_path_marker_tests {
    use crate::core::config::ResolvedCrateConfig;
    use crate::e2e::config::E2eConfig;
    use crate::e2e::fixture::{Assertion, Fixture};
    use std::collections::HashMap;

    fn render(extra: Vec<Assertion>) -> String {
        let mut assertions = vec![Assertion {
            assertion_type: "error".to_string(),
            ..Default::default()
        }];
        assertions.extend(extra);
        let fixture = Fixture {
            id: "rate_limited".to_string(),
            description: "Rejects the request".to_string(),
            assertions,
            ..Fixture::default()
        };
        let mut e2e_config = E2eConfig::default();
        e2e_config.call.function = "parse".to_string();
        e2e_config.call.result_var = "result".to_string();
        let enum_fields: HashMap<String, String> = HashMap::new();
        let _ = crate::e2e::codegen::take_skip_records();
        super::super::spec_file::render_spec_file(
            "error",
            &[&fixture],
            "Sample",
            None,
            "sample",
            None,
            &enum_fields,
            false,
            &e2e_config,
            false,
            false,
            &[],
            &ResolvedCrateConfig::default(),
            &[],
            &[],
            &[],
            &[],
        )
    }

    /// Ruby's error path renders one `raise_error` matcher and returns, so every other assertion
    /// on the fixture used to leave no trace in the generated spec at all.
    #[test]
    fn ruby_equals_on_an_error_field_is_named_instead_of_dropped() {
        let out = render(vec![Assertion {
            assertion_type: "equals".to_string(),
            field: Some("error.status_code".to_string()),
            ..Default::default()
        }]);

        // Positive first: the error block really rendered.
        assert!(
            out.contains("raise_error(RuntimeError)"),
            "the error block must render:\n{out}"
        );
        assert!(
            out.contains(
                "# skipped: assertion type 'equals' has no accessor for error field error.status_code in this backend"
            ),
            "got:\n{out}"
        );

        let records = crate::e2e::codegen::take_skip_records();
        assert_eq!(records.len(), 1, "got: {records:?}");
        assert_eq!(records[0].language, "ruby");
        assert_eq!(records[0].field, "equals");
    }

    /// Negative control: a lone `error` assertion must leave the generated spec marker-free.
    #[test]
    fn ruby_a_lone_error_assertion_renders_no_marker() {
        let out = render(Vec::new());

        assert!(
            out.contains("raise_error(RuntimeError)"),
            "the error block must render:\n{out}"
        );
        assert!(!out.contains("has no accessor for error field"), "got:\n{out}");
    }
}