yandex-tracker-cli 1.0.2

Token-efficient Yandex Tracker CLI for humans and AI agents
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
//! Writing commands, and the gate in front of them.
//!
//! The interesting assertions are not that a POST happens but that it does not:
//! `--dry-run` must reach the network never, and the announcement of which
//! organisation is about to change must always be there.

#![allow(clippy::expect_used, clippy::unwrap_used)]

use predicates::prelude::*;
use wiremock::matchers::{body_json, method, path, query_param};
use wiremock::{Mock, ResponseTemplate};

mod harness;
use harness::{Harness, fixture};

#[tokio::test]
async fn create_sends_the_queue_summary_and_returns_the_new_key() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/"))
        .and(body_json(serde_json::json!({
            "queue": {"key": "PROJ"},
            "summary": "Retry uploads on 5xx",
            "assignee": "ilubenets",
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(fixture("issue.json")))
        .mount(&harness.server)
        .await;

    harness
        .run(&[
            "issue",
            "create",
            "-q",
            "PROJ",
            "-s",
            "Retry uploads on 5xx",
            "--assignee",
            "ilubenets",
        ])
        .assert()
        .success()
        .stdout(predicate::str::starts_with("PROJ-1  "));
}

/// The whole point of a dry run: nothing reaches Tracker. The stub has no
/// mounted route, so any request at all would fail the test.
#[tokio::test]
async fn dry_run_sends_nothing_and_prints_the_body() {
    let harness = Harness::new().await;

    harness
        .run(&[
            "issue",
            "create",
            "-q",
            "PROJ",
            "-s",
            "nothing to see",
            "--dry-run",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "dry run: would create an issue in PROJ",
        ))
        .stderr(predicate::str::contains("\"summary\": \"nothing to see\""));

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// "Which organisation did I just change" must never be a question the output
/// leaves open.
#[tokio::test]
async fn every_write_announces_the_profile_and_organisation() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/comments"))
        .respond_with(
            ResponseTemplate::new(201)
                .set_body_json(serde_json::json!({"id": 205, "text": "done"})),
        )
        .mount(&harness.server)
        .await;

    harness
        .run(&["issue", "comment", "PROJ-1", "done"])
        .assert()
        .success()
        .stderr(predicate::str::contains("→ profile=test org=12345"))
        .stdout(predicate::str::contains("PROJ-1 comment 205"));
}

#[tokio::test]
async fn update_types_values_by_reading_them_as_json() {
    let harness = Harness::new().await;
    Mock::given(method("PATCH"))
        .and(path("/v3/issues/PROJ-1"))
        .and(body_json(serde_json::json!({
            "storyPoints": 3,
            "summary": "still a string",
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture("issue.json")))
        .mount(&harness.server)
        .await;

    harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "--set",
            "storyPoints=3",
            "--set",
            "summary=still a string",
        ])
        .assert()
        .success();
}

#[tokio::test]
async fn an_update_that_changes_nothing_is_refused() {
    let harness = Harness::new().await;

    harness
        .run(&["issue", "update", "PROJ-1"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("nothing to change"));
}

#[tokio::test]
async fn a_malformed_assignment_is_refused_before_anything_is_sent() {
    let harness = Harness::new().await;

    harness
        .run(&["issue", "update", "PROJ-1", "--set", "storyPoints"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("expected key=value"));

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// Listing transitions is a read, and must not be gated as a write.
#[tokio::test]
async fn transition_without_an_id_lists_what_is_available() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/issues/PROJ-1/transitions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {
                "id": "close",
                "display": "Close",
                "to": {"id": "3", "key": "closed", "display": "Closed"}
            },
            {
                "id": "start_progress",
                "display": "Start progress",
                "to": {"id": "2", "key": "inProgress", "display": "In Progress"}
            }
        ])))
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&["issue", "transition", "PROJ-1"])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("close"));
    assert!(stdout.contains("→ Closed"));
    assert!(stdout.ends_with("shown 2 of 2 for PROJ-1\n"));
}

#[tokio::test]
async fn transition_with_an_id_executes_it() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/transitions/close/_execute"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
        .mount(&harness.server)
        .await;

    harness
        .run(&["issue", "transition", "PROJ-1", "close"])
        .assert()
        .success()
        .stdout(predicate::str::contains("PROJ-1 close"));
}

/// Closing an issue usually requires a resolution, and until this the command
/// could not supply one — half the statuses in an ordinary queue were out of
/// reach through this tool.
#[tokio::test]
async fn a_transition_carries_the_fields_it_is_given() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/transitions/close/_execute"))
        .and(body_json(serde_json::json!({
            "resolution": "wontFix",
            "comment": "not this quarter",
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
        .expect(1)
        .mount(&harness.server)
        .await;

    harness
        .run(&[
            "issue",
            "transition",
            "PROJ-1",
            "close",
            "-r",
            "wontFix",
            "--set",
            "comment=not this quarter",
        ])
        .assert()
        .success();
}

/// Tracker names the fields it wanted in the organisation's language and by
/// their display names, which are not what `--set` takes. Its words are kept;
/// the way to act on them is added.
#[tokio::test]
async fn a_transition_refused_for_want_of_a_field_says_how_to_supply_one() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/transitions/close/_execute"))
        .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
            "errorMessages": ["Вы должны указать значения для полей Резолюция."],
            "statusCode": 422,
        })))
        .mount(&harness.server)
        .await;

    harness
        .run(&["issue", "transition", "PROJ-1", "close"])
        .assert()
        .code(5)
        .stderr(predicate::str::contains("Резолюция"))
        .stderr(predicate::str::contains("--resolution"));
}

/// The hint is for the caller who passed nothing. One who did pass fields and
/// was still refused is being told something else, and repeating the advice
/// would bury it.
#[tokio::test]
async fn a_transition_that_was_given_fields_is_not_told_to_pass_fields() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/transitions/close/_execute"))
        .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
            "errorMessages": ["резолюция nope не существует."],
            "statusCode": 422,
        })))
        .mount(&harness.server)
        .await;

    harness
        .run(&["issue", "transition", "PROJ-1", "close", "-r", "nope"])
        .assert()
        .code(5)
        .stderr(predicate::str::contains("--resolution").not());
}

/// A create that timed out must not be retried: a duplicate issue is worse than
/// a clear failure.
#[tokio::test]
async fn a_failed_write_is_not_retried() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/"))
        .respond_with(ResponseTemplate::new(500))
        .expect(1)
        .mount(&harness.server)
        .await;

    harness
        .run(&["issue", "create", "-q", "PROJ", "-s", "once"])
        .assert()
        .code(5);
}

/// The rule the `--yes` flag exists for: one issue is the ordinary case, several
/// is irreversible at scale. Nothing is sent while the answer is still no.
#[tokio::test]
async fn changing_several_issues_without_yes_exits_two_and_sends_nothing() {
    let harness = Harness::new().await;

    harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "PROJ-4",
            "--set",
            "storyPoints=3",
        ])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("without --yes"))
        // What it would have touched, so the caller can see whether the set is
        // the one they pictured.
        .stderr(predicate::str::contains("PROJ-1, PROJ-4"));

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// Several issues are one request, not one each, and the answer is a tally.
///
/// Tracker checks the whole list before it writes anything, which is the part
/// the issue-at-a-time path could never offer: there is no half-applied change
/// to reconstruct afterwards.
#[tokio::test]
async fn several_issues_with_yes_are_one_request_and_a_tally() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/bulkchange/_update"))
        .and(body_json(serde_json::json!({
            "issues": ["PROJ-1", "PROJ-4"],
            "values": {"storyPoints": 3},
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(fixture("bulkchange_created.json")))
        .expect(1)
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/bulkchange/6a92d90773c59502bc8e028a"))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture("bulkchange_complete.json")))
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "PROJ-4",
            "--set",
            "storyPoints=3",
            "--yes",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("changed 2 of 2"), "{stdout}");
    // The only handle on the work afterwards, so it is printed even when
    // nothing went wrong.
    assert!(
        stdout.contains("bulkchange 6a92d90773c59502bc8e028a"),
        "{stdout}"
    );
    // Nothing per issue: the saving is the point, and repeating the keys would
    // spend it on the output.
    assert!(!stdout.contains("PROJ-1"), "{stdout}");
}

/// A change that finished having changed nothing must not exit zero, and the
/// per-issue reasons are worth the second request precisely then.
#[tokio::test]
async fn a_bulk_change_that_failed_names_each_issue_and_why() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/bulkchange/_update"))
        .respond_with(ResponseTemplate::new(201).set_body_json(fixture("bulkchange_created.json")))
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/bulkchange/6a92d90773c59502bc8e028a"))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture("bulkchange_failed.json")))
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/bulkchange/6a92d9387d41a060a2b5e6d9/issues"))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture("bulkchange_issues.json")))
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "PROJ-4",
            "--set",
            "priority=nonexistent",
            "--yes",
        ])
        .assert()
        .code(5);
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("changed 1 of 2"), "{stdout}");
    // Tracker's own words about the field, kept as written.
    assert!(stdout.contains("priority: "), "{stdout}");
    assert!(stdout.contains("PROJ-2"), "{stdout}");
    // The one that worked stays in the tally rather than in a line of its own.
    assert!(!stdout.contains("PROJ-1  "), "{stdout}");
}

/// An unknown key is refused before anything is written, and Tracker names it.
///
/// The issue-at-a-time path had already changed the earlier issues by the time
/// it found out.
#[tokio::test]
async fn a_key_that_does_not_exist_stops_the_whole_change() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/bulkchange/_update"))
        .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
            "errors": {"issues": "задачи [PROJ-999] не существуют"},
            "statusCode": 422,
        })))
        .mount(&harness.server)
        .await;

    harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "PROJ-999",
            "--set",
            "storyPoints=3",
            "--yes",
        ])
        .assert()
        .code(5)
        .stderr(predicate::str::contains("PROJ-999"));
}

/// `--no-wait` claims only what happened: Tracker accepted it.
#[tokio::test]
async fn no_wait_returns_the_id_without_claiming_the_work_is_done() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/bulkchange/_update"))
        .respond_with(ResponseTemplate::new(201).set_body_json(fixture("bulkchange_created.json")))
        .expect(1)
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "PROJ-4",
            "--set",
            "storyPoints=3",
            "--yes",
            "--no-wait",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(
        stdout.contains("bulkchange 6a92d90773c59502bc8e028a"),
        "{stdout}"
    );
    // No tally is invented from the keys we sent: Tracker has not counted them.
    assert!(!stdout.contains("changed 2 of 2"), "{stdout}");
}

/// Two organisations cannot be one request. The slow path stays, and says how
/// far it got in the same words.
#[tokio::test]
async fn keys_in_two_organisations_go_one_at_a_time() {
    let harness = Harness::new().await;
    harness.add_profile("other", "98765");
    for key in ["PROJ-1", "PROJ-4"] {
        Mock::given(method("PATCH"))
            .and(path(format!("/v3/issues/{key}")))
            .and(body_json(serde_json::json!({"storyPoints": 3})))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("issue.json")))
            .expect(1)
            .mount(&harness.server)
            .await;
    }

    let output = harness
        .run(&[
            "issue",
            "update",
            "test/PROJ-1",
            "other/PROJ-4",
            "--set",
            "storyPoints=3",
            "--yes",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("changed 2 of 2"), "{stdout}");
}

/// A dry run names every target, which is the only way to check the set before
/// committing to it.
#[tokio::test]
async fn a_dry_run_over_several_issues_lists_them_all() {
    let harness = Harness::new().await;

    harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "PROJ-4",
            "--set",
            "storyPoints=3",
            "--dry-run",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains("would update PROJ-1, PROJ-4"));

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// Half-applied is the worst outcome, so a bad key stops the run before the
/// first request rather than after the first success.
#[tokio::test]
async fn a_malformed_key_stops_the_run_before_anything_is_sent() {
    let harness = Harness::new().await;

    harness
        .run(&["issue", "update", "PROJ-1", "/", "--set", "x=1", "--yes"])
        .assert()
        .code(2);

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// Every write, not just the ones with a test of their own.
///
/// The gate is only worth having if nothing goes round it, and a new verb that
/// forgets to call it would otherwise be found by a user with a `--dry-run` that
/// wrote something.
#[tokio::test]
async fn no_write_verb_reaches_the_network_under_dry_run() {
    let file = tempfile::NamedTempFile::new().expect("temp file");
    let path = file.path().to_string_lossy().into_owned();

    let writes: Vec<Vec<&str>> = vec![
        vec!["issue", "create", "-q", "PROJ", "-s", "title"],
        vec!["issue", "update", "PROJ-1", "--set", "storyPoints=3"],
        vec!["issue", "comment", "PROJ-1", "text"],
        vec!["issue", "transition", "PROJ-1", "close"],
        vec!["issue", "move", "PROJ-1", "--to", "OPS"],
        vec!["attachment", "upload", "PROJ-1", &path],
    ];

    for args in writes {
        let harness = Harness::new().await;
        let mut with_flag = args.clone();
        with_flag.push("--dry-run");

        harness.run(&with_flag).assert().success();

        assert!(
            harness
                .server
                .received_requests()
                .await
                .expect("recorded")
                .is_empty(),
            "`ytcli {}` sent a request under --dry-run",
            args.join(" ")
        );
    }
}

/// The key changes and nothing puts it back, so a single issue needs `--yes`
/// here where an ordinary update does not.
#[tokio::test]
async fn moving_one_issue_still_needs_yes() {
    let harness = Harness::new().await;

    harness
        .run(&["issue", "move", "PROJ-1", "--to", "OPS"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("cannot be undone"));

    assert!(
        harness.server.received_requests().await.unwrap().is_empty(),
        "a refused move must send nothing"
    );
}

/// What the caller gets back is the new key: nothing they were holding still
/// addresses the issue.
#[tokio::test]
async fn a_move_reports_the_key_the_issue_now_has() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/_move"))
        .and(query_param("queue", "OPS"))
        .and(query_param("moveAllFields", "false"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "key": "OPS-17",
            "summary": "Attachments are lost on move",
            "queue": {"key": "OPS"}
        })))
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&["issue", "move", "PROJ-1", "--to", "OPS", "--yes"])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert_eq!(stdout, "PROJ-1 → OPS-17\n");
}

/// Fields the target queue does not define are dropped by Tracker unless the
/// caller says otherwise, so the flag has to reach the request.
#[tokio::test]
async fn keep_fields_is_passed_through_to_tracker() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/_move"))
        .and(query_param("moveAllFields", "true"))
        .and(query_param("initialStatus", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "key": "OPS-17",
            "summary": "Attachments are lost on move"
        })))
        .mount(&harness.server)
        .await;

    harness
        .run(&[
            "issue",
            "move",
            "PROJ-1",
            "--to",
            "OPS",
            "--keep-fields",
            "--initial-status",
            "--yes",
        ])
        .assert()
        .success();
}

/// A workflow step applied to several issues is one request, with the fields the
/// workflow demands carried into it.
#[tokio::test]
async fn several_issues_take_one_transition_in_one_request() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/bulkchange/_transition"))
        .and(body_json(serde_json::json!({
            "issues": ["PROJ-1", "PROJ-4"],
            "transition": "close",
            "values": {"resolution": "fixed"},
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(fixture("bulkchange_created.json")))
        .expect(1)
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/bulkchange/6a92d90773c59502bc8e028a"))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture("bulkchange_complete.json")))
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&[
            "issue",
            "transition",
            "PROJ-1",
            "PROJ-4",
            "--to",
            "close",
            "-r",
            "fixed",
            "--yes",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("changed 2 of 2"), "{stdout}");
}

/// With a list of keys there is nowhere unambiguous for a bare transition id, so
/// the command says which flag names it rather than guessing which word is which.
#[tokio::test]
async fn several_issues_without_to_are_refused_and_send_nothing() {
    let harness = Harness::new().await;

    harness
        .run(&["issue", "transition", "PROJ-1", "PROJ-4", "close", "--yes"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("--to"));

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// Moving several issues is one request. `--yes` is still required for a single
/// one: the key change is irreversible in kind, not merely at scale.
#[tokio::test]
async fn several_issues_move_in_one_request() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/bulkchange/_move"))
        .and(body_json(serde_json::json!({
            "issues": ["PROJ-1", "PROJ-4"],
            "queue": "OPS",
            "moveAllFields": false,
            "initialStatus": false,
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(fixture("bulkchange_created.json")))
        .expect(1)
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/bulkchange/6a92d90773c59502bc8e028a"))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture("bulkchange_complete.json")))
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&["issue", "move", "PROJ-1", "PROJ-4", "--to", "OPS", "--yes"])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("changed 2 of 2"), "{stdout}");
}

/// The confirmation for a move names every key it is about to change, because
/// after the request none of them address the issue any more.
#[tokio::test]
async fn moving_several_issues_without_yes_names_all_of_them() {
    let harness = Harness::new().await;

    harness
        .run(&["issue", "move", "PROJ-1", "PROJ-4", "--to", "OPS"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("PROJ-1, PROJ-4"));

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// Transition ids are per workflow; a status key is the same everywhere. A
/// caller who has the status gets the id found for them, and only after the
/// direct attempt failed — the ordinary path stays one request.
#[tokio::test]
async fn a_target_status_is_resolved_to_the_transition_that_reaches_it() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/transitions/closed/_execute"))
        .respond_with(ResponseTemplate::new(404))
        .expect(1)
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/issues/PROJ-1/transitions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {"id": "close", "display": "Close", "to": {"key": "closed", "display": "Closed"}}
        ])))
        .expect(1)
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/transitions/close/_execute"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
        .expect(1)
        .mount(&harness.server)
        .await;

    let output = harness
        .run(&["issue", "transition", "PROJ-1", "closed"])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    // The id that worked, so the next call can skip the second request.
    assert!(stdout.contains("PROJ-1 close"), "{stdout}");
}

/// A word that is neither an id nor a reachable status is still a refusal, and
/// the same request is not sent twice to produce it.
#[tokio::test]
async fn a_transition_that_matches_nothing_is_refused_once() {
    let harness = Harness::new().await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/PROJ-1/transitions/nonsense/_execute"))
        .respond_with(ResponseTemplate::new(404))
        .expect(1)
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/issues/PROJ-1/transitions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {"id": "close", "display": "Close", "to": {"key": "closed", "display": "Closed"}}
        ])))
        .mount(&harness.server)
        .await;

    harness
        .run(&["issue", "transition", "PROJ-1", "nonsense"])
        .assert()
        .code(4);
}

/// A description is the field most likely to hold quotes and newlines, and the
/// one most often already in a file.
#[tokio::test]
async fn a_description_can_come_from_a_file() {
    let harness = Harness::new().await;
    let file = harness.config_path().with_file_name("body.md");
    std::fs::write(&file, "## Steps\n\n1. Attach a file\n").expect("write");

    Mock::given(method("POST"))
        .and(path("/v3/issues/"))
        .and(body_json(serde_json::json!({
            "queue": {"key": "PROJ"},
            "summary": "from a file",
            "description": "## Steps\n\n1. Attach a file\n",
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(fixture("issue.json")))
        .expect(1)
        .mount(&harness.server)
        .await;

    harness
        .run(&[
            "issue",
            "create",
            "-q",
            "PROJ",
            "-s",
            "from a file",
            "--description-file",
            file.to_str().expect("utf-8 path"),
        ])
        .assert()
        .success();
}

/// Guessing which of the two was meant is how the wrong text gets written.
#[tokio::test]
async fn a_description_given_twice_is_refused_and_sends_nothing() {
    let harness = Harness::new().await;

    harness
        .run(&[
            "issue",
            "create",
            "-q",
            "PROJ",
            "-s",
            "twice",
            "-d",
            "inline",
            "--description-file",
            "/nonexistent",
        ])
        .assert()
        .failure();

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// `issue update` could only reach the description through `--set` before, which
/// meant quoting markdown into a shell argument.
#[tokio::test]
async fn update_replaces_the_description_from_a_file() {
    let harness = Harness::new().await;
    let file = harness.config_path().with_file_name("new-body.md");
    std::fs::write(&file, "rewritten\n").expect("write");

    Mock::given(method("PATCH"))
        .and(path("/v3/issues/PROJ-1"))
        .and(body_json(serde_json::json!({"description": "rewritten\n"})))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture("issue.json")))
        .expect(1)
        .mount(&harness.server)
        .await;

    harness
        .run(&[
            "issue",
            "update",
            "PROJ-1",
            "--description-file",
            file.to_str().expect("utf-8 path"),
        ])
        .assert()
        .success();
}