| 1 |
# |
| 2 |
# Licensed to the Apache Software Foundation (ASF) under one |
| 3 |
# or more contributor license agreements. See the NOTICE file |
| 4 |
# distributed with this work for additional information |
| 5 |
# regarding copyright ownership. The ASF licenses this file |
| 6 |
# to you under the Apache License, Version 2.0 (the |
| 7 |
# "License"); you may not use this file except in compliance |
| 8 |
# with the License. You may obtain a copy of the License at |
| 9 |
# |
| 10 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
# |
| 12 |
# Unless required by applicable law or agreed to in writing, |
| 13 |
# software distributed under the License is distributed on an |
| 14 |
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 |
# KIND, either express or implied. See the License for the |
| 16 |
# specific language governing permissions and limitations |
| 17 |
# under the License |
| 18 |
# |
| 19 |
|
| 20 |
# Extends the subprocess module to use runtime checkers, and report stderr output. |
| 21 |
|
| 22 |
import os |
| 23 |
import re |
| 24 |
import subprocess |
| 25 |
import tempfile |
| 26 |
from subprocess import PIPE |
| 27 |
|
| 28 |
|
| 29 |
def in_path(name): |
| 30 |
"""Look for name in the PATH""" |
| 31 |
for path in os.environ["PATH"].split(os.pathsep): |
| 32 |
f = os.path.join(path, name) |
| 33 |
if os.path.isfile(f) and os.access(f, os.X_OK): |
| 34 |
return f |
| 35 |
|
| 36 |
|
| 37 |
class TestProcessError(Exception): |
| 38 |
def __init__(self, proc, what, output=None): |
| 39 |
self.output = output |
| 40 |
sep = "\n%s stderr(%s) %s\n" % ("_" * 32, proc.pid, "_" * 32) |
| 41 |
error = sep + proc.error + sep if proc.error else "" |
| 42 |
super(TestProcessError, self).__init__("%s pid=%s exit=%s: %s%s" % ( |
| 43 |
proc.cmd, proc.pid, proc.returncode, what, error)) |
| 44 |
|
| 45 |
|
| 46 |
class Popen(subprocess.Popen): |
| 47 |
""" |
| 48 |
Add TEST_EXE_PREFIX to the command, check stderr for runtime checker output. |
| 49 |
In a 'with' statement it runs check_wait() on exit from the block, or |
| 50 |
check_kill() if initialized with kill_me=True |
| 51 |
""" |
| 52 |
|
| 53 |
def __init__(self, *args, **kwargs): |
| 54 |
""" |
| 55 |
Takes all args and kwargs of subprocess.Popen except stdout, stderr, universal_newlines |
| 56 |
kill_me=True runs check_kill() in __exit__() instead of check_wait() |
| 57 |
""" |
| 58 |
self.on_exit = self.check_kill if kwargs.pop('kill_me', False) else self.check_wait |
| 59 |
self.errfile = tempfile.NamedTemporaryFile(delete=False) |
| 60 |
kwargs.update({'universal_newlines': True, 'stdout': PIPE, 'stderr': self.errfile}) |
| 61 |
prefix = os.environ.get("TEST_EXE_PREFIX") |
| 62 |
if prefix: |
| 63 |
args = [prefix.split() + args[0]] + list(args[1:]) |
| 64 |
self.cmd = args[0] |
| 65 |
super(Popen, self).__init__(*args, **kwargs) |
| 66 |
|
| 67 |
def check_wait(self): |
| 68 |
if self.wait() or self.error: |
| 69 |
raise TestProcessError(self, "check_wait") |
| 70 |
|
| 71 |
def communicate(self, *args, **kwargs): |
| 72 |
result = super(Popen, self).communicate(*args, **kwargs) |
| 73 |
if self.returncode or self.error: |
| 74 |
raise TestProcessError(self, "check_communicate", result[0]) |
| 75 |
return result |
| 76 |
|
| 77 |
def check_kill(self): |
| 78 |
"""Raise if process has already exited, kill and raise if self.error is not empty""" |
| 79 |
if self.poll() is None: |
| 80 |
self.kill() |
| 81 |
self.wait() |
| 82 |
self.stdout.close() # Doesn't get closed if killed |
| 83 |
if self.error: |
| 84 |
raise TestProcessError(self, "check_kill found error output") |
| 85 |
else: |
| 86 |
raise TestProcessError(self, "check_kill process not running") |
| 87 |
|
| 88 |
def expect(self, pattern): |
| 89 |
line = self.stdout.readline() |
| 90 |
match = re.search(pattern, line) |
| 91 |
if not match: |
| 92 |
raise TestProcessError(self, "can't find '%s' in '%s'" % (pattern, line)) |
| 93 |
return match |
| 94 |
|
| 95 |
@property |
| 96 |
def error(self): |
| 97 |
"""Return stderr as string, may only be used after process has terminated.""" |
| 98 |
assert(self.poll is not None) |
| 99 |
if not hasattr(self, "_error"): |
| 100 |
self.errfile.close() # Not auto-deleted |
| 101 |
with open(self.errfile.name) as f: # Re-open to read |
| 102 |
self._error = f.read().strip() |
| 103 |
os.unlink(self.errfile.name) |
| 104 |
return self._error |
| 105 |
|
| 106 |
def __enter__(self): |
| 107 |
return self |
| 108 |
|
| 109 |
def __exit__(self, *args): |
| 110 |
self.on_exit() |
| 111 |
|
| 112 |
|
| 113 |
def check_output(*args, **kwargs): |
| 114 |
return Popen(*args, **kwargs).communicate()[0] |
| 115 |
|
| 116 |
|
| 117 |
class Server(Popen): |
| 118 |
"""A process that prints 'listening on <port>' to stdout""" |
| 119 |
|
| 120 |
def __init__(self, *args, **kwargs): |
| 121 |
super(Server, self).__init__(*args, **kwargs) |
| 122 |
self.port = self.expect("listening on ([0-9]+)$").group(1) |