diff --git a/crates/forge-web/src/api/gitea_tests.rs b/crates/forge-web/src/api/gitea_tests.rs index 60c8f28..7f98544 100644 --- a/crates/forge-web/src/api/gitea_tests.rs +++ b/crates/forge-web/src/api/gitea_tests.rs @@ -273,8 +273,10 @@ fn repo_path_of(rest: &str) -> String { format!("/api/v1/repos/{OWNER}/{REPO}{rest}") } +/// Read routes that share one fixture: version and settings, the repo, its issues, and +/// pagination. None of them changes state, so the scenarios cannot interfere. #[tokio::test] -async fn version_and_settings_unlock_every_feature() { +async fn version_repo_issues_and_pagination() { let f = fixture().await; let (status, _, body) = f.get_as("/api/v1/version", None).await; assert_eq!(status, 200); @@ -282,11 +284,8 @@ async fn version_and_settings_unlock_every_feature() { let (status, _, body) = f.get_as("/api/v1/settings/api", None).await; assert_eq!(status, 200); assert_eq!(body["max_response_items"], 50); -} -#[tokio::test] -async fn repo_info_topics_labels_and_milestones() { - let f = fixture().await; + // The repo, its topics, labels and milestones. let (status, _, repo) = f.get(&repo_path_of("")).await; assert_eq!(status, 200); assert_eq!(repo["name"], REPO); @@ -326,11 +325,8 @@ async fn repo_info_topics_labels_and_milestones() { assert_eq!(m["state"], "open"); assert_eq!(m["due_on"], "2026-12-01T00:00:00Z"); assert!(m["created_at"].is_string()); -} -#[tokio::test] -async fn issues_carry_labels_milestone_assignees_and_comments() { - let f = fixture().await; + // Issues with their labels, milestone, assignees, comments and reactions. let (status, headers, issues) = f .get(&repo_path_of( "/issues?type=issues&state=all&page=1&limit=10", @@ -376,11 +372,8 @@ async fn issues_carry_labels_milestone_assignees_and_comments() { assert_eq!(status, 200); assert_eq!(reactions[0]["reaction"], "+1"); assert_eq!(reactions[0]["user"]["login"], OWNER); -} -#[tokio::test] -async fn pagination_headers_and_link() { - let f = fixture().await; + // Pagination headers, the Link header, and the empty last page. let (status, headers, items) = f .get(&repo_path_of("/issues/1/comments?page=2&limit=1")) .await; @@ -413,9 +406,11 @@ async fn pagination_headers_and_link() { assert_eq!(items.as_array().unwrap().len(), 0); } +/// Pull requests, reviews and releases, which share one fixture as read-only scenarios. #[tokio::test] -async fn pulls_reviews_and_review_comments() { +async fn pulls_reviews_and_releases_in_gitea_shape() { let f = fixture().await; + // Pull requests and their reviews and review comments. let (status, headers, pulls) = f .get(&repo_path_of("/pulls?state=all&page=1&limit=10")) .await; @@ -477,11 +472,8 @@ async fn pulls_reviews_and_review_comments() { // An issue number is not a pull request. let (status, _, _) = f.get(&repo_path_of("/pulls/1/reviews")).await; assert_eq!(status, 404); -} -#[tokio::test] -async fn releases_and_assets_in_gitea_shape() { - let f = fixture().await; + // Releases and their assets in the Gitea shape. let (status, headers, releases) = f.get(&repo_path_of("/releases?page=1&limit=10")).await; assert_eq!(status, 200); assert_eq!(headers["x-total-count"], "1"); @@ -515,9 +507,11 @@ async fn releases_and_assets_in_gitea_shape() { assert_eq!(one["browser_download_url"], url); } +/// Private repos and release asset downloads, which both follow the token rules. #[tokio::test] -async fn private_repos_follow_the_token() { +async fn private_repos_and_asset_downloads_follow_the_token() { let f = fixture().await; + // Private repos follow the token. let secret = "/api/v1/repos/tahinli/secret"; let (status, _, _) = f.get_as(secret, None).await; assert_eq!(status, 401, "anonymous"); @@ -558,11 +552,8 @@ async fn private_repos_follow_the_token() { .get_as(&repo_path_of(""), Some("token forge_nope".into())) .await; assert_eq!(status, 401); -} -#[tokio::test] -async fn release_asset_downloads_with_a_token() { - let f = fixture().await; + // Release asset downloads take the token too. let path = "/tahinli/proj/releases/download/v1.0/app.bin"; let owner = f.owner_token.clone(); let basic = format!("Basic {}", BASE64_STANDARD.encode(format!("x:{owner}"))); diff --git a/crates/forge-web/src/api/releases.rs b/crates/forge-web/src/api/releases.rs index 43064c6..703fc3a 100644 --- a/crates/forge-web/src/api/releases.rs +++ b/crates/forge-web/src/api/releases.rs @@ -642,22 +642,29 @@ mod tests { .await } + /// Refused creates share one fixture and store nothing. Each case is labelled in its message. #[tokio::test] - async fn anonymous_and_bad_tokens_are_unauthorized() { + async fn refused_creates_return_their_status() { let f = fixture(None).await; - let (status, body) = post_json(&f, None, r#"{"tag":"v1"}"#).await; - assert_eq!(status, 401); - assert!(body["error"].is_string()); - let (status, _) = - post_json(&f, Some("Bearer forge_not_a_real_token"), r#"{"tag":"v1"}"#).await; - assert_eq!(status, 401); - } - - #[tokio::test] - async fn token_without_repo_scope_is_forbidden() { - let f = fixture(None).await; - let (status, _) = post_json(&f, Some(&bearer(&f.scopeless_token)), r#"{"tag":"v1"}"#).await; - assert_eq!(status, 403); + let scopeless = bearer(&f.scopeless_token); + // (case, auth, expected status, expects a JSON error body) + let cases: [(&str, Option<&str>, u16, bool); 3] = [ + ("anonymous", None, 401, true), + ( + "bad token", + Some("Bearer forge_not_a_real_token"), + 401, + false, + ), + ("token without repo scope", Some(scopeless.as_str()), 403, false), + ]; + for (name, auth, want, error_body) in cases { + let (status, body) = post_json(&f, auth, r#"{"tag":"v1"}"#).await; + assert_eq!(status, want, "case {name}: {body}"); + if error_body { + assert!(body["error"].is_string(), "case {name}"); + } + } } #[tokio::test] diff --git a/crates/forge-web/src/api/statuses.rs b/crates/forge-web/src/api/statuses.rs index 16a6602..bc5fb76 100644 --- a/crates/forge-web/src/api/statuses.rs +++ b/crates/forge-web/src/api/statuses.rs @@ -340,160 +340,46 @@ mod tests { assert_eq!(body["statuses"].as_array().map(Vec::len), Some(1)); } + /// Every refused write shares one repo fixture, and each case is labelled in its message. #[tokio::test] - async fn read_only_token_is_forbidden_to_post() { + async fn refused_writes_return_their_status() { let s = setup(Visibility::Public).await; - let (status, body) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - Some(&bearer(&s.reader_token)), - None, - Some(SUCCESS), - ) - .await; - assert_eq!(status, 403, "{body}"); - assert!(body["error"].is_string()); - } - - #[tokio::test] - async fn anonymous_and_bad_tokens_are_unauthorized() { - let s = setup(Visibility::Public).await; - let (status, body) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - None, - None, - Some(SUCCESS), - ) - .await; - assert_eq!(status, 401); - assert!(body["error"].is_string()); - - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - Some("Bearer forge_not_a_real_token"), - None, - Some(SUCCESS), - ) - .await; - assert_eq!(status, 401); - } - - #[tokio::test] - async fn session_cookie_alone_is_rejected() { - let s = setup(Visibility::Public).await; - let owner = - s.fx.store - .user_by_username(OWNER) - .await - .unwrap() - .expect("owner"); + let owner = s + .fx + .store + .user_by_username(OWNER) + .await + .unwrap() + .expect("owner"); let session = generate_token(); crate::test_support::create_session(&s.fx.store, &owner.id, &session, "csrf-value").await; let cookie = format!("__Host-{SESSION_COOKIE}={session}"); - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - None, - Some(&cookie), - Some(SUCCESS), - ) - .await; - assert_eq!(status, 401); - } - - #[tokio::test] - async fn token_without_repo_scope_is_forbidden() { - let s = setup(Visibility::Public).await; - let owner = - s.fx.store - .user_by_username(OWNER) - .await - .unwrap() - .expect("owner"); - let raw = token_for(&s.fx.store, &owner.id, &[]).await; - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - Some(&bearer(&raw)), - None, - Some(SUCCESS), - ) - .await; - assert_eq!(status, 403); - } - - #[tokio::test] - async fn bad_sha_and_bad_body_are_rejected() { - let s = setup(Visibility::Public).await; - let auth = bearer(&s.writer_token); - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri("abc123"), - Some(&auth), - None, - Some(SUCCESS), - ) - .await; - assert_eq!(status, 422); - - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - Some(&auth), - None, - Some(r#"{"state":"maybe"}"#), - ) - .await; - assert_eq!(status, 422); - - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - Some(&auth), - None, - Some("{not json"), - ) - .await; - assert_eq!(status, 400); - - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri(&s.sha), - Some(&auth), - None, - Some(r#"{"state":"success","target_url":"javascript:alert(1)"}"#), - ) - .await; - assert_eq!(status, 422); - } - - #[tokio::test] - async fn unknown_commit_is_not_found() { - let s = setup(Visibility::Public).await; - let missing = "0".repeat(40); - let (status, _) = send( - &s.fx.router, - "POST", - &report_uri(&missing), - Some(&bearer(&s.writer_token)), - None, - Some(SUCCESS), - ) - .await; - assert_eq!(status, 404); - let (status, _) = send(&s.fx.router, "GET", &list_uri(&missing), None, None, None).await; - assert_eq!(status, 404); + let unscoped = bearer(&token_for(&s.fx.store, &owner.id, &[]).await); + let writer = bearer(&s.writer_token); + let reader = bearer(&s.reader_token); + let report = report_uri(&s.sha); + let bad_sha = report_uri("abc123"); + let missing = report_uri(&"0".repeat(40)); + // (case, uri, auth, cookie, body, expected status, expects a JSON error body) + let cases: [(&str, &str, Option<&str>, Option<&str>, Option<&str>, u16, bool); 10] = [ + ("read-only token", report.as_str(), Some(reader.as_str()), None, Some(SUCCESS), 403, true), + ("anonymous", report.as_str(), None, None, Some(SUCCESS), 401, true), + ("bad token", report.as_str(), Some("Bearer forge_not_a_real_token"), None, Some(SUCCESS), 401, false), + ("session cookie alone", report.as_str(), None, Some(cookie.as_str()), Some(SUCCESS), 401, false), + ("token without repo scope", report.as_str(), Some(unscoped.as_str()), None, Some(SUCCESS), 403, false), + ("sha too short", bad_sha.as_str(), Some(writer.as_str()), None, Some(SUCCESS), 422, false), + ("unknown state", report.as_str(), Some(writer.as_str()), None, Some(r#"{"state":"maybe"}"#), 422, false), + ("malformed json", report.as_str(), Some(writer.as_str()), None, Some("{not json"), 400, false), + ("javascript target url", report.as_str(), Some(writer.as_str()), None, Some(r#"{"state":"success","target_url":"javascript:alert(1)"}"#), 422, false), + ("unknown commit", missing.as_str(), Some(writer.as_str()), None, Some(SUCCESS), 404, false), + ]; + for (name, uri, auth, cookie, body, want, error_body) in cases { + let (status, json) = send(&s.fx.router, "POST", uri, auth, cookie, body).await; + assert_eq!(status, want, "case {name}: {json}"); + if error_body { + assert!(json["error"].is_string(), "case {name}"); + } + } } #[tokio::test] diff --git a/crates/forge-web/src/backup/tests.rs b/crates/forge-web/src/backup/tests.rs index 2e2f5db..918d572 100644 --- a/crates/forge-web/src/backup/tests.rs +++ b/crates/forge-web/src/backup/tests.rs @@ -222,10 +222,14 @@ async fn end_to_end_set_verifies_with_correct_contents_and_modes() { assert_eq!(only_entry(&out), summary.path); } +/// Each tampering gets its own backup set, so one check cannot hide another. Every case is +/// labelled in its message. #[tokio::test] -async fn one_flipped_bundle_byte_fails_the_sha_check() { +async fn tampered_sets_fail_the_check_that_catches_them() { let fx = fixture().await; - let out = fx.dir.path().join("out"); + + // A flipped bundle byte fails the bundle's sha256. + let out = fx.dir.path().join("out-bundle"); let summary = create_backup(&fx.source, &opts(&out, false, Scope::All)) .await .expect("backup"); @@ -236,19 +240,16 @@ async fn one_flipped_bundle_byte_fails_the_sha_check() { std::fs::write(&bundle, &bytes).expect("tamper"); let report = verify_backup(&summary.path, &fx.git).await.expect("verify"); - assert!(!report.is_ok()); + assert!(!report.is_ok(), "case bundle byte"); let needle = format!("repos/{}.bundle: sha256 mismatch", fx.demo_id); assert!( report.problems.iter().any(|p| p.contains(&needle)), - "{:?}", + "case bundle byte: {:?}", report.problems ); -} -#[tokio::test] -async fn tampered_db_fails_the_sha_check() { - let fx = fixture().await; - let out = fx.dir.path().join("out"); + // An appended byte fails both the size and the sha256 of the database. + let out = fx.dir.path().join("out-db"); let summary = create_backup(&fx.source, &opts(&out, false, Scope::All)) .await .expect("backup"); @@ -263,7 +264,7 @@ async fn tampered_db_fails_the_sha_check() { .problems .iter() .any(|p| p.starts_with("db/forge.db: size mismatch")), - "{:?}", + "case appended db byte: {:?}", report.problems ); assert!( @@ -271,15 +272,13 @@ async fn tampered_db_fails_the_sha_check() { .problems .iter() .any(|p| p.starts_with("db/forge.db: sha256 mismatch")), - "{:?}", + "case appended db byte: {:?}", report.problems ); -} -#[tokio::test] -async fn a_damaged_db_fails_even_when_the_manifest_is_rewritten_to_match() { - let fx = fixture().await; - let out = fx.dir.path().join("out"); + // A truncated database fails the snapshot check even when the manifest is rewritten to + // match, so only the DB checks can catch it. + let out = fx.dir.path().join("out-truncated"); let summary = create_backup(&fx.source, &opts(&out, false, Scope::All)) .await .expect("backup"); @@ -287,7 +286,6 @@ async fn a_damaged_db_fails_even_when_the_manifest_is_rewritten_to_match() { let bytes = std::fs::read(&db).expect("read db"); std::fs::write(&db, &bytes[..bytes.len() / 2]).expect("truncate"); - // Make the manifest agree with the damaged file, so only the DB checks can catch it. let mut m = read_manifest(&summary.path); let (new_bytes, new_sha) = { let data = std::fs::read(&db).expect("read"); @@ -307,15 +305,18 @@ async fn a_damaged_db_fails_even_when_the_manifest_is_rewritten_to_match() { .problems .iter() .any(|p| p.starts_with("database snapshot failed verification")), - "{:?}", + "case truncated db: {:?}", report.problems ); } +/// A manifest repo list that disagrees with the DB snapshot, and a stray file in the set, are +/// each reported. Each case has its own backup set. #[tokio::test] -async fn manifest_repo_list_must_match_the_db_snapshot() { +async fn manifest_and_stray_file_problems_are_reported() { let fx = fixture().await; - let out = fx.dir.path().join("out"); + + let out = fx.dir.path().join("out-manifest"); let summary = create_backup(&fx.source, &opts(&out, false, Scope::All)) .await .expect("backup"); @@ -329,15 +330,11 @@ async fn manifest_repo_list_must_match_the_db_snapshot() { .problems .iter() .any(|p| p.contains("does not match the database snapshot")), - "{:?}", + "case manifest repo list: {:?}", report.problems ); -} -#[tokio::test] -async fn unlisted_file_in_the_set_is_reported() { - let fx = fixture().await; - let out = fx.dir.path().join("out"); + let out = fx.dir.path().join("out-stray"); let summary = create_backup(&fx.source, &opts(&out, false, Scope::All)) .await .expect("backup"); @@ -348,7 +345,7 @@ async fn unlisted_file_in_the_set_is_reported() { .problems .iter() .any(|p| p.contains("unlisted file in the set: repos/stray.txt")), - "{:?}", + "case stray file: {:?}", report.problems ); } @@ -394,30 +391,33 @@ async fn key_is_excluded_by_default_and_included_on_request() { ); } +/// A failed backup leaves nothing behind. Each failure has its own output directory, and the +/// repo breaking case runs last because it damages the shared fixture. #[tokio::test] -async fn include_key_without_a_key_fails_and_leaves_nothing() { +async fn failed_backups_leave_no_partial_directory() { let fx = fixture().await; - let out = fx.dir.path().join("out"); + + let out = fx.dir.path().join("out-no-key"); let err = create_backup(&fx.source, &opts(&out, true, Scope::All)).await; - assert!(err.is_err()); - assert_eq!(std::fs::read_dir(&out).expect("out").count(), 0); -} + assert!(err.is_err(), "case include key without a key"); + assert_eq!( + std::fs::read_dir(&out).expect("out").count(), + 0, + "case include key without a key" + ); -#[tokio::test] -async fn failure_in_a_repo_leaves_no_partial_directory() { - let fx = fixture().await; - let out = fx.dir.path().join("out"); // A repo with no HEAD is not a repository, so reading its refs fails mid-backup. + let out = fx.dir.path().join("out-broken-repo"); let broken = repo_path(&fx.data_dir, &fx.demo_id).expect("path"); std::fs::remove_file(broken.join("HEAD")).expect("break repo"); let result = create_backup(&fx.source, &opts(&out, false, Scope::All)).await; - assert!(result.is_err(), "backup must fail"); + assert!(result.is_err(), "case broken repo: backup must fail"); let left: Vec = std::fs::read_dir(&out) .expect("out") .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) .collect(); - assert!(left.is_empty(), "nothing may be left behind: {left:?}"); + assert!(left.is_empty(), "case broken repo, nothing may be left behind: {left:?}"); } #[tokio::test] diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index 7d84a56..a83001f 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -1360,12 +1360,6 @@ mod tests { use super::*; use http::HeaderValue; - fn headers(value: &'static str) -> HeaderMap { - let mut map = HeaderMap::new(); - map.insert(ACCEPT_LANGUAGE, HeaderValue::from_static(value)); - map - } - #[test] fn every_key_has_text_in_both_languages() { for key in ALL { @@ -1382,36 +1376,38 @@ mod tests { } #[test] - fn stored_language_wins_over_the_browser() { - let turkish = headers("tr"); - assert_eq!(resolve(Some("en"), &turkish), Lang::En); - assert_eq!(resolve(Some("tr"), &HeaderMap::new()), Lang::Tr); - } - - #[test] - fn auto_and_missing_preferences_follow_the_browser() { - assert_eq!(resolve(Some("auto"), &headers("tr-TR,en;q=0.5")), Lang::Tr); - assert_eq!(resolve(None, &headers("tr")), Lang::Tr); - assert_eq!(resolve(None, &HeaderMap::new()), Lang::En); - } - - #[test] - fn accept_language_picks_the_highest_quality_supported_tag() { - assert_eq!(resolve(None, &headers("de,en;q=0.8,tr;q=0.9")), Lang::Tr); - assert_eq!(resolve(None, &headers("en;q=0.9,tr;q=0.5")), Lang::En); - assert_eq!(resolve(None, &headers("tr;q=0,en")), Lang::En); - assert_eq!(resolve(None, &headers("de,fr;q=0.9")), Lang::En); - assert_eq!(resolve(None, &headers("tr;q=oops,en;q=0.1")), Lang::En); + fn stored_preference_then_browser_picks_the_language() { + // (case, stored preference, Accept-Language, expected) + // An empty accept string means the header is absent. + let cases: [(&str, Option<&str>, &str, Lang); 10] = [ + ("stored en beats browser tr", Some("en"), "tr", Lang::En), + ("stored tr with no header", Some("tr"), "", Lang::Tr), + ("auto follows browser", Some("auto"), "tr-TR,en;q=0.5", Lang::Tr), + ("missing preference follows browser", None, "tr", Lang::Tr), + ("no preference, no header", None, "", Lang::En), + ("highest q supported wins", None, "de,en;q=0.8,tr;q=0.9", Lang::Tr), + ("higher q for en", None, "en;q=0.9,tr;q=0.5", Lang::En), + ("q=0 rejects tr", None, "tr;q=0,en", Lang::En), + ("unsupported tags fall back to en", None, "de,fr;q=0.9", Lang::En), + ("malformed q is ignored", None, "tr;q=oops,en;q=0.1", Lang::En), + ]; + for (name, stored, accept, want) in cases { + let map = if accept.is_empty() { + HeaderMap::new() + } else { + let mut map = HeaderMap::new(); + map.insert(ACCEPT_LANGUAGE, HeaderValue::from_str(accept).expect("ascii")); + map + }; + assert_eq!(resolve(stored, &map), want, "case {name}"); + } } #[test] - fn unknown_stored_code_is_english() { + fn language_codes_round_trip_and_unknown_is_english() { + // The codes are stored in the database, so the literals are checked explicitly. assert_eq!(Lang::from_code("fr"), Lang::En); assert_eq!(Lang::from_code("tr"), Lang::Tr); - } - - #[test] - fn html_codes_match_the_languages() { assert_eq!(Lang::En.code(), "en"); assert_eq!(Lang::Tr.code(), "tr"); } diff --git a/crates/forge-web/src/importer/tests.rs b/crates/forge-web/src/importer/tests.rs index 7f6636a..9deb26a 100644 --- a/crates/forge-web/src/importer/tests.rs +++ b/crates/forge-web/src/importer/tests.rs @@ -260,11 +260,11 @@ fn fake() -> Fake { async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() { let fx = fixture().await; let job = new_job(&fx, Source::Git).await; - let spec = spec(Source::Git, ImportOptions::default()); + let git_spec = spec(Source::Git, ImportOptions::default()); run_job::( &fx.state, &job, - &spec, + &git_spec, None, &Transport::Local(fx.upstream.clone()), ) @@ -294,6 +294,21 @@ async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() { .unwrap() .is_none() ); + + // A fetch from a missing remote fails its job, and the failure is recorded. + let bad_job = new_job(&fx, Source::Git).await; + let bad_spec = spec(Source::Git, ImportOptions::default()); + run_job::( + &fx.state, + &bad_job, + &bad_spec, + None, + &Transport::Local("/nonexistent/path.git".into()), + ) + .await; + let bad_job = fx.state.store.import_job(&bad_job.id).await.unwrap().unwrap(); + assert_eq!(bad_job.state, ImportState::Failed); + assert!(bad_job.error.is_some()); } #[tokio::test] @@ -366,32 +381,19 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() { assert_eq!(assets.len(), 1); assert_eq!(assets[0].name, "app_1.tar.gz"); assert_eq!(assets[0].size, 5); -} -#[tokio::test] -async fn running_an_import_twice_creates_nothing_twice() { - let fx = fixture().await; - let api = fake(); - let spec = spec(Source::GitHub, everything()); - for _ in 0..2 { - let job = new_job(&fx, Source::GitHub).await; - run_job( - &fx.state, - &job, - &spec, - Some(&api), - &Transport::Local(fx.upstream.clone()), - ) - .await; - let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(job.state, ImportState::Done, "{:?}", job.error); - } - let store = &fx.state.store; - let all = IssueFilter { - state: None, - per_page: 100, - ..IssueFilter::default() - }; + // A second run of the same import creates nothing twice. + let again = new_job(&fx, Source::GitHub).await; + run_job( + &fx.state, + &again, + &spec, + Some(&api), + &Transport::Local(fx.upstream.clone()), + ) + .await; + let again = store.import_job(&again.id).await.unwrap().unwrap(); + assert_eq!(again.state, ImportState::Done, "{:?}", again.error); let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); assert_eq!(total, 2); let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); @@ -489,24 +491,6 @@ async fn the_token_is_never_written_to_the_database() { ); } -#[tokio::test] -async fn a_failed_git_fetch_marks_the_job_failed() { - let fx = fixture().await; - let job = new_job(&fx, Source::Git).await; - let spec = spec(Source::Git, ImportOptions::default()); - run_job::( - &fx.state, - &job, - &spec, - None, - &Transport::Local("/nonexistent/path.git".into()), - ) - .await; - let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(job.state, ImportState::Failed); - assert!(job.error.is_some()); -} - #[test] fn the_origin_note_escapes_the_mention_and_cleans_the_name() { let note = origin_note( diff --git a/crates/forge-web/src/mail/templates.rs b/crates/forge-web/src/mail/templates.rs index c8cd124..67bfad3 100644 --- a/crates/forge-web/src/mail/templates.rs +++ b/crates/forge-web/src/mail/templates.rs @@ -214,15 +214,16 @@ mod tests { } #[test] - fn subject_names_the_repo_title_and_number() { - let (subject, _) = notification(Lang::En, &sample(None, "Crash on start")); - assert_eq!(subject, "[bob/widgets] Crash on start (#7)"); - } - - #[test] - fn a_newline_in_the_title_cannot_split_the_subject() { - let (subject, _) = notification(Lang::En, &sample(None, "two\r\nlines")); - assert_eq!(subject, "[bob/widgets] two lines (#7)"); + fn subject_names_the_repo_title_and_number_and_stays_on_one_line() { + // A plain title is named as-is; a newline in the title cannot split the subject. + let cases = [ + ("plain", "Crash on start", "[bob/widgets] Crash on start (#7)"), + ("newline", "two\r\nlines", "[bob/widgets] two lines (#7)"), + ]; + for (name, title, want) in cases { + let (subject, _) = notification(Lang::En, &sample(None, title)); + assert_eq!(subject, want, "case {name}"); + } } #[test] diff --git a/crates/forge-web/src/pulls_sync.rs b/crates/forge-web/src/pulls_sync.rs index c8d2c9c..bb870e5 100644 --- a/crates/forge-web/src/pulls_sync.rs +++ b/crates/forge-web/src/pulls_sync.rs @@ -738,7 +738,7 @@ mod tests { } #[test] - fn unchanged_line_follows_insertions_above() { + fn unchanged_line_follows_insertions_and_skips_changed_lines() { let old = "a\nb\nc\n"; let new = "x\na\nb\nc\n"; assert_eq!(unchanged_line(old, new, 1), Some(2)); @@ -746,10 +746,7 @@ mod tests { assert_eq!(unchanged_line(old, new, 3), Some(4)); assert_eq!(unchanged_line(old, new, 0), None); assert_eq!(unchanged_line(old, new, 9), None); - } - - #[test] - fn unchanged_line_is_none_for_modified_or_deleted_lines() { + // A modified or deleted line has no unchanged counterpart. assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 2), None); assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 3), Some(3)); assert_eq!(unchanged_line("a\nb\n", "a\n", 2), None); diff --git a/crates/forge-web/src/replication/mod.rs b/crates/forge-web/src/replication/mod.rs index 3da2b89..35c907d 100644 --- a/crates/forge-web/src/replication/mod.rs +++ b/crates/forge-web/src/replication/mod.rs @@ -651,7 +651,7 @@ mod tests { } #[test] - fn target_parses_user_host_and_base() { + fn target_parses_user_host_and_base_and_refuses_bad_specs() { let t = Target::parse("sb@standby.example:/srv/forge-standby", 2222).expect("parse"); assert_eq!(t.user.as_deref(), Some("sb")); assert_eq!(t.host, "standby.example"); @@ -663,10 +663,6 @@ mod tests { ); let bare = Target::parse("standby:/srv/x", 22).expect("parse"); assert_eq!(bare.destination(), "standby"); - } - - #[test] - fn target_rejects_bad_specs() { for bad in [ "no-colon", "sb@host", @@ -708,10 +704,6 @@ mod tests { assert!(!is_snapshot_name(".tmp-forge-20260101T120000Z.db")); assert!(!is_snapshot_name("forge-2026-01-01T12:00:00Z.db")); assert!(!is_snapshot_name("forge-20260101X120000Z.db")); - } - - #[test] - fn snapshot_stamp_has_the_expected_shape() { let stamp = snapshot_stamp(); assert!(is_snapshot_name(&format!("forge-{stamp}.db")), "{stamp}"); } diff --git a/crates/forge-web/src/views/heatmap.rs b/crates/forge-web/src/views/heatmap.rs index 96a18c1..0ba1af2 100644 --- a/crates/forge-web/src/views/heatmap.rs +++ b/crates/forge-web/src/views/heatmap.rs @@ -352,28 +352,35 @@ mod tests { } #[test] - fn a_gap_ends_the_current_streak_but_not_the_longest() { - let cal = build( - &counts(&[ - ("2026-09-20", 1), - ("2026-09-21", 1), - ("2026-09-22", 1), - ("2026-09-23", 1), - ("2026-09-24", 1), - ("2026-10-15", 2), - ("2026-10-16", 2), - ]), - TODAY, - ); - assert_eq!(cal.longest_streak, 5); - assert_eq!(cal.current_streak, 2); - } - - #[test] - fn an_old_run_is_not_the_current_streak() { - let cal = build(&counts(&[("2026-10-01", 3), ("2026-10-02", 3)]), TODAY); - assert_eq!(cal.current_streak, 0); - assert_eq!(cal.longest_streak, 2); + fn a_gap_or_an_old_run_ends_the_current_streak() { + // (case, counts, current streak, longest streak) + let cases: [(&str, &[(&str, u32)], u64, u64); 2] = [ + ( + "old run", + &[("2026-10-01", 3), ("2026-10-02", 3)], + 0, + 2, + ), + ( + "gap then two days", + &[ + ("2026-09-20", 1), + ("2026-09-21", 1), + ("2026-09-22", 1), + ("2026-09-23", 1), + ("2026-09-24", 1), + ("2026-10-15", 2), + ("2026-10-16", 2), + ], + 2, + 5, + ), + ]; + for (name, input, current, longest) in cases { + let cal = build(&counts(input), TODAY); + assert_eq!(cal.current_streak, current, "case {name}"); + assert_eq!(cal.longest_streak, longest, "case {name}"); + } } #[test] diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index e810e7c..4a083bb 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -1171,16 +1171,13 @@ mod tests { } #[test] - fn csp_allows_the_raw_origin_for_images() { + fn csp_allows_the_raw_origin_for_images_and_falls_back_otherwise() { let origin = origin_of("https://raw.forge.test:8443/some/path/"); assert_eq!(origin.as_deref(), Some("https://raw.forge.test:8443")); let csp = csp_for(origin.as_deref()); assert!(csp.contains("img-src 'self' data: https://raw.forge.test:8443;")); assert!(csp.contains("form-action 'self'; frame-ancestors 'none'")); - } - - #[test] - fn csp_falls_back_when_the_base_url_is_not_an_origin() { + // A base URL that is not an origin falls back to the plain policy. assert_eq!(origin_of("not a url"), None); assert_eq!(origin_of("ftp://files.test"), None); assert_eq!(origin_of("https://user:pw@files.test"), None); @@ -1239,25 +1236,26 @@ mod tests { } /// Renders `/settings/sessions` (a page that uses the shell) for a freshly signed-in user. - async fn menu_html(is_admin: bool) -> String { + async fn menu_html( + router: &topcoat::router::Router, + store: &forge_core::Store, + name: &str, + is_admin: bool, + token: &str, + ) -> String { use crate::auth::SESSION_COOKIE; use topcoat::router::request::Request; use topcoat::router::to_bytes; - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let store = state.store.clone(); - let router = crate::test_support::app_router(state.clone()); - let name = if is_admin { "root" } else { "tahinli" }; let user = store .create_user(name, None, "x", is_admin) .await .expect("user"); - crate::test_support::create_session(&store, &user.id, "menu-token", "menu-csrf").await; + crate::test_support::create_session(store, &user.id, token, "menu-csrf").await; let req = Request::builder() .method("GET") .uri("/settings/sessions") - .header("cookie", format!("__Host-{SESSION_COOKIE}=menu-token")) + .header("cookie", format!("__Host-{SESSION_COOKIE}={token}")) .body(Body::empty()) .expect("request"); let res = router.handle(req).await; @@ -1266,17 +1264,21 @@ mod tests { String::from_utf8_lossy(&bytes).into_owned() } + /// A user sees no admin links and an admin sees the one Admin entry. Both render from one + /// fixture. #[tokio::test] - async fn admin_links_are_hidden_from_non_admins() { - let html = menu_html(false).await; + async fn admin_links_follow_the_role() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let router = crate::test_support::app_router(state); + + let html = menu_html(&router, &store, "tahinli", false, "menu-token-user").await; assert!(html.contains("Log out"), "user menu is rendered"); assert!(!html.contains("/admin/users"), "no admin link for a user"); assert!(!html.contains("/admin/audit"), "no audit link for a user"); - } - #[tokio::test] - async fn admin_links_are_shown_to_admins() { - let html = menu_html(true).await; + let html = menu_html(&router, &store, "root", true, "menu-token-admin").await; assert!(html.contains("href=\"/admin/users\"")); assert!( !html.contains("Admin:"), @@ -1340,6 +1342,13 @@ mod shell_tests { assert!(html.contains("
")); assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\"")); + + // An anonymous page renders the default colours. + let tag = html_tag(&html); + assert!(tag.contains("data-accent-light=\"sage\""), "{tag}"); + assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}"); + assert!(tag.contains("data-base-light=\"fern\""), "{tag}"); + assert!(tag.contains("data-base-dark=\"fern\""), "{tag}"); } /// The `` start tag of a page. @@ -1351,14 +1360,16 @@ mod shell_tests { /// The `` tag of `/settings/sessions` for a signed-in user whose stored colours are the /// four ids given, in the order light accent, dark accent, light base, dark base. - async fn html_tag_for_colours(colours: [&str; 4]) -> String { + async fn html_tag_for_colours( + router: &topcoat::router::Router, + store: &forge_core::Store, + name: &str, + token: &str, + colours: [&str; 4], + ) -> String { use crate::auth::SESSION_COOKIE; - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let store = state.store.clone(); - let router = crate::test_support::app_router(state); let user = store - .create_user("tahinli", None, "x", false) + .create_user(name, None, "x", false) .await .expect("user"); let [accent_light, accent_dark, base_light, base_dark] = colours; @@ -1366,11 +1377,11 @@ mod shell_tests { .set_colours(&user.id, accent_light, accent_dark, base_light, base_dark) .await .expect("colours"); - crate::test_support::create_session(&store, &user.id, "colour-token", "colour-csrf").await; + crate::test_support::create_session(store, &user.id, token, "colour-csrf").await; let req = Request::builder() .method("GET") .uri("/settings/sessions") - .header("cookie", format!("__Host-{SESSION_COOKIE}=colour-token")) + .header("cookie", format!("__Host-{SESSION_COOKIE}={token}")) .body(Body::empty()) .unwrap(); let res = router.handle(req).await; @@ -1379,50 +1390,36 @@ mod shell_tests { html_tag(&String::from_utf8_lossy(&bytes)).to_owned() } + /// Every colour case shares one fixture; each has its own user and session. #[tokio::test] async fn the_html_tag_carries_the_viewers_colours() { - let tag = html_tag_for_colours(["ocean", "plum", "ink", "dusk"]).await; + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let router = crate::test_support::app_router(state); + + let tag = html_tag_for_colours(&router, &store, "tahinli", "colour-token", ["ocean", "plum", "ink", "dusk"]).await; assert!(tag.contains("data-accent-light=\"ocean\""), "{tag}"); assert!(tag.contains("data-accent-dark=\"plum\""), "{tag}"); assert!(tag.contains("data-base-light=\"ink\""), "{tag}"); assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}"); assert!(!tag.contains("data-accent="), "{tag}"); // Stored ids that are no longer offered fall back to the defaults, never to nothing. - let removed = html_tag_for_colours(["removed-palette", "removed-palette", "x", "x"]).await; + let removed = html_tag_for_colours(&router, &store, "removed", "removed-token", ["removed-palette", "removed-palette", "x", "x"]).await; assert!(removed.contains("data-accent-light=\"sage\""), "{removed}"); assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}"); assert!(removed.contains("data-base-light=\"fern\""), "{removed}"); assert!(removed.contains("data-base-dark=\"fern\""), "{removed}"); // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself. - let retired = html_tag_for_colours(["ochre", "ember", "mist", "stone"]).await; + let retired = html_tag_for_colours(&router, &store, "retired", "retired-token", ["ochre", "ember", "mist", "stone"]).await; assert!(retired.contains("data-accent-light=\"sage\""), "{retired}"); assert!(retired.contains("data-accent-dark=\"sage\""), "{retired}"); assert!(retired.contains("data-base-light=\"fern\""), "{retired}"); assert!(retired.contains("data-base-dark=\"fern\""), "{retired}"); - let hued = html_tag_for_colours(["hue-215", "hue-7", "hue-300", "spark"]).await; + let hued = html_tag_for_colours(&router, &store, "hued", "hued-token", ["hue-215", "hue-7", "hue-300", "spark"]).await; assert!(hued.contains("data-accent-light=\"hue-215\""), "{hued}"); assert!(hued.contains("data-accent-dark=\"hue-7\""), "{hued}"); assert!(hued.contains("data-base-light=\"hue-300\""), "{hued}"); assert!(hued.contains("data-base-dark=\"spark\""), "{hued}"); } - - #[tokio::test] - async fn anonymous_pages_render_the_default_colours() { - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let router = crate::test_support::app_router(state); - let req = Request::builder() - .method("GET") - .uri("/login") - .body(Body::empty()) - .unwrap(); - let res = router.handle(req).await; - let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); - let html = String::from_utf8_lossy(&bytes); - let tag = html_tag(&html); - assert!(tag.contains("data-accent-light=\"sage\""), "{tag}"); - assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}"); - assert!(tag.contains("data-base-light=\"fern\""), "{tag}"); - assert!(tag.contains("data-base-dark=\"fern\""), "{tag}"); - } }