use assert_cmd::Command;
use predicates::prelude::*;
use std::io::Write;
use std::process::{Command as ShellCommand, Output};
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_qdf 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 qpdf_check(path: &std::path::Path) -> std::process::ExitStatus {
ShellCommand::new("qpdf")
.args(["--check", path.to_str().unwrap()])
.status()
.expect("failed to spawn qpdf")
}
fn run_qdf_qpdf(extra: &[&str], input: &std::path::Path, output: &std::path::Path) -> Output {
ShellCommand::new("qpdf")
.args(extra)
.args(["--qdf", input.to_str().unwrap(), output.to_str().unwrap()])
.output()
.expect("qpdf should spawn")
}
fn run_qdf_flpdf(extra: &[&str], input: &std::path::Path, output: &std::path::Path) -> Output {
let mut command = Command::cargo_bin("flpdf").expect("flpdf binary should build");
command
.env("FLPDF_PROGNAME", "qpdf")
.arg("qdf")
.args(extra)
.args([input.to_str().unwrap(), output.to_str().unwrap()]);
command.output().expect("flpdf should spawn")
}
fn normalize_qdf_diagnostic(bytes: &[u8], output: &std::path::Path) -> Vec<u8> {
let output = output.to_string_lossy().as_bytes().to_vec();
let mut normalized = Vec::with_capacity(bytes.len());
let mut remaining = bytes;
while let Some(position) = remaining
.windows(output.len())
.position(|window| window == output.as_slice())
{
normalized.extend_from_slice(&remaining[..position]);
normalized.extend_from_slice(b"<output>");
remaining = &remaining[position + output.len()..];
}
normalized.extend_from_slice(remaining);
normalized
}
fn fixture_with_stream() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let objects: Vec<Vec<u8>> = vec![
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << >> /Contents 4 0 R >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Length 9 >>\nstream\nHello PDF\nendstream\nendobj\n".to_vec(),
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::with_capacity(objects.len() + 1);
for object in &objects {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(format!("{:010} 65535 f\n", 0).as_bytes());
for &offset in &offsets {
bytes.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
start_xref
)
.as_bytes(),
);
fixture.as_file_mut().write_all(&bytes).unwrap();
fixture
}
fn assert_canonical_qdf(rendered: &[u8]) {
let contains = |needle: &[u8]| rendered.windows(needle.len()).any(|w| w == needle);
assert!(contains(b"%QDF-1.0"), "expected %QDF-1.0 header marker");
assert!(
contains(b"%% Original object ID:"),
"expected %% Original object ID: comments"
);
assert!(
contains(b"\nxref\n"),
"expected a classic `xref` table keyword"
);
assert!(!contains(b"/Type /XRef"), "QDF must not use an xref stream");
assert!(
!contains(b"/Type /ObjStm"),
"QDF must not use object streams"
);
let has_indirect_length = rendered
.windows(b"/Length ".len())
.enumerate()
.filter(|(_, w)| *w == b"/Length ")
.any(|(i, _)| {
let tail = &rendered[i + b"/Length ".len()..];
let mut j = 0;
while j < tail.len() && tail[j].is_ascii_digit() {
j += 1;
}
j > 0 && tail[j..].starts_with(b" 0 R")
});
assert!(
has_indirect_length,
"expected an indirect `/Length H 0 R` stream length"
);
}
fn strip_id_line(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len());
for line in bytes.split_inclusive(|&b| b == b'\n') {
if line.windows(4).any(|w| w == b"/ID ") {
continue;
}
out.extend_from_slice(line);
}
out
}
#[test]
fn rewrite_qdf_produces_canonical_qdf() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let rendered = std::fs::read(&output).unwrap();
assert_canonical_qdf(&rendered);
if skip_if_qpdf_missing() {
return;
}
assert!(
qpdf_check(&output).success(),
"qpdf --check should pass on rewrite --qdf output"
);
}
#[test]
fn top_level_qdf_matches_rewrite_qdf() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let rewrite_out = temp.path().join("rewrite.pdf");
let toplevel_out = temp.path().join("toplevel.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
input.path().to_str().unwrap(),
rewrite_out.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--qdf",
input.path().to_str().unwrap(),
toplevel_out.to_str().unwrap(),
])
.assert()
.success();
let a = strip_id_line(&std::fs::read(&rewrite_out).unwrap());
let b = strip_id_line(&std::fs::read(&toplevel_out).unwrap());
assert_eq!(
a, b,
"top-level --qdf must be identical to `rewrite --qdf` (modulo /ID)"
);
assert_canonical_qdf(&std::fs::read(&toplevel_out).unwrap());
}
#[test]
fn qdf_subcommand_is_alias_of_rewrite_qdf() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let rewrite_out = temp.path().join("rewrite.pdf");
let subcmd_out = temp.path().join("sub.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
input.path().to_str().unwrap(),
rewrite_out.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"qdf",
input.path().to_str().unwrap(),
subcmd_out.to_str().unwrap(),
])
.assert()
.success();
let a = strip_id_line(&std::fs::read(&rewrite_out).unwrap());
let b = strip_id_line(&std::fs::read(&subcmd_out).unwrap());
assert_eq!(
a, b,
"`qdf` subcommand must be a byte-for-byte alias of `rewrite --qdf` \
(modulo the per-process random trailer /ID)"
);
}
#[test]
fn qdf_subcommand_uses_the_canonical_job_writer_route() {
let source = include_str!("../src/main.rs");
let start = source
.find("fn run_qdf(")
.expect("qdf subcommand route should remain named");
let body = source[start..]
.split_once("\nfn run_qdf_fix")
.expect("qdf-fix should follow the qdf route")
.0;
assert!(
body.contains("run_rewrite("),
"qdf must enter the canonical QPDFJob rewrite lifecycle"
);
assert!(
!body.contains("write_with_pdf_writer("),
"qdf must not retain a direct PdfWriter consumer"
);
}
#[test]
fn qdf_subcommand_matches_qpdf_process_contracts() {
if skip_if_qpdf_missing() {
return;
}
let temp = tempfile::tempdir().unwrap();
let clean = fixture_with_stream();
let repaired = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/test_driver/repairable_input.pdf");
let encrypted = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/encrypted/v5-aes-256-r6.pdf");
let unreferenced = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/unref-resources-one-page.pdf");
let cases: [(&str, &[&str], &[&str], &std::path::Path); 4] = [
("clean", &[], &[], clean.path()),
("repaired", &[], &["--repair"], repaired.as_path()),
(
"encrypted",
&["--password=user-v5-r6"],
&["--password=user-v5-r6"],
encrypted.as_path(),
),
(
"preserve-unreferenced",
&["--preserve-unreferenced"],
&["--preserve-unreferenced"],
unreferenced.as_path(),
),
];
for (name, qpdf_extra, flpdf_extra, input) in cases {
let qpdf_output = temp.path().join(format!("qpdf-{name}.pdf"));
let flpdf_output = temp.path().join(format!("flpdf-{name}.pdf"));
let qpdf = run_qdf_qpdf(qpdf_extra, input, &qpdf_output);
let flpdf = run_qdf_flpdf(flpdf_extra, input, &flpdf_output);
assert_eq!(flpdf.status.code(), qpdf.status.code(), "qdf {name} status");
assert_eq!(flpdf.stdout, qpdf.stdout, "qdf {name} stdout");
assert_eq!(
normalize_qdf_diagnostic(&flpdf.stderr, &flpdf_output),
normalize_qdf_diagnostic(&qpdf.stderr, &qpdf_output),
"qdf {name} stderr"
);
assert!(
matches!(qpdf.status.code(), Some(0) | Some(3)),
"qpdf qdf {name} should succeed or report repair warnings"
);
assert!(
matches!(flpdf.status.code(), Some(0) | Some(3)),
"flpdf qdf {name} should succeed or report repair warnings"
);
assert_eq!(
strip_id_line(&std::fs::read(&flpdf_output).unwrap()),
strip_id_line(&std::fs::read(&qpdf_output).unwrap()),
"qdf {name} output"
);
}
let missing = temp.path().join("missing-directory");
let qpdf_output = missing.join("qpdf.pdf");
let flpdf_output = missing.join("flpdf.pdf");
let qpdf = run_qdf_qpdf(&[], clean.path(), &qpdf_output);
let flpdf = run_qdf_flpdf(&[], clean.path(), &flpdf_output);
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"qdf output-open status"
);
assert_eq!(flpdf.stdout, qpdf.stdout, "qdf output-open stdout");
assert_eq!(
normalize_qdf_diagnostic(&flpdf.stderr, &flpdf_output),
normalize_qdf_diagnostic(&qpdf.stderr, &qpdf_output),
"qdf output-open stderr"
);
}
#[test]
fn qdf_reentrant_signature_matches_qpdf_expected_endobj_warning() {
if skip_if_qpdf_missing() {
return;
}
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/encrypted-indirect-type-signature.pdf");
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf = run_qdf_qpdf(&[], &fixture, &qpdf_output);
let flpdf = run_qdf_flpdf(&[], &fixture, &flpdf_output);
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(
normalize_qdf_diagnostic(&flpdf.stderr, &flpdf_output),
normalize_qdf_diagnostic(&qpdf.stderr, &qpdf_output),
"re-entrant parsing must still reach qpdf's trailing endobj check"
);
}
#[test]
fn qdf_fix_repairs_hand_edited_stream_length() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let qdf_out = temp.path().join("qdf.pdf");
let edited = temp.path().join("edited.pdf");
let fixed = temp.path().join("fixed.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
input.path().to_str().unwrap(),
qdf_out.to_str().unwrap(),
])
.assert()
.success();
let original = std::fs::read(&qdf_out).unwrap();
let edited_bytes = {
let from = b"stream\nHello PDF\nendstream".as_slice();
let to = b"stream\nHello PDF EDITED!!!\nendstream".as_slice();
let pos = original
.windows(from.len())
.position(|w| w == from)
.expect("stream payload present in QDF output");
let mut v = original[..pos].to_vec();
v.extend_from_slice(to);
v.extend_from_slice(&original[pos + from.len()..]);
v
};
std::fs::write(&edited, &edited_bytes).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["qdf-fix", edited.to_str().unwrap(), fixed.to_str().unwrap()])
.assert()
.success();
if skip_if_qpdf_missing() {
return;
}
assert!(
!qpdf_check(&edited).success(),
"the hand-edited (unfixed) QDF should fail qpdf --check"
);
assert!(
qpdf_check(&fixed).success(),
"qdf-fix output should pass qpdf --check"
);
}
#[test]
fn qdf_object_streams_generate_matches_qpdf() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
"--object-streams=generate",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success()
.stderr(predicate::str::is_empty());
let rendered = std::fs::read(&output).unwrap();
assert!(
rendered
.windows(b"/Type /ObjStm".len())
.any(|w| w == b"/Type /ObjStm"),
"QDF + --object-streams=generate must emit ObjStm"
);
assert!(
rendered
.windows(b"/Type /XRef".len())
.any(|w| w == b"/Type /XRef"),
"QDF + --object-streams=generate must emit an xref stream"
);
assert!(!rendered
.windows(b"\nxref\n".len())
.any(|w| w == b"\nxref\n"));
}
#[test]
fn qdf_generate_preserves_nonzero_original_generation_marker() {
if skip_if_qpdf_missing() {
return;
}
let input = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/null-visible-stale-generation.pdf");
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf = ShellCommand::new("qpdf")
.args([
"--qdf",
"--object-streams=generate",
"--static-id",
input.to_str().unwrap(),
qpdf_output.to_str().unwrap(),
])
.status()
.expect("failed to spawn qpdf");
assert!(qpdf.success(), "qpdf QDF generation failed");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
"--object-streams=generate",
"--static-id",
input.to_str().unwrap(),
flpdf_output.to_str().unwrap(),
])
.assert()
.success();
assert_eq!(
std::fs::read(&flpdf_output).unwrap(),
std::fs::read(&qpdf_output).unwrap(),
"QDF Generate must preserve non-zero original object generations"
);
}
#[test]
fn qdf_object_streams_generate_matches_qpdf_at_the_batch_cap_boundary() {
if skip_if_qpdf_missing() {
return;
}
let input = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/objstm-lin-cap-boundary-199-bearing.pdf");
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf_status = ShellCommand::new("qpdf")
.args([
"--qdf",
"--object-streams=generate",
"--static-id",
input.to_str().unwrap(),
qpdf_output.to_str().unwrap(),
])
.status()
.expect("failed to spawn qpdf");
assert!(qpdf_status.success(), "qpdf QDF generation failed");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
"--object-streams=generate",
"--static-id",
input.to_str().unwrap(),
flpdf_output.to_str().unwrap(),
])
.assert()
.success();
let check = ShellCommand::new("qpdf")
.args(["--check", flpdf_output.to_str().unwrap()])
.output()
.expect("failed to spawn qpdf --check");
assert!(
check.status.success(),
"QDF ObjStm output must pass qpdf --check:\n{}",
String::from_utf8_lossy(&check.stdout)
);
assert_eq!(
std::fs::read(&flpdf_output).unwrap(),
std::fs::read(&qpdf_output).unwrap(),
"QDF ObjStm output must match qpdf at the 100-member split boundary"
);
}
#[test]
fn qdf_object_streams_preserve_matches_qpdf_at_the_batch_cap_boundary() {
if skip_if_qpdf_missing() {
return;
}
let input = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/objstm-lin-cap-boundary-199-bearing.pdf");
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf_status = ShellCommand::new("qpdf")
.args([
"--qdf",
"--object-streams=preserve",
"--static-id",
input.to_str().unwrap(),
qpdf_output.to_str().unwrap(),
])
.status()
.expect("failed to spawn qpdf");
assert!(qpdf_status.success(), "qpdf QDF preservation failed");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
"--object-streams=preserve",
"--static-id",
input.to_str().unwrap(),
flpdf_output.to_str().unwrap(),
])
.assert()
.success();
let check = ShellCommand::new("qpdf")
.args(["--check", flpdf_output.to_str().unwrap()])
.output()
.expect("failed to spawn qpdf --check");
assert!(
check.status.success(),
"QDF Preserve output must pass qpdf --check:\n{}{}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
assert_eq!(
std::fs::read(&flpdf_output).unwrap(),
std::fs::read(&qpdf_output).unwrap(),
"QDF Preserve output must match qpdf at the 100-member split boundary"
);
}
#[test]
fn qdf_object_streams_preserve_keeps_a_source_container_over_100_members() {
if skip_if_qpdf_missing() {
return;
}
let input = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/null-visible-preserve-over-100.pdf");
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf_status = ShellCommand::new("qpdf")
.args([
"--qdf",
"--object-streams=preserve",
"--static-id",
input.to_str().unwrap(),
qpdf_output.to_str().unwrap(),
])
.status()
.expect("failed to spawn qpdf");
assert!(qpdf_status.success(), "qpdf QDF preservation failed");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
"--object-streams=preserve",
"--static-id",
input.to_str().unwrap(),
flpdf_output.to_str().unwrap(),
])
.assert()
.success();
let check = ShellCommand::new("qpdf")
.args(["--check", flpdf_output.to_str().unwrap()])
.output()
.expect("failed to spawn qpdf --check");
assert!(
check.status.success(),
"QDF Preserve output must pass qpdf --check:\n{}{}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
assert_eq!(
std::fs::read(&flpdf_output).unwrap(),
std::fs::read(&qpdf_output).unwrap(),
"QDF Preserve must retain a source ObjStm with more than 100 members"
);
}
#[test]
fn qdf_object_streams_disable_matches_qpdf() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
"--object-streams=disable",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success()
.stderr(predicate::str::is_empty());
let rendered = std::fs::read(&output).unwrap();
assert!(!rendered
.windows(b"/Type /ObjStm".len())
.any(|w| w == b"/Type /ObjStm"));
assert!(!rendered
.windows(b"/Type /XRef".len())
.any(|w| w == b"/Type /XRef"));
}
#[test]
fn qdf_linearize_matches_qpdf_rewrite() {
if skip_if_qpdf_missing() {
return;
}
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--static-id", "--qdf", "--linearize"])
.arg(input.path())
.arg(&qpdf_output)
.output()
.expect("failed to spawn qpdf");
assert!(qpdf.status.success(), "qpdf QDF linearization failed");
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args([
"rewrite",
"--static-id",
"--qdf",
"--linearize",
input.path().to_str().unwrap(),
flpdf_output.to_str().unwrap(),
])
.output()
.unwrap();
assert!(
flpdf.status.success(),
"flpdf QDF linearization failed: {}",
String::from_utf8_lossy(&flpdf.stderr)
);
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
let check = qpdf_check(&flpdf_output);
assert!(
check.success(),
"flpdf QDF linearized output must pass qpdf --check"
);
let rendered = std::fs::read(&flpdf_output).unwrap();
assert!(!rendered.starts_with(b"%QDF-"));
assert!(!rendered
.windows(b"Original object ID".len())
.any(|window| { window == b"Original object ID" }));
#[cfg(feature = "qpdf-zlib-compat")]
assert_eq!(
rendered,
std::fs::read(&qpdf_output).unwrap(),
"rewrite --qdf --linearize must match qpdf after QDF is dropped"
);
}
#[test]
fn qdf_linearize_matches_qpdf_top_level() {
if skip_if_qpdf_missing() {
return;
}
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--static-id", "--qdf", "--linearize"])
.arg(input.path())
.arg(&qpdf_output)
.output()
.expect("failed to spawn qpdf");
assert!(qpdf.status.success(), "qpdf QDF linearization failed");
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args([
"--static-id",
"--qdf",
"--linearize",
input.path().to_str().unwrap(),
flpdf_output.to_str().unwrap(),
])
.output()
.unwrap();
assert!(
flpdf.status.success(),
"flpdf QDF linearization failed: {}",
String::from_utf8_lossy(&flpdf.stderr)
);
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
let check = qpdf_check(&flpdf_output);
assert!(
check.success(),
"flpdf QDF linearized output must pass qpdf --check"
);
let rendered = std::fs::read(&flpdf_output).unwrap();
assert!(!rendered.starts_with(b"%QDF-"));
assert!(!rendered
.windows(b"Original object ID".len())
.any(|window| { window == b"Original object ID" }));
#[cfg(feature = "qpdf-zlib-compat")]
assert_eq!(
rendered,
std::fs::read(&qpdf_output).unwrap(),
"top-level --qdf --linearize must match qpdf after QDF is dropped"
);
}
#[test]
fn qdf_page_ops_is_applied_top_level() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--qdf",
"--rotate=+90",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
assert_canonical_qdf(&std::fs::read(output).unwrap());
}
#[test]
fn qdf_split_pages_applies_qdf_to_every_chunk() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--qdf",
"--split-pages=1",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let chunk = temp.path().join("out-1.pdf");
assert!(chunk.exists(), "split operation must write the first chunk");
let rendered = std::fs::read(&chunk).unwrap();
assert_canonical_qdf(&rendered);
if !skip_if_qpdf_missing() {
assert!(
qpdf_check(&chunk).success(),
"qpdf must accept every QDF split chunk"
);
}
let top_level_temp = tempfile::tempdir().unwrap();
let top_level_output = top_level_temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--qdf",
"--split-pages=1",
input.path().to_str().unwrap(),
top_level_output.to_str().unwrap(),
])
.assert()
.success();
assert_canonical_qdf(&std::fs::read(top_level_temp.path().join("out-1.pdf")).unwrap());
}
#[test]
fn qdf_split_pages_preserves_foreign_original_object_ids() {
if skip_if_qpdf_missing() {
return;
}
let input = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/three-page.pdf");
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--qdf", "--split-pages=1", "--static-id"])
.arg(&input)
.arg(&qpdf_output)
.output()
.expect("qpdf split should spawn");
assert!(
qpdf.status.success(),
"qpdf QDF split failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args(["rewrite", "--qdf", "--split-pages=1", "--static-id"])
.arg(&input)
.arg(&flpdf_output)
.output()
.unwrap();
assert!(
flpdf.status.success(),
"flpdf QDF split failed: {}",
String::from_utf8_lossy(&flpdf.stderr)
);
for page in 1..=3 {
let qpdf_chunk = temp.path().join(format!("qpdf-{page}.pdf"));
let flpdf_chunk = temp.path().join(format!("flpdf-{page}.pdf"));
assert_eq!(
std::fs::read(&flpdf_chunk).unwrap(),
std::fs::read(&qpdf_chunk).unwrap(),
"QDF split chunk {page} must preserve qpdf Original object IDs"
);
}
}
#[test]
fn top_level_double_dash_resets_to_main_options_like_qpdf() {
if skip_if_qpdf_missing() {
return;
}
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let qpdf_before_input = temp.path().join("qpdf-before-input.pdf");
let flpdf_before_input = temp.path().join("flpdf-before-input.pdf");
let qpdf_after_input = temp.path().join("qpdf-after-input.pdf");
let flpdf_after_input = temp.path().join("flpdf-after-input.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--", "--qdf", "--static-id"])
.arg(input.path())
.arg(&qpdf_before_input)
.output()
.expect("qpdf top-level section reset should spawn");
assert!(
qpdf.status.success(),
"qpdf top-level section reset failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args(["--", "--qdf", "--static-id"])
.arg(input.path())
.arg(&flpdf_before_input)
.output()
.unwrap();
assert!(
flpdf.status.success(),
"flpdf top-level section reset failed: {}",
String::from_utf8_lossy(&flpdf.stderr)
);
let qpdf = ShellCommand::new("qpdf")
.arg(input.path())
.args(["--", "--qdf", "--static-id"])
.arg(&qpdf_after_input)
.output()
.expect("qpdf post-input section reset should spawn");
assert!(
qpdf.status.success(),
"qpdf post-input section reset failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.arg(input.path())
.args(["--", "--qdf", "--static-id"])
.arg(&flpdf_after_input)
.output()
.unwrap();
assert!(
flpdf.status.success(),
"flpdf post-input section reset failed: {}",
String::from_utf8_lossy(&flpdf.stderr)
);
let qpdf_bytes = std::fs::read(&qpdf_before_input).unwrap();
assert_eq!(
qpdf_bytes,
std::fs::read(&qpdf_after_input).unwrap(),
"qpdf must treat top-level -- consistently before and after the input"
);
assert_eq!(
std::fs::read(&flpdf_before_input).unwrap(),
qpdf_bytes,
"flpdf must match qpdf after consuming a top-level --"
);
assert_eq!(
std::fs::read(&flpdf_after_input).unwrap(),
qpdf_bytes,
"flpdf must match qpdf when top-level -- follows the input"
);
}
#[test]
fn split_pages_reapplies_stream_data_policy_to_every_chunk() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--stream-data=uncompress",
"--split-pages=1",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let rendered = std::fs::read(temp.path().join("out-1.pdf")).unwrap();
assert!(
!rendered.windows(b"/Filter".len()).any(|w| w == b"/Filter"),
"--stream-data=uncompress must survive the final chunk writer"
);
}
#[test]
fn split_pages_reapplies_object_stream_mode_to_every_chunk() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--object-streams=generate",
"--split-pages=1",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let rendered = std::fs::read(temp.path().join("out-1.pdf")).unwrap();
assert!(
rendered
.windows(b"/Type /ObjStm".len())
.any(|w| w == b"/Type /ObjStm"),
"--object-streams=generate must survive the final chunk writer"
);
}
#[test]
fn split_pages_reapplies_newline_before_endstream_to_every_chunk() {
let input = fixture_with_stream();
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--newline-before-endstream=y",
"--split-pages=1",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let rendered = std::fs::read(temp.path().join("out-1.pdf")).unwrap();
assert!(
rendered
.windows(b"\nendstream".len())
.any(|w| w == b"\nendstream"),
"--newline-before-endstream=y must survive the final chunk writer"
);
}