forge
Explore
Log in

Don't you dare go Hollow

Forge-web page tests share their fixtures and merge into tables

Browse files at this commit

b757c23591d6b46f070c35bc03c8b2d97937e89bAhmet Kaan GümüşParent: 40e7f7d
  • test
    • forge-web page tests share their fixtures and merge into tables
Show full message
✅ test: forge-web page tests share their fixtures and merge into tables

Test count in scope: 132 before, 103 after. Per file (before -> after):
api/statuses 10 -> 5, api/releases 10 -> 9, api/gitea_tests 8 -> 3,
backup/tests 10 -> 6, replication 11 -> 9, importer/tests 9 -> 7,
pulls_sync 9 -> 8, views/mod 13 -> 10, views/heatmap 13 -> 11,
mail/templates 8 -> 7, i18n 7 -> 4. importer/api, importer/forgejo_tests
and web_push stay as they were.

Refused writes and read-only lookups now share one fixture, with a case
label on every assertion. Streak, CSP, Target parse, i18n resolve and
unchanged-line cases are folded into tables. No assertion was removed.
crates/forge-web/src/api/gitea_tests.rsmodified+14 -23
@@ -273,8 +273,10 @@ fn repo_path_of(rest: &str) -> String {
273273 format!("/api/v1/repos/{OWNER}/{REPO}{rest}")
274274 }
275275
276+/// Read routes that share one fixture: version and settings, the repo, its issues, and
277+/// pagination. None of them changes state, so the scenarios cannot interfere.
276278 #[tokio::test]
277-async fn version_and_settings_unlock_every_feature() {
279+async fn version_repo_issues_and_pagination() {
278280 let f = fixture().await;
279281 let (status, _, body) = f.get_as("/api/v1/version", None).await;
280282 assert_eq!(status, 200);
@@ -282,11 +284,8 @@ async fn version_and_settings_unlock_every_feature() {
282284 let (status, _, body) = f.get_as("/api/v1/settings/api", None).await;
283285 assert_eq!(status, 200);
284286 assert_eq!(body["max_response_items"], 50);
285-}
286287
287-#[tokio::test]
288-async fn repo_info_topics_labels_and_milestones() {
289- let f = fixture().await;
288+ // The repo, its topics, labels and milestones.
290289 let (status, _, repo) = f.get(&repo_path_of("")).await;
291290 assert_eq!(status, 200);
292291 assert_eq!(repo["name"], REPO);
@@ -326,11 +325,8 @@ async fn repo_info_topics_labels_and_milestones() {
326325 assert_eq!(m["state"], "open");
327326 assert_eq!(m["due_on"], "2026-12-01T00:00:00Z");
328327 assert!(m["created_at"].is_string());
329-}
330328
331-#[tokio::test]
332-async fn issues_carry_labels_milestone_assignees_and_comments() {
333- let f = fixture().await;
329+ // Issues with their labels, milestone, assignees, comments and reactions.
334330 let (status, headers, issues) = f
335331 .get(&repo_path_of(
336332 "/issues?type=issues&state=all&page=1&limit=10",
@@ -376,11 +372,8 @@ async fn issues_carry_labels_milestone_assignees_and_comments() {
376372 assert_eq!(status, 200);
377373 assert_eq!(reactions[0]["reaction"], "+1");
378374 assert_eq!(reactions[0]["user"]["login"], OWNER);
379-}
380375
381-#[tokio::test]
382-async fn pagination_headers_and_link() {
383- let f = fixture().await;
376+ // Pagination headers, the Link header, and the empty last page.
384377 let (status, headers, items) = f
385378 .get(&repo_path_of("/issues/1/comments?page=2&limit=1"))
386379 .await;
@@ -413,9 +406,11 @@ async fn pagination_headers_and_link() {
413406 assert_eq!(items.as_array().unwrap().len(), 0);
414407 }
415408
409+/// Pull requests, reviews and releases, which share one fixture as read-only scenarios.
416410 #[tokio::test]
417-async fn pulls_reviews_and_review_comments() {
411+async fn pulls_reviews_and_releases_in_gitea_shape() {
418412 let f = fixture().await;
413+ // Pull requests and their reviews and review comments.
419414 let (status, headers, pulls) = f
420415 .get(&repo_path_of("/pulls?state=all&page=1&limit=10"))
421416 .await;
@@ -477,11 +472,8 @@ async fn pulls_reviews_and_review_comments() {
477472 // An issue number is not a pull request.
478473 let (status, _, _) = f.get(&repo_path_of("/pulls/1/reviews")).await;
479474 assert_eq!(status, 404);
480-}
481475
482-#[tokio::test]
483-async fn releases_and_assets_in_gitea_shape() {
484- let f = fixture().await;
476+ // Releases and their assets in the Gitea shape.
485477 let (status, headers, releases) = f.get(&repo_path_of("/releases?page=1&limit=10")).await;
486478 assert_eq!(status, 200);
487479 assert_eq!(headers["x-total-count"], "1");
@@ -515,9 +507,11 @@ async fn releases_and_assets_in_gitea_shape() {
515507 assert_eq!(one["browser_download_url"], url);
516508 }
517509
510+/// Private repos and release asset downloads, which both follow the token rules.
518511 #[tokio::test]
519-async fn private_repos_follow_the_token() {
512+async fn private_repos_and_asset_downloads_follow_the_token() {
520513 let f = fixture().await;
514+ // Private repos follow the token.
521515 let secret = "/api/v1/repos/tahinli/secret";
522516 let (status, _, _) = f.get_as(secret, None).await;
523517 assert_eq!(status, 401, "anonymous");
@@ -558,11 +552,8 @@ async fn private_repos_follow_the_token() {
558552 .get_as(&repo_path_of(""), Some("token forge_nope".into()))
559553 .await;
560554 assert_eq!(status, 401);
561-}
562555
563-#[tokio::test]
564-async fn release_asset_downloads_with_a_token() {
565- let f = fixture().await;
556+ // Release asset downloads take the token too.
566557 let path = "/tahinli/proj/releases/download/v1.0/app.bin";
567558 let owner = f.owner_token.clone();
568559 let basic = format!("Basic {}", BASE64_STANDARD.encode(format!("x:{owner}")));
crates/forge-web/src/api/releases.rsmodified+21 -14
@@ -642,22 +642,29 @@ mod tests {
642642 .await
643643 }
644644
645+ /// Refused creates share one fixture and store nothing. Each case is labelled in its message.
645646 #[tokio::test]
646- async fn anonymous_and_bad_tokens_are_unauthorized() {
647+ async fn refused_creates_return_their_status() {
647648 let f = fixture(None).await;
648- let (status, body) = post_json(&f, None, r#"{"tag":"v1"}"#).await;
649- assert_eq!(status, 401);
650- assert!(body["error"].is_string());
651- let (status, _) =
652- post_json(&f, Some("Bearer forge_not_a_real_token"), r#"{"tag":"v1"}"#).await;
653- assert_eq!(status, 401);
654- }
655-
656- #[tokio::test]
657- async fn token_without_repo_scope_is_forbidden() {
658- let f = fixture(None).await;
659- let (status, _) = post_json(&f, Some(&bearer(&f.scopeless_token)), r#"{"tag":"v1"}"#).await;
660- assert_eq!(status, 403);
649+ let scopeless = bearer(&f.scopeless_token);
650+ // (case, auth, expected status, expects a JSON error body)
651+ let cases: [(&str, Option<&str>, u16, bool); 3] = [
652+ ("anonymous", None, 401, true),
653+ (
654+ "bad token",
655+ Some("Bearer forge_not_a_real_token"),
656+ 401,
657+ false,
658+ ),
659+ ("token without repo scope", Some(scopeless.as_str()), 403, false),
660+ ];
661+ for (name, auth, want, error_body) in cases {
662+ let (status, body) = post_json(&f, auth, r#"{"tag":"v1"}"#).await;
663+ assert_eq!(status, want, "case {name}: {body}");
664+ if error_body {
665+ assert!(body["error"].is_string(), "case {name}");
666+ }
667+ }
661668 }
662669
663670 #[tokio::test]
crates/forge-web/src/api/statuses.rsmodified+35 -149
@@ -340,160 +340,46 @@ mod tests {
340340 assert_eq!(body["statuses"].as_array().map(Vec::len), Some(1));
341341 }
342342
343+ /// Every refused write shares one repo fixture, and each case is labelled in its message.
343344 #[tokio::test]
344- async fn read_only_token_is_forbidden_to_post() {
345+ async fn refused_writes_return_their_status() {
345346 let s = setup(Visibility::Public).await;
346- let (status, body) = send(
347- &s.fx.router,
348- "POST",
349- &report_uri(&s.sha),
350- Some(&bearer(&s.reader_token)),
351- None,
352- Some(SUCCESS),
353- )
354- .await;
355- assert_eq!(status, 403, "{body}");
356- assert!(body["error"].is_string());
357- }
358-
359- #[tokio::test]
360- async fn anonymous_and_bad_tokens_are_unauthorized() {
361- let s = setup(Visibility::Public).await;
362- let (status, body) = send(
363- &s.fx.router,
364- "POST",
365- &report_uri(&s.sha),
366- None,
367- None,
368- Some(SUCCESS),
369- )
370- .await;
371- assert_eq!(status, 401);
372- assert!(body["error"].is_string());
373-
374- let (status, _) = send(
375- &s.fx.router,
376- "POST",
377- &report_uri(&s.sha),
378- Some("Bearer forge_not_a_real_token"),
379- None,
380- Some(SUCCESS),
381- )
382- .await;
383- assert_eq!(status, 401);
384- }
385-
386- #[tokio::test]
387- async fn session_cookie_alone_is_rejected() {
388- let s = setup(Visibility::Public).await;
389- let owner =
390- s.fx.store
391- .user_by_username(OWNER)
392- .await
393- .unwrap()
394- .expect("owner");
347+ let owner = s
348+ .fx
349+ .store
350+ .user_by_username(OWNER)
351+ .await
352+ .unwrap()
353+ .expect("owner");
395354 let session = generate_token();
396355 crate::test_support::create_session(&s.fx.store, &owner.id, &session, "csrf-value").await;
397356 let cookie = format!("__Host-{SESSION_COOKIE}={session}");
398- let (status, _) = send(
399- &s.fx.router,
400- "POST",
401- &report_uri(&s.sha),
402- None,
403- Some(&cookie),
404- Some(SUCCESS),
405- )
406- .await;
407- assert_eq!(status, 401);
408- }
409-
410- #[tokio::test]
411- async fn token_without_repo_scope_is_forbidden() {
412- let s = setup(Visibility::Public).await;
413- let owner =
414- s.fx.store
415- .user_by_username(OWNER)
416- .await
417- .unwrap()
418- .expect("owner");
419- let raw = token_for(&s.fx.store, &owner.id, &[]).await;
420- let (status, _) = send(
421- &s.fx.router,
422- "POST",
423- &report_uri(&s.sha),
424- Some(&bearer(&raw)),
425- None,
426- Some(SUCCESS),
427- )
428- .await;
429- assert_eq!(status, 403);
430- }
431-
432- #[tokio::test]
433- async fn bad_sha_and_bad_body_are_rejected() {
434- let s = setup(Visibility::Public).await;
435- let auth = bearer(&s.writer_token);
436- let (status, _) = send(
437- &s.fx.router,
438- "POST",
439- &report_uri("abc123"),
440- Some(&auth),
441- None,
442- Some(SUCCESS),
443- )
444- .await;
445- assert_eq!(status, 422);
446-
447- let (status, _) = send(
448- &s.fx.router,
449- "POST",
450- &report_uri(&s.sha),
451- Some(&auth),
452- None,
453- Some(r#"{"state":"maybe"}"#),
454- )
455- .await;
456- assert_eq!(status, 422);
457-
458- let (status, _) = send(
459- &s.fx.router,
460- "POST",
461- &report_uri(&s.sha),
462- Some(&auth),
463- None,
464- Some("{not json"),
465- )
466- .await;
467- assert_eq!(status, 400);
468-
469- let (status, _) = send(
470- &s.fx.router,
471- "POST",
472- &report_uri(&s.sha),
473- Some(&auth),
474- None,
475- Some(r#"{"state":"success","target_url":"javascript:alert(1)"}"#),
476- )
477- .await;
478- assert_eq!(status, 422);
479- }
480-
481- #[tokio::test]
482- async fn unknown_commit_is_not_found() {
483- let s = setup(Visibility::Public).await;
484- let missing = "0".repeat(40);
485- let (status, _) = send(
486- &s.fx.router,
487- "POST",
488- &report_uri(&missing),
489- Some(&bearer(&s.writer_token)),
490- None,
491- Some(SUCCESS),
492- )
493- .await;
494- assert_eq!(status, 404);
495- let (status, _) = send(&s.fx.router, "GET", &list_uri(&missing), None, None, None).await;
496- assert_eq!(status, 404);
357+ let unscoped = bearer(&token_for(&s.fx.store, &owner.id, &[]).await);
358+ let writer = bearer(&s.writer_token);
359+ let reader = bearer(&s.reader_token);
360+ let report = report_uri(&s.sha);
361+ let bad_sha = report_uri("abc123");
362+ let missing = report_uri(&"0".repeat(40));
363+ // (case, uri, auth, cookie, body, expected status, expects a JSON error body)
364+ let cases: [(&str, &str, Option<&str>, Option<&str>, Option<&str>, u16, bool); 10] = [
365+ ("read-only token", report.as_str(), Some(reader.as_str()), None, Some(SUCCESS), 403, true),
366+ ("anonymous", report.as_str(), None, None, Some(SUCCESS), 401, true),
367+ ("bad token", report.as_str(), Some("Bearer forge_not_a_real_token"), None, Some(SUCCESS), 401, false),
368+ ("session cookie alone", report.as_str(), None, Some(cookie.as_str()), Some(SUCCESS), 401, false),
369+ ("token without repo scope", report.as_str(), Some(unscoped.as_str()), None, Some(SUCCESS), 403, false),
370+ ("sha too short", bad_sha.as_str(), Some(writer.as_str()), None, Some(SUCCESS), 422, false),
371+ ("unknown state", report.as_str(), Some(writer.as_str()), None, Some(r#"{"state":"maybe"}"#), 422, false),
372+ ("malformed json", report.as_str(), Some(writer.as_str()), None, Some("{not json"), 400, false),
373+ ("javascript target url", report.as_str(), Some(writer.as_str()), None, Some(r#"{"state":"success","target_url":"javascript:alert(1)"}"#), 422, false),
374+ ("unknown commit", missing.as_str(), Some(writer.as_str()), None, Some(SUCCESS), 404, false),
375+ ];
376+ for (name, uri, auth, cookie, body, want, error_body) in cases {
377+ let (status, json) = send(&s.fx.router, "POST", uri, auth, cookie, body).await;
378+ assert_eq!(status, want, "case {name}: {json}");
379+ if error_body {
380+ assert!(json["error"].is_string(), "case {name}");
381+ }
382+ }
497383 }
498384
499385 #[tokio::test]
crates/forge-web/src/backup/tests.rsmodified+38 -38
@@ -222,10 +222,14 @@ async fn end_to_end_set_verifies_with_correct_contents_and_modes() {
222222 assert_eq!(only_entry(&out), summary.path);
223223 }
224224
225+/// Each tampering gets its own backup set, so one check cannot hide another. Every case is
226+/// labelled in its message.
225227 #[tokio::test]
226-async fn one_flipped_bundle_byte_fails_the_sha_check() {
228+async fn tampered_sets_fail_the_check_that_catches_them() {
227229 let fx = fixture().await;
228- let out = fx.dir.path().join("out");
230+
231+ // A flipped bundle byte fails the bundle's sha256.
232+ let out = fx.dir.path().join("out-bundle");
229233 let summary = create_backup(&fx.source, &opts(&out, false, Scope::All))
230234 .await
231235 .expect("backup");
@@ -236,19 +240,16 @@ async fn one_flipped_bundle_byte_fails_the_sha_check() {
236240 std::fs::write(&bundle, &bytes).expect("tamper");
237241
238242 let report = verify_backup(&summary.path, &fx.git).await.expect("verify");
239- assert!(!report.is_ok());
243+ assert!(!report.is_ok(), "case bundle byte");
240244 let needle = format!("repos/{}.bundle: sha256 mismatch", fx.demo_id);
241245 assert!(
242246 report.problems.iter().any(|p| p.contains(&needle)),
243- "{:?}",
247+ "case bundle byte: {:?}",
244248 report.problems
245249 );
246-}
247250
248-#[tokio::test]
249-async fn tampered_db_fails_the_sha_check() {
250- let fx = fixture().await;
251- let out = fx.dir.path().join("out");
251+ // An appended byte fails both the size and the sha256 of the database.
252+ let out = fx.dir.path().join("out-db");
252253 let summary = create_backup(&fx.source, &opts(&out, false, Scope::All))
253254 .await
254255 .expect("backup");
@@ -263,7 +264,7 @@ async fn tampered_db_fails_the_sha_check() {
263264 .problems
264265 .iter()
265266 .any(|p| p.starts_with("db/forge.db: size mismatch")),
266- "{:?}",
267+ "case appended db byte: {:?}",
267268 report.problems
268269 );
269270 assert!(
@@ -271,15 +272,13 @@ async fn tampered_db_fails_the_sha_check() {
271272 .problems
272273 .iter()
273274 .any(|p| p.starts_with("db/forge.db: sha256 mismatch")),
274- "{:?}",
275+ "case appended db byte: {:?}",
275276 report.problems
276277 );
277-}
278278
279-#[tokio::test]
280-async fn a_damaged_db_fails_even_when_the_manifest_is_rewritten_to_match() {
281- let fx = fixture().await;
282- let out = fx.dir.path().join("out");
279+ // A truncated database fails the snapshot check even when the manifest is rewritten to
280+ // match, so only the DB checks can catch it.
281+ let out = fx.dir.path().join("out-truncated");
283282 let summary = create_backup(&fx.source, &opts(&out, false, Scope::All))
284283 .await
285284 .expect("backup");
@@ -287,7 +286,6 @@ async fn a_damaged_db_fails_even_when_the_manifest_is_rewritten_to_match() {
287286 let bytes = std::fs::read(&db).expect("read db");
288287 std::fs::write(&db, &bytes[..bytes.len() / 2]).expect("truncate");
289288
290- // Make the manifest agree with the damaged file, so only the DB checks can catch it.
291289 let mut m = read_manifest(&summary.path);
292290 let (new_bytes, new_sha) = {
293291 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() {
307305 .problems
308306 .iter()
309307 .any(|p| p.starts_with("database snapshot failed verification")),
310- "{:?}",
308+ "case truncated db: {:?}",
311309 report.problems
312310 );
313311 }
314312
313+/// A manifest repo list that disagrees with the DB snapshot, and a stray file in the set, are
314+/// each reported. Each case has its own backup set.
315315 #[tokio::test]
316-async fn manifest_repo_list_must_match_the_db_snapshot() {
316+async fn manifest_and_stray_file_problems_are_reported() {
317317 let fx = fixture().await;
318- let out = fx.dir.path().join("out");
318+
319+ let out = fx.dir.path().join("out-manifest");
319320 let summary = create_backup(&fx.source, &opts(&out, false, Scope::All))
320321 .await
321322 .expect("backup");
@@ -329,15 +330,11 @@ async fn manifest_repo_list_must_match_the_db_snapshot() {
329330 .problems
330331 .iter()
331332 .any(|p| p.contains("does not match the database snapshot")),
332- "{:?}",
333+ "case manifest repo list: {:?}",
333334 report.problems
334335 );
335-}
336336
337-#[tokio::test]
338-async fn unlisted_file_in_the_set_is_reported() {
339- let fx = fixture().await;
340- let out = fx.dir.path().join("out");
337+ let out = fx.dir.path().join("out-stray");
341338 let summary = create_backup(&fx.source, &opts(&out, false, Scope::All))
342339 .await
343340 .expect("backup");
@@ -348,7 +345,7 @@ async fn unlisted_file_in_the_set_is_reported() {
348345 .problems
349346 .iter()
350347 .any(|p| p.contains("unlisted file in the set: repos/stray.txt")),
351- "{:?}",
348+ "case stray file: {:?}",
352349 report.problems
353350 );
354351 }
@@ -394,30 +391,33 @@ async fn key_is_excluded_by_default_and_included_on_request() {
394391 );
395392 }
396393
394+/// A failed backup leaves nothing behind. Each failure has its own output directory, and the
395+/// repo breaking case runs last because it damages the shared fixture.
397396 #[tokio::test]
398-async fn include_key_without_a_key_fails_and_leaves_nothing() {
397+async fn failed_backups_leave_no_partial_directory() {
399398 let fx = fixture().await;
400- let out = fx.dir.path().join("out");
399+
400+ let out = fx.dir.path().join("out-no-key");
401401 let err = create_backup(&fx.source, &opts(&out, true, Scope::All)).await;
402- assert!(err.is_err());
403- assert_eq!(std::fs::read_dir(&out).expect("out").count(), 0);
404-}
402+ assert!(err.is_err(), "case include key without a key");
403+ assert_eq!(
404+ std::fs::read_dir(&out).expect("out").count(),
405+ 0,
406+ "case include key without a key"
407+ );
405408
406-#[tokio::test]
407-async fn failure_in_a_repo_leaves_no_partial_directory() {
408- let fx = fixture().await;
409- let out = fx.dir.path().join("out");
410409 // A repo with no HEAD is not a repository, so reading its refs fails mid-backup.
410+ let out = fx.dir.path().join("out-broken-repo");
411411 let broken = repo_path(&fx.data_dir, &fx.demo_id).expect("path");
412412 std::fs::remove_file(broken.join("HEAD")).expect("break repo");
413413
414414 let result = create_backup(&fx.source, &opts(&out, false, Scope::All)).await;
415- assert!(result.is_err(), "backup must fail");
415+ assert!(result.is_err(), "case broken repo: backup must fail");
416416 let left: Vec<String> = std::fs::read_dir(&out)
417417 .expect("out")
418418 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
419419 .collect();
420- assert!(left.is_empty(), "nothing may be left behind: {left:?}");
420+ assert!(left.is_empty(), "case broken repo, nothing may be left behind: {left:?}");
421421 }
422422
423423 #[tokio::test]
crates/forge-web/src/i18n/mod.rsmodified+27 -31
@@ -1360,12 +1360,6 @@ mod tests {
13601360 use super::*;
13611361 use http::HeaderValue;
13621362
1363- fn headers(value: &'static str) -> HeaderMap {
1364- let mut map = HeaderMap::new();
1365- map.insert(ACCEPT_LANGUAGE, HeaderValue::from_static(value));
1366- map
1367- }
1368-
13691363 #[test]
13701364 fn every_key_has_text_in_both_languages() {
13711365 for key in ALL {
@@ -1382,36 +1376,38 @@ mod tests {
13821376 }
13831377
13841378 #[test]
1385- fn stored_language_wins_over_the_browser() {
1386- let turkish = headers("tr");
1387- assert_eq!(resolve(Some("en"), &turkish), Lang::En);
1388- assert_eq!(resolve(Some("tr"), &HeaderMap::new()), Lang::Tr);
1389- }
1390-
1391- #[test]
1392- fn auto_and_missing_preferences_follow_the_browser() {
1393- assert_eq!(resolve(Some("auto"), &headers("tr-TR,en;q=0.5")), Lang::Tr);
1394- assert_eq!(resolve(None, &headers("tr")), Lang::Tr);
1395- assert_eq!(resolve(None, &HeaderMap::new()), Lang::En);
1396- }
1397-
1398- #[test]
1399- fn accept_language_picks_the_highest_quality_supported_tag() {
1400- assert_eq!(resolve(None, &headers("de,en;q=0.8,tr;q=0.9")), Lang::Tr);
1401- assert_eq!(resolve(None, &headers("en;q=0.9,tr;q=0.5")), Lang::En);
1402- assert_eq!(resolve(None, &headers("tr;q=0,en")), Lang::En);
1403- assert_eq!(resolve(None, &headers("de,fr;q=0.9")), Lang::En);
1404- assert_eq!(resolve(None, &headers("tr;q=oops,en;q=0.1")), Lang::En);
1379+ fn stored_preference_then_browser_picks_the_language() {
1380+ // (case, stored preference, Accept-Language, expected)
1381+ // An empty accept string means the header is absent.
1382+ let cases: [(&str, Option<&str>, &str, Lang); 10] = [
1383+ ("stored en beats browser tr", Some("en"), "tr", Lang::En),
1384+ ("stored tr with no header", Some("tr"), "", Lang::Tr),
1385+ ("auto follows browser", Some("auto"), "tr-TR,en;q=0.5", Lang::Tr),
1386+ ("missing preference follows browser", None, "tr", Lang::Tr),
1387+ ("no preference, no header", None, "", Lang::En),
1388+ ("highest q supported wins", None, "de,en;q=0.8,tr;q=0.9", Lang::Tr),
1389+ ("higher q for en", None, "en;q=0.9,tr;q=0.5", Lang::En),
1390+ ("q=0 rejects tr", None, "tr;q=0,en", Lang::En),
1391+ ("unsupported tags fall back to en", None, "de,fr;q=0.9", Lang::En),
1392+ ("malformed q is ignored", None, "tr;q=oops,en;q=0.1", Lang::En),
1393+ ];
1394+ for (name, stored, accept, want) in cases {
1395+ let map = if accept.is_empty() {
1396+ HeaderMap::new()
1397+ } else {
1398+ let mut map = HeaderMap::new();
1399+ map.insert(ACCEPT_LANGUAGE, HeaderValue::from_str(accept).expect("ascii"));
1400+ map
1401+ };
1402+ assert_eq!(resolve(stored, &map), want, "case {name}");
1403+ }
14051404 }
14061405
14071406 #[test]
1408- fn unknown_stored_code_is_english() {
1407+ fn language_codes_round_trip_and_unknown_is_english() {
1408+ // The codes are stored in the database, so the literals are checked explicitly.
14091409 assert_eq!(Lang::from_code("fr"), Lang::En);
14101410 assert_eq!(Lang::from_code("tr"), Lang::Tr);
1411- }
1412-
1413- #[test]
1414- fn html_codes_match_the_languages() {
14151411 assert_eq!(Lang::En.code(), "en");
14161412 assert_eq!(Lang::Tr.code(), "tr");
14171413 }
crates/forge-web/src/importer/tests.rsmodified+29 -45
@@ -260,11 +260,11 @@ fn fake() -> Fake {
260260 async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() {
261261 let fx = fixture().await;
262262 let job = new_job(&fx, Source::Git).await;
263- let spec = spec(Source::Git, ImportOptions::default());
263+ let git_spec = spec(Source::Git, ImportOptions::default());
264264 run_job::<Fake>(
265265 &fx.state,
266266 &job,
267- &spec,
267+ &git_spec,
268268 None,
269269 &Transport::Local(fx.upstream.clone()),
270270 )
@@ -294,6 +294,21 @@ async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() {
294294 .unwrap()
295295 .is_none()
296296 );
297+
298+ // A fetch from a missing remote fails its job, and the failure is recorded.
299+ let bad_job = new_job(&fx, Source::Git).await;
300+ let bad_spec = spec(Source::Git, ImportOptions::default());
301+ run_job::<Fake>(
302+ &fx.state,
303+ &bad_job,
304+ &bad_spec,
305+ None,
306+ &Transport::Local("/nonexistent/path.git".into()),
307+ )
308+ .await;
309+ let bad_job = fx.state.store.import_job(&bad_job.id).await.unwrap().unwrap();
310+ assert_eq!(bad_job.state, ImportState::Failed);
311+ assert!(bad_job.error.is_some());
297312 }
298313
299314 #[tokio::test]
@@ -366,32 +381,19 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() {
366381 assert_eq!(assets.len(), 1);
367382 assert_eq!(assets[0].name, "app_1.tar.gz");
368383 assert_eq!(assets[0].size, 5);
369-}
370384
371-#[tokio::test]
372-async fn running_an_import_twice_creates_nothing_twice() {
373- let fx = fixture().await;
374- let api = fake();
375- let spec = spec(Source::GitHub, everything());
376- for _ in 0..2 {
377- let job = new_job(&fx, Source::GitHub).await;
378- run_job(
379- &fx.state,
380- &job,
381- &spec,
382- Some(&api),
383- &Transport::Local(fx.upstream.clone()),
384- )
385- .await;
386- let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
387- assert_eq!(job.state, ImportState::Done, "{:?}", job.error);
388- }
389- let store = &fx.state.store;
390- let all = IssueFilter {
391- state: None,
392- per_page: 100,
393- ..IssueFilter::default()
394- };
385+ // A second run of the same import creates nothing twice.
386+ let again = new_job(&fx, Source::GitHub).await;
387+ run_job(
388+ &fx.state,
389+ &again,
390+ &spec,
391+ Some(&api),
392+ &Transport::Local(fx.upstream.clone()),
393+ )
394+ .await;
395+ let again = store.import_job(&again.id).await.unwrap().unwrap();
396+ assert_eq!(again.state, ImportState::Done, "{:?}", again.error);
395397 let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap();
396398 assert_eq!(total, 2);
397399 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() {
489491 );
490492 }
491493
492-#[tokio::test]
493-async fn a_failed_git_fetch_marks_the_job_failed() {
494- let fx = fixture().await;
495- let job = new_job(&fx, Source::Git).await;
496- let spec = spec(Source::Git, ImportOptions::default());
497- run_job::<Fake>(
498- &fx.state,
499- &job,
500- &spec,
501- None,
502- &Transport::Local("/nonexistent/path.git".into()),
503- )
504- .await;
505- let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
506- assert_eq!(job.state, ImportState::Failed);
507- assert!(job.error.is_some());
508-}
509-
510494 #[test]
511495 fn the_origin_note_escapes_the_mention_and_cleans_the_name() {
512496 let note = origin_note(
crates/forge-web/src/mail/templates.rsmodified+10 -9
@@ -214,15 +214,16 @@ mod tests {
214214 }
215215
216216 #[test]
217- fn subject_names_the_repo_title_and_number() {
218- let (subject, _) = notification(Lang::En, &sample(None, "Crash on start"));
219- assert_eq!(subject, "[bob/widgets] Crash on start (#7)");
220- }
221-
222- #[test]
223- fn a_newline_in_the_title_cannot_split_the_subject() {
224- let (subject, _) = notification(Lang::En, &sample(None, "two\r\nlines"));
225- assert_eq!(subject, "[bob/widgets] two lines (#7)");
217+ fn subject_names_the_repo_title_and_number_and_stays_on_one_line() {
218+ // A plain title is named as-is; a newline in the title cannot split the subject.
219+ let cases = [
220+ ("plain", "Crash on start", "[bob/widgets] Crash on start (#7)"),
221+ ("newline", "two\r\nlines", "[bob/widgets] two lines (#7)"),
222+ ];
223+ for (name, title, want) in cases {
224+ let (subject, _) = notification(Lang::En, &sample(None, title));
225+ assert_eq!(subject, want, "case {name}");
226+ }
226227 }
227228
228229 #[test]
crates/forge-web/src/pulls_sync.rsmodified+2 -5
@@ -738,7 +738,7 @@ mod tests {
738738 }
739739
740740 #[test]
741- fn unchanged_line_follows_insertions_above() {
741+ fn unchanged_line_follows_insertions_and_skips_changed_lines() {
742742 let old = "a\nb\nc\n";
743743 let new = "x\na\nb\nc\n";
744744 assert_eq!(unchanged_line(old, new, 1), Some(2));
@@ -746,10 +746,7 @@ mod tests {
746746 assert_eq!(unchanged_line(old, new, 3), Some(4));
747747 assert_eq!(unchanged_line(old, new, 0), None);
748748 assert_eq!(unchanged_line(old, new, 9), None);
749- }
750-
751- #[test]
752- fn unchanged_line_is_none_for_modified_or_deleted_lines() {
749+ // A modified or deleted line has no unchanged counterpart.
753750 assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 2), None);
754751 assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 3), Some(3));
755752 assert_eq!(unchanged_line("a\nb\n", "a\n", 2), None);
crates/forge-web/src/replication/mod.rsmodified+1 -9
@@ -651,7 +651,7 @@ mod tests {
651651 }
652652
653653 #[test]
654- fn target_parses_user_host_and_base() {
654+ fn target_parses_user_host_and_base_and_refuses_bad_specs() {
655655 let t = Target::parse("sb@standby.example:/srv/forge-standby", 2222).expect("parse");
656656 assert_eq!(t.user.as_deref(), Some("sb"));
657657 assert_eq!(t.host, "standby.example");
@@ -663,10 +663,6 @@ mod tests {
663663 );
664664 let bare = Target::parse("standby:/srv/x", 22).expect("parse");
665665 assert_eq!(bare.destination(), "standby");
666- }
667-
668- #[test]
669- fn target_rejects_bad_specs() {
670666 for bad in [
671667 "no-colon",
672668 "sb@host",
@@ -708,10 +704,6 @@ mod tests {
708704 assert!(!is_snapshot_name(".tmp-forge-20260101T120000Z.db"));
709705 assert!(!is_snapshot_name("forge-2026-01-01T12:00:00Z.db"));
710706 assert!(!is_snapshot_name("forge-20260101X120000Z.db"));
711- }
712-
713- #[test]
714- fn snapshot_stamp_has_the_expected_shape() {
715707 let stamp = snapshot_stamp();
716708 assert!(is_snapshot_name(&format!("forge-{stamp}.db")), "{stamp}");
717709 }
crates/forge-web/src/views/heatmap.rsmodified+29 -22
@@ -352,28 +352,35 @@ mod tests {
352352 }
353353
354354 #[test]
355- fn a_gap_ends_the_current_streak_but_not_the_longest() {
356- let cal = build(
357- &counts(&[
358- ("2026-09-20", 1),
359- ("2026-09-21", 1),
360- ("2026-09-22", 1),
361- ("2026-09-23", 1),
362- ("2026-09-24", 1),
363- ("2026-10-15", 2),
364- ("2026-10-16", 2),
365- ]),
366- TODAY,
367- );
368- assert_eq!(cal.longest_streak, 5);
369- assert_eq!(cal.current_streak, 2);
370- }
371-
372- #[test]
373- fn an_old_run_is_not_the_current_streak() {
374- let cal = build(&counts(&[("2026-10-01", 3), ("2026-10-02", 3)]), TODAY);
375- assert_eq!(cal.current_streak, 0);
376- assert_eq!(cal.longest_streak, 2);
355+ fn a_gap_or_an_old_run_ends_the_current_streak() {
356+ // (case, counts, current streak, longest streak)
357+ let cases: [(&str, &[(&str, u32)], u64, u64); 2] = [
358+ (
359+ "old run",
360+ &[("2026-10-01", 3), ("2026-10-02", 3)],
361+ 0,
362+ 2,
363+ ),
364+ (
365+ "gap then two days",
366+ &[
367+ ("2026-09-20", 1),
368+ ("2026-09-21", 1),
369+ ("2026-09-22", 1),
370+ ("2026-09-23", 1),
371+ ("2026-09-24", 1),
372+ ("2026-10-15", 2),
373+ ("2026-10-16", 2),
374+ ],
375+ 2,
376+ 5,
377+ ),
378+ ];
379+ for (name, input, current, longest) in cases {
380+ let cal = build(&counts(input), TODAY);
381+ assert_eq!(cal.current_streak, current, "case {name}");
382+ assert_eq!(cal.longest_streak, longest, "case {name}");
383+ }
377384 }
378385
379386 #[test]
crates/forge-web/src/views/mod.rsmodified+48 -51
@@ -1171,16 +1171,13 @@ mod tests {
11711171 }
11721172
11731173 #[test]
1174- fn csp_allows_the_raw_origin_for_images() {
1174+ fn csp_allows_the_raw_origin_for_images_and_falls_back_otherwise() {
11751175 let origin = origin_of("https://raw.forge.test:8443/some/path/");
11761176 assert_eq!(origin.as_deref(), Some("https://raw.forge.test:8443"));
11771177 let csp = csp_for(origin.as_deref());
11781178 assert!(csp.contains("img-src 'self' data: https://raw.forge.test:8443;"));
11791179 assert!(csp.contains("form-action 'self'; frame-ancestors 'none'"));
1180- }
1181-
1182- #[test]
1183- fn csp_falls_back_when_the_base_url_is_not_an_origin() {
1180+ // A base URL that is not an origin falls back to the plain policy.
11841181 assert_eq!(origin_of("not a url"), None);
11851182 assert_eq!(origin_of("ftp://files.test"), None);
11861183 assert_eq!(origin_of("https://user:pw@files.test"), None);
@@ -1239,25 +1236,26 @@ mod tests {
12391236 }
12401237
12411238 /// Renders `/settings/sessions` (a page that uses the shell) for a freshly signed-in user.
1242- async fn menu_html(is_admin: bool) -> String {
1239+ async fn menu_html(
1240+ router: &topcoat::router::Router,
1241+ store: &forge_core::Store,
1242+ name: &str,
1243+ is_admin: bool,
1244+ token: &str,
1245+ ) -> String {
12431246 use crate::auth::SESSION_COOKIE;
12441247 use topcoat::router::request::Request;
12451248 use topcoat::router::to_bytes;
12461249
1247- let dir = tempfile::tempdir().expect("tempdir");
1248- let state = crate::test_support::test_state(dir.path()).await;
1249- let store = state.store.clone();
1250- let router = crate::test_support::app_router(state.clone());
1251- let name = if is_admin { "root" } else { "tahinli" };
12521250 let user = store
12531251 .create_user(name, None, "x", is_admin)
12541252 .await
12551253 .expect("user");
1256- crate::test_support::create_session(&store, &user.id, "menu-token", "menu-csrf").await;
1254+ crate::test_support::create_session(store, &user.id, token, "menu-csrf").await;
12571255 let req = Request::builder()
12581256 .method("GET")
12591257 .uri("/settings/sessions")
1260- .header("cookie", format!("__Host-{SESSION_COOKIE}=menu-token"))
1258+ .header("cookie", format!("__Host-{SESSION_COOKIE}={token}"))
12611259 .body(Body::empty())
12621260 .expect("request");
12631261 let res = router.handle(req).await;
@@ -1266,17 +1264,21 @@ mod tests {
12661264 String::from_utf8_lossy(&bytes).into_owned()
12671265 }
12681266
1267+ /// A user sees no admin links and an admin sees the one Admin entry. Both render from one
1268+ /// fixture.
12691269 #[tokio::test]
1270- async fn admin_links_are_hidden_from_non_admins() {
1271- let html = menu_html(false).await;
1270+ async fn admin_links_follow_the_role() {
1271+ let dir = tempfile::tempdir().expect("tempdir");
1272+ let state = crate::test_support::test_state(dir.path()).await;
1273+ let store = state.store.clone();
1274+ let router = crate::test_support::app_router(state);
1275+
1276+ let html = menu_html(&router, &store, "tahinli", false, "menu-token-user").await;
12721277 assert!(html.contains("Log out"), "user menu is rendered");
12731278 assert!(!html.contains("/admin/users"), "no admin link for a user");
12741279 assert!(!html.contains("/admin/audit"), "no audit link for a user");
1275- }
12761280
1277- #[tokio::test]
1278- async fn admin_links_are_shown_to_admins() {
1279- let html = menu_html(true).await;
1281+ let html = menu_html(&router, &store, "root", true, "menu-token-admin").await;
12801282 assert!(html.contains("href=\"/admin/users\""));
12811283 assert!(
12821284 !html.contains("Admin:"),
@@ -1340,6 +1342,13 @@ mod shell_tests {
13401342
13411343 assert!(html.contains("<main tabindex=\"-1\">"));
13421344 assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\""));
1345+
1346+ // An anonymous page renders the default colours.
1347+ let tag = html_tag(&html);
1348+ assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");
1349+ assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");
1350+ assert!(tag.contains("data-base-light=\"fern\""), "{tag}");
1351+ assert!(tag.contains("data-base-dark=\"fern\""), "{tag}");
13431352 }
13441353
13451354 /// The `<html …>` start tag of a page.
@@ -1351,14 +1360,16 @@ mod shell_tests {
13511360
13521361 /// The `<html>` tag of `/settings/sessions` for a signed-in user whose stored colours are the
13531362 /// four ids given, in the order light accent, dark accent, light base, dark base.
1354- async fn html_tag_for_colours(colours: [&str; 4]) -> String {
1363+ async fn html_tag_for_colours(
1364+ router: &topcoat::router::Router,
1365+ store: &forge_core::Store,
1366+ name: &str,
1367+ token: &str,
1368+ colours: [&str; 4],
1369+ ) -> String {
13551370 use crate::auth::SESSION_COOKIE;
1356- let dir = tempfile::tempdir().expect("tempdir");
1357- let state = crate::test_support::test_state(dir.path()).await;
1358- let store = state.store.clone();
1359- let router = crate::test_support::app_router(state);
13601371 let user = store
1361- .create_user("tahinli", None, "x", false)
1372+ .create_user(name, None, "x", false)
13621373 .await
13631374 .expect("user");
13641375 let [accent_light, accent_dark, base_light, base_dark] = colours;
@@ -1366,11 +1377,11 @@ mod shell_tests {
13661377 .set_colours(&user.id, accent_light, accent_dark, base_light, base_dark)
13671378 .await
13681379 .expect("colours");
1369- crate::test_support::create_session(&store, &user.id, "colour-token", "colour-csrf").await;
1380+ crate::test_support::create_session(store, &user.id, token, "colour-csrf").await;
13701381 let req = Request::builder()
13711382 .method("GET")
13721383 .uri("/settings/sessions")
1373- .header("cookie", format!("__Host-{SESSION_COOKIE}=colour-token"))
1384+ .header("cookie", format!("__Host-{SESSION_COOKIE}={token}"))
13741385 .body(Body::empty())
13751386 .unwrap();
13761387 let res = router.handle(req).await;
@@ -1379,50 +1390,36 @@ mod shell_tests {
13791390 html_tag(&String::from_utf8_lossy(&bytes)).to_owned()
13801391 }
13811392
1393+ /// Every colour case shares one fixture; each has its own user and session.
13821394 #[tokio::test]
13831395 async fn the_html_tag_carries_the_viewers_colours() {
1384- let tag = html_tag_for_colours(["ocean", "plum", "ink", "dusk"]).await;
1396+ let dir = tempfile::tempdir().expect("tempdir");
1397+ let state = crate::test_support::test_state(dir.path()).await;
1398+ let store = state.store.clone();
1399+ let router = crate::test_support::app_router(state);
1400+
1401+ let tag = html_tag_for_colours(&router, &store, "tahinli", "colour-token", ["ocean", "plum", "ink", "dusk"]).await;
13851402 assert!(tag.contains("data-accent-light=\"ocean\""), "{tag}");
13861403 assert!(tag.contains("data-accent-dark=\"plum\""), "{tag}");
13871404 assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
13881405 assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}");
13891406 assert!(!tag.contains("data-accent="), "{tag}");
13901407 // Stored ids that are no longer offered fall back to the defaults, never to nothing.
1391- let removed = html_tag_for_colours(["removed-palette", "removed-palette", "x", "x"]).await;
1408+ let removed = html_tag_for_colours(&router, &store, "removed", "removed-token", ["removed-palette", "removed-palette", "x", "x"]).await;
13921409 assert!(removed.contains("data-accent-light=\"sage\""), "{removed}");
13931410 assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}");
13941411 assert!(removed.contains("data-base-light=\"fern\""), "{removed}");
13951412 assert!(removed.contains("data-base-dark=\"fern\""), "{removed}");
13961413 // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself.
1397- let retired = html_tag_for_colours(["ochre", "ember", "mist", "stone"]).await;
1414+ let retired = html_tag_for_colours(&router, &store, "retired", "retired-token", ["ochre", "ember", "mist", "stone"]).await;
13981415 assert!(retired.contains("data-accent-light=\"sage\""), "{retired}");
13991416 assert!(retired.contains("data-accent-dark=\"sage\""), "{retired}");
14001417 assert!(retired.contains("data-base-light=\"fern\""), "{retired}");
14011418 assert!(retired.contains("data-base-dark=\"fern\""), "{retired}");
1402- let hued = html_tag_for_colours(["hue-215", "hue-7", "hue-300", "spark"]).await;
1419+ let hued = html_tag_for_colours(&router, &store, "hued", "hued-token", ["hue-215", "hue-7", "hue-300", "spark"]).await;
14031420 assert!(hued.contains("data-accent-light=\"hue-215\""), "{hued}");
14041421 assert!(hued.contains("data-accent-dark=\"hue-7\""), "{hued}");
14051422 assert!(hued.contains("data-base-light=\"hue-300\""), "{hued}");
14061423 assert!(hued.contains("data-base-dark=\"spark\""), "{hued}");
14071424 }
1408-
1409- #[tokio::test]
1410- async fn anonymous_pages_render_the_default_colours() {
1411- let dir = tempfile::tempdir().expect("tempdir");
1412- let state = crate::test_support::test_state(dir.path()).await;
1413- let router = crate::test_support::app_router(state);
1414- let req = Request::builder()
1415- .method("GET")
1416- .uri("/login")
1417- .body(Body::empty())
1418- .unwrap();
1419- let res = router.handle(req).await;
1420- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
1421- let html = String::from_utf8_lossy(&bytes);
1422- let tag = html_tag(&html);
1423- assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");
1424- assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");
1425- assert!(tag.contains("data-base-light=\"fern\""), "{tag}");
1426- assert!(tag.contains("data-base-dark=\"fern\""), "{tag}");
1427- }
14281425 }