bbcloud 0.22.0

Bitbucket Cloud CLI — open pull requests, read every comment, write replies, from the shell
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
#![allow(clippy::unwrap_used)]

use assert_cmd::Command;
use wiremock::matchers::{method, path, query_param, query_param_is_missing};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// `BB_WORKSPACE` defaults to `acme` here so every test written before
/// workspace resolution became explicit keeps working unchanged; tests that
/// care about resolution order override or remove it.
fn bb(base: &str) -> Command {
    let mut cmd = Command::cargo_bin("bb").unwrap();
    cmd.env("BB_NO_UPDATE_CHECK", "1");
    cmd.env("BB_EMAIL", "me@example.com")
        .env("BB_TOKEN", "t0ken-value")
        .env("BB_API_BASE", base)
        .env("BB_KEYRING_DISABLE", "1")
        .env("BB_WORKSPACE", "acme")
        .env("NO_COLOR", "1");
    cmd
}

fn user_body() -> serde_json::Value {
    serde_json::json!({ "uuid": "{me}", "display_name": "Me" })
}

fn pr(id: u64, repo: &str, author_uuid: &str, reviewer_uuid: Option<&str>) -> serde_json::Value {
    let reviewers = match reviewer_uuid {
        Some(uuid) => serde_json::json!([{ "uuid": uuid, "display_name": "R" }]),
        None => serde_json::json!([]),
    };
    serde_json::json!({
        "id": id,
        "title": format!("pr {id}"),
        "state": "OPEN",
        "draft": false,
        "updated_on": "2026-08-10T09:00:00+00:00",
        "author": { "uuid": author_uuid, "display_name": "A" },
        "reviewers": reviewers,
        "participants": [],
        "source": { "branch": { "name": "feat" } },
        "destination": { "branch": { "name": "main" } },
        "links": { "html": { "href": format!("https://bitbucket.org/{repo}/pull-requests/{id}") } }
    })
}

fn page(values: Vec<serde_json::Value>) -> serde_json::Value {
    serde_json::json!({ "values": values })
}

async fn mock_user(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(ResponseTemplate::new(200).set_body_json(user_body()))
        .mount(server)
        .await;
}

/// Mounts all four api paths Atlassian removed under CHANGE-2770, each with
/// `.expect(0)` so a regression back to any of them fails the suite instead
/// of silently degrading to a 410 in production. There is no more
/// workspace-discovery request at all — every test that used to call
/// `mock_workspaces` now supplies `--workspace`/`BB_WORKSPACE` directly.
async fn mock_removed_endpoints(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/workspaces"))
        .respond_with(ResponseTemplate::new(410).set_body_json(serde_json::json!({
            "error": { "message": "CHANGE-2770 - Functionality has been deprecated" }
        })))
        .expect(0)
        .mount(server)
        .await;
    Mock::given(method("GET"))
        .and(path("/user/permissions/workspaces"))
        .respond_with(ResponseTemplate::new(410).set_body_json(serde_json::json!({
            "error": { "message": "CHANGE-2770 - Functionality has been deprecated" }
        })))
        .expect(0)
        .mount(server)
        .await;
    Mock::given(method("GET"))
        .and(path("/user/permissions/repositories"))
        .respond_with(ResponseTemplate::new(410).set_body_json(serde_json::json!({
            "error": { "message": "CHANGE-2770 - Functionality has been deprecated" }
        })))
        .expect(0)
        .mount(server)
        .await;
    Mock::given(method("GET"))
        .and(path_regex_repositories())
        .and(query_param("role", "member"))
        .respond_with(ResponseTemplate::new(410).set_body_json(serde_json::json!({
            "error": { "message": "CHANGE-2770 - Functionality has been deprecated" }
        })))
        .expect(0)
        .mount(server)
        .await;
}

/// The removed cross-workspace authored endpoint. Mounted with `.expect(0)`
/// in every test so a regression back to it fails the suite instead of
/// silently degrading to a 404 in production.
async fn mock_removed_authored_endpoint(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({})))
        .expect(0)
        .mount(server)
        .await;
}

fn path_regex_repositories() -> wiremock::matchers::PathRegexMatcher {
    wiremock::matchers::path_regex(r"^/repositories/.*$")
}

fn repos_page(names: &[&str]) -> serde_json::Value {
    page(
        names
            .iter()
            .map(|n| serde_json::json!({ "full_name": n }))
            .collect(),
    )
}

#[tokio::test]
async fn role_author_asks_only_the_workspace_scoped_authored_endpoint() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(page(vec![pr(42, "acme/api", "{me}", None)])),
        )
        .expect(1)
        .mount(&server)
        .await;
    // No repository enumeration may happen on the author-only path.
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&[])))
        .expect(0)
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let rows = value["pull_requests"].as_array().unwrap();
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0]["id"], 42);
    assert_eq!(rows[0]["repo"], "acme/api");
    assert_eq!(rows[0]["my_role"], "author");
    assert_eq!(rows[0]["updated_on"], "2026-08-10T09:00:00+00:00");
    assert!(value["partial"].as_array().unwrap().is_empty());
}

#[tokio::test]
async fn workspace_flag_skips_workspace_enumeration_for_role_author() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "author",
            "--workspace",
            "acme",
            "--json",
        ])
        .assert()
        .success();
}

#[tokio::test]
async fn empty_json_prints_only_the_value() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
    assert!(value["pull_requests"].as_array().unwrap().is_empty());
    assert!(value["partial"].as_array().unwrap().is_empty());
}

#[tokio::test]
async fn state_is_passed_through_to_the_api() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .and(query_param("state", "MERGED"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr", "mine", "--role", "author", "--state", "merged", "--json",
        ])
        .assert()
        .success();
}

#[tokio::test]
async fn a_404_from_the_authored_endpoint_exits_three() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({})))
        .mount(&server)
        .await;

    bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--json"])
        .assert()
        .code(3);
}

#[tokio::test]
async fn human_output_names_the_repository() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(page(vec![pr(42, "acme/api", "{me}", None)])),
        )
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "author"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert!(stdout.contains("acme/api"), "got {stdout}");
    assert!(stdout.contains("REPO"), "got {stdout}");
}

#[tokio::test]
async fn reviewer_side_keeps_only_pull_requests_i_review() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .and(query_param_is_missing("role"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api"])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![
            pr(7, "acme/api", "{other}", Some("{me}")),
            pr(8, "acme/api", "{other}", Some("{someone-else}")),
        ])))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "reviewer", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let rows = value["pull_requests"].as_array().unwrap();
    assert_eq!(rows.len(), 1, "only the pr I review may survive: {stdout}");
    assert_eq!(rows[0]["id"], 7);
    assert_eq!(rows[0]["my_role"], "reviewer");
    assert_eq!(rows[0]["my_review_state"], "pending");
}

#[tokio::test]
async fn a_500_from_repositories_fails_the_whole_command() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({})))
        .mount(&server)
        .await;

    bb(&server.uri())
        .args(["pr", "mine", "--role", "reviewer", "--json"])
        .assert()
        .code(1);
}

#[tokio::test]
async fn a_401_from_repositories_exits_two() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({})))
        .mount(&server)
        .await;

    bb(&server.uri())
        .args(["pr", "mine", "--role", "reviewer", "--json"])
        .assert()
        .code(2);
}

#[tokio::test]
async fn authored_and_reviewed_dedupes_into_one_row_marked_both() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![pr(
            7,
            "acme/api",
            "{me}",
            Some("{me}"),
        )])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api"])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![pr(
            7,
            "acme/api",
            "{me}",
            Some("{me}"),
        )])))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let rows = value["pull_requests"].as_array().unwrap();
    assert_eq!(rows.len(), 1, "the same pr must appear once: {stdout}");
    assert_eq!(rows[0]["my_role"], "both");
}

#[tokio::test]
async fn workspace_flag_skips_workspace_enumeration() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api"])))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "acme",
            "--json",
        ])
        .assert()
        .success();
}

#[tokio::test]
async fn repo_limit_caps_the_fan_out() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api", "acme/web"])),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .expect(1)
        .mount(&server)
        .await;
    // Second repository is beyond the limit and must never be asked.
    Mock::given(method("GET"))
        .and(path("/repositories/acme/web/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .expect(0)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "acme",
            "--repo-limit",
            "1",
            "--json",
        ])
        .assert()
        .success();
}

#[tokio::test]
async fn repositories_are_requested_newest_first_with_no_role_parameter() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .and(query_param("sort", "-updated_on"))
        .and(query_param_is_missing("role"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&[])))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "acme",
            "--json",
        ])
        .assert()
        .success();
}

#[tokio::test]
async fn an_unreadable_workspace_is_reported_not_fatal() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api"])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![pr(
            7,
            "acme/api",
            "{other}",
            Some("{me}"),
        )])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/locked"))
        .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({})))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "acme,locked",
            "--json",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(value["pull_requests"].as_array().unwrap().len(), 1);
    assert_eq!(value["partial"], serde_json::json!(["locked"]));
}

/// Finding 1: the authored half must carry the same partial-response `fields`
/// parameter the reviewer half already does, or `draft`, `reviewers` and
/// `my_review_state` all come back wrong instead of merely absent. The
/// fixture's `pr()` returns `reviewers`/`draft` regardless of the query
/// string, so this must assert on the request itself.
#[tokio::test]
async fn authored_request_carries_the_reviewer_fields_parameter() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .and(query_param(
            "fields",
            "+values.reviewers,+values.participants,+values.draft,+values.comment_count",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--json"])
        .assert()
        .success();
}

/// Finding 2: the merge must land on "both" from provenance, not from
/// trusting whichever half's pull-request object happened to be seen first.
/// Here the authored half's fixture is deliberately given no reviewer, so a
/// naive "keep the first row" dedupe would leave `my_role` as `"author"`.
#[tokio::test]
async fn a_pr_found_in_both_halves_is_marked_both_even_when_the_first_seen_row_lacks_a_reviewer() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(page(vec![pr(7, "acme/api", "{me}", None)])),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api"])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![pr(
            7,
            "acme/api",
            "{me}",
            Some("{me}"),
        )])))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let rows = value["pull_requests"].as_array().unwrap();
    assert_eq!(rows.len(), 1, "the same pr must appear once: {stdout}");
    assert_eq!(rows[0]["my_role"], "both", "got {stdout}");
}

/// Finding 3: the repository listing must ask for a bounded page rather than
/// draining every page before `.take(limit)` runs, and must never follow a
/// second page.
#[tokio::test]
async fn repository_listing_request_carries_a_bounded_pagelen_and_fetches_one_page() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .and(query_param("pagelen", "1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "values": [{ "full_name": "acme/api" }],
            "next": format!("{}/repositories/acme?page=2", server.uri()),
        })))
        .expect(1)
        .mount(&server)
        .await;
    // A second page must never be fetched: page one is already everything
    // `--repo-limit` wants, thanks to `sort=-updated_on`.
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .and(query_param("page", "2"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/web"])))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![])))
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "acme",
            "--repo-limit",
            "1",
            "--json",
        ])
        .assert()
        .success();
}

/// Finding 3: `--repo-limit 0` must scan nothing, and must not even ask.
#[tokio::test]
async fn repo_limit_zero_scans_nothing_and_issues_no_listing_request() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api"])))
        .expect(0)
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "acme",
            "--repo-limit",
            "0",
            "--json",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(value["pull_requests"].as_array().unwrap().is_empty());
}

/// Finding 5: a pull request whose `repo` cannot be parsed as a `RepoSlug`
/// (the link-less `"-"` case) must still carry `build_state`/`build` when
/// `--build` is passed, so every row has the same JSON shape.
#[tokio::test]
async fn a_row_with_no_parseable_repo_still_carries_build_fields_when_build_is_requested() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    let mut linkless = pr(7, "acme/api", "{me}", None);
    linkless["links"] = serde_json::json!({});
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![linkless])))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--build", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let rows = value["pull_requests"].as_array().unwrap();
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0]["repo"], "-");
    assert_eq!(rows[0]["build_state"], "none", "got {stdout}");
    assert_eq!(
        rows[0]["build"].as_array().unwrap().len(),
        0,
        "got {stdout}"
    );
}

/// Finding 6: `pr mine --state draft` is rejected rather than silently asking
/// bitbucket for an invalid `DRAFT` state and surfacing a raw api error.
#[tokio::test]
async fn state_draft_is_rejected_with_a_config_error() {
    let server = MockServer::start().await;
    mock_user(&server).await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--state", "draft", "--json"])
        .assert()
        .code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(stderr.contains("draft"), "got {stderr}");
}

/// Finding 7: `-R`/`--repo` is not accepted with `pr mine`, since it is not
/// repository-scoped and the flag would otherwise be silently discarded.
#[tokio::test]
async fn repo_flag_is_rejected_with_pr_mine() {
    let server = MockServer::start().await;
    mock_user(&server).await;

    bb(&server.uri())
        .args(["--repo", "acme/api", "pr", "mine", "--json"])
        .assert()
        .failure();
}

/// Finding 8: an account with no uuid must fail explicitly rather than
/// degrading into an empty-uuid request where every row is mislabelled
/// "reviewer".
#[tokio::test]
async fn an_account_with_no_uuid_is_a_config_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(serde_json::json!({ "display_name": "Me" })),
        )
        .mount(&server)
        .await;

    bb(&server.uri())
        .args(["pr", "mine", "--json"])
        .assert()
        .code(1);
}

#[tokio::test]
async fn build_is_fetched_once_for_a_deduped_row() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![pr(
            7,
            "acme/api",
            "{me}",
            Some("{me}"),
        )])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&["acme/api"])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![pr(
            7,
            "acme/api",
            "{me}",
            Some("{me}"),
        )])))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/api/pullrequests/7/statuses"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![
            serde_json::json!({ "key": "PIPE", "name": "p", "state": "FAILED" }),
        ])))
        .expect(1)
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--build", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let rows = value["pull_requests"].as_array().unwrap();
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0]["build_state"], "failed");
    assert_eq!(rows[0]["build"].as_array().unwrap().len(), 1);
}

/// Resolution order 1: `--workspace a,b` scans both workspaces, comma-
/// separated, in one invocation.
#[tokio::test]
async fn workspace_flag_with_a_comma_list_scans_both_workspaces() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&[])))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/other"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&[])))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "acme,other",
            "--json",
        ])
        .assert()
        .success();
}

/// Resolution order 2: `--workspace` beats `BB_WORKSPACE` — the flag names
/// `other`, the env var (set by the `bb` helper's default) names `acme`, and
/// only `other` may be scanned.
#[tokio::test]
async fn workspace_flag_beats_bb_workspace_env_var() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&[])))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/other"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&[])))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args([
            "pr",
            "mine",
            "--role",
            "reviewer",
            "--workspace",
            "other",
            "--json",
        ])
        .assert()
        .success();
}

/// Resolution order 3: with no `--workspace`, `BB_WORKSPACE` is used — the
/// `bb` helper already sets it to `acme` by default, so this just asserts
/// that a bare invocation (no flag) reaches the workspace the env var names.
#[tokio::test]
async fn bb_workspace_env_var_is_used_when_the_flag_is_absent() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(repos_page(&[])))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server.uri())
        .args(["pr", "mine", "--role", "reviewer", "--json"])
        .assert()
        .success();
}

/// Resolution order 4: no `--workspace`, no `BB_WORKSPACE`, and the test
/// runs with a working directory inside this git repository — whose remote
/// is GitHub, not Bitbucket — so `repo::resolve` fails naturally too. That
/// must be a config error (exit 1) naming both `--workspace` and
/// `BB_WORKSPACE`, never a silent empty success.
#[tokio::test]
async fn no_workspace_source_is_a_config_error_not_an_empty_success() {
    let server = MockServer::start().await;
    mock_user(&server).await;

    let out = bb(&server.uri())
        .env_remove("BB_WORKSPACE")
        .args(["pr", "mine", "--role", "reviewer", "--json"])
        .assert()
        .code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(stderr.contains("--workspace"), "got {stderr}");
    assert!(stderr.contains("BB_WORKSPACE"), "got {stderr}");
}

/// The bug this field exists for: a reviewer comments without approving or
/// requesting changes, so `my_review_state` stays `pending` and the row looks
/// idle. `comment_count` is the only signal in phase 1 that says otherwise, so
/// it has to reach `--json`.
#[tokio::test]
async fn a_commented_on_authored_row_carries_the_comment_count() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    let mut commented = pr(42, "acme/api", "{me}", Some("{dana}"));
    commented["comment_count"] = serde_json::json!(3);
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![commented])))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let row = &value["pull_requests"][0];
    // The reviewer never acted, so the state alone still reads as idle.
    assert_eq!(row["my_review_state"], serde_json::Value::Null);
    assert_eq!(row["comment_count"], 3);
}

/// A pull request nobody has commented on reports zero rather than nothing:
/// the brief's candidate rule reads the field on every row, and a missing key
/// there would be indistinguishable from an api that did not answer.
#[tokio::test]
async fn an_untouched_row_reports_zero_comments() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    let mut quiet = pr(7, "acme/api", "{me}", None);
    quiet["comment_count"] = serde_json::json!(0);
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(ResponseTemplate::new(200).set_body_json(page(vec![quiet])))
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(value["pull_requests"][0]["comment_count"], 0);
}

/// When the api omits the counter the key is still present and null, never
/// absent and never coerced to 0 — a consumer must be able to tell "no
/// comments" from "the api did not say", because the second one means it has
/// to fetch the pull request to find out.
#[tokio::test]
async fn a_missing_comment_count_is_null_not_zero() {
    let server = MockServer::start().await;
    mock_user(&server).await;
    mock_removed_authored_endpoint(&server).await;
    mock_removed_endpoints(&server).await;
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/pullrequests/%7Bme%7D"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(page(vec![pr(9, "acme/api", "{me}", None)])),
        )
        .mount(&server)
        .await;

    let out = bb(&server.uri())
        .args(["pr", "mine", "--role", "author", "--json"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let row = value["pull_requests"][0].as_object().unwrap();
    assert!(row.contains_key("comment_count"));
    assert_eq!(row["comment_count"], serde_json::Value::Null);
}