How to write CLI tests for PyPDFForm
masterCLI tests follow a four-step pattern:
- Define the expected PDF file.
- Write input data (e.g., YAML) to
tmp_path. - Invoke the CLI command using
typer.testing.CliRunner. - Compare the generated PDF with the expected file.
Key requirements:
- Mark tests with
@pytest.mark.cli_test. - Use
CliRunnerfromtyper.testing. - Import
cli_appfromPyPDFForm.cli.root.
Example implementation:
@pytest.mark.cli_test
def test_fill(pdf_samples, tmp_path):
expected_path = os.path.join(pdf_samples, "docs", "test_fill_text_check.pdf")
input_path = os.path.join(tmp_path, "input.yaml")
output_path = os.path.join(tmp_path, "output.pdf")
fill_data = {
"test": "test_1",
"check": True,
"test_2": "test_2",
"check_2": False,
"test_3": "test_3",
"check_3": True,
}
with open(input_path, "w") as f:
yaml.safe_dump(fill_data, f)
result = runner.invoke(
cli_app,
[
"fill",
os.path.join(pdf_samples, "sample_template.pdf"),
"-f",
input_path,
"-o",
output_path,
],
)
assert result.exit_code == 0
with open(expected_path, "rb") as f1, open(output_path, "rb") as f2:
expected = f1.read()
actual = f2.read()
assert len(expected) == len(actual)
assert expected == actual