diff --git a/app/tests/baselines.rs b/app/tests/baselines.rs index 93604592..3549b56b 100644 --- a/app/tests/baselines.rs +++ b/app/tests/baselines.rs @@ -9,11 +9,59 @@ use laravel::db; use laravel::testing::prelude::*; use serde_json::json; -fn png(rgb: [u8; 3]) -> Vec { +/// An 8x6 PNG of one colour, with `nonce` in a `tEXt` chunk: the same pixels in every test, but bytes (and so a blob +/// key) of this test's own. Tests in the one binary (tests/all.rs) run at once, and identical bytes everywhere had them +/// all writing and verifying the same `blobs/` together. +fn png(rgb: [u8; 3], nonce: &str) -> Vec { let img = image::RgbImage::from_pixel(8, 6, image::Rgb(rgb)); let mut out = std::io::Cursor::new(Vec::new()); img.write_to(&mut out, image::ImageFormat::Png).unwrap(); - out.into_inner() + let encoded = out.into_inner(); + // After the signature (8 bytes) and IHDR (25): a chunk is length, type, data, then the CRC-32 of type and data. + let data = [b"tEXt".as_slice(), b"Comment\0", nonce.as_bytes()].concat(); + let mut chunk = u32::try_from(data.len() - 4).unwrap().to_be_bytes().to_vec(); + chunk.extend_from_slice(&data); + chunk.extend_from_slice(&crc32(&data).to_be_bytes()); + [&encoded[..33], &chunk, &encoded[33..]].concat() +} + +fn crc32(bytes: &[u8]) -> u32 { + let mut crc = !0u32; + for &b in bytes { + crc ^= u32::from(b); + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc +} + +/// PUT the bytes to a presigned upload URL as the CLI does (client.rs): a 429 or a 5xx from the store is tried again +/// with a jittered backoff (each retry printed); anything else that isn't a success fails the test with the store's +/// answer. +async fn upload(url: &str, bytes: Vec) { + const TRIES: u32 = 6; + for attempt in 1..=TRIES { + let r = reqwest::Client::new() + .put(url) + .header("content-type", "image/png") + .body(bytes.clone()) + .send() + .await + .unwrap(); + let status = r.status(); + if status.is_success() { + return; + } + let body = r.text().await.unwrap_or_default(); + let retryable = status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error(); + assert!(retryable && attempt < TRIES, "PUT {url} (try {attempt}): HTTP {status}: {body}"); + eprintln!("PUT {url} (try {attempt}): HTTP {status}: {body}; trying again"); + // 0.5 s doubling, plus up to half again at random so tests that failed together don't retry together. + let wait = 500u64 << (attempt - 1); + let jitter = u64::from(laravel::str::uuid7().as_bytes()[15]) * wait / 2 / 255; + tokio::time::sleep(std::time::Duration::from_millis(wait + jitter)).await; + } } const RED: [u8; 3] = [255, 0, 0]; @@ -23,6 +71,8 @@ const BLUE: [u8; 3] = [0, 0, 255]; struct World { project: Project, token: String, + /// Makes this test's images' bytes its own ([`png`]). + nonce: String, } async fn world() -> laravel::Result { @@ -38,7 +88,8 @@ async fn world() -> laravel::Result { ) .insert() .await?; - Ok(World { project, token }) + let nonce = laravel::str::uuid7().simple().to_string(); + Ok(World { project, token, nonce }) } impl World { @@ -111,7 +162,7 @@ impl World { let mut list = Vec::new(); let mut bodies = Vec::new(); for (name, rgb) in files { - let bytes = png(*rgb); + let bytes = png(*rgb, &self.nonce); let sha = visualci_core::sha256_hex(&bytes); list.push(json!({ "name": name, "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", @@ -127,14 +178,7 @@ impl World { registered.assert_ok(); for (s, bytes) in registered.json()["snapshots"].as_array().unwrap().iter().zip(bodies) { if let Some(url) = s["upload_url"].as_str() { - let r = reqwest::Client::new() - .put(url) - .header("content-type", "image/png") - .body(bytes) - .send() - .await - .unwrap(); - assert!(r.status().is_success()); + upload(url, bytes).await; } } let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; @@ -485,3 +529,15 @@ async fn inherited_falls_back_to_the_default_branch_for_an_unbuilt_base(app: App assert_eq!((found.build, found.snapshot_ids.len()), (m2.number, 1)); Ok(()) } + +#[test] +fn each_tests_images_have_the_same_pixels_and_bytes_of_their_own() { + let (a, b) = (png(RED, "one"), png(RED, "two")); + assert_ne!(visualci_core::sha256_hex(&a), visualci_core::sha256_hex(&b)); + let pixels = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgb8().into_raw(); + assert_eq!(pixels(&a), pixels(&b)); + assert_eq!( + visualci_core::image_hash::fingerprint_bytes(&a).unwrap(), + visualci_core::image_hash::fingerprint_bytes(&b).unwrap() + ); +}