klenwell information services : PythonBufferCapture

Python Buffer Capture

return to PythonTesting

A working example.

class BufferTestCase(unittest.TestCase):
   
    def openBuffer(self):
        import StringIO, sys
        self.old_buffer = sys.stdout
        sys.stdout = self.new_buffer = StringIO.StringIO()
        return self.old_buffer
   
    def closeBuffer(self):
        buffer_content = self.new_buffer.getvalue()
        sys.stdout = self.old_buffer
        self.new_buffer.close()
        return buffer_content
   
    def testBuffer(self):
        self.openBuffer()
        print 'hello'
        buffer = self.closeBuffer()        
        self.assertEqual(buffer, 'hello\n')