use forge_core::reviews::{ReviewState, Side}; use forge_core::{IssueState, NewPull, PullRequest, User, Visibility}; use forge_git::GitEnv; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; use forge_web_app::auth::{SESSION_COOKIE, percent_encode}; use forge_web_app::test_support::fixture::{Fixture, OWNER, REPO, git}; fn cookie(token: &str) -> String { format!("__Host-{SESSION_COOKIE}={token}") } async fn send( router: &Router, method: &str, uri: &str, token: Option<&str>, form: Option, ) -> (u16, Option, String) { let mut req = Request::builder().method(method).uri(uri); if let Some(token) = token { req = req.header("cookie", cookie(token)); } let body = match form { Some(form) => { req = req.header("content-type", "application/x-www-form-urlencoded"); Body::from(form) } None => Body::empty(), }; let res = router.handle(req.body(body).unwrap()).await; let status = res.status().as_u16(); let location = res .headers() .get("location") .map(|v| v.to_str().unwrap().to_owned()); let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); ( status, location, String::from_utf8_lossy(&bytes).into_owned(), ) } async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User { let user = fx .store .create_user(name, None, "not-a-real-hash", false) .await .unwrap(); forge_web_app::test_support::create_session( &fx.store, &user.id, token, &format!("{token}-csrf"), ) .await; user } async fn owner_session(fx: &Fixture) { let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); forge_web_app::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf") .await; } fn csrf_form(token: &str, pairs: &[(&str, &str)]) -> String { let mut form = format!("csrf={}", percent_encode(&format!("{token}-csrf"))); for (key, value) in pairs { form.push_str(&format!("&{key}={}", percent_encode(value))); } form } async fn post_form( fx: &Fixture, uri: &str, token: &str, pairs: &[(&str, &str)], ) -> (u16, Option, String) { send( &fx.router, "POST", uri, Some(token), Some(csrf_form(token, pairs)), ) .await } async fn pull(fx: &Fixture, number: i64) -> PullRequest { let repo = fx .store .repo_by_owner_and_name(OWNER, REPO) .await .unwrap() .unwrap(); fx.store .pull_by_number(&repo.id, number) .await .unwrap() .unwrap() } async fn open_pull(fx: &Fixture) -> i64 { let base_oid = git(&fx.work, &["rev-parse", "HEAD"]); git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]); std::fs::write(fx.work.join("a.txt"), "one\nchanged\nthree\n").unwrap(); git(&fx.work, &["add", "-A"]); git(&fx.work, &["commit", "-q", "-m", "Change a.txt"]); let head_oid = git(&fx.work, &["rev-parse", "HEAD"]); git( &fx.work, &[ "push", "-q", &fx.bare.to_string_lossy(), "HEAD:refs/heads/feature", ], ); let repo = fx .store .repo_by_owner_and_name(OWNER, REPO) .await .unwrap() .unwrap(); let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); let pr = fx .store .create_pull(&NewPull { repo_id: &repo.id, author_id: &owner.id, title: "Change a", body: "", base_branch: "main", head_repo_id: &repo.id, head_branch: "feature", head_oid: &head_oid, base_oid: &base_oid, }) .await .unwrap(); let env = GitEnv { git_bin: "git".into(), data_dir: fx.work.clone(), }; forge_git::pulls::fetch_into_pull_ref(&env, &fx.bare, &fx.bare, &head_oid, pr.issue.number) .await .unwrap(); pr.issue.number } async fn head_of(fx: &Fixture, number: i64) -> String { pull(fx, number).await.head_oid } async fn comment_on( fx: &Fixture, number: i64, token: &str, line: &str, body: &str, ) -> (u16, Option) { let head = head_of(fx, number).await; let (status, location, _) = post_form( fx, &format!("/tahinli/demo/pulls/{number}/review_comments"), token, &[ ("file_index", "0"), ("side", "new"), ("line", line), ("head_oid", head.as_str()), ("action", "single"), ("body", body), ], ) .await; (status, location) } async fn root_at(fx: &Fixture, number: i64, index: usize) -> String { let pr = pull(fx, number).await; fx.store.review_threads(&pr.issue.id, None).await.unwrap()[index] .root .id .clone() } fn suggestion(text: &str) -> String { format!("Try this:\n```suggestion\n{text}\n```") } async fn apply_as( fx: &Fixture, number: i64, token: &str, comment_id: &str, ) -> (u16, Option) { let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply"); let (status, location, _) = post_form(fx, &uri, token, &[("block", "0"), ("return", "files")]).await; (status, location) } #[tokio::test] async fn comment_rules_and_pending_review_on_one_pull() { let fx = Fixture::new(Visibility::Public).await; owner_session(&fx).await; let number = open_pull(&fx).await; let pr = pull(&fx, number).await; let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await; assert_eq!(status, 303, "outside diff"); assert!( location.unwrap().contains("review_error=bad_line"), "outside diff" ); assert!( fx.store .review_threads(&pr.issue.id, None) .await .unwrap() .is_empty(), "outside diff left a thread" ); let zero = "0".repeat(40); let (status, location, _) = post_form( &fx, &format!("/tahinli/demo/pulls/{number}/review_comments"), "tahinli", &[ ("file_index", "0"), ("side", "new"), ("line", "2"), ("head_oid", zero.as_str()), ("action", "single"), ("body", "Stale"), ], ) .await; assert_eq!(status, 303, "stale head"); assert_eq!( location.as_deref(), Some(format!("/tahinli/demo/pulls/{number}/files?review_error=stale").as_str()), "stale head" ); assert!( fx.store .review_threads(&pr.issue.id, None) .await .unwrap() .is_empty(), "stale head left a thread" ); let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await; assert_eq!(status, 303, "single comment"); assert_eq!( location.as_deref(), Some(format!("/tahinli/demo/pulls/{number}/files#L-0-new-2").as_str()), "single comment" ); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert_eq!(threads.len(), 1, "single comment"); let root = &threads[0].root; assert_eq!( (root.path.as_str(), root.side, root.line), ("a.txt", Side::New, 2), "single comment" ); assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment"); assert!(!root.pending, "single comment"); let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); let head = pr.head_oid.clone(); let (status, _, _) = post_form( &fx, &format!("/tahinli/demo/pulls/{number}/review_comments"), "tahinli", &[ ("file_index", "0"), ("side", "new"), ("line", "2"), ("head_oid", head.as_str()), ("action", "review"), ("body", "Draft"), ], ) .await; assert_eq!(status, 303, "pending start"); assert_eq!( fx.store .review_threads(&pr.issue.id, None) .await .unwrap() .len(), 1, "pending thread hidden from everyone" ); let mine = fx .store .review_threads(&pr.issue.id, Some(&tahinli.id)) .await .unwrap(); assert_eq!(mine.len(), 2, "author sees the pending thread"); assert!( mine.iter().any(|t| t.root.pending), "the author's draft is pending" ); let form = csrf_form("tahinli", &[("state", "comment"), ("body", "Done")]); let (status, _, _) = send( &fx.router, "POST", &format!("/tahinli/demo/pulls/{number}/reviews"), Some("tahinli"), Some(form), ) .await; assert_eq!(status, 303, "submit review"); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert_eq!(threads.len(), 2, "submitted review is public"); assert!(threads.iter().all(|t| !t.root.pending), "submitted review"); let uri = format!("/tahinli/demo/pulls/{number}/review_comments"); let form = csrf_form( "tahinli", &[ ("file_index", "0"), ("side", "new"), ("line", "2"), ("head_oid", head.as_str()), ("action", "single"), ("body", "Anon"), ], ); let (status, location, _) = send(&fx.router, "POST", &uri, None, Some(form)).await; assert_eq!(status, 303, "anonymous write"); assert!(location.unwrap().starts_with("/login"), "anonymous write"); let form = format!("file_index=0&side=new&line=2&head_oid={head}&action=single&body=NoCsrf"); let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; assert_eq!(status, 403, "missing csrf"); } #[tokio::test] async fn thread_reply_edit_resolve_and_delete() { let fx = Fixture::new(Visibility::Public).await; owner_session(&fx).await; sign_in(&fx, "bob", "bob").await; let number = open_pull(&fx).await; comment_on(&fx, number, "tahinli", "2", "First").await; let pr = pull(&fx, number).await; let root = root_at(&fx, number, 0).await; let (status, location, _) = post_form( &fx, &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"), "bob", &[("body", "Reply")], ) .await; assert_eq!(status, 303, "reply"); assert_eq!( location.as_deref(), Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()), "reply" ); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert_eq!(threads[0].replies.len(), 1, "reply"); assert_eq!(threads[0].replies[0].author_name, "bob", "reply"); let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit"); let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await; assert_eq!(status, 200, "edit form"); assert!(body.contains("Save comment"), "edit form"); let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await; assert_eq!(status, 403, "edit form for a non-author"); let (status, _, _) = post_form(&fx, &edit, "bob", &[("body", "Hijacked")]).await; assert_eq!(status, 403, "edit by a non-author"); let (status, location, _) = post_form(&fx, &edit, "tahinli", &[("body", "Edited")]).await; assert_eq!(status, 303, "edit"); assert_eq!( location.as_deref(), Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()), "edit" ); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert_eq!(threads[0].root.body, "Edited", "edit"); let resolve = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/resolve"); let (status, _, _) = post_form(&fx, &resolve, "bob", &[("resolved", "1")]).await; assert_eq!(status, 403, "resolve by a reader"); let (status, _, _) = post_form(&fx, &resolve, "tahinli", &[("resolved", "1")]).await; assert_eq!(status, 303, "resolve"); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert!(threads[0].root.resolved, "resolve"); comment_on(&fx, number, "tahinli", "2", "Doomed").await; let doomed = root_at(&fx, number, 1).await; let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{doomed}/delete"); let (status, _, _) = post_form(&fx, &uri, "bob", &[]).await; assert_eq!(status, 403, "delete by a non-author"); let (status, _, _) = post_form(&fx, &uri, "tahinli", &[]).await; assert_eq!(status, 303, "delete"); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert_eq!(threads.len(), 1, "delete"); assert_eq!(threads[0].root.id, root, "delete kept the other thread"); } #[tokio::test] async fn reviews_approve_then_close_the_pull() { let fx = Fixture::new(Visibility::Public).await; owner_session(&fx).await; sign_in(&fx, "bob", "bob").await; let number = open_pull(&fx).await; let pr = pull(&fx, number).await; let uri = format!("/tahinli/demo/pulls/{number}/reviews"); let (status, location, _) = post_form(&fx, &uri, "bob", &[("state", "approve")]).await; assert_eq!(status, 303, "reader approval"); assert!(location.unwrap().contains("#review-"), "reader approval"); let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap(); assert_eq!(reviews.len(), 1, "reader approval"); assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval"); let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await; assert_eq!(status, 303, "author approval"); assert_eq!( location.as_deref(), Some(format!("/tahinli/demo/pulls/{number}?review_error=own_pr").as_str()), "author approval" ); assert_eq!( fx.store.list_reviews(&pr.issue.id).await.unwrap().len(), 1, "author approval" ); let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); fx.store .set_issue_state( &pr.issue.id, Some(&tahinli.id), IssueState::Closed, None, serde_json::Value::Null, ) .await .unwrap(); let (status, location) = comment_on(&fx, number, "tahinli", "2", "After close").await; assert_eq!(status, 303, "comment on a closed pull"); assert!( location.unwrap().contains("#L-0-new-2"), "comment on a closed pull" ); let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await; assert_eq!(status, 303, "review on a closed pull"); assert!( location.unwrap().ends_with("?review_error=closed"), "review on a closed pull" ); } #[tokio::test] async fn dismiss_needs_write_and_a_reason() { let fx = Fixture::new(Visibility::Public).await; owner_session(&fx).await; sign_in(&fx, "bob", "bob").await; let number = open_pull(&fx).await; let pr = pull(&fx, number).await; let (status, _, _) = post_form( &fx, &format!("/tahinli/demo/pulls/{number}/reviews"), "bob", &[("state", "request_changes")], ) .await; assert_eq!(status, 303, "setup review"); let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0); let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id); let (status, _, _) = post_form(&fx, &uri, "bob", &[("reason", "mine")]).await; assert_eq!(status, 403, "dismiss by a reader"); let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("reason", " ")]).await; assert_eq!(status, 303, "blank reason"); assert!( location.unwrap().ends_with("?review_error=empty"), "blank reason" ); let (status, _, _) = post_form(&fx, &uri, "tahinli", &[("reason", "Addressed")]).await; assert_eq!(status, 303, "dismiss"); let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0); assert_eq!(review.state, ReviewState::Dismissed, "dismiss"); } #[tokio::test] async fn suggestions_reader_outdated_and_apply() { let fx = Fixture::new(Visibility::Public).await; owner_session(&fx).await; sign_in(&fx, "rita", "rita").await; let number = open_pull(&fx).await; let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await; assert_eq!(status, 303, "first suggestion"); let first = root_at(&fx, number, 0).await; let page = get(&fx, number, "rita").await; assert!(page.contains("Suggested change"), "the diff still shows"); assert!( !page.contains("Apply suggestion"), "no apply button without push access" ); let (status, location) = apply_as(&fx, number, "rita", &first).await; assert_eq!(status, 303, "reader apply"); assert!( location.unwrap().contains("review_error=no_push"), "reader apply" ); let pr = pull(&fx, number).await; std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap(); git(&fx.work, &["commit", "-q", "-am", "Move line 2"]); let moved = git(&fx.work, &["rev-parse", "HEAD"]); git( &fx.work, &[ "push", "-q", &fx.bare.to_string_lossy(), "HEAD:refs/heads/feature", ], ); fx.store .update_pull_head(&pr.issue.id, &moved) .await .unwrap(); let page = get(&fx, number, "tahinli").await; assert!( page.contains("This suggestion is outdated"), "outdated note shown" ); assert!( !page.contains("Apply suggestion"), "no apply button when outdated" ); let (status, location) = apply_as(&fx, number, "tahinli", &first).await; assert_eq!(status, 303, "outdated apply"); assert!( location.unwrap().contains("review_error=outdated"), "outdated apply" ); assert_eq!( git(&fx.bare, &["rev-parse", "feature"]), moved, "nothing was committed" ); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert!( !threads[0].root.resolved, "a refused apply leaves the thread open" ); let before = pull(&fx, number).await.head_oid; assert_eq!(before, moved, "the head is the moved commit"); let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await; assert_eq!(status, 303, "fresh suggestion"); let second = root_at(&fx, number, 1).await; let (status, location) = apply_as(&fx, number, "tahinli", &second).await; assert_eq!(status, 303, "apply"); assert!(!location.unwrap().contains("review_error"), "apply"); let pr = pull(&fx, number).await; assert_ne!( pr.head_oid, before, "the head moved to the suggestion commit" ); assert_eq!( git(&fx.bare, &["show", &format!("{}:a.txt", pr.head_oid)]), "one\ntwo!\nthree", "apply" ); assert_eq!( git(&fx.bare, &["log", "-1", "--format=%an", &pr.head_oid]), "tahinli", "apply" ); let message = git(&fx.bare, &["log", "-1", "--format=%B", &pr.head_oid]); assert!( message.starts_with("Apply suggestion from review"), "{message}" ); assert!( message.contains("Co-authored-by: tahinli <"), "commenter trailer: {message}" ); assert_eq!( git(&fx.bare, &["rev-parse", "feature"]), pr.head_oid, "apply" ); let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); assert!(threads[1].root.resolved, "applying resolves the thread"); } async fn get(fx: &Fixture, number: i64, token: &str) -> String { let uri = format!("/tahinli/demo/pulls/{number}/files"); let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await; body }