#/usr/bin/python -Qwarnall -tt import unittest from test import test_support import p4util, os, StringIO class MyStringIO(StringIO.StringIO): ''' Prevent close() from wiping out what we've gathered. ''' def __init__(self): StringIO.StringIO.__init__(self) self.value = None def getvalue(self): if self.value is None: return StringIO.StringIO.getvalue(self) else: return self.value def close(self): self.value = StringIO.StringIO.getvalue(self) StringIO.StringIO.close(self) class Mock_P4Commands_Cmd(p4util.P4Commands_Cmd): def __init__(self, outp): ''' outp: a StringIO object (or other stream) to simulate the stdout. ''' self.read_input = MyStringIO() self.called_cmds = [] self.output = outp def __popen(self, cmd, mode = 'rw'): ''' Mock overwriting of the simulated forked process ''' class MockProc: def __init__(self, inp, outp): self.stdout = outp self.stdin = inp def wait(self): return 0 self.called_cmds.append(cmd) return MockProc(self.read_input, self.output) def mock_compare_cmds(self, expected_commands): ''' expected_commands: list of 'cmd' args passed to __popen return: True if they're equal, otherwise False ''' if len(self.called_cmds) != len(expected_commands): return False for i in range(0, len(self.called_cmds)): ccL = self.called_cmds[i] ecL = expected_commands[i] if len(ccL) != len(ecL): return False for j in range(0, len(ccL)): if ccL[j] != ecL[j]: return False return True def mock_compare_input(self, expected_input): return self.read_input.getvalue() == expected_input if __name__ == '__main__': unittest.main()