prlens 0.1.1

One queue for all your PRs — aggregates GitHub and Bitbucket review requests into a single interactive view
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
// Integration tests for GitHubProvider against a wiremock HTTP mock server.
// These tests validate the full Provider trait contract without hitting the real GitHub API:
//   - AUTH-01: list_prs() returns correctly mapped PullRequest from search response
//   - AUTH-01 boundary: list_prs() returns empty Vec when no PRs match
//   - D-02: re-review detection works when new commits exist since approval
//   - ARCH-04: second list_prs() call within 60s returns cached data without API call

use prlens::config::GithubConfig;
use prlens::models::ReviewStatus;
use prlens::provider::github::GitHubProvider;
use prlens::provider::Provider;
use serde_json::json;
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

// Install the ring CryptoProvider for rustls before each test that makes HTTP requests.
// Both ring and aws-lc-rs are in the transitive dependency tree (via reqwest/octocrab).
// When both features are present, rustls cannot auto-detect the provider — we must
// install one explicitly. `install_default()` is idempotent (no-op if already set).
fn ensure_crypto_provider() {
    let _ = rustls::crypto::ring::default_provider().install_default();
}

// ---------------------------------------------------------------------------
// Helper: base Author fixture used in multiple tests
// ---------------------------------------------------------------------------

fn author_fixture(login: &str, id: u64) -> serde_json::Value {
    json!({
        "login": login,
        "id": id,
        "node_id": "U_testnode",
        "avatar_url": "https://avatars.githubusercontent.com/u/1",
        "gravatar_id": "",
        "url": format!("https://api.github.com/users/{}", login),
        "html_url": format!("https://github.com/{}", login),
        "followers_url": format!("https://api.github.com/users/{}/followers", login),
        "following_url": format!("https://api.github.com/users/{}/following{{/other_user}}", login),
        "gists_url": format!("https://api.github.com/users/{}/gists{{/gist_id}}", login),
        "starred_url": format!("https://api.github.com/users/{}/starred{{/owner}}{{/repo}}", login),
        "subscriptions_url": format!("https://api.github.com/users/{}/subscriptions", login),
        "organizations_url": format!("https://api.github.com/users/{}/orgs", login),
        "repos_url": format!("https://api.github.com/users/{}/repos", login),
        "events_url": format!("https://api.github.com/users/{}/events{{/privacy}}", login),
        "received_events_url": format!("https://api.github.com/users/{}/received_events", login),
        "type": "User",
        "site_admin": false
    })
}

// ---------------------------------------------------------------------------
// Helper: a minimal search Issue fixture
// ---------------------------------------------------------------------------

fn search_issue_fixture(
    number: u64,
    title: &str,
    author_login: &str,
    author_id: u64,
    owner: &str,
    repo: &str,
) -> serde_json::Value {
    json!({
        "id": number * 1000,
        "node_id": format!("I_test{}", number),
        "url": format!("https://api.github.com/repos/{}/{}/issues/{}", owner, repo, number),
        "repository_url": format!("https://api.github.com/repos/{}/{}", owner, repo),
        "labels_url": format!("https://api.github.com/repos/{}/{}/issues/{}/labels{{/name}}", owner, repo, number),
        "comments_url": format!("https://api.github.com/repos/{}/{}/issues/{}/comments", owner, repo, number),
        "events_url": format!("https://api.github.com/repos/{}/{}/issues/{}/events", owner, repo, number),
        "html_url": format!("https://github.com/{}/{}/pull/{}", owner, repo, number),
        "number": number,
        "state": "open",
        "title": title,
        "user": author_fixture(author_login, author_id),
        "labels": [],
        "assignee": null,
        "assignees": [],
        "locked": false,
        "comments": 0,
        "created_at": "2026-05-27T10:00:00Z",
        "updated_at": "2026-05-27T10:00:00Z",
        "pull_request": {
            "url": format!("https://api.github.com/repos/{}/{}/pulls/{}", owner, repo, number),
            "html_url": format!("https://github.com/{}/{}/pull/{}", owner, repo, number),
            "diff_url": format!("https://github.com/{}/{}/pull/{}.diff", owner, repo, number),
            "patch_url": format!("https://github.com/{}/{}/pull/{}.patch", owner, repo, number)
        }
    })
}

// ---------------------------------------------------------------------------
// Helper: mount the /user endpoint on a mock server
// ---------------------------------------------------------------------------

async fn mount_user_endpoint(mock_server: &MockServer, login: &str, id: u64) {
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(ResponseTemplate::new(200).set_body_json(author_fixture(login, id)))
        .mount(mock_server)
        .await;
}

// ---------------------------------------------------------------------------
// Helper: mount an empty re-review search response (no approved PRs)
// ---------------------------------------------------------------------------

async fn mount_empty_re_review_search(mock_server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/search/issues"))
        .and(query_param("q", "is:pr is:open reviewed-by:@me review:approved"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "total_count": 0,
            "incomplete_results": false,
            "items": []
        })))
        .mount(mock_server)
        .await;
}

// ---------------------------------------------------------------------------
// TEST 1: list_prs() maps a search result to PullRequest correctly (AUTH-01, D-03)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn list_prs_returns_search_results() {
    ensure_crypto_provider();
    let mock_server = MockServer::start().await;
    let temp_dir = tempfile::TempDir::new().expect("TempDir failed");
    let cache_file = temp_dir.path().join("github.json");

    // Mount current user endpoint
    mount_user_endpoint(&mock_server, "testuser", 99).await;

    // Mount primary search: 1 PR review-requested
    Mock::given(method("GET"))
        .and(path("/search/issues"))
        .and(query_param("q", "is:pr is:open review-requested:@me"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "total_count": 1,
            "incomplete_results": false,
            "items": [
                search_issue_fixture(42, "feat: add feature", "alice", 1, "owner", "repo")
            ]
        })))
        .mount(&mock_server)
        .await;

    // Mount re-review search: no approved PRs requiring re-review
    mount_empty_re_review_search(&mock_server).await;

    let provider = GitHubProvider::new_with_base_url(
        GithubConfig::default(),
        mock_server.uri(),
        cache_file,
    );

    let result = provider.list_prs().await.unwrap();

    assert_eq!(result.len(), 1, "Expected exactly 1 PR");
    assert_eq!(result[0].number, 42);
    assert_eq!(result[0].title, "feat: add feature");
    assert_eq!(result[0].provider, "github");
    assert_eq!(result[0].author.login, "alice");
    assert_eq!(result[0].repo_full_name, "owner/repo");
}

// ---------------------------------------------------------------------------
// TEST 2: list_prs() returns empty Vec when no PRs match (AUTH-01 boundary)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn list_prs_empty_when_no_prs() {
    ensure_crypto_provider();
    let mock_server = MockServer::start().await;
    let temp_dir = tempfile::TempDir::new().expect("TempDir failed");
    let cache_file = temp_dir.path().join("github.json");

    // Mount current user endpoint
    mount_user_endpoint(&mock_server, "testuser", 99).await;

    // Mount primary search: 0 PRs
    Mock::given(method("GET"))
        .and(path("/search/issues"))
        .and(query_param("q", "is:pr is:open review-requested:@me"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "total_count": 0,
            "incomplete_results": false,
            "items": []
        })))
        .mount(&mock_server)
        .await;

    // Mount re-review search: no approved PRs
    mount_empty_re_review_search(&mock_server).await;

    let provider = GitHubProvider::new_with_base_url(
        GithubConfig::default(),
        mock_server.uri(),
        cache_file,
    );

    let result = provider.list_prs().await;
    assert!(result.is_ok(), "Expected Ok result, got: {:?}", result.err());
    assert_eq!(result.unwrap().len(), 0, "Expected empty Vec");
}

// ---------------------------------------------------------------------------
// TEST 3: re-review detection — PR shows as InReview when user approved
//         but new commits were pushed since (D-02, D-03)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn re_review_detected() {
    ensure_crypto_provider();
    let mock_server = MockServer::start().await;
    let temp_dir = tempfile::TempDir::new().expect("TempDir failed");
    let cache_file = temp_dir.path().join("github.json");

    // Mount current user endpoint
    mount_user_endpoint(&mock_server, "testuser", 99).await;

    // Mount primary search: no review-requested PRs
    Mock::given(method("GET"))
        .and(path("/search/issues"))
        .and(query_param("q", "is:pr is:open review-requested:@me"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "total_count": 0,
            "incomplete_results": false,
            "items": []
        })))
        .mount(&mock_server)
        .await;

    // Mount re-review candidate search: PR #99 where user already approved
    Mock::given(method("GET"))
        .and(path("/search/issues"))
        .and(query_param("q", "is:pr is:open reviewed-by:@me review:approved"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "total_count": 1,
            "incomplete_results": false,
            "items": [
                search_issue_fixture(99, "old feature", "prauthor", 2, "owner", "repo")
            ]
        })))
        .mount(&mock_server)
        .await;

    // Mount list_reviews for PR #99: testuser approved at commit abc123
    Mock::given(method("GET"))
        .and(path("/repos/owner/repo/pulls/99/reviews"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!([
            {
                "id": 1,
                "node_id": "PRR_test1",
                "html_url": "https://github.com/owner/repo/pull/99#pullrequestreview-1",
                "user": author_fixture("testuser", 99),
                "body": null,
                "commit_id": "abc123",
                "state": "APPROVED",
                "submitted_at": "2026-05-20T10:00:00Z",
                "pull_request_url": "https://api.github.com/repos/owner/repo/pulls/99",
                "author_association": "COLLABORATOR",
                "_links": {
                    "html": { "href": "https://github.com/owner/repo/pull/99#pullrequestreview-1" },
                    "pull_request": { "href": "https://api.github.com/repos/owner/repo/pulls/99" }
                }
            }
        ])))
        .mount(&mock_server)
        .await;

    // Mount full PR fetch for PR #99: current head SHA is def456 (differs from approval commit abc123)
    Mock::given(method("GET"))
        .and(path("/repos/owner/repo/pulls/99"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "url": "https://api.github.com/repos/owner/repo/pulls/99",
            "id": 99000,
            "node_id": "PR_test99",
            "html_url": "https://github.com/owner/repo/pull/99",
            "diff_url": "https://github.com/owner/repo/pull/99.diff",
            "patch_url": "https://github.com/owner/repo/pull/99.patch",
            "issue_url": "https://api.github.com/repos/owner/repo/issues/99",
            "commits_url": "https://api.github.com/repos/owner/repo/pulls/99/commits",
            "review_comments_url": "https://api.github.com/repos/owner/repo/pulls/99/comments",
            "review_comment_url": "https://api.github.com/repos/owner/repo/pulls/comments{/number}",
            "comments_url": "https://api.github.com/repos/owner/repo/issues/99/comments",
            "statuses_url": "https://api.github.com/repos/owner/repo/statuses/def456",
            "number": 99,
            "state": "open",
            "locked": false,
            "maintainer_can_modify": false,
            "title": "old feature",
            "user": author_fixture("prauthor", 2),
            "body": null,
            "labels": [],
            "assignees": [],
            "requested_reviewers": [],
            "requested_teams": [],
            "created_at": "2026-05-01T10:00:00Z",
            "updated_at": "2026-05-27T10:00:00Z",
            "merged": false,
            "head": {
                "ref": "feat/old",
                "sha": "def456",
                "label": "owner:feat/old",
                "user": author_fixture("owner", 1),
                "repo": null
            },
            "base": {
                "ref": "main",
                "sha": "000000",
                "label": "owner:main",
                "user": author_fixture("owner", 1),
                "repo": null
            },
            "_links": {
                "self": { "href": "https://api.github.com/repos/owner/repo/pulls/99" },
                "html": { "href": "https://github.com/owner/repo/pull/99" }
            },
            "author_association": "NONE",
            "additions": 0,
            "deletions": 0,
            "changed_files": 0,
            "commits": 1,
            "review_comments": 0,
            "comments": 0
        })))
        .mount(&mock_server)
        .await;

    let provider = GitHubProvider::new_with_base_url(
        GithubConfig::default(),
        mock_server.uri(),
        cache_file,
    );

    let result = provider.list_prs().await.unwrap();

    assert_eq!(result.len(), 1, "Expected exactly 1 re-review PR");
    assert_eq!(result[0].number, 99);
    assert!(
        matches!(result[0].review_status, ReviewStatus::InReview),
        "Expected ReviewStatus::InReview, got {:?}",
        result[0].review_status
    );
}

// ---------------------------------------------------------------------------
// TEST 4: cache_hit_skips_api_call — second call returns cached data (ARCH-04)
// Cache is pre-populated; mock server has no routes so any API call returns 404.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn cache_hit_skips_api_call() {
    let temp_dir = tempfile::TempDir::new().expect("TempDir failed");
    let cache_file = temp_dir.path().join("github.json");

    // Write a fresh CacheEntry<Vec<PullRequest>> directly to the cache file.
    // Use serde_json to construct the exact shape that cache::read_cache expects.
    let now = chrono::Utc::now().to_rfc3339();
    let cached_pr_json = json!({
        "fetched_at": now,
        "ttl_seconds": 60,
        "data": [{
            "id": {
                "provider": "github",
                "owner": "owner",
                "repo": "repo",
                "number": 7
            },
            "number": 7,
            "title": "cached pr",
            "url": "https://github.com/owner/repo/pull/7",
            "author": {
                "login": "cacheduser",
                "display_name": null,
                "avatar_url": null
            },
            "reviewers": [],
            "repo_full_name": "owner/repo",
            "provider": "github",
            "head_branch": "",
            "base_branch": "",
            "state": "Open",
            "review_status": "NeedsReview",
            "ci_status": null,
            "draft": false,
            "created_at": "2026-05-27T10:00:00Z",
            "updated_at": "2026-05-27T10:00:00Z",
            "labels": [],
            "comment_count": 0,
            "additions": null,
            "deletions": null
        }]
    });

    std::fs::write(&cache_file, cached_pr_json.to_string()).expect("Failed to write cache file");

    // Start a mock server with NO routes — any HTTP call will return 404.
    let mock_server = MockServer::start().await;

    let provider = GitHubProvider::new_with_base_url(
        GithubConfig::default(),
        mock_server.uri(),
        cache_file,
    );

    let result = provider.list_prs().await.unwrap();

    assert_eq!(result.len(), 1, "Expected 1 cached PR");
    assert_eq!(result[0].number, 7, "Expected PR number 7 from cache");
    assert_eq!(result[0].title, "cached pr");

    // Verify that mock server received zero requests (cache bypass)
    let received = mock_server.received_requests().await.unwrap();
    assert!(
        received.is_empty(),
        "Expected 0 API calls on cache hit, got: {} request(s)",
        received.len()
    );
}