#!/usr/bin/env python3 """Drive a program on a pseudo-terminal. ptydrive.py [-c COLS] program [args...] < script Each line of the script is one step: send TEXT type TEXT; C-style escapes are decoded (\\r is Enter, \\t is Tab, \\x03 is ^C, \\x1a is ^Z, \\x1b is ESC) wait SECS pause expect TEXT wait (up to 5 s) until TEXT has appeared in the output since the previous step; the test fails if it does not Everything the program writes is copied to stdout with terminal control sequences removed, so that a test can compare it with a .exp file. Only the interactive tests use this; it is not needed on z/OS. """ import codecs, os, pty, re, select, signal, sys, time def main(): args = sys.argv[1:] cols = 80 if args and args[0] == "-c": cols = int(args[1]); args = args[2:] pid, fd = pty.fork() if pid == 0: os.environ["TERM"] = "vt100" os.execvp(args[0], args) import fcntl, struct, termios fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24, cols, 0, 0)) out = bytearray() mark = 0 def pump(timeout): end = time.time() + timeout while True: left = end - time.time() if left <= 0: return r, _, _ = select.select([fd], [], [], left) if not r: return try: data = os.read(fd, 4096) except OSError: return if not data: return out.extend(data) ok = True pump(0.3) for line in sys.stdin: line = line.rstrip("\n") if not line or line.startswith("#"): continue op, _, arg = line.partition(" ") if op == "send": mark = len(out) os.write(fd, codecs.decode(arg, "unicode_escape").encode("latin-1")) pump(0.15) elif op == "wait": pump(float(arg)) elif op == "expect": want = arg.encode() end = time.time() + 5 while want not in clean(out[mark:]) and time.time() < end: pump(0.05) if want not in clean(out[mark:]): sys.stderr.write("ptydrive.py: expected %r\n" % arg) ok = False pump(0.3) try: os.kill(pid, signal.SIGHUP) except OSError: pass try: os.close(fd) except OSError: pass os.waitpid(pid, 0) sys.stdout.write(clean(out).decode("latin-1")) sys.exit(0 if ok else 1) def clean(data): data = re.sub(rb"\x1b\[[0-9;?]*[A-Za-z]", b"", bytes(data)) data = data.replace(b"\r\n", b"\n") # A redraw rewrites the row from column 0: keep only the final state. lines = [] for ln in data.split(b"\n"): parts = [p for p in ln.split(b"\r") if p] lines.append(parts[-1] if parts else b"") return b"\n".join(lines).replace(b"\x07", b"") main()