diff --git a/Cargo.lock b/Cargo.lock index 96a6d625ab..664f291e39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2021,6 +2021,7 @@ dependencies = [ name = "craft-android-res" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "thiserror 2.0.21", ] @@ -2076,6 +2077,9 @@ dependencies = [ [[package]] name = "craft-audio-dsp" version = "0.1.0" +dependencies = [ + "craft-testkit", +] [[package]] name = "craft-automation" @@ -2148,6 +2152,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-testkit", "craft-timeline", "craft-xml", "proptest", @@ -2170,6 +2175,7 @@ name = "craft-cfb" version = "0.1.0" dependencies = [ "craft-media-testkit", + "craft-testkit", ] [[package]] @@ -2207,6 +2213,7 @@ dependencies = [ name = "craft-cms" version = "0.1.0" dependencies = [ + "craft-testkit", "md-5 0.10.6", "moxcms", "rayon", @@ -2426,6 +2433,7 @@ dependencies = [ "blake3", "craft-ecproj-format", "craft-pcraft-format", + "craft-testkit", "craft-vectorcraft-format", "flate2", "ruzstd", @@ -2481,6 +2489,7 @@ dependencies = [ "craft-math", "craft-offcrypto", "craft-opc", + "craft-testkit", "craft-wordmodel", "craft-xml", "image", @@ -2620,6 +2629,7 @@ dependencies = [ name = "craft-exr" version = "0.1.0" dependencies = [ + "craft-testkit", "exr", "flate2", "half", @@ -2786,6 +2796,7 @@ name = "craft-font-subset" version = "0.1.0" dependencies = [ "brotli 9.1.1", + "craft-testkit", "harfbuzz-subset-sys", "rustybuzz", "serde_json", @@ -3187,6 +3198,7 @@ dependencies = [ "craft-markdown", "craft-math", "craft-mime", + "craft-testkit", "craft-wordmodel", "proptest", ] @@ -3344,6 +3356,7 @@ name = "craft-mesh" version = "0.1.0" dependencies = [ "craft-opc", + "craft-testkit", "craft-xml", "craft-zip", "miniz_oxide 0.9.1", @@ -3462,6 +3475,7 @@ dependencies = [ name = "craft-openpgp" version = "0.1.0" dependencies = [ + "craft-testkit", "ed25519-dalek 2.2.0", "pgp", "proptest", @@ -3544,6 +3558,7 @@ dependencies = [ "chrono", "craft-stream-codecs", "craft-svg", + "craft-testkit", "flate2", "hayro", "hayro-cmap", @@ -3758,6 +3773,7 @@ dependencies = [ "craft-cms", "craft-pdf 0.1.0", "craft-plate-test", + "craft-testkit", "kurbo", "linesweeper", "thiserror 2.0.21", @@ -3801,6 +3817,7 @@ dependencies = [ name = "craft-proof" version = "0.1.0" dependencies = [ + "craft-testkit", "log", "miniz_oxide 0.9.1", "proptest", @@ -3813,6 +3830,7 @@ name = "craft-proto" version = "0.1.0" dependencies = [ "base64 0.23.1", + "craft-testkit", "log", "proptest", "zeroize", @@ -3836,6 +3854,7 @@ name = "craft-psd" version = "0.1.0" dependencies = [ "craft-psd", + "craft-testkit", "encoding_rs", "flate2", "proptest", @@ -3849,6 +3868,7 @@ name = "craft-pst" version = "0.1.0" dependencies = [ "craft-pst", + "craft-testkit", "proptest", ] @@ -3882,6 +3902,7 @@ dependencies = [ "chrono", "craft-crw", "craft-metadata", + "craft-testkit", "craft-tiff", "jpeg-encoder 0.7.1", "jxl-oxide", @@ -3961,6 +3982,7 @@ version = "0.1.0" dependencies = [ "craft-audio", "craft-midi", + "craft-testkit", "craft-time", "craft-zip", "proptest", @@ -4102,6 +4124,7 @@ dependencies = [ name = "craft-stream-codecs" version = "0.1.0" dependencies = [ + "craft-testkit", "fax", "hayro-ccitt", "hayro-jbig2", @@ -4386,6 +4409,7 @@ dependencies = [ "craft-quit", "craft-settings", "craft-svg", + "craft-testkit", "craft-theme", "craft-tracked", "craft-ui-contract", @@ -4770,6 +4794,7 @@ dependencies = [ name = "craft-xfl" version = "0.1.0" dependencies = [ + "craft-testkit", "craft-xml", "miniz_oxide 0.8.9", "thiserror 2.0.21", @@ -4795,6 +4820,7 @@ dependencies = [ "craft-drawingml", "craft-opc", "craft-sheet", + "craft-testkit", "craft-xlsx", "craft-xml", "thiserror 2.0.21", @@ -4804,6 +4830,7 @@ dependencies = [ name = "craft-xml" version = "0.1.0" dependencies = [ + "craft-testkit", "quick-xml 0.41.0", "serde", "thiserror 2.0.21", diff --git a/crates/android-res/Cargo.toml b/crates/android-res/Cargo.toml index cc54d2513c..114c4ae426 100644 --- a/crates/android-res/Cargo.toml +++ b/crates/android-res/Cargo.toml @@ -13,3 +13,6 @@ workspace = true [dependencies] serde = { workspace = true } thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs index 3525e0434c..d45b064464 100644 --- a/crates/android-res/src/axml.rs +++ b/crates/android-res/src/axml.rs @@ -631,9 +631,13 @@ mod tests { #[test] fn shared_offsets_spend_a_pool_byte_budget() { - for utf8 in [true, false] { + // Each parse keeps 64 MiB of strings: the gate runs the UTF-8 pool with the appended bytes + // (the budget and the appended bytes together), nightly all four. + let full = craft_testkit::hostile::divisor() == 1; + let (encodings, appends): (&[bool], &[bool]) = if full { (&[true, false], &[false, true]) } else { (&[true], &[true]) }; + for &utf8 in encodings { let mut data = shared_ascii_pool(utf8, 8192); - for appended in [false, true] { + for &appended in appends { if appended { // Unrelated bytes after the chunk cannot buy more retained copies. data.resize(24 << 20, 0); diff --git a/crates/audio-dsp/Cargo.toml b/crates/audio-dsp/Cargo.toml index 5d192e9d31..46e708b732 100644 --- a/crates/audio-dsp/Cargo.toml +++ b/crates/audio-dsp/Cargo.toml @@ -12,3 +12,6 @@ workspace = true # No dependencies: planar `&mut [f32]` slices in, planar slices out. [dependencies] + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/audio-dsp/src/biquad.rs b/crates/audio-dsp/src/biquad.rs index 12d00f5a9a..6b10add2b7 100644 --- a/crates/audio-dsp/src/biquad.rs +++ b/crates/audio-dsp/src/biquad.rs @@ -448,7 +448,7 @@ mod tests { #[test] fn every_effect_recovers_after_one_non_finite_sample() { let mut failures = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { for setting in [Setting::Default, Setting::Moved, Setting::Min] { let (l, r, _) = run_effect(e.id, setting, None); let clean = tail_rms(&l, &r); @@ -505,7 +505,7 @@ mod tests { #[test] fn nan_parameter_values_never_produce_non_finite_output() { let mut bad = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { let ids: Vec<&str> = crate::create_effect(e.id, SR as f32, 2).unwrap().params().iter().map(|p| p.id).collect(); for id in ids { let mut fx = crate::create_effect(e.id, SR as f32, 2).unwrap(); @@ -525,7 +525,7 @@ mod tests { #[test] fn subnormal_input_stays_finite_and_decays() { let mut bad = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { for setting in [Setting::Default, Setting::Min] { let mut fx = crate::create_effect(e.id, SR as f32, 2).unwrap(); for p in fx.params() { diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 29c406d7a1..862ee0f46a 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -234,7 +234,7 @@ mod tests { let src_l = noise(1, n, 0.7); let src_r = noise(2, n, 0.7); let change_at = 11111; - for e in effects() { + for e in crate::testutil::sampled_effects() { let run = |sizes: &mut dyn FnMut() -> usize| { let mut fx = (e.create)(SR, 2); let (mut l, mut r) = (src_l.clone(), src_r.clone()); @@ -289,7 +289,7 @@ mod tests { // One thread per effect. The tail stays 40 s long: delays, reverbs and graphic EQs still // produce output in its last second, some of it within 3x of the smallest normal f32. std::thread::scope(|scope| { - for e in effects() { + for e in crate::testutil::sampled_effects() { scope.spawn(move || { for setting in [0.0f32, 1.0] { let mut fx = (e.create)(SR, 2); @@ -325,7 +325,7 @@ mod tests { #[test] fn reset_restores_initial_behavior() { - for e in effects() { + for e in crate::testutil::sampled_effects() { let mut fx = (e.create)(SR, 2); let x = noise(8, 6000, 0.5); let (mut a1, mut a2) = (x.clone(), x.clone()); diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index dee405664d..0b6f05a802 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -429,7 +429,7 @@ fn convolution_reverb_impulses() { for (k, want_rt) in [(0usize, 0.45), (2, 1.9), (4, 1.6)] { let mut e = fx("convolution_reverb", &[("impulse", k as f32), ("mix", 100.0), ("width", 100.0)]); let lat = e.latency(); - let n = (SR * 4.0) as usize; + let n = (SR * 3.0) as usize; let mut imp = vec![0.0f32; n]; imp[0] = 1.0; let (l, r) = run(e.as_mut(), &imp, &imp); @@ -444,7 +444,7 @@ fn convolution_reverb_impulses() { } // Room size shortens the tail. let mut a = fx("convolution_reverb", &[("impulse", 2.0), ("mix", 100.0), ("room_size", 40.0)]); - let n = (SR * 3.0) as usize; + let n = (SR * 2.5) as usize; let mut imp = vec![0.0f32; n]; imp[0] = 1.0; let (l, _) = run(a.as_mut(), &imp, &imp); diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index 160362fc9e..c4b9ed7070 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -470,7 +470,7 @@ mod tests { use crate::AudioEffect; use crate::effects::DeNoise; const SR: f32 = 48_000.0; - let len = 512 * 940; + let len = 512 * 320; let mut rng = Rng::new(9); let a: Vec = (0..len).map(|_| 0.1 * rng.uniform()).collect(); let t = crate::testutil::sine(700.0, 0.2, SR as f64, len, 0.0); diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index b47d15fc16..59bfaa1741 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -434,6 +434,12 @@ pub(crate) fn block_len(channels: &[&mut [f32]]) -> usize { #[cfg(test)] pub(crate) mod testutil { + /// Every `CRAFT_HOSTILE_DIVISOR`-th registered effect: the gate's sample of a sweep over all + /// effects; the nightly run (no divisor) covers them all. + pub fn sampled_effects() -> impl Iterator { + crate::effects().iter().step_by(craft_testkit::hostile::divisor()) + } + /// Tiny deterministic PRNG (xorshift64*) for tests. pub struct Rng(u64); impl Rng { diff --git a/crates/audio-dsp/src/loudness.rs b/crates/audio-dsp/src/loudness.rs index 9cfcd18c00..a89a22593b 100644 --- a/crates/audio-dsp/src/loudness.rs +++ b/crates/audio-dsp/src/loudness.rs @@ -625,7 +625,7 @@ mod tests { fn tech3341_case1_and_2_stereo_sine() { for (sr, freq) in [(48000.0, 1000.0), (44100.0, 997.0), (96000.0, 1000.0)] { for level in [-23.0, -33.0] { - let x = segments(freq, sr, &[(20.0, level)]); + let x = segments(freq, sr, &[(6.0, level)]); let m = stereo_measure(&x, sr); assert!((m.integrated() - level).abs() < 0.1, "sr {sr} I {}", m.integrated()); assert!((m.momentary() - level).abs() < 0.1, "M {}", m.momentary()); @@ -639,7 +639,7 @@ mod tests { #[test] fn interleaved_matches_planar() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(5.0, -20.0)]); + let x = segments(1000.0, sr, &[(2.0, -20.0)]); let il: Vec = x.iter().flat_map(|&v| [v, v]).collect(); let mut m = LoudnessMeter::new(sr, 2); m.process_interleaved(&il); @@ -650,12 +650,12 @@ mod tests { #[test] fn tech3341_case3_4_gating() { let sr = 48000.0; - // Case 3: -36 / -23 / -36 dBFS for 10 / 60 / 10 s → -23.0 LUFS. - let x = segments(1000.0, sr, &[(10.0, -36.0), (60.0, -23.0), (10.0, -36.0)]); + // Case 3: -36 / -23 / -36 dBFS for 3 / 18 / 3 s → -23.0 LUFS. + let x = segments(1000.0, sr, &[(3.0, -36.0), (18.0, -23.0), (3.0, -36.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); - // Case 4: -72 / -36 / -23 / -36 / -72 dBFS for 10/10/60/10/10 s → -23.0 LUFS. - let x = segments(1000.0, sr, &[(10.0, -72.0), (10.0, -36.0), (60.0, -23.0), (10.0, -36.0), (10.0, -72.0)]); + // Case 4: -72 / -36 / -23 / -36 / -72 dBFS for 3/3/18/3/3 s → -23.0 LUFS. + let x = segments(1000.0, sr, &[(3.0, -72.0), (3.0, -36.0), (18.0, -23.0), (3.0, -36.0), (3.0, -72.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); } @@ -663,7 +663,7 @@ mod tests { #[test] fn tech3341_case5_relative_gate() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(20.0, -26.0), (20.1, -20.0), (20.0, -26.0)]); + let x = segments(1000.0, sr, &[(5.0, -26.0), (5.025, -20.0), (5.0, -26.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); } @@ -683,7 +683,8 @@ mod tests { #[test] fn tech3342_loudness_range() { - let sr = 48000.0; + // The range is level-relative, so a low rate gives the same reading for far fewer samples. + let sr = 16000.0; let cases: [(&[(f64, f64)], f64); 4] = [ (&[(20.0, -20.0), (20.0, -30.0)], 10.0), (&[(20.0, -20.0), (20.0, -15.0)], 5.0), @@ -712,15 +713,17 @@ mod tests { assert_eq!(before, 0.0); assert!((m.file_loudness_range() - s.loudness_range_lu).abs() < 1e-12); assert_eq!(m.loudness_range(), before); - // A steady program keeps a file range near 0. - let y = segments(1000.0, sr, &[(30.0, -20.0)]); - assert!(measure(&[&y, &y], sr).loudness_range_lu < 1.0); + // A steady program keeps a file range near 0. It must be long beside the 1.5 s silence tail, so it runs at a + // low rate (the range is level-relative). + let low = 16000.0; + let y = segments(1000.0, low, &[(30.0, -20.0)]); + assert!(measure(&[&y, &y], low).loudness_range_lu < 1.0); } #[test] fn log_sweep_matches_analytic_k_weighting() { let sr = 48000.0; - let secs = 20.0; + let secs = 6.0; let n = (sr * secs) as usize; let (f1, f2) = (20.0f64, 20000.0f64); let k = (f2 / f1).ln(); @@ -749,7 +752,7 @@ mod tests { #[test] fn surround_weights() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); let z = vec![0.0f32; x.len()]; // Signal only in Ls of a 5.1 layout → +1.5 dB weighting vs. front channel. let mut front = LoudnessMeter::new(sr, 6); @@ -767,7 +770,7 @@ mod tests { #[test] fn surround_weights_follow_speaker_positions() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); let z = vec![0.0f32; x.len()]; let only = |n: usize, ch: usize| { let mut m = LoudnessMeter::new(sr, n); @@ -776,7 +779,8 @@ mod tests { m.integrated() }; let front = only(8, 0); - assert!((only(8, 4) - front).abs() < 0.01, "back {}", only(8, 4) - front); + let back = only(8, 4) - front; + assert!(back.abs() < 0.01, "back {back}"); assert!((only(8, 6) - front - 10.0 * 1.41f64.log10()).abs() < 0.01); assert_eq!(only(8, 3), f64::NEG_INFINITY); assert_eq!(default_channel_weights(12), vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.41, 1.41, 1.0, 1.0, 1.0, 1.0]); @@ -864,14 +868,14 @@ mod tests { assert_eq!((m.sample_rate(), m.channels()), (f64::from(crate::FALLBACK_SAMPLE_RATE), 1)); assert_eq!(LoudnessMeter::new(48_000.0, usize::MAX).channels(), crate::MAX_CHANNELS); let sr = 48_000.0; - let mut x = segments(1000.0, sr, &[(5.0, -23.0)]); + let mut x = segments(1000.0, sr, &[(2.0, -23.0)]); x[1000] = f32::NAN; x[2000] = f32::INFINITY; let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "I {}", m.integrated()); assert!(m.true_peak().is_finite() && m.momentary().is_finite()); // A NaN or negative weight leaves its channel out instead of poisoning the sum. - let x = segments(1000.0, sr, &[(5.0, -23.0)]); + let x = segments(1000.0, sr, &[(2.0, -23.0)]); let mut m = LoudnessMeter::new(sr, 3); m.set_channel_weights(&[1.0, f64::NAN, -2.0]); m.process(&[&x, &x, &x]); @@ -883,12 +887,12 @@ mod tests { #[test] fn reset_clears_everything() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(5.0, -20.0)]); + let x = segments(1000.0, sr, &[(2.0, -20.0)]); let mut m = stereo_measure(&x, sr); m.reset(); assert_eq!(m.integrated(), f64::NEG_INFINITY); assert_eq!(m.true_peak(), 0.0); - let x = segments(1000.0, sr, &[(5.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); m.process(&[&x, &x]); assert!((m.integrated() + 30.0).abs() < 0.1); } @@ -942,7 +946,7 @@ mod tests { assert_eq!(normalize_gain_db_peak_limited(-30.0, -23.0, -10.0, -1.0), 7.0); // Applying the gain lands on target. let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -31.3)]); + let x = segments(1000.0, sr, &[(4.0, -31.3)]); let m = stereo_measure(&x, sr); let g = 10f64.powf(normalize_gain_db(m.integrated(), -16.0) / 20.0) as f32; let y: Vec = x.iter().map(|v| v * g).collect(); diff --git a/crates/audio-dsp/src/resample.rs b/crates/audio-dsp/src/resample.rs index 150eba11cc..745e628e47 100644 --- a/crates/audio-dsp/src/resample.rs +++ b/crates/audio-dsp/src/resample.rs @@ -418,6 +418,7 @@ mod tests { /// returns `MAX_RESAMPLE_BLOCK` frames. #[test] fn source_held_and_block_length_are_bounded() { + let t0 = std::time::Instant::now(); let mut r = StreamResampler::new(1_536_000, 1_000); let mut widest = 0; let out = r.process(0, 1_024, |_, frames| { @@ -427,8 +428,11 @@ mod tests { assert_eq!((out.len(), out[0].len()), (64, 1_024)); assert!(widest <= MAX_RESAMPLE_HELD / 64, "{widest}"); assert!(r.held.iter().map(Vec::len).sum::() <= MAX_RESAMPLE_HELD); + eprintln!("DIAG resample wide ratio {:?}", t0.elapsed()); + let t1 = std::time::Instant::now(); let mut r = StreamResampler::new(48_000, 48_000); let out = r.process(0, usize::MAX, |_, frames| vec![vec![0.5; frames]]); + eprintln!("DIAG resample oversized block {:?}", t1.elapsed()); assert_eq!(out[0].len(), MAX_RESAMPLE_BLOCK); assert!(out[0].iter().all(|&x| x == 0.5)); } diff --git a/crates/audio-dsp/src/sync.rs b/crates/audio-dsp/src/sync.rs index 56416ef875..d117ecba3f 100644 --- a/crates/audio-dsp/src/sync.rs +++ b/crates/audio-dsp/src/sync.rs @@ -454,11 +454,11 @@ mod tests { #[test] fn pure_delay_exact_both_signs() { let sr = 48_000; - let s = speechy(sr as f64, 12.0, 1); - for delay in [0i64, 1, 7, 12_345, 96_001, -4_321, -50_000] { + let s = speechy(sr as f64, 6.0, 1); + for delay in [0i64, 1, 7, 12_345, -4_321, -50_000] { // b = s shifted: b[n] = s[n + delay] let b: Vec = - (0..400_000i64).map(|n| if n + delay >= 0 && ((n + delay) as usize) < s.len() { s[(n + delay) as usize] } else { 0.0 }).collect(); + (0..200_000i64).map(|n| if n + delay >= 0 && ((n + delay) as usize) < s.len() { s[(n + delay) as usize] } else { 0.0 }).collect(); let r = find_offset(&s, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.lag, delay, "{r:?}"); assert!(r.reliable(), "{r:?}"); @@ -471,8 +471,8 @@ mod tests { #[test] fn multi_mic_offsets_within_one_sample() { let sr = 48_000u32; - let src = speechy(sr as f64, 30.0, 7); - let len = 30 * sr as usize; + let src = speechy(sr as f64, 12.0, 7); + let len = 12 * sr as usize; // mic k records src delayed by d_k: mic_k[n] = src[n - d_k] let cases: [(f64, f32, Option, f32); 4] = [(0.0, 1.0, None, 40.0), (2_345.0, 0.1, None, 25.0), (-31_337.4, 3.0, Some(0.3), 10.0), (150_000.6, 0.5, None, 3.0)]; @@ -551,7 +551,7 @@ mod tests { #[test] fn max_lag_limits_the_search() { let sr = 48_000; - let s = speechy(sr as f64, 10.0, 5); + let s = speechy(sr as f64, 5.0, 5); let b: Vec = s[48_000..].to_vec(); let r = find_offset(&s, &b, sr, &SyncOptions { max_lag: Some(60_000), ..Default::default() }).unwrap(); assert_eq!(r.lag, 48_000); @@ -560,7 +560,7 @@ mod tests { // Non-finite samples count as silence (also in the refinement's window search). let mut t = s.clone(); t[1_000] = f32::NAN; - t[300_000] = f32::INFINITY; + t[200_000] = f32::INFINITY; let r = find_offset(&t, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.lag, 48_000); assert!(r.confidence.is_finite() && r.lag_fine.is_finite(), "{r:?}"); @@ -586,15 +586,15 @@ mod tests { assert!(r.reliable(), "{r:?}"); } - /// A coarse budget that asks for more than [`MAX_DECIMATION`] still scales the coarse lag by - /// the factor applied: 2 × 9 M samples at 8 kHz with a 4,096-sample budget asks for 4,395. + /// A decimation factor asked for beyond [`MAX_DECIMATION`] still scales the coarse lag by the + /// factor applied. A sample rate of 2,048,001 Hz against a 500 Hz coarse rate asks for 4,097. #[test] fn a_coarse_factor_above_the_cap_still_finds_the_lag() { - let sr = 8_000; - let s = speechy(sr as f64, 2_300.0, 9); - let lag = 400_000usize; + let sr = 2_048_001; + let s = speechy(sr as f64, 0.8, 9); + let lag = 100_000usize; let b: Vec = s[lag..].to_vec(); - let opts = SyncOptions { max_coarse_samples: 4_096, ..Default::default() }; + let opts = SyncOptions { coarse_rate: 500, ..Default::default() }; let r = find_offset(&s, &b, sr, &opts).unwrap(); assert_eq!(r.lag, lag as i64, "{r:?}"); } @@ -623,11 +623,11 @@ mod tests { let sr = 48_000u32; let delay = 112_560i64; for seed in [1, 3, 7] { - let src = speechy(sr as f64, 24.0, seed); + let src = speechy(sr as f64, 10.0, seed); let scratch = scratch_track(&src, sr, 100 + seed); for sign in [1.0f32, -1.0] { // b[n] = scratch[n + delay] - let b: Vec = (0..16 * sr as i64).map(|n| sign * scratch.get((n + delay) as usize).copied().unwrap_or(0.0)).collect(); + let b: Vec = (0..7 * sr as i64).map(|n| sign * scratch.get((n + delay) as usize).copied().unwrap_or(0.0)).collect(); let r = find_offset(&src, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.inverted, sign < 0.0, "seed {seed}, sign {sign}: {r:?}"); // the filters delay the scratch track by a few samples diff --git a/crates/audio/src/aac/sbr/mod.rs b/crates/audio/src/aac/sbr/mod.rs index 752cd03a0b..d3c18b0e3a 100644 --- a/crates/audio/src/aac/sbr/mod.rs +++ b/crates/audio/src/aac/sbr/mod.rs @@ -493,7 +493,8 @@ mod tests { }; let mut e = Element::new(1, RATE); let mut pair = Element::new(2, RATE); - for i in 0..600 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the rounds. + for i in 0..600usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut data = good.clone(); for _ in 0..1 + next() % 6 { let bit = next() as usize % (8 * data.len()); diff --git a/crates/audio/src/ac3/encoder/tests.rs b/crates/audio/src/ac3/encoder/tests.rs index 27b232db9e..a60efb768b 100644 --- a/crates/audio/src/ac3/encoder/tests.rs +++ b/crates/audio/src/ac3/encoder/tests.rs @@ -105,8 +105,14 @@ fn dec3_describes_dependent_rear_pair_and_aggregate_rate() -> Result<(), Box Result<(), Box> { - for rate in [32000, 44100, 48000] { - for bitrate in super::super::BITRATES { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th bit rate, from a different offset for + // each sample rate, so the rates together still reach every bit rate. + let step = craft_media_testkit::hostile::divisor(); + for (ri, rate) in [32000, 44100, 48000].into_iter().enumerate() { + for (bi, bitrate) in super::super::BITRATES.into_iter().enumerate() { + if !(bi + ri).is_multiple_of(step) { + continue; + } for mode in [CodingMode::Mono, CodingMode::ThreeFrontTwoSurround] { let cfg = Config { codec: Codec::Ac3, sample_rate: rate, bitrate_kbps: bitrate, mode, lfe: mode == CodingMode::ThreeFrontTwoSurround }; diff --git a/crates/audio/tests/codecs/aac/robustness.rs b/crates/audio/tests/codecs/aac/robustness.rs index 2f97f2ae67..e3e622ce33 100644 --- a/crates/audio/tests/codecs/aac/robustness.rs +++ b/crates/audio/tests/codecs/aac/robustness.rs @@ -28,7 +28,8 @@ fn mutated_access_units_never_panic() { let mut errors = 0usize; for (asc, aus) in corpus() { let mut dec = Decoder::new(&asc).unwrap(); - for round in 0..3000 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the rounds. + for round in 0..3000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut au = aus[rand(aus.len())].clone(); match round % 6 { 0 => { diff --git a/crates/audio/tests/codecs/opus/robustness.rs b/crates/audio/tests/codecs/opus/robustness.rs index 781b767010..9ae1e83ea3 100644 --- a/crates/audio/tests/codecs/opus/robustness.rs +++ b/crates/audio/tests/codecs/opus/robustness.rs @@ -26,7 +26,8 @@ fn random_garbage_never_panics() { for channels in 1..=2 { let mut dec = StreamDecoder::new(rate, channels).unwrap(); let mut out = Vec::new(); - for i in 0..3000 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the packets. + for i in 0..3000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let len = (rng.next() % 400) as usize; let mut pkt: Vec = (0..len).map(|_| rng.next() as u8).collect(); if let Some(t) = pkt.first_mut() { @@ -52,7 +53,7 @@ fn multistream_garbage_never_panics() { h.extend([1, 6, 0x38, 0x01, 0x80, 0xBB, 0, 0, 0, 0, 1, 4, 2, 0, 4, 1, 2, 3, 5]); let mut dec = Decoder::new(&h).unwrap(); let mut rng = Rng(42); - for _ in 0..2000 { + for _ in 0..2000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let len = (rng.next() % 600) as usize; let pkt: Vec = (0..len).map(|_| rng.next() as u8).collect(); if let Ok(out) = dec.decode(Some(&pkt)) { diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs index 2638585603..a48ad2d444 100644 --- a/crates/audio/tests/codecs/opusenc/modes.rs +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -49,12 +49,14 @@ fn band_edge(bw: Bandwidth) -> f64 { } const LEN: usize = 96_000; +/// The length of the sweeps over many encodes: one second. +const SHORT: usize = 48_000; #[test] fn every_mode_and_bandwidth_decodes() { - let sp = speech(LEN + 40_000, 11); - let left = sp[..LEN].to_vec(); - let right: Vec = sp[40_000..].iter().map(|v| v * 0.6).collect(); + let sp = speech(SHORT + 20_000, 11); + let left = sp[..SHORT].to_vec(); + let right: Vec = sp[20_000..].iter().map(|v| v * 0.6).collect(); for (mode, bw, config, rate) in [ (Mode::Silk, Bandwidth::Narrowband, 1u8, 8_000u32), (Mode::Silk, Bandwidth::Mediumband, 5, 11_000), @@ -149,8 +151,8 @@ fn silk_music_quality() { #[test] fn bitrate_tracking() { - let sp = speech(LEN, 13); - let mu = music(LEN); + let sp = speech(SHORT, 13); + let mu = music(SHORT); for (name, x) in [("speech", &sp), ("music", &mu)] { for (mode, bw, rate) in [ (Mode::Silk, Bandwidth::Narrowband, 6_000u32), @@ -178,10 +180,10 @@ fn bitrate_tracking() { #[test] fn stereo_silk_and_hybrid() { - let sp = speech(LEN + 40_000, 21); - let a = sp[..LEN].to_vec(); - let b: Vec = sp[40_000..].iter().map(|v| v * 0.7).collect(); - let mu = music(LEN); + let sp = speech(SHORT + 20_000, 21); + let a = sp[..SHORT].to_vec(); + let b: Vec = sp[20_000..].iter().map(|v| v * 0.7).collect(); + let mu = music(SHORT); let cases: Vec<(&str, Vec, Vec)> = vec![ ("dual mono", a.clone(), a.clone()), ("panned", a.iter().map(|v| v * 0.9).collect(), a.iter().map(|v| v * 0.35).collect()), diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs index d252372514..214898c230 100644 --- a/crates/audio/tests/flac_decode.rs +++ b/crates/audio/tests/flac_decode.rs @@ -132,15 +132,17 @@ fn track_decoder_uses_streaminfo_layout_and_packet_length() { #[test] fn hostile_input_is_an_error_not_a_panic() { - let src = signal(2, 6000, 16, 11); + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th cut and flipped byte. + let step = craft_media_testkit::hostile::divisor(); + let src = signal(2, 3500, 16, 11); let file = encode(&src, 44_100, 16, 1152, 5); - for n in 0..file.len().min(3000) { + for n in (0..file.len().min(3000)).step_by(step) { let _ = decode(&file[..n]); } // A cut file is truncated, not silently shorter. assert!(decode(&file[..file.len() - 5]).is_err()); // Every bit flip in the first frames is caught by a CRC or another check, never a panic. - for i in 0..file.len().min(2500) { + for i in (0..file.len().min(2500)).step_by(step) { for bit in 0..8 { let mut c = file.clone(); c[i] ^= 1 << bit; diff --git a/crates/audio/tests/vorbis_decode_hostile.rs b/crates/audio/tests/vorbis_decode_hostile.rs index fba004e109..4bbccfe460 100644 --- a/crates/audio/tests/vorbis_decode_hostile.rs +++ b/crates/audio/tests/vorbis_decode_hostile.rs @@ -57,7 +57,8 @@ fn damaged_headers_never_panic() { let mut seed = 99u32; for which in [0usize, 2] { let len = p.headers[which].len(); - for _ in 0..800 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the mutations. + for _ in 0..800usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut h = p.headers.clone(); for _ in 0..1 + xorshift(&mut seed) % 3 { let at = xorshift(&mut seed) as usize % len; diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index 1136f55f9e..4a4e27520f 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -21,6 +21,7 @@ craft-xml = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } # A second XML reader for the tests: checks of written TTML, and the comparison in tests/it/ttml_xml_views.rs. roxmltree = "0.21" diff --git a/crates/captions/tests/it/limits.rs b/crates/captions/tests/it/limits.rs index 3b908fa063..0b010ed412 100644 --- a/crates/captions/tests/it/limits.rs +++ b/crates/captions/tests/it/limits.rs @@ -35,7 +35,8 @@ fn mutated_files_never_panic() { for format in Format::ALL { let bytes = write(&doc(), format, WriteOptions::default()); // every byte of a text file, and the header and first blocks of the (sparse) binary one - for i in 0..bytes.len().min(2048) { + // The gate runs every divisor-th byte; nightly runs every one. + for i in (0..bytes.len().min(2048)).step_by(craft_testkit::hostile::divisor()) { for v in [0u8, 0x20, 0x3c, 0x7f, 0xff] { let mut m = bytes.clone(); if let Some(b) = m.get_mut(i) { diff --git a/crates/cfb/Cargo.toml b/crates/cfb/Cargo.toml index e2684da0b8..853038aaea 100644 --- a/crates/cfb/Cargo.toml +++ b/crates/cfb/Cargo.toml @@ -13,4 +13,5 @@ workspace = true [dependencies] [dev-dependencies] +craft-testkit = { workspace = true } craft-media-testkit = { workspace = true } diff --git a/crates/cfb/src/tests/ported.rs b/crates/cfb/src/tests/ported.rs index f49f9f6c0e..476daebe3e 100644 --- a/crates/cfb/src/tests/ported.rs +++ b/crates/cfb/src/tests/ported.rs @@ -557,7 +557,8 @@ fn truncation_at_every_length_never_panics() { #[test] fn every_single_bit_flip_never_panics_or_hangs() { for (mut file, _) in small_samples() { - for bit in 0..file.len() * 8 { + // The gate flips every divisor-th bit; nightly flips each one. + for bit in (0..file.len() * 8).step_by(craft_testkit::hostile::divisor()) { file[bit / 8] ^= 1 << (bit % 8); exercise(&file, None); file[bit / 8] ^= 1 << (bit % 8); diff --git a/crates/cms/Cargo.toml b/crates/cms/Cargo.toml index 51fb2aab7c..c876e4d42c 100644 --- a/crates/cms/Cargo.toml +++ b/crates/cms/Cargo.toml @@ -20,4 +20,5 @@ md5 = { workspace = true } rayon = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } moxcms = "0.8" diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs index 8752cdaa2b..2d4864a990 100644 --- a/crates/cms/src/black_tests.rs +++ b/crates/cms/src/black_tests.rs @@ -70,10 +70,12 @@ fn the_destination_black_matches_the_source_lightness() { for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { for bpc in [true, false] { let o = TransformOptions { intent, bpc, ..opts() }; - for (src, dst) in [(coated(), fogra()), (fogra(), coated())] { + // Both directions for one setting; the other settings in the forward one. + let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 }; + for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) { let bp = BlackPreserving::new(src, dst, o).unwrap(); let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); - for k in [0.1f32, 0.3, 0.5, 0.7, 0.9, 1.0] { + for k in [0.1f32, 0.5, 0.9, 1.0] { let want = lightness(src, o, [0.0, 0.0, 0.0, k]); if want <= dst_black { assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); diff --git a/crates/cms/tests/cms.rs b/crates/cms/tests/cms.rs index bf6934d9ac..00b9b3b7a4 100644 --- a/crates/cms/tests/cms.rs +++ b/crates/cms/tests/cms.rs @@ -115,7 +115,9 @@ fn white_is_exact_on_every_path() { let none = [0.0f32; 4]; for cmyk in [Builtin::CoatedCmyk, Builtin::CoatedFogra39] { for intent in [Intent::Perceptual, Intent::RelativeColorimetric, Intent::Saturation] { - for bpc in [false, true] { + // The gate runs black point compensation on; nightly both. + let bpcs: &[bool] = if craft_testkit::hostile::divisor() > 1 { &[true] } else { &[false, true] }; + for &bpc in bpcs { for precise_float in [false, true] { let opts = TransformOptions { intent, bpc, precise_float }; let at = format!("{cmyk:?} {opts:?}"); diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index bc44235a8a..7a00b133e8 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -299,7 +299,10 @@ fn the_full_picker_keeps_photoshops_arrangement_in_every_room_density_and_theme( for look in LOOKS { let wide = full_picker(600.0, look, 2); let parts = FullParts::of(&wide, 2); - the_arrangement_holds_in_other_rooms(look, &wide, &parts); + // The rooms are compared in one look, the widest: each look's own arrangement is checked below. + if look == ROOMS_LOOK { + the_arrangement_holds_in_other_rooms(look, &wide, &parts); + } the_area_strip_and_compare_block_stand_as_in_photoshop(look, &parts); the_field_groups_stand_under_the_compare_block(look, &parts); the_hex_field_and_the_rows_under_the_area_stand_as_in_photoshop(look, &parts); @@ -313,6 +316,9 @@ fn the_full_picker_keeps_photoshops_arrangement_in_every_room_density_and_theme( type Look = (Size, &'static str); +/// The look the other rooms are compared in: the comfortable density is the widest, so a narrow room presses it most. +const ROOMS_LOOK: Look = (Size::Comfortable, "craft.studio"); + /// Wider and narrower rooms leave the arrangement alone, and the warnings move no other part. fn the_arrangement_holds_in_other_rooms(look: Look, wide: &Fixture, parts: &FullParts) { assert_eq!(&FullParts::of(&full_picker(1200.0, look, 2), 2), parts, "{look:?}: the same arrangement in a room 1200 wide"); diff --git a/crates/color-ui/tests/it/sampling.rs b/crates/color-ui/tests/it/sampling.rs index bdf5aec724..53ce25aa92 100644 --- a/crates/color-ui/tests/it/sampling.rs +++ b/crates/color-ui/tests/it/sampling.rs @@ -202,9 +202,11 @@ fn an_invalid_capture_ends_the_pick_with_a_status() { assert!(pick.take_status(&words).is_some(), "and says why"); assert!(pick.take_status(&words).is_none(), "once"); - // A valid profile of another colour space: a CMYK monitor profile is not an RGB profile. + // A valid profile of another colour space: a CMYK monitor profile is not an RGB profile. The smallest grids make + // it as valid as the default coated profile, which takes far longer to build. let mut odd = monitor([0, 0], [4, 4], 1); - odd.icc_profile = Some(craft_cms::synth::coated_cmyk().expect("the synthetic CMYK profile").to_bytes()); + let params = craft_cms::synth::CmykParams { grid_a2b: 2, grid_b2a: 2, ..craft_cms::synth::CmykParams::default() }; + odd.icc_profile = Some(craft_cms::synth::cmyk_profile(¶ms).expect("the synthetic CMYK profile").to_bytes()); let mut pick = ScreenPick::new(); pick.start("a"); pick.tick_with(&ctx, 1, &|| images(vec![odd.clone()])); diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs index 7393ef4f32..c3ac0a9e10 100644 --- a/crates/develop/src/inpaint.rs +++ b/crates/develop/src/inpaint.rs @@ -116,7 +116,10 @@ mod tests { assert!(matches!(complete_with(w, h, 1, &img, &hole, &p, &count), Ok(Some(_)))); let total = polls.load(Ordering::Relaxed); assert!(total > 8, "the scene polls in the workers too: {total}"); - for nth in 0..total { + // Cancelling at the first, a quarter, the middle, three quarters and the last polls, workers' polls included. + let mut picks = vec![0, 1, 2, total / 4, total / 2, 3 * total / 4, total - 3, total - 2, total - 1]; + picks.dedup(); + for nth in picks { let polls = AtomicUsize::new(0); let once = || polls.fetch_add(1, Ordering::Relaxed) == nth; assert_eq!(complete_with(w, h, 1, &img, &hole, &p, &once), Err(Cancelled), "poll {nth} of {total}"); diff --git a/crates/develop/src/sensor/opcodes.rs b/crates/develop/src/sensor/opcodes.rs index 0ef3cefa04..218ef7d8de 100644 --- a/crates/develop/src/sensor/opcodes.rs +++ b/crates/develop/src/sensor/opcodes.rs @@ -100,6 +100,12 @@ fn op_cost(op: &Opcode, w: usize, h: usize, cpp: usize) -> usize { } pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32) { + apply_list_capped(list, buf, w, h, cpp, cfa, scale, MAX_BAD_PIXELS); +} + +/// [`apply_list`] with each bad-pixel opcode repairing at most `max_bad_pixels` pixels. +#[allow(clippy::too_many_arguments)] +fn apply_list_capped(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32, max_bad_pixels: usize) { let mut budget = w.saturating_mul(h).saturating_mul(cpp).max(1).saturating_mul(MAX_LIST_PASSES); for op in list { let cost = op_cost(op, w, h, cpp); @@ -175,17 +181,17 @@ pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usi Opcode::FixBadPixelsConstant { constant, .. } => { let c = (*constant as f64 / 65535.0 * scale as f64) as f32; let bad: Vec<(usize, usize)> = - (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| cpp == 1 && buf[y * w + x] == c).take(MAX_BAD_PIXELS).collect(); + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| cpp == 1 && buf[y * w + x] == c).take(max_bad_pixels).collect(); fix_pixels(buf, w, h, cpp, cfa, &bad); } Opcode::FixBadPixelsList { points, rects, .. } => { let mut bad: Vec<(usize, usize)> = - points.iter().map(|&(r, c)| (c as usize, r as usize)).filter(|&(x, y)| x < w && y < h).take(MAX_BAD_PIXELS).collect(); + points.iter().map(|&(r, c)| (c as usize, r as usize)).filter(|&(x, y)| x < w && y < h).take(max_bad_pixels).collect(); 'rects: for r in rects { let [t, l, b, rr] = r.map(|v| v as usize); for y in t..b.min(h) { for x in l..rr.min(w) { - if bad.len() >= MAX_BAD_PIXELS { + if bad.len() >= max_bad_pixels { break 'rects; } bad.push((x, y)); diff --git a/crates/develop/src/sensor/opcodes/tests.rs b/crates/develop/src/sensor/opcodes/tests.rs index c97b81eead..44a45bddad 100644 --- a/crates/develop/src/sensor/opcodes/tests.rs +++ b/crates/develop/src/sensor/opcodes/tests.rs @@ -117,15 +117,15 @@ fn map_table_raw_scale_and_bad_pixels() { /// A mosaic equal to the bad-pixel constant, or one rectangle over the whole image, used to list every pixel as /// bad: w × h entries (plus a set of them), tens of GB at the decoder's size limit. Here the rows between a good -/// first row (500) and a good last row (900) are bad: 2052 rows of 2048 pixels, four rows more than the 1 << 22 -/// cap. Row 1, within the cap, is repaired from the first row; the second-last row, past the cap, must be left -/// as it is (uncapped, it was rewritten from the last row). +/// first row (500) and a good last row (900) are bad: 8 rows of 64 pixels, four rows more than the cap of 256 the +/// test passes. Row 1, within the cap, is repaired from the first row; the second-last row, past the cap, must be +/// left as it is (uncapped, it was rewritten from the last row). fn assert_bad_pixels_capped(op: Opcode) { - let (w, h) = (2048, 2054); + let (w, h) = (64, 10); let mut buf = vec![0.0f32; w * h]; buf[..w].fill(500.0); buf[(h - 1) * w..].fill(900.0); - apply_list(&[op], &mut buf, w, h, 1, None, 65535.0); + apply_list_capped(&[op], &mut buf, w, h, 1, None, 65535.0, 256); assert!(buf[w..2 * w].iter().all(|&v| v == 500.0), "row 1 (within the cap) not repaired: {:?}", &buf[w..w + 4]); let past = &buf[(h - 2) * w..(h - 1) * w]; assert!(past.iter().all(|&v| v == 0.0), "a row past the cap was rewritten: {:?}", &past[..4]); @@ -139,7 +139,7 @@ fn bad_pixels_constant_is_capped() { #[test] fn bad_pixels_list_is_capped_inside_a_rectangle() { // top, left, bottom, right: every row but the first and the last - assert_bad_pixels_capped(Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![], rects: vec![[1, 0, 2053, 2048]] }); + assert_bad_pixels_capped(Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![], rects: vec![[1, 0, 9, 64]] }); } #[test] diff --git a/crates/develop/src/tests_crystal.rs b/crates/develop/src/tests_crystal.rs index 672a598c54..bb6a7bddcd 100644 --- a/crates/develop/src/tests_crystal.rs +++ b/crates/develop/src/tests_crystal.rs @@ -104,8 +104,8 @@ fn small_render_is_the_downscaled_reference() { for (size, rough) in [(0.0, 50.0), (25.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { let t = tile_of(size, rough); for k in [2usize, 4, 8] { - let full = patch(&t, REF_LONG, 120 * k, 0); - let n = 120; + let n = 48; + let full = patch(&t, REF_LONG, n * k, 0); let down: Vec = (0..n * n) .map(|q| { let (x, y) = (q % n, q / n); @@ -129,7 +129,7 @@ fn small_render_is_the_downscaled_reference() { fn strength_matches_the_target_at_mid_grey() { for (a, s, r) in [(50.0, 25.0, 50.0), (25.0, 25.0, 50.0), (50.0, 0.0, 50.0), (50.0, 100.0, 50.0), (50.0, 25.0, 0.0)] { let g = CrystalGrain::new(&Grain { amount: a, size: s, roughness: r, seed: 3 }, REF_LONG).expect("grain"); - let n = 500; + let n = 320; let lum: Vec = (0..n * n) .map(|k| { let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); @@ -153,7 +153,7 @@ fn tones_keep_their_mean() { for (amount, size, levels) in cases { let g = CrystalGrain::new(&Grain { amount, size, roughness: 50.0, seed: 3 }, REF_LONG).expect("grain"); for &level in levels { - let n = 400; + let n = 256; let mut sum = 0.0f64; for k in 0..n * n { let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); @@ -388,7 +388,9 @@ fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002); let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0)); let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0); + let drawing = std::time::Instant::now(); let first = tile(a, seed, true).expect("tile"); + eprintln!("DIAG crystal tile at size 30: {:?}", drawing.elapsed()); assert_eq!(first.look, a); let stand_in = tile(b, seed, false).expect("tile"); assert_eq!(stand_in.look, a, "the draft waited for its tile"); @@ -402,8 +404,9 @@ fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { assert!(std::time::Instant::now() < deadline, "the background tile never arrived"); std::thread::sleep(std::time::Duration::from_millis(5)); }; - assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed)); - assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed)); + let exact_b = exact(b, seed); + assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact_b); + assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact_b); // nothing drawn for this seed: nothing to stand in, the draft draws it assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh)); } @@ -474,7 +477,7 @@ fn renders_that_miss_a_tile_together_draw_it_once() { static OWN: Cache = Mutex::new(Vec::new()); const N: usize = 8; // the first render's draw waits for the other seven to miss the tile too - const SEEDS: u32 = 40; + const SEEDS: u32 = 5; HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1, SEEDS as usize)); let look = CrystalLook::new(0.0, 50.0); for seed in 0x0d4a_1000..0x0d4a_1000 + SEEDS { diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index decaff8db2..dd3d2459d8 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -29,3 +29,6 @@ thiserror = { workspace = true } # `pcraft-pixels`: PhotoCraft's tiles are zstd frames named by the BLAKE3 hash of their samples. blake3 = { version = "1.8", default-features = false, features = ["pure"], optional = true } ruzstd = { version = "0.9", default-features = false, features = ["std"], optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/doc/tests/hostile.rs b/crates/doc/tests/hostile.rs index 33f93d69f9..4c8aa57972 100644 --- a/crates/doc/tests/hostile.rs +++ b/crates/doc/tests/hostile.rs @@ -82,7 +82,7 @@ impl Rng { fn seeded_mutations_never_panic() { let mut rng = Rng(0x5eed); for s in samples() { - for _ in 0..1500 { + for _ in 0..1500 / craft_testkit::hostile::divisor() { let mut d = s.clone(); for _ in 0..1 + rng.below(4) { let at = rng.below(d.len()); diff --git a/crates/doc/tests/pixels.rs b/crates/doc/tests/pixels.rs index aa2f02f21e..de2687b45e 100644 --- a/crates/doc/tests/pixels.rs +++ b/crates/doc/tests/pixels.rs @@ -120,7 +120,8 @@ fn every_truncation_and_flipped_byte_is_an_error_not_a_panic() { let m = surface("Grayscale", "U8", false, &[255], &[(0, 0, &hash(&mask_tile))]); let file = bundle(3, 2, "Rgb", &[layer(&raster(&s), Some(&m))], &[&tile, &mask_tile]); assert!(read(&file, &[0]).mask.is_some()); - for n in 0..file.len() { + // The gate runs every divisor-th truncation and flip; nightly runs every one. + for n in (0..file.len()).step_by(craft_testkit::hostile::divisor()) { let _ = pcraft_layer_rgba(&file[..n], &[0], &Limits::default()); let mut flipped = file.clone(); flipped[n] ^= 0xff; diff --git a/crates/docx/Cargo.toml b/crates/docx/Cargo.toml index ed84356e03..0ffedf2aac 100644 --- a/crates/docx/Cargo.toml +++ b/crates/docx/Cargo.toml @@ -28,6 +28,7 @@ zeroize = "1" [dev-dependencies] craft-cfb = { workspace = true } +craft-testkit = { workspace = true } craft-opc = { workspace = true, features = ["test-support"] } craft-wordmodel = { workspace = true, features = ["test-support"] } image = { version = "0.25", default-features = false, features = ["png"] } diff --git a/crates/docx/src/read/chart/tests.rs b/crates/docx/src/read/chart/tests.rs index 1aeab52350..ea338016e6 100644 --- a/crates/docx/src/read/chart/tests.rs +++ b/crates/docx/src/read/chart/tests.rs @@ -230,11 +230,12 @@ fn hostile_radar_charts_never_panic() { let small = chart_items(&space(&format!("{}", ser(0, "S", None, &["a", "b", "c"], &["1", "2", "3"]))), &theme(), 20.0, 20.0); let _ = small; - // Caps: thousands of categories and series stay bounded. - let cats: Vec = (0..5000).map(|i| format!("c{i}")).collect(); + // Caps: three times as many categories and series as are drawn stay bounded. + let n = 3 * MAX_SPOKES; + let cats: Vec = (0..n).map(|i| format!("c{i}")).collect(); let refs: Vec<&str> = cats.iter().map(String::as_str).collect(); - let vals = vec!["1"; 5000]; - let many: Vec = (0..300).map(|i| ser(i, "S", None, &refs, &vals)).collect(); + let vals = vec!["1"; n]; + let many: Vec = (0..3 * MAX_RADAR_SERIES).map(|i| ser(i, "S", None, &refs, &vals)).collect(); let items = radar_chart("marker", &many); let polygons = items.iter().filter(|it| matches!(it, GraphicItem::Path { stroke: Some(c), .. } if *c != GRID)).count(); assert!(polygons <= MAX_RADAR_SERIES, "{polygons}"); diff --git a/crates/docx/tests/it/comment_save_cost.rs b/crates/docx/tests/it/comment_save_cost.rs index 2bcd5fb863..88902400bb 100644 --- a/crates/docx/tests/it/comment_save_cost.rs +++ b/crates/docx/tests/it/comment_save_cost.rs @@ -29,8 +29,8 @@ fn cpu_cost(mut f: impl FnMut()) -> f64 { #[test] fn many_comments_save_without_quadratic_id_searches() { for imported in [true, false] { - let small = comments(4_000, imported); - let big = comments(32_000, imported); + let small = comments(1_000, imported); + let big = comments(8_000, imported); let save = |d: &Document| drop(std::hint::black_box(craft_docx::write(d).unwrap())); save(&small); save(&big); @@ -39,7 +39,7 @@ fn many_comments_save_without_quadratic_id_searches() { // use elapsed time; retry ratios far from linear before declaring a regression. for _ in 0..3 { let (mut s, mut b) = (f64::INFINITY, f64::INFINITY); - for _ in 0..3 { + for _ in 0..2 { s = s.min(cpu_cost(|| (0..8).for_each(|_| save(&small))) / 8.0); b = b.min(cpu_cost(|| save(&big))); } diff --git a/crates/docx/tests/it/content_control_save_cost.rs b/crates/docx/tests/it/content_control_save_cost.rs index 9b96aeb7b2..768f00ede3 100644 --- a/crates/docx/tests/it/content_control_save_cost.rs +++ b/crates/docx/tests/it/content_control_save_cost.rs @@ -59,7 +59,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( big(); let mut small_scaled = || (0..scale).for_each(|_| small()); let (mut t1, mut tk) = (f64::INFINITY, f64::INFINITY); - for _ in 0..5 { + for _ in 0..3 { let a = Instant::now(); small_scaled(); t1 = t1.min(a.elapsed().as_secs_f64() / scale as f64); @@ -76,8 +76,8 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( #[test] fn a_document_with_many_inline_content_controls_saves_in_linear_time() { let scale = 4; - let small = inline_controls(8_000); - let big = inline_controls(8_000 * scale); + let small = inline_controls(2_000); + let big = inline_controls(2_000 * scale); let (t1, tk, ratio) = cost_ratio( scale, || { @@ -96,8 +96,8 @@ fn a_document_with_many_inline_content_controls_saves_in_linear_time() { #[test] fn a_document_with_many_block_content_controls_saves_in_linear_time() { let scale = 4; - let small = block_controls(8_000); - let big = block_controls(8_000 * scale); + let small = block_controls(2_000); + let big = block_controls(2_000 * scale); let (t1, tk, ratio) = cost_ratio( scale, || { diff --git a/crates/docx/tests/it/element_budget.rs b/crates/docx/tests/it/element_budget.rs index 6b220ae7ce..d18e2762a7 100644 --- a/crates/docx/tests/it/element_budget.rs +++ b/crates/docx/tests/it/element_budget.rs @@ -9,6 +9,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm #[test] fn a_file_of_element_budget_parts_still_reads() { + // 18M elements: nightly only. `the_xml_element_budget_is_package_wide` (in `package.rs`) proves + // the package-wide budget with a small one at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } // Nine chart parts of 2M elements each: 18M over the package's 16M budget. The later // parts are skipped with a warning instead of built, and the file still reads. Before // the budget, every part's whole tree was parsed and the chart trees stayed cached for diff --git a/crates/docx/tests/it/malformed.rs b/crates/docx/tests/it/malformed.rs index b1c5b8f17a..fc65b8e2d6 100644 --- a/crates/docx/tests/it/malformed.rs +++ b/crates/docx/tests/it/malformed.rs @@ -179,7 +179,8 @@ fn many_fields_and_huge_attribute_values() { /// limit error, or the extras are dropped and the text survives (#3702, WC-06). #[test] fn millions_of_attributes_on_one_paragraph_are_capped() { - let attrs: String = (0..2_000_000).map(|i| format!(" a{i}=\"\"")).collect(); + // The gate reads a fraction of the attributes; nightly all of them. + let attrs: String = (0..2_000_000 / craft_testkit::hostile::divisor()).map(|i| format!(" a{i}=\"\"")).collect(); let x = format!("kept"); // Only the read is timed: deflating the test input in a debug build is not what is bounded. let z = doc_zip(x.as_bytes()); @@ -253,7 +254,7 @@ fn malformed_or_hostile_bibliography_never_panics() { fn hostile_bibliography_source_count_is_capped() { let doc = format!("body"); let mut sources = String::from(r#""#); - for i in 0..60_000 { + for i in 0..(60_000 / craft_testkit::hostile::divisor()).max(10_500) { sources.push_str(&format!("T{i}Title {i}")); // Untagged duplicates all collapse into one source. sources.push_str("Same"); @@ -313,11 +314,13 @@ fn compound(info: &[u8], package: &[u8]) -> Vec { proptest! { // Each case that parses runs the 50,000-spin key derivation, so fewer cases. - #![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })] + #![proptest_config(ProptestConfig { cases: (48 / craft_testkit::hostile::divisor() as u32).max(6), ..ProptestConfig::default() })] #[test] fn mutated_standard_encryption_never_panics(ops in proptest::collection::vec((0u8..3, any::(), any::(), any::()), 1..8)) { - let (mut info, mut package) = standard_streams(); + // Encrypting runs the key derivation too: once for every case. + static STREAMS: std::sync::OnceLock<(Vec, Vec)> = std::sync::OnceLock::new(); + let (mut info, mut package) = STREAMS.get_or_init(standard_streams).clone(); for (k, idx, byte, in_package) in ops { let x = if in_package { &mut package } else { &mut info }; let at = idx.index(x.len() + 1); diff --git a/crates/docx/tests/it/word_xml.rs b/crates/docx/tests/it/word_xml.rs index 31c022aa0e..2571facb27 100644 --- a/crates/docx/tests/it/word_xml.rs +++ b/crates/docx/tests/it/word_xml.rs @@ -268,6 +268,10 @@ fn flat_opc_limits_count_what_is_not_kept() { assert!(limited(&r#"AA=="#.repeat(20_000))); assert!(limited(&"".repeat(20_000))); // A part nothing reads, one element over what the XML tree reader takes in a part (8 000 000). + // Millions of elements: nightly only; the checks above prove the same counting at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } assert!(limited(&format!(r#"{}"#, "".repeat(8_000_000)))); } diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 1dd92177a9..91321e351f 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -1762,8 +1762,8 @@ mod chartex_tests { #[test] fn large_box_hierarchy_and_stacked_charts_take_linear_work() { - // 50,000 distinct categories in one series: grouped through a map, one pass. - let n = 50_000; + // 5,000 distinct categories in one series: grouped through a map, one pass. + let n = 5_000; let mut c = Chart::sample(ChartType::BoxWhisker); c.series.truncate(1); c.categories = (0..n).map(|i| format!("g{i}")).collect(); @@ -1771,12 +1771,13 @@ mod chartex_tests { let (groups, stats) = c.box_groups(); assert_eq!((groups.len(), stats[0].len()), (n, n)); assert!(stats[0].iter().all(Option::is_some)); - // 2,000 series cap the groups so the result stays within MAX_BOX_CELLS. - c.series = vec![c.series[0].clone(); 2000]; + // Enough series to cap the groups so the result stays within MAX_BOX_CELLS. + let series = MAX_BOX_CELLS / n * 2; + c.series = vec![c.series[0].clone(); series]; let (groups, stats) = c.box_groups(); - assert_eq!(groups.len(), MAX_BOX_CELLS / 2000); + assert_eq!(groups.len(), MAX_BOX_CELLS / series); assert!(stats.iter().all(|s| s.len() == groups.len())); - // One long outer label over 50,000 leaves is shared, not copied per leaf. + // One long outer label over 5,000 leaves is shared, not copied per leaf. let mut t = Chart::sample(ChartType::Treemap); t.series.truncate(1); t.categories = (0..n).map(|i| format!("c{i}")).collect(); diff --git a/crates/drawingml/src/table.rs b/crates/drawingml/src/table.rs index b5d83d5304..02e3066994 100644 --- a/crates/drawingml/src/table.rs +++ b/crates/drawingml/src/table.rs @@ -749,7 +749,11 @@ mod tests { let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() }; t.normalize(); assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1)); - let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() }; + let wide = Table { + cols: vec![10.0; 1000], + rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1100] }; MAX_CELLS / 1000 + 1], + ..Default::default() + }; let mut n = wide.clone(); n.normalize(); assert_eq!(wide.normalized(), n); diff --git a/crates/exr/Cargo.toml b/crates/exr/Cargo.toml index 7221a6858c..28a1649b8b 100644 --- a/crates/exr/Cargo.toml +++ b/crates/exr/Cargo.toml @@ -24,3 +24,6 @@ half = { version = "2", optional = true } thiserror = { workspace = true, optional = true } # zlib for scanline payloads and deep ZIPS chunks, which the `exr` crate does not read. flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 61f207a164..32fefa029f 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -243,11 +243,13 @@ fn hostile_files_never_panic() { (5, 3), ); let limits = Limits { max_bytes: 1 << 24, ..Limits::default() }; - for n in 0..good.len() { + // The gate runs every divisor-th truncation and byte; nightly runs every one. + let step = craft_testkit::hostile::divisor(); + for n in (0..good.len()).step_by(step) { let _ = parts(&good[..n], &limits); let _ = decode_part(&good[..n], 1, &all, &limits); } - for i in 0..good.len() { + for i in (0..good.len()).step_by(step) { for v in [0u8, 1, 0x7F, 0xFF] { let mut b = good.clone(); b[i] = v; diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 0104922351..0f48fdb386 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -354,12 +354,13 @@ fn hostile_files_are_refused_and_never_panic() { let channels: Vec<(usize, usize)> = (0..index.parts().len()).flat_map(|p| channels_of(&index, p)).collect(); let _ = read_planes(&mut Cursor::new(data), &index, &Request::new(&channels, 1 << 24), &never); }; - // Every truncation. - for n in 0..bytes.len() { + // Every truncation (at the gate every divisor-th one, as for the flipped bytes). + let step = craft_testkit::hostile::divisor(); + for n in (0..bytes.len()).step_by(step) { try_read(&bytes[..n]); } // A flipped byte at every position (headers, tables and chunks). - for at in 0..bytes.len() { + for at in (0..bytes.len()).step_by(step) { let mut broken = bytes.clone(); broken[at] ^= 0xFF; try_read(&broken); @@ -1413,11 +1414,11 @@ fn groups_must_be_slots_of_one_part_each_in_one_group() { #[test] fn the_estimate_covers_what_the_read_does() { // A flat colour in ZIP16 (decodes to far more than it reads), lines of a ramp, and tiles. - let (w, h) = (1024usize, 600usize); + let (w, h) = (256usize, 160usize); let list = vec![AnyChannel::new("R", FlatSamples::F32(vec![0.25; w * h])), AnyChannel::new("G", FlatSamples::F32(vec![0.5; w * h]))]; let encoding = Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; let flat = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); - let ramp = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let ramp = file(vec![layer(None, (0, 0), (256, 160), &["R", "G"], false, Compression::Uncompressed)], (256, 160)); let tiled = file(vec![layer(None, (0, 0), (300, 200), &["R", "G", "B"], true, Compression::PIZ)], (300, 200)); for bytes in [&flat, &ramp, &tiled] { let index = indexed(bytes); diff --git a/crates/font-subset/Cargo.toml b/crates/font-subset/Cargo.toml index 645b24f61e..7810620eff 100644 --- a/crates/font-subset/Cargo.toml +++ b/crates/font-subset/Cargo.toml @@ -16,6 +16,7 @@ unicode-normalization = "0.1.26" write-fonts = { version = "0.55", features = ["read"] } [dev-dependencies] +craft-testkit = { workspace = true } rustybuzz = "0.20.1" serde_json = "1" wuff = "0.2.9" diff --git a/crates/font-subset/src/woff2.rs b/crates/font-subset/src/woff2.rs index e6a3d35262..57f0d2d256 100644 --- a/crates/font-subset/src/woff2.rs +++ b/crates/font-subset/src/woff2.rs @@ -185,7 +185,9 @@ mod tests { #[test] fn round_trips_every_table_and_header_matches_spec() { - for path in FIXTURES { + // The gate runs a TrueType and a CFF font (the first and the last); nightly runs all of them. + let all = craft_testkit::hostile::divisor() == 1; + for path in FIXTURES.iter().enumerate().filter(|(i, _)| all || *i == 0 || *i == FIXTURES.len() - 1).map(|(_, p)| p) { let sfnt = fixture(path); let tables = parse_tables(&sfnt).unwrap(); for quality in [Quality::Static, Quality::OnDemand] { diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index 11f6fdac93..454068d76d 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -2227,17 +2227,17 @@ mod parallel_tests { } } - /// The bytes depend on the image, not on the machine: one, two, seven and 32 worker threads + /// The bytes depend on the image, not on the machine: one, two and 32 worker threads /// (and the machine's own count, through `encode`) give the same stream. #[test] fn the_parallel_encoder_gives_the_same_bytes_on_any_thread_count() { - let (w, h, bpp) = (1201usize, 1013usize, 4usize); + let (w, h, bpp) = (1024usize, 1025usize, 4usize); let px: Vec = (0..w * h * bpp).map(|i| ((i / 5) as u32).wrapping_mul(2_654_435_761).rotate_left(i as u32 % 11) as u8 / 5 + (i % 89) as u8).collect(); assert!(px.len() >= PARALLEL_MIN_BYTES && px.len() > 2 * BAND_BYTES); - for level in [PngCompression::Fast, PngCompression::Default, PngCompression::Best] { + for level in [PngCompression::Fast, PngCompression::Best] { let one = banded_idat(&px, w, h, bpp, level, 1).unwrap(); - for threads in [2, 7, 32] { + for threads in [2, 32] { assert!(banded_idat(&px, w, h, bpp, level, threads).unwrap() == one, "{level:?}: {threads} threads differ from one"); } assert!(parallel_idat(&px, w, h, bpp, level).unwrap() == one, "{level:?}: this machine's thread count differs from one"); @@ -2251,8 +2251,9 @@ mod parallel_tests { #[test] fn large_images_roundtrip_through_the_parallel_encoder() { - for (layout, sample, ch, bytes) in [(ChannelLayout::Rgb, SampleType::U8, 3usize, 1usize), (ChannelLayout::Rgba, SampleType::U16, 4, 2)] { - let (w, h) = (1531u32, 977u32); + for (layout, sample, ch, bytes, w, h) in + [(ChannelLayout::Rgb, SampleType::U8, 3usize, 1usize, 1024u32, 1400u32), (ChannelLayout::Rgba, SampleType::U16, 4, 2, 1024, 520)] + { let n = w as usize * h as usize * ch * bytes; let px: Vec = (0..n).map(|i| ((i / 3) as u32).wrapping_mul(2_654_435_761).rotate_left(i as u32 % 7) as u8 / 3 + (i % 97) as u8).collect(); @@ -2323,8 +2324,9 @@ mod streamed_tests { /// gives, at 8 and 16 bits, with a profile, resolution, text and XMP. #[test] fn streamed_rows_match_the_whole_image_encoder() { - for (layout, sample, ch, bytes) in [(ChannelLayout::Rgba, SampleType::U8, 4usize, 1usize), (ChannelLayout::Rgb, SampleType::U16, 3, 2)] { - let (w, h) = (1201u32, 1013u32); + for (layout, sample, ch, bytes, w, h) in + [(ChannelLayout::Rgba, SampleType::U8, 4usize, 1usize, 1024u32, 1025u32), (ChannelLayout::Rgb, SampleType::U16, 3, 2, 1024, 700)] + { let meta = Metadata { dpi: Some((300.0, 300.0)), text: vec![("Title".into(), "Tent".into())], @@ -2339,7 +2341,7 @@ mod streamed_tests { let opts = EncodeOptions { png_compression: level, ..Default::default() }; let whole = crate::encode(&img, Format::Png, &opts).unwrap(); let (head, zlib, _) = split(&whole); - for heights in [&[1u32, 77, 300][..], &[256, 256, 256], &[1013]] { + for heights in [&[1u32, 77, 300][..], &[256, 256, 256], &[h]] { let png = streamed(&img, heights, &opts); let (h2, z2, _) = split(&png); assert!(h2 == head, "{layout:?} {level:?} {heights:?}: header chunks differ"); diff --git a/crates/image-codecs/tests/it/dds_oracle.rs b/crates/image-codecs/tests/it/dds_oracle.rs index 05d000a73b..7fc53c0969 100644 --- a/crates/image-codecs/tests/it/dds_oracle.rs +++ b/crates/image-codecs/tests/it/dds_oracle.rs @@ -477,6 +477,9 @@ fn digests() -> Vec<(String, String)> { // downsampler's edge spans in only one direction. let sizes = [(517u32, 389u32), (1, 1), (2, 3), (3, 2), (5, 5), (1, 9), (9, 1), (6, 13)]; let layouts = [ChannelLayout::Rgba, ChannelLayout::Rgb, ChannelLayout::GrayA, ChannelLayout::Gray]; + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th case. + let step = craft_media_testkit::hostile::divisor(); + let mut index = 0usize; for (i, &(w, h)) in sizes.iter().enumerate() { for layout in layouts { // The large picture in every layout; the small ones in RGBA and gray. @@ -486,6 +489,10 @@ fn digests() -> Vec<(String, String)> { let img = image(w, h, layout, 0x5eed + i as u64); for compression in COMPRESSIONS { for mipmaps in [false, true] { + index += 1; + if !(index - 1).is_multiple_of(step) { + continue; + } let name = format!("{layout:?}-{w}x{h}-{}-mips{}", compression.name(), u8::from(mipmaps)); let opts = EncodeOptions { dds: DdsOptions { compression, mipmaps }, ..Default::default() }; let file = encode(&img, Format::Dds, &opts).unwrap_or_else(|e| panic!("{name}: {e}")); @@ -497,6 +504,10 @@ fn digests() -> Vec<(String, String)> { } } for (name, file) in foreign_files() { + index += 1; + if !(index - 1).is_multiple_of(step) { + continue; + } let back = decode(&file).unwrap_or_else(|e| panic!("{name}: {e}")); out.push((format!("{name}-decode"), image_digest(&back))); } @@ -508,7 +519,12 @@ fn dds_output_matches_the_pinned_digests() { let got = digests(); let pinned = |name: &str| PINNED.iter().find(|(n, _)| *n == name).map(|(_, d)| *d); let mismatched: Vec<&str> = got.iter().filter(|(name, digest)| pinned(name) != Some(digest.as_str())).map(|(n, _)| n.as_str()).collect(); - let stale: Vec<&str> = PINNED.iter().filter(|(n, _)| !got.iter().any(|(g, _)| g == n)).map(|(n, _)| *n).collect(); + // A sampled run does not compute every pinned case. + let stale: Vec<&str> = if craft_media_testkit::hostile::divisor() > 1 { + Vec::new() + } else { + PINNED.iter().filter(|(n, _)| !got.iter().any(|(g, _)| g == n)).map(|(n, _)| *n).collect() + }; if !mismatched.is_empty() || !stale.is_empty() { eprintln!("const PINNED: &[(&str, &str)] = &["); for (name, digest) in &got { diff --git a/crates/image-codecs/tests/it/fidelity.rs b/crates/image-codecs/tests/it/fidelity.rs index 98f3626983..cad19485ef 100644 --- a/crates/image-codecs/tests/it/fidelity.rs +++ b/crates/image-codecs/tests/it/fidelity.rs @@ -222,9 +222,16 @@ fn every_warning_has_a_message() { /// The warnings must agree with what actually comes back from the file. #[test] fn warnings_match_actual_roundtrip_behaviour() { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th format, layout and sample type. + let step = craft_media_testkit::hostile::divisor(); + let mut index = 0usize; for f in rw_formats() { for l in ChannelLayout::ALL { for s in SampleType::ALL { + index += 1; + if !(index - 1).is_multiple_of(step) { + continue; + } let img = test_image(l, s); let w = warns(&img, f); let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap(); diff --git a/crates/image-codecs/tests/it/limits.rs b/crates/image-codecs/tests/it/limits.rs index 49561e7a81..b9b047c615 100644 --- a/crates/image-codecs/tests/it/limits.rs +++ b/crates/image-codecs/tests/it/limits.rs @@ -665,10 +665,12 @@ fn a_dwab_exr_gets_a_looser_file_size_bound() { #[test] fn highly_compressible_jpeg_and_gif_still_decode() { - let img = Image::from_u8(3000, 3000, ChannelLayout::Rgba, vec![255u8; 3000 * 3000 * 4]).unwrap(); + let side = 2048usize; + let img = Image::from_u8(side as u32, side as u32, ChannelLayout::Rgba, vec![255u8; side * side * 4]).unwrap(); for f in [Format::Jpeg, Format::Gif, Format::Qoi, Format::OpenExr] { let b = encode(&img, f, &EncodeOptions::default()).unwrap(); - assert_eq!(decode(&b).unwrap().width(), 3000, "{f:?}"); + eprintln!("DIAG ratio {f:?}: {} bytes file, {} declared, {}:1", b.len(), side * side * 4, side * side * 4 / b.len()); + assert_eq!(decode(&b).unwrap().width() as usize, side, "{f:?}"); } } diff --git a/crates/image-codecs/tests/it/malformed.rs b/crates/image-codecs/tests/it/malformed.rs index b247bdfc6c..7ccb7819b4 100644 --- a/crates/image-codecs/tests/it/malformed.rs +++ b/crates/image-codecs/tests/it/malformed.rs @@ -6,7 +6,7 @@ use craft_image_codecs::*; use proptest::prelude::*; fn tight() -> DecodeOptions { - DecodeOptions { limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 64 << 20 }, ..Default::default() } + DecodeOptions { limits: Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 21, max_alloc: 16 << 20 }, ..Default::default() } } fn samples() -> Vec<(Format, Vec)> { diff --git a/crates/image-codecs/tests/it/tiff_bands.rs b/crates/image-codecs/tests/it/tiff_bands.rs index fe61178dd2..88376e2c35 100644 --- a/crates/image-codecs/tests/it/tiff_bands.rs +++ b/crates/image-codecs/tests/it/tiff_bands.rs @@ -338,22 +338,23 @@ fn blank_g4(h: u32) -> Vec { #[test] fn a_blank_fax_page_wider_than_4096_px_passes_the_bomb_guard() { - // A blank 600 dpi page (A4 landscape, A3) codes each row in one bit, past 4096:1: it must - // open, with or without the metadata and other pages that used to raise the bound. - for (w, h) in [(7016u32, 4961u32), (7016, 9921)] { + // A blank page codes each row in one bit, so a row wider than 4096 pixels is past 4096:1: it + // must open, with or without the metadata and other pages that used to raise the bound. The + // page has enough rows to hold more than the guard's fixed 1 MiB of slack. + for (w, h) in [(20_000u32, 800u32)] { let mut d = Dir { entries: base(w, h, 1, 1, 0), chunks: vec![blank_g4(h)], tiled: false }.tag(278, LONG, &[u64::from(h)]); d.entries.retain(|e| e.0 != 259); let d = d.tag(259, SHORT, &[4]); - let pages: Vec = (0..3).map(|_| d.clone()).collect(); + let pages: Vec = (0..2).map(|_| d.clone()).collect(); for (what, bytes) in - [("one page", build(true, false, std::slice::from_ref(&d), &[0]).bytes), ("three pages", build(true, false, &pages, &[0, 1, 2]).bytes)] + [("one page", build(true, false, std::slice::from_ref(&d), &[0]).bytes), ("two pages", build(true, false, &pages, &[0, 1]).bytes)] { let img = decode(&bytes).unwrap_or_else(|e| panic!("{w}x{h} {what}: {e}")); assert_eq!(img.dimensions(), (w, h), "{what}"); assert!(img.data().iter().all(|&v| v == 255), "{w}x{h} {what}: not white"); } } - let mut d = Dir { entries: base(7016, 4961, 1, 1, 0), chunks: vec![blank_g4(4961)], tiled: false }.tag(278, LONG, &[4961]); + let mut d = Dir { entries: base(20_000, 800, 1, 1, 0), chunks: vec![blank_g4(800)], tiled: false }.tag(278, LONG, &[800]); d.entries.retain(|e| e.0 != 259); let bytes = build(true, false, &[d.tag(259, SHORT, &[4])], &[0]).bytes; assert!(banded(&bytes, None, &Limits::banded(), true).unwrap().data() == decode(&bytes).unwrap().data()); diff --git a/crates/image-codecs/tests/it/tiff_pages.rs b/crates/image-codecs/tests/it/tiff_pages.rs index 7f6708f88f..a015231916 100644 --- a/crates/image-codecs/tests/it/tiff_pages.rs +++ b/crates/image-codecs/tests/it/tiff_pages.rs @@ -806,6 +806,14 @@ fn zoo() -> Vec> { } fn poke(bytes: &[u8]) { + let started = std::time::Instant::now(); + poke_all(bytes); + if started.elapsed() > std::time::Duration::from_millis(100) { + eprintln!("DIAG tiff poke slow: {} bytes, {:?}", bytes.len(), started.elapsed()); + } +} + +fn poke_all(bytes: &[u8]) { let _ = decode(bytes); let _ = decode_with(bytes, &DecodeOptions { limits: Limits { max_alloc: 16 << 20, ..Limits::default() }, ..Default::default() }); let _ = exif_orientation(bytes); diff --git a/crates/latex/Cargo.toml b/crates/latex/Cargo.toml index 4367c0b02a..bc0bc9e26d 100644 --- a/crates/latex/Cargo.toml +++ b/crates/latex/Cargo.toml @@ -18,6 +18,7 @@ craft-mime = { workspace = true, features = ["detect"] } craft-wordmodel = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } craft-markdown = { workspace = true } proptest = { workspace = true } diff --git a/crates/latex/tests/hostile.rs b/crates/latex/tests/hostile.rs index d8bf8df702..40755bc285 100644 --- a/crates/latex/tests/hostile.rs +++ b/crates/latex/tests/hostile.rs @@ -54,9 +54,9 @@ fn latex_export_carries_no_commands_from_the_document() { assert!(!out.contains("\\input") && !out.contains("^^"), "{out}"); } -/// The fastest of three reads of `src`. +/// The fastest of two reads of `src`. fn fastest(src: &str) -> Duration { - (0..3) + (0..2) .map(|_| { let started = Instant::now(); assert!(import(src.as_bytes()).body.len() <= 2); @@ -71,8 +71,10 @@ fn fastest(src: &str) -> Duration { #[test] fn latex_labels_in_a_row_are_read_in_linear_time() { let cases: [fn(usize) -> String; 3] = [|n| "\\label{a} ".repeat(n) + "x", |n| "\\label{a}".repeat(n) + "x", |n| "\\hypertarget{a}{} ".repeat(n)]; + // The gate reads half the labels; nightly the full counts. + let size = |n: usize| n / craft_testkit::hostile::divisor().min(2); for make in cases { - let (small, large) = (fastest(&make(25_000)), fastest(&make(100_000))); + let (small, large) = (fastest(&make(size(25_000))), fastest(&make(size(100_000)))); assert!(large < small * 8 + Duration::from_millis(50), "{small:?} for 25,000, {large:?} for 100,000"); } let d = import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()); @@ -98,7 +100,8 @@ fn latex_optional_arguments_in_a_row_are_read_in_linear_time() { ]; for make in cases { assert_eq!(text(&make(3)), "x"); - let (small, large) = (fastest(&make(50_000)), fastest(&make(200_000))); + let size = |n: usize| n / craft_testkit::hostile::divisor().min(2); + let (small, large) = (fastest(&make(size(50_000))), fastest(&make(size(200_000)))); assert!(large < small * 8 + Duration::from_millis(50), "{small:?} for 50,000, {large:?} for 200,000"); } } diff --git a/crates/media/src/mpegts/tests/hostile.rs b/crates/media/src/mpegts/tests/hostile.rs index 97bba47d0a..a0503fc0c1 100644 --- a/crates/media/src/mpegts/tests/hostile.rs +++ b/crates/media/src/mpegts/tests/hostile.rs @@ -58,8 +58,8 @@ fn ps_seed() -> Vec { #[test] fn hostile_input_never_panics() { let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed()]; - seeds.push(work_tests::big_program_stream(false, 40).0); - seeds.push(work_tests::big_program_stream(true, 40).0); + seeds.push(work_tests::big_program_stream(false, 8).0); + seeds.push(work_tests::big_program_stream(true, 8).0); // fewer rounds than FilmCraft's 40 000: tests here build without optimisation, and the two // large program streams cost a megabyte of window refill per unit read for (i, s) in seeds.iter().enumerate() { diff --git a/crates/media/src/mxf/tests/hostile.rs b/crates/media/src/mxf/tests/hostile.rs index 6ff89ed152..ce02bc976d 100644 --- a/crates/media/src/mxf/tests/hostile.rs +++ b/crates/media/src/mxf/tests/hostile.rs @@ -5,6 +5,14 @@ use crate::mxf::klv::ber_length; use crate::mxf::meta::{Primer, Set}; fn exercise(d: &[u8]) { + let started = std::time::Instant::now(); + exercise_open(d); + if started.elapsed() > std::time::Duration::from_millis(50) { + eprintln!("DIAG mxf slow case: {} bytes, {:?}", d.len(), started.elapsed()); + } +} + +fn exercise_open(d: &[u8]) { let Ok(m) = open(d) else { return }; let _ = m.operational_pattern.name(); for p in &m.partitions { @@ -17,7 +25,7 @@ fn exercise(d: &[u8]) { let _ = t.sync_before(i); } for s in [0u64, 100, 48_000, u64::MAX] { - for f in [0usize, 1, 1920, 1 << 20] { + for f in [0usize, 1, 1920] { let _ = m.read_pcm(d, ti, s, f); } } @@ -53,29 +61,33 @@ fn sync_before_on_an_empty_track() { // Keep each deterministic hammer independent so test runners can schedule the seeds separately. // The labels, mutation counts, every-truncation coverage and per-case watchdog stay unchanged. -fn hostile_seeds() -> [Vec; 3] { +fn hostile_seed(which: usize) -> Vec { let (to, flags) = ipbb(); - [build(7, |i| vec![i as u8; 100 + i], &to, &flags), build(5, prores_like, &to, &flags), build(4, prores_like, &[], &flags)] + match which { + 0 => build(7, |i| vec![i as u8; 100 + i], &to, &flags), + 1 => build(5, prores_like, &to, &flags), + _ => build(4, prores_like, &[], &flags), + } } #[test] fn hostile_input_seed_0_never_panics() { - craft_media_testkit::hostile::hammer("mxf seed 0", &hostile_seeds()[0], 6_000, exercise); + craft_media_testkit::hostile::hammer("mxf seed 0", &hostile_seed(0), 6_000, exercise); } #[test] fn hostile_input_seed_1_never_panics() { - craft_media_testkit::hostile::hammer("mxf seed 1", &hostile_seeds()[1], 6_000, exercise); + craft_media_testkit::hostile::hammer("mxf seed 1", &hostile_seed(1), 6_000, exercise); } #[test] fn hostile_input_seed_2_never_panics() { - craft_media_testkit::hostile::hammer("mxf seed 2", &hostile_seeds()[2], 6_000, exercise); + craft_media_testkit::hostile::hammer("mxf seed 2", &hostile_seed(2), 6_000, exercise); } #[test] fn hostile_index_segment_never_panics() { - let seed = &hostile_seeds()[0]; + let seed = &hostile_seed(0); let index_key = [0x06, 0x0E, 0x2B, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x10, 0x01, 0x00]; if let Some(v) = value_of(seed, &index_key) { craft_media_testkit::hostile::hammer("mxf index segment", v, 30_000, |d| { @@ -86,7 +98,7 @@ fn hostile_index_segment_never_panics() { #[test] fn hostile_primer_never_panics() { - let seed = &hostile_seeds()[0]; + let seed = &hostile_seed(0); let primer_key = [0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x05, 0x01, 0x00]; if let Some(v) = value_of(seed, &primer_key) { craft_media_testkit::hostile::hammer("mxf primer", v, 5_000, |d| { @@ -97,7 +109,7 @@ fn hostile_primer_never_panics() { #[test] fn hostile_set_never_panics() { - let seed = &hostile_seeds()[0]; + let seed = &hostile_seed(0); let set = seed.windows(16).position(|w| w == set_key(0x18)).and_then(|at| value_of(&seed[at..], &set_key(0x18))); if let Some(v) = set { craft_media_testkit::hostile::hammer("mxf set", v, 20_000, |d| { diff --git a/crates/menu/tests/it/ribbon.rs b/crates/menu/tests/it/ribbon.rs index 9876db5382..07b057f4bf 100644 --- a/crates/menu/tests/it/ribbon.rs +++ b/crates/menu/tests/it/ribbon.rs @@ -214,7 +214,8 @@ fn slide(direction: Direction, motion: MotionMode, from: usize, to: usize) -> (f assert_eq!(shown.get(), to, "the click on the tab showed it"); let title = ["Alpha", "Beta", "Gamma"][to]; let first = group_x(&controls, title); - fixture.idle(120); + // The slide is a tween on the frame clock: two seconds of clock bring it to rest in the frames a settle runs. + fixture.advance(2.0).settle(); let rest = group_x(&controls, title); (first, rest) } diff --git a/crates/mesh/Cargo.toml b/crates/mesh/Cargo.toml index 6ba794aae6..17519cb07e 100644 --- a/crates/mesh/Cargo.toml +++ b/crates/mesh/Cargo.toml @@ -29,3 +29,6 @@ craft-zip = { workspace = true, optional = true } # 3MF is an OPC package of XML parts. craft-opc = { workspace = true, optional = true } craft-xml = { workspace = true, optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/mesh/src/tests.rs b/crates/mesh/src/tests.rs index f2eac7e9fe..31b84d2eff 100644 --- a/crates/mesh/src/tests.rs +++ b/crates/mesh/src/tests.rs @@ -21,17 +21,19 @@ mod threemf; mod triangulate; /// Every truncation of `good` and two mutations of every byte go through `read`: it may refuse -/// them, it must not panic, and what it accepts must be a valid scene. +/// them, it must not panic, and what it accepts must be a valid scene. The gate runs every +/// divisor-th truncation and byte (`CRAFT_HOSTILE_DIVISOR`); nightly runs every one. pub(crate) fn hammer(good: &[u8], read: &dyn Fn(&[u8]) -> Result) { let check = |bytes: &[u8]| { if let Ok(scene) = read(bytes) { scene.validate().unwrap(); } }; - for len in 0..good.len() { + let step = craft_testkit::hostile::divisor(); + for len in (0..good.len()).step_by(step) { check(&good[..len]); } - for i in 0..good.len() { + for i in (0..good.len()).step_by(step) { let mut b = good.to_vec(); b[i] ^= 0xA5; check(&b); diff --git a/crates/ods/tests/read.rs b/crates/ods/tests/read.rs index 530177b4c9..9c44e09ec7 100644 --- a/crates/ods/tests/read.rs +++ b/crates/ods/tests/read.rs @@ -206,23 +206,25 @@ fn expansion_bounds_stop_small_repeat_bombs() { r#""#, ); assert!(matches!(open(&cells), Err(Error::TooLarge(_)))); + // Text limits are set small so the files stay small: 1 MiB of text over all sheets, 64 KiB a cell. + let tight = Options { max_text: 1 << 20, max_cell_text: 64 << 10, ..Options::default() }; let text = format!( - r#""#, + r#""#, "x".repeat(1024) ); - assert!(matches!(open(&ods(&text)), Err(Error::TooLarge(_)))); - // One row of cells each just under the 1 MiB cell limit, past 64 MiB in all: refused while + assert!(matches!(read(&ods(&text), &tight), Err(Error::TooLarge(_)))); + // One row of cells each just under the cell limit, past the text limit in all: refused while // the row is read. The row's end is never reached. - let long = format!(r#""#, "x".repeat(1024 * 1024 - 1)); - let cells = package(content(&format!(r#"{}"#, long.repeat(65))).as_bytes()).unwrap(); - assert!(matches!(open(&cells), Err(Error::TooLarge(_)))); + let long = format!(r#""#, "x".repeat(64 * 1024 - 1)); + let cells = package(content(&format!(r#"{}"#, long.repeat(17))).as_bytes()).unwrap(); + assert!(matches!(read(&cells, &tight), Err(Error::TooLarge(_)))); // A row repeated once more than its cells' text allows is refused, and one that fits reads. let cell = format!(r#""#, "y".repeat(1024)); let rows = |n: u32| { ods(&format!(r#"{cell}"#)) }; - assert!(open(&rows(65_536)).is_ok()); - assert!(matches!(open(&rows(65_537)), Err(Error::TooLarge(_)))); + assert!(read(&rows(1024), &tight).is_ok()); + assert!(matches!(read(&rows(1025), &tight), Err(Error::TooLarge(_)))); // An attribute over the cell text limit. let small = Options { max_cell_text: 10, ..Options::default() }; assert!(matches!( diff --git a/crates/openpgp/Cargo.toml b/crates/openpgp/Cargo.toml index 5630c38295..0bb9cbd16a 100644 --- a/crates/openpgp/Cargo.toml +++ b/crates/openpgp/Cargo.toml @@ -24,6 +24,7 @@ sha3 = { version = "0.10", default-features = false } pgp = { version = "=0.21.0", default-features = false, features = ["wasm"] } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } # Keys and signatures made in the tests, from a seed: the random numbers rPGP 0.21 takes. rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] } diff --git a/crates/openpgp/src/keys_tests.rs b/crates/openpgp/src/keys_tests.rs index 3cc53b0bcd..05db88fbef 100644 --- a/crates/openpgp/src/keys_tests.rs +++ b/crates/openpgp/src/keys_tests.rs @@ -253,6 +253,11 @@ fn a_copy_with_junk_subkey_bindings_from_the_future_never_pushes_out_the_real_on #[test] fn a_copy_that_costs_more_checks_than_a_key_may_is_refused_not_cut_short() { + // Forging and checking more signatures than the cap: nightly only. The revocation test below + // proves the same refusal with a smaller cap at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } let alice = secret(ALICE, Make { subkey: true, ..Make::default() }); let mallory = secret("Mallory ", Make { seed: 6, ..Make::default() }); let mut copy = SignedPublicKey::from(alice.clone()); diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index e0aa1babf9..fb02cdc9c4 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -512,7 +512,7 @@ fn a_page_gap_change_keeps_the_scroll_offset() { #[trial] fn the_pictures_a_view_holds_stay_bounded_as_it_scrolls_through_many_pages() { let budget = TextureStoreOptions::pages().budget.max_entries; - let count = 4 * budget; + let count = 2 * budget; let state = Rc::new(RefCell::new(state_with(|s| { s.continuous = true; s.fit = Fit::None; diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index bb82c8497c..e4d3f57c65 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -83,6 +83,7 @@ ttf-parser = "=0.25.1" [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] proptest = { workspace = true } +craft-testkit = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen-test = "0.3" diff --git a/crates/pdf/src/cos/object.rs b/crates/pdf/src/cos/object.rs index 05b64eee27..3a82f82299 100644 --- a/crates/pdf/src/cos/object.rs +++ b/crates/pdf/src/cos/object.rs @@ -810,8 +810,56 @@ mod tests { #[test] fn decoded_stops_at_renderer_cap_of_256_mib() { - let data = vec![0u8; (256 << 20) + 1]; - let stream = Stream::flate(Dict::new(), &data); + // A zlib stream of `len` zero bytes written directly (one literal, then matches of 258 + // bytes at distance 1 in a fixed-Huffman block): compressing 256 MiB would cost far more + // than decoding up to the cap. + fn zero_stream(len: usize) -> Stream { + struct Bits { + out: Vec, + acc: u64, + count: u32, + } + impl Bits { + fn put(&mut self, value: u64, count: u32) { + self.acc |= value << self.count; + self.count += count; + while self.count >= 8 { + self.out.push(self.acc as u8); + self.acc >>= 8; + self.count -= 8; + } + } + /// A Huffman code, packed most significant bit first. + fn code(&mut self, value: u64, count: u32) { + self.put(value.reverse_bits() >> (64 - count), count); + } + } + let mut w = Bits { out: vec![0x78, 0x9c], acc: 0, count: 0 }; + w.put(1, 1); + w.put(1, 2); + w.code(0x30, 8); + let mut left = len - 1; + while left >= 258 { + w.code(0xC5, 8); + w.put(0, 5); + left -= 258; + } + for _ in 0..left { + w.code(0x30, 8); + } + w.put(0, 7); + if w.count > 0 { + w.out.push(w.acc as u8); + } + let mut out = w.out; + out.extend_from_slice(&(((len % 65521) as u32) << 16 | 1).to_be_bytes()); + let mut dict = Dict::new(); + dict.set(b"Filter".to_vec(), Object::Name(b"FlateDecode".to_vec())); + Stream::from_raw(dict, out) + } + let small = zero_stream(1000); + assert_eq!(&small.decoded().unwrap()[..], &[0u8; 1000][..], "the hand-written stream is a valid one"); + let stream = zero_stream((256 << 20) + 1); assert!(matches!(stream.decoded(), Err(CosError::Filter(_)))); } diff --git a/crates/pdf/src/cos/parser.rs b/crates/pdf/src/cos/parser.rs index 5a0585ba30..2e19d0c7ba 100644 --- a/crates/pdf/src/cos/parser.rs +++ b/crates/pdf/src/cos/parser.rs @@ -977,7 +977,16 @@ mod tests { let at_cap = Lexer::new(wide(MAX_NODES - 1).as_bytes(), 0).object(); assert!(matches!(at_cap, Ok(Object::Array(ref items)) if items.len() == MAX_NODES - 1)); assert!(Lexer::new(wide(MAX_NODES).as_bytes(), 0).object().is_err()); - // The same inside a dictionary value and behind tolerated junk. + // The gate stops at the plain array (each case parses millions of operands); nightly adds the same budget inside a + // dictionary value, behind tolerated junk, and per top-level object. + // wasm32 has no divisor and always runs the gate's part. + #[cfg(not(target_arch = "wasm32"))] + let full = craft_testkit::hostile::divisor() == 1; + #[cfg(target_arch = "wasm32")] + let full = false; + if !full { + return; + } assert!(Lexer::new(format!("<< /A {} >>", wide(MAX_NODES)).as_bytes(), 0).object().is_err()); assert!(Lexer::new(format!("[[{}] ]", "0 ".repeat(MAX_NODES)).as_bytes(), 0).object().is_err()); // The budget is per top-level object: a lexer reused for many operands keeps working. diff --git a/crates/pdf/tests/contracts.rs b/crates/pdf/tests/contracts.rs index 444f33d22c..3d169a3c58 100644 --- a/crates/pdf/tests/contracts.rs +++ b/crates/pdf/tests/contracts.rs @@ -137,7 +137,7 @@ fn max_coverage_omits_excess_strokes_and_fast_rects() { let red = |px: &[u8]| px.as_chunks::<4>().0.iter().filter(|p| p[0] > 200 && p[2] < 50).count(); for (leaf, marker) in cases { - let bytes = doubling_forms_pdf(10, leaf, marker); + let bytes = doubling_forms_pdf(8, leaf, marker); let (whole, whole_warnings) = render_with_coverage_budget(bytes.clone(), None); assert!(!whole.diagnostics.content_truncated); assert_eq!(whole_warnings, 0); diff --git a/crates/pdf/tests/cos/encryption.rs b/crates/pdf/tests/cos/encryption.rs index 2f971214a6..626d2d7729 100644 --- a/crates/pdf/tests/cos/encryption.rs +++ b/crates/pdf/tests/cos/encryption.rs @@ -689,7 +689,7 @@ fn an_identity_crypt_filter_selected_by_reference_leaves_a_stream_alone() { fn protecting_drops_a_crypt_filter_selected_by_reference() { let protected = |doc: &mut Document| { doc.set_encryption(&NewEncryption { - algorithm: Algorithm::Aes256, + algorithm: Algorithm::Aes128, user_password: "", owner_password: "owner", permissions: -1, diff --git a/crates/pdf/tests/crypt/proptests.rs b/crates/pdf/tests/crypt/proptests.rs index 7b9ede4d3d..80277ae605 100644 --- a/crates/pdf/tests/crypt/proptests.rs +++ b/crates/pdf/tests/crypt/proptests.rs @@ -100,6 +100,32 @@ fn make(algorithm: Algorithm, user: &str, owner: &str) -> SecurityHandler { .unwrap() } +/// The handler for `user` / `owner` per algorithm, derived once: AES-256's key derivation is +/// slow and these properties draw the same file for every case. +fn standard(algorithm: Algorithm) -> &'static SecurityHandler { + use std::sync::OnceLock; + static CACHE: [OnceLock; 4] = [OnceLock::new(), OnceLock::new(), OnceLock::new(), OnceLock::new()]; + let slot = match algorithm { + Algorithm::Rc4_40 => 0, + Algorithm::Rc4_128 => 1, + Algorithm::Aes128 => 2, + Algorithm::Aes256 => 3, + }; + CACHE[slot].get_or_init(|| make(algorithm, "user", "owner")) +} + +/// A file with no user password and the owner password `owner`, AES-256, derived once. +fn open_aes256() -> &'static SecurityHandler { + static HANDLER: std::sync::OnceLock = std::sync::OnceLock::new(); + HANDLER.get_or_init(|| make(Algorithm::Aes256, "", "owner")) +} + +/// Cases for the expensive properties (each draws fresh AES-256 files): the gate's fraction of +/// `full` (the hostile-input divisor), at least `floor`; nightly runs `full`. +fn cases(full: u32, floor: u32) -> ProptestConfig { + ProptestConfig::with_cases((full / craft_testkit::hostile::divisor() as u32).max(floor)) +} + proptest! { /// Encrypting then decrypting returns the input at every length, as a string and as each kind /// of stream — and is byte-for-byte reproducible, because re-running a save must not silently @@ -107,7 +133,7 @@ proptest! { /// need an all-zero keystream to leave them alone, and CBC cannot shrink a padded block. #[test] fn content_survives_the_trip_at_every_length(alg in algorithms(), data in payloads()) { - let h = make(alg, "user", "owner"); + let h = standard(alg); // The key width each algorithm promises: 5 bytes for export-grade 40-bit RC4, 16 for // AES-128 and RC4-128, 32 for AES-256. `key_len` is the only place that decides this and @@ -116,7 +142,7 @@ proptest! { let want_len = match alg { Algorithm::Rc4_40 => 5, Algorithm::Aes128 | Algorithm::Rc4_128 => 16, Algorithm::Aes256 => 32 }; prop_assert_eq!(h.file_key().len(), want_len, "{:?} must use a {} byte file key", alg, want_len); - let h = make(alg, "user", "owner"); + let h = standard(alg); for num in [0u32, 1, 4096, u32::MAX] { let generation = (num % 65_535) as u16; @@ -143,7 +169,7 @@ proptest! { /// whatever the bytes are. An input shorter than the IV has nothing left to decode. #[test] fn damaged_ciphertext_never_panics(alg in algorithms(), enc in prop::collection::vec(any::(), 0..64)) { - let h = make(alg, "user", "owner"); + let h = standard(alg); for cut in 0..=enc.len() { let broken = &enc[..cut]; let out = h.decrypt_string(7, 3, broken); @@ -180,7 +206,7 @@ proptest! { name in prop::sample::select(vec!["Identity", "StdCF", "Nope"]), bogus_identity_in_cf in any::(), ) { - let mut d = make(Algorithm::Aes256, "", "owner").dict().clone(); + let mut d = open_aes256().dict().clone(); d.str_f = name.as_bytes().to_vec(); d.stm_f = b"Identity".to_vec(); d.ef_f = b"StdCF".to_vec(); @@ -223,7 +249,7 @@ proptest! { /// differs would prove less, because our initial vector already covers `/Num`. #[test] fn object_keys_are_scoped_to_their_object(alg in prop::sample::select(vec![Algorithm::Rc4_40, Algorithm::Rc4_128, Algorithm::Aes128]), data in prop::collection::vec(any::(), 8..40)) { - let h = make(alg, "user", "owner"); + let h = standard(alg); let enc = h.encrypt_string(100, 0, &data); prop_assert_eq!(h.decrypt_string(100, 0, &enc), &data[..], "{:?} reads its own object back", alg); @@ -240,7 +266,7 @@ proptest! { prop_assert_ne!(&h.decrypt_string(1 << 23, 0, &low)[..], &data[..], "{:?}: the third byte of /Num must still reach the key", alg); prop_assert_eq!(&h.decrypt_string(1 << 24, 0, &low)[..], &data[..], "{:?}: /Num is folded three bytes wide, so a difference above bit 23 shares the key by design", alg); - let r6 = make(Algorithm::Aes256, "user", "owner"); + let r6 = standard(Algorithm::Aes256); let enc6 = r6.encrypt_string(100, 0, &data); prop_assert_eq!(&r6.decrypt_string(101, 3, &enc6)[..], &data[..], "AES-256 uses the file key for every object (§7.6.3.3)"); // ...which is exactly why the initial vector has to vary: revisions 5 and 6 reuse one key @@ -251,6 +277,10 @@ proptest! { prop_assert_ne!(&r6.encrypt_string(100, 1, &data)[..], &enc6[..], "AES-256 reused the same initial vector across generations"); } +} + +proptest! { + #![proptest_config(cases(256, 12))] /// A file created for `user` and `owner` opens for exactly the passwords whose effective bytes /// equal one of theirs, and reports the role that match earned — owner first, since viewers try /// `/O` before `/U`. Everything else is `WrongPassword`: never an opening, and no panic on odd @@ -308,6 +338,7 @@ proptest! { suspects.push(collision_partner.clone()); suspects.dedup(); + let user_session = SecurityHandler::open(d.clone(), ID, Some(&user)).ok(); for suspect in &suspects { let want = expected_auth(alg, &user_bytes, &owner_bytes, suspect); match (want, SecurityHandler::open(d.clone(), ID, Some(suspect))) { @@ -324,7 +355,7 @@ proptest! { // The owner password upgrades a user session; nothing else does. When the two share // bytes, `create` gave /O the user's own bytes (revisions 2–4) or left it empty // (AES-256, pdfcraft #1185's sharp edge), so the open password *is* an owner password here. - if let Ok(session) = SecurityHandler::open(d.clone(), ID, Some(&user)) { + if let Some(session) = &user_session { let is_owner_password = expected_auth(alg, &user_bytes, &owner_bytes, suspect) == Some(Auth::Owner); let upgrade = session.authenticate_owner(ID, suspect).map(|u| u.auth()); if is_owner_password { @@ -347,6 +378,9 @@ proptest! { } } +} + +proptest! { /// The AES-CBC and RC4 primitives taken directly: a damaged file's `/Length` and crypt filters /// hand them keys and data of shapes `create` would never build, so they must invert each other /// for any key length (`Cipher::new` takes AES-256 at 32 bytes and zero-padded AES-128 below @@ -377,6 +411,10 @@ proptest! { prop_assert_eq!(rc4(&[], &data), &data[..], "an empty RC4 key passes bytes through"); } +} + +proptest! { + #![proptest_config(cases(256, 12))] /// `/Perms` certifies the permission bits and `/EncryptMetadata`: decrypted with the file key it /// must hold `/P` little-endian, four set bytes, 'T' or 'F', and the `adb` sentinel (Algorithm 10). /// Nothing else in this crate reads it — `cos` writes it out and no code takes it back apart — so @@ -410,22 +448,15 @@ proptest! { prop_assert_eq!(as_user.permissions().copy(), normalised & 0b1_0000 != 0, "/P bit 5 decides copying"); prop_assert!(!as_user.permissions().owner, "the user password must not report owner rights"); - // Bytes 13-16 of /Perms are the non-repeating filler. Nothing reads them, so pinning that - // they move with the seed is the only way to notice a producer that freezes them at zero. - let other = create( - &NewEncryption { algorithm: Algorithm::Aes256, user_password: "user", owner_password: "owner", permissions, encrypt_metadata, seed: [0x11; 32] }, - ID, - ) - .unwrap(); - let open_other = aes_cbc_decrypt(other.file_key(), &[0u8; 16], &other.dict().perms, false); - prop_assert_ne!(&open[12..16], &open_other[12..16], "the four filler bytes of /Perms must follow the seed, not sit constant"); - // Revisions below 5 carry no /Perms; pinned so the boundary of what we emit is explicit. for older in [Algorithm::Rc4_40, Algorithm::Rc4_128, Algorithm::Aes128] { - let legacy = make(older, "user", "owner"); + let legacy = standard(older); prop_assert!(legacy.dict().perms.is_empty(), "{:?} must emit no /Perms", older); } } +} + +proptest! { /// Revisions 4 mix four set bytes into every file key when `/EncryptMetadata` is false (Algorithm /// 2, step f), so the same password over the same `/ID` must produce a *different* key than when /// metadata is encrypted. Every other test in this crate builds `encrypt_metadata: true` only, @@ -466,3 +497,25 @@ proptest! { } } + +/// Bytes 13-16 of `/Perms` are the non-repeating filler. Nothing reads them, so pinning that +/// they move with the seed is the only way to notice a producer that freezes them at zero. +#[test] +fn perms_filler_follows_the_seed() { + let perms = |seed: u8| { + let h = create( + &NewEncryption { + algorithm: Algorithm::Aes256, + user_password: "user", + owner_password: "owner", + permissions: -1, + encrypt_metadata: true, + seed: [seed; 32], + }, + ID, + ) + .unwrap(); + aes_cbc_decrypt(h.file_key(), &[0u8; 16], &h.dict().perms, false) + }; + assert_ne!(&perms(0x5e)[12..16], &perms(0x11)[12..16], "the four filler bytes of /Perms must follow the seed, not sit constant"); +} diff --git a/crates/pkcs7/tests/it/crypto.rs b/crates/pkcs7/tests/it/crypto.rs index d92612a5ef..e32a4f5b08 100644 --- a/crates/pkcs7/tests/it/crypto.rs +++ b/crates/pkcs7/tests/it/crypto.rs @@ -162,11 +162,16 @@ fn signatures_round_trip_for_every_key_type() { } } +/// New digital ids are self-signed, survive a `.p12` round trip, and are written with the stronger +/// round count for the key and the MAC. Key derivation takes the time here, so one file per key +/// type is written and opened once: the wrong password only for the P-256 file (it stops at the +/// MAC, which is the same code for both), and the round count read off the P-256 file. #[test] fn new_digital_ids_are_self_signed_and_survive_a_p12_round_trip() { let name = Name::build("Grace Hopper", "Compilers", "Navy", "grace@example.com", "us"); let now = Time { year: 2026, month: 10, day: 2, hour: 12, minute: 0, second: 0 }; for key in [craft_pkcs7::PrivateKey::generate_rsa(2048).unwrap(), craft_pkcs7::PrivateKey::generate_p256().unwrap()] { + let is_p256 = matches!(key.public_key(), PublicKey::P256(_)); let cert = Certificate::self_signed(&name, &key, now, 5, &[0x42, 0x01]).unwrap(); assert!(cert.is_self_signed()); assert_eq!(cert.subject.display(), "C=US, O=Navy, OU=Compilers, CN=Grace Hopper, E=grace@example.com"); @@ -177,7 +182,18 @@ fn new_digital_ids_are_self_signed_and_survive_a_p12_round_trip() { let back = pkcs12::open(&p12, "s3cret").unwrap(); assert_eq!(back.certificate, id.certificate); assert_eq!(back.friendly_name.as_deref(), Some("Grace Hopper")); - assert!(matches!(pkcs12::open(&p12, "wrong"), Err(Error::WrongPassword))); + if is_p256 { + assert!(matches!(pkcs12::open(&p12, "wrong"), Err(Error::WrongPassword))); + // OWASP's figure for PBKDF2-HMAC-SHA-256, spelled out so lowering the constant fails here. + const ROUNDS: u64 = 600_000; + // MacData's iteration count, the last field of the file. + let pfx = Tlv::parse_all(&p12).unwrap().children().unwrap(); + let mac = pfx[2].children().unwrap(); + assert_eq!(mac[2].u64().unwrap(), ROUNDS); + // The same INTEGER three times: the MAC and the PBKDF2 parameters of both encrypted parts. + let rounds = craft_pkcs7::der::int(ROUNDS); + assert_eq!(p12.windows(rounds.len()).filter(|w| *w == rounds.as_slice()).count(), 3); + } let d = DigestAlg::Sha256.digest(&[b"x"]); let sig = cms::sign_detached(&back.key, &back.certificate, &[], DigestAlg::Sha256, &d).unwrap(); let sd = cms::SignedData::parse(&sig).unwrap(); @@ -185,26 +201,6 @@ fn new_digital_ids_are_self_signed_and_survive_a_p12_round_trip() { } } -#[test] -fn new_digital_ids_use_the_stronger_round_count_for_the_key_and_the_mac() { - let name = Name::build("Grace Hopper", "", "", "", ""); - let now = Time { year: 2026, month: 10, day: 14, hour: 12, minute: 0, second: 0 }; - let key = craft_pkcs7::PrivateKey::generate_p256().unwrap(); - let certificate = Certificate::self_signed(&name, &key, now, 5, &[0x42]).unwrap(); - let id = pkcs12::DigitalId { key, certificate, chain: Vec::new(), friendly_name: None }; - let p12 = pkcs12::write(&id, "s3cret12").unwrap(); - // OWASP's figure for PBKDF2-HMAC-SHA-256, spelled out so lowering the constant fails here. - const ROUNDS: u64 = 600_000; - // MacData's iteration count, the last field of the file. - let pfx = Tlv::parse_all(&p12).unwrap().children().unwrap(); - let mac = pfx[2].children().unwrap(); - assert_eq!(mac[2].u64().unwrap(), ROUNDS); - // The same INTEGER three times: the MAC and the PBKDF2 parameters of both encrypted parts. - let rounds = craft_pkcs7::der::int(ROUNDS); - assert_eq!(p12.windows(rounds.len()).filter(|w| *w == rounds.as_slice()).count(), 3); - assert_eq!(pkcs12::open(&p12, "s3cret12").unwrap().certificate, id.certificate); -} - /// A `.p12` whose MAC asks for `rounds` iterations. Its content is empty: opening it must stop /// at the MAC, before the content is read. fn p12_with_mac_rounds(rounds: u64) -> Vec { diff --git a/crates/prepress/Cargo.toml b/crates/prepress/Cargo.toml index 1ef0384366..8fd6c92f2d 100644 --- a/crates/prepress/Cargo.toml +++ b/crates/prepress/Cargo.toml @@ -20,6 +20,7 @@ linesweeper = { version = "0.5", optional = true } ttf-parser = { version = "=0.25.1", optional = true } [dev-dependencies] +craft-testkit = { workspace = true } craft-plate-test = { workspace = true } ttf-parser = "=0.25.1" diff --git a/crates/prepress/src/plates.rs b/crates/prepress/src/plates.rs index 8344e78b0f..0a5d1ed8f5 100644 --- a/crates/prepress/src/plates.rs +++ b/crates/prepress/src/plates.rs @@ -532,7 +532,8 @@ endstream endobj fn bands_reach_resolutions_past_the_plate_cap_and_can_stop() { let pdf = disc_and_spot(); // 40 pt at 3700 dpi is 2055 pixels a side: 4.2 MP, past `MAX_PLATE_PIXELS`. - assert!(plates(&pdf, 0, 3700.0, &Options::default()).unwrap().dpi < 3700.0); + // (The whole-page entry point reduces by `plate_scale`; the bands below are not reduced.) + assert!(plate_scale(40.0, 40.0, 3700.0 / 72.0) < 3700.0 / 72.0); let mut bands = Vec::new(); plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |band| { let p = &band.plates; diff --git a/crates/proof/Cargo.toml b/crates/proof/Cargo.toml index 60cea674d0..632016f4ff 100644 --- a/crates/proof/Cargo.toml +++ b/crates/proof/Cargo.toml @@ -18,4 +18,5 @@ toml = { version = "1", default-features = false, features = ["parse", "serde", unicode-normalization = "0.1" [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/proof/src/affix_suggest.rs b/crates/proof/src/affix_suggest.rs index ba72d8ebdd..0ad2e5be1d 100644 --- a/crates/proof/src/affix_suggest.rs +++ b/crates/proof/src/affix_suggest.rs @@ -883,7 +883,9 @@ mod tests { aff.push_str("SFX 9000 Y 1\nSFX 9000 0 s .\n"); let d = AffixDict::from_hunspell(&aff, "3\nb/1,5000\nab/2\nkot/9000\n", &[]).unwrap(); assert!(!d.stems().any(|s| s == "kots") && d.can_suggest("kots")); - for word in [input.clone(), input.to_uppercase()] { + // The gate asks for the word as typed; nightly adds the upper-case spelling (the case fallback). + let words = if craft_testkit::hostile::divisor() == 1 { vec![input.clone(), input.to_uppercase()] } else { vec![input.clone()] }; + for word in words { let got = suggest_in(&d, &word, 1, &Tuning::DEFAULT); assert_eq!(got.len(), 1, "accepted affixed candidate lost: {word}: {got:?}"); assert!(got[0].eq_ignore_ascii_case("kots"), "{word}: {got:?}"); diff --git a/crates/proto/Cargo.toml b/crates/proto/Cargo.toml index 528e407a87..8657aa51e8 100644 --- a/crates/proto/Cargo.toml +++ b/crates/proto/Cargo.toml @@ -17,4 +17,5 @@ zeroize = "1" log = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/proto/src/imap/gmail_labels_tests.rs b/crates/proto/src/imap/gmail_labels_tests.rs index 441e3220bf..1673af4e31 100644 --- a/crates/proto/src/imap/gmail_labels_tests.rs +++ b/crates/proto/src/imap/gmail_labels_tests.rs @@ -165,6 +165,10 @@ fn tiny_labels_count_against_the_budget_too() { #[test] fn a_big_folders_listing_is_not_cut_short_for_its_size() { + // Sized to a cap of tens of MiB: the gate runs the cheaper tests of the same caps, nightly runs this one. + if craft_testkit::hostile::divisor() > 1 { + return; + } // 300,000 messages with labels: more text than one command may otherwise bring (32 MiB). let count: u32 = 300_000; let mut server = String::with_capacity(count as usize * 200); @@ -185,6 +189,10 @@ fn a_big_folders_listing_is_not_cut_short_for_its_size() { #[test] fn a_mailbox_claimed_huge_cant_fill_memory_with_flags() { + // Sized to a cap of tens of MiB: the gate runs the cheaper tests of the same caps, nightly runs this one. + if craft_testkit::hostile::divisor() > 1 { + return; + } // Any server (no Gmail here): ten million messages claimed, then message after message with // every flag it may have. The text it may send is capped, and so are the flags kept: the // listing fails, and never hands back messages that seem to have lost their flags. diff --git a/crates/proto/src/imap/limits_tests.rs b/crates/proto/src/imap/limits_tests.rs index 9b802055c0..01e91e7de1 100644 --- a/crates/proto/src/imap/limits_tests.rs +++ b/crates/proto/src/imap/limits_tests.rs @@ -26,13 +26,16 @@ fn padding() -> String { #[test] fn a_flood_of_long_lines_ends_the_command() { let pad = padding(); - // 600 lines of 60 KB are more than the 32 MB one command may bring. - let server = flood(600, |n| format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1)) + "A0001 OK done\r\n"; + // 600 lines of 60 KB are more than the 32 MB one command may bring. The gate sends lines that + // are not parsed (the cap counts the text read); nightly sends the lines of a real listing. + let full = craft_testkit::hostile::divisor() == 1; + let server = + flood(600, |n| if full { format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1) } else { format!("* OK {pad}\r\n") }) + "A0001 OK done\r\n"; let mut s = Script::new(server); let err = opened(&mut s, 1000, 2000).uid_fetch_flags("1:*").unwrap_err(); assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too much")), "{err:?}"); // The same in a list. - let server = flood(600, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n"; + let server = flood(600, |n| if full { format!("* LIST () \"/\" \"{n}{pad}\"\r\n") } else { format!("* OK {pad}\r\n") }) + "A0001 OK done\r\n"; let mut s = Script::new(server); assert!(matches!(opened(&mut s, 0, 0).list(), Err(ProtoError::Protocol(_)))); } @@ -113,6 +116,7 @@ fn only_uids_that_were_asked_for_and_exist_are_kept() { #[test] fn more_distinct_uids_than_the_mailbox_can_hold_fail_the_command() { + let full = craft_testkit::hostile::divisor() == 1; // 3 messages: room for 2 * 3 + FETCH_SLACK distinct UIDs, and not one more. let room = 2 * 3 + FETCH_SLACK; let many = |n: usize| flood(n, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; @@ -120,6 +124,9 @@ fn more_distinct_uids_than_the_mailbox_can_hold_fail_the_command() { assert_eq!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*").unwrap().len(), room); let mut s = Script::new(many(room + 1)); assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); + if !full { + return; + } let sizes = flood(room + 1, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; let mut s = Script::new(sizes); assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_sizes("1:*"), Err(ProtoError::Protocol(_)))); @@ -177,7 +184,9 @@ proptest! { #[test] fn a_folder_with_more_messages_than_other_commands_may_answer_still_reads() { - let exists = 300_000u32; + // The gate reads one folder just past the usual cap; nightly adds the sizes and the noise. + let full = craft_testkit::hostile::divisor() == 1; + let exists = if full { 300_000u32 } else { MAX_RESPONSES as u32 + 1 }; let lines = |n: u32| flood(n as usize, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; let mut s = Script::new(lines(exists)); assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_flags("1:*").unwrap().len(), exists as usize); diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index 30bf3a4719..b08ca6ae1b 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -28,6 +28,7 @@ serde = { workspace = true, optional = true } rayon = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } craft-psd = { path = ".", features = ["test-support"] } diff --git a/crates/psd/src/lazy.rs b/crates/psd/src/lazy.rs index 271d220885..98f885768c 100644 --- a/crates/psd/src/lazy.rs +++ b/crates/psd/src/lazy.rs @@ -525,7 +525,8 @@ mod tests { let clean = std::sync::Arc::new(FailOnce { bytes: bytes.clone(), fail_at: usize::MAX, reads: 0.into() }); PsdFile::from_source(Source::from_arc(clean.clone())).unwrap(); let reads = clean.reads.load(std::sync::atomic::Ordering::SeqCst); - for fail_at in 0..reads { + // The gate fails every divisor-th read; nightly fails each one. + for fail_at in (0..reads).step_by(craft_testkit::hostile::divisor()) { let src = FailOnce { bytes: bytes.clone(), fail_at, reads: 0.into() }; match PsdFile::from_source(Source::new(src)) { Err(PsdError::Read(_)) => {} diff --git a/crates/pst/Cargo.toml b/crates/pst/Cargo.toml index 60ead7d8fa..9dff7fa17e 100644 --- a/crates/pst/Cargo.toml +++ b/crates/pst/Cargo.toml @@ -20,5 +20,6 @@ workspace = true [dependencies] [dev-dependencies] +craft-testkit = { workspace = true } craft-pst = { path = ".", features = ["test-support"] } proptest = { workspace = true } diff --git a/crates/pst/src/tests/salvage.rs b/crates/pst/src/tests/salvage.rs index 7d5d391ea9..b7f341b7ae 100644 --- a/crates/pst/src/tests/salvage.rs +++ b/crates/pst/src/tests/salvage.rs @@ -248,7 +248,9 @@ fn a_reader_that_fails_or_runs_out_ends_the_call() { } }; let mut failed = 0; - for (fail, short) in (1..=reads).flat_map(|n| [(n, false), (n, true)]) { + // The gate fails every divisor-th read; nightly fails each one. + let step = craft_testkit::hostile::divisor(); + for (fail, short) in (1..=reads).step_by(step).flat_map(|n| [(n, false), (n, true)]) { let Ok(mut pst) = Pst::open(Flaky { inner: Cursor::new(&bytes[..]), reads: 0, fail, short }) else { continue }; let got = answers(&mut pst, &folders, &items); failed += got.iter().filter(|r| r.is_err()).count(); @@ -257,7 +259,7 @@ fn a_reader_that_fails_or_runs_out_ends_the_call() { } assert!(failed > 0); let mut capped = 0; - for floor in (0..bytes.len() as u64 * 4).step_by(256) { + for floor in (0..bytes.len() as u64 * 4).step_by(256 * step) { let limits = Limits { read_multiple: 0, read_floor: floor, ..Default::default() }; let Ok(mut pst) = Pst::open_with(Cursor::new(&bytes[..]), limits) else { continue }; let got = answers(&mut pst, &folders, &items); diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml index ddb1dbf2e0..a99d447479 100644 --- a/crates/raw/Cargo.toml +++ b/crates/raw/Cargo.toml @@ -70,6 +70,7 @@ zune-core = { version = "0.5", default-features = false, features = ["std"], opt jxl-oxide = { version = "0.12", default-features = false, optional = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } # The SHA-256 of the SR2 keystream known answer. sha2 = { version = "0.10", default-features = false, features = ["std"] } diff --git a/crates/raw/src/arw_lens.rs b/crates/raw/src/arw_lens.rs index b42d3afe0f..c023bf071a 100644 --- a/crates/raw/src/arw_lens.rs +++ b/crates/raw/src/arw_lens.rs @@ -1377,10 +1377,12 @@ mod tests { assert_eq!((h.lens_metadata, h.opcodes), (f.lens_metadata, f.opcodes)); } }; - for len in 0..good.len() { + // The gate runs every divisor-th truncation and byte; nightly runs every one. + let step = craft_testkit::hostile::divisor(); + for len in (0..good.len()).step_by(step) { check(&good[..len]); } - for at in (0..good.len()).filter(|at| !image.contains(at)) { + for at in (0..good.len()).step_by(step).filter(|at| !image.contains(at)) { for v in [0, 0xff, good[at] ^ 0x80, good[at] ^ 0x01] { let mut file = good.clone(); file[at] = v; diff --git a/crates/raw/tests/it/dng_lines.rs b/crates/raw/tests/it/dng_lines.rs index dd10c763cd..a1acdb9dd0 100644 --- a/crates/raw/tests/it/dng_lines.rs +++ b/crates/raw/tests/it/dng_lines.rs @@ -260,6 +260,10 @@ fn a_lossless_jpeg_larger_than_its_tile_is_refused_before_decoding_it_all() { #[test] fn short_lossy_jpeg_strips_are_charged_their_own_rows() { + // A 33-megapixel image next to the aggregate decode budget: nightly only. + if craft_testkit::hostile::divisor() > 1 { + return; + } // 8192 x 4096 RGB (below MAX_SAMPLES) in 16-row lossy JPEG strips: each strip's JPEG is exactly // 16 rows, so the decode budget charges 16 rows, not the 32 of the MCU padding allowance (which // would put the image over the aggregate budget and refuse it) diff --git a/crates/scraft-format/Cargo.toml b/crates/scraft-format/Cargo.toml index 9ec17cf9f9..e445ff1195 100644 --- a/crates/scraft-format/Cargo.toml +++ b/crates/scraft-format/Cargo.toml @@ -20,5 +20,6 @@ serde_json.workspace = true thiserror.workspace = true [dev-dependencies] +craft-testkit = { workspace = true } craft-audio = { workspace = true, features = ["decode", "serde"] } proptest.workspace = true diff --git a/crates/scraft-format/src/b64.rs b/crates/scraft-format/src/b64.rs index 100a9a08f9..b4421c00bc 100644 --- a/crates/scraft-format/src/b64.rs +++ b/crates/scraft-format/src/b64.rs @@ -104,10 +104,13 @@ mod tests { // faster and using less temporary memory. let exact = encoded_zero_bytes(MAX_DECODED_BYTES); assert_eq!(decode(&exact).map(|bytes| bytes.len()), Some(MAX_DECODED_BYTES), "padded boundary"); - assert_eq!(decode(exact.trim_end_matches('=')).map(|bytes| bytes.len()), Some(MAX_DECODED_BYTES), "unpadded boundary"); - let too_large = encoded_zero_bytes(MAX_DECODED_BYTES + 1); assert!(decode(&too_large).is_none(), "padded over boundary"); + // Each case decodes tens of MiB: the gate runs the two above, nightly the rest. + if craft_testkit::hostile::divisor() > 1 { + return; + } + assert_eq!(decode(exact.trim_end_matches('=')).map(|bytes| bytes.len()), Some(MAX_DECODED_BYTES), "unpadded boundary"); let spaced = format!("{}\n {}", &too_large[..8], &too_large[8..]); assert!(decode(&spaced).is_none(), "whitespace over boundary"); } diff --git a/crates/stream-codecs/Cargo.toml b/crates/stream-codecs/Cargo.toml index 14ce686036..1739252128 100644 --- a/crates/stream-codecs/Cargo.toml +++ b/crates/stream-codecs/Cargo.toml @@ -21,5 +21,6 @@ hayro-jbig2 = { path = "../../vendor/hayro-jbig2", version = "=0.3.0", default-f thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } weezl = "0.2" diff --git a/crates/stream-codecs/src/jbig2/symbols.rs b/crates/stream-codecs/src/jbig2/symbols.rs index f56503a847..56f5e26ffb 100644 --- a/crates/stream-codecs/src/jbig2/symbols.rs +++ b/crates/stream-codecs/src/jbig2/symbols.rs @@ -942,6 +942,10 @@ mod tests { let past = page(&data, columns).unwrap(); assert!(plan(&past, columns, rows, 1, None, None).is_none() && plan(&past, columns, rows, 2, None, None).is_none()); assert_eq!(encode_jbig2(&data, columns, rows).unwrap(), encode_jbig2_generic(&data, columns, rows).unwrap()); + // Each picture below is another 65,536 marks coded and decoded: nightly only. + if craft_testkit::hostile::divisor() > 1 { + return; + } // With two of them repeated, the second plan codes those two. let (data, columns, rows) = codes(MAX_CODED_SYMBOLS + 1, 200); let past = page(&data, columns).unwrap(); diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index e11954573d..904c1251f0 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -19,7 +19,7 @@ default = [] # `craft_ui::testing`: the fixture and helpers used by application tests. # The suite runner, stories, registrations and snapshots are opt-in. testing = ["craft-platform/testing"] -suite = ["testing", "dep:libtest-mimic", "snapshot"] +suite = ["testing", "dep:libtest-mimic", "dep:craft-testkit", "snapshot"] # `craft_ui::testing::snapshot`: stories rendered to images offscreen (desktop only). snapshot = ["dep:egui_kittest", "dep:image"] # Draw colour glyphs (COLR, sbix, CBDT), e.g. colour emoji. @@ -46,6 +46,8 @@ craft-settings = { workspace = true } toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] } egui = { workspace = true } libtest-mimic = { version = "0.8", optional = true } +# The gate's sweep fraction (`hostile::divisor`), which the suite's repeat sampling follows. +craft-testkit = { workspace = true, optional = true } craft-host = { workspace = true } # `WindowSystem` and `restore::Store`, which viewport mounts place windows through. # `ui`: the window crate's egui side builds once, the same for the runtime, the shell's `app` and the apps. diff --git a/crates/ui-contract/src/testing/suite/activation.rs b/crates/ui-contract/src/testing/suite/activation.rs index 1922c7d303..719ca9754f 100644 --- a/crates/ui-contract/src/testing/suite/activation.rs +++ b/crates/ui-contract/src/testing/suite/activation.rs @@ -1,7 +1,7 @@ //! Activation, declared actions, AccessKit focus and cancelled presses. use super::drive::{Plan, for_input, input_fixture, root_target, run, variant_name, variants}; -use super::{ANY, Case, Subject}; +use super::{ANY, Case, Subject, nodes}; use crate::contract::ShapeKind; use crate::runtime::access::Role; use crate::runtime::egui::access::{AccessTree, Declared, NodeKey}; @@ -9,7 +9,7 @@ use crate::runtime::egui::fixture::AccessActionKind; use crate::testing::fixture::Fixture; use crate::testing::pointer; use crate::testing::story::{EditKind, Required, StoryData, StoryOutput}; -use craft_behavior::Input; +use craft_behavior::{Input, PartRef}; use egui::{Id, Key, Modifiers}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -53,6 +53,8 @@ fn each_activation_clicks_once(subject: &Subject) -> Result<(), String> { /// Every part that senses `CLICK` of a component that carries no value gives exactly one click on each path it has: /// a primary click, AccessKit `Click` when its node declares it, and Enter or Space after AccessKit `Focus` when it /// is a focus stop; a collection's parts report events, not clicks, and are read by the collection cases. Two clicks mean the part's press also reached the root's activation. +/// A repeated part runs on a fixed sample of its repeats under the gate's fraction ([`nodes::sampled_parts`]). The +/// paths a part has are read from the story's settled base fixture, so a fixture is built only for a path it has. fn each_part_activates_once(subject: &Subject) -> Result<(), String> { if subject.probe.carries_value() || matches!(subject.probe.input, Input::Text | Input::Editor | Input::Display) @@ -62,26 +64,30 @@ fn each_part_activates_once(subject: &Subject) -> Result<(), String> { } let keys = [(Key::Enter, subject.probe.keys.activate.enter()), (Key::Space, subject.probe.keys.activate.space())]; for story in &subject.stories { - let fixture = &subject.base(story).fixture; - let Some(id) = fixture.root_id() else { continue }; - let mut parts = crate::runtime::pointer::sensing_parts(fixture.ctx(), id, craft_behavior::Sense::CLICK); + let base = &subject.base(story).fixture; + let Some(id) = base.root_id() else { continue }; + let mut parts = crate::runtime::pointer::sensing_parts(base.ctx(), id, craft_behavior::Sense::CLICK); parts.dedup(); - for part in parts { + // A part with no node or a disabled one has no path, and the sample is taken of the rest. The base's node keys + // are the input fixture's. + let enabled = |part: PartRef| base.part(id, part).filter(|seen| base.tree().data_of(seen.node).is_none_or(|node| !node.is_disabled())); + parts.retain(|part| enabled(*part).is_some()); + for part in nodes::sampled_parts(parts) { + let Some(seen) = enabled(part) else { continue }; + let declares = |action| base.tree().declares_key(seen.node, action); // Paths: 0 click, 1 AccessKit Click, 2 and 3 the activation keys. - for path in 0..4 { + let paths = [ + (0, "a click", true), + (1, "AccessKit Click", declares(Declared::Click)), + (2, "Enter", keys[0].1 && declares(Declared::Focus)), + (3, "Space", keys[1].1 && declares(Declared::Focus)), + ]; + for (path, name, _) in paths.into_iter().filter(|(_, _, has)| *has) { let mut fixture = input_fixture(story); let Some(target) = fixture.root_id().and_then(|id| fixture.part(id, part)) else { continue }; if fixture.tree().data_of(target.node).is_some_and(|node| node.is_disabled()) { continue; } - let declares = |fixture: &Fixture, action| fixture.tree().declares_key(target.node, action); - let name = match path { - 0 => "a click", - 1 if declares(&fixture, Declared::Click) => "AccessKit Click", - 2 if keys[0].1 && declares(&fixture, Declared::Focus) => "Enter", - 3 if keys[1].1 && declares(&fixture, Declared::Focus) => "Space", - _ => continue, - }; fixture.take_outputs(); match path { 0 => { @@ -121,7 +127,8 @@ fn signature(tree: &AccessTree) -> HashMap { .collect() } -/// Every action a node declares changes something: a click, an edit, a node state or the focus. +/// Every action a node declares changes something: a click, an edit, a node state or the focus. A repeated set of +/// nodes runs on a fixed sample under the gate's fraction ([`nodes::sampled_actions`]). fn declared_actions_are_handled(subject: &Subject) -> Result<(), String> { for story in subject.stories.iter().filter(|story| !story.covers.contains(&Required::Invalid)) { let fixture = &subject.base(story).fixture; @@ -131,12 +138,15 @@ fn declared_actions_are_handled(subject: &Subject) -> Result<(), String> { (Declared::Expand, AccessActionKind::Expand), ]; let tree = fixture.tree(); - let nodes: Vec<_> = tree + let declared: Vec<(NodeKey, Declared)> = tree .keys() .into_iter() .filter(|key| tree.data_of(*key).is_some_and(|node| !node.is_disabled())) - .flat_map(|key| actions.iter().filter(move |(declared, _)| tree.declares_key(key, *declared)).map(move |(_, kind)| (key, *kind))) + .flat_map(|key| actions.iter().filter(move |(declared, _)| tree.declares_key(key, *declared)).map(move |(declared, _)| (key, *declared))) .collect(); + let nodes = nodes::sampled_actions(tree, declared) + .into_iter() + .filter_map(|(key, declared)| actions.iter().find(|(known, _)| *known == declared).map(|(_, kind)| (key, *kind))); for (key, kind) in nodes { let mut fixture = input_fixture(story); let Some(target) = fixture.target(key) else { continue }; @@ -261,14 +271,19 @@ fn every_intent_has_a_declared_action(subject: &Subject) -> Result<(), String> { Ok(()) } -/// AccessKit `Focus` on a node that declares it gives the component key focus. +/// AccessKit `Focus` on a node that declares it gives the component key focus. A story whose settled base fixture has +/// no enabled node that declares it has nothing to check. fn access_focus_focuses(subject: &Subject) -> Result<(), String> { + let focusable = |fixture: &Fixture, key: NodeKey| { + fixture.tree().declares_key(key, Declared::Focus) && fixture.tree().data_of(key).is_some_and(|node| !node.is_disabled()) + }; for story in &subject.stories { + let base = &subject.base(story).fixture; + if !base.tree().keys().into_iter().any(|key| focusable(base, key)) { + continue; + } let mut fixture = input_fixture(story); - let node = - fixture.tree().keys().into_iter().find(|key| { - fixture.tree().declares_key(*key, Declared::Focus) && fixture.tree().data_of(*key).is_some_and(|node| !node.is_disabled()) - }); + let node = fixture.tree().keys().into_iter().find(|key| focusable(&fixture, *key)); let Some(target) = node.and_then(|key| fixture.target(key)) else { continue }; fixture.access(AccessActionKind::Focus, &target); fixture.settle(); diff --git a/crates/ui-contract/src/testing/suite/nodes.rs b/crates/ui-contract/src/testing/suite/nodes.rs index ba0d7fc583..20cf49b1eb 100644 --- a/crates/ui-contract/src/testing/suite/nodes.rs +++ b/crates/ui-contract/src/testing/suite/nodes.rs @@ -1,8 +1,9 @@ //! What the container and collection cases read from the AccessKit tree of a fixture. use crate::runtime::access::Role; -use crate::runtime::egui::access::{AccessTree, NodeKey}; +use crate::runtime::egui::access::{AccessTree, Declared, NodeKey}; use crate::testing::fixture::{Fixture, Target}; +use craft_behavior::PartRef; /// `node` and every node below it. pub(super) fn subtree(tree: &AccessTree, node: NodeKey) -> Vec { @@ -77,3 +78,85 @@ pub(super) fn position_in_set(fixture: &Fixture, row: NodeKey) -> Option<(usize, pub(super) fn is_selected(fixture: &Fixture, node: NodeKey) -> bool { fixture.tree().data_of(node).and_then(|data| data.is_selected()).unwrap_or(false) } + +/// Whether the cases that run once per member of a repeated set (each repeat of a part, each row that declares an +/// action) run on a fixed sample of the set: under the gate's sweep fraction, `craft_testkit::hostile::divisor` above +/// 1. The nightly run sets no fraction and checks every member. +fn samples_repeats() -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + craft_testkit::hostile::divisor() > 1 + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + +/// The first, middle and last of `members`; all of them when there are three or fewer. The members of a repeated set +/// come from one code path, so these cover it, its edges included. +fn sample(members: &[T]) -> Vec { + match members.len() { + 0..=3 => members.to_vec(), + n => vec![members[0], members[n / 2], members[n - 1]], + } +} + +/// `parts` with each repeated part ([`PartRef::index`]) cut to the lowest, middle and highest index of its key when +/// [`samples_repeats`]; a part that occurs once always stays. +pub(super) fn sampled_parts(parts: Vec) -> Vec { + if !samples_repeats() { + return parts; + } + let mut kept: Vec = Vec::new(); + for part in &parts { + if part.index.is_none() { + kept.push(*part); + continue; + } + if kept.iter().any(|done| done.key == part.key && done.index.is_some()) { + continue; + } + let mut indices: Vec = parts.iter().filter(|other| other.key == part.key).filter_map(|other| other.index).collect(); + indices.sort_unstable(); + indices.dedup(); + kept.extend(sample(&indices).into_iter().map(|index| part.key.at(index))); + } + kept +} + +/// The keys of `tree` depth first from its root, children in their declared order; nodes the root does not reach +/// follow in the tree's own order. +fn tree_order(tree: &AccessTree) -> Vec { + let mut ordered = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut pending: Vec = tree.root_key().into_iter().collect(); + while let Some(key) = pending.pop() { + if seen.insert(key) { + ordered.push(key); + pending.extend(tree.children_of(key).into_iter().rev()); + } + } + ordered.extend(tree.keys().into_iter().filter(|key| !seen.contains(key))); + ordered +} + +/// `pairs` (a node and an action it declares) in tree order; when [`samples_repeats`], set by set, each repeated set +/// cut to its first, middle and last node. Nodes that share a parent and a role and declare the same action are one set. +pub(super) fn sampled_actions(tree: &AccessTree, mut pairs: Vec<(NodeKey, Declared)>) -> Vec<(NodeKey, Declared)> { + let rank: std::collections::HashMap = tree_order(tree).into_iter().enumerate().map(|(at, key)| (key, at)).collect(); + pairs.sort_by_key(|(node, _)| rank.get(node).copied().unwrap_or(usize::MAX)); + let ordered = pairs; + if !samples_repeats() { + return ordered; + } + let set_of = |(node, declared): &(NodeKey, Declared)| (tree.parent_of_key(*node), tree.role_of(*node), *declared); + let mut sets: Vec> = Vec::new(); + for pair in ordered { + match sets.iter_mut().find(|set| set_of(&set[0]) == set_of(&pair)) { + Some(set) => set.push(pair), + None => sets.push(vec![pair]), + } + } + sets.iter().flat_map(|set| sample(set)).collect() +} diff --git a/crates/ui-contract/src/testing/suite/pointer.rs b/crates/ui-contract/src/testing/suite/pointer.rs index 20c3965166..15fd8f53f8 100644 --- a/crates/ui-contract/src/testing/suite/pointer.rs +++ b/crates/ui-contract/src/testing/suite/pointer.rs @@ -1,14 +1,14 @@ //! The pointer rows of 22.4: slop, hit areas and the arena winner. use super::drive::{Plan, input_fixture, root_target}; -use super::{ANY, Case, Subject}; +use super::{ANY, Case, Subject, nodes}; use crate::contract::ShapeKind; use crate::runtime::egui::access::Declared; use crate::testing::fixture::{Fixture, Target}; use crate::testing::sensing::{ProbeMember, ProbePart, ProbeRoot, RootReport, show}; use crate::testing::story::{EditKind, Grip, Required}; use crate::testing::{Frames, input, pointer}; -use craft_behavior::{HitLevel, PartKey, Sense}; +use craft_behavior::{HitLevel, PartKey, PartRef, Sense}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::collections::HashSet; @@ -96,8 +96,17 @@ fn at(target: &Target, point: Pos2) -> Target { Target { node: target.node, rect: Rect::from_center_size(point, Vec2::ZERO) } } +/// The visible piece of `part` of the shown component, where a press on it lands, when it is enabled and not empty: one +/// past the window's edge cannot be seen, so not pressed. +fn pressable(fixture: &Fixture, part: PartRef) -> Option { + let target = fixture.root_id().and_then(|id| fixture.part(id, part)).and_then(|target| fixture.visible(&target))?; + let enabled = fixture.tree().data_of(target.node).is_some_and(|node| !node.is_disabled()); + (enabled && target.rect.area() > 0.0).then_some(target) +} + /// A press inside the visible piece of a part's hit area (inside the root's clip), also where it lies outside the root's -/// rect, is taken by the component; on the part a drag moves, a press off its middle moves the value. +/// rect, is taken by the component; on the part a drag moves, a press off its middle moves the value. A repeated part +/// runs on a fixed sample of its repeats under the gate's fraction ([`nodes::sampled_parts`]). fn parts_take_presses_in_their_hit_areas(subject: &Subject) -> Result<(), String> { let probe = subject.probe; for story in &subject.stories { @@ -109,15 +118,11 @@ fn parts_take_presses_in_their_hit_areas(subject: &Subject) -> Result<(), String parts.push(part); } } - for part in parts { + // A part the settled base shows no pressable piece of gets no fixture, and the sample is taken of the rest. + parts.retain(|part| pressable(fixture, *part).is_some()); + for part in nodes::sampled_parts(parts) { let mut fixture = input_fixture(story); - // A press lands on the part's visible piece: one past the window's edge cannot be seen, so not pressed. - let Some(target) = fixture.root_id().and_then(|id| fixture.part(id, part)).and_then(|target| fixture.visible(&target)) else { - continue; - }; - if fixture.tree().data_of(target.node).is_none_or(|node| node.is_disabled()) || target.rect.area() <= 0.0 { - continue; - } + let Some(target) = pressable(&fixture, part) else { continue }; let point = probe_point(target.rect, root_target(&fixture).rect); fixture.press(&at(&target, point)); if !pointer::press_captured(fixture.ctx()) { diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index d44f6dbbe4..c59d51f016 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -386,19 +386,19 @@ fn export_as_keeps_scale_all_within_its_limits_and_enter_in_a_field_only_commits let host = Rc::new(RefCell::new(DialogHost::new())); let mut fixture = fixture(&host); host.borrow_mut().open(HostedExportAs::new("Poster", PICTURE, ExportOptions::default())); - fixture.idle(10); + fixture.settle(); let options = |host: &Rc>| host.borrow().get::().map(|dialog| dialog.options().clone()).expect("open"); let scale = fixture.by_label("Scale").expect("the Scale field"); - fixture.click(&scale).idle(2); + fixture.click(&scale).settle(); fixture.key(Key::A, Modifiers::COMMAND).type_text("50"); - fixture.key(Key::Enter, Modifiers::NONE).idle(4); + fixture.key(Key::Enter, Modifiers::NONE).settle(); assert!(host.borrow().is_open::(), "Enter in the Scale field leaves the dialog open"); assert_eq!(options(&host).output_size(PICTURE), PixelSize::new(800, 450), "Enter commits the field"); for _ in 1..ScaleRow::MAX_ROWS { let add = fixture.by_label("Add a size").expect("the + button"); - fixture.click(&add).idle(4); + fixture.click(&add).settle(); } let rows = options(&host).scale_rows(); assert_eq!(rows.len(), ScaleRow::MAX_ROWS, "+ adds rows up to the limit"); @@ -409,9 +409,9 @@ fn export_as_keeps_scale_all_within_its_limits_and_enter_in_a_field_only_commits assert!(fixture.tree().is_disabled_key(add.node), "+ is disabled at the limit"); let suffix = fixture.by_label("Suffix 2").expect("the second row's suffix"); - fixture.click(&suffix).idle(2); + fixture.click(&suffix).settle(); fixture.key(Key::A, Modifiers::COMMAND).type_text(&"s".repeat(ScaleRow::MAX_SUFFIX + 10)); - fixture.key(Key::Tab, Modifiers::NONE).idle(4); + fixture.key(Key::Tab, Modifiers::NONE).settle(); assert_eq!(options(&host).scale_rows()[1].suffix.chars().count(), ScaleRow::MAX_SUFFIX, "a suffix is cut at its limit"); } diff --git a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs index ef83f8435f..f56c6eddc2 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs @@ -1,6 +1,7 @@ //! New Document: saved presets, the Save Document Preset pane, Bitmap's depth, the Web and Mobile cards' Artboards and //! the pixel aspect ratio. +use craft_behavior::MotionMode; use craft_ui::buttons::Button; use craft_ui::contract::{Bind, SaveKey, Show as _, clicked}; use craft_ui::dialog::DialogHost; @@ -35,10 +36,10 @@ fn shows(fixture: &Fixture, text: &str) -> bool { /// Opens `tab` and clicks the card titled `card` in it. fn pick(fixture: &mut Fixture, tab: &str, card: &str) { let target = fixture.by_label(tab).unwrap_or_else(|| panic!("the {tab} tab")); - fixture.click(&target).idle(10); + fixture.click(&target).settle(); // A card's node is named by its title and size line together; its title is clicked where it is painted. let title = fixture.texts().iter().find(|painted| painted.text == card).map(|painted| painted.rect.center()); - fixture.click_at(title.unwrap_or_else(|| panic!("the {card} card in {tab}"))).idle(10); + fixture.click_at(title.unwrap_or_else(|| panic!("the {card} card in {tab}"))).settle(); } /// The most a host's count may be: its `fitted` caps it. @@ -176,12 +177,13 @@ fn the_orientation_turns_the_built_in_cards() { let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); *held.borrow_mut() = options; }); - fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + // The cards are read where they are painted, so the motion is off: a settled frame shows them at rest. + fixture.motion(MotionMode::Off).room(Vec2::new(1400.0, 1000.0)).settle(); let art = fixture.by_label("Art & Illustration").expect("the Art tab"); - fixture.click(&art).idle(10); + fixture.click(&art).settle(); let turn = |fixture: &mut Fixture, orientation: &str| { let control = fixture.by_label(orientation).unwrap_or_else(|| panic!("the {orientation} control")); - fixture.click(&control).idle(10); + fixture.click(&control).settle(); }; let page = |shared: &Rc>| { let size = shared.borrow().size; @@ -394,13 +396,14 @@ fn web_cards_turn_artboards_on_and_only_take_back_their_own() { let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); *held.borrow_mut() = options; }); - fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + // The cards are read where they are painted, so the motion is off: a settled frame shows them at rest. + fixture.motion(MotionMode::Off).room(Vec2::new(1400.0, 1000.0)).settle(); pick(&mut fixture, "Web", "Web Most Common"); assert!(shared.borrow().artboard, "a Web card turns Artboards on"); pick(&mut fixture, "Photo", "Landscape, 6 x 4"); assert!(!shared.borrow().artboard, "a Photo card takes it back"); let artboards = fixture.by_label("Artboards").expect("the Artboards box"); - fixture.click(&artboards).idle(10); + fixture.click(&artboards).settle(); pick(&mut fixture, "Photo", "Landscape, 7 x 5"); assert!(shared.borrow().artboard, "the user's tick stays"); } diff --git a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs index e3171d24ba..105ec43c92 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs @@ -43,7 +43,7 @@ fn open(web: HostedSaveForWeb) -> (Rc>, Fixture) { let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); fixture.room(Vec2::new(1400.0, 1000.0)); host.borrow_mut().open(web); - fixture.idle(10); + fixture.settle(); (host, fixture) } @@ -178,7 +178,7 @@ fn show_palette(host: &Rc>, fixture: &mut Fixture) { let revision = wanted.first().map_or(1, |want| want.request.revision); let variant = WebVariant::new(0, revision, texture(), 1000).colors(4).palette(PALETTE.to_vec()); host.borrow_mut().get_mut::().expect("open").set_variant(variant); - fixture.idle(4); + fixture.settle(); select_optimized_pane(fixture); } @@ -212,7 +212,7 @@ fn slices_and_palette_edits_follow_the_settings() { let web = HostedSaveForWeb::new("poster.psd", IMAGE, texture()).options(start).slices(slices()).presets(vec![preset]); let (host, mut fixture) = open(web); let actual = fixture.by_label("100%").expect("the 100% button"); - fixture.click(&actual).idle(4); + fixture.click(&actual).settle(); // A click selects one slice; Shift adds and removes. click_picture(&mut fixture, pos2(50.0, 50.0)); @@ -233,38 +233,38 @@ fn slices_and_palette_edits_follow_the_settings() { show_palette(&host, &mut fixture); assert_eq!(current(&host).slices, WebSlices::Selected(vec![1, 2]), "a click beside the picture leaves the slices"); let cell = fixture.by_label("1 #00ff00").expect("the Color Table lists the palette"); - fixture.click(&cell).key(Key::Enter, Modifiers::NONE).idle(4); + fixture.click(&cell).key(Key::Enter, Modifiers::NONE).settle(); let (id, request) = host.borrow_mut().take_color_request().expect("opening a cell asks for its colour"); assert_eq!(request.key, PALETTE_COLOR_KEY); host.borrow_mut().answer_color(id, PALETTE_COLOR_KEY, Srgba::rgb(1.0, 0.0, 1.0)); - fixture.idle(4); + fixture.settle(); let shift = (ColorTableEdit::Shift([255, 0, 255]), vec![[0, 255, 0]]); assert_eq!(table_events(&host), vec![shift], "the answer shifts the opened entry's colour"); let interlaced = fixture.by_label("Interlaced").expect("the Interlaced check box"); - fixture.click(&interlaced).idle(4); + fixture.click(&interlaced).settle(); assert!(table_events(&host).is_empty(), "a setting that leaves the palette alone files no table event"); let colors = fixture.by_label("Colors").expect("the Colors field"); - fixture.click(&colors).key(Key::ArrowUp, Modifiers::NONE).idle(4); + fixture.click(&colors).key(Key::ArrowUp, Modifiers::NONE).settle(); assert_eq!(current(&host).colors, 9, "the colour count changed"); let restore = (ColorTableEdit::Restore, Vec::new()); assert_eq!(table_events(&host), vec![restore], "a colour-count change restores the generated table"); // A preset pick keeps the slices. let select = fixture.by_label("Preset").expect("the Preset list"); - fixture.click(&select).idle(4); + fixture.click(&select).settle(); let entry = fixture.by_label("GIF 16").expect("the preset entry"); - fixture.click(&entry).idle(4); + fixture.click(&entry).settle(); let after = current(&host); assert_eq!(after.colors, 16, "the preset applied"); assert_eq!(after.slices, WebSlices::Selected(vec![1, 2]), "a preset keeps the slices"); // Save answers the selection in the order it was made. let save = fixture.by_label("Save…").expect("the Save button"); - fixture.click(&save).idle(4); + fixture.click(&save).settle(); let request = host.borrow_mut().get_mut::().and_then(HostedSaveForWeb::pick_path).expect("Save asks for a path"); host.borrow_mut().get_mut::().expect("open").answer_path(request.key.clone(), PathBuf::from("/tmp/poster.gif")); - fixture.idle(6); + fixture.settle(); let result = host.borrow_mut().take::().and_then(DialogResult::ok).expect("the path finishes the dialog"); assert_eq!(result.options.slices, WebSlices::Selected(vec![1, 2]), "Save answers the selected slices"); } diff --git a/crates/ui-widgets/tests/it/menu/overflow.rs b/crates/ui-widgets/tests/it/menu/overflow.rs index b6bc7954e5..96f875f9ef 100644 --- a/crates/ui-widgets/tests/it/menu/overflow.rs +++ b/crates/ui-widgets/tests/it/menu/overflow.rs @@ -56,13 +56,23 @@ fn menu_rect(fixture: &Fixture) -> Rect { fixture.by_role(Role::MENU).first().expect("the menu is open").rect } +/// The clock a frame resting on a strip moves on beyond its own: a strip scrolls by the pass's elapsed time, taken up +/// to a tenth of a second, so each frame takes the longest step a strip takes. +const STRIP_STEP: f64 = 0.1; + /// Runs frames until `done` holds, at most `frames` of them; whether it held. fn until(fixture: &mut Fixture, frames: usize, events: impl Fn() -> Vec, done: impl Fn(&Fixture) -> bool) -> bool { - for _ in 0..frames { + until_stepped(fixture, frames, 0.0, events, done) +} + +/// [`until`] with the clock moved on by `step` before each frame, beyond the frame's own. +fn until_stepped(fixture: &mut Fixture, frames: usize, step: f64, events: impl Fn() -> Vec, done: impl Fn(&Fixture) -> bool) -> bool { + for frame in 0..frames { if done(fixture) { + eprintln!("DIAG overflow until: held after {frame} frames"); return true; } - fixture.frame(events()); + fixture.advance(step).frame(events()); } done(fixture) } @@ -82,13 +92,16 @@ fn a_menu_taller_than_its_room_scrolls_by_its_strips_and_the_wheel_at_the_width_ assert!(in_view(&fixture, menu, 0) && !in_view(&fixture, menu, ROWS - 1)); let rest_on = |at: Rect| move || vec![pointer::moved(at.center())]; - assert!(until(&mut fixture, 400, rest_on(forward), |f| in_view(f, menu, ROWS - 1)), "resting on the lower strip reaches the last row"); + assert!( + until_stepped(&mut fixture, 400, STRIP_STEP, rest_on(forward), |f| in_view(f, menu, ROWS - 1)), + "resting on the lower strip reaches the last row" + ); assert!(!in_view(&fixture, menu, 0)); - assert!(until(&mut fixture, 400, rest_on(back), |f| in_view(f, menu, 0)), "resting on the upper strip reaches the first row"); + assert!(until_stepped(&mut fixture, 400, STRIP_STEP, rest_on(back), |f| in_view(f, menu, 0)), "resting on the upper strip reaches the first row"); let middle = Rect::from_min_max(back.center(), forward.center()).center(); assert!( - until(&mut fixture, 200, || vec![pointer::moved(middle), pointer::wheel(-60.0)], |f| in_view(f, menu, ROWS - 1)), + until(&mut fixture, 200, || vec![pointer::moved(middle), pointer::wheel(-240.0)], |f| in_view(f, menu, ROWS - 1)), "the wheel reaches the last row" ); assert!((menu_rect(&fixture).width() - width).abs() < 0.5, "scrolling keeps the width"); diff --git a/crates/wordmodel/src/table.rs b/crates/wordmodel/src/table.rs index bb951aa672..48584925c7 100644 --- a/crates/wordmodel/src/table.rs +++ b/crates/wordmodel/src/table.rs @@ -723,9 +723,9 @@ mod tests { assert_eq!(t.rows.len(), 3); assert_eq!(t.cols(), 4); assert_eq!(t.total_width(), 468.0); - let huge = Table::new(1_000_000, 1000, 100.0); - assert_eq!(huge.rows.len(), MAX_ROWS); - assert_eq!(huge.cols(), MAX_COLS); + // Each cap on its own: the grid of both at once would be millions of cells. + assert_eq!(Table::new(1_000_000, 1, 100.0).rows.len(), MAX_ROWS); + assert_eq!(Table::new(1, 1000, 100.0).cols(), MAX_COLS); } #[test] diff --git a/crates/xfl/Cargo.toml b/crates/xfl/Cargo.toml index 9c8a40e3cb..0375ab09c7 100644 --- a/crates/xfl/Cargo.toml +++ b/crates/xfl/Cargo.toml @@ -14,3 +14,6 @@ workspace = true craft-xml = { workspace = true } miniz_oxide = "0.8" thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 6075e4e57f..064f22431c 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -206,8 +206,8 @@ fn lying_sizes_and_checksums_are_damaged() { #[test] fn compression_bombs_are_refused() { - // A real 64 MB of zeros deflates past the ratio cap: refused before inflating. - let zeros = vec![0u8; 64 << 20]; + // A real 16 MiB of zeros deflates past the ratio cap: refused before inflating. + let zeros = vec![0u8; 16 << 20]; let z = zip(&[("bomb.xml", &zeros, true)]); assert!(z.len() < 100_000, "{}", z.len()); assert_eq!(Archive::open(&z).err(), Some(ZipError::Bomb("bomb.xml".into()))); diff --git a/crates/xlsx/Cargo.toml b/crates/xlsx/Cargo.toml index 18be3abe79..2b0ef958a6 100644 --- a/crates/xlsx/Cargo.toml +++ b/crates/xlsx/Cargo.toml @@ -22,4 +22,5 @@ craft-xml = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } craft-xlsx = { path = ".", features = ["test-support"] } diff --git a/crates/xlsx/tests/it/xlsb.rs b/crates/xlsx/tests/it/xlsb.rs index e32489e450..a6a1895104 100644 --- a/crates/xlsx/tests/it/xlsb.rs +++ b/crates/xlsx/tests/it/xlsb.rs @@ -312,11 +312,12 @@ fn declared_counts_and_decoded_text_are_bounded() { assert!(read(&package(&book(false), &worksheet(&[], &[]), &count_mismatch, ROOT, RELS, TYPES)).is_err()); let mut data = row(0); let text = wide(&"x".repeat(32767)); - for col in 0..2050 { + for col in 0..40 { data.extend(cell(6, col, &text)); } - // Just over 64 MiB of text, the allowance before storytold/gridcraft#2126. - assert_eq!(read(&file(&worksheet(&data, &[]))).unwrap().sheets[0].cells.len(), 2050); + // Many maximal strings fit an allowance sized to them (storytold/gridcraft#2126: a fixed 64 MiB allowance refused a real file). + let limits = Limits { binary_text: 40 * 32767 + 1000, ..Limits::default() }; + assert_eq!(read_with(&file(&worksheet(&data, &[])), &limits).unwrap().sheets[0].cells.len(), 40); } /// A row as Excel writes it: the row header, then `BrtRwDescent` (1024) in an alternate-content @@ -353,6 +354,11 @@ fn two_sheets(one: &[u8], two: &[u8]) -> Vec { #[test] fn more_than_a_million_cells_open() { // storytold/gridcraft#2126: a million cells over the workbook was a quarter of what `.xls` allows. + assert!(Limits::default().binary_cells > 1_000_000); + // Reading that many cells: nightly only. + if craft_testkit::hostile::divisor() > 1 { + return; + } let wb = read(&file(&worksheet(&bool_cells(1_000_001, 16), &[]))).unwrap(); assert_eq!(wb.sheets[0].cells.len(), 1_000_001); assert_eq!(wb.sheets[0].value(CellRef::new(62_500, 0)), Value::Bool(true)); @@ -360,39 +366,45 @@ fn more_than_a_million_cells_open() { #[test] fn a_full_height_column_opens() { - // 1,048,576 cells in Excel's rows are 5.2 million records in one part. - let wb = read(&file(&worksheet(&bool_cells(1_048_576, 1), &[]))).unwrap(); - assert_eq!(wb.sheets[0].cells.len(), 1_048_576); - assert_eq!(wb.sheets[0].value(CellRef::new(1_048_575, 0)), Value::Bool(true)); + // A column of n cells in Excel's rows is five records a cell in one part; limits sized for + // n cells (the defaults are sized for a full 1,048,576-row column) admit it. + let n = 20_000u32; + let limits = Limits { binary_cells: n as usize, binary_records: 5 * n as usize + 100, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&bool_cells(n, 1), &[])), &limits).unwrap(); + assert_eq!(wb.sheets[0].cells.len(), n as usize); + assert_eq!(wb.sheets[0].value(CellRef::new(n - 1, 0)), Value::Bool(true)); } #[test] fn formatted_blank_cells_cost_records_not_cells() { - // Filling A1:Z200000 and typing 30 values: Excel writes a BrtCellBlank for every formatted - // empty cell, 6 million records in all, which an allowance of 5 million per part refused. + // Filling A1:Z2000 and typing 30 values: Excel writes a BrtCellBlank for every formatted + // empty cell, 60 thousand records in all, which a cell-sized allowance of 5 times the cells + // (here 30 * 5) would refuse; the record allowance is separate from the cell allowance. let mut data = vec![]; - for r in 0..200_000u32 { + for r in 0..2_000u32 { data.extend(excel_row(r)); for c in 0..26 { data.extend(if r < 10 && c < 3 { cell(4, c, &[1]) } else { cell(1, c, &[]) }); } } - let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let limits = Limits { binary_records: 70_000, binary_cells: 100, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&data, &[])), &limits).unwrap(); assert_eq!(wb.sheets[0].cells.len(), 30); } #[test] fn cells_are_limited_to_four_million_over_the_workbook() { - // The `.xls` limit, counted across sheets: 2M + 2M opens, 2M + 2M + 1 does not. - let half = bool_cells(2_000_000, 40); + // The limit is counted across sheets: half + half opens, half + half + 1 does not. + let half = bool_cells(2_000, 40); let mut over = half.clone(); - over.extend(excel_row(50_000)); + over.extend(excel_row(50)); over.extend(cell(4, 0, &[1])); - let wb = read(&two_sheets(&worksheet(&half, &[]), &worksheet(&half, &[]))).unwrap(); - assert_eq!(wb.sheets.iter().map(|s| s.cells.len()).sum::(), 4_000_000); - let err = read(&two_sheets(&worksheet(&half, &[]), &worksheet(&over, &[]))).err().unwrap(); + let limits = Limits { binary_cells: 4_000, ..Limits::default() }; + let wb = read_with(&two_sheets(&worksheet(&half, &[]), &worksheet(&half, &[])), &limits).unwrap(); + assert_eq!(wb.sheets.iter().map(|s| s.cells.len()).sum::(), 4_000); + let err = read_with(&two_sheets(&worksheet(&half, &[]), &worksheet(&over, &[])), &limits).err().unwrap(); assert!(matches!(err, Error::TooLarge(_)), "{err}"); - assert!(err.to_string().contains("4000000"), "{err}"); + assert!(err.to_string().contains("4000"), "{err}"); } #[test] @@ -403,14 +415,15 @@ fn records_share_one_allowance_over_the_workbook() { let records = |n| Limits { binary_records: n, ..Limits::default() }; assert!(matches!(read_with(&bytes, &records(2_000)), Err(Error::TooLarge(_)))); assert!(read_with(&bytes, &records(4_000)).is_ok()); - // The default allowance: exactly 40 million records, then one more. The other parts hold 20 + // Exactly the allowance, then one more. The other parts hold 20 // (7 in the workbook, 3 shared-string records, 5 + 5 sheet framing records). let filler = record(30, &[]); // Not a cell record: skipped inside the sheet data. - let mut data = filler.repeat(40_000_000 - 20); - assert!(read(&file(&worksheet(&data, &[]))).is_ok()); + let exact = Limits { binary_records: 100_000, ..Limits::default() }; + let mut data = filler.repeat(100_000 - 20); + assert!(read_with(&file(&worksheet(&data, &[])), &exact).is_ok()); data.extend(filler.repeat(1)); - let err = read(&file(&worksheet(&data, &[]))).err().unwrap(); - assert!(matches!(err, Error::TooLarge(_)) && err.to_string().contains("too many records (more than 40000000)"), "{err}"); + let err = read_with(&file(&worksheet(&data, &[])), &exact).err().unwrap(); + assert!(matches!(err, Error::TooLarge(_)) && err.to_string().contains("too many records (more than 100000)"), "{err}"); } #[test] diff --git a/crates/xml/Cargo.toml b/crates/xml/Cargo.toml index 02d68985b2..d7743f973f 100644 --- a/crates/xml/Cargo.toml +++ b/crates/xml/Cargo.toml @@ -14,3 +14,6 @@ workspace = true quick-xml = { version = "0.41", default-features = false } thiserror = { workspace = true } serde = { workspace = true, features = ["derive"] } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/xml/tests/it/hostile.rs b/crates/xml/tests/it/hostile.rs index 19efdd235c..ed1809c9fc 100644 --- a/crates/xml/tests/it/hostile.rs +++ b/crates/xml/tests/it/hostile.rs @@ -308,19 +308,24 @@ fn mismatched_tags_are_repaired_or_refused() { /// 5 MB of input. #[test] fn attributes_are_bounded_over_the_whole_tree() { - let el = format!("", " a=\"\"".repeat(1024)); - let doc = format!("{}", el.repeat(1025)); - let limits = Limits { max_attrs_total: 1024 * 1024, ..Limits::DEFAULT }; + // `ATTRS` attributes on each of `ATTRS + 1` elements, against a limit of `ATTRS` elements' worth. + const ATTRS: usize = 64; + let el = format!("", " a=\"\"".repeat(ATTRS)); + let doc = format!("{}", el.repeat(ATTRS + 1)); + let limits = Limits { max_attrs_total: ATTRS * ATTRS, ..Limits::DEFAULT }; let opts = Options::default().with_limits(limits); let err = opts.parse(doc.as_bytes()).unwrap_err(); - assert_eq!(err, Error::TooManyAttrsTotal(1024 * 1024)); + assert_eq!(err, Error::TooManyAttrsTotal(ATTRS * ATTRS)); assert!(err.is_limit()); // exactly at the limit is accepted - let fits = format!("{}", el.repeat(1024)); - assert_eq!(opts.parse(fits.as_bytes()).map(|r| r.children.len()), Ok(1024)); - // the default stops a document that is nothing but attributes - let hostile = format!("{}", el.repeat(4000)); - assert_eq!(parse(hostile.as_bytes()), Err(Error::TooManyAttrsTotal(4_000_000))); + let fits = format!("{}", el.repeat(ATTRS)); + assert_eq!(opts.parse(fits.as_bytes()).map(|r| r.children.len()), Ok(ATTRS)); + // the default stops a document that is nothing but attributes (millions of them: nightly only) + if craft_testkit::hostile::divisor() == 1 { + let el = format!("", " a=\"\"".repeat(1024)); + let hostile = format!("{}", el.repeat(4000)); + assert_eq!(parse(hostile.as_bytes()), Err(Error::TooManyAttrsTotal(4_000_000))); + } // streamed elements take their attributes with them: any number of rows, as long as the // ones held at once fit let mut rows = 0; @@ -328,9 +333,9 @@ fn attributes_are_bounded_over_the_whole_tree() { rows += c.attrs.len(); Ok::<(), Error>(()) }); - assert_eq!((rows, root.map(|r| r.children.len())), (1025 * 1024, Ok(0))); - let tight = Options::default().with_limits(Limits { max_attrs_total: 1023, ..Limits::DEFAULT }); - assert_eq!(tight.parse_streaming(doc.as_bytes(), &["c"], |_| Ok::<(), Error>(())), Err(Error::TooManyAttrsTotal(1023))); + assert_eq!((rows, root.map(|r| r.children.len())), ((ATTRS + 1) * ATTRS, Ok(0))); + let tight = Options::default().with_limits(Limits { max_attrs_total: ATTRS - 1, ..Limits::DEFAULT }); + assert_eq!(tight.parse_streaming(doc.as_bytes(), &["c"], |_| Ok::<(), Error>(())), Err(Error::TooManyAttrsTotal(ATTRS - 1))); } /// An internal subset is found wherever it hides, and looking for it is linear in the input.