nest-rs-cli 1.2.0

Scaffolding CLI for NestRS — new projects, feature generators, and project health checks.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

fn write_fake_workspace(root: &Path) {
    fs::create_dir_all(root.join("crates/features/src")).unwrap();
    fs::create_dir_all(root.join("apps")).unwrap();
    fs::write(
        root.join("Cargo.toml"),
        r#"
[workspace]
members = ["crates/*", "apps/*"]

[workspace.package]
version = "0.1.0"
"#,
    )
    .unwrap();
    fs::write(
        root.join("crates/features/src/lib.rs"),
        "pub mod users;\n\npub use users::UsersModule;\n",
    )
    .unwrap();
    fs::write(
        root.join("crates/features/Cargo.toml"),
        "[package]\nname = \"features\"\n\n[dependencies]\nnest-rs-core.workspace = true\n",
    )
    .unwrap();
    fs::write(root.join(".env"), "NESTRS_DATABASE__URL=postgres://x\n").unwrap();
}

/// An app crate inside the fake workspace, carrying the
/// `#[module(imports = [ … ])]` shape the auto-wiring anchors on.
fn write_fake_app(root: &Path, name: &str) -> PathBuf {
    let app = root.join("apps").join(name);
    fs::create_dir_all(app.join("src")).unwrap();
    fs::write(
        app.join("Cargo.toml"),
        format!("[package]\nname = \"{name}\"\n\n[dependencies]\nnest-rs-core.workspace = true\n"),
    )
    .unwrap();
    fs::write(
        app.join("src/module.rs"),
        "use nest_rs_core::module;\nuse nest_rs_http::{HttpConfig, HttpModule};\n\n\
         #[module(\n    imports = [\n        \
         HttpModule::for_root(HttpConfig { port: 3000, ..Default::default() }),\n    ],\n)]\n\
         pub struct AppModule;\n",
    )
    .unwrap();
    app
}

/// Run `nestrs <args...>` with cwd at `dir`, asserting success.
fn run_ok(dir: &Path, args: &[&str]) -> String {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(args)
        .current_dir(dir)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "args {args:?} stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).into_owned()
}

#[test]
fn new_standalone_hello_template() {
    let dir = tempfile::tempdir().unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "demo-api", "--standalone"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let app = dir.path().join("demo-api");
    assert!(app.join("src/main.rs").is_file());
    assert!(app.join("src/lib.rs").is_file());
    assert!(app.join("src/controller.rs").is_file());
    // The scaffolded smoke test needs no live infra ⇒ `integration` suite.
    assert!(app.join("tests/integration/main.rs").is_file());
    // …and an empty `e2e` suite beside it: the test recipes filter on
    // `binary(e2e)`, which nextest refuses to parse when nothing matches.
    assert!(app.join("tests/e2e/main.rs").is_file());
    assert!(app.join("Cargo.toml").is_file());
    assert!(app.join("Dockerfile").is_file());
    assert!(app.join(".dockerignore").is_file());
    assert!(app.join("rust-toolchain.toml").is_file());
    assert!(app.join(".env").is_file());
    assert!(app.join(".env.development").is_file());
    let dev_env = fs::read_to_string(app.join(".env.development")).unwrap();
    assert!(dev_env.contains("NESTRS_LOG=debug"));
    assert_env_example_points_test_overrides_somewhere_loaded(&app);

    let main_rs = fs::read_to_string(app.join("src/main.rs")).unwrap();
    // Baseline logging is nest-rs-core's job now — a scaffold must not pull
    // the observability stack; it stays a documented opt-in.
    assert!(!main_rs.contains("OpenTelemetry"));
    assert!(main_rs.contains("Environment::init"));

    let module_rs = fs::read_to_string(app.join("src/module.rs")).unwrap();
    assert!(!module_rs.contains("OpenTelemetryModule"));

    let cargo = fs::read_to_string(app.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("[workspace]"));
    assert!(cargo.contains("nest-rs-guards"));
    assert!(cargo.contains("nest-rs-interceptors"));
    assert!(!cargo.contains("nest-rs-opentelemetry"));
    assert!(app.join(".gitignore").is_file());
    assert!(app.join("Justfile").is_file());
    let justfile = fs::read_to_string(app.join("Justfile")).unwrap();
    assert!(justfile.contains("build:"));
    assert!(justfile.contains("cargo build --release"));
    assert!(justfile.contains("mod test"));
    // The db verbs drive the workspace's `migrations`/`seed` crates, which a
    // single crate has nowhere to put — so neither the module nor the file.
    assert!(!justfile.contains("mod db"));
    assert!(!app.join("db.just").exists());
    assert!(app.join("test.just").is_file());
    let test_just = fs::read_to_string(app.join("test.just")).unwrap();
    assert!(test_just.contains("unit:"));
    assert!(test_just.contains("e2e:"));
    assert!(test_just.contains("doc:"));
    assert!(test_just.contains("cargo test --doc"));
}

#[test]
fn new_workspace_greenfield() {
    let dir = tempfile::tempdir().unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "acme"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let root = dir.path().join("acme");
    assert!(root.join("Cargo.toml").is_file());
    assert!(
        root.join("crates/features/src/hello/http/controller.rs")
            .is_file()
    );
    // The default app and demo feature are both named `hello`.
    assert!(root.join("apps/hello/src/module.rs").is_file());
    assert!(!root.join("apps/hello/src/controller.rs").exists());
    // The scaffolded smoke test needs no live infra ⇒ `integration` suite,
    // with an empty `e2e` suite beside it so the nextest filtersets resolve.
    assert!(root.join("apps/hello/tests/integration/main.rs").is_file());
    assert!(root.join("apps/hello/tests/e2e/main.rs").is_file());
    let smoke = fs::read_to_string(root.join("apps/hello/tests/integration/main.rs")).unwrap();
    assert!(
        !smoke.contains("with_test_telemetry"),
        "that builder method is behind an optional feature the scaffold does not enable"
    );
    // The db verbs name these two crates in every recipe.
    assert!(root.join("crates/migrations/src/bin/migrate.rs").is_file());
    assert!(root.join("crates/migrations/src/migrator.rs").is_file());
    assert!(root.join("crates/seed/src/main.rs").is_file());
    // No Dockerfile ships in workspace mode, so nothing to ignore for.
    assert!(!root.join(".dockerignore").exists());
    assert!(root.join("Justfile").is_file());
    let justfile = fs::read_to_string(root.join("Justfile")).unwrap();
    assert!(justfile.contains("dev app=\"hello\""));
    // `build --all` is a conditional on the single `build` recipe, not a separate recipe.
    assert!(!justfile.contains("build-all"));
    assert!(justfile.contains(r#"if app == "--all""#));
    assert!(justfile.contains("mod test"));
    assert!(justfile.contains("mod db"));

    let test_just = fs::read_to_string(root.join("test.just")).unwrap();
    assert!(test_just.contains("unit:"));
    assert!(test_just.contains("e2e:"));
    assert!(test_just.contains("cargo test --workspace --doc"));
    let db_just = fs::read_to_string(root.join("db.just")).unwrap();
    assert!(db_just.contains("up:"));
    assert!(db_just.contains("reset: fresh seed"));

    let module = fs::read_to_string(root.join("apps/hello/src/module.rs")).unwrap();
    assert!(module.contains("HelloHttpModule"));
    assert!(module.contains("features::hello"));
    assert!(module.contains("port: 3000"));

    let env = fs::read_to_string(root.join(".env")).unwrap();
    assert!(!env.contains("NESTRS_HTTP__PORT"));
    assert_env_example_points_test_overrides_somewhere_loaded(&root);

    let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("members = [\"crates/*\", \"apps/*\"]"));
}

/// The scaffolded `.env.example` sends a test override to a file the cascade
/// actually loads under `NESTRS_ENV=test` (see `templates::shared::ENV_EXAMPLE`
/// for why the wrong answer fails silently).
fn assert_env_example_points_test_overrides_somewhere_loaded(root: &Path) {
    let example = fs::read_to_string(root.join(".env.example")).unwrap();
    assert!(
        example.contains(".env.test.local"),
        "`.env.example` must name the file a test override actually loads from: {example}"
    );
    assert!(
        example.contains("skips `.env.local`"),
        "…and say why `.env.local` is not it: {example}"
    );
}

#[test]
fn new_app_inside_nestrs_workspace() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "demo-api"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let app = dir.path().join("apps/demo-api");
    assert!(app.join("src/module.rs").is_file());
    assert!(app.join("src/main.rs").is_file());
    // Logic never lands in an app crate — the greeting is a feature.
    assert!(!app.join("src/controller.rs").exists());

    let module = fs::read_to_string(app.join("src/module.rs")).unwrap();
    assert!(module.contains("HttpConfig { port: 3000"));
    assert!(!module.contains("for_root(None)"));

    // The norm: an app added to a workspace gets its own `hello` feature, so it
    // answers on `/` the first time it runs rather than 404ing.
    let feature = dir.path().join("crates/features/src/demo_api");
    assert!(feature.join("service.rs").is_file());
    let controller = fs::read_to_string(feature.join("http/controller.rs")).unwrap();
    assert!(
        controller.contains(r#"#[controller(path = "/")]"#) && controller.contains("#[public]"),
        "the scaffolded app must mount a public GET /: {controller}"
    );
    assert!(
        module.contains("DemoApiHttpModule") && module.contains("features::demo_api"),
        "and the app must import it: {module}"
    );

    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(lib.contains("pub mod demo_api;"), "features lib.rs: {lib}");
    // The pre-existing feature declaration survives the edit.
    assert!(lib.contains("pub mod users;"), "features lib.rs: {lib}");

    // A smoke test ships with the greeting it asserts.
    assert!(app.join("tests/integration/main.rs").is_file());
}

/// `nestrs new posts` where a `posts` feature already exists would clobber
/// product code. Refuse instead — the app name is free to change.
#[test]
fn new_app_refuses_to_reuse_an_existing_feature_name() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    fs::create_dir_all(dir.path().join("crates/features/src/users")).unwrap();

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "users"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(!output.status.success());
    assert!(!dir.path().join("apps/users").exists());
}

#[test]
fn new_app_picks_next_http_port() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    fs::create_dir_all(dir.path().join("apps/auth/src")).unwrap();
    fs::write(
        dir.path().join("apps/auth/src/module.rs"),
        "HttpModule::for_root(HttpConfig { port: 3001, ..Default::default() })",
    )
    .unwrap();

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "blog"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let module = fs::read_to_string(dir.path().join("apps/blog/src/module.rs")).unwrap();
    assert!(module.contains("HttpConfig { port: 3002"));
}

#[test]
fn new_app_inside_workspace_already_exists() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    fs::create_dir_all(dir.path().join("apps/blog")).unwrap();

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "blog"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("already exists"));
    assert!(stderr.contains("blog"));
}

#[test]
fn new_workspace_app_scaffold() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "blog", "-o"])
        .arg(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let app = dir.path().join("apps/blog");
    assert!(app.join("src/module.rs").is_file());
    assert!(app.join("src/lib.rs").is_file());
    assert!(!app.join("src/controller.rs").exists());
    assert!(dir.path().join(".env").is_file());
    assert!(dir.path().join(".env.development").is_file());
    assert!(dir.path().join("Justfile").is_file());
    assert!(dir.path().join(".gitignore").is_file());
    assert!(dir.path().join("compose.yml").is_file());

    // The committed `.env` points at the compose services (T26): the DB URL is
    // active so `nestrs run db up` works out of the box; the port stays code.
    let env = fs::read_to_string(dir.path().join(".env")).unwrap();
    assert!(!env.contains("NESTRS_HTTP__PORT"));
    assert!(env.contains("NESTRS_DATABASE__URL=postgres://"));

    let module = fs::read_to_string(app.join("src/module.rs")).unwrap();
    assert!(module.contains("HttpConfig { port: 3000"));
    assert!(!module.contains("OpenTelemetryModule"));
}

#[test]
fn generate_feature_creates_port_and_wires_lib() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "feature", "posts", "-p", dir.path().to_str().unwrap()],
    );

    let feature = dir.path().join("crates/features/src/posts");
    assert!(feature.join("mod.rs").is_file());
    assert!(feature.join("module.rs").is_file());
    assert!(feature.join("service.rs").is_file());
    // no transport yet
    assert!(!feature.join("http").exists());

    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(lib.contains("pub mod posts;"));
}

#[test]
fn generate_resource_creates_crud_slice_and_deps() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "resource", "posts", "-p", dir.path().to_str().unwrap()],
    );

    let feature = dir.path().join("crates/features/src/posts");
    assert!(feature.join("entity.rs").is_file());
    assert!(feature.join("service.rs").is_file());
    assert!(feature.join("http/controller.rs").is_file());

    let entity = fs::read_to_string(feature.join("entity.rs")).unwrap();
    assert!(entity.contains("#[expose(name = \"Post\""));
    assert!(entity.contains("table_name = \"post\""));

    // Dependencies spliced into both manifests. `schemars` and `nest-rs-authz`
    // are what `#[expose]`/`#[crud]` expand to, so their absence would only
    // surface as macro-expansion errors on the first `cargo check`.
    let root_cargo = fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
    assert!(root_cargo.contains("nest-rs-seaorm"));
    assert!(root_cargo.contains("schemars"));
    assert!(root_cargo.contains("nest-rs-authz"));
    assert!(
        root_cargo.contains("sea-orm = { version = \"2.0\""),
        "the generated pin tracks the released sea-orm, not a release candidate: {root_cargo}"
    );
    let features_cargo = fs::read_to_string(dir.path().join("crates/features/Cargo.toml")).unwrap();
    assert!(features_cargo.contains("nest-rs-seaorm"));
    assert!(features_cargo.contains("schemars"));
    assert!(features_cargo.contains("nest-rs-authz"));

    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(lib.contains("pub mod posts;"));
}

#[test]
fn generate_resource_emits_the_guarded_form_and_bootstraps_auth() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "resource", "posts", "-p", dir.path().to_str().unwrap()],
    );

    let feature = dir.path().join("crates/features/src/posts");
    let controller = fs::read_to_string(feature.join("http/controller.rs")).unwrap();
    assert!(
        controller.contains("#[use_guards(AuthnGuard, AuthzGuard)]"),
        "a DB-backed controller serves nothing without an ability guard: {controller}"
    );
    assert!(
        controller.contains("#[crud(") && controller.contains("entity = PostEntity"),
        "the resource controller uses the #[crud] form: {controller}"
    );

    let module = fs::read_to_string(feature.join("http/module.rs")).unwrap();
    assert!(
        module.contains("AuthzHttpModule"),
        "the http module imports AuthzHttpModule: {module}"
    );

    // The guards it names have to exist — so the adapter came with it.
    let src = dir.path().join("crates/features/src");
    assert!(src.join("authn/strategy.rs").is_file());
    assert!(src.join("authz/ability.rs").is_file());
    assert!(src.join("authz/http/guard.rs").is_file());
    assert!(src.join("identity/claims.rs").is_file());

    let env = fs::read_to_string(dir.path().join(".env")).unwrap();
    assert!(env.contains("NESTRS_AUTHN__SECRET"));
}

#[test]
fn generate_auth_scaffolds_the_adapter_once() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "auth", "-p", dir.path().to_str().unwrap()],
    );

    let src = dir.path().join("crates/features/src");
    let ability = fs::read_to_string(src.join("authz/ability.rs")).unwrap();
    assert!(ability.contains("impl AbilityFactory for AppAbility"));
    // Both branches are scaffolded empty: the authenticated policy and the
    // visitor one a `#[public]` route reads. Leaving `define_visitor` out would
    // hide the only place an anonymous read can be granted.
    assert!(
        ability.contains("fn define(") && ability.contains("fn define_visitor("),
        "the scaffolded policy carries both branches: {ability}"
    );
    let guard = fs::read_to_string(src.join("authz/http/guard.rs")).unwrap();
    assert!(guard.contains("AbilityGuard<AppAbility>"));

    let lib = fs::read_to_string(src.join("lib.rs")).unwrap();
    assert!(lib.contains("pub mod authn;"));
    assert!(lib.contains("pub mod authz;"));
    assert!(lib.contains("pub use identity::{Claims, Role};"));

    // A workspace has exactly one auth adapter; a second run must not clobber
    // the policy the developer has been editing.
    let second = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["g", "auth", "-p", dir.path().to_str().unwrap()])
        .current_dir(dir.path())
        .output()
        .unwrap();
    assert!(!second.status.success());
}

// Both auth roots have to reach the composition site from one run. They are two
// imports into the same `module.rs`, and a scaffold transaction resolves every
// edit against the file *on disk* — so queuing them as two edits would silently
// drop the first, leaving an app that lists only half of what it serves.
#[test]
fn generate_auth_wires_both_roots_into_the_app() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let app = write_fake_app(dir.path(), "api");

    run_ok(&app, &["g", "auth"]);

    let module = fs::read_to_string(app.join("src/module.rs")).unwrap();
    for (use_path, ident) in [
        ("features::authn::AuthnModule", "AuthnModule"),
        ("features::authz::AuthzHttpModule", "AuthzHttpModule"),
    ] {
        assert!(module.contains(&format!("use {use_path};")), "{module}");
        assert!(
            module.contains(&format!("{ident},")),
            "the imports array must list {ident}: {module}"
        );
    }
    // The pre-existing import is untouched.
    assert!(module.contains("HttpModule::for_root"), "{module}");
}

// Same obligation on the bootstrap path: `g resource` scaffolds the adapter when
// the workspace has none, so it owes the same composition site the same entries
// — in the one edit it already spends on `module.rs` for its own module.
#[test]
fn generate_resource_wires_the_auth_roots_it_bootstrapped() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let app = write_fake_app(dir.path(), "api");
    // `g resource` wires only into an app that already has a database.
    let module_rs = app.join("src/module.rs");
    let with_db = fs::read_to_string(&module_rs)
        .unwrap()
        .replace("    ],", "        DatabaseModule::for_root(None),\n    ],");
    fs::write(&module_rs, with_db).unwrap();

    run_ok(&app, &["g", "resource", "posts"]);

    let module = fs::read_to_string(&module_rs).unwrap();
    for ident in ["PostsHttpModule", "AuthnModule", "AuthzHttpModule"] {
        assert!(module.contains(&format!("{ident},")), "{ident}: {module}");
    }
}

fn write_fake_migrations_crate(root: &Path) {
    let dir = root.join("crates/migrations/src");
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        dir.join("lib.rs"),
        "mod m20260101_000000_init;\nmod migrator;\n\npub use migrator::Migrator;\n",
    )
    .unwrap();
    fs::write(
        dir.join("migrator.rs"),
        "use sea_orm_migration::prelude::*;\n\nuse super::{\n    m20260101_000000_init,\n};\n\npub struct Migrator;\n",
    )
    .unwrap();
    fs::write(dir.join("m20260101_000000_init.rs"), "// init\n").unwrap();
}

#[test]
fn generate_migration_registers_in_both_lib_and_migrator() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    write_fake_migrations_crate(dir.path());

    run_ok(
        dir.path(),
        &[
            "g",
            "migration",
            "create_widget",
            "-p",
            dir.path().to_str().unwrap(),
        ],
    );

    let mig = dir.path().join("crates/migrations/src");
    // The generated file: m<date>_<seq>_create_widget.rs (date is today).
    let generated: Vec<_> = fs::read_dir(&mig)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|n| n.ends_with("_create_widget.rs"))
        .collect();
    assert_eq!(
        generated.len(),
        1,
        "one migration file created: {generated:?}"
    );
    let stem = generated[0].trim_end_matches(".rs").to_string();

    // Registered in BOTH lib.rs and migrator.rs — the whole point.
    let lib = fs::read_to_string(mig.join("lib.rs")).unwrap();
    assert!(lib.contains(&format!("mod {stem};")), "lib.rs: {lib}");

    let migrator = fs::read_to_string(mig.join("migrator.rs")).unwrap();
    // The new stem appears twice (the `use super::` import and the `Box::new`
    // vec entry) regardless of how rustfmt wrapped the file.
    assert!(
        migrator.matches(&stem).count() >= 2,
        "migrator must import and box the new migration: {migrator}"
    );
    assert!(
        migrator.contains(&format!("Box::new({stem}::Migration)")),
        "migrator vec: {migrator}"
    );
    // The pre-existing migration survives the regeneration.
    assert!(
        migrator.contains("Box::new(m20260101_000000_init::Migration)"),
        "migrator kept init: {migrator}"
    );
    assert!(
        migrator.contains("pub async fn migrate"),
        "migrator has migrate fn"
    );
}

#[test]
fn generate_migration_bootstraps_the_crate_when_absent() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    // No `crates/migrations` — a workspace scaffolded before it shipped.
    run_ok(
        dir.path(),
        &[
            "g",
            "migration",
            "create_widget",
            "-p",
            dir.path().to_str().unwrap(),
        ],
    );

    let mig = dir.path().join("crates/migrations/src");
    assert!(mig.join("lib.rs").is_file());
    assert!(mig.join("bin/migrate.rs").is_file());
    assert!(dir.path().join("crates/seed/src/main.rs").is_file());

    let lib = fs::read_to_string(mig.join("lib.rs")).unwrap();
    assert!(
        lib.contains("_create_widget;"),
        "lib.rs registers it: {lib}"
    );
    let migrator = fs::read_to_string(mig.join("migrator.rs")).unwrap();
    assert!(
        migrator.contains("_create_widget::Migration)"),
        "migrator boxes it: {migrator}"
    );
}

#[test]
fn generate_http_adapter_wires_feature_mod() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "http", "posts", "-p", path]);

    let feature = dir.path().join("crates/features/src/posts");
    assert!(feature.join("http/controller.rs").is_file());
    assert!(feature.join("http/module.rs").is_file());

    let mod_rs = fs::read_to_string(feature.join("mod.rs")).unwrap();
    assert!(mod_rs.contains("pub mod http;"));
    assert!(mod_rs.contains("PostsController"));
    assert!(mod_rs.contains("PostsHttpModule"));
}

/// Every route declares a posture — the `hello` starter and the GraphQL adapter
/// both write `#[public]`, and the HTTP adapter used to write neither, so any
/// app that took a `g http` booted with `unguarded routes detected` on a route
/// nobody had decided about.
#[test]
fn generate_http_adapter_declares_a_route_posture() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "http", "posts", "-p", path]);

    let controller = fs::read_to_string(
        dir.path()
            .join("crates/features/src/posts/http/controller.rs"),
    )
    .unwrap();
    assert!(
        controller.contains("#[public]"),
        "the scaffolded route must declare its posture: {controller}"
    );
    assert!(
        controller.contains("SECURITY:"),
        "and say why it is open, the way the graphql adapter does: {controller}"
    );
}

#[test]
fn generate_ws_adapter_ensures_dep_and_wires() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "ws", "posts", "-p", path]);

    assert!(
        dir.path()
            .join("crates/features/src/posts/ws/gateway.rs")
            .is_file()
    );
    let features_cargo = fs::read_to_string(dir.path().join("crates/features/Cargo.toml")).unwrap();
    assert!(features_cargo.contains("nest-rs-ws"));
}

/// A self-mount path is its exclusive namespace, so two gateways cannot share
/// one. The template hard-coded `/ws`, which meant a second `g ws` produced an
/// app that failed boot on `duplicate self-mounted endpoint path "/ws"` — and
/// the generator's own next-step line told you to wire it in.
#[test]
fn generate_ws_adapter_gives_each_gateway_a_distinct_path() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "ws", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "feature", "notify", "-p", path]);
    run_ok(dir.path(), &["g", "ws", "notify", "-p", path]);

    let read = |feature: &str| {
        fs::read_to_string(
            dir.path()
                .join(format!("crates/features/src/{feature}/ws/gateway.rs")),
        )
        .unwrap()
    };
    let posts = read("posts");
    let notify = read("notify");
    assert!(
        posts.contains(r#"path = "/ws/posts""#),
        "the gateway path carries the feature name: {posts}"
    );
    assert!(
        notify.contains(r#"path = "/ws/notify""#),
        "so a second adapter does not collide: {notify}"
    );

    // The HTTP adapter claims `/<feature>`; the gateway must not land there
    // either — a controller prefix and a self-mount on one path is the same
    // exclusivity failure across families.
    run_ok(dir.path(), &["g", "http", "posts", "-p", path]);
    let controller = fs::read_to_string(
        dir.path()
            .join("crates/features/src/posts/http/controller.rs"),
    )
    .unwrap();
    assert!(
        controller.contains(r#"path = "/posts""#) && !posts.contains(r#"path = "/posts""#),
        "the two adapters of one feature must claim different paths",
    );
}

/// `WsModule` provides the connection registry every default-namespace gateway
/// reads. Left out, the app compiles, mounts the gateway, and *then* dies — so
/// the generator writes the import rather than leaving it to the boot.
#[test]
fn generate_ws_adapter_imports_the_connection_registry() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "ws", "posts", "-p", path]);

    let module_rs =
        fs::read_to_string(dir.path().join("crates/features/src/posts/ws/module.rs")).unwrap();
    assert!(
        module_rs.contains("use nest_rs_ws::WsModule;")
            && module_rs.contains("imports = [PostsModule, WsModule]"),
        "the generated ws module must import WsModule: {module_rs}"
    );
}

/// `#[messages]` expands to `nest_rs_guards::GuardAsWsMessageCheck`, gated
/// behind that crate's `ws` feature — and the gateway body logs. Without both,
/// `cargo check -p features` fails while `cargo check --workspace` passes
/// (feature unification through a dev-dependency), which is the worst possible
/// place for the failure to surface.
#[test]
fn generate_ws_adapter_enables_the_guards_ws_feature_and_tracing() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();
    let features_cargo_path = dir.path().join("crates/features/Cargo.toml");
    fs::write(
        &features_cargo_path,
        "[package]\nname = \"features\"\n\n[dependencies]\n\
         nest-rs-core.workspace = true\nnest-rs-guards.workspace = true\n",
    )
    .unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "ws", "posts", "-p", path]);

    let features_cargo = fs::read_to_string(&features_cargo_path).unwrap();
    assert!(
        features_cargo
            .lines()
            .any(|l| l.starts_with("nest-rs-guards") && l.contains("\"ws\"")),
        "nest-rs-guards needs its `ws` feature: {features_cargo}"
    );
    assert!(features_cargo.contains("tracing"), "{features_cargo}");
}

/// The finding: `/websockets/` listed three dependencies and said `nestrs g ws`
/// writes all three — it did, and the *first typed payload* still failed to
/// compile. `nest_rs_ws` re-exports `serde_json`, never `serde`, so the
/// `#[derive(serde::Deserialize)]` DTO the next page presents as the normal case
/// had no `serde` in the manifest.
#[test]
fn generate_ws_adapter_brings_serde_for_a_typed_payload() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();
    let features_cargo_path = dir.path().join("crates/features/Cargo.toml");
    fs::write(
        &features_cargo_path,
        "[package]\nname = \"features\"\n\n[dependencies]\n\
         nest-rs-core.workspace = true\nnest-rs-guards.workspace = true\n",
    )
    .unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "ws", "posts", "-p", path]);

    let features_cargo = fs::read_to_string(&features_cargo_path).unwrap();
    assert!(
        features_cargo.lines().any(|l| l.starts_with("serde")),
        "the features crate needs `serde` for a typed WS payload: {features_cargo}"
    );
    let root_cargo = fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
    assert!(
        root_cargo.contains("serde = { version = \"1\", features = [\"derive\"] }"),
        "and the workspace pin carries the `derive` feature the DTO needs: {root_cargo}"
    );
}

/// The schedule skeleton logs too — same class as the ws and queue ones.
#[test]
fn generate_schedule_adapter_brings_tracing() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "schedule", "posts", "-p", path]);

    let tasks_rs = fs::read_to_string(
        dir.path()
            .join("crates/features/src/posts/schedule/tasks.rs"),
    )
    .unwrap();
    assert!(tasks_rs.contains("tracing::"), "the skeleton logs");
    let features_cargo = fs::read_to_string(dir.path().join("crates/features/Cargo.toml")).unwrap();
    assert!(
        features_cargo.contains("tracing"),
        "…so `tracing` has to be a dependency: {features_cargo}"
    );
}

#[test]
fn generate_queue_adapter_puts_command_at_the_port() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "queue", "posts", "-p", path]);

    let feature = dir.path().join("crates/features/src/posts");

    // The imperative queue payload is a `Command` at the port, not inside the
    // `queue/` adapter — a producer↔worker contract the processor imports.
    let command_rs = fs::read_to_string(feature.join("command.rs")).unwrap();
    assert!(command_rs.contains("pub struct ProcessPostCommand"));

    let processor_rs = fs::read_to_string(feature.join("queue/processor.rs")).unwrap();
    // rustfmt may reorder the braced list, so assert on the names, not the line.
    let port_import = processor_rs
        .lines()
        .find(|l| l.starts_with("use crate::posts::"))
        .expect("the processor imports its port");
    assert!(
        port_import.contains("ProcessPostCommand") && port_import.contains("PostsQueue"),
        "{port_import}"
    );
    assert!(processor_rs.contains("job: ProcessPostCommand"));
    // The payload is imported, never redefined in the adapter.
    assert!(!processor_rs.contains("pub struct ProcessPostCommand"));

    // The port `mod.rs` exposes both the command and the adapter module.
    let mod_rs = fs::read_to_string(feature.join("mod.rs")).unwrap();
    assert!(mod_rs.contains("mod command;"));
    let command_export = mod_rs
        .lines()
        .find(|l| l.starts_with("pub use command::"))
        .expect("the port re-exports its command");
    assert!(
        command_export.contains("ProcessPostCommand") && command_export.contains("PostsQueue"),
        "{command_export}"
    );
    assert!(mod_rs.contains("pub mod queue;"));
    assert!(mod_rs.contains("PostsQueueModule"));
}

/// The `#[queue]` marker is the artifact `push_to::<Q>` is generic over, so it
/// has to be *reachable*. Declared in the adapter's private `processor` module
/// it was invisible to the feature's own service one directory up, leaving the
/// untyped `push(name, job)` escape hatch as the only way to enqueue — the exact
/// check `QueueName` exists to provide, lost.
#[test]
fn generate_queue_adapter_declares_the_queue_marker_at_the_port() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "queue", "posts", "-p", path]);

    let feature = dir.path().join("crates/features/src/posts");
    let command_rs = fs::read_to_string(feature.join("command.rs")).unwrap();
    assert!(
        command_rs.contains("#[queue(name = \"posts\", job = ProcessPostCommand)]")
            && command_rs.contains("pub struct PostsQueue;"),
        "the marker belongs beside the payload it names: {command_rs}"
    );

    let processor_rs = fs::read_to_string(feature.join("queue/processor.rs")).unwrap();
    assert!(
        !processor_rs.contains("pub struct PostsQueue"),
        "and nowhere else: {processor_rs}"
    );
    assert!(processor_rs.contains("#[process(queue = PostsQueue"));

    // Reachable from the port, which is what a producer imports.
    let mod_rs = fs::read_to_string(feature.join("mod.rs")).unwrap();
    assert!(mod_rs.contains("PostsQueue"), "{mod_rs}");
}

/// The generated processor module imports the port like every sibling adapter
/// does. It reads as redundant only while the stub stays inert: give it the
/// documented shape — a thin processor delegating to the port service — and
/// without the import the worker dies at boot with an access violation.
#[test]
fn generate_queue_adapter_module_imports_the_port() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "queue", "posts", "-p", path]);

    let module_rs =
        fs::read_to_string(dir.path().join("crates/features/src/posts/queue/module.rs")).unwrap();
    assert!(
        module_rs.contains("imports = [PostsModule]"),
        "the queue adapter module must import its port: {module_rs}"
    );

    // The skeleton logs, so `tracing` has to come with it.
    let features_cargo = fs::read_to_string(dir.path().join("crates/features/Cargo.toml")).unwrap();
    assert!(features_cargo.contains("tracing"), "{features_cargo}");
}

/// `#[resolver]` expands to names behind `nest-rs-guards`' `graphql` feature,
/// and that crate is already a dependency of every scaffolded workspace — so
/// the generator has to turn the *feature* on, not add the entry. Without it
/// the very first `cargo check` after `g graphql` is a wall of
/// `cannot find … in nest_rs_guards`.
#[test]
fn generate_graphql_adapter_enables_the_guards_graphql_feature() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();
    // The starter shape: the crate is declared, with default features.
    let features_cargo_path = dir.path().join("crates/features/Cargo.toml");
    fs::write(
        &features_cargo_path,
        "[package]\nname = \"features\"\n\n[dependencies]\nnest-rs-core.workspace = true\n\
         nest-rs-guards.workspace = true\n",
    )
    .unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "graphql", "posts", "-p", path]);

    let features_cargo = fs::read_to_string(&features_cargo_path).unwrap();
    assert!(
        features_cargo.contains("nest-rs-guards") && features_cargo.contains("graphql"),
        "the guards crate has to gain the graphql feature: {features_cargo}"
    );

    // A port with no entity stays the `#[public]` stand-in — nothing to guard.
    let resolver = fs::read_to_string(
        dir.path()
            .join("crates/features/src/posts/graphql/resolver.rs"),
    )
    .unwrap();
    assert!(resolver.contains("#[public]"), "{resolver}");
    assert!(
        !dir.path().join("crates/features/src/authz").exists(),
        "a workspace with no policy does not get one from a public count query",
    );
}

/// The GraphQL twin of `generate_resource_emits_the_guarded_form_…`: over a
/// `g resource` port the resolver is the `#[crud]` form behind the app's
/// guards, and the per-operation bridge it is enforced through
/// (`authz/graphql/`) is scaffolded with it. The old scaffold called
/// `svc.count()` — a method a `CrudService` does not have.
#[test]
fn generate_graphql_over_a_resource_emits_the_crud_form_and_its_bridge() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "resource", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "graphql", "posts", "-p", path]);

    let src = dir.path().join("crates/features/src");
    let resolver = fs::read_to_string(src.join("posts/graphql/resolver.rs")).unwrap();
    assert!(
        !resolver.contains("count()"),
        "a CrudService has no `count()`: {resolver}"
    );
    assert!(
        resolver.contains("#[use_guards(AuthnGuard, AuthzGuard)]"),
        "DB-backed rows are only reachable behind the ability guard: {resolver}"
    );
    assert!(
        resolver.contains("#[crud(") && resolver.contains("entity = PostEntity"),
        "the resource resolver uses the #[crud] form: {resolver}"
    );

    // The entity has to *be* a GraphQL object for the resolver to return it.
    let entity = fs::read_to_string(src.join("posts/entity.rs")).unwrap();
    assert!(entity.contains("#[expose(graphql"), "{entity}");

    // The bridge `/graphql` gates through, and the module that serves it.
    let module = fs::read_to_string(src.join("posts/graphql/module.rs")).unwrap();
    assert!(module.contains("AuthzGraphqlModule"), "{module}");
    let bridge = fs::read_to_string(src.join("authz/graphql/bridge.rs")).unwrap();
    assert!(
        bridge.contains("GraphqlAbilityBridge<AuthnGuard, AuthzGuard>"),
        "{bridge}"
    );
    let authz_graphql = fs::read_to_string(src.join("authz/graphql/module.rs")).unwrap();
    assert!(
        authz_graphql.contains("dyn GraphqlOperationGuard")
            && authz_graphql.contains("dyn GraphqlBatchContext")
            && authz_graphql.contains("forward_principal!(Claims, GraphqlAuthnGuard)"),
        "the three providers the bridge needs: {authz_graphql}"
    );
    let authz_mod = fs::read_to_string(src.join("authz/mod.rs")).unwrap();
    assert!(
        authz_mod.contains("pub use graphql::AuthzGraphqlModule;"),
        "{authz_mod}"
    );

    // Its crates, with the features that make those paths resolve.
    let features_cargo = fs::read_to_string(dir.path().join("crates/features/Cargo.toml")).unwrap();
    for needed in ["nest-rs-graphql", "async-graphql", "nest-rs-guards"] {
        assert!(
            features_cargo.contains(needed),
            "{needed}: {features_cargo}"
        );
    }
    assert!(
        features_cargo
            .contains("nest-rs-authz = { workspace = true, features = [\"http\", \"graphql\"] }"),
        "{features_cargo}"
    );
}

/// A second GraphQL adapter reuses the bridge the first one created rather
/// than failing on a file that already exists.
#[test]
fn generate_graphql_reuses_an_existing_authz_bridge() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "resource", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "graphql", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "resource", "tags", "-p", path]);
    run_ok(dir.path(), &["g", "graphql", "tags", "-p", path]);

    let authz_mod =
        fs::read_to_string(dir.path().join("crates/features/src/authz/mod.rs")).unwrap();
    assert_eq!(
        authz_mod.matches("pub mod graphql;").count(),
        1,
        "the index line is written once: {authz_mod}"
    );
}

#[test]
fn generate_adapter_is_rejected_on_rerun() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "http", "posts", "-p", path]);

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["g", "http", "posts", "-p", path])
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("already exists"));
}

#[test]
fn generate_adapter_requires_existing_feature() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["g", "ws", "ghost", "-p", dir.path().to_str().unwrap()])
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("not found"));
}

#[test]
fn generate_dry_run_writes_nothing() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &[
            "g",
            "feature",
            "posts",
            "--dry-run",
            "-p",
            dir.path().to_str().unwrap(),
        ],
    );

    assert!(!dir.path().join("crates/features/src/posts").exists());
    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(!lib.contains("pub mod posts;"));
}

#[test]
fn version_prints_single_line() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("version")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let line = stdout.trim();
    assert!(line.starts_with("NestRS "));
    assert!(!line.contains('\n'));
}

#[test]
fn about_prints_metadata_block() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("about")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Version:"));
    assert!(stdout.contains("Tagline:"));
    assert!(stdout.contains("Yoann Vanitou"));
}

#[test]
fn run_subcommand_is_listed_in_help() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("--help")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("run"));
}

#[test]
fn run_without_toolchain_and_no_bootstrap_errors_clearly() {
    // Hide just/bacon/cargo from the child so the toolchain probe finds nothing,
    // then assert the bootstrap-disabled path reports a manual-install hint
    // instead of silently installing or panicking.
    let empty = tempfile::tempdir().unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["run", "--no-bootstrap", "dev"])
        .env("PATH", empty.path())
        .output()
        .unwrap();

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("just"), "stderr: {stderr}");
    assert!(stderr.contains("cargo install"), "stderr: {stderr}");
}

#[test]
fn doctor_passes_with_rust_toolchain() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("doctor")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}