alef 0.115.6

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
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
//! Shared resolution of `client_factory` construction arguments.
//!
//! Bindings whose API hangs off a client object are generated through a factory call
//! of the shape `factory(<credential>, <base URL>, <trailing args…>)`. The first two
//! slots are the generator's business — it owns the credential expression and knows
//! whether a mock server is in play — but everything after them is project-specific,
//! so it comes from configuration (`client_factory_trailing_args`) or, for a single
//! documentation snippet, from that fixture's `docs.client`.
//!
//! Every entry point here takes the fixture's documentation client as an explicit
//! `Option`, never reading it off the fixture itself. A renderer shared between the
//! docs path and the executable e2e suite therefore has to name the docs override at
//! its call site, and the e2e call site names `None` — the docs endpoint cannot reach
//! a real test by omission.

use crate::e2e::config::{CallConfig, CallOverride, E2eConfig};
use crate::e2e::fixture::{Fixture, FixtureDocsClient};

/// Verbatim argument expressions to emit after the credential and base-URL slots of a
/// `client_factory` call, resolved most-specific source first:
///
/// 1. `docs_client`'s own `args.<language>` — documentation snippets only,
/// 2. `[e2e.calls.<name>.overrides.<language>] client_factory_trailing_args`,
/// 3. `[e2e.call.overrides.<language>] client_factory_trailing_args`,
/// 4. `fallback`.
///
/// `fallback` is the list the caller hardcoded before this hook was wired up. Passing
/// it keeps every project that has not configured the override rendering byte-for-byte
/// what it renders today, so adopting the hook is not a breaking change.
pub fn trailing_args(
    docs_client: Option<&FixtureDocsClient>,
    e2e_config: &E2eConfig,
    call_config: &CallConfig,
    language: &str,
    fallback: &[&str],
) -> Vec<String> {
    if let Some(args) = docs_client.and_then(|client| client.args_for(language)) {
        return args.to_vec();
    }
    call_config
        .overrides
        .get(language)
        .map(|overrides| overrides.client_factory_trailing_args.clone())
        .filter(|args| !args.is_empty())
        .or_else(|| {
            e2e_config
                .call
                .overrides
                .get(language)
                .map(|overrides| overrides.client_factory_trailing_args.clone())
                .filter(|args| !args.is_empty())
        })
        .unwrap_or_else(|| fallback.iter().map(|arg| (*arg).to_string()).collect())
}

/// The base URL a documentation snippet constructs its client with, or `None` when the
/// fixture documents no particular endpoint and the generator should fall back to its
/// usual choice (the mock server, or nothing).
pub fn docs_base_url(docs_client: Option<&FixtureDocsClient>) -> Option<&str> {
    docs_client.and_then(|client| client.base_url.as_deref())
}

/// An override value for `language` resolved the way the executable e2e suites resolve their
/// client factory: the resolved call's own override first, then the default `[e2e.call]`
/// override. A named call that repeats none of the file-level overrides therefore still gets
/// the project's client.
fn call_or_default_override<'a>(
    e2e_config: &'a E2eConfig,
    call_config: &'a CallConfig,
    language: &str,
    pick: impl Fn(&'a CallOverride) -> Option<&'a str>,
) -> Option<&'a str> {
    call_config
        .overrides
        .get(language)
        .and_then(&pick)
        .or_else(|| e2e_config.call.overrides.get(language).and_then(&pick))
}

/// The positional client factory `language` constructs a client with for this call
/// (`client_factory`), resolved by [`call_or_default_override`].
pub fn plain_factory<'a>(e2e_config: &'a E2eConfig, call_config: &'a CallConfig, language: &str) -> Option<&'a str> {
    call_or_default_override(e2e_config, call_config, language, |overrides| {
        overrides.client_factory.as_deref()
    })
}

/// The client factory `language` constructs a client with for this call, or `None` when the call
/// is a free-function call that needs no client.
///
/// A call opts out with an empty `client_factory` in its own `[e2e.calls.<name>.overrides.<language>]`
/// table: [`plain_factory`] returns that empty value instead of falling back to the default call's
/// factory, and an empty factory names no client. Without it every call inherits the default call's
/// client, so a library's free function was generated as a method of a client that does not have
/// it (GH#592).
pub fn call_client_factory<'a>(
    e2e_config: &'a E2eConfig,
    call_config: &'a CallConfig,
    language: &str,
) -> Option<&'a str> {
    plain_factory(e2e_config, call_config, language).filter(|factory| !factory.is_empty())
}

/// True when this call is a free-function call: its own `client_factory` override is empty, which
/// stops [`plain_factory`] from falling back to the default call's client. For backends that
/// receive the file-level factory as a parameter and only need to drop it for this call.
pub fn is_free_function_call(e2e_config: &E2eConfig, call_config: &CallConfig, language: &str) -> bool {
    plain_factory(e2e_config, call_config, language).is_some_and(str::is_empty)
}

/// The PHP client factory (`php_client_factory`) for this call, resolved by
/// [`call_or_default_override`]. PHP projects name their factory under this key, and the PHP
/// e2e suite reads only it, so the snippet must too.
pub fn php_factory<'a>(e2e_config: &'a E2eConfig, call_config: &'a CallConfig) -> Option<&'a str> {
    call_or_default_override(e2e_config, call_config, "php", |overrides| {
        overrides.php_client_factory.as_deref()
    })
}

/// The JSON-string client factory `language` constructs a configured client with, resolved by
/// [`call_or_default_override`].
pub fn from_json_factory<'a>(
    e2e_config: &'a E2eConfig,
    call_config: &'a CallConfig,
    language: &str,
) -> Option<&'a str> {
    call_or_default_override(e2e_config, call_config, language, |overrides| {
        overrides.client_factory_from_json.as_deref()
    })
}

/// A fixture's `docs.client.config` as the compact JSON text a snippet embeds as a string
/// literal. Object keys come out sorted, so the literal is stable across regenerations.
pub fn client_config_json(fixture: &Fixture) -> Option<String> {
    fixture.docs_client()?.config.as_ref().map(serde_json::Value::to_string)
}

/// The factory call a snippet constructs its client with for `language`, when the fixture
/// declares a `docs.client.config` and the language configures a JSON factory: the factory name
/// and the JSON text to pass it as a string literal. `None` means the plain
/// `client_factory` call applies.
///
/// A fixture with `docs.client.config` whose language has no JSON factory never reaches a
/// renderer; the snippet driver excludes it first (see [`client_config_exclusion`]).
pub fn client_config_call<'a>(
    fixture: &Fixture,
    e2e_config: &'a E2eConfig,
    call_config: &'a CallConfig,
    language: &str,
) -> Option<(&'a str, String)> {
    let json = client_config_json(fixture)?;
    Some((from_json_factory(e2e_config, call_config, language)?, json))
}

/// The name a JavaScript/TypeScript snippet imports and the statement that constructs its
/// client: the JSON factory when the fixture declares `docs.client.config`, otherwise the plain
/// `factory` with the documentation credential.
pub fn js_client_construction(
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    call_config: &CallConfig,
    language: &str,
    factory: &str,
) -> (String, String) {
    match client_config_call(fixture, e2e_config, call_config, language) {
        Some((from_json_factory, json)) => (
            from_json_factory.to_string(),
            format!(
                "const client = {from_json_factory}(\"{}\");",
                crate::e2e::escape::escape_js(&json)
            ),
        ),
        None => (
            factory.to_string(),
            format!("const client = {factory}(\"your-api-key\");"),
        ),
    }
}

/// The languages whose executable generator applies a fixture's `client_options`.
///
/// ~keep Every other language excludes such a fixture ([`client_options_exclusion`]); listing a
/// language here means its test function reads `Fixture::client_options` and passes them to the
/// client it builds. `rust` builds the client through the call's `client_factory_from_json`
/// with the options in the JSON; `python` passes each option as a keyword argument of the
/// `client_factory`.
const CLIENT_OPTIONS_LANGUAGES: [&str; 2] = ["rust", "python"];

/// Python's reserved words. A keyword argument cannot carry one of these names.
const PYTHON_KEYWORDS: [&str; 35] = [
    "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del",
    "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal",
    "not", "or", "pass", "raise", "return", "try", "while", "with", "yield",
];

/// Why the executable suite for `language` cannot run `fixture`, when the fixture declares
/// `client_options` the language has no way to apply.
///
/// Running the fixture with a default client would test the default options and report it as
/// a pass for the options the fixture names, so the fixture is excluded, and the returned reason says why.
pub fn client_options_exclusion(fixture: &Fixture, e2e_config: &E2eConfig, language: &str) -> Option<&'static str> {
    let options = fixture.client_options.as_ref()?;
    let is_identifier = |name: &str| {
        name.chars()
            .next()
            .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
    };
    if !options.keys().all(|name| is_identifier(name)) {
        return Some("client option names must be plain identifiers");
    }
    // ~keep Python passes each option as a keyword argument, so a name that is a Python keyword
    // (`class`) would make the generated module a syntax error. Rust writes the names as JSON
    // keys, where no keyword is reserved, and every other language is excluded below.
    if language == "python" && options.keys().any(|name| PYTHON_KEYWORDS.contains(&name.as_str())) {
        return Some("client option names must not be Python keywords");
    }
    if !CLIENT_OPTIONS_LANGUAGES.contains(&language) {
        return Some("client options are not applied by this language's e2e generator");
    }
    let call_config = e2e_config.resolve_call_for_fixture(
        fixture.call.as_deref(),
        &fixture.id,
        &fixture.resolved_category(),
        &fixture.tags,
        &fixture.input,
    );
    if call_client_factory(e2e_config, call_config, language).is_none() {
        return Some("client options need a client_factory for this call");
    }
    if language == "rust" && from_json_factory(e2e_config, call_config, language).is_none() {
        return Some("client options need client_factory_from_json for rust");
    }
    None
}

/// Why a documentation snippet for `fixture` cannot be rendered for `language`, when the
/// fixture declares a `docs.client.config` the language has no way to apply.
///
/// Emitting the plain `client_factory` snippet instead would document a client with none
/// of the configuration the fixture exists to show.
pub fn client_config_exclusion(
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    language: &str,
    renders_client_config: bool,
) -> Option<String> {
    client_config_json(fixture)?;
    let call_config = e2e_config.resolve_call_for_fixture(
        fixture.call.as_deref(),
        &fixture.id,
        &fixture.resolved_category(),
        &fixture.tags,
        &fixture.input,
    );
    if !renders_client_config {
        return Some(format!(
            "fixture declares `docs.client.config`, which the `{language}` snippet generator cannot render"
        ));
    }
    if from_json_factory(e2e_config, call_config, language).is_none() {
        return Some(format!(
            "fixture declares `docs.client.config` but `[crates.e2e.call.overrides.{language}] client_factory_from_json` is not configured"
        ));
    }
    None
}

/// Fails when a fixture declares `docs.client.config` but the rendered snippet never calls the
/// language's JSON factory.
///
/// A backend resolves its client factory from several places (the call's own override, the
/// file-level one, a language-specific key), and not all of them agree with
/// [`client_config_exclusion`]. Checking the rendered text instead of re-deriving that
/// resolution is what keeps a backend that quietly falls back to the plain client from
/// publishing a snippet that documents none of the configuration. ~keep
pub fn ensure_client_config_applied(
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    language: &str,
    body: &str,
) -> anyhow::Result<()> {
    if client_config_json(fixture).is_none() {
        return Ok(());
    }
    let call_config = e2e_config.resolve_call_for_fixture(
        fixture.call.as_deref(),
        &fixture.id,
        &fixture.resolved_category(),
        &fixture.tags,
        &fixture.input,
    );
    let Some(factory) = from_json_factory(e2e_config, call_config, language) else {
        return Ok(());
    };
    // Generators spell the same configured name in their language's casing
    // (`CreateClientFromJSON`, `createClientFromJson`, `create_client_from_json`). ~keep
    let normalize = |text: &str| text.to_lowercase().replace('_', "");
    if normalize(body).contains(&normalize(factory)) {
        return Ok(());
    }
    anyhow::bail!(
        "fixture declares `docs.client.config`, but the rendered `{language}` snippet never calls `{factory}`: \
         its call resolves no `client_factory` to configure"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::e2e::config::CallOverride;

    const FALLBACK: [&str; 3] = ["None", "None", "None"];

    fn config_with_trailing_args(args: &[&str]) -> E2eConfig {
        let mut call = CallConfig::default();
        call.overrides.insert(
            "rust".into(),
            CallOverride {
                client_factory_trailing_args: args.iter().map(|arg| (*arg).to_string()).collect(),
                ..CallOverride::default()
            },
        );
        E2eConfig {
            call,
            ..E2eConfig::default()
        }
    }

    fn docs_client() -> FixtureDocsClient {
        FixtureDocsClient {
            base_url: Some("https://llm.internal.example.com/v1".into()),
            args: [("rust".to_string(), vec!["Some(60)".to_string(), "None".to_string()])]
                .into_iter()
                .collect(),
            ..FixtureDocsClient::default()
        }
    }

    #[test]
    fn unconfigured_projects_keep_the_argument_list_the_generator_hardcoded() {
        let e2e_config = E2eConfig::default();
        assert_eq!(
            trailing_args(None, &e2e_config, &e2e_config.call, "rust", &FALLBACK),
            vec!["None", "None", "None"],
            "an absent override must not shorten the factory's argument list"
        );
    }

    #[test]
    fn file_level_override_replaces_the_fallback() {
        let e2e_config = config_with_trailing_args(&["Some(30)", "Some(5)"]);
        assert_eq!(
            trailing_args(None, &e2e_config, &e2e_config.call, "rust", &FALLBACK),
            vec!["Some(30)", "Some(5)"]
        );
    }

    #[test]
    fn override_is_scoped_to_its_own_language() {
        let e2e_config = config_with_trailing_args(&["Some(30)"]);
        assert_eq!(
            trailing_args(None, &e2e_config, &e2e_config.call, "java", &["null"]),
            vec!["null"],
            "a rust override must not leak into the java factory call"
        );
    }

    #[test]
    fn named_call_override_wins_over_the_file_level_one() {
        let e2e_config = config_with_trailing_args(&["file"]);
        let mut named = CallConfig::default();
        named.overrides.insert(
            "rust".into(),
            CallOverride {
                client_factory_trailing_args: vec!["call".into()],
                ..CallOverride::default()
            },
        );
        assert_eq!(
            trailing_args(None, &e2e_config, &named, "rust", &FALLBACK),
            vec!["call"]
        );
    }

    #[test]
    fn named_call_without_its_own_list_inherits_the_file_level_one() {
        let e2e_config = config_with_trailing_args(&["file"]);
        assert_eq!(
            trailing_args(None, &e2e_config, &CallConfig::default(), "rust", &FALLBACK),
            vec!["file"],
            "a named call that omits the key must not fall through to the fallback"
        );
    }

    #[test]
    fn fixture_docs_client_outranks_every_configured_list() {
        let client = docs_client();
        let e2e_config = config_with_trailing_args(&["file"]);
        assert_eq!(
            trailing_args(Some(&client), &e2e_config, &e2e_config.call, "rust", &FALLBACK),
            vec!["Some(60)", "None"]
        );
        assert_eq!(
            trailing_args(Some(&client), &e2e_config, &e2e_config.call, "java", &["null"]),
            vec!["null"],
            "a language the fixture says nothing about keeps the configured default"
        );
    }

    #[test]
    fn a_caller_that_declares_no_docs_client_reads_no_base_url() {
        assert_eq!(docs_base_url(None), None);
        assert_eq!(
            docs_base_url(Some(&docs_client())),
            Some("https://llm.internal.example.com/v1")
        );
        assert_eq!(
            docs_base_url(Some(&FixtureDocsClient::default())),
            None,
            "a docs client that only overrides trailing args must not invent an endpoint"
        );
    }

    fn config_fixture() -> Fixture {
        serde_json::from_value(serde_json::json!({
            "id": "enforced",
            "description": "a configured client",
            "docs": {
                "topic": "budget",
                "client": {"config": {"budget": {"global_limit": 0.0, "enforcement": "hard"}, "api_key": "k"}},
            },
        }))
        .expect("fixture parses")
    }

    fn config_with_factories(from_json: Option<&str>, plain: Option<&str>) -> E2eConfig {
        let mut call = CallConfig::default();
        call.overrides.insert(
            "go".into(),
            CallOverride {
                client_factory: plain.map(str::to_string),
                client_factory_from_json: from_json.map(str::to_string),
                ..CallOverride::default()
            },
        );
        E2eConfig {
            call,
            ..E2eConfig::default()
        }
    }

    #[test]
    fn plain_factories_resolve_the_call_override_then_the_file_level_one() {
        let e2e_config = config_with_factories(None, Some("Plain"));
        assert_eq!(
            plain_factory(&e2e_config, &CallConfig::default(), "go"),
            Some("Plain"),
            "a named call without its own override inherits the file-level factory"
        );
        let mut named = CallConfig::default();
        named.overrides.insert(
            "go".into(),
            CallOverride {
                client_factory: Some("CallPlain".into()),
                ..CallOverride::default()
            },
        );
        assert_eq!(plain_factory(&e2e_config, &named, "go"), Some("CallPlain"));
        assert_eq!(plain_factory(&e2e_config, &named, "java"), None);
    }

    #[test]
    fn the_php_factory_is_read_from_php_client_factory_only() {
        let mut e2e_config = E2eConfig::default();
        e2e_config.call.overrides.insert(
            "php".into(),
            CallOverride {
                client_factory: Some("NotRead".into()),
                ..CallOverride::default()
            },
        );
        assert_eq!(php_factory(&e2e_config, &CallConfig::default()), None);
        e2e_config
            .call
            .overrides
            .get_mut("php")
            .expect("php override")
            .php_client_factory = Some("createClient".into());
        assert_eq!(php_factory(&e2e_config, &CallConfig::default()), Some("createClient"));
    }

    #[test]
    fn client_config_serializes_compactly_with_sorted_keys() {
        assert_eq!(
            client_config_json(&config_fixture()).as_deref(),
            Some(r#"{"api_key":"k","budget":{"enforcement":"hard","global_limit":0.0}}"#)
        );
        assert_eq!(client_config_json(&Fixture::default()), None);
    }

    #[test]
    fn from_json_factory_prefers_the_call_override_then_the_file_level_one() {
        let e2e_config = config_with_factories(Some("FromJson"), Some("Plain"));
        assert_eq!(
            from_json_factory(&e2e_config, &CallConfig::default(), "go"),
            Some("FromJson"),
            "a named call without its own override inherits the file-level factory"
        );
        let mut named = CallConfig::default();
        named.overrides.insert(
            "go".into(),
            CallOverride {
                client_factory_from_json: Some("CallFromJson".into()),
                ..CallOverride::default()
            },
        );
        assert_eq!(from_json_factory(&e2e_config, &named, "go"), Some("CallFromJson"));
        assert_eq!(
            from_json_factory(&e2e_config, &named, "java"),
            None,
            "a factory configured for one language must not leak into another"
        );
    }

    #[test]
    fn a_fixture_without_client_config_never_selects_the_json_factory() {
        let e2e_config = config_with_factories(Some("FromJson"), Some("Plain"));
        assert!(client_config_call(&Fixture::default(), &e2e_config, &e2e_config.call, "go").is_none());
        let (factory, json) =
            client_config_call(&config_fixture(), &e2e_config, &e2e_config.call, "go").expect("config call");
        assert_eq!(factory, "FromJson");
        assert!(json.starts_with('{') && json.contains("\"enforcement\":\"hard\""));
    }

    #[test]
    fn a_language_that_cannot_apply_client_config_is_excluded_with_a_reason() {
        let fixture = config_fixture();
        let configured = config_with_factories(Some("FromJson"), Some("Plain"));
        assert_eq!(client_config_exclusion(&fixture, &configured, "go", true), None);
        assert_eq!(
            client_config_exclusion(&Fixture::default(), &E2eConfig::default(), "go", false),
            None,
            "a fixture without client_config is never excluded, whatever the language supports"
        );
        let unsupported = client_config_exclusion(&fixture, &configured, "go", false).expect("excluded");
        assert!(unsupported.contains("cannot render"), "{unsupported}");
        let unconfigured = config_with_factories(None, Some("Plain"));
        let reason = client_config_exclusion(&fixture, &unconfigured, "go", true).expect("excluded");
        assert!(reason.contains("client_factory_from_json"), "{reason}");
    }

    #[test]
    fn a_snippet_that_never_calls_the_json_factory_is_rejected() {
        let fixture = config_fixture();
        let e2e_config = config_with_factories(Some("CreateClientFromJSON"), Some("CreateClient"));
        assert!(
            ensure_client_config_applied(
                &fixture,
                &e2e_config,
                "go",
                "client, err := pkg.CreateClient(\"your-api-key\", nil, nil, nil, nil)"
            )
            .is_err(),
            "the plain factory must not satisfy a client_config fixture"
        );
        assert!(ensure_client_config_applied(&fixture, &e2e_config, "go", "pkg.CreateClientFromJSON(`{}`)").is_ok());
        assert!(
            ensure_client_config_applied(&fixture, &e2e_config, "go", "pkg.create_client_from_json(x)").is_ok(),
            "a generator may respell the configured name in its own casing"
        );
        assert!(
            ensure_client_config_applied(&Fixture::default(), &e2e_config, "go", "pkg.CreateClient()").is_ok(),
            "a fixture without client_config has nothing to apply"
        );
    }

    fn options_fixture() -> Fixture {
        serde_json::from_value(serde_json::json!({
            "id": "timeout_options",
            "description": "a client with a short timeout",
            "client_options": {"timeout_secs": 1, "max_retries": 0},
        }))
        .expect("fixture parses")
    }

    fn config_with_factory_for(language: &str, plain: Option<&str>, from_json: Option<&str>) -> E2eConfig {
        let mut call = CallConfig::default();
        call.overrides.insert(
            language.into(),
            CallOverride {
                client_factory: plain.map(str::to_string),
                client_factory_from_json: from_json.map(str::to_string),
                ..CallOverride::default()
            },
        );
        E2eConfig {
            call,
            ..E2eConfig::default()
        }
    }

    #[test]
    fn a_fixture_without_client_options_is_never_excluded_for_them() {
        let config = config_with_factory_for("go", Some("CreateClient"), None);
        assert_eq!(client_options_exclusion(&Fixture::default(), &config, "go"), None);
    }

    #[test]
    fn a_language_that_cannot_apply_client_options_excludes_the_fixture_with_a_reason() {
        let config = config_with_factory_for("go", Some("CreateClient"), Some("CreateClientFromJSON"));
        let reason = client_options_exclusion(&options_fixture(), &config, "go").expect("go is excluded");
        assert!(reason.contains("client options"), "{reason}");
    }

    #[test]
    fn python_applies_client_options_when_the_call_has_a_client_factory() {
        let config = config_with_factory_for("python", Some("create_client"), None);
        assert_eq!(client_options_exclusion(&options_fixture(), &config, "python"), None);
        let bare = config_with_factory_for("python", None, None);
        assert!(client_options_exclusion(&options_fixture(), &bare, "python").is_some());
    }

    #[test]
    fn rust_applies_client_options_only_through_the_json_factory() {
        let with_json = config_with_factory_for("rust", Some("create_client"), Some("create_client_from_json"));
        assert_eq!(client_options_exclusion(&options_fixture(), &with_json, "rust"), None);
        let without_json = config_with_factory_for("rust", Some("create_client"), None);
        let reason = client_options_exclusion(&options_fixture(), &without_json, "rust").expect("excluded");
        assert!(reason.contains("client_factory_from_json"), "{reason}");
    }

    #[test]
    fn python_refuses_a_client_option_named_like_a_python_keyword() {
        let config = config_with_factory_for("python", Some("create_client"), None);
        for keyword in PYTHON_KEYWORDS {
            let mut fixture = options_fixture();
            fixture
                .client_options
                .as_mut()
                .expect("options")
                .insert(keyword.to_string(), serde_json::json!(1));
            let reason = client_options_exclusion(&fixture, &config, "python")
                .unwrap_or_else(|| panic!("`{keyword}` must be refused"));
            assert!(reason.contains("Python keywords"), "{reason}");
        }
    }

    #[test]
    fn rust_accepts_a_client_option_named_like_a_python_keyword() {
        let config = config_with_factory_for("rust", Some("create_client"), Some("create_client_from_json"));
        let mut fixture = options_fixture();
        fixture
            .client_options
            .as_mut()
            .expect("options")
            .insert("class".to_string(), serde_json::json!(1));
        assert_eq!(
            client_options_exclusion(&fixture, &config, "rust"),
            None,
            "the Rust suite writes option names as JSON keys"
        );
    }

    #[test]
    fn client_option_names_must_be_plain_identifiers() {
        let mut fixture = options_fixture();
        fixture
            .client_options
            .as_mut()
            .expect("options")
            .insert("timeout secs".to_string(), serde_json::json!(1));
        let config = config_with_factory_for("python", Some("create_client"), None);
        assert!(client_options_exclusion(&fixture, &config, "python").is_some());
    }
}