comparison cmd2.py @ 380:de2306847251

replacing temporaryfile with an object seems good
author cat@eee
date Mon, 22 Feb 2010 21:26:40 -0500
parents 1babd3df22d1
children 2687482dfa33
comparison
equal deleted inserted replaced
379:1babd3df22d1 380:de2306847251
1426 obj = object.__new__(cls, *a, **k) 1426 obj = object.__new__(cls, *a, **k)
1427 obj.__dict__ = cls._shared_state 1427 obj.__dict__ = cls._shared_state
1428 return obj 1428 return obj
1429 1429
1430 class OutputTrap(Borg): 1430 class OutputTrap(Borg):
1431 '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing.
1432 Call `tearDown()` to return to normal output.'''
1433 def __init__(self):
1434 self.old_stdout = sys.stdout
1435 self.trap = tempfile.TemporaryFile()
1436 sys.stdout = self.trap
1437 def read(self):
1438 self.trap.seek(0)
1439 result = self.trap.read().decode() # Py3 sends stdout trap as bytes, not strings
1440 self.trap.truncate(0)
1441 try:
1442 return result.strip('\x00') #TODO: understand this
1443 except TypeError:
1444 return result
1445 def tearDown(self):
1446 sys.stdout = self.old_stdout
1447
1448 class OutputTrap(Borg):
1449 '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing. 1431 '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing.
1450 Call `tearDown()` to return to normal output.''' 1432 Call `tearDown()` to return to normal output.'''
1451 def __init__(self): 1433 def __init__(self):
1452 self.contents = '' 1434 self.contents = ''
1453 self.old_stdout = sys.stdout 1435 self.old_stdout = sys.stdout
1454 sys.stdout = self 1436 sys.stdout = self
1455 def write(self, txt): 1437 def write(self, txt):
1456 self.contents += txt 1438 self.contents += txt
1457 def read(self): 1439 def read(self):
1458 return self.contents 1440 result = self.contents
1441 self.contents = ''
1442 return result
1459 def tearDown(self): 1443 def tearDown(self):
1460 sys.stdout = self.old_stdout 1444 sys.stdout = self.old_stdout
1461 self.contents = '' 1445 self.contents = ''
1462 1446
1463 class Cmd2TestCase(unittest.TestCase): 1447 class Cmd2TestCase(unittest.TestCase):