unittest of file-reading function

Kent Johnson kent37 at tds.net
Tue Oct 18 16:41:48 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?

If you can refactor openFileAndProcessContents() so it looks like this:
def openFileAndProcessContents(filename):
  data = open(filename).read()
  processContents(data)

then you can write your tests against processContents() and just pass it a string with the test data.

I usually have a set of test files as part of my project that I can pass to functions like this.

Kent



More information about the Python-list mailing list