I am writing a wrapper for the ConfigParser in Python to provide an easy interface for storing and retrieving application settings.
The wrapper has two methods, read and write, and a set of properties for the different application settings.
The write method is just a wrapper for the ConfigParser‘s write method with the addition of also creating the file object needed by the ConfigParser. It looks like this:
def write(self):
f = open(self.path, "w")
try:
self.config_parser.write(f)
finally:
f.close()
I would like to write a unit test that asserts that this method raises an IOError if the file could not be written to and in the other case that the write method of the config parser was called.
The second test is quite easy to handle with a mock object. But the open call makes things a little tricky. Eventually I have to create a file object to pass to the config parser. The fact that a file will actually be created when running this code doesn’t make it very useful for a unit test. Is there some strategy for mocking file creation? Can this piece of code be tested in some way? Or is it just too simple to be tested?
First, you don’t actually need to unit test
open(), since it’s pretty reasonable to assume that the standard library is correct.Next, you don’t want to do file system manipulations to get
open()to generate the error you want, because then you’re not unit testing, you’re doing a functional/integration test by including the file system.So you could perhaps replace
open()in the global namespace with a surrogate that just raises anIOError. Though, probably need to make sure you put things back if execution continues.But in the end, what value does the test have? There’s so little in that code snippet that’s your own system. Even replacing
open()really just ends up being a test that says “does thetryandfinallystatement in Python work?”My suggestion? Just add a statement to the docstring that records your expectation. “Raises an IOError if the file can’t be written.” Then move on. You can add a unit test later if this method gains some complexity (and merit for testing).