diff --git a/crates/forge-web/src/pages/media.rs b/crates/forge-web/src/pages/media.rs index 682568c..5c2ffb8 100644 --- a/crates/forge-web/src/pages/media.rs +++ b/crates/forge-web/src/pages/media.rs @@ -339,97 +339,120 @@ mod tests { .to_vec() } + /// The public route, read-only, on one fixture: the linked object as a download, HEAD, and + /// the 404 cases (unlinked object, non-pointer, absent path, unknown repo). #[tokio::test] - async fn media_serves_the_linked_object_as_a_download() { + async fn public_media_serves_downloads_heads_and_404s() { let fx = fixture().await; + + // Scenario: a linked object is served as a download with its headers. let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/big.bin").await; - assert_eq!(res.status(), StatusCode::OK); - assert_eq!(header_str(&res, "content-disposition"), "attachment"); - assert_eq!(header_str(&res, "x-content-type-options"), "nosniff"); - assert_eq!(header_str(&res, "content-type"), OCTET); + assert_eq!(res.status(), StatusCode::OK, "linked object"); + assert_eq!( + header_str(&res, "content-disposition"), + "attachment", + "linked object disposition" + ); + assert_eq!( + header_str(&res, "x-content-type-options"), + "nosniff", + "linked object nosniff" + ); + assert_eq!( + header_str(&res, "content-type"), + OCTET, + "linked object content type" + ); assert_eq!( header_str(&res, "content-length"), - fx.object.len().to_string() + fx.object.len().to_string(), + "linked object length" ); - assert_eq!(header_str(&res, "etag"), format!("\"{}\"", fx.oid)); - assert_eq!(body_bytes(res).await, fx.object); - } + assert_eq!( + header_str(&res, "etag"), + format!("\"{}\"", fx.oid), + "linked object etag" + ); + assert_eq!(body_bytes(res).await, fx.object, "linked object body"); - #[tokio::test] - async fn head_has_headers_and_no_body() { - let fx = fixture().await; + // Scenario: HEAD has the headers and no body. let res = get(&fx.router, "HEAD", "/tahinli/pub/-/media/main/big.bin").await; - assert_eq!(res.status(), StatusCode::OK); + assert_eq!(res.status(), StatusCode::OK, "head"); assert_eq!( header_str(&res, "content-length"), - fx.object.len().to_string() + fx.object.len().to_string(), + "head length" ); - assert!(body_bytes(res).await.is_empty()); - } + assert!(body_bytes(res).await.is_empty(), "head body"); - #[tokio::test] - async fn missing_object_is_404() { - let fx = fixture().await; - // The pointer exists, but the repo does not link its object. + // Scenario: the pointer exists, but the repo does not link its object. let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/missing.bin").await; - assert_eq!(res.status(), StatusCode::NOT_FOUND); - } + assert_eq!(res.status(), StatusCode::NOT_FOUND, "unlinked object"); - #[tokio::test] - async fn non_pointer_and_missing_path_are_404() { - let fx = fixture().await; + // Scenario: a non-pointer file, an absent path and an unknown repo all 404. let text = get(&fx.router, "GET", "/tahinli/pub/-/media/main/plain.txt").await; - assert_eq!(text.status(), StatusCode::NOT_FOUND); + assert_eq!(text.status(), StatusCode::NOT_FOUND, "non-pointer"); let absent = get(&fx.router, "GET", "/tahinli/pub/-/media/main/nope.bin").await; - assert_eq!(absent.status(), StatusCode::NOT_FOUND); + assert_eq!(absent.status(), StatusCode::NOT_FOUND, "absent path"); let unknown_repo = get(&fx.router, "GET", "/tahinli/nope/-/media/main/big.bin").await; - assert_eq!(unknown_repo.status(), StatusCode::NOT_FOUND); + assert_eq!(unknown_repo.status(), StatusCode::NOT_FOUND, "unknown repo"); } + /// Private media and signed URLs, read-only, on one fixture: a private repo needs a valid + /// token, and `media_url` encodes paths and signs only private repos. #[tokio::test] - async fn private_repo_needs_a_valid_token() { + async fn private_media_needs_a_valid_token_and_urls_sign_private_repos_only() { let fx = fixture().await; let path = "/tahinli/priv/-/media/main/big.bin"; + + // Scenario: no token is a 404. let none = get(&fx.router, "GET", path).await; - assert_eq!(none.status(), StatusCode::NOT_FOUND); + assert_eq!(none.status(), StatusCode::NOT_FOUND, "no token"); + // Scenario: a valid token serves the object. let now = now_unix(); let valid = sign_raw(&fx.state.key, &fx.private.id, now + 60); let ok = get(&fx.router, "GET", &format!("{path}?token={valid}")).await; - assert_eq!(ok.status(), StatusCode::OK); - assert_eq!(body_bytes(ok).await, fx.object); + assert_eq!(ok.status(), StatusCode::OK, "valid token"); + assert_eq!(body_bytes(ok).await, fx.object, "valid token body"); + // Scenario: an expired token is a 404. let expired = sign_raw(&fx.state.key, &fx.private.id, now - 1); let res = get(&fx.router, "GET", &format!("{path}?token={expired}")).await; - assert_eq!(res.status(), StatusCode::NOT_FOUND); + assert_eq!(res.status(), StatusCode::NOT_FOUND, "expired token"); - // A token signed for the public repo does not open the private one. + // Scenario: a token signed for the public repo does not open the private one. let other = sign_raw(&fx.state.key, &fx.public.id, now + 60); let res = get(&fx.router, "GET", &format!("{path}?token={other}")).await; - assert_eq!(res.status(), StatusCode::NOT_FOUND); - } + assert_eq!(res.status(), StatusCode::NOT_FOUND, "token for another repo"); - #[tokio::test] - async fn media_url_encodes_and_signs_private_repos_only() { - let fx = fixture().await; + // Scenario: a public URL is encoded and unsigned. let public = media_url(&fx.state, &fx.public, "main", "a b/big.bin"); assert_eq!( public, - "http://127.0.0.1:7661/tahinli/pub/-/media/main/a%20b/big.bin" + "http://127.0.0.1:7661/tahinli/pub/-/media/main/a%20b/big.bin", + "public url" ); + + // Scenario: a private URL carries a token that verifies for the private repo. let private = media_url(&fx.state, &fx.private, "main", "big.bin"); assert!( - private.starts_with("http://127.0.0.1:7661/tahinli/priv/-/media/main/big.bin?token=") + private.starts_with("http://127.0.0.1:7661/tahinli/priv/-/media/main/big.bin?token="), + "private url prefix" ); let token = private .split_once("?token=") .map(|(_, t)| t) .unwrap_or_default(); - assert!(verify_raw(&fx.state.key, token, &fx.private.id, now_unix())); + assert!( + verify_raw(&fx.state.key, token, &fx.private.id, now_unix()), + "private url token" + ); } /// A branch named `media` must not shadow the media route. The raw route serves its files, - /// and the URL from `media_url` still serves the linked LFS object. + /// and the URL from `media_url` still serves the linked LFS object. This test pushes a + /// branch, so it keeps its own fixture. #[tokio::test] async fn branch_named_media_does_not_shadow_the_media_route() { let fx = fixture().await; @@ -446,19 +469,23 @@ mod tests { ); let readme = get(&fx.router, "GET", "/tahinli/pub/media/README.md").await; - assert_eq!(readme.status(), StatusCode::OK); - assert_eq!(body_bytes(readme).await, b"# On a media branch\n".to_vec()); + assert_eq!(readme.status(), StatusCode::OK, "branch raw file"); + assert_eq!( + body_bytes(readme).await, + b"# On a media branch\n".to_vec(), + "branch raw body" + ); // `-` is never a ref, so a raw path under it is not resolved. let dash = get(&fx.router, "GET", "/tahinli/pub/-/README.md").await; - assert_eq!(dash.status(), StatusCode::NOT_FOUND); + assert_eq!(dash.status(), StatusCode::NOT_FOUND, "dash is not a ref"); let url = media_url(&fx.state, &fx.public, "main", "big.bin"); let path = url .strip_prefix("http://127.0.0.1:7661") .expect("configured base"); let media = get(&fx.router, "GET", path).await; - assert_eq!(media.status(), StatusCode::OK); - assert_eq!(body_bytes(media).await, fx.object); + assert_eq!(media.status(), StatusCode::OK, "media route still wins"); + assert_eq!(body_bytes(media).await, fx.object, "media body"); } } diff --git a/crates/forge-web/src/pages/new_repo.rs b/crates/forge-web/src/pages/new_repo.rs index 40d25db..a3971e9 100644 --- a/crates/forge-web/src/pages/new_repo.rs +++ b/crates/forge-web/src/pages/new_repo.rs @@ -436,64 +436,16 @@ mod tests { const CSRF: &str = "new-repo-test-csrf"; - /// POSTs `/new` as tahinli with the given extra fields; returns the status and the label count - /// of the repo it created, or `None` when no repo was created. - async fn create_with(fields: &[(&str, &str)]) -> (u16, Option) { - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let store: Store = state.store.clone(); - let router: Router = crate::test_support::app_router(state); - let tahinli = store - .create_user("tahinli", None, "x", false) - .await - .expect("tahinli"); - crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", CSRF).await; - let cookie = format!("__Host-{SESSION_COOKIE}=tahinli-token"); - - let mut pairs = vec![("csrf", CSRF), ("name", "fresh")]; - pairs.extend_from_slice(fields); - let body = form_urlencoded::Serializer::new(String::new()) - .extend_pairs(pairs) - .finish(); - let req = Request::builder() - .method("POST") - .uri("/new") - .header("cookie", cookie) - .header("content-type", "application/x-www-form-urlencoded") - .body(Body::from(body)) - .expect("request"); - let res = router.handle(req).await; - let status = res.status().as_u16(); - let _ = to_bytes(res.into_body(), usize::MAX).await.expect("body"); - - let repo = store - .repo_by_owner_and_name("tahinli", "fresh") - .await - .expect("query"); - let count = match repo { - Some(repo) => Some(store.list_labels(&repo.id).await.expect("labels").len()), - None => None, - }; - (status, count) - } - - #[tokio::test] - async fn new_repo_with_default_labels_checked_gets_nine() { - let (status, count) = create_with(&[("default_labels", "on")]).await; - assert_eq!(status, 303); - assert_eq!(count, Some(9)); - } - - #[tokio::test] - async fn new_repo_with_default_labels_unchecked_gets_none() { - let (status, count) = create_with(&[]).await; - assert_eq!(status, 303); - assert_eq!(count, Some(0)); + /// One store and router with `tahinli` signed in. Every scenario below uses its own repo name, + /// so they share this site. + struct Site { + store: Store, + router: Router, + tahinli_id: String, + _dir: tempfile::TempDir, } - /// POSTs `/new` as tahinli with the mirror fields and returns the status, the store and the repo - /// created (if any). The form's token is the shared CSRF value. - async fn submit_with_mirror(fields: &[(&str, &str)]) -> (u16, Store, Option) { + async fn site() -> Site { let dir = tempfile::tempdir().expect("tempdir"); let state = crate::test_support::test_state(dir.path()).await; let store: Store = state.store.clone(); @@ -503,9 +455,18 @@ mod tests { .await .expect("tahinli"); crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", CSRF).await; - let cookie = format!("__Host-{SESSION_COOKIE}=tahinli-token"); + Site { + store, + router, + tahinli_id: tahinli.id, + _dir: dir, + } + } - let mut pairs = vec![("csrf", CSRF), ("name", "mirrored")]; + /// POSTs `/new` as tahinli for a repo called `name` with the extra fields. Returns the status + /// and the repo created, if any. The form's token is the shared CSRF value. + async fn post_new(site: &Site, name: &str, fields: &[(&str, &str)]) -> (u16, Option) { + let mut pairs = vec![("csrf", CSRF), ("name", name)]; pairs.extend_from_slice(fields); let body = form_urlencoded::Serializer::new(String::new()) .extend_pairs(pairs) @@ -513,97 +474,126 @@ mod tests { let req = Request::builder() .method("POST") .uri("/new") - .header("cookie", cookie) + .header("cookie", format!("__Host-{SESSION_COOKIE}=tahinli-token")) .header("content-type", "application/x-www-form-urlencoded") .body(Body::from(body)) .expect("request"); - let res = router.handle(req).await; + let res = site.router.handle(req).await; let status = res.status().as_u16(); - let body = to_bytes(res.into_body(), usize::MAX).await.expect("body"); - let text = String::from_utf8_lossy(&body).into_owned(); + let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); + let text = String::from_utf8_lossy(&bytes).into_owned(); assert!( !text.contains("hunter2-secret"), - "the mirror password is rendered" + "case {name}: the mirror password is rendered" ); - let repo = store - .repo_by_owner_and_name("tahinli", "mirrored") + let repo = site + .store + .repo_by_owner_and_name("tahinli", name) .await .expect("query"); - (status, store, repo) + (status, repo) } + /// The default labels are added only when the box is checked. #[tokio::test] - async fn new_repo_with_mirror_url_creates_a_pull_mirror() { - let (status, store, repo) = submit_with_mirror(&[ - ("mirror_url", "https://example.com/upstream/proj.git"), - ("mirror_username", "bot"), - ("mirror_secret", "hunter2-secret"), - ("mirror_interval", "60"), - ]) + async fn default_labels_are_added_only_when_checked() { + let site = site().await; + let cases: [(&str, &[(&str, &str)], usize); 2] = [ + ("checked", &[("default_labels", "on")], 9), + ("unchecked", &[], 0), + ]; + for (name, fields, want) in cases { + let (status, repo) = post_new(&site, name, fields).await; + assert_eq!(status, 303, "case {name}: status"); + let repo = repo.unwrap_or_else(|| panic!("case {name}: the repo is created")); + let labels = site + .store + .list_labels(&repo.id) + .await + .expect("labels") + .len(); + assert_eq!(labels, want, "case {name}: label count"); + } + } + + /// Mirror fields: a valid URL makes a pull mirror, a loopback URL is refused and creates + /// nothing, and a blank URL makes the repo without a mirror. + #[tokio::test] + async fn mirror_url_decides_whether_a_pull_mirror_is_made() { + let site = site().await; + + // Case: a valid URL creates a pull mirror with the given settings. + let (status, repo) = post_new( + &site, + "mirror-ok", + &[ + ("mirror_url", "https://example.com/upstream/proj.git"), + ("mirror_username", "bot"), + ("mirror_secret", "hunter2-secret"), + ("mirror_interval", "60"), + ], + ) .await; - assert_eq!(status, 303); - let repo = repo.expect("the repo is created"); - let mirror = store + assert_eq!(status, 303, "valid mirror: status"); + let repo = repo.expect("valid mirror: the repo is created"); + let mirror = site + .store .pull_mirror(&repo.id) .await .expect("query") - .expect("a pull mirror"); - assert_eq!(mirror.direction, MirrorDirection::Pull); - assert_eq!(mirror.url, "https://example.com/upstream/proj.git"); - assert_eq!(mirror.username, "bot"); - assert!(mirror.has_secret); - assert_eq!(mirror.interval_minutes, 60); + .expect("valid mirror: a pull mirror"); + assert_eq!(mirror.direction, MirrorDirection::Pull, "valid mirror: direction"); + assert_eq!( + mirror.url, "https://example.com/upstream/proj.git", + "valid mirror: url" + ); + assert_eq!(mirror.username, "bot", "valid mirror: username"); + assert!(mirror.has_secret, "valid mirror: secret kept"); + assert_eq!(mirror.interval_minutes, 60, "valid mirror: interval"); assert!( mirror.next_sync_at <= now_stamp(), - "the first sync is due now" + "valid mirror: the first sync is due now" ); - } - #[tokio::test] - async fn new_repo_with_loopback_mirror_url_is_refused_and_creates_nothing() { - let (status, store, repo) = - submit_with_mirror(&[("mirror_url", "https://127.0.0.1/upstream/proj.git")]).await; - assert_eq!(status, 200, "the form is shown again with the error"); - assert!(repo.is_none(), "no repo is created for a refused mirror"); + // Case: a loopback URL shows the form again and creates nothing. + let (status, repo) = post_new( + &site, + "mirror-loopback", + &[("mirror_url", "https://127.0.0.1/upstream/proj.git")], + ) + .await; + assert_eq!(status, 200, "loopback: the form is shown again with the error"); + assert!(repo.is_none(), "loopback: no repo is created for a refused mirror"); + + // Case: a blank URL creates the repo without a mirror. + let (status, repo) = post_new(&site, "mirror-blank", &[("mirror_url", " ")]).await; + assert_eq!(status, 303, "blank: status"); + let repo = repo.expect("blank: the repo is created"); assert!( - store - .repo_by_owner_and_name("tahinli", "mirrored") + site.store + .pull_mirror(&repo.id) .await .expect("query") - .is_none() + .is_none(), + "blank: no mirror" ); } - #[tokio::test] - async fn new_repo_with_blank_mirror_url_creates_no_mirror() { - let (status, store, repo) = submit_with_mirror(&[("mirror_url", " ")]).await; - assert_eq!(status, 303); - let repo = repo.expect("the repo is created"); - assert!(store.pull_mirror(&repo.id).await.expect("query").is_none()); - } - + /// A viewer who chose Turkish gets the Turkish form. #[tokio::test] async fn the_form_is_in_turkish_for_a_turkish_viewer() { - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let store: Store = state.store.clone(); - let router: Router = crate::test_support::app_router(state); - let tahinli = store - .create_user("tahinli", None, "x", false) - .await - .expect("tahinli"); - store - .set_ui_prefs(&tahinli.id, "auto", "tr") + let site = site().await; + site.store + .set_ui_prefs(&site.tahinli_id, "auto", "tr") .await .expect("prefs"); - crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", CSRF).await; let req = Request::builder() .method("GET") .uri("/new") .header("cookie", format!("__Host-{SESSION_COOKIE}=tahinli-token")) .body(Body::empty()) .expect("request"); - let res = router.handle(req).await; + let res = site.router.handle(req).await; let status = res.status().as_u16(); let body = to_bytes(res.into_body(), usize::MAX).await.expect("body"); let text = String::from_utf8_lossy(&body).into_owned(); diff --git a/crates/forge-web/src/pages/reactions_tests.rs b/crates/forge-web/src/pages/reactions_tests.rs index 2072007..05d658d 100644 --- a/crates/forge-web/src/pages/reactions_tests.rs +++ b/crates/forge-web/src/pages/reactions_tests.rs @@ -152,14 +152,17 @@ async fn on_issue(s: &Seed) -> Vec { .unwrap_or_default() } +/// Reactions that succeed: a signed-in reaction toggles on and off and redirects to the item's +/// anchor, and a reaction on a comment anchors on that comment. One seeded site serves both. #[tokio::test] -async fn signed_in_reaction_toggles_on_and_off_and_redirects_to_anchor() { +async fn reactions_toggle_and_comment_reactions_anchor_on_their_target() { let s = seeded().await; let uri = issue_uri(s.issue_number); - let body = fields("issue", &s.issue_id, "heart"); + // Case: a signed-in reaction turns on and redirects to the issue anchor. + let body = fields("issue", &s.issue_id, "heart"); let on = post(&s.site, &uri, Some(&s.bob_cookie), &body).await; - assert_eq!(on.status, 303); + assert_eq!(on.status, 303, "toggle on: status"); assert_eq!( on.location.as_deref(), Some( @@ -168,23 +171,21 @@ async fn signed_in_reaction_toggles_on_and_off_and_redirects_to_anchor() { s.issue_number, s.issue_number ) .as_str() - ) + ), + "toggle on: anchor" ); let summaries = on_issue(&s).await; - assert_eq!(summaries.len(), 1); - assert_eq!(summaries[0].reaction, Reaction::Heart); - assert_eq!(summaries[0].count, 1); - assert_eq!(summaries[0].users, vec!["bob"]); + assert_eq!(summaries.len(), 1, "toggle on: one reaction"); + assert_eq!(summaries[0].reaction, Reaction::Heart, "toggle on: kind"); + assert_eq!(summaries[0].count, 1, "toggle on: count"); + assert_eq!(summaries[0].users, vec!["bob"], "toggle on: who"); + // Case: the same reaction again turns it off. let off = post(&s.site, &uri, Some(&s.bob_cookie), &body).await; - assert_eq!(off.status, 303); - assert!(on_issue(&s).await.is_empty()); -} + assert_eq!(off.status, 303, "toggle off: status"); + assert!(on_issue(&s).await.is_empty(), "toggle off: nothing left"); -#[tokio::test] -async fn comment_reaction_anchors_on_the_comment() { - let s = seeded().await; - let uri = issue_uri(s.issue_number); + // Case: a reaction on a comment anchors on the comment. let reply = post( &s.site, &uri, @@ -192,7 +193,7 @@ async fn comment_reaction_anchors_on_the_comment() { &fields("comment", &s.comment_id, "eyes"), ) .await; - assert_eq!(reply.status, 303); + assert_eq!(reply.status, 303, "comment: status"); assert_eq!( reply.location.as_deref(), Some( @@ -201,7 +202,8 @@ async fn comment_reaction_anchors_on_the_comment() { s.issue_number, s.comment_id ) .as_str() - ) + ), + "comment: anchor" ); let map = s .site @@ -213,13 +215,20 @@ async fn comment_reaction_anchors_on_the_comment() { ) .await .expect("reactions"); - assert!(map[&s.comment_id][0].reacted_by_viewer); + assert!( + map[&s.comment_id][0].reacted_by_viewer, + "comment: reacted by the viewer" + ); } +/// Reactions that must be refused, in one seeded site. Every refusal leaves the issue without +/// reactions, and the archived-repo case runs last because it changes the repo. #[tokio::test] -async fn missing_or_wrong_csrf_is_forbidden_and_changes_nothing() { +async fn refused_reactions_are_rejected_and_change_nothing() { let s = seeded().await; let uri = issue_uri(s.issue_number); + + // Case: a missing or wrong CSRF token is 403. let no_token = vec![ ("target_kind", "issue"), ("target_id", s.issue_id.as_str()), @@ -229,7 +238,8 @@ async fn missing_or_wrong_csrf_is_forbidden_and_changes_nothing() { post(&s.site, &uri, Some(&s.bob_cookie), &no_token) .await .status, - 403 + 403, + "missing csrf" ); let wrong = vec![ ("csrf", "not-the-token"), @@ -241,24 +251,21 @@ async fn missing_or_wrong_csrf_is_forbidden_and_changes_nothing() { post(&s.site, &uri, Some(&s.bob_cookie), &wrong) .await .status, - 403 + 403, + "wrong csrf" ); - assert!(on_issue(&s).await.is_empty()); -} + assert!(on_issue(&s).await.is_empty(), "csrf: nothing changes"); -#[tokio::test] -async fn signed_out_viewer_is_sent_to_login() { - let s = seeded().await; - let uri = issue_uri(s.issue_number); + // Case: a signed-out viewer is sent to login. let reply = post(&s.site, &uri, None, &fields("issue", &s.issue_id, "+1")).await; - assert_eq!(reply.status, 303); - assert!(reply.location.unwrap_or_default().starts_with("/login")); - assert!(on_issue(&s).await.is_empty()); -} + assert_eq!(reply.status, 303, "signed out: status"); + assert!( + reply.location.unwrap_or_default().starts_with("/login"), + "signed out: redirect to login" + ); + assert!(on_issue(&s).await.is_empty(), "signed out: nothing changes"); -#[tokio::test] -async fn hidden_repo_answers_not_found_for_a_viewer_without_access() { - let s = seeded().await; + // Case: a hidden repo answers 404 for a viewer without access. let reply = post( &s.site, "/tahinli/secret/issues/1/reactions", @@ -266,14 +273,10 @@ async fn hidden_repo_answers_not_found_for_a_viewer_without_access() { &fields("issue", "anything", "+1"), ) .await; - assert_eq!(reply.status, 404); -} + assert_eq!(reply.status, 404, "hidden repo"); -#[tokio::test] -async fn target_must_belong_to_this_issue() { - let s = seeded().await; - let uri = issue_uri(s.issue_number); - // An issue id from another item in the same repo is not this item's body. + // Case: a target must belong to this issue. An issue id from another item in the same repo + // is not this item's body. let wrong_issue = post( &s.site, &uri, @@ -281,9 +284,8 @@ async fn target_must_belong_to_this_issue() { &fields("issue", &s.other_issue_id, "+1"), ) .await; - assert_eq!(wrong_issue.status, 404); - // A comment of the other issue (the comment belongs to the first issue) is rejected on the - // second issue's page. + assert_eq!(wrong_issue.status, 404, "issue of another item"); + // A comment of the first issue is rejected on the second issue's page. let other_uri = issue_uri(s.issue_number + 1); let wrong_comment = post( &s.site, @@ -292,41 +294,28 @@ async fn target_must_belong_to_this_issue() { &fields("comment", &s.comment_id, "+1"), ) .await; - assert_eq!(wrong_comment.status, 404); - assert!(on_issue(&s).await.is_empty()); -} + assert_eq!(wrong_comment.status, 404, "comment of another issue"); + assert!(on_issue(&s).await.is_empty(), "wrong target: nothing changes"); -#[tokio::test] -async fn unknown_reaction_and_target_kind_are_bad_requests() { - let s = seeded().await; - let uri = issue_uri(s.issue_number); - assert_eq!( - post( - &s.site, - &uri, - Some(&s.bob_cookie), - &fields("issue", &s.issue_id, "party") - ) - .await - .status, - 400 - ); - assert_eq!( - post( - &s.site, - &uri, - Some(&s.bob_cookie), - &fields("pull", &s.issue_id, "+1") - ) - .await - .status, - 400 - ); -} + // Case: an unknown reaction and an unknown target kind are 400. + let bad_reaction = post( + &s.site, + &uri, + Some(&s.bob_cookie), + &fields("issue", &s.issue_id, "party"), + ) + .await; + assert_eq!(bad_reaction.status, 400, "unknown reaction"); + let bad_kind = post( + &s.site, + &uri, + Some(&s.bob_cookie), + &fields("pull", &s.issue_id, "+1"), + ) + .await; + assert_eq!(bad_kind.status, 400, "unknown target kind"); -#[tokio::test] -async fn archived_repo_refuses_reactions() { - let s = seeded().await; + // Case: an archived repo refuses reactions. This runs last because it archives the repo. s.site .store .set_repo_archived(&s.repo_id, true) @@ -334,11 +323,11 @@ async fn archived_repo_refuses_reactions() { .expect("archive"); let reply = post( &s.site, - &issue_uri(s.issue_number), + &uri, Some(&s.bob_cookie), &fields("issue", &s.issue_id, "+1"), ) .await; - assert_eq!(reply.status, 403); - assert!(on_issue(&s).await.is_empty()); + assert_eq!(reply.status, 403, "archived repo"); + assert!(on_issue(&s).await.is_empty(), "archived: nothing changes"); } diff --git a/crates/forge-web/src/pages/register.rs b/crates/forge-web/src/pages/register.rs index 2028840..7d28dd3 100644 --- a/crates/forge-web/src/pages/register.rs +++ b/crates/forge-web/src/pages/register.rs @@ -527,7 +527,7 @@ mod tests { let tmp = tempfile::tempdir().expect("tempdir"); let (router, _state) = app(tmp.path(), Registration::Closed).await; let (status, _, _) = send(&router, "GET", "/register", None, None).await; - assert_eq!(status, 404); + assert_eq!(status, 404, "closed: form"); let (status, _, _) = send( &router, "POST", @@ -536,30 +536,35 @@ mod tests { Some("username=bob&password=x&confirm=x"), ) .await; - assert_eq!(status, 404); + assert_eq!(status, 404, "closed: post"); } + /// Invite mode on one app: no invite shows no form, a bad invite is refused, a valid invite + /// makes one verified account, and the same link is spent afterwards. #[tokio::test] - async fn invite_mode_needs_an_invite() { + async fn invite_mode_needs_a_valid_single_use_invite() { let tmp = tempfile::tempdir().expect("tempdir"); - let (router, _state) = app(tmp.path(), Registration::Invite).await; + let (router, state) = app(tmp.path(), Registration::Invite).await; + + // Case: without an invite the form is not shown. let (status, _, html) = send(&router, "GET", "/register", None, None).await; - assert_eq!(status, 200); - assert!(html.contains("Registration is by invitation only")); + assert_eq!(status, 200, "no invite: status"); + assert!( + html.contains("Registration is by invitation only"), + "no invite: notice" + ); assert!( !html.contains("name=\"username\""), - "no form without an invite" + "no invite: no form without an invite" ); + + // Case: an invalid invite is refused. let (status, _, html) = send(&router, "GET", "/register?invite=forge_nope", None, None).await; - assert_eq!(status, 200); - assert!(html.contains("This invite is invalid")); - } + assert_eq!(status, 200, "bad invite: status"); + assert!(html.contains("This invite is invalid"), "bad invite: notice"); - #[tokio::test] - async fn invite_creates_one_verified_account_and_the_link_is_single_use() { - let tmp = tempfile::tempdir().expect("tempdir"); - let (router, state) = app(tmp.path(), Registration::Invite).await; + // Case: a valid invite creates one verified account with the invited address. let admin = state .store .create_user("admin", None, "hash", true) @@ -573,9 +578,12 @@ mod tests { let uri = format!("/register?invite={token}"); let (cookie, precsrf) = precsrf_for(&router, &uri).await; let (status, _, html) = send(&router, "GET", &uri, Some(&cookie), None).await; - assert_eq!(status, 200); - assert!(html.contains("bob@example.com"), "invited address is shown"); - assert_eq!(field_from(&html, "invite"), token); + assert_eq!(status, 200, "valid invite: form status"); + assert!( + html.contains("bob@example.com"), + "valid invite: invited address is shown" + ); + assert_eq!(field_from(&html, "invite"), token, "valid invite: token"); let form = format!( "precsrf={precsrf}&invite={token}&username=bob&email=mallory%40example.com\ @@ -583,8 +591,12 @@ mod tests { ); let (status, headers, _) = send(&router, "POST", "/register", Some(&cookie), Some(&form)).await; - assert_eq!(status, 303); - assert_eq!(headers["location"].to_str().unwrap(), "/"); + assert_eq!(status, 303, "valid invite: status"); + assert_eq!( + headers["location"].to_str().unwrap(), + "/", + "valid invite: redirect" + ); let bob = state .store @@ -595,11 +607,14 @@ mod tests { assert_eq!( bob.email.as_deref(), Some("bob@example.com"), - "the invite's address wins" + "valid invite: the invite's address wins" + ); + assert!( + state.store.email_is_verified(&bob.id).await.unwrap(), + "valid invite: verified" ); - assert!(state.store.email_is_verified(&bob.id).await.unwrap()); - // The same link now answers as spent, and creates nothing. + // Case: the same link now answers as spent, and creates nothing. let (cookie, precsrf) = precsrf_for(&router, &uri).await; let form = format!( "precsrf={precsrf}&invite={token}&username=carol&email=\ @@ -607,48 +622,53 @@ mod tests { ); let (status, _, html) = send(&router, "POST", "/register", Some(&cookie), Some(&form)).await; - assert_eq!(status, 200); - assert!(html.contains("This invite is invalid")); + assert_eq!(status, 200, "spent: status"); + assert!(html.contains("This invite is invalid"), "spent: notice"); assert!( state .store .user_by_username("carol") .await .unwrap() - .is_none() + .is_none(), + "spent: no account" ); } + /// Open registration on one app: a new account is unverified and gets a verification mail, + /// and a verify link marks its address verified once. #[tokio::test] - async fn open_registration_queues_a_verification_mail_and_no_verified_mark() { + async fn open_registration_mails_a_verify_link_and_verifies_once() { let tmp = tempfile::tempdir().expect("tempdir"); let (router, state) = app(tmp.path(), Registration::Open).await; + + // Case: a new account is unverified and a verification link is queued for it. let (cookie, precsrf) = precsrf_for(&router, "/register").await; let form = format!( "precsrf={precsrf}&invite=&username=dave&email=dave%40example.com\ &password=correct-horse-battery&confirm=correct-horse-battery" ); let (status, _, _) = send(&router, "POST", "/register", Some(&cookie), Some(&form)).await; - assert_eq!(status, 303); + assert_eq!(status, 303, "open: status"); let dave = state .store .user_by_username("dave") .await .unwrap() .expect("account"); - assert!(!state.store.email_is_verified(&dave.id).await.unwrap()); + assert!( + !state.store.email_is_verified(&dave.id).await.unwrap(), + "open: not verified yet" + ); let mail = state.store.recent_mail(10).await.unwrap(); assert!( mail.iter() .any(|m| m.to_addr == "dave@example.com" && m.body.contains("/verify/")), - "a verification link is queued" + "open: a verification link is queued" ); - } - #[tokio::test] - async fn verify_link_marks_the_address_verified_once() { - let tmp = tempfile::tempdir().expect("tempdir"); - let (router, state) = app(tmp.path(), Registration::Open).await; + // Case: the verify link marks the address verified once. The mail is picked by its + // recipient, since the dave mail is queued too. let user = state .store .create_user("erin", Some("erin@example.com"), "hash", false) @@ -657,26 +677,47 @@ mod tests { crate::mail::account::send_verify(&state, &user, "erin@example.com") .await .unwrap(); - let body = state.store.recent_mail(10).await.unwrap()[0].body.clone(); + let mail = state.store.recent_mail(10).await.unwrap(); + let body = mail + .iter() + .find(|m| m.to_addr == "erin@example.com") + .expect("erin mail") + .body + .clone(); let link = link_in(&body, "/verify/"); let path = link.trim_start_matches("https://forge.test"); - assert!(!state.store.email_is_verified(&user.id).await.unwrap()); + assert!( + !state.store.email_is_verified(&user.id).await.unwrap(), + "verify: starts unverified" + ); // A GET only shows the confirm button; it spends nothing. let (status, _, html) = send(&router, "GET", path, None, None).await; - assert_eq!(status, 200); - assert!(html.contains("Confirm address")); - assert!(!state.store.email_is_verified(&user.id).await.unwrap()); + assert_eq!(status, 200, "verify GET: status"); + assert!(html.contains("Confirm address"), "verify GET: button"); + assert!( + !state.store.email_is_verified(&user.id).await.unwrap(), + "verify GET: still unverified" + ); let (cookie, precsrf) = precsrf_for(&router, path).await; let form = format!("precsrf={precsrf}"); let (status, _, html) = send(&router, "POST", path, Some(&cookie), Some(&form)).await; - assert_eq!(status, 200); - assert!(html.contains("Your email address is verified")); - assert!(state.store.email_is_verified(&user.id).await.unwrap()); + assert_eq!(status, 200, "verify POST: status"); + assert!( + html.contains("Your email address is verified"), + "verify POST: notice" + ); + assert!( + state.store.email_is_verified(&user.id).await.unwrap(), + "verify POST: verified" + ); let (status, _, html) = send(&router, "POST", path, Some(&cookie), Some(&form)).await; - assert_eq!(status, 200); - assert!(html.contains("This verification link is invalid")); + assert_eq!(status, 200, "verify again: status"); + assert!( + html.contains("This verification link is invalid"), + "verify again: spent" + ); } } diff --git a/crates/forge-web/src/pages/security_tab_tests.rs b/crates/forge-web/src/pages/security_tab_tests.rs index be086cc..526ff8e 100644 --- a/crates/forge-web/src/pages/security_tab_tests.rs +++ b/crates/forge-web/src/pages/security_tab_tests.rs @@ -76,23 +76,20 @@ async fn fixture(site: &Site) -> (String, String) { (owner_cookie, reader_cookie) } +/// One advisories-on site serves the owner, a Write collaborator and a reader in turn. #[tokio::test] -async fn security_tab_shows_to_the_owner_when_advisories_are_on() { +async fn security_tab_follows_the_role_while_advisories_are_on() { let site = site(true).await; - let (owner_cookie, _) = fixture(&site).await; + let (owner_cookie, reader_cookie) = fixture(&site).await; + let (status, body) = get(&site, "/owner/proj/issues", Some(&owner_cookie)).await; - assert_eq!(status, 200); + assert_eq!(status, 200, "owner page"); assert!( body.contains(SECURITY_TAB), "owner should see the Security tab" ); assert!(body.contains("/owner/proj/security")); -} -#[tokio::test] -async fn security_tab_shows_to_write_collaborators() { - let site = site(true).await; - fixture(&site).await; let writer = site .store .create_user("writer", None, "unused", false) @@ -110,25 +107,21 @@ async fn security_tab_shows_to_write_collaborators() { .unwrap(); let writer_cookie = sign_in(&site.store, &writer.id, "writer-token").await; let (status, body) = get(&site, "/owner/proj/issues", Some(&writer_cookie)).await; - assert_eq!(status, 200); + assert_eq!(status, 200, "writer page"); assert!( body.contains(SECURITY_TAB), "a Write collaborator should see the tab" ); -} -#[tokio::test] -async fn security_tab_is_hidden_from_readers() { - let site = site(true).await; - let (_, reader_cookie) = fixture(&site).await; let (status, body) = get(&site, "/owner/proj/issues", Some(&reader_cookie)).await; - assert_eq!(status, 200); + assert_eq!(status, 200, "reader page"); assert!( !body.contains(SECURITY_TAB), "a reader must not see the tab" ); } +/// With advisories off, even the owner gets no tab. #[tokio::test] async fn security_tab_is_hidden_when_advisories_are_off() { let site = site(false).await; diff --git a/crates/forge-web/src/pages/snippets.rs b/crates/forge-web/src/pages/snippets.rs index 4e008e0..ff050da 100644 --- a/crates/forge-web/src/pages/snippets.rs +++ b/crates/forge-web/src/pages/snippets.rs @@ -833,8 +833,11 @@ mod tests { .collect() } + /// Saving drops blank cards but editing keeps them, and a leading newline survives the + /// textarea. #[test] - fn blank_cards_are_dropped_only_on_save() { + fn draft_saves_drop_blank_cards_and_keep_leading_newlines() { + // Case: every rendered card is kept while editing; a save drops the blank ones. let draft = Draft::from_form(&form(&[ ("title", "t"), ("visibility", "public"), @@ -845,38 +848,52 @@ mod tests { ("name_2", "b.rs"), ("content_2", ""), ])); - assert_eq!( - draft.files.len(), - 3, - "every rendered card is kept while editing" - ); + assert_eq!(draft.files.len(), 3, "blank cards: every card is kept while editing"); let saved = draft.saved_files(); - assert_eq!(saved.len(), 2); - assert_eq!(saved[0].content, "one\ntwo"); - assert_eq!(saved[1].name, "b.rs"); + assert_eq!(saved.len(), 2, "blank cards: a save drops the blank ones"); + assert_eq!(saved[0].content, "one\ntwo", "blank cards: CRLF is normalised"); + assert_eq!(saved[1].name, "b.rs", "blank cards: the kept file"); + + // Case: a leading newline in a file survives the textarea. + let mut draft = Draft::blank(); + draft.files = vec![( + 0, + SnippetFile { + name: "a".into(), + content: "\nx".into(), + }, + )]; + assert_eq!(draft.slots()[0].content, "\n\nx", "leading newline"); } + /// The card steps: a new form shows one card, add and remove move the cards, the shown tab + /// follows the step, and a save or a failed save keeps the posted tab. #[test] - fn new_form_shows_one_empty_card() { + fn card_steps_add_remove_and_show_the_right_tab() { + // Case: a new form shows one empty card. let draft = Draft::blank(); let slots = draft.slots(); - assert_eq!(slots.len(), 1); - assert_eq!((slots[0].number, slots[0].name.as_str()), (0, "")); - } + assert_eq!(slots.len(), 1, "new form: one card"); + assert_eq!( + (slots[0].number, slots[0].name.as_str()), + (0, ""), + "new form: the card is empty" + ); - #[test] - fn add_appends_a_card_until_the_snippet_is_full() { + // Case: add appends a card until the snippet is full. let mut draft = Draft::blank(); for _ in 0..MAX_FILES + 3 { draft.add_blank(); } - assert_eq!(draft.slots().len(), MAX_FILES); + assert_eq!(draft.slots().len(), MAX_FILES, "add: stops at the limit"); let numbers: Vec = draft.slots().iter().map(|s| s.number).collect(); - assert_eq!(numbers, (0..MAX_FILES).collect::>()); - } + assert_eq!( + numbers, + (0..MAX_FILES).collect::>(), + "add: numbers run from zero" + ); - #[test] - fn remove_keeps_the_other_field_numbers() { + // Case: removing a card keeps the other field numbers. let mut draft = Draft::blank(); draft.add_blank(); draft.add_blank(); @@ -884,72 +901,52 @@ mod tests { draft.files[1].1.name = "b.txt".into(); draft.remove(0); let numbers: Vec = draft.slots().iter().map(|s| s.number).collect(); - assert_eq!(numbers, vec![1, 2]); - assert_eq!(draft.slots()[0].name, "b.txt"); - } + assert_eq!(numbers, vec![1, 2], "remove: numbers are kept"); + assert_eq!(draft.slots()[0].name, "b.txt", "remove: the other card's name"); - #[test] - fn add_and_remove_clicks_are_told_apart_from_a_save() { + // Case: add and remove clicks are told apart from a save. let add = form(&[("op", "add"), ("name_0", "a")]); let mut draft = Draft::from_form(&add); - assert_eq!(apply_slot_step(&mut draft, &add), Some(1)); - assert_eq!(draft.slots().len(), 2); + assert_eq!(apply_slot_step(&mut draft, &add), Some(1), "add click: tab"); + assert_eq!(draft.slots().len(), 2, "add click: two cards"); let remove = form(&[("remove", "1"), ("name_0", "a"), ("name_1", "")]); let mut draft = Draft::from_form(&remove); - assert_eq!(apply_slot_step(&mut draft, &remove), Some(0)); - assert_eq!(draft.slots().len(), 1); + assert_eq!(apply_slot_step(&mut draft, &remove), Some(0), "remove click: tab"); + assert_eq!(draft.slots().len(), 1, "remove click: one card"); assert_eq!( apply_slot_step(&mut Draft::blank(), &form(&[("title", "t")])), - None + None, + "save: not a card step" ); - } - #[test] - fn add_shows_the_new_last_file() { + // Case: add shows the new last file. let mut draft = Draft::blank(); let add = form(&[("op", "add"), ("name_0", "a")]); - assert_eq!(apply_slot_step(&mut draft, &add), Some(0)); - assert_eq!(apply_slot_step(&mut draft, &add), Some(1)); - assert_eq!(draft.slots().len(), 2); - } + assert_eq!(apply_slot_step(&mut draft, &add), Some(0), "add shows: first add"); + assert_eq!(apply_slot_step(&mut draft, &add), Some(1), "add shows: new last"); + assert_eq!(draft.slots().len(), 2, "add shows: two cards"); - #[test] - fn remove_shows_the_file_before_the_removed_one() { + // Case: removing a card shows the file before it, and the first one when it is first. let mut draft = Draft::blank(); for _ in 0..3 { draft.add_blank(); } // Files 0..=2 at positions 0..=2; removing the file at position 2 shows position 1. let remove = form(&[("remove", "2")]); - assert_eq!(apply_slot_step(&mut draft, &remove), Some(1)); + assert_eq!(apply_slot_step(&mut draft, &remove), Some(1), "remove shows: before"); // Removing the first file shows the new first one. let remove = form(&[("remove", "0")]); - assert_eq!(apply_slot_step(&mut draft, &remove), Some(0)); - } + assert_eq!(apply_slot_step(&mut draft, &remove), Some(0), "remove shows: first"); - #[test] - fn a_failed_save_keeps_the_posted_tab() { + // Case: a failed save keeps the posted tab, and falls back to the first. let mut draft = Draft::blank(); for _ in 0..3 { draft.add_blank(); } let numbers: Vec = draft.slots().iter().map(|s| s.number).collect(); - assert_eq!(numbers, vec![0, 1, 2]); - assert_eq!(posted_tab(&draft, &form(&[("tab", "2")])), 2); - assert_eq!(posted_tab(&draft, &form(&[("tab", "9")])), 0); - assert_eq!(posted_tab(&draft, &form(&[])), 0); - } - - #[test] - fn leading_newline_survives_the_textarea() { - let mut draft = Draft::blank(); - draft.files = vec![( - 0, - SnippetFile { - name: "a".into(), - content: "\nx".into(), - }, - )]; - assert_eq!(draft.slots()[0].content, "\n\nx"); + assert_eq!(numbers, vec![0, 1, 2], "failed save: three cards"); + assert_eq!(posted_tab(&draft, &form(&[("tab", "2")])), 2, "failed save: posted tab"); + assert_eq!(posted_tab(&draft, &form(&[("tab", "9")])), 0, "failed save: unknown tab"); + assert_eq!(posted_tab(&draft, &form(&[])), 0, "failed save: no tab"); } }