wizlight 0.1.0-beta.1

Async client for Philips WiZ smart bulbs over the local UDP protocol, plus the wizlight CLI
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
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
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
#![cfg(feature = "cli")]

mod common;

use std::process::{Command as Proc, Output};
use std::time::Duration;

use clap::{CommandFactory, Parser};
use common::mock_bulb::{MockBulb, Personality};
use serde_json::Value;
use wizlight::cli::{Cli, Command, Target, render_failure};
use wizlight::{DEFAULT_WAIT, RetryPolicy, Scene};

/// Runs the real binary, which is the only way to observe an exit code.
fn wizlight(args: &[&str]) -> Output {
    Proc::new(env!("CARGO_BIN_EXE_wizlight"))
        .args(args)
        .output()
        .expect("the binary was built by the test harness")
}

/// Runs a command that would otherwise broadcast onto the real LAN.
///
/// Every scan in this file is aimed at loopback and given a short window, so
/// that the suite neither shouts at whatever network the machine is on nor
/// waits five seconds a time to hear nothing back.
fn scan(args: &[&str]) -> Output {
    scan_at("127.0.0.1", "0.05", args, &[])
}

/// [`scan`] with an environment variable set for the run.
fn scan_with_env(args: &[&str], key: &str, value: &str) -> Output {
    scan_at("127.0.0.1", "0.05", args, &[(key, value)])
}

fn scan_at(broadcast: &str, wait: &str, args: &[&str], env: &[(&str, &str)]) -> Output {
    let mut full = vec!["--broadcast", broadcast, "--wait", wait];
    full.extend_from_slice(args);
    let mut proc = Proc::new(env!("CARGO_BIN_EXE_wizlight"));
    proc.args(&full);
    for (key, value) in env {
        proc.env(key, value);
    }
    proc.output()
        .expect("the binary was built by the test harness")
}

fn target(name: &str) -> Target {
    Target {
        target: Some(name.parse().expect("a valid target")),
        all: false,
    }
}

#[test]
fn global_flags_and_subcommand_are_parsed() {
    let cli = Cli::try_parse_from([
        "wizlight",
        "--json",
        "--timeout",
        "7",
        "--broadcast",
        "192.168.1.255:38899",
        "discover",
    ])
    .expect("discover should parse");

    assert!(cli.json);
    assert_eq!(cli.timeout, Duration::from_secs(7));
    assert_eq!(
        cli.broadcast,
        ["192.168.1.255:38899".parse().expect("a socket address")]
    );
    assert_eq!(cli.command, Command::Discover);
}

#[test]
fn a_broadcast_address_may_omit_the_port_and_may_repeat() {
    // Bulbs are only ever on 38899, so requiring it would be ceremony; a
    // multi-homed host needs one address per subnet, so one is not enough.
    let cli = Cli::try_parse_from([
        "wizlight",
        "--broadcast",
        "192.168.0.255",
        "--broadcast",
        "10.0.0.255",
        "discover",
    ])
    .expect("both parse");

    let ports: Vec<u16> = cli.broadcast.iter().map(|addr| addr.port()).collect();
    assert_eq!(ports, [wizlight::PORT, wizlight::PORT]);
    let ips: Vec<String> = cli
        .broadcast
        .iter()
        .map(|addr| addr.ip().to_string())
        .collect();
    assert_eq!(ips, ["192.168.0.255", "10.0.0.255"]);
}

#[test]
fn durations_may_be_fractional_and_may_not_be_negative() {
    let cli = Cli::try_parse_from(["wizlight", "--wait", "0.25", "discover"]).expect("parses");
    assert_eq!(cli.wait, Duration::from_millis(250));

    // Rejected by the parser, so it is a usage error rather than a run that
    // fails much later for a reason nobody connects to the flag.
    assert!(Cli::try_parse_from(["wizlight", "--timeout", "-1", "discover"]).is_err());
    assert!(Cli::try_parse_from(["wizlight", "--wait", "soon", "discover"]).is_err());
}

#[test]
fn the_scan_window_defaults_to_the_measured_one() {
    // Asserted against the library constant rather than a literal: five
    // seconds is what a scan needs to stop coming back a bulb short, and the
    // flag's default must not drift away from it.
    let cli = Cli::try_parse_from(["wizlight", "discover"]).expect("parses");
    assert_eq!(cli.wait, DEFAULT_WAIT);
}

#[test]
fn the_cli_is_more_patient_than_the_library_default() {
    // The library's 500 ms is measured at close range; the same bulb across a
    // flat has a round trip past a second. Everything else about the policy is
    // the library's.
    let cli = Cli::try_parse_from(["wizlight", "discover"]).expect("parses");
    let policy = cli.policy();
    let default = RetryPolicy::default();

    assert_eq!(policy.attempt_timeout, Duration::from_secs(2));
    assert!(policy.attempt_timeout > default.attempt_timeout);
    assert_eq!(policy.attempts, default.attempts);
    assert_eq!(policy.min_interval, default.min_interval);
}

#[test]
fn a_target_is_parsed_and_reported_by_the_command() {
    let cli = Cli::try_parse_from(["wizlight", "status", "192.168.0.5"]).expect("status parses");
    assert_eq!(cli.command, Command::Status(target("192.168.0.5")));
    assert_eq!(cli.command.name(), "status");
    assert_eq!(cli.command.target(), Some("192.168.0.5"));
    assert_eq!(Command::Discover.target(), None);
}

#[test]
fn a_global_flag_is_accepted_after_the_subcommand() {
    let cli = Cli::try_parse_from(["wizlight", "status", "192.168.0.5", "--json"])
        .expect("global flags are global");
    assert!(cli.json);
}

#[test]
fn output_renderer_formats_typed_data_as_json() {
    let json = wizlight::cli::render_json(&serde_json::json!({"ok": true, "value": 3}));
    assert_eq!(json.trim(), "{\"ok\":true,\"value\":3}");
}

#[test]
fn a_human_failure_is_a_plain_line_not_json() {
    let rendered = render_failure(Some(&Command::Status(target("1.2.3.4"))), "boom", false);
    assert_eq!(rendered, "error: boom");
}

#[test]
fn a_json_failure_carries_the_command_and_target() {
    let rendered = render_failure(Some(&Command::Status(target("1.2.3.4"))), "boom", true);
    let value: Value = serde_json::from_str(&rendered).expect("valid JSON");
    assert_eq!(value["ok"], Value::Bool(false));
    assert_eq!(value["command"], "status");
    assert_eq!(value["target"], "1.2.3.4");
    assert_eq!(value["error"], "boom");

    // A command with no target still produces the key, as null.
    let rendered = render_failure(Some(&Command::Discover), "boom", true);
    let value: Value = serde_json::from_str(&rendered).expect("valid JSON");
    assert_eq!(value["command"], "discover");
    assert_eq!(value["target"], Value::Null);
}

#[tokio::test(flavor = "multi_thread")]
async fn bench_ramps_rate_probes_latency_and_interpolation_and_restores_state() {
    let bulb = MockBulb::builder()
        .mac("9877d5230f0a")
        .pilot(serde_json::json!({
            "mac": "9877d5230f0a",
            "state": true,
            "r": 255,
            "g": 80,
            "b": 0,
            "dimming": 40,
            "sceneId": 0,
            "rssi": -52
        }))
        .start()
        .await;
    let addr = bulb.addr().to_string();

    let human = against(
        &bulb,
        &addr,
        &[
            "bench",
            "--min-rate",
            "10",
            "--max-rate",
            "20",
            "--steps",
            "2",
            "--hold",
            "0.05",
        ],
    )
    .await;
    assert_eq!(human.status.code(), Some(0));
    let stdout = String::from_utf8(human.stdout).expect("utf-8");
    assert!(stdout.contains("ESP25_SHRGB_01"), "{stdout}");
    assert!(stdout.contains("rate (Hz)"), "{stdout}");
    assert!(stdout.contains("latency"), "{stdout}");
    assert!(stdout.contains("interpolate"), "{stdout}");
    assert!(stdout.contains("restored      yes"), "{stdout}");
    let stderr = String::from_utf8(human.stderr).expect("utf-8");
    assert!(
        stderr.contains("warning: benchmarking will visibly flash"),
        "{stderr}"
    );

    let json = stdout_json(
        &against(
            &bulb,
            &addr,
            &[
                "--json",
                "bench",
                "--min-rate",
                "10",
                "--max-rate",
                "20",
                "--steps",
                "2",
                "--hold",
                "0.05",
            ],
        )
        .await,
    );
    assert_eq!(json["ok"], Value::Bool(true));
    assert_eq!(json["command"], "bench");
    assert_eq!(json["result"]["device"]["model"], "ESP25_SHRGB_01");
    assert_eq!(json["result"]["restored"], Value::Bool(true));
    let steps = json["result"]["rate_sweep"].as_array().expect("steps list");
    assert_eq!(steps.len(), 2);
    assert_eq!(steps[0]["rate_hz"], 10.0);
    assert_eq!(steps[1]["rate_hz"], 20.0);
    assert!(steps[0]["rtt_ms"]["median"].is_number(), "{steps:?}");
    assert_eq!(
        json["result"]["latency_probe"]["pattern"],
        "black_to_white_step"
    );
    assert_eq!(
        json["result"]["interpolation_probe"]["abrupt_step"]["pattern"],
        "red_to_blue_step"
    );

    // Pre-bench state was restored after both runs.
    let restored = bulb.pilot();
    assert_eq!(restored["state"], Value::Bool(true));
    assert_eq!(restored["r"], 255);
    assert_eq!(restored["g"], 80);
    assert_eq!(restored["b"], 0);
    assert_eq!(restored["dimming"], 40);
}

#[test]
fn bench_rejects_invalid_rate_and_step_arguments() {
    for args in [
        &["bench", "192.168.0.5", "--min-rate", "0"][..],
        &["bench", "192.168.0.5", "--max-rate", "-5"][..],
        &["bench", "192.168.0.5", "--steps", "0"][..],
        &["bench", "192.168.0.5", "--hold", "0"][..],
        &[
            "bench",
            "192.168.0.5",
            "--min-rate",
            "40",
            "--max-rate",
            "10",
        ][..],
        &["bench", "192.168.0.5", "--rates", "0,5"][..],
        &[
            "bench",
            "192.168.0.5",
            "--rates",
            "1,2,4",
            "--min-rate",
            "1",
        ][..],
        &["bench", "192.168.0.5", "--pulse-durations", "0,100"][..],
        &["bench", "192.168.0.5", "--pulse-delta", "0"][..],
    ] {
        let output = wizlight(args);
        assert_eq!(output.status.code(), Some(2), "{args:?}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn bench_supports_explicit_rates_dimming_set_state_and_pulse_sweeps() {
    let bulb = MockBulb::builder()
        .mac("9877d5230f0a")
        .pilot(serde_json::json!({
            "mac": "9877d5230f0a",
            "state": true,
            "sceneId": 11,
            "temp": 2700,
            "dimming": 75,
            "rssi": -50
        }))
        .start()
        .await;
    let addr = bulb.addr().to_string();

    let json = stdout_json(
        &against(
            &bulb,
            &addr,
            &[
                "--json",
                "bench",
                "--mode",
                "set-state",
                "--rates",
                "2,4,8",
                "--hold",
                "0.05",
                "--pulse-durations",
                "50,150",
                "--pulse-delta",
                "-60",
            ],
        )
        .await,
    );
    assert_eq!(json["ok"], Value::Bool(true));
    assert_eq!(json["result"]["config"]["mode"], "set_state");
    assert_eq!(json["result"]["config"]["method"], "setState");
    let steps = json["result"]["rate_sweep"].as_array().expect("rate steps");
    let rates: Vec<f64> = steps
        .iter()
        .map(|s| s["rate_hz"].as_f64().unwrap())
        .collect();
    assert_eq!(rates, vec![2.0, 4.0, 8.0]);
    assert_eq!(
        json["result"]["interpolation_probe"]["abrupt_step"]["pattern"],
        "dim_10_to_100_step"
    );
    let pulses = json["result"]["pulse_sweep"]
        .as_array()
        .expect("pulse steps");
    assert_eq!(pulses.len(), 2);
    assert_eq!(pulses[0]["delta"], -60);
    assert_eq!(pulses[0]["duration_ms"], 50);
    assert_eq!(pulses[0]["responses"], 1);
    assert_eq!(pulses[1]["duration_ms"], 150);
    assert_eq!(pulses[1]["responses"], 1);
    assert_eq!(json["result"]["restored"], Value::Bool(true));
    assert_eq!(bulb.pilot()["sceneId"], 11);
    assert_eq!(bulb.pilot()["dimming"], 75);
}

#[tokio::test(flavor = "multi_thread")]
async fn pulse_command_sends_pulse_and_rejects_non_dimmable_devices() {
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    let human = against(
        &bulb,
        &addr,
        &["pulse", "--delta", "-80", "--duration", "150"],
    )
    .await;
    assert_eq!(human.status.code(), Some(0));
    assert_eq!(
        String::from_utf8(human.stdout).unwrap().trim(),
        "pulse -80%  150 ms"
    );

    let json = stdout_json(
        &against(
            &bulb,
            &addr,
            &["--json", "pulse", "--delta", "50", "--duration", "200"],
        )
        .await,
    );
    assert_eq!(json["ok"], Value::Bool(true));
    assert_eq!(json["command"], "pulse");
    assert_eq!(json["result"]["delta"], 50);
    assert_eq!(json["result"]["duration"], 200);

    // A smart socket has no brightness feature, so `pulse` fails cleanly.
    let socket = MockBulb::builder()
        .personality(Personality::socket())
        .start()
        .await;
    let sock_addr = socket.addr().to_string();
    let failed = against(
        &socket,
        &sock_addr,
        &["pulse", "--delta", "-50", "--duration", "100"],
    )
    .await;
    assert_eq!(failed.status.code(), Some(1));
    let stderr = String::from_utf8(failed.stderr).unwrap();
    assert!(stderr.contains("cannot pulse brightness"), "{stderr}");

    // Usage errors for invalid delta or duration.
    for bad in [
        &["pulse", "192.168.0.5", "--delta", "0", "--duration", "100"][..],
        &[
            "pulse",
            "192.168.0.5",
            "--delta",
            "-101",
            "--duration",
            "100",
        ][..],
        &["pulse", "192.168.0.5", "--delta", "-50", "--duration", "0"][..],
    ] {
        assert_eq!(wizlight(bad).status.code(), Some(2), "{bad:?}");
    }
}

/// A bulb that is there and will not answer, so a command times out rather
/// than failing to find anything. A closed port would be quicker, but Windows
/// turns the resulting ICMP into a socket error and the failure would no
/// longer be the one being tested.
async fn deaf_bulb() -> MockBulb {
    let bulb = MockBulb::start().await;
    bulb.drop_next(usize::MAX);
    bulb
}

#[tokio::test(flavor = "multi_thread")]
async fn a_failure_goes_to_stderr_and_stdout_stays_empty() {
    let bulb = deaf_bulb().await;
    let addr = bulb.addr().to_string();

    let output =
        tokio::task::spawn_blocking(move || wizlight(&["--timeout", "0.05", "status", &addr]))
            .await
            .expect("the command ran");

    assert_eq!(output.status.code(), Some(4), "a timeout has its own code");
    assert!(
        output.stdout.is_empty(),
        "results go to stdout, errors do not"
    );

    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(stderr.starts_with("error: "), "{stderr}");
    assert!(stderr.contains("getPilot"), "{stderr}");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_json_failure_goes_to_stderr_as_json_and_only_once() {
    let bulb = deaf_bulb().await;
    let addr = bulb.addr().to_string();
    let target = addr.clone();

    let output = tokio::task::spawn_blocking(move || {
        wizlight(&["--json", "--timeout", "0.05", "status", &addr])
    })
    .await
    .expect("the command ran");

    assert_eq!(output.status.code(), Some(4));
    assert!(
        output.stdout.is_empty(),
        "results go to stdout, errors do not"
    );

    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert_eq!(stderr.lines().count(), 1, "rendered twice: {stderr}");

    let value: Value = serde_json::from_str(stderr.trim()).expect("stderr is JSON under --json");
    assert_eq!(value["ok"], Value::Bool(false));
    assert_eq!(value["command"], "status");
    assert_eq!(value["target"], target);
}

/// Long enough for a loopback registration and the `getSystemConfig` that
/// follows it, short enough that the suite stays quick.
const SCAN: &str = "0.4";

#[tokio::test(flavor = "multi_thread")]
async fn discover_lists_what_answered() {
    let bulb = MockBulb::builder().mac("9877d5230f0a").start().await;
    let addr = bulb.addr().to_string();

    let output = tokio::task::spawn_blocking(move || scan_at(&addr, SCAN, &["discover"], &[]))
        .await
        .expect("the scan ran");

    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8(output.stdout).expect("utf-8");
    let line = stdout.trim();

    // MAC first: it is the column worth copying, being the only identity that
    // survives a DHCP lease.
    assert!(line.starts_with("9877d5230f0a"), "{line}");
    assert!(line.contains("127.0.0.1"), "{line}");
    assert!(line.contains("ESP25_SHRGB_01"), "{line}");
    assert!(line.contains("1.38.0"), "{line}");
}

#[tokio::test(flavor = "multi_thread")]
async fn discover_json_carries_the_envelope_and_one_object_per_bulb() {
    let bulb = MockBulb::builder().mac("9877d5230f0a").start().await;
    let addr = bulb.addr().to_string();
    let port = bulb.port();

    let output =
        tokio::task::spawn_blocking(move || scan_at(&addr, SCAN, &["--json", "discover"], &[]))
            .await
            .expect("the scan ran");

    let stdout = String::from_utf8(output.stdout).expect("utf-8");
    let value: Value = serde_json::from_str(stdout.trim()).expect("stdout is JSON under --json");

    assert_eq!(value["ok"], Value::Bool(true));
    assert_eq!(value["command"], "discover");
    assert_eq!(value["target"], Value::Null);

    let bulbs = value["result"].as_array().expect("result is a list");
    assert_eq!(bulbs.len(), 1);
    assert_eq!(bulbs[0]["mac"], "9877d5230f0a");
    assert_eq!(bulbs[0]["ip"], "127.0.0.1");
    assert_eq!(bulbs[0]["port"], port);
    assert_eq!(bulbs[0]["model"], "ESP25_SHRGB_01");
    assert_eq!(bulbs[0]["firmware"], "1.38.0");
}

#[tokio::test(flavor = "multi_thread")]
async fn discover_finding_nothing_is_a_success_with_an_empty_list() {
    // A scan answers a question, and "nobody is out there" is an answer. It is
    // acting on a bulb that is not there that deserves a non-zero exit.
    let output = tokio::task::spawn_blocking(|| scan(&["--json", "discover"]))
        .await
        .expect("the scan ran");

    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8(output.stdout).expect("utf-8");
    let value: Value = serde_json::from_str(stdout.trim()).expect("JSON");
    assert_eq!(value["ok"], Value::Bool(true));
    assert_eq!(value["result"], serde_json::json!([]));

    let human = String::from_utf8(scan(&["discover"]).stdout).expect("utf-8");
    assert!(human.trim().starts_with("no bulbs answered"), "{human}");
}

#[tokio::test(flavor = "multi_thread")]
async fn discover_reports_a_bulb_that_will_not_describe_itself() {
    // `getSystemConfig` is a courtesy, not a condition of existing. Firmware
    // old enough to lack it answers the registration perfectly well, and a
    // listing that hid those bulbs would be worse than one with gaps in it.
    let bulb = MockBulb::builder()
        .personality(Personality::rgb().with_system_config(
            r#"{"env":"pro","error":{"code":-32601,"message":"Method not found"}}"#,
        ))
        .mac("9877d523a4da")
        .start()
        .await;
    let addr = bulb.addr().to_string();

    let output =
        tokio::task::spawn_blocking(move || scan_at(&addr, SCAN, &["--json", "discover"], &[]))
            .await
            .expect("the scan ran");

    let stdout = String::from_utf8(output.stdout).expect("utf-8");
    let value: Value = serde_json::from_str(stdout.trim()).expect("JSON");
    let bulbs = value["result"].as_array().expect("result is a list");
    assert_eq!(bulbs.len(), 1, "{value}");
    assert_eq!(bulbs[0]["mac"], "9877d523a4da");
    assert_eq!(bulbs[0]["model"], Value::Null);
    assert_eq!(bulbs[0]["firmware"], Value::Null);

    // The human column is a dash rather than the word "null".
    let addr = bulb.addr().to_string();
    let human = String::from_utf8(
        tokio::task::spawn_blocking(move || scan_at(&addr, SCAN, &["discover"], &[]))
            .await
            .expect("the scan ran")
            .stdout,
    )
    .expect("utf-8");
    assert_eq!(human.trim(), "9877d523a4da  127.0.0.1  -  -");
}

/// Runs a command against a bulb, addressing it by whatever `target` says.
///
/// `--broadcast` points any scan at the mock rather than at the LAN, and the
/// windows are short because everything here is loopback.
async fn against(bulb: &MockBulb, target: &str, args: &[&str]) -> Output {
    let addr = bulb.addr().to_string();
    let target = target.to_owned();
    let mut owned: Vec<String> = vec![
        "--broadcast".into(),
        addr,
        "--wait".into(),
        SCAN.into(),
        "--timeout".into(),
        "0.5".into(),
    ];
    owned.extend(args.iter().map(|arg| (*arg).to_string()));
    owned.push(target);

    tokio::task::spawn_blocking(move || {
        let borrowed: Vec<&str> = owned.iter().map(String::as_str).collect();
        wizlight(&borrowed)
    })
    .await
    .expect("the command ran")
}

/// Lets a bulb answer the scan, then stops it answering anything else.
async fn goes_quiet_once_scanned(bulb: &MockBulb) {
    for _ in 0..400 {
        if !bulb.requests().is_empty() {
            break;
        }
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    bulb.drop_next(usize::MAX);
}

fn stdout_json(output: &Output) -> Value {
    let stdout = std::str::from_utf8(&output.stdout).expect("utf-8");
    serde_json::from_str(stdout.trim()).unwrap_or_else(|err| panic!("{err}: {stdout}"))
}

#[tokio::test(flavor = "multi_thread")]
async fn status_reports_what_the_bulb_says_it_is_doing() {
    let bulb = MockBulb::builder()
        .mac("9877d5230f0a")
        .pilot(serde_json::json!({
            "state": true, "r": 255, "g": 80, "b": 0, "dimming": 40, "sceneId": 0, "rssi": -52
        }))
        .start()
        .await;
    let addr = bulb.addr().to_string();

    let human = against(&bulb, &addr, &["status"]).await;
    assert_eq!(human.status.code(), Some(0));
    let line = String::from_utf8(human.stdout).expect("utf-8");
    assert_eq!(line.trim(), "on  rgb 255,80,0  40%  -52 dBm");

    let json = stdout_json(&against(&bulb, &addr, &["--json", "status"]).await);
    assert_eq!(json["ok"], Value::Bool(true));
    assert_eq!(json["command"], "status");
    assert_eq!(json["result"]["state"], Value::Bool(true));
    assert_eq!(json["result"]["r"], 255);
    assert_eq!(json["result"]["dimming"], 40);
}

#[tokio::test(flavor = "multi_thread")]
async fn status_names_a_running_scene() {
    let bulb = MockBulb::builder()
        .pilot(serde_json::json!({"state": true, "sceneId": 4, "speed": 100, "dimming": 100}))
        .start()
        .await;
    let addr = bulb.addr().to_string();

    let human = String::from_utf8(against(&bulb, &addr, &["status"]).await.stdout).expect("utf-8");
    assert!(human.contains("scene Party (4)"), "{human}");

    let json = stdout_json(&against(&bulb, &addr, &["--json", "status"]).await);
    assert_eq!(json["result"]["sceneId"], 4);
    assert_eq!(json["result"]["scene"], "Party");
}

#[tokio::test(flavor = "multi_thread")]
async fn info_describes_the_model_and_what_it_can_do() {
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    let human = String::from_utf8(against(&bulb, &addr, &["info"]).await.stdout).expect("utf-8");
    assert!(human.contains("ESP25_SHRGB_01"), "{human}");
    assert!(human.contains("1.38.0"), "{human}");
    assert!(human.contains("2200-6500 K"), "{human}");
    assert!(human.contains("colour"), "{human}");

    let json = stdout_json(&against(&bulb, &addr, &["--json", "info"]).await);
    assert_eq!(json["result"]["class"], "RGB");
    assert_eq!(json["result"]["features"]["color"], Value::Bool(true));
    assert_eq!(json["result"]["kelvin_range"]["min"], 2200);
}

#[tokio::test(flavor = "multi_thread")]
async fn scenes_lists_only_what_that_class_plays() {
    // A tunable white bulb has no colour, so the colour-only scenes are not
    // offered to it. Printing the whole table would be the easy thing to do
    // and would be wrong.
    let colour = MockBulb::start().await;
    let white = MockBulb::builder()
        .personality(Personality::tunable_white())
        .start()
        .await;
    let colour_addr = colour.addr().to_string();
    let white_addr = white.addr().to_string();

    let listed =
        String::from_utf8(against(&colour, &colour_addr, &["scenes"]).await.stdout).expect("utf-8");
    assert!(listed.contains("Party"), "{listed}");

    let listed =
        String::from_utf8(against(&white, &white_addr, &["scenes"]).await.stdout).expect("utf-8");
    assert!(!listed.contains("Party"), "{listed}");
    assert!(listed.contains("Cozy"), "{listed}");

    let json = stdout_json(&against(&white, &white_addr, &["--json", "scenes"]).await);
    let scenes = json["result"].as_array().expect("a list");
    assert!(scenes.iter().all(|scene| scene["name"] != "Party"));
}

#[tokio::test(flavor = "multi_thread")]
async fn on_sends_the_colour_it_was_given() {
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    let output = against(&bulb, &addr, &["on", "--rgb", "255,80,0", "-b", "40"]).await;
    assert_eq!(output.status.code(), Some(0));

    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["method"], "setPilot");
    assert_eq!(request["params"]["state"], Value::Bool(true));
    assert_eq!(request["params"]["r"], 255);
    assert_eq!(request["params"]["g"], 80);
    assert_eq!(request["params"]["b"], 0);
    assert_eq!(request["params"]["dimming"], 40);
}

#[tokio::test(flavor = "multi_thread")]
async fn hsv_is_converted_because_the_protocol_has_none() {
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    // Pure red at full saturation and value.
    against(&bulb, &addr, &["on", "--hsv", "0,100,100"]).await;
    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["params"]["r"], 255);
    assert_eq!(request["params"]["g"], 0);
    assert_eq!(request["params"]["b"], 0);

    // Half value halves the channels; it is not the bulb's own dimming, which
    // is not sent at all here.
    against(&bulb, &addr, &["on", "--hsv", "120,100,50"]).await;
    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["params"]["g"], 128);
    assert_eq!(request["params"]["dimming"], Value::Null);
}

#[tokio::test(flavor = "multi_thread")]
async fn the_white_emitters_compose_with_a_colour() {
    // `r`/`g`/`b` and `c`/`w` are halves of one colour mode, so this is one
    // request with five channels in it — the same request a single
    // `--rgbww R,G,B,C,W` flag would have produced.
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    let output = against(
        &bulb,
        &addr,
        &[
            "--json", "on", "--rgb", "255,80,0", "--cold", "12", "--warm", "34",
        ],
    )
    .await;
    assert_eq!(output.status.code(), Some(0));

    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["params"]["r"], 255);
    assert_eq!(request["params"]["g"], 80);
    assert_eq!(request["params"]["b"], 0);
    assert_eq!(request["params"]["c"], 12);
    assert_eq!(request["params"]["w"], 34);

    // Reported back under the bulb's own keys, so a request lines up against
    // the `c`/`w` a later `status` prints.
    let json = stdout_json(&output);
    assert_eq!(json["result"]["c"], 12);
    assert_eq!(json["result"]["w"], 34);

    // `--hsv` is a spelling of the same triple, so it composes too.
    against(&bulb, &addr, &["on", "--hsv", "0,100,100", "--warm", "64"]).await;
    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["params"]["r"], 255);
    assert_eq!(request["params"]["w"], 64);
    assert_eq!(request["params"]["c"], Value::Null);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_white_emitter_can_be_sent_on_its_own() {
    // Measured: this is a white-*only* request. The five channels are one
    // instruction and a write replaces all of them, so the colour goes dark
    // rather than staying underneath — which is also why the flag pair beats
    // a five-value tuple, since `--rgb 0,0,0 --warm 128` says the same thing
    // the long way round.
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    against(&bulb, &addr, &["on", "--rgb", "255,80,0"]).await;
    let output = against(&bulb, &addr, &["set", "--warm", "128"]).await;
    assert_eq!(output.status.code(), Some(0));

    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["method"], "setState");
    assert_eq!(request["params"]["w"], 128);
    assert_eq!(request["params"]["r"], Value::Null);

    let json = stdout_json(&against(&bulb, &addr, &["--json", "status"]).await);
    assert_eq!(json["result"]["w"], 128);
    assert_eq!(json["result"]["r"], 0, "the colour it replaced went dark");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_colour_with_nothing_lit_in_it_is_refused_before_it_is_sent() {
    // Measured on `ESP25_SHRGB_01` fw 1.38.0: an all-zero channel group is
    // discarded, and the bulb's own answer is no help. `set --warm 0` at
    // least fails, with a bare -32600 naming nothing; `on --warm 0` carries a
    // `state` as well, so the bulb answers `success` having ignored the
    // colour completely. Both are usage errors here instead.
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    for args in [
        vec!["on", "--rgb", "0,0,0"],
        vec!["set", "--rgb", "0,0,0"],
        vec!["on", "--warm", "0"],
        vec!["on", "--hsv", "120,100,0"],
        vec!["on", "--cold", "0", "--warm", "0"],
    ] {
        let output = against(&bulb, &addr, &args).await;
        assert_eq!(output.status.code(), Some(2), "{args:?}");
        let stderr = String::from_utf8(output.stderr).expect("utf-8");
        assert!(
            stderr.contains("asks for no light at all"),
            "{args:?}: {stderr}"
        );
        assert!(bulb.requests().is_empty(), "{args:?} reached the bulb");
    }

    // One lit channel is enough, and the zeroes beside it are fine.
    let output = against(&bulb, &addr, &["on", "--rgb", "0,0,0", "--warm", "128"]).await;
    assert_eq!(output.status.code(), Some(0));
    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["params"]["r"], 0);
    assert_eq!(request["params"]["w"], 128);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_white_emitter_conflicts_with_temp_and_scene_but_not_with_a_colour() {
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    for pair in [
        vec!["--cold", "12", "--kelvin", "2700"],
        vec!["--warm", "34", "--scene", "Party"],
    ] {
        let mut args = vec!["on"];
        args.extend(pair.iter().copied());
        let output = against(&bulb, &addr, &args).await;
        assert_eq!(output.status.code(), Some(2), "{pair:?}");
        assert!(bulb.requests().is_empty(), "{pair:?} reached the bulb");
    }

    // And the two whites are not exclusive with each other.
    let output = against(&bulb, &addr, &["on", "--cold", "12", "--warm", "34"]).await;
    assert_eq!(output.status.code(), Some(0));
}

#[tokio::test(flavor = "multi_thread")]
async fn status_shows_a_white_emitter_only_when_it_is_lit() {
    // A bulb in channel mode reports `c` and `w` on every read, both `0`
    // unless something set them, so the human line would otherwise carry two
    // columns that almost never say anything.
    let bulb = MockBulb::builder()
        .pilot(serde_json::json!({
            "state": true, "r": 255, "g": 80, "b": 0, "c": 0, "w": 64,
            "dimming": 100, "sceneId": 0
        }))
        .start()
        .await;
    let addr = bulb.addr().to_string();

    let line = String::from_utf8(against(&bulb, &addr, &["status"]).await.stdout).expect("utf-8");
    assert_eq!(line.trim(), "on  rgb 255,80,0  warm 64  100%");

    // `--json` renders whatever the bulb reported, lit or not.
    let json = stdout_json(&against(&bulb, &addr, &["--json", "status"]).await);
    assert_eq!(json["result"]["c"], 0);
    assert_eq!(json["result"]["w"], 64);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_scene_is_named_or_numbered_and_matched_leniently() {
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    for spelling in ["Deep dive", "deep-dive", "DEEPDIVE", "23"] {
        against(&bulb, &addr, &["on", "--scene", spelling]).await;
        let request = bulb.last_request().expect("a write arrived");
        assert_eq!(request["params"]["sceneId"], 23, "{spelling}");
    }

    // An id the bulb accepts and then does something else with is refused
    // before it is sent: 41 plays at a third of normal brightness.
    let output = against(&bulb, &addr, &["on", "--scene", "41"]).await;
    assert_eq!(
        output.status.code(),
        Some(2),
        "a bad value is a usage error"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn off_and_toggle_write_the_power_state() {
    let bulb = MockBulb::builder()
        .pilot(serde_json::json!({"state": true, "dimming": 100}))
        .start()
        .await;
    let addr = bulb.addr().to_string();

    against(&bulb, &addr, &["off"]).await;
    assert_eq!(
        bulb.last_request().expect("a write")["params"]["state"],
        Value::Bool(false)
    );

    // The bulb is now off, so a toggle turns it back on.
    let output = against(&bulb, &addr, &["toggle"]).await;
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(
        bulb.last_request().expect("a write")["params"]["state"],
        Value::Bool(true)
    );
    assert_eq!(
        String::from_utf8(output.stdout).expect("utf-8").trim(),
        "on"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn set_uses_set_state_and_needs_something_to_set() {
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    against(&bulb, &addr, &["set", "--kelvin", "2700"]).await;
    let request = bulb.last_request().expect("a write arrived");
    assert_eq!(request["method"], "setState");
    assert_eq!(request["params"]["temp"], 2700);

    // `on` is complete on its own and `set` is not, which no single clap group
    // can express — but it is still a usage error, and exits like one.
    let output = against(&bulb, &addr, &["set"]).await;
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(stderr.contains("needs something to set"), "{stderr}");
    assert!(stderr.contains("Usage:"), "{stderr}");
}

#[tokio::test(flavor = "multi_thread")]
async fn two_ways_of_saying_a_colour_is_a_usage_error() {
    // clap rejects it before anything is sent. `PilotBuilder` refuses the same
    // pair, but only once the command is running and with no flag to name.
    let bulb = MockBulb::start().await;
    let addr = bulb.addr().to_string();

    for pair in [
        vec!["--rgb", "255,0,0", "--kelvin", "2700"],
        vec!["--rgb", "255,0,0", "--hsv", "0,100,100"],
        vec!["--scene", "Party", "--kelvin", "2700"],
    ] {
        let mut args = vec!["on"];
        args.extend(pair.iter().copied());
        let output = against(&bulb, &addr, &args).await;
        assert_eq!(output.status.code(), Some(2), "{pair:?}");
        assert!(bulb.requests().is_empty(), "{pair:?} reached the bulb");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn asking_a_bulb_for_what_it_has_no_hardware_for_names_its_class() {
    // The bulb will not refuse this itself — measured: it answers `success`
    // for parameters it has nothing to apply to.
    let bulb = MockBulb::builder()
        .personality(Personality::dimmable_white())
        .start()
        .await;
    let addr = bulb.addr().to_string();

    let output = against(&bulb, &addr, &["on", "--rgb", "255,0,0"]).await;
    assert_eq!(output.status.code(), Some(1));
    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(stderr.contains("ESP06_SHDW9_01"), "{stderr}");
    assert!(stderr.contains("Dimmable White"), "{stderr}");
    assert!(stderr.contains("cannot show a colour"), "{stderr}");

    // And it was refused before any write went out.
    assert!(
        bulb.requests().iter().all(|raw| !raw.contains("setPilot")),
        "{:?}",
        bulb.requests()
    );

    // The white emitters are gated the same way and named separately, since
    // "cannot show a colour" is not what was asked for.
    let output = against(&bulb, &addr, &["on", "--warm", "64"]).await;
    assert_eq!(output.status.code(), Some(1));
    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(
        stderr.contains("cannot be given raw white channels"),
        "{stderr}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_target_may_be_a_mac_in_any_spelling() {
    let bulb = MockBulb::builder().mac("9877d5230f0a").start().await;

    for spelling in ["9877d5230f0a", "98:77:d5:23:0f:0a", "9877D5230F0A"] {
        let output = against(&bulb, spelling, &["--json", "status"]).await;
        assert_eq!(output.status.code(), Some(0), "{spelling}");
        // The envelope echoes the argument as it was typed.
        assert_eq!(stdout_json(&output)["target"], spelling);
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_mac_nothing_answers_to_is_not_found_rather_than_a_failure() {
    let bulb = MockBulb::builder().mac("9877d5230f0a").start().await;

    let output = against(&bulb, "aabbccddeeff", &["status"]).await;
    assert_eq!(output.status.code(), Some(3), "not found has its own code");
    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(stderr.contains("aabbccddeeff"), "{stderr}");
    assert!(stderr.contains("powered off"), "{stderr}");
}

#[test]
fn a_target_that_is_neither_an_address_nor_a_mac_is_a_usage_error() {
    let output = wizlight(&["status", "kitchen"]);
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(
        stderr.contains("neither an IP address nor a MAC"),
        "{stderr}"
    );
}

#[test]
fn a_command_needs_a_target_or_all_and_not_both() {
    assert_eq!(wizlight(&["status"]).status.code(), Some(2));
    assert_eq!(
        wizlight(&["status", "--all", "9877d5230f0a"]).status.code(),
        Some(2)
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn all_fans_out_and_one_failure_does_not_hide_the_others() {
    let working = MockBulb::builder()
        .mac("9877d5230f0a")
        .pilot(serde_json::json!({"state": true, "dimming": 100}))
        .start()
        .await;
    let deaf = MockBulb::builder().mac("9877d523a4da").start().await;
    let addrs = [working.addr().to_string(), deaf.addr().to_string()];

    let output = tokio::task::spawn_blocking(move || {
        wizlight(&[
            "--json",
            "--broadcast",
            &addrs[0],
            "--broadcast",
            &addrs[1],
            "--wait",
            SCAN,
            "--timeout",
            "0.05",
            "status",
            "--all",
        ])
    });
    // It answers the scan and then goes quiet, so it is found and then
    // unreachable — waited for rather than timed, because a cold debug binary
    // can take longer to start than any sleep worth writing.
    goes_quiet_once_scanned(&deaf).await;
    let output = output.await.expect("the command ran");

    assert_eq!(output.status.code(), Some(1), "a partial failure is not 0");
    let json = stdout_json(&output);
    assert_eq!(json["ok"], Value::Bool(false));
    assert_eq!(json["target"], Value::Null);

    let results = json["result"].as_array().expect("one entry per bulb");
    assert_eq!(results.len(), 2);
    // Sorted by MAC, so a fan-out can be diffed between runs.
    assert_eq!(results[0]["target"], "9877d5230f0a");
    assert_eq!(results[0]["ok"], Value::Bool(true));
    assert_eq!(results[0]["result"]["state"], Value::Bool(true));
    assert_eq!(results[1]["target"], "9877d523a4da");
    assert_eq!(results[1]["ok"], Value::Bool(false));
    assert!(
        results[1]["error"]
            .as_str()
            .expect("a message")
            .contains("no reply"),
        "{}",
        results[1]["error"]
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_fan_out_labels_every_line_with_the_bulb_it_came_from() {
    let one = MockBulb::builder()
        .mac("9877d5230f0a")
        .pilot(serde_json::json!({"state": true, "dimming": 100}))
        .start()
        .await;
    let two = MockBulb::builder()
        .mac("9877d523a4da")
        .pilot(serde_json::json!({"state": false, "dimming": 40}))
        .start()
        .await;
    let addrs = [one.addr().to_string(), two.addr().to_string()];

    let output = tokio::task::spawn_blocking(move || {
        wizlight(&[
            "--broadcast",
            &addrs[0],
            "--broadcast",
            &addrs[1],
            "--wait",
            SCAN,
            "status",
            "--all",
        ])
    })
    .await
    .expect("the command ran");

    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8(output.stdout).expect("utf-8");
    // One line per bulb, MAC first, so the output stays greppable.
    assert_eq!(
        stdout.trim(),
        "9877d5230f0a  on  100%\n9877d523a4da  off  40%"
    );
}

#[test]
fn no_subcommand_is_a_usage_error_not_a_success() {
    let output = wizlight(&[]);
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(stderr.contains("Usage:"), "{stderr}");
}

#[test]
fn an_unknown_subcommand_is_a_usage_error() {
    let output = wizlight(&["nosuchcommand"]);
    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn help_succeeds_and_is_printed_to_stdout() {
    for flag in ["--help", "-h"] {
        let output = wizlight(&[flag]);
        assert_eq!(output.status.code(), Some(0), "{flag}");
        let stdout = String::from_utf8(output.stdout).expect("utf-8");
        assert!(stdout.contains("Usage:"), "{flag}: {stdout}");
    }
}

#[test]
fn help_leaks_no_rustdoc_at_either_length() {
    // clap promotes the `Cli` doc comment to the long description unless
    // `long_about = None` says otherwise, which had `--help` opening with
    // "Global CLI flags shared across all commands." while `-h` did not.
    //
    // This asserted `long == short` while every flag's help was one line. It
    // no longer is — `--broadcast` needs a second paragraph to explain the
    // multi-homed case, and telling only `--help` about it is exactly what the
    // two lengths are for. So the invariant is what it always meant: the same
    // opening, and no internal notes in either.
    let long = String::from_utf8(wizlight(&["--help"]).stdout).expect("utf-8");
    let short = String::from_utf8(wizlight(&["-h"]).stdout).expect("utf-8");

    for help in [&long, &short] {
        assert!(help.starts_with("Control Philips WiZ bulbs"), "{help}");
        assert!(!help.contains("Global CLI flags"), "{help}");
        // Every visible subcommand is listed at both lengths.
        for command in [
            "discover", "status", "on", "off", "info", "set", "toggle", "pulse", "scenes", "watch",
            "bench",
        ] {
            assert!(help.contains(command), "{command} missing from {help}");
        }
        assert!(
            !help.contains("completions"),
            "hidden command leaked: {help}"
        );
    }

    // The long form is the one that elaborates, and only it.
    assert!(long.contains("multi-homed"), "{long}");
    assert!(long.contains("Start with:"), "{long}");
    assert!(
        long.lines().count() <= 80,
        "help is taller than a terminal: {long}"
    );
    let commands = long
        .split_once("Commands:")
        .and_then(|(_, rest)| rest.split_once("Options:"))
        .map(|(commands, _)| commands)
        .expect("commands section");
    for pair in [
        ("discover", "status"),
        ("status", "on"),
        ("on", "off"),
        ("off", "info"),
    ] {
        assert!(
            commands.find(&format!("  {}", pair.0)) < commands.find(&format!("  {}", pair.1)),
            "wrong command order: {commands}"
        );
    }
    assert!(short.len() < long.len(), "-h should be the summary");
}

#[test]
fn on_set_and_bench_long_help_include_working_examples() {
    for command in ["on", "set", "pulse", "bench"] {
        let output = wizlight(&[command, "--help"]);
        assert_eq!(output.status.code(), Some(0), "{command}");
        let help = String::from_utf8(output.stdout).expect("utf-8");
        assert!(help.contains("Examples:"), "{command}: {help}");
        assert!(
            help.contains(&format!("wizlight {command}")),
            "{command}: {help}"
        );
    }
}

#[test]
fn every_command_and_flag_has_help_text() {
    fn check(command: &clap::Command) {
        assert!(
            command.get_about().is_some(),
            "{} has no about",
            command.get_name()
        );
        for argument in command.get_arguments() {
            assert!(
                argument.get_help().is_some(),
                "{} {} has no help",
                command.get_name(),
                argument.get_id()
            );
        }
        for subcommand in command.get_subcommands() {
            check(subcommand);
        }
    }

    check(&Cli::command());
}

#[test]
fn completions_generate_for_every_supported_shell_with_scene_hints() {
    for scene in Scene::all() {
        let hint = scene.name().to_ascii_lowercase().replace(' ', "-");
        Cli::try_parse_from(["wizlight", "on", "192.168.0.5", "--scene", &hint])
            .unwrap_or_else(|error| panic!("completion `{hint}` does not parse: {error}"));
    }

    for shell in ["bash", "zsh", "fish", "powershell", "elvish"] {
        let output = wizlight(&["completions", shell]);
        assert_eq!(output.status.code(), Some(0), "{shell}");
        assert!(output.stderr.is_empty(), "{shell}: {:?}", output.stderr);
        let script = String::from_utf8(output.stdout).expect("utf-8");
        assert!(script.contains("wizlight"), "{shell}: {script}");
        if matches!(shell, "bash" | "zsh" | "fish") {
            assert!(
                script.contains("deep-dive"),
                "scene hints missing from {shell}"
            );
        }
    }
}

#[test]
fn version_reports_the_crate_version() {
    // Asserted against `CARGO_PKG_VERSION` rather than a literal, so the two
    // cannot drift apart on the next release.
    let expected = format!("wizlight {}", env!("CARGO_PKG_VERSION"));
    for flag in ["--version", "-V"] {
        let output = wizlight(&[flag]);
        assert_eq!(output.status.code(), Some(0), "{flag}");
        let stdout = String::from_utf8(output.stdout).expect("utf-8");
        assert_eq!(stdout.trim(), expected, "{flag}");
    }
}

#[test]
fn version_does_not_need_a_subcommand() {
    // `arg_required_else_help` must not turn `--version` into a usage error.
    assert_eq!(wizlight(&["--version"]).status.code(), Some(0));
}

#[test]
fn the_command_tree_is_internally_consistent() {
    // clap's own validation: duplicate short flags, conflicting names, bad arg
    // groups. Cheap insurance now that `-v` and `-V` sit next to each other.
    Cli::command().debug_assert();
}

#[test]
fn verbosity_controls_the_log_output() {
    let quiet = String::from_utf8(scan(&["discover"]).stderr).expect("utf-8");
    assert!(
        !quiet.contains("parsed invocation"),
        "logs at the default level: {quiet}"
    );

    let loud =
        String::from_utf8(scan(&["-vv", "--timeout", "9", "discover"]).stderr).expect("utf-8");
    assert!(loud.contains("parsed invocation"), "{loud}");
    assert!(loud.contains("timeout=9s"), "{loud}");
}

#[test]
fn rust_log_overrides_the_verbosity_flag() {
    let output = scan_with_env(&["discover"], "RUST_LOG", "debug");

    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(stderr.contains("parsed invocation"), "{stderr}");
}

#[test]
fn logging_never_lands_on_stdout() {
    // Log output on stdout would corrupt `--json` for anything parsing it.
    let stdout = String::from_utf8(scan(&["-vvv", "--json", "discover"]).stdout).expect("utf-8");
    let value: Value = serde_json::from_str(stdout.trim()).expect("stdout is only the payload");
    assert_eq!(value["command"], "discover");
}

#[test]
fn output_is_not_coloured_when_it_is_not_going_to_a_terminal() {
    // The test harness captures through a pipe, so nothing here is a TTY.
    // `tracing-subscriber` colours by default and would otherwise write escape
    // sequences into whatever the output was redirected to.
    let stderr = String::from_utf8(scan(&["-vv", "discover"]).stderr).expect("utf-8");
    assert!(stderr.contains("parsed invocation"), "{stderr}");
    assert!(
        !stderr.contains('\x1b'),
        "ANSI escape in a pipe: {stderr:?}"
    );
}

#[test]
fn no_color_suppresses_colour() {
    let output = scan_with_env(&["-vv", "discover"], "NO_COLOR", "1");
    let stderr = String::from_utf8(output.stderr).expect("utf-8");
    assert!(!stderr.contains('\x1b'), "{stderr:?}");
}