Follow up to r1884279: Fix 'make check GLOBAL_SCHEDULER=1' with Python 2.
* build/run_tests.py
(Popen): New class to provide context manager for backwards-compatibility
with Python 2.
(Job.execute, CollectingThread._count_c_tests,
CollectingThread._count_py_tests, TestHarness._run_c_test):
Use custom Popen class with context manager instead of subprocess.Popen.
@@ -91,6 +91,29 @@ class TextColors:
cls.SUCCESS = ''
+if hasattr(subprocess.Popen, '__enter__'):
+ Popen = subprocess.Popen
+else:
+ class Popen(subprocess.Popen):
+ """Popen objects are supported as context managers since Python 3.2.
+ This class provides backwards-compatibility with Python 2.
+ """
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ if self.stdout:
+ self.stdout.close()
+ if self.stderr:
+ self.stderr.close()
+ try:
+ if self.stdin:
+ self.stdin.close()
+ finally:
+ self.wait()
+
+
def _get_term_width():
'Attempt to discern the width of the terminal'
# This may not work on all platforms, in which case the default of 80
@@ -364,7 +387,7 @@ class TestHarness:
def execute(self, harness):
start_time = datetime.now()
- with subprocess.Popen(self._command_line(harness),
+ with Popen(self._command_line(harness),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.progdir) as prog:
@@ -390,24 +413,20 @@ class TestHarness:
def _count_c_tests(self, progabs, progdir, progbase):
'Run a c test, escaping parameters as required.'
cmdline = [ progabs, '--list' ]
- with subprocess.Popen(cmdline, stdout=subprocess.PIPE,
- cwd=progdir) as prog:
+ with Popen(cmdline, stdout=subprocess.PIPE, cwd=progdir) as prog:
lines = prog.stdout.readlines()
self.result.append(TestHarness.Job(len(lines) - 2, False, progabs,
progdir, progbase))
- prog.wait()
def _count_py_tests(self, progabs, progdir, progbase):
'Run a c test, escaping parameters as required.'
cmdline = [ sys.executable, progabs, '--list' ]
- with subprocess.Popen(cmdline, stdout=subprocess.PIPE,
- cwd=progdir) as prog:
+ with Popen(cmdline, stdout=subprocess.PIPE, cwd=progdir) as prog:
lines = prog.stdout.readlines()
for i in range(0, len(lines) - 2):
self.result.append(TestHarness.Job(i + 1, True, progabs,
progdir, progbase))
- prog.wait()
def run(self):
"Run a single test. Return the test's exit code."
@@ -802,7 +821,7 @@ class TestHarness:
total = len(test_nums)
else:
total_cmdline = [cmdline[0], '--list']
- prog = subprocess.Popen(total_cmdline, stdout=subprocess.PIPE)
+ with Popen(total_cmdline, stdout=subprocess.PIPE) as prog:
lines = prog.stdout.readlines()
total = len(lines) - 2
@@ -819,8 +838,7 @@ class TestHarness:
self.dots_written = dots
tests_completed = 0
- prog = subprocess.Popen(cmdline, stdout=subprocess.PIPE,
- stderr=self.log)
+ with Popen(cmdline, stdout=subprocess.PIPE, stderr=self.log) as prog:
line = prog.stdout.readline()
while line:
line = ensure_str(line)
