forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiB3cdd794Tahinli26 minutes ago331 commits

pull_reviews.rs615 lines, 19.7 KiBHistoryRawDownload
1use forge_core::reviews::{ReviewState, Side};
2use forge_core::{IssueState, NewPull, PullRequest, User, Visibility};
3use forge_git::GitEnv;
4use topcoat::router::request::Request;
5use topcoat::router::{Body, Router, to_bytes};
6
7use forge_web_app::auth::{SESSION_COOKIE, percent_encode};
8use forge_web_app::test_support::fixture::{Fixture, OWNER, REPO, git};
9
10fn cookie(token: &str) -> String {
11 format!("__Host-{SESSION_COOKIE}={token}")
12}
13
14async fn send(
15 router: &Router,
16 method: &str,
17 uri: &str,
18 token: Option<&str>,
19 form: Option<String>,
20) -> (u16, Option<String>, String) {
21 let mut req = Request::builder().method(method).uri(uri);
22 if let Some(token) = token {
23 req = req.header("cookie", cookie(token));
24 }
25 let body = match form {
26 Some(form) => {
27 req = req.header("content-type", "application/x-www-form-urlencoded");
28 Body::from(form)
29 }
30 None => Body::empty(),
31 };
32 let res = router.handle(req.body(body).unwrap()).await;
33 let status = res.status().as_u16();
34 let location = res
35 .headers()
36 .get("location")
37 .map(|v| v.to_str().unwrap().to_owned());
38 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
39 (
40 status,
41 location,
42 String::from_utf8_lossy(&bytes).into_owned(),
43 )
44}
45
46async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
47 let user = fx
48 .store
49 .create_user(name, None, "not-a-real-hash", false)
50 .await
51 .unwrap();
52 forge_web_app::test_support::create_session(
53 &fx.store,
54 &user.id,
55 token,
56 &format!("{token}-csrf"),
57 )
58 .await;
59 user
60}
61
62async fn owner_session(fx: &Fixture) {
63 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
64 forge_web_app::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf")
65 .await;
66}
67
68fn csrf_form(token: &str, pairs: &[(&str, &str)]) -> String {
69 let mut form = format!("csrf={}", percent_encode(&format!("{token}-csrf")));
70 for (key, value) in pairs {
71 form.push_str(&format!("&{key}={}", percent_encode(value)));
72 }
73 form
74}
75
76async fn post_form(
77 fx: &Fixture,
78 uri: &str,
79 token: &str,
80 pairs: &[(&str, &str)],
81) -> (u16, Option<String>, String) {
82 send(
83 &fx.router,
84 "POST",
85 uri,
86 Some(token),
87 Some(csrf_form(token, pairs)),
88 )
89 .await
90}
91
92async fn pull(fx: &Fixture, number: i64) -> PullRequest {
93 let repo = fx
94 .store
95 .repo_by_owner_and_name(OWNER, REPO)
96 .await
97 .unwrap()
98 .unwrap();
99 fx.store
100 .pull_by_number(&repo.id, number)
101 .await
102 .unwrap()
103 .unwrap()
104}
105
106async fn open_pull(fx: &Fixture) -> i64 {
107 let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);
108 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
109 std::fs::write(fx.work.join("a.txt"), "one\nchanged\nthree\n").unwrap();
110 git(&fx.work, &["add", "-A"]);
111 git(&fx.work, &["commit", "-q", "-m", "Change a.txt"]);
112 let head_oid = git(&fx.work, &["rev-parse", "HEAD"]);
113 git(
114 &fx.work,
115 &[
116 "push",
117 "-q",
118 &fx.bare.to_string_lossy(),
119 "HEAD:refs/heads/feature",
120 ],
121 );
122
123 let repo = fx
124 .store
125 .repo_by_owner_and_name(OWNER, REPO)
126 .await
127 .unwrap()
128 .unwrap();
129 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
130 let pr = fx
131 .store
132 .create_pull(&NewPull {
133 repo_id: &repo.id,
134 author_id: &owner.id,
135 title: "Change a",
136 body: "",
137 base_branch: "main",
138 head_repo_id: &repo.id,
139 head_branch: "feature",
140 head_oid: &head_oid,
141 base_oid: &base_oid,
142 })
143 .await
144 .unwrap();
145 let env = GitEnv {
146 git_bin: "git".into(),
147 data_dir: fx.work.clone(),
148 };
149 forge_git::pulls::fetch_into_pull_ref(&env, &fx.bare, &fx.bare, &head_oid, pr.issue.number)
150 .await
151 .unwrap();
152 pr.issue.number
153}
154
155async fn head_of(fx: &Fixture, number: i64) -> String {
156 pull(fx, number).await.head_oid
157}
158
159async fn comment_on(
160 fx: &Fixture,
161 number: i64,
162 token: &str,
163 line: &str,
164 body: &str,
165) -> (u16, Option<String>) {
166 let head = head_of(fx, number).await;
167 let (status, location, _) = post_form(
168 fx,
169 &format!("/tahinli/demo/pulls/{number}/review_comments"),
170 token,
171 &[
172 ("file_index", "0"),
173 ("side", "new"),
174 ("line", line),
175 ("head_oid", head.as_str()),
176 ("action", "single"),
177 ("body", body),
178 ],
179 )
180 .await;
181 (status, location)
182}
183
184async fn root_at(fx: &Fixture, number: i64, index: usize) -> String {
185 let pr = pull(fx, number).await;
186 fx.store.review_threads(&pr.issue.id, None).await.unwrap()[index]
187 .root
188 .id
189 .clone()
190}
191
192fn suggestion(text: &str) -> String {
193 format!("Try this:\n```suggestion\n{text}\n```")
194}
195
196async fn apply_as(
197 fx: &Fixture,
198 number: i64,
199 token: &str,
200 comment_id: &str,
201) -> (u16, Option<String>) {
202 let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply");
203 let (status, location, _) =
204 post_form(fx, &uri, token, &[("block", "0"), ("return", "files")]).await;
205 (status, location)
206}
207
208#[tokio::test]
209async fn comment_rules_and_pending_review_on_one_pull() {
210 let fx = Fixture::new(Visibility::Public).await;
211 owner_session(&fx).await;
212 let number = open_pull(&fx).await;
213 let pr = pull(&fx, number).await;
214
215 let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await;
216 assert_eq!(status, 303, "outside diff");
217 assert!(
218 location.unwrap().contains("review_error=bad_line"),
219 "outside diff"
220 );
221 assert!(
222 fx.store
223 .review_threads(&pr.issue.id, None)
224 .await
225 .unwrap()
226 .is_empty(),
227 "outside diff left a thread"
228 );
229
230 let zero = "0".repeat(40);
231 let (status, location, _) = post_form(
232 &fx,
233 &format!("/tahinli/demo/pulls/{number}/review_comments"),
234 "tahinli",
235 &[
236 ("file_index", "0"),
237 ("side", "new"),
238 ("line", "2"),
239 ("head_oid", zero.as_str()),
240 ("action", "single"),
241 ("body", "Stale"),
242 ],
243 )
244 .await;
245 assert_eq!(status, 303, "stale head");
246 assert_eq!(
247 location.as_deref(),
248 Some(format!("/tahinli/demo/pulls/{number}/files?review_error=stale").as_str()),
249 "stale head"
250 );
251 assert!(
252 fx.store
253 .review_threads(&pr.issue.id, None)
254 .await
255 .unwrap()
256 .is_empty(),
257 "stale head left a thread"
258 );
259
260 let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await;
261 assert_eq!(status, 303, "single comment");
262 assert_eq!(
263 location.as_deref(),
264 Some(format!("/tahinli/demo/pulls/{number}/files#L-0-new-2").as_str()),
265 "single comment"
266 );
267 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
268 assert_eq!(threads.len(), 1, "single comment");
269 let root = &threads[0].root;
270 assert_eq!(
271 (root.path.as_str(), root.side, root.line),
272 ("a.txt", Side::New, 2),
273 "single comment"
274 );
275 assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment");
276 assert!(!root.pending, "single comment");
277
278 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
279 let head = pr.head_oid.clone();
280 let (status, _, _) = post_form(
281 &fx,
282 &format!("/tahinli/demo/pulls/{number}/review_comments"),
283 "tahinli",
284 &[
285 ("file_index", "0"),
286 ("side", "new"),
287 ("line", "2"),
288 ("head_oid", head.as_str()),
289 ("action", "review"),
290 ("body", "Draft"),
291 ],
292 )
293 .await;
294 assert_eq!(status, 303, "pending start");
295 assert_eq!(
296 fx.store
297 .review_threads(&pr.issue.id, None)
298 .await
299 .unwrap()
300 .len(),
301 1,
302 "pending thread hidden from everyone"
303 );
304 let mine = fx
305 .store
306 .review_threads(&pr.issue.id, Some(&tahinli.id))
307 .await
308 .unwrap();
309 assert_eq!(mine.len(), 2, "author sees the pending thread");
310 assert!(
311 mine.iter().any(|t| t.root.pending),
312 "the author's draft is pending"
313 );
314
315 let form = csrf_form("tahinli", &[("state", "comment"), ("body", "Done")]);
316 let (status, _, _) = send(
317 &fx.router,
318 "POST",
319 &format!("/tahinli/demo/pulls/{number}/reviews"),
320 Some("tahinli"),
321 Some(form),
322 )
323 .await;
324 assert_eq!(status, 303, "submit review");
325 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
326 assert_eq!(threads.len(), 2, "submitted review is public");
327 assert!(threads.iter().all(|t| !t.root.pending), "submitted review");
328
329 let uri = format!("/tahinli/demo/pulls/{number}/review_comments");
330 let form = csrf_form(
331 "tahinli",
332 &[
333 ("file_index", "0"),
334 ("side", "new"),
335 ("line", "2"),
336 ("head_oid", head.as_str()),
337 ("action", "single"),
338 ("body", "Anon"),
339 ],
340 );
341 let (status, location, _) = send(&fx.router, "POST", &uri, None, Some(form)).await;
342 assert_eq!(status, 303, "anonymous write");
343 assert!(location.unwrap().starts_with("/login"), "anonymous write");
344 let form = format!("file_index=0&side=new&line=2&head_oid={head}&action=single&body=NoCsrf");
345 let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
346 assert_eq!(status, 403, "missing csrf");
347}
348
349#[tokio::test]
350async fn thread_reply_edit_resolve_and_delete() {
351 let fx = Fixture::new(Visibility::Public).await;
352 owner_session(&fx).await;
353 sign_in(&fx, "bob", "bob").await;
354 let number = open_pull(&fx).await;
355 comment_on(&fx, number, "tahinli", "2", "First").await;
356 let pr = pull(&fx, number).await;
357 let root = root_at(&fx, number, 0).await;
358
359 let (status, location, _) = post_form(
360 &fx,
361 &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"),
362 "bob",
363 &[("body", "Reply")],
364 )
365 .await;
366 assert_eq!(status, 303, "reply");
367 assert_eq!(
368 location.as_deref(),
369 Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()),
370 "reply"
371 );
372 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
373 assert_eq!(threads[0].replies.len(), 1, "reply");
374 assert_eq!(threads[0].replies[0].author_name, "bob", "reply");
375
376 let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit");
377 let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await;
378 assert_eq!(status, 200, "edit form");
379 assert!(body.contains("Save comment"), "edit form");
380 let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await;
381 assert_eq!(status, 403, "edit form for a non-author");
382 let (status, _, _) = post_form(&fx, &edit, "bob", &[("body", "Hijacked")]).await;
383 assert_eq!(status, 403, "edit by a non-author");
384 let (status, location, _) = post_form(&fx, &edit, "tahinli", &[("body", "Edited")]).await;
385 assert_eq!(status, 303, "edit");
386 assert_eq!(
387 location.as_deref(),
388 Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()),
389 "edit"
390 );
391 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
392 assert_eq!(threads[0].root.body, "Edited", "edit");
393
394 let resolve = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/resolve");
395 let (status, _, _) = post_form(&fx, &resolve, "bob", &[("resolved", "1")]).await;
396 assert_eq!(status, 403, "resolve by a reader");
397 let (status, _, _) = post_form(&fx, &resolve, "tahinli", &[("resolved", "1")]).await;
398 assert_eq!(status, 303, "resolve");
399 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
400 assert!(threads[0].root.resolved, "resolve");
401
402 comment_on(&fx, number, "tahinli", "2", "Doomed").await;
403 let doomed = root_at(&fx, number, 1).await;
404 let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{doomed}/delete");
405 let (status, _, _) = post_form(&fx, &uri, "bob", &[]).await;
406 assert_eq!(status, 403, "delete by a non-author");
407 let (status, _, _) = post_form(&fx, &uri, "tahinli", &[]).await;
408 assert_eq!(status, 303, "delete");
409 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
410 assert_eq!(threads.len(), 1, "delete");
411 assert_eq!(threads[0].root.id, root, "delete kept the other thread");
412}
413
414#[tokio::test]
415async fn reviews_approve_then_close_the_pull() {
416 let fx = Fixture::new(Visibility::Public).await;
417 owner_session(&fx).await;
418 sign_in(&fx, "bob", "bob").await;
419 let number = open_pull(&fx).await;
420 let pr = pull(&fx, number).await;
421 let uri = format!("/tahinli/demo/pulls/{number}/reviews");
422
423 let (status, location, _) = post_form(&fx, &uri, "bob", &[("state", "approve")]).await;
424 assert_eq!(status, 303, "reader approval");
425 assert!(location.unwrap().contains("#review-"), "reader approval");
426 let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap();
427 assert_eq!(reviews.len(), 1, "reader approval");
428 assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval");
429
430 let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await;
431 assert_eq!(status, 303, "author approval");
432 assert_eq!(
433 location.as_deref(),
434 Some(format!("/tahinli/demo/pulls/{number}?review_error=own_pr").as_str()),
435 "author approval"
436 );
437 assert_eq!(
438 fx.store.list_reviews(&pr.issue.id).await.unwrap().len(),
439 1,
440 "author approval"
441 );
442
443 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
444 fx.store
445 .set_issue_state(
446 &pr.issue.id,
447 Some(&tahinli.id),
448 IssueState::Closed,
449 None,
450 serde_json::Value::Null,
451 )
452 .await
453 .unwrap();
454 let (status, location) = comment_on(&fx, number, "tahinli", "2", "After close").await;
455 assert_eq!(status, 303, "comment on a closed pull");
456 assert!(
457 location.unwrap().contains("#L-0-new-2"),
458 "comment on a closed pull"
459 );
460 let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await;
461 assert_eq!(status, 303, "review on a closed pull");
462 assert!(
463 location.unwrap().ends_with("?review_error=closed"),
464 "review on a closed pull"
465 );
466}
467
468#[tokio::test]
469async fn dismiss_needs_write_and_a_reason() {
470 let fx = Fixture::new(Visibility::Public).await;
471 owner_session(&fx).await;
472 sign_in(&fx, "bob", "bob").await;
473 let number = open_pull(&fx).await;
474 let pr = pull(&fx, number).await;
475 let (status, _, _) = post_form(
476 &fx,
477 &format!("/tahinli/demo/pulls/{number}/reviews"),
478 "bob",
479 &[("state", "request_changes")],
480 )
481 .await;
482 assert_eq!(status, 303, "setup review");
483 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
484 let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id);
485
486 let (status, _, _) = post_form(&fx, &uri, "bob", &[("reason", "mine")]).await;
487 assert_eq!(status, 403, "dismiss by a reader");
488
489 let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("reason", " ")]).await;
490 assert_eq!(status, 303, "blank reason");
491 assert!(
492 location.unwrap().ends_with("?review_error=empty"),
493 "blank reason"
494 );
495
496 let (status, _, _) = post_form(&fx, &uri, "tahinli", &[("reason", "Addressed")]).await;
497 assert_eq!(status, 303, "dismiss");
498 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
499 assert_eq!(review.state, ReviewState::Dismissed, "dismiss");
500}
501
502#[tokio::test]
503async fn suggestions_reader_outdated_and_apply() {
504 let fx = Fixture::new(Visibility::Public).await;
505 owner_session(&fx).await;
506 sign_in(&fx, "rita", "rita").await;
507 let number = open_pull(&fx).await;
508 let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
509 assert_eq!(status, 303, "first suggestion");
510 let first = root_at(&fx, number, 0).await;
511
512 let page = get(&fx, number, "rita").await;
513 assert!(page.contains("Suggested change"), "the diff still shows");
514 assert!(
515 !page.contains("Apply suggestion"),
516 "no apply button without push access"
517 );
518 let (status, location) = apply_as(&fx, number, "rita", &first).await;
519 assert_eq!(status, 303, "reader apply");
520 assert!(
521 location.unwrap().contains("review_error=no_push"),
522 "reader apply"
523 );
524
525 let pr = pull(&fx, number).await;
526 std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap();
527 git(&fx.work, &["commit", "-q", "-am", "Move line 2"]);
528 let moved = git(&fx.work, &["rev-parse", "HEAD"]);
529 git(
530 &fx.work,
531 &[
532 "push",
533 "-q",
534 &fx.bare.to_string_lossy(),
535 "HEAD:refs/heads/feature",
536 ],
537 );
538 fx.store
539 .update_pull_head(&pr.issue.id, &moved)
540 .await
541 .unwrap();
542
543 let page = get(&fx, number, "tahinli").await;
544 assert!(
545 page.contains("This suggestion is outdated"),
546 "outdated note shown"
547 );
548 assert!(
549 !page.contains("Apply suggestion"),
550 "no apply button when outdated"
551 );
552 let (status, location) = apply_as(&fx, number, "tahinli", &first).await;
553 assert_eq!(status, 303, "outdated apply");
554 assert!(
555 location.unwrap().contains("review_error=outdated"),
556 "outdated apply"
557 );
558 assert_eq!(
559 git(&fx.bare, &["rev-parse", "feature"]),
560 moved,
561 "nothing was committed"
562 );
563 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
564 assert!(
565 !threads[0].root.resolved,
566 "a refused apply leaves the thread open"
567 );
568
569 let before = pull(&fx, number).await.head_oid;
570 assert_eq!(before, moved, "the head is the moved commit");
571 let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
572 assert_eq!(status, 303, "fresh suggestion");
573 let second = root_at(&fx, number, 1).await;
574 let (status, location) = apply_as(&fx, number, "tahinli", &second).await;
575 assert_eq!(status, 303, "apply");
576 assert!(!location.unwrap().contains("review_error"), "apply");
577
578 let pr = pull(&fx, number).await;
579 assert_ne!(
580 pr.head_oid, before,
581 "the head moved to the suggestion commit"
582 );
583 assert_eq!(
584 git(&fx.bare, &["show", &format!("{}:a.txt", pr.head_oid)]),
585 "one\ntwo!\nthree",
586 "apply"
587 );
588 assert_eq!(
589 git(&fx.bare, &["log", "-1", "--format=%an", &pr.head_oid]),
590 "tahinli",
591 "apply"
592 );
593 let message = git(&fx.bare, &["log", "-1", "--format=%B", &pr.head_oid]);
594 assert!(
595 message.starts_with("Apply suggestion from review"),
596 "{message}"
597 );
598 assert!(
599 message.contains("Co-authored-by: tahinli <"),
600 "commenter trailer: {message}"
601 );
602 assert_eq!(
603 git(&fx.bare, &["rev-parse", "feature"]),
604 pr.head_oid,
605 "apply"
606 );
607 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
608 assert!(threads[1].root.resolved, "applying resolves the thread");
609}
610
611async fn get(fx: &Fixture, number: i64, token: &str) -> String {
612 let uri = format!("/tahinli/demo/pulls/{number}/files");
613 let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await;
614 body
615}