StrugglingProgrammer
StrugglingProgrammer

Reputation: 758

How to write tests for writers / parsers? (Python)

I have written a piece of software in Python that does a lot of parsing and a lot of writing files to disk. I am starting to write unit tests, but have no idea how to unit test a function that just writes some data to disk, and returns nothing.

I am familiar with unittest and ddt. Any advice or even a link to a resource where I could learn more would be appreciated.

Upvotes: 1

Views: 385

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386020

Arguably, the best solution is to split your function into two pieces. One piece to do the parsing, the second to do the writing. Then, you can unit test each piece separately.

For the first piece, give it a file and verify the parsing function returns the proper string, and/or throws the proper exception.

For the second, give it a string to write, and then verify that the file was written and that the contents match your string. It's tempting to skip the test that writes the data, since it's reasonable to assume that the python open and write functions work. However, the unit testing also proves that the data you pass in is the data that gets written (ie: you don't have a bug that causes a fixed string to be written to the file).

If refactoring the code isn't something you can do, you can still test the function. Feed it the data to be parsed, then open the file that it wrote to and compare the result to what you expect it to be.

Upvotes: 3

Related Questions