Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(117)

Side by Side Diff: expect_tests/pipeline.py

Issue 412773002: Copy expect_tests from build (Closed) Base URL: https://chromium.googlesource.com/infra/testing/expect_tests@master
Patch Set: Fancy ast walker Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « expect_tests/main.py ('k') | expect_tests/serialize.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import Queue
6 import glob
7 import logging
8 import multiprocessing
9 import re
10 import signal
11 import traceback
12
13 from cStringIO import StringIO
14
15 from expect_tests.type_definitions import (
16 Test, UnknownError, TestError, NoMatchingTestsError, MultiTest,
17 Result, ResultStageAbort)
18
19 from expect_tests import util
20
21
22 class ResetableStringIO(object):
23 def __init__(self):
24 self._stream = StringIO()
25
26 def reset(self):
27 self._stream = StringIO()
28
29 def __getattr__(self, key):
30 return getattr(self._stream, key)
31
32
33 def gen_loop_process(gen, test_queue, result_queue, opts, kill_switch,
34 cover_ctx):
35 """Generate `Test`'s from |gen|, and feed them into |test_queue|.
36
37 Non-Test instances will be translated into `UnknownError` objects.
38
39 On completion, feed |opts.jobs| None objects into |test_queue|.
40
41 @param gen: generator yielding Test() instances.
42 @type test_queue: multiprocessing.Queue()
43 @type result_queue: multiprocessing.Queue()
44 @type opts: argparse.Namespace
45 @type kill_switch: multiprocessing.Event()
46 @type cover_ctx: cover.CoverageContext().create_subprocess_context()
47 """
48 # Implicitly append '*'' to globs that don't specify it.
49 globs = ['%s%s' % (g, '*' if '*' not in g else '') for g in opts.test_glob]
50
51 matcher = re.compile(
52 '^%s$' % '|'.join('(?:%s)' % glob.fnmatch.translate(g)
53 for g in globs if g[0] != '-'))
54 if matcher.pattern == '^$':
55 matcher = re.compile('^.*$')
56
57 neg_matcher = re.compile(
58 '^%s$' % '|'.join('(?:%s)' % glob.fnmatch.translate(g[1:])
59 for g in globs if g[0] == '-'))
60
61 def generate_tests():
62 paths_seen = set()
63 seen_tests = False
64 try:
65 with cover_ctx:
66 gen_inst = gen()
67
68 while not kill_switch.is_set():
69 with cover_ctx:
70 root_test = next(gen_inst)
71
72 if kill_switch.is_set():
73 break
74
75 ok_tests = []
76
77 if isinstance(root_test, MultiTest):
78 subtests = root_test.tests
79 else:
80 subtests = [root_test]
81
82 for subtest in subtests:
83 if not isinstance(subtest, Test):
84 result_queue.put_nowait(
85 UnknownError('Got non-[Multi]Test isinstance from generator: %r'
86 % subtest))
87 continue
88
89 test_path = subtest.expect_path()
90 if test_path is not None and test_path in paths_seen:
91 result_queue.put_nowait(
92 TestError(subtest, 'Duplicate expectation path!'))
93 else:
94 if test_path is not None:
95 paths_seen.add(test_path)
96 name = subtest.name
97 if not neg_matcher.match(name) and matcher.match(name):
98 ok_tests.append(subtest)
99
100 if ok_tests:
101 seen_tests = True
102 yield root_test.restrict(ok_tests)
103
104 if not seen_tests:
105 result_queue.put_nowait(NoMatchingTestsError())
106 except StopIteration:
107 pass
108 except KeyboardInterrupt:
109 pass
110 finally:
111 for _ in xrange(opts.jobs):
112 test_queue.put_nowait(None)
113
114
115 next_stage = (result_queue if opts.handler.SKIP_RUNLOOP else test_queue)
116 opts.handler.gen_stage_loop(opts, generate_tests(), next_stage.put_nowait,
117 result_queue.put_nowait)
118
119
120 def run_loop_process(test_queue, result_queue, opts, kill_switch, cover_ctx):
121 """Consume `Test` instances from |test_queue|, run them, and yield the results
122 into opts.run_stage_loop().
123
124 Generates coverage data as a side-effect.
125
126 @type test_queue: multiprocessing.Queue()
127 @type result_queue: multiprocessing.Queue()
128 @type opts: argparse.Namespace
129 @type kill_switch: multiprocessing.Event()
130 @type cover_ctx: cover.CoverageContext().create_subprocess_context()
131 """
132 logstream = ResetableStringIO()
133 logger = logging.getLogger()
134 logger.setLevel(logging.DEBUG)
135 shandler = logging.StreamHandler(logstream)
136 shandler.setFormatter(
137 logging.Formatter('%(levelname)s: %(message)s'))
138 logger.addHandler(shandler)
139
140 SKIP = object()
141 def process_test(subtest):
142 logstream.reset()
143 with cover_ctx(include=subtest.coverage_includes()):
144 subresult = subtest.run()
145 if isinstance(subresult, TestError):
146 result_queue.put_nowait(subresult)
147 return SKIP
148 elif not isinstance(subresult, Result):
149 result_queue.put_nowait(
150 TestError(
151 subtest,
152 'Got non-Result instance from test: %r' % subresult))
153 return SKIP
154 return subresult
155
156 def generate_tests_results():
157 try:
158 while not kill_switch.is_set():
159 try:
160 test = test_queue.get(timeout=0.1)
161 if test is None:
162 break
163 except Queue.Empty:
164 continue
165
166 try:
167 for subtest, subresult in test.process(process_test):
168 if subresult is not SKIP:
169 yield subtest, subresult, logstream.getvalue().splitlines()
170 except Exception:
171 result_queue.put_nowait(
172 TestError(test, traceback.format_exc(),
173 logstream.getvalue().splitlines()))
174 except KeyboardInterrupt:
175 pass
176
177 opts.handler.run_stage_loop(opts, generate_tests_results(),
178 result_queue.put_nowait)
179
180
181 def result_loop(test_gen, cover_ctx, opts):
182 kill_switch = multiprocessing.Event()
183 def handle_killswitch(*_):
184 kill_switch.set()
185 # Reset the signal to DFL so that double ctrl-C kills us for sure.
186 signal.signal(signal.SIGINT, signal.SIG_DFL)
187 signal.signal(signal.SIGTERM, signal.SIG_DFL)
188 signal.signal(signal.SIGINT, handle_killswitch)
189 signal.signal(signal.SIGTERM, handle_killswitch)
190
191 test_queue = multiprocessing.Queue()
192 result_queue = multiprocessing.Queue()
193
194 gen_cover_ctx = cover_ctx
195 if cover_ctx.enabled:
196 gen_cover_ctx = cover_ctx(include=util.get_cover_list(test_gen))
197
198 test_gen_args = (
199 test_gen, test_queue, result_queue, opts, kill_switch, gen_cover_ctx)
200
201 procs = []
202 if opts.handler.SKIP_RUNLOOP:
203 gen_loop_process(*test_gen_args)
204 else:
205 procs = [multiprocessing.Process(
206 target=gen_loop_process, args=test_gen_args)]
207
208 procs += [
209 multiprocessing.Process(
210 target=run_loop_process, args=(
211 test_queue, result_queue, opts, kill_switch, cover_ctx))
212 for _ in xrange(opts.jobs)
213 ]
214
215 for p in procs:
216 p.daemon = True
217 p.start()
218
219 error = False
220 try:
221 def generate_objects():
222 while not kill_switch.is_set():
223 while not kill_switch.is_set():
224 try:
225 yield result_queue.get(timeout=0.1)
226 except Queue.Empty:
227 break
228
229 if not any(p.is_alive() for p in procs):
230 break
231
232 # Get everything still in the queue. Still need timeout, but since nothing
233 # is going to be adding stuff to the queue, use a very short timeout.
234 while not kill_switch.is_set():
235 try:
236 yield result_queue.get(timeout=0.00001)
237 except Queue.Empty:
238 break
239
240 if kill_switch.is_set():
241 raise ResultStageAbort()
242 error = opts.handler.result_stage_loop(opts, generate_objects())
243 except ResultStageAbort:
244 pass
245
246 for p in procs:
247 p.join()
248
249 if not kill_switch.is_set() and not result_queue.empty():
250 error = True
251
252 return error, kill_switch.is_set()
OLDNEW
« no previous file with comments | « expect_tests/main.py ('k') | expect_tests/serialize.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698