bbcloud 0.19.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
#![allow(clippy::unwrap_used)] // test code is exempt from the unwrap/expect ban

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

fn bb(server: &MockServer) -> Command {
    let mut cmd = Command::cargo_bin("bb").unwrap();
    cmd.env("BB_EMAIL", "dev@example.com")
        .env("BB_TOKEN", "t0ken-value")
        .env("BB_API_BASE", server.uri())
        .env("BB_REPO", "acme/widgets")
        .env("NO_COLOR", "1")
        // Without this a test can reach the real OS keyring and destroy the
        // developer's stored token.
        .env("BB_KEYRING_DISABLE", "1");
    cmd
}

/// A pull request with three reviewers in three different states.
fn pr_with_reviewers() -> serde_json::Value {
    serde_json::json!({
        "id": 7,
        "title": "fix the thing",
        "state": "OPEN",
        "author": { "uuid": "{sean}", "nickname": "sean", "display_name": "Sean B" },
        "source": { "branch": { "name": "feature/a" } },
        "destination": { "branch": { "name": "main" } },
        "links": { "html": { "href": "https://bitbucket.org/acme/widgets/pull-requests/7" } },
        "reviewers": [
            { "uuid": "{a}", "display_name": "Ana" },
            { "uuid": "{b}", "display_name": "Bo" },
            { "uuid": "{c}", "display_name": "Cy" },
            { "uuid": "{d}", "display_name": "Dee" }
        ],
        "participants": [
            { "role": "REVIEWER", "state": "approved", "user": { "uuid": "{a}", "display_name": "Ana" } },
            { "role": "REVIEWER", "state": "changes_requested", "user": { "uuid": "{b}", "display_name": "Bo" } },
            { "role": "REVIEWER", "state": null, "user": { "uuid": "{c}", "display_name": "Cy" } },
            { "role": "PARTICIPANT", "state": "approved", "user": { "uuid": "{z}", "display_name": "Zed" } }
        ]
    })
}

async fn mount_list(server: &MockServer, values: serde_json::Value) {
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": values })),
        )
        .mount(server)
        .await;
}

/// The whole point of the feature: without this parameter Bitbucket returns a
/// reduced pull-request object with no reviewers, participants or draft flag, and
/// the reviewer column is silently empty.
#[tokio::test]
async fn list_requests_the_reviewer_fields() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests"))
        .and(query_param(
            "fields",
            "+values.reviewers,+values.participants,+values.draft",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": [] })))
        .mount(&server)
        .await;

    bb(&server).args(["pr", "list"]).assert().success();
}

/// A bare `bb pr list`, with no `--state` flag at all, must default to asking
/// bitbucket for OPEN only — otherwise merged/declined noise leaks into the
/// default view.
#[tokio::test]
async fn list_with_no_state_flag_requests_open() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests"))
        .and(query_param("state", "OPEN"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": [] })))
        .mount(&server)
        .await;

    bb(&server).args(["pr", "list"]).assert().success();
}

#[tokio::test]
async fn list_marks_each_reviewer_with_their_state() {
    let server = MockServer::start().await;
    mount_list(&server, serde_json::json!([pr_with_reviewers()])).await;

    let out = bb(&server).args(["pr", "list"]).output().unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("Ana ✓"), "{text}");
    assert!(text.contains("Bo ✗"), "{text}");
    assert!(text.contains("Cy ·"), "{text}");
    // Tagged but never seen by the api's participant list.
    assert!(text.contains("Dee ·"), "{text}");
    // A commenter is not a reviewer.
    assert!(
        !text.contains("Zed"),
        "plain participant rendered as reviewer: {text}"
    );
}

#[tokio::test]
async fn list_shows_the_pr_state_column() {
    let server = MockServer::start().await;
    let mut draft = pr_with_reviewers();
    draft["draft"] = serde_json::json!(true);
    let mut declined = pr_with_reviewers();
    declined["id"] = serde_json::json!(8);
    declined["state"] = serde_json::json!("DECLINED");
    mount_list(&server, serde_json::json!([draft, declined])).await;

    let out = bb(&server)
        .args(["pr", "list", "--state", "all"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("STATE"), "{text}");
    assert!(text.contains("Draft"), "{text}");
    assert!(text.contains("Declined"), "{text}");
}

#[tokio::test]
async fn list_json_emits_structured_reviewers_and_no_approvals_key() {
    let server = MockServer::start().await;
    mount_list(&server, serde_json::json!([pr_with_reviewers()])).await;

    let out = bb(&server).args(["pr", "list", "--json"]).output().unwrap();
    let value: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(value[0]["id"], 7);
    assert_eq!(value[0]["state"], "OPEN");
    assert_eq!(value[0]["draft"], false);
    assert_eq!(value[0]["reviewers"][0]["name"], "Ana");
    assert_eq!(value[0]["reviewers"][0]["uuid"], "{a}");
    assert_eq!(value[0]["reviewers"][0]["state"], "approved");
    assert_eq!(value[0]["reviewers"][1]["state"], "changes_requested");
    assert_eq!(value[0]["reviewers"][2]["state"], "pending");
    assert!(
        value[0].get("approvals").is_none(),
        "approvals key should be gone: {value}"
    );
}

#[tokio::test]
async fn list_json_on_zero_rows_is_a_pure_empty_array() {
    let server = MockServer::start().await;
    mount_list(&server, serde_json::json!([])).await;

    let out = bb(&server).args(["pr", "list", "--json"]).output().unwrap();
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    let value: serde_json::Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("stdout did not parse as JSON: {e}\nstdout: {stdout}"));
    assert_eq!(value, serde_json::json!([]));
}

#[tokio::test]
async fn list_still_filters_by_destination_branch() {
    let server = MockServer::start().await;
    let mut other = pr_with_reviewers();
    other["id"] = serde_json::json!(8);
    other["source"] = serde_json::json!({ "branch": { "name": "feature/b" } });
    other["destination"] = serde_json::json!({ "branch": { "name": "develop" } });
    mount_list(&server, serde_json::json!([pr_with_reviewers(), other])).await;

    let out = bb(&server)
        .args(["pr", "list", "develop"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("feature/b"), "{text}");
    assert!(
        !text.contains("feature/a"),
        "destination filter not applied: {text}"
    );
}

#[tokio::test]
async fn list_state_all_asks_the_api_for_every_state() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests"))
        .and(query_param("state", "OPEN,MERGED,DECLINED,SUPERSEDED"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": [] })))
        .mount(&server)
        .await;

    bb(&server)
        .args(["pr", "list", "--state", "all"])
        .assert()
        .success();
}

/// Two pull requests: 7 has Ana approving and Dee pending, 8 has only Dee.
fn pr_pair() -> serde_json::Value {
    let mut second = pr_with_reviewers();
    second["id"] = serde_json::json!(8);
    second["title"] = serde_json::json!("other thing");
    second["source"] = serde_json::json!({ "branch": { "name": "feature/b" } });
    second["author"] =
        serde_json::json!({ "uuid": "{a}", "nickname": "ana", "display_name": "Ana" });
    second["reviewers"] = serde_json::json!([{ "uuid": "{d}", "display_name": "Dee" }]);
    second["participants"] = serde_json::json!([
        { "role": "REVIEWER", "state": null, "user": { "uuid": "{d}", "display_name": "Dee" } }
    ]);
    serde_json::json!([pr_with_reviewers(), second])
}

async fn mount_members(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/workspaces/acme/members"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "values": [
                { "user": { "uuid": "{a}", "display_name": "Ana", "nickname": "ana" } },
                { "user": { "uuid": "{b}", "display_name": "Bo", "nickname": "bo" } },
                { "user": { "uuid": "{d}", "display_name": "Dee", "nickname": "dee" } },
                { "user": { "uuid": "{sean}", "display_name": "Sean B", "nickname": "sean" } }
            ]
        })))
        .mount(server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/default-reviewers"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": [] })))
        .mount(server)
        .await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/permissions-config/users"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": [] })))
        .mount(server)
        .await;
}

/// `@me` and the review-state filters need to know who the token belongs to.
async fn mount_me(server: &MockServer, uuid: &str, name: &str) {
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "uuid": uuid,
            "display_name": name,
            "nickname": name.to_lowercase()
        })))
        .mount(server)
        .await;
}

#[tokio::test]
async fn state_draft_keeps_only_drafts() {
    let server = MockServer::start().await;
    let mut draft = pr_with_reviewers();
    draft["draft"] = serde_json::json!(true);
    let mut plain = pr_with_reviewers();
    plain["id"] = serde_json::json!(8);
    plain["title"] = serde_json::json!("not a draft");
    mount_list(&server, serde_json::json!([draft, plain])).await;

    let out = bb(&server)
        .args(["pr", "list", "--state", "draft"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("fix the thing"), "{text}");
    assert!(
        !text.contains("not a draft"),
        "draft filter not applied: {text}"
    );
}

/// `--state draft` still has to ask bitbucket for OPEN: DRAFT is not an api state.
#[tokio::test]
async fn state_draft_requests_open_from_the_api() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests"))
        .and(query_param("state", "OPEN"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": [] })))
        .mount(&server)
        .await;

    bb(&server)
        .args(["pr", "list", "--state", "draft"])
        .assert()
        .success();
}

#[tokio::test]
async fn reviewer_filter_keeps_only_prs_that_person_reviews() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    mount_members(&server).await;

    let out = bb(&server)
        .args(["pr", "list", "--reviewer", "bo"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("fix the thing"), "{text}");
    assert!(
        !text.contains("other thing"),
        "reviewer filter not applied: {text}"
    );
}

#[tokio::test]
async fn author_filter_keeps_only_that_authors_prs() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    mount_members(&server).await;

    let out = bb(&server)
        .args(["pr", "list", "--author", "ana"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("other thing"), "{text}");
    assert!(
        !text.contains("fix the thing"),
        "author filter not applied: {text}"
    );
}

#[tokio::test]
async fn author_me_uses_the_authenticated_account() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    mount_me(&server, "{a}", "Ana").await;

    let out = bb(&server)
        .args(["pr", "list", "--author", "@me"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("other thing"), "{text}");
    assert!(!text.contains("fix the thing"), "@me not resolved: {text}");
}

#[tokio::test]
async fn needs_my_review_keeps_prs_where_i_have_not_approved() {
    let server = MockServer::start().await;
    // I am Bo, who requested changes on 7 and is not a reviewer on 8.
    mount_list(&server, pr_pair()).await;
    mount_me(&server, "{b}", "Bo").await;

    let out = bb(&server)
        .args(["pr", "list", "--needs-my-review"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("fix the thing"), "{text}");
    assert!(
        !text.contains("other thing"),
        "not-a-reviewer pr kept: {text}"
    );
}

#[tokio::test]
async fn needs_my_review_drops_prs_i_already_approved() {
    let server = MockServer::start().await;
    // I am Ana, who approved 7 and does not review 8.
    mount_list(&server, pr_pair()).await;
    mount_me(&server, "{a}", "Ana").await;

    let out = bb(&server)
        .args(["pr", "list", "--needs-my-review"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        !text.contains("fix the thing"),
        "approved pr still listed: {text}"
    );
    assert!(!text.contains("other thing"), "{text}");
}

#[tokio::test]
async fn review_state_approved_keeps_only_what_i_approved() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    mount_me(&server, "{a}", "Ana").await;

    let out = bb(&server)
        .args(["pr", "list", "--review-state", "approved"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("fix the thing"), "{text}");
    assert!(!text.contains("other thing"), "{text}");
}

#[tokio::test]
async fn review_state_changes_requested_matches_my_rejection() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    mount_me(&server, "{b}", "Bo").await;

    let out = bb(&server)
        .args(["pr", "list", "--review-state", "changes-requested"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("fix the thing"), "{text}");
    assert!(!text.contains("other thing"), "{text}");
}

#[tokio::test]
async fn review_state_pending_matches_an_unreviewed_tag() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    // Cy is tagged on 7 but has no participant entry, so their state is Pending.
    // Cy is not tagged on 8 at all.
    mount_me(&server, "{c}", "Cy").await;

    let out = bb(&server)
        .args(["pr", "list", "--review-state", "pending"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("fix the thing"), "{text}");
    assert!(!text.contains("other thing"), "{text}");
}

/// `--author @me` and `--needs-my-review` both need "who am I"; they must share one
/// `GET /user` call rather than each fetching it independently.
#[tokio::test]
async fn author_me_and_needs_my_review_share_a_single_user_fetch() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "uuid": "{sean}",
            "display_name": "Sean B",
            "nickname": "sean"
        })))
        .expect(1)
        .mount(&server)
        .await;

    bb(&server)
        .args(["pr", "list", "--author", "@me", "--needs-my-review"])
        .assert()
        .success();
}

/// Filters must AND, not OR.
#[tokio::test]
async fn two_filters_intersect() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    mount_members(&server).await;

    // Dee reviews both; only 8 is authored by Ana.
    let out = bb(&server)
        .args(["pr", "list", "--reviewer", "dee", "--author", "ana"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("other thing"), "{text}");
    assert!(
        !text.contains("fix the thing"),
        "filters ORed instead of ANDed: {text}"
    );
}

#[tokio::test]
async fn an_invalid_review_state_is_rejected_before_any_request() {
    let server = MockServer::start().await;

    bb(&server)
        .args(["pr", "list", "--review-state", "nonsense"])
        .assert()
        .failure();
    assert!(
        server
            .received_requests()
            .await
            .unwrap_or_default()
            .is_empty(),
        "clap should reject the value before any http call"
    );
}

#[tokio::test]
async fn a_filter_matching_nothing_prints_an_empty_json_array() {
    let server = MockServer::start().await;
    mount_list(&server, pr_pair()).await;
    mount_members(&server).await;

    let out = bb(&server)
        .args([
            "pr",
            "list",
            "--reviewer",
            "bo",
            "--author",
            "ana",
            "--json",
        ])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let value: serde_json::Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("stdout did not parse as JSON: {e}\nstdout: {stdout}"));
    assert_eq!(value, serde_json::json!([]));
}

/// Two open pull requests by two different authors, so the "only fetch what
/// survived the other filters" behaviour is testable.
fn two_prs() -> serde_json::Value {
    serde_json::json!([
        {
            "id": 7,
            "title": "fix the thing",
            "state": "OPEN",
            "author": { "uuid": "{sean}", "nickname": "sean", "display_name": "Sean B" },
            "source": { "branch": { "name": "feature/a" } },
            "destination": { "branch": { "name": "main" } },
            "links": { "html": { "href": "https://bitbucket.org/acme/widgets/pull-requests/7" } }
        },
        {
            "id": 9,
            "title": "add the other thing",
            "state": "OPEN",
            "author": { "uuid": "{ana}", "nickname": "ana", "display_name": "Ana" },
            "source": { "branch": { "name": "feature/b" } },
            "destination": { "branch": { "name": "main" } },
            "links": { "html": { "href": "https://bitbucket.org/acme/widgets/pull-requests/9" } }
        }
    ])
}

async fn mount_statuses(server: &MockServer, id: u64, states: &[&str]) -> () {
    let values: Vec<serde_json::Value> = states
        .iter()
        .enumerate()
        .map(|(i, s)| {
            serde_json::json!({
                "key": format!("KEY{i}"),
                "name": format!("Check {i}"),
                "state": s,
                "url": format!("https://bitbucket.org/build/{id}/{i}")
            })
        })
        .collect();
    Mock::given(method("GET"))
        .and(path(format!(
            "/repositories/acme/widgets/pullrequests/{id}/statuses"
        )))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(serde_json::json!({ "values": values })),
        )
        .mount(server)
        .await;
}

/// The whole point of making the column opt-in: the default path must stay a
/// single request, however many pull requests come back.
#[tokio::test]
async fn list_without_build_never_touches_the_statuses_endpoint() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests/7/statuses"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    bb(&server)
        .args(["pr", "list", "--json"])
        .assert()
        .success();
}

#[tokio::test]
async fn build_flag_adds_the_column_with_the_rollup() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;
    mount_statuses(&server, 7, &["SUCCESSFUL", "FAILED"]).await;
    mount_statuses(&server, 9, &["SUCCESSFUL"]).await;

    let out = bb(&server)
        .args(["pr", "list", "--build"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();

    assert!(text.contains("BUILD"), "missing column header:\n{text}");
    assert!(text.contains("FAILED"), "missing rollup for pr 7:\n{text}");
    assert!(
        text.contains("SUCCESSFUL"),
        "missing rollup for pr 9:\n{text}"
    );
}

#[tokio::test]
async fn build_json_carries_rollup_and_every_status() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;
    mount_statuses(&server, 7, &["SUCCESSFUL", "FAILED"]).await;
    mount_statuses(&server, 9, &["SUCCESSFUL"]).await;

    let out = bb(&server)
        .args(["pr", "list", "--build", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rows: serde_json::Value = serde_json::from_slice(&out).unwrap();

    let seven = rows
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["id"] == 7)
        .unwrap();
    assert_eq!(seven["build_state"], "failed");
    assert_eq!(seven["build"].as_array().unwrap().len(), 2);
    assert_eq!(seven["build"][1]["key"], "KEY1");
}

/// `statuses_for` uses `try_collect`: the first failing status request aborts
/// the whole listing rather than rendering partial rows with blank cells.
#[tokio::test]
async fn build_flag_fails_the_whole_list_when_one_status_request_fails() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;
    mount_statuses(&server, 7, &["SUCCESSFUL"]).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests/9/statuses"))
        .respond_with(ResponseTemplate::new(429))
        .mount(&server)
        .await;

    bb(&server)
        .args(["pr", "list", "--build", "--json"])
        .assert()
        .failure();
}

/// Existing callers must see the same shape they see today.
#[tokio::test]
async fn json_without_build_has_no_build_fields() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;

    let out = bb(&server)
        .args(["pr", "list", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rows: serde_json::Value = serde_json::from_slice(&out).unwrap();

    let first = &rows.as_array().unwrap()[0];
    assert!(first.get("build").is_none(), "leaked build: {first}");
    assert!(
        first.get("build_state").is_none(),
        "leaked build_state: {first}"
    );
}

#[tokio::test]
async fn build_status_filter_keeps_only_matching_prs_and_implies_the_column() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;
    mount_statuses(&server, 7, &["FAILED"]).await;
    mount_statuses(&server, 9, &["SUCCESSFUL"]).await;

    let out = bb(&server)
        .args(["pr", "list", "--build-status", "failed", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rows: serde_json::Value = serde_json::from_slice(&out).unwrap();

    assert_eq!(rows.as_array().unwrap().len(), 1);
    assert_eq!(rows[0]["id"], 7);
    // implied column: the fields are present without --build
    assert_eq!(rows[0]["build_state"], "failed");
}

#[tokio::test]
async fn build_status_none_matches_a_pr_with_no_checks() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;
    mount_statuses(&server, 7, &["FAILED"]).await;
    mount_statuses(&server, 9, &[]).await;

    let out = bb(&server)
        .args(["pr", "list", "--build-status", "none", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rows: serde_json::Value = serde_json::from_slice(&out).unwrap();

    assert_eq!(rows.as_array().unwrap().len(), 1);
    assert_eq!(rows[0]["id"], 9);
    assert_eq!(rows[0]["build_state"], "none");
}

/// Statuses are fetched after the other filters, so a pull request filtered out
/// by `--author` must cost no request at all.
#[tokio::test]
async fn statuses_are_fetched_only_for_surviving_rows() {
    let server = MockServer::start().await;
    mount_list(&server, two_prs()).await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "uuid": "{sean}", "nickname": "sean", "display_name": "Sean B"
        })))
        .mount(&server)
        .await;
    mount_statuses(&server, 7, &["FAILED"]).await;
    Mock::given(method("GET"))
        .and(path("/repositories/acme/widgets/pullrequests/9/statuses"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    bb(&server)
        .args(["pr", "list", "--author", "@me", "--build", "--json"])
        .assert()
        .success();
}

/// JSON purity on the empty path: `print_table`'s "nothing to show" line must
/// not escape, and neither must a spinner.
#[tokio::test]
async fn empty_result_with_build_prints_only_an_empty_json_array() {
    let server = MockServer::start().await;
    mount_list(&server, serde_json::json!([])).await;

    let out = bb(&server)
        .args(["pr", "list", "--build", "--json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();

    assert_eq!(text.trim(), "[]");
}