Mocking Python Files

Monday, 29 June 2009

Just a quick note on testing python; I needed to test a method the reads in from a file. To do that I could either created a temp file or use stringio. Stringio is easier and quicker so I used that, here's how:


def mockfile(text):
return StringIO.StringIO(text)

class Tester1(unittest.TestCase):
def setUp(self):
self.filehandle = mockfile("""
gen , G1 , 101 , 450 , 50 , U20""")
self.components = read(self.filehandle)

def tearDown(self):
self.filehandle.close()
self.filehandle = None
self.components = None

def test_name(self):
self.assertEqual(set(self.components.keys()),
set("G1"))


class Tester2(unittest.TestCase):
def test_a(self):
components = read(mockfile(""))
self.assertEqual(len(components),0)


Hopefully I this is the first in a series of posts on practical TDD. Watch this space

0 comments

Post a Comment