OILS / test / sh_spec.py View on Github | oils.pub

1516 lines, 940 significant
1#!/usr/bin/env python2
2from __future__ import print_function
3"""
4sh_spec.py -- Test framework to compare shells.
5
6Assertion help:
7 stdout: A single line of expected stdout. Newline is implicit.
8 stdout-json: JSON-encoded string. Use for the empty string (no newline),
9 for unicode chars, etc.
10
11 stderr: Ditto for stderr stream.
12 status: Expected shell return code. If not specified, the case must exit 0.
13
14Results:
15 PASS - we got the ideal, expected value
16 OK - we got a value that was not ideal, but expected
17 For OSH this is behavior that was defined to be different?
18 N-I - Not implemented (e.g. $''). Assertions still checked (in case it
19 starts working)
20 BUG - we verified the value of a known bug
21 FAIL - we got an unexpected value. If the implementation can't be changed,
22 it should be converted to BUG or OK. Otherwise it should be made to
23 PASS.
24
25NOTE: The difference between OK and BUG is a matter of judgement. If the ideal
26behavior is a compile time error (code 2), a runtime error is generally OK.
27
28If ALL shells agree on a broken behavior, they are all marked OK (but our
29implementation will be PASS.) But if the behavior is NOT POSIX compliant, then
30it will be a BUG.
31
32If one shell disagrees with others, that is generally a BUG.
33
34Example test case:
35
36#### hello and fail
37echo hello
38echo world
39exit 1
40## status: 1
41#
42# ignored comment
43#
44## STDOUT:
45hello
46world
47## END
48
49"""
50
51import collections
52import cgi
53import cStringIO
54import errno
55import json
56import optparse
57import os
58import pprint
59import re
60import shutil
61import subprocess
62import sys
63
64from test import spec_lib
65from doctools import html_head
66
67log = spec_lib.log
68
69# Magic strings for other variants of OSH.
70
71# NOTE: osh_ALT is usually _bin/osh -- the release binary.
72# It would be better to rename these osh-cpython and osh-ovm. Have the concept
73# of a suffix?
74
75OSH_CPYTHON = ('osh', 'osh-dbg')
76OTHER_OSH = ('osh_ALT', )
77
78YSH_CPYTHON = ('ysh', 'ysh-dbg')
79OTHER_YSH = ('oil_ALT', )
80
81# For now, only count the Oils CPython failures. TODO: the spec-cpp job should
82# assert the osh-cpp and ysh-cpp deltas.
83OTHER_OILS = OTHER_OSH + OTHER_YSH + ('osh-cpp', 'ysh-cpp')
84
85
86class ParseError(Exception):
87 pass
88
89
90# EXAMPLES:
91## stdout: foo
92## stdout-json: ""
93#
94# In other words, it could be (name, value) or (qualifier, name, value)
95
96KEY_VALUE_RE = re.compile(
97 r'''
98 [#][#] \s+
99 # optional prefix with qualifier and shells
100 (?: (OK|BUG|N-I) \s+ ([\w+/]+) \s+ )?
101 ([\w\-]+) # key
102 :
103 \s* (.*) # value
104''', re.VERBOSE)
105
106END_MULTILINE_RE = re.compile(r'''
107 [#][#] \s+ END
108''', re.VERBOSE)
109
110# Line types
111TEST_CASE_BEGIN = 0 # Starts with ####
112KEY_VALUE = 1 # Metadata
113KEY_VALUE_MULTILINE = 2 # STDOUT STDERR
114END_MULTILINE = 3 # STDOUT STDERR
115PLAIN_LINE = 4 # Uncommented
116EOF = 5
117
118LEX_OUTER = 0 # Ignore blank lines, e.g. for separating cases
119LEX_RAW = 1 # Blank lines are significant
120
121
122class Tokenizer(object):
123 """Modal lexer!"""
124
125 def __init__(self, f):
126 self.f = f
127
128 self.cursor = None
129 self.line_num = 0
130
131 self.next()
132
133 def _ClassifyLine(self, line, lex_mode):
134 if not line: # empty
135 return self.line_num, EOF, ''
136
137 if lex_mode == LEX_OUTER and not line.strip():
138 return None
139
140 if line.startswith('####'):
141 desc = line[4:].strip()
142 return self.line_num, TEST_CASE_BEGIN, desc
143
144 m = KEY_VALUE_RE.match(line)
145 if m:
146 qualifier, shells, name, value = m.groups()
147 # HACK: Expected data should have the newline.
148 if name in ('stdout', 'stderr'):
149 value += '\n'
150
151 if name in ('STDOUT', 'STDERR'):
152 token_type = KEY_VALUE_MULTILINE
153 else:
154 token_type = KEY_VALUE
155 return self.line_num, token_type, (qualifier, shells, name, value)
156
157 m = END_MULTILINE_RE.match(line)
158 if m:
159 return self.line_num, END_MULTILINE, None
160
161 # If it starts with ##, it should be metadata. This finds some typos.
162 if line.lstrip().startswith('##'):
163 raise RuntimeError('Invalid ## line %r' % line)
164
165 if line.lstrip().startswith('#'): # Ignore comments
166 return None # try again
167
168 # Non-empty line that doesn't start with '#'
169 # NOTE: We need the original line to test the whitespace sensitive <<-.
170 # And we need rstrip because we add newlines back below.
171 return self.line_num, PLAIN_LINE, line
172
173 def next(self, lex_mode=LEX_OUTER):
174 """Raises StopIteration when exhausted."""
175 while True:
176 line = self.f.readline()
177 self.line_num += 1
178
179 tok = self._ClassifyLine(line, lex_mode)
180 if tok is not None:
181 break
182
183 self.cursor = tok
184 return self.cursor
185
186 def peek(self):
187 return self.cursor
188
189
190def AddMetadataToCase(case, qualifier, shells, name, value, line_num):
191 shells = shells.split('/') # bash/dash/mksh
192 for shell in shells:
193 if shell not in case:
194 case[shell] = {}
195
196 # Check a duplicate specification
197 name_without_type = re.sub(r'-(json|repr)$', '', name)
198 if (name_without_type in case[shell] or
199 name_without_type + '-json' in case[shell] or
200 name_without_type + '-repr' in case[shell]):
201 raise ParseError('Line %d: duplicate spec %r for %r' %
202 (line_num, name, shell))
203
204 # Check inconsistent qualifier
205 if 'qualifier' in case[shell] and qualifier != case[shell]['qualifier']:
206 raise ParseError(
207 'Line %d: inconsistent qualifier %r is specified for %r, '
208 'but %r was previously specified. '
209 % (line_num, qualifier, shell, case[shell]['qualifier']))
210
211 case[shell][name] = value
212 case[shell]['qualifier'] = qualifier
213
214
215# Format of a test script.
216#
217# -- Code is either literal lines, or a commented out code: value.
218# code = PLAIN_LINE*
219# | '## code:' VALUE
220#
221# -- Key value pairs can be single- or multi-line
222# key_value = '##' KEY ':' VALUE
223# | KEY_VALUE_MULTILINE PLAIN_LINE* END_MULTILINE
224#
225# -- Description, then key-value pairs surrounding code.
226# test_case = '####' DESC
227# key_value*
228# code
229# key_value*
230#
231# -- Should be a blank line after each test case. Leading comments and code
232# -- are OK.
233#
234# test_file =
235# key_value* -- file level metadata
236# (test_case '\n')*
237
238
239def ParseKeyValue(tokens, case):
240 """Parse commented-out metadata in a test case.
241
242 The metadata must be contiguous.
243
244 Args:
245 tokens: Tokenizer
246 case: dictionary to add to
247 """
248 while True:
249 line_num, kind, item = tokens.peek()
250
251 if kind == KEY_VALUE_MULTILINE:
252 qualifier, shells, name, empty_value = item
253 if empty_value:
254 raise ParseError(
255 'Line %d: got value %r for %r, but the value should be on the '
256 'following lines' % (line_num, empty_value, name))
257
258 value_lines = []
259 while True:
260 tokens.next(lex_mode=LEX_RAW) # empty lines aren't skipped
261 _, kind2, item2 = tokens.peek()
262 if kind2 != PLAIN_LINE:
263 break
264 value_lines.append(item2)
265
266 value = ''.join(value_lines)
267
268 name = name.lower() # STDOUT -> stdout
269 if qualifier:
270 AddMetadataToCase(case, qualifier, shells, name, value,
271 line_num)
272 else:
273 case[name] = value
274
275 # END token is optional.
276 if kind2 == END_MULTILINE:
277 tokens.next()
278
279 elif kind == KEY_VALUE:
280 qualifier, shells, name, value = item
281
282 if qualifier:
283 AddMetadataToCase(case, qualifier, shells, name, value,
284 line_num)
285 else:
286 case[name] = value
287
288 tokens.next()
289
290 else: # Unknown token type
291 break
292
293
294def ParseCodeLines(tokens, case):
295 """Parse uncommented code in a test case."""
296 _, kind, item = tokens.peek()
297 if kind != PLAIN_LINE:
298 raise ParseError('Expected a line of code (got %r, %r)' % (kind, item))
299 code_lines = []
300 while True:
301 _, kind, item = tokens.peek()
302 if kind != PLAIN_LINE:
303 case['code'] = ''.join(code_lines)
304 return
305 code_lines.append(item)
306 tokens.next(lex_mode=LEX_RAW)
307
308
309def ParseTestCase(tokens):
310 """Parse a single test case and return it.
311
312 If at EOF, return None.
313 """
314 line_num, kind, item = tokens.peek()
315 if kind == EOF:
316 return None
317
318 if kind != TEST_CASE_BEGIN:
319 raise RuntimeError("line %d: Expected TEST_CASE_BEGIN, got %r" %
320 (line_num, [kind, item]))
321
322 tokens.next()
323
324 case = {'desc': item, 'line_num': line_num}
325
326 ParseKeyValue(tokens, case)
327
328 # For broken code
329 if 'code' in case: # Got it through a key value pair
330 return case
331
332 ParseCodeLines(tokens, case)
333 ParseKeyValue(tokens, case)
334
335 return case
336
337
338_META_FIELDS = [
339 'our_shell',
340 'compare_shells',
341 'suite',
342 'tags',
343 'oils_failures_allowed',
344 'oils_cpp_failures_allowed',
345]
346
347
348def ParseTestFile(test_file, tokens):
349 """
350 test_file: Only for error message
351 """
352 file_metadata = {}
353 test_cases = []
354
355 try:
356 # Skip over the header. Setup code can go here, although would we have to
357 # execute it on every case?
358 while True:
359 line_num, kind, item = tokens.peek()
360 if kind != KEY_VALUE:
361 break
362
363 qualifier, shells, name, value = item
364 if qualifier is not None:
365 raise RuntimeError('Invalid qualifier in spec file metadata')
366 if shells is not None:
367 raise RuntimeError('Invalid shells in spec file metadata')
368
369 file_metadata[name] = value
370
371 tokens.next()
372
373 while True: # Loop over cases
374 test_case = ParseTestCase(tokens)
375 if test_case is None:
376 break
377 test_cases.append(test_case)
378
379 except StopIteration:
380 raise RuntimeError('Unexpected EOF parsing test cases')
381
382 for name in file_metadata:
383 if name not in _META_FIELDS:
384 raise RuntimeError('Invalid file metadata %r in %r' %
385 (name, test_file))
386
387 return file_metadata, test_cases
388
389
390def CreateStringAssertion(d, key, assertions, qualifier=False):
391 found = False
392
393 exp = d.get(key)
394 if exp is not None:
395 a = EqualAssertion(key, exp, qualifier=qualifier)
396 assertions.append(a)
397 found = True
398
399 exp_json = d.get(key + '-json')
400 if exp_json is not None:
401 exp = json.loads(exp_json, encoding='utf-8')
402 a = EqualAssertion(key, exp, qualifier=qualifier)
403 assertions.append(a)
404 found = True
405
406 # For testing invalid unicode
407 exp_repr = d.get(key + '-repr')
408 if exp_repr is not None:
409 exp = eval(exp_repr)
410 a = EqualAssertion(key, exp, qualifier=qualifier)
411 assertions.append(a)
412 found = True
413
414 return found
415
416
417def CreateIntAssertion(d, key, assertions, qualifier=False):
418 exp = d.get(key) # expected
419 if exp is not None:
420 # For now, turn it into int
421 a = EqualAssertion(key, int(exp), qualifier=qualifier)
422 assertions.append(a)
423 return True
424 return False
425
426
427def CreateAssertions(case, sh_label):
428 """Given a raw test case and a shell label, create EqualAssertion instances
429 to run."""
430 assertions = []
431
432 # Whether we found assertions
433 stdout = False
434 stderr = False
435 status = False
436
437 # So the assertion are exactly the same for osh and osh_ALT
438
439 if sh_label.startswith('osh'):
440 case_sh = 'osh'
441 elif sh_label.startswith('bash'):
442 case_sh = 'bash'
443 else:
444 case_sh = sh_label
445
446 if case_sh in case:
447 q = case[case_sh]['qualifier']
448 if CreateStringAssertion(case[case_sh],
449 'stdout',
450 assertions,
451 qualifier=q):
452 stdout = True
453 if CreateStringAssertion(case[case_sh],
454 'stderr',
455 assertions,
456 qualifier=q):
457 stderr = True
458 if CreateIntAssertion(case[case_sh], 'status', assertions,
459 qualifier=q):
460 status = True
461
462 if not stdout:
463 CreateStringAssertion(case, 'stdout', assertions)
464 if not stderr:
465 CreateStringAssertion(case, 'stderr', assertions)
466 if not status:
467 if 'status' in case:
468 CreateIntAssertion(case, 'status', assertions)
469 else:
470 # If the user didn't specify a 'status' assertion, assert that the exit
471 # code is 0.
472 a = EqualAssertion('status', 0)
473 assertions.append(a)
474
475 no_traceback = SubstringAssertion('stderr', 'Traceback (most recent')
476 assertions.append(no_traceback)
477
478 #print 'SHELL', shell
479 #pprint.pprint(case)
480 #print(assertions)
481 return assertions
482
483
484class Result(object):
485 """Result of an stdout/stderr/status assertion or of a (case, shell) cell.
486
487 Order is important: the result of a cell is the minimum of the results of
488 each assertion.
489 """
490 TIMEOUT = 0 # ONLY a cell result, not an assertion result
491 FAIL = 1
492 BUG = 2
493 NI = 3
494 OK = 4
495 PASS = 5
496
497 length = 6 # for loops
498
499
500def QualifierToResult(qualifier):
501 # type: (str) -> Result
502 if qualifier == 'BUG': # equal, but known bad
503 return Result.BUG
504 if qualifier == 'N-I': # equal, and known UNIMPLEMENTED
505 return Result.NI
506 if qualifier == 'OK': # equal, but ok (not ideal)
507 return Result.OK
508 return Result.PASS # ideal behavior
509
510
511class EqualAssertion(object):
512 """Check that two values are equal."""
513
514 def __init__(self, key, expected, qualifier=None):
515 self.key = key
516 self.expected = expected # expected value
517 self.qualifier = qualifier # whether this was a special case?
518
519 def __repr__(self):
520 return '<EqualAssertion %s == %r>' % (self.key, self.expected)
521
522 def Check(self, shell, record):
523 actual = record[self.key]
524 if actual != self.expected:
525 if len(str(self.expected)) < 40:
526 msg = '[%s %s] Expected %r, got %r' % (shell, self.key,
527 self.expected, actual)
528 else:
529 msg = '''
530[%s %s]
531Expected %r
532Got %r
533''' % (shell, self.key, self.expected, actual)
534
535 # TODO: Make this better and add a flag for it.
536 if 0:
537 import difflib
538 for line in difflib.unified_diff(self.expected,
539 actual,
540 fromfile='expected',
541 tofile='actual'):
542 print(repr(line))
543
544 return Result.FAIL, msg
545
546 return QualifierToResult(self.qualifier), ''
547
548
549class SubstringAssertion(object):
550 """Check that a string like stderr doesn't have a substring."""
551
552 def __init__(self, key, substring):
553 self.key = key
554 self.substring = substring
555
556 def __repr__(self):
557 return '<SubstringAssertion %s == %r>' % (self.key, self.substring)
558
559 def Check(self, shell, record):
560 actual = record[self.key]
561 if self.substring in actual:
562 msg = '[%s %s] Found %r' % (shell, self.key, self.substring)
563 return Result.FAIL, msg
564 return Result.PASS, ''
565
566
567class Stats(object):
568
569 def __init__(self, num_cases, sh_labels):
570 self.counters = collections.defaultdict(int)
571 c = self.counters
572 c['num_cases'] = num_cases
573 c['oils_num_passed'] = 0
574 c['oils_num_failed'] = 0
575 c['oils_cpp_num_failed'] = 0
576 # Number of osh_ALT results that differed from osh.
577 c['oils_ALT_delta'] = 0
578
579 self.by_shell = {}
580 for sh in sh_labels:
581 self.by_shell[sh] = collections.defaultdict(int)
582 self.nonzero_results = collections.defaultdict(int)
583
584 self.tsv_rows = []
585
586 def Inc(self, counter_name):
587 self.counters[counter_name] += 1
588
589 def Get(self, counter_name):
590 return self.counters[counter_name]
591
592 def Set(self, counter_name, val):
593 self.counters[counter_name] = val
594
595 def ReportCell(self, case_num, cell_result, sh_label):
596 self.tsv_rows.append(
597 (str(case_num), sh_label, TEXT_CELLS[cell_result]))
598
599 self.by_shell[sh_label][cell_result] += 1
600 self.nonzero_results[cell_result] += 1
601
602 c = self.counters
603 if cell_result == Result.TIMEOUT:
604 c['num_timeout'] += 1
605 elif cell_result == Result.FAIL:
606 # Special logic: don't count osh_ALT because its failures will be
607 # counted in the delta.
608 if sh_label not in OTHER_OILS:
609 c['num_failed'] += 1
610
611 if sh_label in OSH_CPYTHON + YSH_CPYTHON:
612 c['oils_num_failed'] += 1
613
614 if sh_label in ('osh-cpp', 'ysh-cpp'):
615 c['oils_cpp_num_failed'] += 1
616 elif cell_result == Result.BUG:
617 c['num_bug'] += 1
618 elif cell_result == Result.NI:
619 c['num_ni'] += 1
620 elif cell_result == Result.OK:
621 c['num_ok'] += 1
622 elif cell_result == Result.PASS:
623 c['num_passed'] += 1
624 if sh_label in OSH_CPYTHON + YSH_CPYTHON:
625 c['oils_num_passed'] += 1
626 else:
627 raise AssertionError()
628
629 def WriteTsv(self, f):
630 f.write('case\tshell\tresult\n')
631 for row in self.tsv_rows:
632 f.write('\t'.join(row))
633 f.write('\n')
634
635
636PIPE = subprocess.PIPE
637
638
639def RunCases(cases, case_predicate, shells, env, out, opts):
640 """Run a list of test 'cases' for all 'shells' and write output to
641 'out'."""
642 if opts.trace:
643 for _, sh in shells:
644 log('\tshell: %s', sh)
645 print('\twhich $SH: ', end='', file=sys.stderr)
646 subprocess.call(['which', sh])
647
648 #pprint.pprint(cases)
649 if isinstance(case_predicate, spec_lib.RangePredicate) and (
650 case_predicate.begin > (len(cases) - 1)
651 ):
652 raise RuntimeError(
653 "valid case indexes are from 0 to %s. given range: %s-%s"
654 % ((len(cases) - 1), case_predicate.begin, case_predicate.end)
655 )
656
657 sh_labels = [sh_label for sh_label, _ in shells]
658
659 out.WriteHeader(sh_labels)
660 stats = Stats(len(cases), sh_labels)
661
662 # Make an environment for each shell. $SH is the path to the shell, so we
663 # can test flags, etc.
664 sh_env = []
665 for _, sh_path in shells:
666 e = dict(env)
667 e[opts.sh_env_var_name] = sh_path
668 sh_env.append(e)
669
670 # Determine which one (if any) is osh-cpython, for comparison against other
671 # shells.
672 osh_cpython_index = -1
673 for i, (sh_label, _) in enumerate(shells):
674 if sh_label in OSH_CPYTHON:
675 osh_cpython_index = i
676 break
677
678 timeout_dir = os.path.abspath('_tmp/spec/timeouts')
679 try:
680 shutil.rmtree(timeout_dir)
681 os.mkdir(timeout_dir)
682 except OSError:
683 pass
684
685 # Now run each case, and print a table.
686 for i, case in enumerate(cases):
687 line_num = case['line_num']
688 desc = case['desc']
689 code = case['code']
690
691 if opts.trace:
692 log('case %d: %s', i, desc)
693
694 if not case_predicate(i, case):
695 stats.Inc('num_skipped')
696 continue
697
698 if opts.do_print:
699 print('#### %s' % case['desc'])
700 print(case['code'])
701 print()
702 continue
703
704 stats.Inc('num_cases_run')
705
706 result_row = []
707
708 for shell_index, (sh_label, sh_path) in enumerate(shells):
709 timeout_file = os.path.join(timeout_dir, '%02d-%s' % (i, sh_label))
710 if opts.timeout:
711 if opts.timeout_bin:
712 # This is what smoosh itself uses. See smoosh/tests/shell_tests.sh
713 # QUIRK: interval can only be a whole number
714 argv = [
715 opts.timeout_bin,
716 '-t',
717 opts.timeout,
718 # Somehow I'm not able to get this timeout file working? I think
719 # it has a bug when using stdin. It waits for the background
720 # process too.
721
722 #'-i', '1',
723 #'-l', timeout_file
724 ]
725 else:
726 # This kills hanging tests properly, but somehow they fail with code
727 # -9?
728 #argv = ['timeout', '-s', 'KILL', opts.timeout]
729
730 # s suffix for seconds
731 argv = ['timeout', opts.timeout + 's']
732 else:
733 argv = []
734 argv.append(sh_path)
735
736 # dash doesn't support -o posix
737 if opts.posix and sh_label != 'dash':
738 argv.extend(['-o', 'posix'])
739
740 if opts.trace:
741 log('\targv: %s', ' '.join(argv))
742
743 case_env = sh_env[shell_index]
744
745 # Unique dir for every test case and shell
746 tmp_base = os.path.normpath(opts.tmp_env) # no . or ..
747 case_tmp_dir = os.path.join(tmp_base, '%02d-%s' % (i, sh_label))
748
749 try:
750 os.makedirs(case_tmp_dir)
751 except OSError as e:
752 if e.errno != errno.EEXIST:
753 raise
754
755 # Some tests assume _tmp exists
756 # TODO: get rid of this in the common case, to save inodes! I guess have
757 # an opt-in setting per FILE, like make_underscore_tmp: true.
758 try:
759 os.mkdir(os.path.join(case_tmp_dir, '_tmp'))
760 except OSError as e:
761 if e.errno != errno.EEXIST:
762 raise
763
764 case_env['TMP'] = case_tmp_dir
765
766 if opts.pyann_out_dir:
767 case_env = dict(case_env)
768 case_env['PYANN_OUT'] = os.path.join(opts.pyann_out_dir,
769 '%d.json' % i)
770
771 try:
772 p = subprocess.Popen(argv,
773 env=case_env,
774 cwd=case_tmp_dir,
775 stdin=PIPE,
776 stdout=PIPE,
777 stderr=PIPE)
778 except OSError as e:
779 print('Error running %r: %s' % (sh_path, e), file=sys.stderr)
780 sys.exit(1)
781
782 p.stdin.write(code)
783
784 actual = {}
785 actual['stdout'], actual['stderr'] = p.communicate()
786
787 actual['status'] = p.wait()
788
789 if opts.timeout_bin and os.path.exists(timeout_file):
790 cell_result = Result.TIMEOUT
791 elif not opts.timeout_bin and actual['status'] == 124:
792 cell_result = Result.TIMEOUT
793 else:
794 messages = []
795 cell_result = Result.PASS
796
797 # TODO: Warn about no assertions? Well it will always test the error
798 # code.
799 assertions = CreateAssertions(case, sh_label)
800 for a in assertions:
801 result, msg = a.Check(sh_label, actual)
802 # The minimum one wins.
803 # If any failed, then the result is FAIL.
804 # If any are OK, but none are FAIL, the result is OK.
805 cell_result = min(cell_result, result)
806 if msg:
807 messages.append(msg)
808
809 if cell_result != Result.PASS or opts.details:
810 d = (i, sh_label, actual['stdout'], actual['stderr'],
811 messages)
812 out.AddDetails(d)
813
814 result_row.append(cell_result)
815
816 stats.ReportCell(i, cell_result, sh_label)
817
818 if sh_label in OTHER_OSH:
819 # This is only an error if we tried to run ANY OSH.
820 if osh_cpython_index == -1:
821 raise RuntimeError(
822 "Couldn't determine index of osh-cpython")
823
824 other_result = result_row[shell_index]
825 cpython_result = result_row[osh_cpython_index]
826 if other_result != cpython_result:
827 stats.Inc('oils_ALT_delta')
828
829 out.WriteRow(i, line_num, result_row, desc)
830
831 return stats
832
833
834# ANSI color constants
835_RESET = '\033[0;0m'
836_BOLD = '\033[1m'
837
838_RED = '\033[31m'
839_GREEN = '\033[32m'
840_YELLOW = '\033[33m'
841_PURPLE = '\033[35m'
842
843TEXT_CELLS = {
844 Result.TIMEOUT: 'TIME',
845 Result.FAIL: 'FAIL',
846 Result.BUG: 'BUG',
847 Result.NI: 'N-I',
848 Result.OK: 'ok',
849 Result.PASS: 'pass',
850}
851
852ANSI_COLORS = {
853 Result.TIMEOUT: _PURPLE,
854 Result.FAIL: _RED,
855 Result.BUG: _YELLOW,
856 Result.NI: _YELLOW,
857 Result.OK: _YELLOW,
858 Result.PASS: _GREEN,
859}
860
861
862def _AnsiCells():
863 lookup = {}
864 for i in xrange(Result.length):
865 lookup[i] = ''.join([ANSI_COLORS[i], _BOLD, TEXT_CELLS[i], _RESET])
866 return lookup
867
868
869ANSI_CELLS = _AnsiCells()
870
871HTML_CELLS = {
872 Result.TIMEOUT: '<td class="timeout">TIME',
873 Result.FAIL: '<td class="fail">FAIL',
874 Result.BUG: '<td class="bug">BUG',
875 Result.NI: '<td class="n-i">N-I',
876 Result.OK: '<td class="ok">ok',
877 Result.PASS: '<td class="pass">pass',
878}
879
880
881def _ValidUtf8String(s):
882 """Return an arbitrary string as a readable utf-8 string.
883
884 We output utf-8 to either HTML or the console. If we get invalid
885 utf-8 as stdout/stderr (which is very possible), then show the ASCII
886 repr().
887 """
888 try:
889 s.decode('utf-8')
890 return s # it decoded OK
891 except UnicodeDecodeError:
892 return repr(s) # ASCII representation
893
894
895class Output(object):
896
897 def __init__(self, f, verbose):
898 self.f = f
899 self.verbose = verbose
900 self.details = []
901
902 def BeginCases(self, test_file):
903 pass
904
905 def WriteHeader(self, sh_labels):
906 pass
907
908 def WriteRow(self, i, line_num, row, desc):
909 pass
910
911 def EndCases(self, sh_labels, stats):
912 pass
913
914 def AddDetails(self, entry):
915 self.details.append(entry)
916
917 # Helper function
918 def _WriteDetailsAsText(self, details):
919 for case_index, shell, stdout, stderr, messages in details:
920 print('case: %d' % case_index, file=self.f)
921 for m in messages:
922 print(m, file=self.f)
923
924 # Assume the terminal can show utf-8, but we don't want random binary.
925 print('%s stdout:' % shell, file=self.f)
926 print(_ValidUtf8String(stdout), file=self.f)
927
928 print('%s stderr:' % shell, file=self.f)
929 print(_ValidUtf8String(stderr), file=self.f)
930
931 print('', file=self.f)
932
933
934class TeeOutput(object):
935 """For multiple outputs in one run, e.g. HTML and TSV.
936
937 UNUSED
938 """
939
940 def __init__(self, outs):
941 self.outs = outs
942
943 def BeginCases(self, test_file):
944 for out in self.outs:
945 out.BeginCases(test_file)
946
947 def WriteHeader(self, sh_labels):
948 for out in self.outs:
949 out.WriteHeader(sh_labels)
950
951 def WriteRow(self, i, line_num, row, desc):
952 for out in self.outs:
953 out.WriteRow(i, line_num, row, desc)
954
955 def EndCases(self, sh_labels, stats):
956 for out in self.outs:
957 out.EndCases(sh_labels, stats)
958
959 def AddDetails(self, entry):
960 for out in self.outs:
961 out.AddDetails(entry)
962
963
964class TsvOutput(Output):
965 """Write a plain-text TSV file.
966
967 UNUSED since we are outputting LONG format with --tsv-output.
968 """
969
970 def WriteHeader(self, sh_labels):
971 self.f.write('case\tline\t') # case number and line number
972 for sh_label in sh_labels:
973 self.f.write(sh_label)
974 self.f.write('\t')
975 self.f.write('\n')
976
977 def WriteRow(self, i, line_num, row, desc):
978 self.f.write('%3d\t%3d\t' % (i, line_num))
979
980 for result in row:
981 c = TEXT_CELLS[result]
982 self.f.write(c)
983 self.f.write('\t')
984
985 # note: 'desc' could use TSV8, but just ignore it for now
986 #self.f.write(desc)
987 self.f.write('\n')
988
989
990class AnsiOutput(Output):
991
992 def BeginCases(self, test_file):
993 self.f.write('%s\n' % test_file)
994
995 def WriteHeader(self, sh_labels):
996 self.f.write(_BOLD)
997 self.f.write('case\tline\t') # case number and line number
998 for sh_label in sh_labels:
999 self.f.write(sh_label)
1000 self.f.write('\t')
1001 self.f.write(_RESET)
1002 self.f.write('\n')
1003
1004 def WriteRow(self, i, line_num, row, desc):
1005 self.f.write('%3d\t%3d\t' % (i, line_num))
1006
1007 for result in row:
1008 c = ANSI_CELLS[result]
1009 self.f.write(c)
1010 self.f.write('\t')
1011
1012 self.f.write(desc)
1013 self.f.write('\n')
1014
1015 if self.verbose:
1016 self._WriteDetailsAsText(self.details)
1017 self.details = []
1018
1019 def _WriteShellSummary(self, sh_labels, stats):
1020 if len(stats.nonzero_results) <= 1: # Skip trivial summaries
1021 return
1022
1023 # Reiterate header
1024 self.f.write(_BOLD)
1025 self.f.write('\t\t')
1026 for sh_label in sh_labels:
1027 self.f.write(sh_label)
1028 self.f.write('\t')
1029 self.f.write(_RESET)
1030 self.f.write('\n')
1031
1032 # Write totals by cell.
1033 for result in sorted(stats.nonzero_results, reverse=True):
1034 self.f.write('\t%s' % ANSI_CELLS[result])
1035 for sh_label in sh_labels:
1036 self.f.write('\t%d' % stats.by_shell[sh_label][result])
1037 self.f.write('\n')
1038
1039 # The bottom row is all the same, but it helps readability.
1040 self.f.write('\ttotal')
1041 for sh_label in sh_labels:
1042 self.f.write('\t%d' % stats.counters['num_cases_run'])
1043 self.f.write('\n')
1044 self.f.write('\n')
1045
1046 def EndCases(self, sh_labels, stats):
1047 print()
1048 self._WriteShellSummary(sh_labels, stats)
1049
1050
1051class HtmlOutput(Output):
1052
1053 def __init__(self, f, verbose, spec_name, sh_labels, cases):
1054 Output.__init__(self, f, verbose)
1055 self.spec_name = spec_name
1056 self.sh_labels = sh_labels # saved from header
1057 self.cases = cases # for linking to code
1058 self.row_html = [] # buffered
1059
1060 def _SourceLink(self, line_num, desc):
1061 return '<a href="%s.test.html#L%d">%s</a>' % (self.spec_name, line_num,
1062 cgi.escape(desc))
1063
1064 def BeginCases(self, test_file):
1065 css_urls = ['../../../web/base.css', '../../../web/spec-tests.css']
1066 title = '%s: spec test case results' % self.spec_name
1067 html_head.Write(self.f, title, css_urls=css_urls)
1068
1069 self.f.write('''\
1070 <body class="width60">
1071 <p id="home-link">
1072 <a href=".">spec test index</a>
1073 /
1074 <a href="/">oils.pub</a>
1075 </p>
1076 <h1>Results for %s</h1>
1077 <table>
1078 ''' % test_file)
1079
1080 def _WriteShellSummary(self, sh_labels, stats):
1081 # NOTE: This table has multiple <thead>, which seems OK.
1082 self.f.write('''
1083<thead>
1084 <tr class="table-header">
1085 ''')
1086
1087 columns = ['status'] + sh_labels + ['']
1088 for c in columns:
1089 self.f.write('<td>%s</td>' % c)
1090
1091 self.f.write('''
1092 </tr>
1093</thead>
1094''')
1095
1096 # Write totals by cell.
1097 for result in sorted(stats.nonzero_results, reverse=True):
1098 self.f.write('<tr>')
1099
1100 self.f.write(HTML_CELLS[result])
1101 self.f.write('</td> ')
1102
1103 for sh_label in sh_labels:
1104 self.f.write('<td>%d</td>' % stats.by_shell[sh_label][result])
1105
1106 self.f.write('<td></td>')
1107 self.f.write('</tr>\n')
1108
1109 # The bottom row is all the same, but it helps readability.
1110 self.f.write('<tr>')
1111 self.f.write('<td>total</td>')
1112 for sh_label in sh_labels:
1113 self.f.write('<td>%d</td>' % stats.counters['num_cases_run'])
1114 self.f.write('<td></td>')
1115 self.f.write('</tr>\n')
1116
1117 # Blank row for space.
1118 self.f.write('<tr>')
1119 for i in xrange(len(sh_labels) + 2):
1120 self.f.write('<td style="height: 2em"></td>')
1121 self.f.write('</tr>\n')
1122
1123 def WriteHeader(self, sh_labels):
1124 f = cStringIO.StringIO()
1125
1126 f.write('''
1127<thead>
1128 <tr class="table-header">
1129 ''')
1130
1131 columns = ['case'] + sh_labels
1132 for c in columns:
1133 f.write('<td>%s</td>' % c)
1134 f.write('<td class="case-desc">description</td>')
1135
1136 f.write('''
1137 </tr>
1138</thead>
1139''')
1140
1141 self.row_html.append(f.getvalue())
1142
1143 def WriteRow(self, i, line_num, row, desc):
1144 f = cStringIO.StringIO()
1145 f.write('<tr>')
1146 f.write('<td>%3d</td>' % i)
1147
1148 show_details = False
1149
1150 for result in row:
1151 c = HTML_CELLS[result]
1152 if result not in (Result.PASS, Result.TIMEOUT): # nothing to show
1153 show_details = True
1154
1155 f.write(c)
1156 f.write('</td>')
1157 f.write('\t')
1158
1159 f.write('<td class="case-desc">')
1160 f.write(self._SourceLink(line_num, desc))
1161 f.write('</td>')
1162 f.write('</tr>\n')
1163
1164 # Show row with details link.
1165 if show_details:
1166 f.write('<tr>')
1167 f.write('<td class="details-row"></td>') # for the number
1168
1169 for col_index, result in enumerate(row):
1170 f.write('<td class="details-row">')
1171 if result != Result.PASS:
1172 sh_label = self.sh_labels[col_index]
1173 f.write('<a href="#details-%s-%s">details</a>' %
1174 (i, sh_label))
1175 f.write('</td>')
1176
1177 f.write('<td class="details-row"></td>') # for the description
1178 f.write('</tr>\n')
1179
1180 self.row_html.append(f.getvalue()) # buffer it
1181
1182 def _WriteStats(self, stats):
1183 self.f.write('%(num_passed)d passed, %(num_ok)d OK, '
1184 '%(num_ni)d not implemented, %(num_bug)d BUG, '
1185 '%(num_failed)d failed, %(num_timeout)d timeouts, '
1186 '%(num_skipped)d cases skipped\n' % stats.counters)
1187
1188 def EndCases(self, sh_labels, stats):
1189 self._WriteShellSummary(sh_labels, stats)
1190
1191 # Write all the buffered rows
1192 for h in self.row_html:
1193 self.f.write(h)
1194
1195 self.f.write('</table>\n')
1196 self.f.write('<pre>')
1197 self._WriteStats(stats)
1198 if stats.Get('oils_num_failed'):
1199 self.f.write('%(oils_num_failed)d failed under osh\n' %
1200 stats.counters)
1201 self.f.write('</pre>')
1202
1203 if self.details:
1204 self._WriteDetails()
1205
1206 self.f.write('</body></html>')
1207
1208 def _WriteDetails(self):
1209 self.f.write("<h2>Details on runs that didn't PASS</h2>")
1210 self.f.write('<table id="details">')
1211
1212 for case_index, sh_label, stdout, stderr, messages in self.details:
1213 self.f.write('<tr>')
1214 self.f.write('<td><a name="details-%s-%s"></a><b>%s</b></td>' %
1215 (case_index, sh_label, sh_label))
1216
1217 self.f.write('<td>')
1218
1219 # Write description and link to the code
1220 case = self.cases[case_index]
1221 line_num = case['line_num']
1222 desc = case['desc']
1223 self.f.write('%d ' % case_index)
1224 self.f.write(self._SourceLink(line_num, desc))
1225 self.f.write('<br/><br/>\n')
1226
1227 for m in messages:
1228 self.f.write('<span class="assertion">%s</span><br/>\n' %
1229 cgi.escape(m))
1230 if messages:
1231 self.f.write('<br/>\n')
1232
1233 def _WriteRaw(s):
1234 self.f.write('<pre>')
1235
1236 # stdout might contain invalid utf-8; make it valid;
1237 valid_utf8 = _ValidUtf8String(s)
1238
1239 self.f.write(cgi.escape(valid_utf8))
1240 self.f.write('</pre>')
1241
1242 self.f.write('<i>stdout:</i> <br/>\n')
1243 _WriteRaw(stdout)
1244
1245 self.f.write('<i>stderr:</i> <br/>\n')
1246 _WriteRaw(stderr)
1247
1248 self.f.write('</td>')
1249 self.f.write('</tr>')
1250
1251 self.f.write('</table>')
1252
1253
1254def MakeTestEnv(opts):
1255 if not opts.tmp_env:
1256 raise RuntimeError('--tmp-env required')
1257 if not opts.path_env:
1258 raise RuntimeError('--path-env required')
1259 env = {
1260 'PATH': opts.path_env,
1261 #'LANG': opts.lang_env,
1262 }
1263 for p in opts.env_pair:
1264 name, value = p.split('=', 1)
1265 env[name] = value
1266
1267 return env
1268
1269
1270def _DefaultSuite(spec_name):
1271 if spec_name.startswith('ysh-'):
1272 suite = 'ysh'
1273 elif spec_name.startswith('hay'): # hay.test.sh is ysh
1274 suite = 'ysh'
1275
1276 elif spec_name.startswith('tea-'):
1277 suite = 'tea'
1278 else:
1279 suite = 'osh'
1280
1281 return suite
1282
1283
1284def ParseTestList(test_files):
1285 for test_file in test_files:
1286 with open(test_file) as f:
1287 tokens = Tokenizer(f)
1288 try:
1289 file_metadata, cases = ParseTestFile(test_file, tokens)
1290 except RuntimeError as e:
1291 log('ERROR in %r', test_file)
1292 raise
1293 except ParseError as e:
1294 log('PARSE ERROR in %r', test_file)
1295 raise
1296
1297 tmp = os.path.basename(test_file)
1298 spec_name = tmp.split('.')[0] # foo.test.sh -> foo
1299
1300 suite = file_metadata.get('suite') or _DefaultSuite(spec_name)
1301
1302 tmp = file_metadata.get('tags')
1303 tags = tmp.split() if tmp else []
1304
1305 # Don't need compare_shells, etc. to decide what to run
1306
1307 row = {'spec_name': spec_name, 'suite': suite, 'tags': tags}
1308 #print(row)
1309 yield row
1310
1311
1312def main(argv):
1313 # First check if bash is polluting the environment. Tests rely on the
1314 # environment.
1315 v = os.getenv('RANDOM')
1316 if v is not None:
1317 raise AssertionError('got $RANDOM = %s' % v)
1318 v = os.getenv('PPID')
1319 if v is not None:
1320 raise AssertionError('got $PPID = %s' % v)
1321
1322 p = optparse.OptionParser('%s [options] TEST_FILE shell...' % sys.argv[0])
1323 spec_lib.DefineCommon(p)
1324 spec_lib.DefineShSpec(p)
1325 opts, argv = p.parse_args(argv)
1326
1327 # --print-tagged to figure out what to run
1328 if opts.print_tagged:
1329 to_find = opts.print_tagged
1330 for row in ParseTestList(argv[1:]):
1331 if to_find in row['tags']:
1332 print(row['spec_name'])
1333 return 0
1334
1335 # --print-table to figure out what to run
1336 if opts.print_table:
1337 for row in ParseTestList(argv[1:]):
1338 print('%(suite)s\t%(spec_name)s' % row)
1339 #print(row)
1340 return 0
1341
1342 #
1343 # Now deal with a single file
1344 #
1345
1346 try:
1347 test_file = argv[1]
1348 except IndexError:
1349 p.print_usage()
1350 return 1
1351
1352 with open(test_file) as f:
1353 tokens = Tokenizer(f)
1354 file_metadata, cases = ParseTestFile(test_file, tokens)
1355
1356 # List test cases and return
1357 if opts.do_list:
1358 for i, case in enumerate(cases):
1359 if opts.verbose: # print the raw dictionary for debugging
1360 print(pprint.pformat(case))
1361 else:
1362 print('%d\t%s' % (i, case['desc']))
1363 return 0
1364
1365 # for test/spec-cpp.sh
1366 if opts.print_spec_suite:
1367 tmp = os.path.basename(test_file)
1368 spec_name = tmp.split('.')[0] # foo.test.sh -> foo
1369
1370 suite = file_metadata.get('suite') or _DefaultSuite(spec_name)
1371 print(suite)
1372 return 0
1373
1374 if opts.verbose:
1375 for k, v in file_metadata.items():
1376 print('\t%-20s: %s' % (k, v), file=sys.stderr)
1377 print('', file=sys.stderr)
1378
1379 if opts.oils_bin_dir:
1380
1381 shells = []
1382
1383 if opts.compare_shells:
1384 comp = file_metadata.get('compare_shells')
1385 # Compare 'compare_shells' and Python
1386 shells.extend(comp.split() if comp else [])
1387
1388 # Always run with the Python version
1389 our_shell = file_metadata.get('our_shell', 'osh') # default is OSH
1390 if our_shell != '-':
1391 shells.append(os.path.join(opts.oils_bin_dir, our_shell))
1392
1393 # Legacy OVM/CPython build
1394 if opts.ovm_bin_dir:
1395 shells.append(os.path.join(opts.ovm_bin_dir, our_shell))
1396
1397 # New C++ build
1398 if opts.oils_cpp_bin_dir:
1399 shells.append(os.path.join(opts.oils_cpp_bin_dir, our_shell))
1400
1401 # Overwrite it when --oils-bin-dir is set
1402 # It's no longer a flag
1403 opts.oils_failures_allowed = \
1404 int(file_metadata.get('oils_failures_allowed', 0))
1405
1406 else:
1407 # TODO: remove this mode?
1408 shells = argv[2:]
1409
1410 shell_pairs = spec_lib.MakeShellPairs(shells)
1411
1412 if opts.range:
1413 begin, end = spec_lib.ParseRange(opts.range)
1414 case_predicate = spec_lib.RangePredicate(begin, end)
1415 elif opts.regex:
1416 desc_re = re.compile(opts.regex, re.IGNORECASE)
1417 case_predicate = spec_lib.RegexPredicate(desc_re)
1418 else:
1419 case_predicate = lambda i, case: True
1420
1421 out_f = sys.stderr if opts.do_print else sys.stdout
1422
1423 # Set up output style. Also see asdl/format.py
1424 if opts.format == 'ansi':
1425 out = AnsiOutput(out_f, opts.verbose)
1426
1427 elif opts.format == 'html':
1428 spec_name = os.path.basename(test_file)
1429 spec_name = spec_name.split('.')[0]
1430
1431 sh_labels = [label for label, _ in shell_pairs]
1432
1433 out = HtmlOutput(out_f, opts.verbose, spec_name, sh_labels, cases)
1434
1435 else:
1436 raise AssertionError()
1437
1438 out.BeginCases(os.path.basename(test_file))
1439
1440 env = MakeTestEnv(opts)
1441 stats = RunCases(cases, case_predicate, shell_pairs, env, out, opts)
1442
1443 out.EndCases([sh_label for sh_label, _ in shell_pairs], stats)
1444
1445 if opts.tsv_output:
1446 with open(opts.tsv_output, 'w') as f:
1447 stats.WriteTsv(f)
1448
1449 # TODO: Could --stats-{file,template} be a separate awk step on .tsv files?
1450 stats.Set('oils_failures_allowed', opts.oils_failures_allowed)
1451
1452 # If it's not set separately for C++, we default to the allowed number
1453 # above
1454 x = int(
1455 file_metadata.get('oils_cpp_failures_allowed',
1456 opts.oils_failures_allowed))
1457 stats.Set('oils_cpp_failures_allowed', x)
1458
1459 if opts.stats_file:
1460 with open(opts.stats_file, 'w') as f:
1461 f.write(opts.stats_template % stats.counters)
1462 f.write('\n') # bash 'read' requires a newline
1463
1464 # spec/smoke.test.sh -> smoke
1465 test_name = os.path.basename(test_file).split('.')[0]
1466
1467 return _SuccessOrFailure(test_name, stats)
1468
1469
1470def _SuccessOrFailure(test_name, stats):
1471 allowed = stats.Get('oils_failures_allowed')
1472 allowed_cpp = stats.Get('oils_cpp_failures_allowed')
1473
1474 all_count = stats.Get('num_failed')
1475 oils_count = stats.Get('oils_num_failed')
1476 oils_cpp_count = stats.Get('oils_cpp_num_failed')
1477
1478 errors = []
1479 if oils_count != allowed:
1480 errors.append('Got %d Oils failures, but %d are allowed' %
1481 (oils_count, allowed))
1482 else:
1483 if allowed != 0:
1484 log('%s: note: Got %d allowed Oils failures', test_name, allowed)
1485
1486 # TODO: remove special case for 0
1487 if oils_cpp_count != 0:
1488 if oils_cpp_count != allowed_cpp:
1489 errors.append('Got %d Oils C++ failures, but %d are allowed' %
1490 (oils_cpp_count, allowed_cpp))
1491 else:
1492 if allowed_cpp != 0:
1493 log('%s: note: Got %d allowed Oils C++ failures', test_name,
1494 allowed_cpp)
1495
1496 if all_count != allowed:
1497 errors.append('Got %d total failures, but %d are allowed' %
1498 (all_count, allowed))
1499
1500 if errors:
1501 for msg in errors:
1502 log('%s: FATAL: %s', test_name, msg)
1503 return 1
1504
1505 return 0
1506
1507
1508if __name__ == '__main__':
1509 try:
1510 sys.exit(main(sys.argv))
1511 except KeyboardInterrupt as e:
1512 print('%s: interrupted with Ctrl-C' % sys.argv[0], file=sys.stderr)
1513 sys.exit(1)
1514 except RuntimeError as e:
1515 print('FATAL: %s' % e, file=sys.stderr)
1516 sys.exit(1)