Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i unit test a docx generation function

I'm creating a small program that generate a report as a .docx file with the python-docx-template library. In this program i have a function that generates this report with different values and pictures (which are placed in a dummy logo placeholder).

What would be the best way to unit test this function ?

I first thought of generating a report and compare it with an expected one but I'm still not sure how i would proceed to make this check.

Here's the function in question :

def generate_report(name, logo):
    doc = DocxTemplate("templates/template.docx")
    context = { 'name' : name,
                'stat1': "955$",
                'stat2': "800$"
            }

    with Image.open(logo) as logo:
        padded_logo = pad_logo(logo)
        buffered_logo = image_to_bytes_buffer(padded_logo)

        doc.replace_pic('dummy', buffered_logo)
        doc.render(context)
        doc.save("output/generated_doc.docx")
        padded_logo.close()
        buffered_logo.close()
like image 366
SevenMax Avatar asked May 21 '26 11:05

SevenMax


1 Answers

After rendering and saving the DocxTemplate object, you can access the doc.docx attribute which is a Document object from the python-docx package (internally used by the docxtpl). Having the Document, you have an awkward access to the inner XML based structure of your docx document through the _element attribute of the Document. Furthermore, _element.body seems to give you access to the XML tree representing the content of the document. In your test, you would then check if your expected elements are in the tree. This requires a bit of knowledge about the docx XML, which I can't help you with as I'm trying to figure it out myself, but here are some examples of simple things I've found useful.

# This seems to be the entry point to the content XML
body = doc.docx._element.body

# All XML elements have `.xml` which gives you the XML content as a string
body.xml

# You might have a paragraph as the first element in your body which has .text
# which you could assert
assert body[0].text == "Expected text"

The documentation for the XML tree is lacking as it's not part of the public interface of the python-docx package, but the code seems relatively easy to follow. E.g. check https://python-docx.readthedocs.io/en/latest/_modules/docx/text/paragraph.html#Paragraph for the code for the class representing a paragraph.

Happy exploring!

like image 84
Rubinous Avatar answered May 24 '26 01:05

Rubinous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!