| 1 |
#!/usr/bin/python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
from subprocess import Popen, PIPE, call |
| 5 |
|
| 6 |
import signal |
| 7 |
|
| 8 |
class Alarm(Exception): |
| 9 |
pass |
| 10 |
|
| 11 |
class IOTest: |
| 12 |
expectedRetCodeFail = False |
| 13 |
|
| 14 |
def alarmHandler(self, signum, frame): |
| 15 |
raise Alarm |
| 16 |
|
| 17 |
def withTimeout(self, seconds, cmd, *args, **kwargs): |
| 18 |
signal.signal(signal.SIGALRM, self.alarmHandler) |
| 19 |
signal.alarm(seconds) |
| 20 |
ret = cmd(*args, **kwargs) |
| 21 |
signal.alarm(0) # reset |
| 22 |
return ret |
| 23 |
|
| 24 |
def communicateFlush(self, string): |
| 25 |
self.proc.stdin.write(string.encode('utf-8') + b'\0') |
| 26 |
self.proc.stdin.flush() |
| 27 |
|
| 28 |
output = b'' |
| 29 |
c = None |
| 30 |
while c != b'\0': |
| 31 |
try: |
| 32 |
c = self.withTimeout(2, self.proc.stdout.read, 1) |
| 33 |
except Alarm: |
| 34 |
break |
| 35 |
if c != b'\0': |
| 36 |
output += c |
| 37 |
|
| 38 |
return output.decode('utf-8') |
| 39 |
|
| 40 |
def checkCommand(self, cmd): |
| 41 |
self.assertEqual(0, call(cmd)) |
| 42 |
|
| 43 |
def runCommand(self, cmd, pairs): |
| 44 |
self.proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) |
| 45 |
|
| 46 |
blank = '[][\n]' |
| 47 |
for inp, exp in pairs: |
| 48 |
with self.subTest(input_line=inp): |
| 49 |
self.assertEqual(exp+blank, self.communicateFlush(inp+blank)) |
| 50 |
|
| 51 |
self.proc.communicate() # let it terminate |
| 52 |
self.proc.stdin.close() |
| 53 |
self.proc.stdout.close() |
| 54 |
self.proc.stderr.close() |
| 55 |
|
| 56 |
retCode = self.proc.poll() |
| 57 |
if self.expectedRetCodeFail: |
| 58 |
self.assertNotEqual(0, retCode) |
| 59 |
else: |
| 60 |
self.assertEqual(0, retCode) |