blob: 6d843d9f6a552c0271b209f14496f873acd2e2d5 [file] [log] [blame]
Roger Meier41ad4342015-03-24 22:30:40 +01001#
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
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090020from __future__ import print_function
Roger Meier41ad4342015-03-24 22:30:40 +010021import datetime
22import json
23import multiprocessing
24import os
25import platform
26import re
27import subprocess
28import sys
29import time
30import traceback
31
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090032from .compat import logfile_open, path_join, str_join
Nobuaki Sukegawa2de27002015-11-22 01:13:48 +090033from .test import TestEntry
Roger Meier41ad4342015-03-24 22:30:40 +010034
35LOG_DIR = 'log'
36RESULT_HTML = 'result.html'
37RESULT_JSON = 'results.json'
38FAIL_JSON = 'known_failures_%s.json'
39
40
41def generate_known_failures(testdir, overwrite, save, out):
42 def collect_failures(results):
43 success_index = 5
44 for r in results:
45 if not r[success_index]:
46 yield TestEntry.get_name(*r)
47 try:
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090048 with logfile_open(os.path.join(testdir, RESULT_JSON), 'r') as fp:
Roger Meier41ad4342015-03-24 22:30:40 +010049 results = json.load(fp)
50 except IOError:
51 sys.stderr.write('Unable to load last result. Did you run tests ?\n')
52 return False
53 fails = collect_failures(results['results'])
54 if not overwrite:
55 known = load_known_failures(testdir)
56 known.extend(fails)
57 fails = known
Nobuaki Sukegawaf5b795d2015-03-29 14:48:48 +090058 fails_json = json.dumps(sorted(set(fails)), indent=2, separators=(',', ': '))
Roger Meier41ad4342015-03-24 22:30:40 +010059 if save:
Nobuaki Sukegawae68ccc22015-12-13 21:45:39 +090060 with logfile_open(os.path.join(testdir, FAIL_JSON % platform.system()), 'w+') as fp:
Roger Meier41ad4342015-03-24 22:30:40 +010061 fp.write(fails_json)
62 sys.stdout.write('Successfully updated known failures.\n')
63 if out:
64 sys.stdout.write(fails_json)
65 sys.stdout.write('\n')
66 return True
67
68
69def load_known_failures(testdir):
70 try:
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090071 with logfile_open(os.path.join(testdir, FAIL_JSON % platform.system()), 'r') as fp:
Roger Meier41ad4342015-03-24 22:30:40 +010072 return json.load(fp)
73 except IOError:
74 return []
75
76
77class TestReporter(object):
78 # Unfortunately, standard library doesn't handle timezone well
79 # DATETIME_FORMAT = '%a %b %d %H:%M:%S %Z %Y'
80 DATETIME_FORMAT = '%a %b %d %H:%M:%S %Y'
81
82 def __init__(self):
83 self._log = multiprocessing.get_logger()
84 self._lock = multiprocessing.Lock()
85
86 @classmethod
Nobuaki Sukegawa783660a2015-04-12 00:32:40 +090087 def test_logfile(cls, test_name, prog_kind, dir=None):
88 relpath = os.path.join('log', '%s_%s.log' % (test_name, prog_kind))
Nobuaki Sukegawa2de27002015-11-22 01:13:48 +090089 return relpath if not dir else os.path.realpath(path_join(dir, relpath))
Roger Meier41ad4342015-03-24 22:30:40 +010090
91 def _start(self):
92 self._start_time = time.time()
93
94 @property
95 def _elapsed(self):
96 return time.time() - self._start_time
97
98 @classmethod
99 def _format_date(cls):
100 return '%s' % datetime.datetime.now().strftime(cls.DATETIME_FORMAT)
101
102 def _print_date(self):
103 self.out.write('%s\n' % self._format_date())
104
105 def _print_bar(self, out=None):
106 (out or self.out).write(
107 '======================================================================\n')
108
109 def _print_exec_time(self):
110 self.out.write('Test execution took {:.1f} seconds.\n'.format(self._elapsed))
111
112
113class ExecReporter(TestReporter):
114 def __init__(self, testdir, test, prog):
115 super(ExecReporter, self).__init__()
116 self._test = test
117 self._prog = prog
Nobuaki Sukegawa783660a2015-04-12 00:32:40 +0900118 self.logpath = self.test_logfile(test.name, prog.kind, testdir)
Roger Meier41ad4342015-03-24 22:30:40 +0100119 self.out = None
120
121 def begin(self):
122 self._start()
123 self._open()
124 if self.out and not self.out.closed:
125 self._print_header()
126 else:
127 self._log.debug('Output stream is not available.')
128
129 def end(self, returncode):
130 self._lock.acquire()
131 try:
132 if self.out and not self.out.closed:
133 self._print_footer(returncode)
134 self._close()
135 self.out = None
136 else:
137 self._log.debug('Output stream is not available.')
138 finally:
139 self._lock.release()
140
141 def killed(self):
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +0900142 self.end(None)
Roger Meier41ad4342015-03-24 22:30:40 +0100143
144 _init_failure_exprs = {
145 'server': list(map(re.compile, [
146 '[Aa]ddress already in use',
147 'Could not bind',
148 'EADDRINUSE',
149 ])),
150 'client': list(map(re.compile, [
151 '[Cc]onnection refused',
152 'Could not connect to localhost',
153 'ECONNREFUSED',
154 'No such file or directory', # domain socket
155 ])),
156 }
157
158 def maybe_false_positive(self):
159 """Searches through log file for socket bind error.
160 Returns True if suspicious expression is found, otherwise False"""
Roger Meier41ad4342015-03-24 22:30:40 +0100161 try:
162 if self.out and not self.out.closed:
163 self.out.flush()
Nobuaki Sukegawa9b35a7c2015-11-17 11:01:41 +0900164 exprs = self._init_failure_exprs[self._prog.kind]
Roger Meier41ad4342015-03-24 22:30:40 +0100165
Nobuaki Sukegawa9b35a7c2015-11-17 11:01:41 +0900166 def match(line):
167 for expr in exprs:
168 if expr.search(line):
169 return True
170
171 with logfile_open(self.logpath, 'r') as fp:
Roger Meier41ad4342015-03-24 22:30:40 +0100172 if any(map(match, fp)):
173 return True
174 except (KeyboardInterrupt, SystemExit):
175 raise
176 except Exception as ex:
177 self._log.warn('[%s]: Error while detecting false positive: %s' % (self._test.name, str(ex)))
178 self._log.info(traceback.print_exc())
179 return False
180
181 def _open(self):
Nobuaki Sukegawae68ccc22015-12-13 21:45:39 +0900182 self.out = logfile_open(self.logpath, 'w+')
Roger Meier41ad4342015-03-24 22:30:40 +0100183
184 def _close(self):
185 self.out.close()
186
187 def _print_header(self):
188 self._print_date()
Nobuaki Sukegawa2de27002015-11-22 01:13:48 +0900189 self.out.write('Executing: %s\n' % str_join(' ', self._prog.command))
Roger Meier41ad4342015-03-24 22:30:40 +0100190 self.out.write('Directory: %s\n' % self._prog.workdir)
191 self.out.write('config:delay: %s\n' % self._test.delay)
192 self.out.write('config:timeout: %s\n' % self._test.timeout)
193 self._print_bar()
194 self.out.flush()
195
196 def _print_footer(self, returncode=None):
197 self._print_bar()
198 if returncode is not None:
199 self.out.write('Return code: %d\n' % returncode)
200 else:
201 self.out.write('Process is killed.\n')
202 self._print_exec_time()
203 self._print_date()
204
205
206class SummaryReporter(TestReporter):
207 def __init__(self, testdir, concurrent=True):
208 super(SummaryReporter, self).__init__()
209 self.testdir = testdir
210 self.logdir = os.path.join(testdir, LOG_DIR)
211 self.out_path = os.path.join(testdir, RESULT_JSON)
212 self.concurrent = concurrent
213 self.out = sys.stdout
214 self._platform = platform.system()
215 self._revision = self._get_revision()
216 self._tests = []
217 if not os.path.exists(self.logdir):
218 os.mkdir(self.logdir)
219 self._known_failures = load_known_failures(testdir)
220 self._unexpected_success = []
221 self._unexpected_failure = []
222 self._expected_failure = []
223 self._print_header()
224
225 def _get_revision(self):
226 p = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'],
227 cwd=self.testdir, stdout=subprocess.PIPE)
228 out, _ = p.communicate()
229 return out.strip()
230
231 def _format_test(self, test, with_result=True):
232 name = '%s-%s' % (test.server.name, test.client.name)
233 trans = '%s-%s' % (test.transport, test.socket)
234 if not with_result:
235 return '{:19s}{:13s}{:25s}'.format(name[:18], test.protocol[:12], trans[:24])
236 else:
237 result = 'success' if test.success else (
238 'timeout' if test.expired else 'failure')
239 result_string = '%s(%d)' % (result, test.returncode)
240 return '{:19s}{:13s}{:25s}{:s}\n'.format(name[:18], test.protocol[:12], trans[:24], result_string)
241
242 def _print_test_header(self):
243 self._print_bar()
244 self.out.write(
245 '{:19s}{:13s}{:25s}{:s}\n'.format('server-client:', 'protocol:', 'transport:', 'result:'))
246
247 def _print_header(self):
248 self._start()
249 self.out.writelines([
250 'Apache Thrift - Integration Test Suite\n',
251 ])
252 self._print_date()
253 self._print_test_header()
254
255 def _print_unexpected_failure(self):
256 if len(self._unexpected_failure) > 0:
257 self.out.writelines([
258 '*** Following %d failures were unexpected ***:\n' % len(self._unexpected_failure),
259 'If it is introduced by you, please fix it before submitting the code.\n',
260 # 'If not, please report at https://issues.apache.org/jira/browse/THRIFT\n',
261 ])
262 self._print_test_header()
263 for i in self._unexpected_failure:
264 self.out.write(self._format_test(self._tests[i]))
265 self._print_bar()
266 else:
267 self.out.write('No unexpected failures.\n')
268
269 def _print_unexpected_success(self):
270 if len(self._unexpected_success) > 0:
271 self.out.write(
272 'Following %d tests were known to fail but succeeded (it\'s normal):\n' % len(self._unexpected_success))
273 self._print_test_header()
274 for i in self._unexpected_success:
275 self.out.write(self._format_test(self._tests[i]))
276 self._print_bar()
277
Nobuaki Sukegawaf5b795d2015-03-29 14:48:48 +0900278 def _http_server_command(self, port):
279 if sys.version_info[0] < 3:
280 return 'python -m SimpleHTTPServer %d' % port
281 else:
282 return 'python -m http.server %d' % port
283
Roger Meier41ad4342015-03-24 22:30:40 +0100284 def _print_footer(self):
285 fail_count = len(self._expected_failure) + len(self._unexpected_failure)
286 self._print_bar()
287 self._print_unexpected_success()
288 self._print_unexpected_failure()
289 self._write_html_data()
290 self._assemble_log('unexpected failures', self._unexpected_failure)
291 self._assemble_log('known failures', self._expected_failure)
292 self.out.writelines([
293 'You can browse results at:\n',
294 '\tfile://%s/%s\n' % (self.testdir, RESULT_HTML),
Nobuaki Sukegawaf5b795d2015-03-29 14:48:48 +0900295 '# If you use Chrome, run:\n',
296 '# \tcd %s\n#\t%s\n' % (self.testdir, self._http_server_command(8001)),
297 '# then browse:\n',
298 '# \thttp://localhost:%d/%s\n' % (8001, RESULT_HTML),
Roger Meier41ad4342015-03-24 22:30:40 +0100299 'Full log for each test is here:\n',
300 '\ttest/log/client_server_protocol_transport_client.log\n',
301 '\ttest/log/client_server_protocol_transport_server.log\n',
302 '%d failed of %d tests in total.\n' % (fail_count, len(self._tests)),
303 ])
304 self._print_exec_time()
305 self._print_date()
306
307 def _render_result(self, test):
308 return [
309 test.server.name,
310 test.client.name,
311 test.protocol,
312 test.transport,
313 test.socket,
314 test.success,
315 test.as_expected,
316 test.returncode,
317 {
Nobuaki Sukegawa783660a2015-04-12 00:32:40 +0900318 'server': self.test_logfile(test.name, test.server.kind),
319 'client': self.test_logfile(test.name, test.client.kind),
Roger Meier41ad4342015-03-24 22:30:40 +0100320 },
321 ]
322
323 def _write_html_data(self):
324 """Writes JSON data to be read by result html"""
325 results = [self._render_result(r) for r in self._tests]
Nobuaki Sukegawae68ccc22015-12-13 21:45:39 +0900326 with logfile_open(self.out_path, 'w+') as fp:
Roger Meier41ad4342015-03-24 22:30:40 +0100327 fp.write(json.dumps({
328 'date': self._format_date(),
329 'revision': str(self._revision),
330 'platform': self._platform,
331 'duration': '{:.1f}'.format(self._elapsed),
332 'results': results,
333 }, indent=2))
334
335 def _assemble_log(self, title, indexes):
336 if len(indexes) > 0:
337 def add_prog_log(fp, test, prog_kind):
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +0900338 print('*************************** %s message ***************************' % prog_kind,
339 file=fp)
Nobuaki Sukegawa783660a2015-04-12 00:32:40 +0900340 path = self.test_logfile(test.name, prog_kind, self.testdir)
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +0900341 if os.path.exists(path):
342 with logfile_open(path, 'r') as prog_fp:
343 print(prog_fp.read(), file=fp)
Roger Meier41ad4342015-03-24 22:30:40 +0100344 filename = title.replace(' ', '_') + '.log'
Nobuaki Sukegawae68ccc22015-12-13 21:45:39 +0900345 with logfile_open(os.path.join(self.logdir, filename), 'w+') as fp:
Roger Meier41ad4342015-03-24 22:30:40 +0100346 for test in map(self._tests.__getitem__, indexes):
347 fp.write('TEST: [%s]\n' % test.name)
348 add_prog_log(fp, test, test.server.kind)
349 add_prog_log(fp, test, test.client.kind)
350 fp.write('**********************************************************************\n\n')
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +0900351 print('%s are logged to test/%s/%s' % (title.capitalize(), LOG_DIR, filename))
Roger Meier41ad4342015-03-24 22:30:40 +0100352
353 def end(self):
354 self._print_footer()
355 return len(self._unexpected_failure) == 0
356
357 def add_test(self, test_dict):
358 test = TestEntry(self.testdir, **test_dict)
359 self._lock.acquire()
360 try:
361 if not self.concurrent:
362 self.out.write(self._format_test(test, False))
363 self.out.flush()
364 self._tests.append(test)
365 return len(self._tests) - 1
366 finally:
367 self._lock.release()
368
369 def add_result(self, index, returncode, expired):
370 self._lock.acquire()
371 try:
372 failed = returncode is None or returncode != 0
373 test = self._tests[index]
374 known = test.name in self._known_failures
375 if failed:
376 if known:
377 self._log.debug('%s failed as expected' % test.name)
378 self._expected_failure.append(index)
379 else:
380 self._log.info('unexpected failure: %s' % test.name)
381 self._unexpected_failure.append(index)
382 elif known:
383 self._log.info('unexpected success: %s' % test.name)
384 self._unexpected_success.append(index)
385 test.success = not failed
386 test.returncode = returncode
387 test.expired = expired
388 test.as_expected = known == failed
389 if not self.concurrent:
390 result = 'success' if not failed else 'failure'
391 result_string = '%s(%d)' % (result, returncode)
392 self.out.write(result_string + '\n')
393 else:
394 self.out.write(self._format_test(test))
395 finally:
396 self._lock.release()