How to unit test a Python function that draws PDF graphics?

前端 未结 5 1888
悲&欢浪女
悲&欢浪女 2020-12-09 10:01

I\'m writing a CAD application that outputs PDF files using the Cairo graphics library. A lot of the unit testing does not require actually generating the PDF files, such as

5条回答
  •  旧巷少年郎
    2020-12-09 10:32

    I wrote a tool in Python to validate PDFs for my employer's documentation. It has the capability to compare individual pages to master images. I used a library I found called swftools to export the page to PNG, then used the Python Imaging Library to compare it with the master.

    The relevant code looks something like this (this won't run as there are some dependencies on other parts of the script, but you should get the idea):

    # exporting
    
    gfxpdf = gfx.open("pdf", self.pdfpath)
    if os.path.isfile(pngPath):
        os.remove(pngPath)
    page = gfxpdf.getPage(pagenum)
    img = gfx.ImageList()
    img.startpage(page.width, page.height)
    page.render(img)
    img.endpage()
    img.save(pngPath)
    return os.path.isfile(pngPath)
    
    # comparing
    
    outPng = os.path.join(outpath, pngname)
    masterPng = os.path.join(outpath, "_master", pngname)
    if os.path.isfile(masterPng):
        output = Image.open(outPng).convert("RGB") # discard alpha channel, if any
        master = Image.open(masterPng).convert("RGB")
        mismatch = any(x[1] for x in ImageChops.difference(output, master).getextrema())
    

提交回复
热议问题