use assert_cmd::Command as CargoCommand;
use std::path::{Path, PathBuf};
use std::process::Command as ShellCommand;
use tempfile::tempdir;
const COMPAT_FIXTURE_DIR: &str = "../../tests/fixtures/compat";
fn fixture_path(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join(COMPAT_FIXTURE_DIR)
.join(name)
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Verdict {
Pass,
Warn(String),
Fail(String),
NotLinearized,
}
fn qpdf_available() -> bool {
ShellCommand::new("qpdf")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
#[must_use]
fn skip_if_qpdf_missing() -> bool {
if qpdf_available() {
return false;
}
let on_ci = std::env::var_os("CI").is_some();
if on_ci {
panic!(
"qpdf is required for cli_linearize_qpdf tests on CI; \
install qpdf in the workflow before running this test suite"
);
}
eprintln!(
"skipping: qpdf not available (target_os={}, CI={})",
std::env::consts::OS,
on_ci
);
true
}
fn run_qpdf_check(path: &Path) -> (i32, String) {
let out = ShellCommand::new("qpdf")
.args(["--check-linearization", path.to_str().unwrap()])
.output()
.expect("failed to spawn qpdf");
let code = out.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&out.stdout).to_string();
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
let combined = format!("{stdout}{stderr}");
(code, combined)
}
fn qpdf_verdict(exit: i32, output: &str) -> Verdict {
if output.contains("is not linearized") {
return Verdict::NotLinearized;
}
match exit {
0 => {
if output.contains("no linearization errors") || output.trim().is_empty() {
Verdict::Pass
} else {
Verdict::Warn(output.to_string())
}
}
3 => Verdict::Warn(output.to_string()),
_ => Verdict::Fail(output.to_string()),
}
}
fn qpdf_linearization_verdict(path: &Path) -> Verdict {
let (code, output) = run_qpdf_check(path);
qpdf_verdict(code, &output)
}
fn qpdf_linearize(input: &Path, output: &Path) {
let status = ShellCommand::new("qpdf")
.args([
"--linearize",
input.to_str().unwrap(),
output.to_str().unwrap(),
])
.status()
.expect("failed to spawn qpdf --linearize");
assert!(status.success(), "qpdf --linearize failed");
}
fn linearize_via_flpdf(input: &Path, output: &Path) -> bool {
CargoCommand::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
input.to_str().unwrap(),
output.to_str().unwrap(),
])
.output()
.map(|o| o.status.success())
.expect("failed to spawn flpdf")
}
fn rewrite_via_flpdf(input: &Path, output: &Path) -> bool {
CargoCommand::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", input.to_str().unwrap(), output.to_str().unwrap()])
.output()
.map(|o| o.status.success())
.expect("failed to spawn flpdf")
}
fn flpdf_check(path: &Path) -> (i32, String) {
let out = CargoCommand::cargo_bin("flpdf")
.unwrap()
.args(["check-linearization", path.to_str().unwrap()])
.output()
.expect("failed to spawn flpdf check-linearization");
let code = out.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&out.stdout).to_string();
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
let combined = format!("{stdout}{stderr}");
(code, combined)
}
fn flpdf_verdict(path: &Path) -> Verdict {
let (code, output) = flpdf_check(path);
match code {
0 => Verdict::Pass,
1 => {
if output.contains("not a linearized PDF") {
Verdict::NotLinearized
} else {
Verdict::Fail(output)
}
}
_ => Verdict::Fail(output),
}
}
struct CaseResult {
label: String,
status: CaseStatus,
reason: String,
}
enum CaseStatus {
Pass,
Fail,
KnownIssue,
}
impl CaseResult {
fn pass(label: impl Into<String>) -> Self {
Self {
label: label.into(),
status: CaseStatus::Pass,
reason: String::new(),
}
}
fn fail(label: impl Into<String>, reason: impl Into<String>) -> Self {
Self {
label: label.into(),
status: CaseStatus::Fail,
reason: reason.into(),
}
}
fn known(label: impl Into<String>, issue: &str, detail: impl Into<String>) -> Self {
Self {
label: label.into(),
status: CaseStatus::KnownIssue,
reason: format!("known: {issue} — {}", detail.into()),
}
}
}
fn classify_qpdf_warning(label: &str, msg: &str) -> CaseResult {
const KNOWN: &[(&str, &str, &str)] = &[
];
for (needle, issue, detail) in KNOWN {
if msg.contains(needle) {
return CaseResult::known(label.to_string(), issue, *detail);
}
}
CaseResult::fail(label.to_string(), format!("unexpected qpdf warning: {msg}"))
}
fn print_summary(results: &[CaseResult]) {
println!();
println!("=== cli_linearize_qpdf test summary ===");
for r in results {
let tag = match r.status {
CaseStatus::Pass => "OK ",
CaseStatus::Fail => "FAIL ",
CaseStatus::KnownIssue => "KNOWN-ISSUE",
};
if r.reason.is_empty() {
println!(" [{tag}] {}", r.label);
} else {
println!(" [{tag}] {} — {}", r.label, r.reason);
}
}
println!("=======================================");
println!();
}
#[test]
fn linearize_qpdf_check_matrix() {
if skip_if_qpdf_missing() {
return;
}
let fixtures: &[(&str, &str)] = &[
("one-page.pdf", "(a) single-page"),
("two-page.pdf", "(a) multi-page (2 pages)"),
("three-page.pdf", "(a) multi-page (3 pages)"),
];
let tmp = tempdir().unwrap();
let mut results: Vec<CaseResult> = Vec::new();
for (fixture_name, label) in fixtures {
let input = fixture_path(fixture_name);
let output = tmp.path().join(format!("linearized-{fixture_name}"));
let success = linearize_via_flpdf(&input, &output);
if !success {
results.push(CaseResult::fail(
*label,
"flpdf --linearize exited with non-zero status",
));
continue;
}
let verdict = qpdf_linearization_verdict(&output);
match &verdict {
Verdict::Pass => {
results.push(CaseResult::pass(*label));
}
Verdict::Warn(msg) => results.push(classify_qpdf_warning(label, msg)),
Verdict::Fail(msg) => {
results.push(CaseResult::fail(*label, format!("qpdf hard fail: {msg}")));
}
Verdict::NotLinearized => {
results.push(CaseResult::fail(
*label,
"flpdf output is not recognized as linearized",
));
}
}
}
print_summary(&results);
let hard_failures: Vec<&CaseResult> = results
.iter()
.filter(|r| matches!(r.status, CaseStatus::Fail))
.collect();
if !hard_failures.is_empty() {
let msgs: Vec<_> = hard_failures.iter().map(|r| r.label.as_str()).collect();
panic!(
"(a) hard failures that are not categorised as known issues: {:?}",
msgs
);
}
}
#[test]
fn non_linear_collapse_from_qpdf_linearized() {
if skip_if_qpdf_missing() {
return;
}
let tmp = tempdir().unwrap();
let source = fixture_path("one-page.pdf");
let qpdf_linearized = tmp.path().join("qpdf-linearized.pdf");
qpdf_linearize(&source, &qpdf_linearized);
let (check_exit, check_output) = run_qpdf_check(&qpdf_linearized);
assert_eq!(
check_exit, 0,
"(b) pre-condition: qpdf --linearize output should be valid, got: {check_output}"
);
assert!(
!check_output.contains("is not linearized"),
"(b) pre-condition: qpdf --linearize output must be linearized"
);
let flpdf_out = tmp.path().join("flpdf-collapsed.pdf");
let rewrite_ok = rewrite_via_flpdf(&qpdf_linearized, &flpdf_out);
assert!(rewrite_ok, "(b) flpdf rewrite exited with non-zero status");
let (qpdf_exit, qpdf_output) = run_qpdf_check(&flpdf_out);
let verdict = qpdf_verdict(qpdf_exit, &qpdf_output);
assert_eq!(
verdict,
Verdict::NotLinearized,
"(b) MUST PASS: flpdf rewrite (no --linearize) of qpdf-linearized PDF \
must produce a non-linearized output.\n\
qpdf exit={qpdf_exit}, output={qpdf_output}"
);
println!("(b) non-linear collapse from qpdf-linearized: OK");
}
#[test]
fn verdict_match_flpdf_vs_qpdf() {
if skip_if_qpdf_missing() {
return;
}
let fixtures = &["one-page.pdf", "two-page.pdf", "three-page.pdf"];
let tmp = tempdir().unwrap();
let mut results: Vec<CaseResult> = Vec::new();
for fixture_name in fixtures {
let input = fixture_path(fixture_name);
let linearized = tmp.path().join(format!("lin-{fixture_name}"));
let success = linearize_via_flpdf(&input, &linearized);
if !success {
results.push(CaseResult::fail(
format!("(c) {fixture_name}"),
"flpdf linearize failed, cannot compare verdicts",
));
continue;
}
let fv = flpdf_verdict(&linearized);
let qv = qpdf_linearization_verdict(&linearized);
let fv_pass = matches!(fv, Verdict::Pass | Verdict::Warn(_));
let qv_pass = matches!(qv, Verdict::Pass | Verdict::Warn(_));
let label = format!("(c) verdict match — {fixture_name}");
if fv_pass == qv_pass {
results.push(CaseResult::pass(label));
} else {
let detail = format!(
"flpdf={} qpdf={}",
if fv_pass { "Pass/Warn" } else { "Fail" },
if qv_pass { "Pass/Warn" } else { "Fail" }
);
results.push(CaseResult::fail(
label,
format!("verdict mismatch between flpdf and qpdf: {detail}"),
));
}
}
print_summary(&results);
let mismatches: Vec<&CaseResult> = results
.iter()
.filter(|r| matches!(r.status, CaseStatus::Fail))
.collect();
if !mismatches.is_empty() {
let msgs: Vec<_> = mismatches.iter().map(|r| r.label.as_str()).collect();
panic!(
"(c) verdict mismatches between flpdf and qpdf (regressions): {:?}",
msgs
);
}
}
#[test]
fn non_linear_collapse_multi_page() {
if skip_if_qpdf_missing() {
return;
}
let tmp = tempdir().unwrap();
let mut results: Vec<CaseResult> = Vec::new();
let fixtures = &["two-page.pdf", "three-page.pdf"];
for fixture_name in fixtures {
let source = fixture_path(fixture_name);
let qpdf_linearized = tmp.path().join(format!("qpdf-lin-{fixture_name}"));
let flpdf_out = tmp.path().join(format!("flpdf-collapsed-{fixture_name}"));
qpdf_linearize(&source, &qpdf_linearized);
let success = rewrite_via_flpdf(&qpdf_linearized, &flpdf_out);
if !success {
results.push(CaseResult::fail(
format!("(b) multi-page collapse — {fixture_name}"),
"flpdf rewrite exited with non-zero status",
));
continue;
}
let (qpdf_exit, qpdf_output) = run_qpdf_check(&flpdf_out);
let verdict = qpdf_verdict(qpdf_exit, &qpdf_output);
let label = format!("(b) non-linear collapse — {fixture_name}");
if verdict == Verdict::NotLinearized {
results.push(CaseResult::pass(label));
} else {
results.push(CaseResult::fail(
label,
format!("expected NotLinearized, got {:?}", verdict),
));
}
}
print_summary(&results);
let failures: Vec<_> = results
.iter()
.filter(|r| matches!(r.status, CaseStatus::Fail))
.map(|r| r.label.as_str())
.collect();
assert!(
failures.is_empty(),
"(b) non-linear collapse MUST PASS for all fixtures, failing: {:?}",
failures
);
}
#[test]
fn classify_unknown_warning_fails() {
let r = classify_qpdf_warning("(a) test", "some unrelated qpdf warning text");
assert!(
matches!(r.status, CaseStatus::Fail),
"unknown qpdf warning must be CaseStatus::Fail, got {:?}",
r.reason
);
assert!(
r.reason.contains("unexpected qpdf warning"),
"reason text should name it as unexpected, got: {}",
r.reason
);
}
#[test]
fn classify_hint_table_warning_is_known() {
let r = classify_qpdf_warning(
"(a) test",
"WARNING: file: hint table length mismatch detected",
);
assert!(
matches!(r.status, CaseStatus::Fail),
"hint-table-length-mismatch is no longer a known issue — must be Fail"
);
}
fn qpdf_show_linearization_content_lengths(path: &Path) -> Vec<u64> {
let out = ShellCommand::new("qpdf")
.args(["--show-linearization", path.to_str().unwrap()])
.output()
.expect("failed to spawn qpdf --show-linearization");
assert!(
out.status.success(),
"qpdf --show-linearization failed: exit={:?}, stderr={}, stdout={}",
out.status.code(),
String::from_utf8_lossy(&out.stderr),
String::from_utf8_lossy(&out.stdout)
);
let stdout = String::from_utf8_lossy(&out.stdout);
stdout
.lines()
.filter_map(|line| {
let trimmed = line.trim_start();
trimmed
.strip_prefix("content_length:")
.map(|rest| rest.trim().parse::<u64>().expect("parse content_length"))
})
.collect()
}
#[test]
fn linearize_populates_per_page_content_length() {
if skip_if_qpdf_missing() {
return;
}
let tmp = tempdir().unwrap();
for fixture_name in &["one-page.pdf", "two-page.pdf", "three-page.pdf"] {
let input = fixture_path(fixture_name);
let output = tmp.path().join(format!("lin-{fixture_name}"));
let ok = linearize_via_flpdf(&input, &output);
assert!(ok, "flpdf --linearize {fixture_name} failed");
assert_eq!(
qpdf_linearization_verdict(&output),
Verdict::Pass,
"qpdf --check-linearization regressed on {fixture_name}"
);
let lengths = qpdf_show_linearization_content_lengths(&output);
assert!(
!lengths.is_empty(),
"qpdf --show-linearization on {fixture_name} produced no \
content_length entries"
);
for (i, &len) in lengths.iter().enumerate() {
assert!(
len > 0,
"page {i} of {fixture_name} has content_length=0; \
expected a positive content_length, got {lengths:?}"
);
}
}
}
#[test]
fn linearize_failure_stderr_matches_qpdf() {
if skip_if_qpdf_missing() {
return;
}
let tmp = tempdir().unwrap();
for fixture in [
"adbe-orphan-url.pdf",
"compressible-stale-generation-alias.pdf",
"null-visible-stale-generation.pdf",
] {
let input = fixture_path(fixture);
let theirs = tmp.path().join("qpdf-out.pdf");
let ours = tmp.path().join("flpdf-out.pdf");
let expected = ShellCommand::new("qpdf")
.args(["--deterministic-id", "--linearize"])
.arg(&input)
.arg(&theirs)
.output()
.expect("qpdf runs");
assert_eq!(
expected.status.code(),
Some(2),
"{fixture}: qpdf must fail to linearize this fixture"
);
let actual = CargoCommand::cargo_bin("flpdf")
.unwrap()
.args(["--deterministic-id", "--linearize"])
.arg(&input)
.arg(&ours)
.output()
.expect("flpdf runs");
assert_eq!(
actual.status.code(),
expected.status.code(),
"{fixture}: exit code must match qpdf"
);
let expected_stderr = String::from_utf8_lossy(&expected.stderr).replace("qpdf:", "<prog>:");
let actual_stderr = String::from_utf8_lossy(&actual.stderr).replace("flpdf:", "<prog>:");
assert_eq!(
actual_stderr, expected_stderr,
"{fixture}: stderr must match qpdf apart from the program name"
);
}
}