4 How can I unit test a Python function that draws PDF graphics?
4.1 Answer
I’m doing the same thing using a shell script on Linux that wraps
- ImageMagick’s
comparecommand - the
pdftkutility - Ghostscript (optionally)
(It would be rather easy to port this to a .bat Batch file for DOS/Windows.)
I have a few reference PDFs created by my application which are “known good”. Newly generated PDFs after code changes are compared to these reference PDFs. The comparison is done pixel by pixel and is saved as a new PDF. In this PDF, all unchanged pixels are painted in white, while all differing pixels are painted in red.
This method utilizes three different building blocks: pdftk, compare (part of ImageMagick) and Ghostscript.
pdftk
Use this command to split multipage PDF files into multiple singlepage PDFs:
compare
Use this command to create a “diff” PDF page for each of the pages:
Ghostscript
Because of automatically inserted meta data (such as the current date+time), PDF output is not working well for MD5hash-based file comparisons.
If you want to automatically discover all cases which consist of purely white pages, you could also convert to a meta-data free bitmap format using the bmp256 output device.
You can do that for the original PDFs (reference and comparison), or for the diff-PDF pages:
If the MD5sum is what you expect for an all-white page of 595x842 PostScript points, then your unit test passed.