monospace-cli 0.1.1

Render ASCII and Unicode box-drawing diagrams from JSON on the command line
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
//! End-to-end checks that run the built binary as a subprocess.

use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Output};

/// Writes `contents` to a fresh file under the system temp directory, named after the calling
/// test so parallel tests never collide.
fn write_description(name: &str, contents: &str) -> PathBuf {
    let path = std::env::temp_dir().join(format!(
        "monospace-cli-test-{name}-{}.json",
        std::process::id()
    ));
    std::fs::File::create(&path)
        .and_then(|mut file| file.write_all(contents.as_bytes()))
        .expect("temp description file should be writable");
    path
}

/// Runs the built binary with `args` and returns its captured output.
fn run(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_monospace-cli"))
        .args(args)
        .output()
        .expect("the monospace-cli binary should be runnable")
}

/// The shipped demonstration's path, relative to the workspace root, so a test can pass it
/// explicitly the same way a user would.
const DEMO_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/assets/demo.json");

/// The first of the eight captioned pictures the no-argument run prints, with its caption line and
/// the blank line after it stripped. Pins no caption's wording.
///
/// The seven pictures below it are appended rather than inserted, so the coordinates `char_at`
/// reads in the tests further down still name the same cells of the first picture — which is why
/// this function needs no change of its own when a picture is added.
///
/// Only the demonstration is captioned. A file's run is one picture and nothing else, so a test
/// that passes a path compares the whole of stdout.
fn first_demonstrated_picture(output: &str) -> String {
    let (first_block, _rest) = output
        .split_once("\n\n")
        .expect("two captioned pictures separated by a blank line");
    let (_caption, picture) = first_block
        .split_once('\n')
        .expect("a caption line precedes the picture");
    format!("{picture}\n")
}

/// An identity written as a string prints nothing to stdout, names the field on stderr, and fails.
///
/// **The refusal the whole wire change turns on**, and the wording is asserted rather than
/// described: `serde` alone reports `invalid type: string "#1", expected a nonzero u16`, which names
/// neither `id` nor what the file did wrong beyond its own words, so the reader puts the field in
/// front of it. `"#1"` is the spelling every description in this repository used until the change,
/// so it is the one a caller upgrading this format will have in hand.
///
/// **A `"shape"` and a `0` beside it**, in the same test rather than a second one: the three fields
/// share a deserializer and differ only in the name they print, so a reader that printed `id` for
/// all of them would pass a test on `id` alone. `two_entries_carrying_one_identity_are_both_read_and_both_drawn`
/// is the accepted cost beside this one: two entries may still carry one ordinal, and both are read.
#[test]
fn an_identity_written_as_a_string_is_refused_by_name_on_stderr_and_fails() {
    let a_string_id = write_description(
        "string-id",
        r##"{
            "next_id": 2,
            "shapes": [ { "kind": "box", "id": "#1", "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"##,
    );
    let a_string_shape = write_description(
        "string-shape",
        r##"{
            "next_id": 3,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light" },
                { "kind": "connector", "id": 2,
                  "from": { "at": { "kind": "reference", "shape": "#1", "anchor": "right" },
                            "terminal": { "kind": "arm" } },
                  "to": { "at": { "kind": "point", "x": 8, "y": 1 }, "leaving": "left",
                          "terminal": { "kind": "arm" } },
                  "stroke": "light" } ]
        }"##,
    );

    for (path, named) in [(a_string_id, "id"), (a_string_shape, "shape")] {
        let output = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

        assert!(
            !output.status.success(),
            "a name is not an ordinal and must fail"
        );
        assert!(output.stdout.is_empty(), "printed to stdout");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains(&format!("`{named}` is an ordinal")),
            "expected `{named}` to be named on stderr, got: {stderr}"
        );
        assert!(
            stderr.contains("\"#1\""),
            "expected the message to quote what the file said, got: {stderr}"
        );
    }
}

/// A `next_id` of zero prints nothing to stdout, names the field on stderr, and fails.
///
/// **Zero is the one value the format cannot express**, so the reader turns it away where the file
/// is rather than letting the counter stand at an identity no shape can carry. It is the same
/// refusal as the one beside it, in the one field that could otherwise have issued `"#0"` — which
/// the old reader held and handed out.
#[test]
fn a_next_id_of_zero_is_refused_by_name_on_stderr_and_fails() {
    let path = write_description(
        "zero-next-id",
        r#"{
            "next_id": 0,
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"#,
    );

    let output = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

    assert!(
        !output.status.success(),
        "zero is not an identity and must fail"
    );
    assert!(output.stdout.is_empty(), "printed to stdout");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("`next_id` is an ordinal"),
        "expected `next_id` to be named on stderr, got: {stderr}"
    );
}

/// Two entries carrying the same `id` are **both** read. Both shapes are drawn, the run exits
/// successfully, and nothing is written to stderr.
///
/// **Pinned as an accepted cost rather than as a bug**, so a later slice that decides to report a
/// repeated identity has to say so rather than discover it. The diagram-level half — both held,
/// `get` returning the first — is `a_diagram_issues_the_counter_and_a_shape_added_under_a_callers_identity_does_not_move_it`
/// in `monospace-diagram`; this is the same cost arriving through a wire, where a reader might
/// plausibly have checked it and did not. An identity being a number did not change any of that:
/// `1` is no more unique than `"#1"` was, and nothing in the format checks it.
#[test]
fn two_entries_carrying_one_identity_are_both_read_and_both_drawn() {
    let path = write_description(
        "repeated-id",
        r#"{
            "next_id": 2,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light" },
                { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light" }
            ]
        }"#,
    );

    let output = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

    assert!(output.status.success(), "exited with {}", output.status);
    assert!(output.stderr.is_empty(), "wrote to stderr");
    // Both boxes draw: the first entry's border and the second one's, overlapping. A reader that
    // refused a repeated identity would have drawn one of them, and one that read the first and
    // dropped the second would draw a different picture than two of them do.
    let picture = String::from_utf8_lossy(&output.stdout);
    assert!(
        picture.contains("┌──┐") && picture.contains("└──┘") && picture.lines().count() >= 4,
        "both entries must draw, and a 6x4 window is four rows:\n{picture}"
    );
}

/// With no arguments, the binary prints the shipped demonstration and exits successfully, with
/// nothing on stderr.
#[test]
fn no_arguments_prints_the_demonstration_and_exits_successfully() {
    let output = run(&[]);

    assert!(output.status.success(), "exited with {}", output.status);
    assert!(!output.stdout.is_empty(), "printed nothing");
    assert!(output.stderr.is_empty(), "wrote to stderr");
}

/// Running with no arguments from a different working directory prints the same diagram, since
/// the demonstration is embedded in the binary rather than read from a path relative to the
/// working directory.
#[test]
fn running_from_a_different_working_directory_prints_the_same_diagram() {
    let from_temp_dir = Command::new(env!("CARGO_BIN_EXE_monospace-cli"))
        .current_dir(std::env::temp_dir())
        .output()
        .expect("the monospace-cli binary should be runnable from the temp directory");
    let from_manifest_dir = Command::new(env!("CARGO_BIN_EXE_monospace-cli"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .output()
        .expect("the monospace-cli binary should be runnable from its manifest directory");

    assert_eq!(from_temp_dir.stdout, from_manifest_dir.stdout);
}

/// The shipped demonstration's own path, passed explicitly, prints the picture the no-argument
/// run prints first — and stops there.
///
/// Byte-identical output from both runs was asked for once. It no longer holds, deliberately: the
/// caption and the moved shape belong to the demonstration, not to a description someone hands
/// the binary. What survives is that both parse the same text and draw it the same way.
#[test]
fn the_demo_path_passed_explicitly_prints_the_demonstrations_first_picture() {
    let no_arguments = run(&[]);
    let explicit_path = run(&[DEMO_PATH]);

    assert!(no_arguments.status.success());
    assert!(explicit_path.status.success());
    assert_eq!(
        String::from_utf8_lossy(&explicit_path.stdout),
        first_demonstrated_picture(&String::from_utf8_lossy(&no_arguments.stdout))
    );
}

/// An explicit path to a hand-written single-box file prints exactly that box.
///
/// **The size is passed on the command line**, because a path given no `--size` is drawn into this
/// binary's own window rather than the one its file names — which is the whole of what the default
/// is for, and why a test that wants a four-by-three picture has to say four by three.
#[test]
fn an_explicit_path_prints_the_hand_written_box() {
    let path = write_description(
        "one-box",
        r#"{
            "next_id": 2,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" }
            ]
        }"#,
    );

    let output = run(&[
        "--size",
        "4x3",
        path.to_str().expect("temp path should be valid UTF-8"),
    ]);

    assert!(output.status.success(), "exited with {}", output.status);
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        "┌──┐\n│░░│\n└──┘\n"
    );
    assert!(output.stderr.is_empty(), "wrote to stderr");
}

/// Rule 8 — a path and no `--size` draws into the demonstration's window.
///
/// **The file says `4x3` and the picture is fifty by seventeen.** That is the whole of the claim:
/// the default is a value this binary chose, and the description it was handed has nothing to say
/// about it. The picture is the box in the top-left corner of a window that reaches well past it,
/// which is what makes the default visible rather than asserted.
#[test]
fn a_path_and_no_size_draws_into_the_demonstrations_window() {
    let path = write_description(
        "default-window",
        r#"{
            "next_id": 2,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" }
            ]
        }"#,
    );

    let output = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

    assert!(output.status.success(), "exited with {}", output.status);
    let picture = String::from_utf8_lossy(&output.stdout);
    assert_eq!(
        picture.lines().count(),
        17,
        "the demonstration's window is seventeen rows tall: {picture}"
    );
    assert_eq!(
        picture.lines().next().expect("a first row").chars().count(),
        50,
        "and fifty columns wide: {picture}"
    );
    assert!(
        picture.starts_with("┌──┐"),
        "the box stands in the window's own top-left corner: {picture}"
    );
}

/// Rule 9 — the bare run draws into the demonstration's window, and nothing on the command line
/// changes that.
///
/// **The flags are read and the demonstration is drawn at its own size anyway**, because the two
/// callers are not the same caller: `cargo xtask render` always passes a size, so the default is
/// never what a generated picture uses, and the only person a bare run serves is one watching it.
/// A flag given to a run with no path is therefore not a window — it is a person typing.
#[test]
fn the_bare_run_draws_into_the_demonstrations_window() {
    let bare = run(&[]);
    let asked = run(&["--size", "6x4", "--origin", "1,1"]);

    for output in [&bare, &asked] {
        assert!(output.status.success(), "exited with {}", output.status);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let first = first_demonstrated_picture(&stdout);
        assert_eq!(
            first.lines().count(),
            17,
            "the demonstration is seventeen rows tall whatever the command line says"
        );
        assert_eq!(
            first.lines().next().expect("a first row").chars().count(),
            50,
            "and fifty columns wide"
        );
    }
}

/// A size and an origin on the command line decide the window a path is drawn into, and the
/// window the file itself names is not what the picture is drawn at.
///
/// **The file says `6x4` and the command line says `4x3`, and the picture is four by three.** That
/// is the whole of the claim: a caller that names a window names it, and the description it drew
/// from has nothing to say about it.
///
/// The second half is the origin, and it is the window's corner rather than a move of the figure:
/// the same box at `(0, 0)` drawn into a window starting at `(1, 1)` is **outside** it, and what
/// survives is the part of the box the window holds. Measured rather than argued — the first draft
/// of this test expected the box to have traveled one cell right and down, and the binary drew
/// the corner of a box that had not moved at all.
///
/// The file's own window is still read and still used when no flag is given — which is what every
/// generated picture in this repository is drawn at until the markers carry their own — so the
/// assertion that matters is the one where the two disagree.
#[test]
fn a_size_and_an_origin_on_the_command_line_decide_the_window_a_path_is_drawn_into() {
    let path = write_description(
        "with-flags",
        r#"{
            "next_id": 2,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" }
            ]
        }"#,
    );
    let path = path.to_str().expect("temp path should be valid UTF-8");

    let asked = run(&["--size", "4x3", path]);
    assert!(asked.status.success(), "exited with {}", asked.status);
    assert_eq!(
        String::from_utf8_lossy(&asked.stdout),
        "┌──┐\n│░░│\n└──┘\n",
        "the command line's size is the window, not the file's own"
    );

    let moved = run(&["--size", "4x3", "--origin", "1,1", path]);
    assert!(moved.status.success(), "exited with {}", moved.status);
    assert_eq!(
        String::from_utf8_lossy(&moved.stdout),
        "░░│ \n──┘ \n    \n",
        "the origin is the window's corner, so the box at (0, 0) is outside it and only the part \
         the window holds is drawn"
    );
}

/// Rule 3 — the window comes from the flags and nowhere else.
///
/// **The file says `13x9` and the command line says `6x4`, and the picture is six by four.** That
/// is the whole of the claim, and it is the one a later change is most likely to break by making the
/// marker's size optional for symmetry with the flag's: a window that could be inherited from a
/// file is a window with two sources, and the rule for which wins is the decision this change
/// removes.
///
/// The file's own window is still read and still there — the format carries it until the increment
/// that takes it out — so the assertion that matters is the one where the two disagree.
#[test]
fn the_window_comes_from_the_flags_and_nowhere_else() {
    let path = write_description(
        "two-windows",
        r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 13, "height": 9 } },
            "next_id": 2,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" }
            ]
        }"#,
    );
    let path = path.to_str().expect("temp path should be valid UTF-8");

    let asked = run(&["--size", "6x4", path]);
    assert!(asked.status.success(), "exited with {}", asked.status);
    assert_eq!(
        String::from_utf8_lossy(&asked.stdout),
        "┌──┐  \n│░░│  \n└──┘  \n      \n",
        "the command line's window is the one the picture is drawn at"
    );

    let moved = run(&["--size", "6x4", "--origin", "1,1", path]);
    assert!(moved.status.success(), "exited with {}", moved.status);
    assert_eq!(
        String::from_utf8_lossy(&moved.stdout),
        "░░│   \n──┘   \n      \n      \n",
        "the origin is the window's corner, so the box at (0, 0) is outside it and only the part \
         the window holds is drawn"
    );
}

/// A flag this binary does not read prints nothing to stdout, names itself on stderr, and fails.
///
/// **The refusal is the boundary, and it is the same shape the parser's own unit tests pin.** A
/// binary that read `--width 20` as a path would draw a picture of a file that does not exist and
/// report the missing file, which is a refusal about the wrong thing.
#[test]
fn a_flag_this_binary_does_not_read_names_it_on_stderr_and_fails() {
    let output = run(&["--width", "20", "x.json"]);

    assert!(!output.status.success());
    assert!(output.stdout.is_empty(), "printed to stdout");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("`--width` is not an option"), "{stderr}");
    assert!(stderr.contains("usage:"), "{stderr}");
}

/// A box, a line and a connector at stated positions print all three composed.
#[test]
fn a_file_with_a_box_a_line_and_a_connector_prints_all_three_composed() {
    let path = write_description(
        "three-shapes",
        r#"{
            "next_id": 4,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" },
                { "kind": "line", "id": 2, "at": { "x": 0, "y": 4 }, "len": 4, "orientation": "horizontal",
                  "stroke": "light" },
                { "kind": "connector", "id": 3,
                  "from": { "at": { "kind": "point", "x": 5, "y": 0 }, "leaving": "right",
                            "terminal": { "kind": "glyph", "glyph": ">" } },
                  "to": { "at": { "kind": "point", "x": 9, "y": 2 }, "leaving": "down",
                          "terminal": { "kind": "glyph", "glyph": "v" } },
                  "stroke": "light" }
            ]
        }"#,
    );

    let output = run(&[
        "--size",
        "10x5",
        path.to_str().expect("temp path should be valid UTF-8"),
    ]);

    assert!(output.status.success(), "exited with {}", output.status);
    // Corrected on feature 099: this connector's route was a genuine tie under _The route of a
    // connector_ (fewest bends, same closeness), which feature 039 broke arbitrarily by comparing
    // waypoint coordinates. The model's own tie-break prefers the route that turns at the middle
    // of the route rectangle (x = 7), which is what this picture now pins.
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        "┌──┐ >─┐  \n│░░│   │  \n└──┘   │ v\n       └─┘\n────      \n"
    );
    assert!(output.stderr.is_empty(), "wrote to stderr");
}

/// A box at the origin, four by three, so its right side centre is `{3, 1}`. The figure the three
/// wire cases below hang an endpoint from.
const A_BOX: &str = r#"{ "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
        "stroke": "light" }"#;

/// Runs a one-connector description over `at` and returns the whole of stdout, which for a path is
/// one picture and nothing else — nothing else because a picture bound for a Markdown fence cannot
/// arrive wrapped in prose, and `cargo xtask render` embeds this output in one.
///
/// `label` names the temp file, so it is the caller's short handle and not the JSON: a description
/// is full of slashes and quotes and makes for no filename at all.
fn picture_of_a_connector_hanging_from(label: &str, at: &str) -> String {
    let leaving = if at.contains(r#""kind": "point""#) {
        r#""leaving": "right","#
    } else {
        ""
    };
    let path = write_description(
        label,
        &format!(
            r#"{{
            "next_id": 3,
            "shapes": [
                {A_BOX},
                {{ "kind": "connector", "id": 2,
                  "from": {{ "at": {at}, {leaving}
                             "terminal": {{ "kind": "glyph", "glyph": ">" }} }},
                  "to": {{ "at": {{ "kind": "point", "x": 8, "y": 1 }}, "leaving": "left",
                           "terminal": {{ "kind": "arm" }} }},
                  "stroke": "light" }}
            ]
        }}"#
        ),
    );

    let output = run(&[
        "--size",
        "9x3",
        path.to_str().expect("temp path should be valid UTF-8"),
    ]);
    assert!(output.status.success(), "exited with {}", output.status);
    assert!(output.stderr.is_empty(), "wrote to stderr");
    String::from_utf8_lossy(&output.stdout).into_owned()
}

/// A file may name a side of another figure and an offset, and the picture it draws is the
/// picture the resolved point draws.
#[test]
fn a_file_naming_a_reference_draws_what_the_point_it_resolves_to_draws() {
    let named = picture_of_a_connector_hanging_from(
        "with-offset",
        r#"{ "kind": "reference", "shape": 1, "anchor": "right", "offset": { "dx": 2, "dy": 0 } }"#,
    );
    let spelled = picture_of_a_connector_hanging_from(
        "with-offset-point",
        r#"{ "kind": "point", "x": 6, "y": 1 }"#,
    );

    assert_eq!(named, spelled);
    assert!(
        !named.trim().is_empty(),
        "a reference to a box the file holds must draw the connector"
    );
}

/// A reference carrying **no** `offset` at all draws exactly what a description naming the point
/// it resolves to draws, byte for byte.
///
/// The case `{"kind": "reference", "shape": 1, "anchor": "right"}` exists for: `offset` is
/// optional and absent is zero, so a reference on the side itself is three fields rather than five,
/// and it has to draw the same thing a file spelling `{4, 1}` outright does (standing one cell
/// outward by default for a non-arm terminal).
#[test]
fn a_file_naming_a_reference_with_no_offset_draws_the_point_it_stands_on() {
    let named = picture_of_a_connector_hanging_from(
        "no-offset",
        r#"{ "kind": "reference", "shape": 1, "anchor": "right" }"#,
    );
    let spelled = picture_of_a_connector_hanging_from(
        "no-offset-point",
        r#"{ "kind": "point", "x": 4, "y": 1 }"#,
    );

    assert_eq!(named, spelled);
}

/// A file may name the gap from the side in the side's own words, and it draws the picture the
/// offset it stands for draws.
///
/// **Three routes to one cell and a fourth that is not it.** `out: 1` on a `right` side, the same
/// gap as `offset: {dx: 1, dy: 0}`, and the point `{5, 1}` spelled outright are three spellings of
/// one cell, so the comparison is not two files agreeing with each other because both were read
/// wrong. The fourth is the reference with **no gap at all**, which stands at the default gap and
/// draws something else — so the three agreeing is the field being read rather than ignored.
#[test]
fn a_file_naming_an_out_draws_the_point_the_offset_it_stands_for_draws() {
    let named = picture_of_a_connector_hanging_from(
        "with-out",
        r#"{ "kind": "reference", "shape": 1, "anchor": "right", "out": 1 }"#,
    );
    let as_an_offset = picture_of_a_connector_hanging_from(
        "with-the-offset-an-out-stands-for",
        r#"{ "kind": "reference", "shape": 1, "anchor": "right", "offset": { "dx": 1, "dy": 0 } }"#,
    );
    let outright = picture_of_a_connector_hanging_from(
        "with-the-point-an-out-reaches",
        r#"{ "kind": "point", "x": 5, "y": 1 }"#,
    );
    let at_default_gap = picture_of_a_connector_hanging_from(
        "with-no-gap",
        r#"{ "kind": "reference", "shape": 1, "anchor": "right" }"#,
    );

    assert_eq!(
        named, as_an_offset,
        "an `out` and the offset it stands for differ"
    );
    assert_eq!(named, outright, "an `out` and the point it reaches differ");
    assert_ne!(
        named, at_default_gap,
        "an `out` of one drew what a reference with no gap draws, so the field is being dropped"
    );
}

/// A file naming a shape it does not hold draws **a box and no connector at all**, and the run
/// succeeds.
///
/// This is a hole that was silent below the wire arriving through it — a position that cannot be
/// resolved is not drawn and nothing reports that it was skipped — and the offset is what makes it
/// a test rather than a comment: a large offset is the case where an implementation might clamp,
/// fall back or report, and none of the three happens. Nothing on stderr, a successful exit, and
/// the picture is the box alone.
#[test]
fn a_file_naming_a_shape_it_does_not_hold_draws_the_box_and_no_connector_and_succeeds() {
    let drawn = picture_of_a_connector_hanging_from(
        "foreign-shape",
        r#"{ "kind": "reference", "shape": 7, "anchor": "right", "offset": { "dx": 2, "dy": 0 } }"#,
    );
    let box_alone = {
        let path = write_description(
            "just-the-box",
            &format!(
                r#"{{
                "next_id": 2,
                "shapes": [ {A_BOX} ]
            }}"#
            ),
        );
        let output = run(&[
            "--size",
            "9x3",
            path.to_str().expect("temp path should be valid UTF-8"),
        ]);
        assert!(output.status.success(), "exited with {}", output.status);
        assert!(output.stderr.is_empty(), "wrote to stderr");
        String::from_utf8_lossy(&output.stdout).into_owned()
    };

    assert_eq!(
        drawn, box_alone,
        "a reference to nothing must draw the box and nothing else"
    );
}

/// The two overlapping boxes the reordering test below writes, as the `monospace_core` shapes
/// they describe, so the expected picture in each order comes from stamping them directly rather
/// than from a literal picture.
/// they describe, so the expected picture in each order comes from stamping them directly rather
/// than from a literal picture.
fn overlap_boxes() -> (monospace_core::BoxShape, monospace_core::BoxShape) {
    use monospace_core::{BoxShape, Glyph, Pos, Size, Stroke};

    (
        BoxShape {
            at: Pos { x: 0, y: 0 },
            size: Size {
                width: 4,
                height: 3,
            },
            stroke: Stroke::from("light"),
            fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
        },
        BoxShape {
            at: Pos { x: 2, y: 1 },
            size: Size {
                width: 4,
                height: 3,
            },
            stroke: Stroke::from("light"),
            fill: Some(Glyph::new("▓").expect("\"▓\" is one glyph")),
        },
    )
}

/// Renders `back` then `front`, back to front, each stamped with `StampMode::Above` — the picture
/// a description's `shapes` array in that order produces, per _The two orders are equivalent_.
fn render_back_to_front_with_above(
    back: &monospace_core::BoxShape,
    front: &monospace_core::BoxShape,
) -> String {
    use monospace_core::{
        Buffer, FigureLayer, GlyphCatalog, Pos, Shape, Size, StampMode, Window, render,
    };

    let origin = Pos { x: 0, y: 0 };
    let size = Size {
        width: 6,
        height: 4,
    };
    let mut buffer = Buffer::new(Window { origin, size });
    back.draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));
    front.draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));
    render(&buffer, &GlyphCatalog::light(), buffer.window())
}

/// The same file with its shapes reordered changes which one is drawn on top where they overlap
/// — the last entry in `shapes` is front-most and decides the shared cells, matching the two core
/// shapes stamped back to front with `Above`.
#[test]
fn reordering_shapes_changes_which_one_is_drawn_on_top() {
    let first = write_description(
        "overlap-a-then-b",
        r#"{
            "next_id": 3,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" },
                { "kind": "box", "id": 2, "at": { "x": 2, "y": 1 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "▓" }
            ]
        }"#,
    );
    let second = write_description(
        "overlap-b-then-a",
        r#"{
            "next_id": 3,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "▓" },
                { "kind": "box", "id": 2, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" }
            ]
        }"#,
    );

    let first_output = run(&[
        "--size",
        "6x4",
        first.to_str().expect("temp path should be valid UTF-8"),
    ]);
    let second_output = run(&[
        "--size",
        "6x4",
        second.to_str().expect("temp path should be valid UTF-8"),
    ]);

    let (a, b) = overlap_boxes();
    assert_eq!(
        String::from_utf8_lossy(&first_output.stdout),
        render_back_to_front_with_above(&a, &b)
    );
    assert_eq!(
        String::from_utf8_lossy(&second_output.stdout),
        render_back_to_front_with_above(&b, &a)
    );
    assert_ne!(first_output.stdout, second_output.stdout);
}

/// Running the same file twice produces identical output.
#[test]
fn running_the_same_file_twice_produces_identical_output() {
    let path = write_description(
        "determinism",
        r#"{
            "next_id": 2,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "░" }
            ]
        }"#,
    );

    let first = run(&[path.to_str().expect("temp path should be valid UTF-8")]);
    let second = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

    assert_eq!(first.stdout, second.stdout);
}

/// A path that does not exist prints nothing to stdout, names the path on stderr, and fails.
#[test]
fn a_missing_path_names_it_on_stderr_and_fails() {
    let path = std::env::temp_dir().join(format!(
        "monospace-cli-test-does-not-exist-{}.json",
        std::process::id()
    ));
    let _ = std::fs::remove_file(&path);

    let output = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

    assert!(!output.status.success());
    assert!(output.stdout.is_empty(), "printed to stdout");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains(path.to_str().expect("temp path should be valid UTF-8")),
        "{stderr}"
    );
}

/// Malformed JSON prints nothing to stdout, locates the problem on stderr, and fails.
#[test]
fn malformed_json_locates_the_problem_on_stderr_and_fails() {
    let path = write_description("broken", r#"{ "canvas": "#);

    let output = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

    assert!(!output.status.success());
    assert!(output.stdout.is_empty(), "printed to stdout");
    assert!(!output.stderr.is_empty(), "wrote nothing to stderr");
}

/// An unrecognized shape kind prints nothing to stdout, names the kind on stderr, and fails.
#[test]
fn an_unrecognized_kind_names_it_on_stderr_and_fails() {
    let path = write_description(
        "bad-kind",
        r#"{
            "next_id": 1,
            "shapes": [ { "kind": "triangle" } ]
        }"#,
    );

    let output = run(&[path.to_str().expect("temp path should be valid UTF-8")]);

    assert!(!output.status.success());
    assert!(output.stdout.is_empty(), "printed to stdout");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("triangle"), "{stderr}");
}

/// Edge case: more than one command-line argument prints a usage message and fails, instead of
/// being matched on as a path.
#[test]
fn more_than_one_argument_prints_usage_and_fails() {
    let output = run(&["one.json", "two.json"]);

    assert!(!output.status.success());
    assert!(output.stdout.is_empty(), "printed to stdout");
    assert!(!output.stderr.is_empty(), "wrote nothing to stderr");
}

/// Returns the character at `(x, y)` in the first picture of `output`, treating each line as a
/// row and each `char` as a column, the same coordinates the demonstration's own window is drawn
/// at. `+ 1` skips the caption line the demonstration puts above that picture.
fn char_at(output: &str, x: usize, y: usize) -> char {
    output
        .lines()
        .nth(y + 1)
        .and_then(|line| line.chars().nth(x))
        .unwrap_or_else(|| panic!("no character at ({x}, {y}) in {output:?}"))
}

/// With no arguments, the demonstration contains both a box-drawing character (from Light) and
/// one of `+`, `-`, `|` (from ASCII).
#[test]
fn the_demonstration_contains_both_light_and_ascii_characters() {
    let output = run(&[]);
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains(['┌', '┐', '└', '┘', '│', '─', '┬', '┴', '├', '┤', '┼']),
        "no box-drawing character in {stdout:?}"
    );
    assert!(
        stdout.contains(['+', '-', '|']),
        "no ASCII box character in {stdout:?}"
    );
}

/// At the two crossings between an ASCII figure and a Light figure added to the demo, the shared
/// cell reads from whichever figure is in front. `(28, 2)` is where
/// an ASCII box, added after a Light box already on the canvas and so front-most, shares a border
/// cell with it; `(36, 2)` is where a Light box, added after an ASCII box and so front-most,
/// shares a border cell with it.
#[test]
fn the_two_crossings_read_from_whichever_figure_is_in_front() {
    let output = run(&[]);
    let stdout = String::from_utf8_lossy(&output.stdout);

    let ascii_in_front = char_at(&stdout, 28, 2);
    assert!(
        matches!(ascii_in_front, '+' | '-' | '|'),
        "expected an ASCII character at (28, 2), got {ascii_in_front:?}"
    );

    let light_in_front = char_at(&stdout, 36, 2);
    assert_eq!(
        light_in_front, '┼',
        "expected the Light crossing character at (36, 2)"
    );
}

/// Feature 056 follow-up: the demonstration also contains a box drawn with each of Double, Heavy
/// and Light Round, so a no-argument run shows all five built-in tables at once.
#[test]
fn the_demonstration_contains_double_heavy_and_light_round_characters() {
    let output = run(&[]);
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains(['║', '╗', '╦', '╬', '╣', '╔', '╠', '═', '╩', '╝', '╚']),
        "no Double box character in {stdout:?}"
    );
    assert!(
        stdout.contains(['┃', '┓', '┳', '╋', '┫', '┏', '┣', '━', '┻', '┛', '┗']),
        "no Heavy box character in {stdout:?}"
    );
    assert!(
        stdout.contains(['╮', '╭', '╯', '╰']),
        "no Light Round corner character in {stdout:?}"
    );
}

/// Each pair of overlapping boxes below the original demonstration crosses two single-stroke
/// tables. Feature 060 loads mixing tables for two of the six pairs here — Light with Double and
/// Light with Heavy — so their crossing now draws the character the exact mixed arms produce
/// instead of degrading. The other two pairs (Light Round with Light, Double with Heavy) still
/// have no mixing table pairing them, so they still degrade every connected arm to the one base
/// stroke — the stroke of the figure that last claimed the cell, which is what makes the answer to
/// "why that character?" a single sentence, and whichever figure is added last since it is
/// front-most and decides first.
/// Each crossing cell below is the same position the original two crossings use: where the first
/// box's bottom border meets the second box's left side.
#[test]
fn crossings_between_the_new_tables_mix_or_degrade_depending_on_table_coverage() {
    let output = run(&[]);
    let stdout = String::from_utf8_lossy(&output.stdout);

    for (x, y, expected, label) in [
        (
            2,
            11,
            '╫',
            "Double in front of Light: covered by Light/Double, mixes instead of degrading",
        ),
        (
            10,
            11,
            '╪',
            "Light in front of Double: covered by Light/Double, mixes instead of degrading",
        ),
        (
            18,
            11,
            '╂',
            "Heavy in front of Light: covered by Light/Heavy, mixes instead of degrading",
        ),
        (
            26,
            11,
            '┿',
            "Light in front of Heavy: covered by Light/Heavy, mixes instead of degrading",
        ),
        (
            34,
            11,
            '┼',
            "Light Round in front of Light: no mixing table pairs them, still degrades",
        ),
        (
            42,
            11,
            '╬',
            "Double in front of Heavy: no mixing table pairs them, still degrades",
        ),
    ] {
        let ch = char_at(&stdout, x, y);
        assert_eq!(ch, expected, "{label}: expected {expected:?} at ({x}, {y})");
    }
}

/// Rule 8 — `--symbols` prints one row per style `all()` reports, in name order, each name padded
/// to the longest and one space, then one cell per symbol.
///
/// **A miss is a space and the row keeps it**, which is what makes the four pointer styles' rows end
/// in three spaces while `ascii`'s two gaps sit before its circle.
#[test]
fn symbols_prints_a_row_per_style_in_name_order_with_a_space_for_a_miss() {
    let output = run(&["--symbols"]);

    assert!(output.status.success(), "the sheet is a run");
    assert!(output.stderr.is_empty(), "wrote to stderr");

    let expected = concat!(
        "arrow         ↑→↓←   \n",
        "ascii         ^>v<  o\n",
        "outline       △▷▽◁◇⬡○\n",
        "small-outline ▵▹▿◃   \n",
        "small-solid   ▴▸▾◂   \n",
        "solid         ▲▶▼◀◆⬢●\n",
        "solid-pointer ▲►▼◄   \n",
    );

    assert_eq!(String::from_utf8_lossy(&output.stdout), expected);
}

/// Rule 9 — the sheet takes nothing else, so a path or a window beside it is refused by name, and
/// the usage line lists `--symbols` as a form of its own.
#[test]
fn symbols_refuses_a_path_and_a_window_and_the_usage_line_names_it() {
    for (args, said) in [
        (
            &["--symbols", "x.json"][..],
            "`x.json` cannot be given beside `--symbols`",
        ),
        (
            &["--size", "4x3", "--symbols"][..],
            "`--size` cannot be given beside `--symbols`",
        ),
        (
            &["--origin", "0,0", "--symbols"][..],
            "`--origin` cannot be given beside `--symbols`",
        ),
        (
            &["--symbols", "--symbols"][..],
            "`--symbols` was given twice",
        ),
    ] {
        let output = run(args);

        assert!(
            !output.status.success(),
            "{args:?} should have been refused"
        );
        assert!(output.stdout.is_empty(), "{args:?} printed to stdout");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains(said), "{args:?}: {stderr}");
        assert!(
            stderr.contains("monospace-cli --symbols"),
            "{args:?}: the usage line names the sheet: {stderr}"
        );
    }
}