unittest of file-reading function

Peter Hansen peter at engcorp.com
Tue Oct 18 14:49:47 CEST 2005


Helge Stenstroem wrote:
> Say I have a function
> 
> def f(filename):
>     result = openFileAndProcessContents(filename)
>     return result
> 
> Can that function be unit tested without having a real file as input?
> Something along the lines of
> 
> import unittest
> class tests(unittest.TestCase):
>     def test1(self):
>         fileContents = "bla bla bla\nmore bla bla bla"
>         ???   # make f read this string instead of opening a file
>         expected = expectedResult
>         result = f(filename)
>         self.assertEqual(result, expected)
> 
> One possibility would be to make the unit test write to a temporary
> file. Are there better alternatives?

The simplest approach is to use a StringIO.  Often that will require 
passing a "file" object to the routine instead of a file *name*, but 
often that's better anyway (decouples file management and parsing).

Another approach is to create a "mock file" object.  Depending on your 
needs, this can be a very simple or a very complex thing to do.  I can 
offer more detail/suggestions here if you need.

-Peter



More information about the Python-list mailing list