Mocking Python Files

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 = None
self.components = None

def test_name(self):

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

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