Skip to main content

test data for unittest.TestCase

Trivial but useful.

Recently I needed to test the behavior of the function that fetched some remote resource. I wanted to control how it works and supply my own cached version stored as a file.

While I originally thought unittest should support this using some sort of a method to get testdata directory, it is actually quite easy to implement. You only need to create some folder (I called it “testdata”) in the “tests” directory and then you can refer to it using plain old reference to __file__:

import os
...
testdata_dir = os.path.dirname(__file__)
testfile = os.path.join(testdata_dir, 'somefile.xml')

It took a while to understand that I may simply use __file__ and don’t bother creating a HTTP server.

Disclaimer: No wheel was reinvented during these tests.

Comments

Comments powered by Disqus