rtb-app 0.9.0

Application context, tool metadata, runtime features, and the Command plugin trait. Part of the phpboyscout Rust toolkit.
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
//! Unit-level acceptance tests for `rtb-app`.
//!
//! Each test maps to a T# criterion in
//! `docs/development/specs/2026-04-22-rtb-app-v0.1.md`.

#![allow(missing_docs)]

use std::sync::Arc;

use rtb_app::app::App;
use rtb_app::command::{Command, CommandSpec, BUILTIN_COMMANDS};
use rtb_app::features::{Feature, Features, FeaturesBuilder};
use rtb_app::metadata::{HelpChannel, ReleaseSource, ToolMetadata};
use rtb_app::version::VersionInfo;
use semver::Version;

// ---------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------

fn sample_metadata() -> ToolMetadata {
    ToolMetadata::builder().name("mytool").summary("a test tool").build()
}

const fn sample_version() -> VersionInfo {
    VersionInfo::new(Version::new(1, 2, 3))
}

fn sample_app() -> App {
    App::for_testing(sample_metadata(), sample_version())
}

// ---------------------------------------------------------------------
// T1 — App is Send + Sync + Clone
// ---------------------------------------------------------------------

#[test]
fn t1_app_is_send_sync_clone() {
    fn assert_bounds<T: Send + Sync + Clone + 'static>() {}
    assert_bounds::<App>();
}

// ---------------------------------------------------------------------
// T2 — App::clone shares Arcs (pointer equality)
// ---------------------------------------------------------------------

#[test]
fn t2_clone_shares_arcs() {
    let orig = sample_app();
    let clone = orig.clone();

    assert!(Arc::ptr_eq(&orig.metadata, &clone.metadata), "metadata Arc not shared");
    assert!(Arc::ptr_eq(&orig.version, &clone.version), "version Arc not shared");
    assert!(Arc::ptr_eq(&orig.assets, &clone.assets), "assets Arc not shared");
    // The config field is `pub(crate)` after the v0.4.1 type-erased
    // refactor. Confirm Arc-sharing through the public downcast
    // accessor instead — `typed_config` uses `Arc::downcast` which
    // preserves the underlying allocation.
    let orig_cfg = orig.typed_config::<()>().expect("Config<()> downcast");
    let clone_cfg = clone.typed_config::<()>().expect("Config<()> downcast");
    assert!(Arc::ptr_eq(&orig_cfg, &clone_cfg), "config Arc not shared via typed_config");
}

// ---------------------------------------------------------------------
// T3 — App.shutdown child cancellation cascades
// ---------------------------------------------------------------------

#[test]
fn t3_shutdown_cascades_to_children() {
    let app = sample_app();
    let child = app.shutdown.child_token();
    assert!(!child.is_cancelled());
    app.shutdown.cancel();
    assert!(child.is_cancelled(), "child token did not cancel with parent");
}

// ---------------------------------------------------------------------
// T4 — ToolMetadata::builder requires name and summary (trybuild fixture)
// ---------------------------------------------------------------------

#[test]
fn t4_builder_required_fields_fixture_exists() {
    let p = std::path::Path::new("tests/trybuild/metadata_requires_name.rs");
    assert!(
        p.exists() || std::env::var_os("RTB_SKIP_TRYBUILD").is_some(),
        "missing trybuild fixture for T4",
    );
}

// ---------------------------------------------------------------------
// T5 — ToolMetadata serde round-trip
// ---------------------------------------------------------------------

#[test]
fn t5_metadata_serde_roundtrip() {
    let original = ToolMetadata::builder()
        .name("mytool")
        .summary("does stuff")
        .description("a longer explanation")
        .release_source(ReleaseSource::Github {
            owner: "me".into(),
            repo: "it".into(),
            host: "github.com".into(),
        })
        .help(HelpChannel::Url { url: "https://example.com/help".into() })
        .build();

    let yaml = serde_yaml::to_string(&original).expect("serialise");
    let restored: ToolMetadata = serde_yaml::from_str(&yaml).expect("deserialise");

    assert_eq!(restored.name, original.name);
    assert_eq!(restored.summary, original.summary);
    assert_eq!(restored.description, original.description);
    assert!(matches!(restored.release_source, Some(ReleaseSource::Github { .. })));
    assert!(matches!(restored.help, HelpChannel::Url { .. }));
}

// ---------------------------------------------------------------------
// T6 — ReleaseSource::Github default host
// ---------------------------------------------------------------------

#[test]
fn t6_github_default_host() {
    let yaml = "type: github\nowner: me\nrepo: it\n";
    let rs: ReleaseSource = serde_yaml::from_str(yaml).expect("deserialise");
    match rs {
        ReleaseSource::Github { host, .. } => assert_eq!(host, "github.com"),
        other => panic!("expected Github, got {other:?}"),
    }
}

// ---------------------------------------------------------------------
// T7 — ReleaseSource::Gitlab default host
// ---------------------------------------------------------------------

#[test]
fn t7_gitlab_default_host() {
    let yaml = "type: gitlab\nproject: me/it\n";
    let rs: ReleaseSource = serde_yaml::from_str(yaml).expect("deserialise");
    match rs {
        ReleaseSource::Gitlab { host, project } => {
            assert_eq!(host, "gitlab.com");
            assert_eq!(project, "me/it");
        }
        other => panic!("expected Gitlab, got {other:?}"),
    }
}

// ---------------------------------------------------------------------
// T8 — HelpChannel::footer formats
// ---------------------------------------------------------------------

#[test]
fn t8_helpchannel_footer_none() {
    assert_eq!(HelpChannel::None.footer(), None);
}

#[test]
fn t8_helpchannel_footer_slack() {
    let h = HelpChannel::Slack { team: "platform".into(), channel: "cli-tools".into() };
    assert_eq!(h.footer().as_deref(), Some("support: slack #cli-tools (in platform)"));
}

#[test]
fn t8_helpchannel_footer_teams() {
    let h = HelpChannel::Teams { team: "SRE".into(), channel: "oncall".into() };
    assert_eq!(h.footer().as_deref(), Some("support: Teams → SRE / oncall"));
}

#[test]
fn t8_helpchannel_footer_url() {
    let h = HelpChannel::Url { url: "https://support.example.com".into() };
    assert_eq!(h.footer().as_deref(), Some("support: https://support.example.com"));
}

// ---------------------------------------------------------------------
// T9 — VersionInfo::new / with_commit / with_date
// ---------------------------------------------------------------------

#[test]
fn t9_versioninfo_builder_chain() {
    let v = VersionInfo::new(Version::new(1, 0, 0)).with_commit("abc123").with_date("2026-04-22");
    assert_eq!(v.version, Version::new(1, 0, 0));
    assert_eq!(v.commit.as_deref(), Some("abc123"));
    assert_eq!(v.date.as_deref(), Some("2026-04-22"));
}

// ---------------------------------------------------------------------
// T10 — is_development table
// ---------------------------------------------------------------------

#[test]
fn t10_is_development_table() {
    fn dev(s: &str) -> bool {
        VersionInfo::new(Version::parse(s).unwrap()).is_development()
    }
    assert!(dev("0.1.0"), "0.1.0 is pre-1.0");
    assert!(dev("0.0.0"), "from_env fallback");
    assert!(dev("1.0.0-alpha"), "pre-release identifier");
    assert!(dev("1.2.3-dev.5"), "pre-release identifier");
    assert!(!dev("1.0.0"), "stable release");
    assert!(!dev("2.3.4"), "stable release");
}

// ---------------------------------------------------------------------
// T11 — version capture reflects the CALLING crate, not rtb-app
// ---------------------------------------------------------------------

#[test]
fn t11_version_info_macro_reports_the_calling_crate() {
    // The macro must expand `env!("CARGO_PKG_VERSION")` at the *call
    // site*. The superseded `VersionInfo::from_env()` was a plain fn, so
    // its `env!` expanded while rtb-app itself was compiled, and every
    // downstream tool reported rtb-app's version instead of its own.
    // That broke `rtb update`: the updater self-tests the staged binary
    // by checking its reported version against the release tag, and a
    // 0.8.2 build claiming 0.8.0 fails that check, so the swap is
    // refused.
    //
    // Caveat: this test lives in rtb-app's own package, so call site and
    // rtb-app share a version and it cannot by itself tell the two
    // behaviours apart. It pins the contract; the deprecation of
    // `from_env` (tests/trybuild/from_env_is_deprecated.rs) is what
    // actually stops the footgun reaching downstreams.
    let v = rtb_app::version_info!();
    assert_eq!(
        v.version,
        Version::parse(env!("CARGO_PKG_VERSION")).expect("own version parses"),
        "version_info!() must report the calling crate's CARGO_PKG_VERSION"
    );
}

#[test]
fn t11_from_pkg_version_parses_and_falls_back() {
    assert_eq!(
        VersionInfo::from_pkg_version("1.2.3").version,
        Version::new(1, 2, 3),
        "valid semver parses"
    );
    assert_eq!(
        VersionInfo::from_pkg_version("1.0.0-alpha.1").version,
        Version::parse("1.0.0-alpha.1").unwrap(),
        "pre-release identifiers survive"
    );
    // Documented silent fallback — flagged in turn by is_development().
    let bad = VersionInfo::from_pkg_version("not-a-version");
    assert_eq!(bad.version, Version::new(0, 0, 0), "garbage falls back to 0.0.0");
    assert!(bad.is_development(), "the 0.0.0 fallback counts as development");
}

// ---------------------------------------------------------------------
// T12 — Features::default matches the documented defaults
// ---------------------------------------------------------------------

#[test]
fn t12_features_defaults() {
    let f = Features::default();
    // Enabled
    for feature in [
        Feature::Init,
        Feature::Version,
        Feature::Update,
        Feature::Docs,
        Feature::Mcp,
        Feature::Doctor,
        Feature::Credentials, // since 0.4.0
        Feature::Telemetry,   // moved to default-on in 0.4.0 alongside the
        // `telemetry` CLI subtree.
        Feature::Config, // moved to default-on in 0.4.0 alongside the
                         // `config get / set / schema / validate` extension.
    ] {
        assert!(f.is_enabled(feature), "{feature:?} should be enabled by default");
    }
    // Disabled
    for feature in [Feature::Ai, Feature::Changelog] {
        assert!(!f.is_enabled(feature), "{feature:?} should be disabled by default");
    }
}

// ---------------------------------------------------------------------
// T13 — builder.disable keeps the other defaults
// ---------------------------------------------------------------------

#[test]
fn t13_builder_disable_preserves_others() {
    let f = FeaturesBuilder::new().disable(Feature::Update).enable(Feature::Ai).build();
    assert!(!f.is_enabled(Feature::Update));
    assert!(f.is_enabled(Feature::Ai));
    assert!(f.is_enabled(Feature::Init), "Init should still be enabled");
    assert!(f.is_enabled(Feature::Docs), "Docs should still be enabled");
}

// ---------------------------------------------------------------------
// T14 — BUILTIN_COMMANDS registration from this test binary
// ---------------------------------------------------------------------

use rtb_app::linkme::distributed_slice;

struct TestCmd;

#[async_trait::async_trait]
impl Command for TestCmd {
    fn spec(&self) -> &CommandSpec {
        static SPEC: CommandSpec = CommandSpec {
            name: "rtb-app-test-cmd",
            about: "registered from rtb-app's unit test binary",
            ..CommandSpec::DEFAULT
        };
        &SPEC
    }

    async fn run(&self, _app: App) -> miette::Result<()> {
        Ok(())
    }
}

#[distributed_slice(BUILTIN_COMMANDS)]
fn __register_test_cmd() -> Box<dyn Command> {
    Box::new(TestCmd)
}

#[test]
fn t14_distributed_slice_observable() {
    let names: Vec<&'static str> = BUILTIN_COMMANDS.iter().map(|f| f().spec().name).collect();
    assert!(
        names.contains(&"rtb-app-test-cmd"),
        "registered test command not found in BUILTIN_COMMANDS; got: {names:?}",
    );
}

// ---------------------------------------------------------------------
// T15 — CommandSpec is Clone + Debug
// ---------------------------------------------------------------------

#[test]
fn t15_commandspec_clone_debug() {
    fn assert_bounds<T: Clone + std::fmt::Debug>() {}
    assert_bounds::<CommandSpec>();
}

// ---------------------------------------------------------------------
// T16 — Command is object-safe (compile check)
// ---------------------------------------------------------------------

#[test]
fn t16_command_is_object_safe() {
    let _: Box<dyn Command> = Box::new(TestCmd);
}

// ---------------------------------------------------------------------
// T17 — #[non_exhaustive] on Feature (trybuild fixture exists)
// ---------------------------------------------------------------------

#[test]
fn t17_feature_non_exhaustive_fixture_exists() {
    let p = std::path::Path::new("tests/trybuild/feature_non_exhaustive.rs");
    assert!(
        p.exists() || std::env::var_os("RTB_SKIP_TRYBUILD").is_some(),
        "missing trybuild fixture for T17",
    );
}

// ---------------------------------------------------------------------
// T18 — #[non_exhaustive] on ReleaseSource (trybuild fixture exists)
// ---------------------------------------------------------------------

#[test]
fn t18_releasesource_non_exhaustive_fixture_exists() {
    let p = std::path::Path::new("tests/trybuild/releasesource_non_exhaustive.rs");
    assert!(
        p.exists() || std::env::var_os("RTB_SKIP_TRYBUILD").is_some(),
        "missing trybuild fixture for T18",
    );
}

// ---------------------------------------------------------------------
// T19 — ReleaseSource carries all six variants (Github / Gitlab /
//        Bitbucket / Gitea / Codeberg / Direct) round-tripping through
//        serde with the documented `type:` discriminator.
// ---------------------------------------------------------------------

#[test]
fn t19_releasesource_all_six_variants_round_trip() {
    use rtb_app::metadata::ReleaseSource;

    let cases = [
        (
            "{\"type\":\"github\",\"owner\":\"acme\",\"repo\":\"widget\"}",
            "github",
        ),
        (
            "{\"type\":\"gitlab\",\"project\":\"acme/widget\"}",
            "gitlab",
        ),
        (
            "{\"type\":\"bitbucket\",\"workspace\":\"acme\",\"repo_slug\":\"widget\"}",
            "bitbucket",
        ),
        (
            "{\"type\":\"gitea\",\"owner\":\"acme\",\"repo\":\"widget\",\"host\":\"git.acme.io\"}",
            "gitea",
        ),
        (
            "{\"type\":\"codeberg\",\"owner\":\"acme\",\"repo\":\"widget\"}",
            "codeberg",
        ),
        (
            "{\"type\":\"direct\",\"url_template\":\"https://dist.acme.io/{tool}/{version}/{asset}\"}",
            "direct",
        ),
    ];
    for (json, label) in cases {
        // Verify each variant deserialises (would panic on a missing
        // variant) and re-serialises back into the same enum shape on
        // a second pass — defaults are filled in on serialise so we
        // compare via re-parse rather than literal JSON equality.
        let parsed: ReleaseSource = serde_json::from_str(json).expect(label);
        let serialised = serde_json::to_string(&parsed).expect(label);
        let _round_tripped: ReleaseSource = serde_json::from_str(&serialised).expect(label);
    }
}