unittest of file-reading function
André Malo
auch-ich-m at g-kein-spam.com
Tue Oct 18 18:02:44 EDT 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?
You can also just replace or shadow the file/open builtin (that's what I'm
doing). Something like:
def test1(self):
import StringIO
fileContents = "bla bla bla\nmore bla bla bla"
def myfile(name, mode, buffering):
return StringIO.StringIO(fileContents)
testedmodule.file = myfile
try:
expected = expectedResult
result = f(filename)
finally:
del testedmodule.file
self.assertEqual(result, expected)
(if you're using open, replace .file with .open)
(testedmodule is of course the module where the file call happens)
nd
--
die (eval q-qq[Just Another Perl Hacker
]
;-)
# André Malo, <http://www.perlig.de/> #
More information about the Python-list
mailing list