should.py 30.2 KB
Newer Older
1 2
#!/usr/bin/env python3

3
# should -- Test command-line applications through .should files
4 5 6 7 8 9 10 11 12 13 14
#
# Copyright (C) 2018 by CRIStAL (UMR CNRS 9189, Université Lille) and Inria Lille
# Contributors:
#     Mathieu Giraud <mathieu.giraud@vidjil.org>
#     Mikaël Salson <mikael.salson@vidjil.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
15
# "should" is distributed in the hope that it will be useful,
16 17 18 19 20
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
21
# along with "should". If not, see <http://www.gnu.org/licenses/>
22 23 24

import sys

25 26
if not (sys.version_info >= (3, 4)):
    print("Python >= 3.4 required")
27 28
    sys.exit(1)

29 30 31
__version_info__ = ('1','0','0+dev')
__version__ = '.'.join(__version_info__)

32 33 34 35
import re
import argparse
import subprocess
import time
36
import random
37
import os.path
38 39 40
from collections import defaultdict, OrderedDict
import xml.etree.ElementTree as ET
import datetime
41
import tempfile
42 43 44 45 46 47

# Make sure the output is in utf8
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1)

DEFAULT_CFG = 'should.cfg'
48 49
RETRY = 'should.retry'
RETRY_FLAG = '--retry'
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

TOKEN_COMMENT = '#'
TOKEN_DIRECTIVE = '!'
TOKEN_NAME = '$'
TOKEN_TEST = ':'
RE_TEST = re.compile('^(\S)*[:]')

DIRECTIVE_REQUIRES = '!REQUIRES:'
DIRECTIVE_NO_LAUNCHER = '!NO_LAUNCHER:'
DIRECTIVE_SCRIPT = '!LAUNCH:'
DIRECTIVE_OPTIONS = '!OPTIONS:'
DIRECTIVE_SOURCE = '!OUTPUT_FILE:'
DIRECTIVE_EXIT_CODE = '!EXIT_CODE:'

VAR_LAUNCHER = '$LAUNCHER'
65
VAR_EXTRA = '$EXTRA'
66 67 68 69

MOD_TODO = 'f'
MOD_REGEX = 'r'
MOD_COUNT_ALL = 'w'
70
MOD_IGNORE_CASE = 'i'
71 72 73 74
MOD_BLANKS = 'b'
MOD_MULTI_LINES = 'l'
MOD_KEEP_LEADING_TRAILING_SPACES = 'z'

75 76 77
MOD_MORE_THAN = '>'
MOD_LESS_THAN = '<'

78 79 80 81 82 83 84
TIMEOUT = 120
SHOW_ELAPSED_TIME_ABOVE = 1.0

RE_MODIFIERS = re.compile('^(\D*)(\d*)(\D*)$')

OUT_LOG = '.log'
OUT_TAP = '.tap'
85
OUT_XML = 'should.xml'
86 87 88 89

LINE = '-' * 40
ENDLINE_CHARS = '\r\n'
CONTINUATION_CHAR = '\\'
90 91
MAX_HALF_DUMP_LINES = 45
MAX_DUMP_LINES = 2*MAX_HALF_DUMP_LINES + 10
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

SKIP = 'SKIP'

TODO = 'TODO'
TODO_PASSED = 'TODO_PASSED'

STATUS = {
    None: 'not run',
    False: 'failed',
    True: 'ok',
    SKIP: 'skip',
    TODO: 'TODO',
    TODO_PASSED: 'TODO-but-ok',
}

107
WARN_STATUS = [False, SKIP, TODO, TODO_PASSED]
108

109 110 111 112 113 114 115 116 117
STATUS_TAP = {
    None: 'not run',
    False: 'not ok',
    True: 'ok',
    SKIP: 'ok # SKIP',
    TODO: 'not ok # TODO',
    TODO_PASSED: 'ok # TODO',
}

118 119 120 121
STATUS_XML = STATUS.copy()
STATUS_XML[False] = 'failure'
STATUS_XML[SKIP] = 'skipped'

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

# Simple colored output

CSIm = '\033[%sm'

class ANSI:
    RESET = 0
    BRIGHT = 1
    BLACK = 30
    RED = 31
    GREEN = 32
    YELLOW = 33
    BLUE = 34
    MAGENTA = 35
    CYAN = 36
    WHITE = 37

def color(col, text, colorize = True):
    if not colorize:
        return text
    return CSIm % ANSI.BRIGHT + CSIm % col + text + CSIm % ANSI.RESET

STATUS_COLORS = {
    None: ANSI.BLUE,
    False: ANSI.RED,
    True: ANSI.GREEN,
    SKIP: ANSI.BLUE,
    TODO: ANSI.BLUE,
    TODO_PASSED: ANSI.BLUE,
}

# Modifier parser

MODIFIERS = [
    (MOD_TODO, 'todo', 'consider that the test should fail'),
    (MOD_REGEX, 'regex', 'consider as a regular expression'),
    (MOD_COUNT_ALL, 'count-all', 'count all occurrences, even on a same line'),
159
    (MOD_IGNORE_CASE, 'ignore-case', 'ignore case changes'),
160 161 162
    (MOD_BLANKS, 'blanks', "ignore whitespace differences as soon as there is at least one space. Implies 'r'"),
    (MOD_MULTI_LINES, 'multi-lines', 'search on all the output rather than on every line'),
    (MOD_KEEP_LEADING_TRAILING_SPACES, 'ltspaces', 'keep leading and trailing spaces'),
163 164 165

    (MOD_MORE_THAN, 'more-than', 'requires that the expression occurs strictly more than the given number'),
    (MOD_LESS_THAN, 'less-than', 'requires that the expression occurs strictly less than the given number'),
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
]



class ArgParser(argparse.ArgumentParser):

    def convert_arg_line_to_args(self, l):
        '''
        More flexible argument parsing from configuration file:
          - ignore leading and trailing spaces
          - allow empty lines
        '''
        ll = l.strip()
        return [ ll ] if ll else [ ]


class ModifierParser(ArgParser):

    def parse_modifiers(self, modifiers):
        mods, unknown = self.parse_known_args(['-' + mod for mod in modifiers])
186 187
        for m in unknown:
            sys.stderr.write("! Unknown modifier '%s'\n" % m[1])
188 189 190 191 192 193 194 195
        return mods

parser_mod = ModifierParser()
parser_mod.help = 'modifiers (uppercase letters cancel previous modifiers)\n'

for (mod_char, mod_long, mod_help) in MODIFIERS:
    parser_mod.add_argument('-' + mod_char, '--' + mod_long, action='store_true', help=mod_help)

196 197 198 199 200 201 202 203
    if mod_char.upper() != mod_char:
        parser_mod.add_argument('-' + mod_char.upper(), dest=mod_long.replace('-', '_'), action='store_const', const=False, default=False,
                                help='back to default, overriding any previous -%s' % mod_char)
        help_upper = '/%s' % mod_char.upper()
    else:
        help_upper = '  '

    parser_mod.help += '  %s%s %s\n' % (mod_char, help_upper, mod_help)
204 205 206 207 208 209

# Main argument parser

parser = ArgParser(description='Test command-line applications through .should files',
                   fromfile_prefix_chars='@',
                   epilog='''Example:
210
  %(prog)s demo/hello.should''',
211 212
                                 formatter_class=argparse.RawTextHelpFormatter)

213 214 215
parser.add_argument('--version', action='version',
                    version='%(prog)s {version}'.format(version=__version__))

216 217 218 219 220 221
options = ArgParser(fromfile_prefix_chars='@') # Can be used in !OPTIONS: directive

for p in (parser, options):
    p.add_argument('--cd', metavar='PATH', help='directory from which to run the test commands')
    p.add_argument('--cd-same', action='store_true', help='run the test commands from the same directory as the .should files')
    p.add_argument('--launcher', metavar='CMD', default='', help='launcher preceding each command (or replacing %s)' % VAR_LAUNCHER)
222
    p.add_argument('--extra', metavar='ARG', default='', help='extra argument after the first word of each command (or replacing %s)' % VAR_EXTRA)
223 224 225
    p.add_argument('--mod', metavar='MODIFIERS', action='append', help='global ' + parser_mod.help)
    p.add_argument('--var', metavar='NAME=value', action='append', help='variable definition (then use $NAME in .should files)')

226 227
parser.add_argument('--shuffle', action='store_true', help='shuffle the tests')

228 229 230 231
output = parser.add_argument_group('output options')

output.add_argument('--log', action='append_const', dest='output', const=OUT_LOG, help='stores the output into .log files')
output.add_argument('--tap', action='append_const', dest='output', const=OUT_TAP, help='outputs .tap files')
232
output.add_argument('--xml', action='append_const', dest='output', const=OUT_XML, help='outputs JUnit-like XML into %s' % OUT_XML)
233 234 235 236
output.add_argument('-v', '--verbose', action='count', help='increase verbosity', default=1)
output.add_argument('-q', '--quiet', action='store_const', dest='verbose', const=0, help='verbosity to zero')

parser.add_argument('file', metavar='should-file', nargs='+', help='''input files (.should)''')
237
parser.add_argument(RETRY_FLAG, action='store_true', help='launch again the last failed or warned tests')
238 239 240 241 242 243 244 245 246 247

class ShouldException(BaseException):
    pass


def write_to_file(f, what):
    print('==> %s' % f)
    with open(f, 'w', encoding='utf-8') as ff:
        ff.write(what)

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264


# Command pre-processing

def pre_process(cmd):

    cc = cmd.split(' ')

    if not VAR_EXTRA in cmd:
        cc = [cc[0], VAR_EXTRA] + cc[1:]

    if not VAR_LAUNCHER in cmd:
        cc = [VAR_LAUNCHER] + cc

    return ' '.join(cc)


265 266 267 268 269
# Variables definition and expansion

def populate_variables(var):
    '''
    >>> populate_variables(['ab=cd', 'ef=xyz'])
270
    [('$ef', 'xyz'), ('$ab', 'cd')]
271 272 273 274 275 276 277 278
    '''

    variables = []

    if var:
        for v in var:
            try:
                key, var = v.split('=')
279
                variables = [('$' + key, var)] + variables
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

            except IOError:
                raise ShouldException('Error in parsing variable definition: ' + v)
    return variables


def print_variables(variables):
    for (k, v) in variables:
        print('%s=%s' % (k, v))
    print('')

def replace_variables(s, variables):
    '''
    >>> replace_variables('hello', None)
    'hello'

    >>> replace_variables('hello', [('hell', 'w'), ('o', 'orld')])
    'world'

    >>> replace_variables('xyz xyz', [('y', 'abc')])
    'xabcz xabcz'
    '''

    if variables:
        for (key, val) in variables:
            s = s.replace(key, val)
    return s


309 310 311 312
class OrderedDefaultListDict(OrderedDict):
    def __missing__(self, key):
        self[key] = value = []
        return value
313 314 315 316

class Stats():
    '''
    >>> s = Stats('foo')
317
    >>> s.up(2)
318 319
    >>> list(s.keys())
    [2]
320 321
    >>> s[2]
    [1]
322 323

    >>> t = Stats()
324 325
    >>> t.up(2, 'hello')
    >>> t.up(3)
326 327 328 329 330 331

    >>> u = s + t
    >>> sorted(u.keys())
    [2, 3]
    >>> list(s.keys())
    [2]
332 333 334

    >>> sorted(u.items())
    [(2, [1, 'hello']), (3, [1])]
335 336 337
    '''

    def __init__(self, item=''):
338
        self.stats = OrderedDefaultListDict()
339 340 341 342 343
        self.item = item

    def __getitem__(self, key):
        return self.stats[key]

344 345 346
    def up(self, key, data=1):
        self.stats[key].append(data)

347 348 349 350 351 352
    def __setitem__(self, key, value):
        self.stats[key] = value

    def keys(self):
        return self.stats.keys()

353 354 355 356 357 358 359 360 361
    def items(self):
        return self.stats.items()

    def values(self):
        return self.stats.values()

    def total(self):
        return sum(map(len, self.stats.values()))

362 363 364 365
    def __add__(self, other):
        result = Stats(self.item)
        for data in (self, other):
            for key in data.keys():
366
                result.stats[key] += data.stats[key]
367 368 369 370 371 372
        return result

    def str_status(self, status, colorize=True):
        s = '==> '
        s += STATUS[status]
        s += ' - '
373
        s += ' '.join(['%s:%d' % (STATUS[key], len(val)) for (key, val) in self.items()] + ['total:%s' % self.total()])
374
        if self.item:
375
            s += ' ' + self.item + ('s' if self.total() > 1 else '')
376 377 378 379 380
        return color(STATUS_COLORS[status], s, colorize)




381
class TestCaseAbstract:
382 383 384 385 386 387
    def __init__(self):
        raise NotImplemented

    def str_additional_status(self, verbose=False):
        return ''

388
    def str_status(self, verbose=False, names=STATUS, colorize=True):
389
        s = ''
390
        s += color(STATUS_COLORS[self.status], names[self.status], colorize)
391 392 393 394
        s += self.str_additional_status(verbose)

        return s

395 396 397 398 399 400 401
    def xml(self):
        x = ET.Element('testcase', {'name': self.name, 'status': STATUS_XML[self.status]})
        if self.status in WARN_STATUS:
            x.append(ET.Element(STATUS_XML[self.status],
                                {'message': repr(self) + '\n' + self.str_status(names=STATUS_XML, colorize = False)}))
        return x

402
    def tap(self, names=STATUS_TAP, colorize=False):
403 404 405
        s = []

        if self.status is not None:
406
            s.append(self.str_status(names=names, colorize=colorize))
407 408 409 410 411 412

        if self.name:
            s.append(self.name)

        return ' - '.join(s)

413 414 415
    def str(self, colorize):
        return self.tap(names=STATUS, colorize=colorize)

416
    def __str__(self):
417
        return self.str(colorize=True)
418

419 420
    def __repr__(self):
        raise NotImplemented
421

422
class ExternalTestCase(TestCaseAbstract):
423 424 425 426 427 428 429
    def __init__(self, name, status, info=''):
        self.name = name
        self.status = status
        self.info = info

    def str_additional_status(self, verbose = False):
        s = ''
430
        if self.status in WARN_STATUS or verbose:
431 432 433 434 435 436
            s += ' (%s)' % self.info
        return s

    def test(self, *args, **kwargs):
        pass

437 438 439 440 441
    def __repr__(self):
        return self.info


class TestCase(TestCaseAbstract):
442
    '''
443
    >>> test = TestCase('', 'hello')
444 445 446
    >>> repr(test)
    ':hello'

447
    >>> test.str_status(colorize=False)
448 449 450 451 452 453 454 455 456 457 458 459
    'not run'

    >>> test.test(['world'])
    False

    >>> test.status
    False

    >>> test.test(['hello'])
    True


460
    >>> test = TestCase('3', 'hello')
461 462 463 464 465 466 467
    >>> repr(test)
    '3:hello'

    >>> test.test(['hello'])
    False
    >>> test.count
    1
468
    >>> print(test.str(colorize=False))
469 470 471 472 473 474 475 476
    failed (1/3)
    >>> test.tap()
    'not ok (1/3)'

    >>> test.test(['hello'] * 3)
    True


477
    >>> TestCase('r2', ' e.*o ').test(['hello', 'ello', 'world'])
478 479
    True

480
    >>> TestCase('z1', ' e').test(['hello', 'h ello'])
481 482
    True

483
    >>> TestCase('rl', 'e.*o').test(['hel', 'lo'])
484 485
    True

486
    >>> TestCase('', 'e o').test(['e  o'])
487 488
    False

489
    >>> TestCase('f', 'e o').test(['e  o'])
490 491
    'TODO'

492
    >>> TestCase('b', 'e o').test(['e  o'])
493 494
    True

495
    >>> TestCase('b', 'e    o').test(['e  o'])
496 497
    True

498
    >>> TestCase('w2', 'o').test(['hello world'])
499 500
    True

501
    >>> TestCase('wW2', 'o').test(['hello world'])
502 503
    False

504
    >>> TestCase('wr2', 'a.c').test(['bli abc axc bla'])
505 506 507
    True


508
    >>> repr(TestCase('x3y', 'hello'))
509 510
    'xy3:hello'

511
    >>> print(TestCase('1x2', 'hello')) # doctest: +IGNORE_EXCEPTION_DETAIL
512 513 514 515 516 517 518 519
    Traceback (most recent call last):
     ...
    ShouldException: Error in parsing modifiers: 1x2
    '''

    def __init__(self, modifiers, expression, name=''):
        self.name = name
        self.status = None
520
        self.count = '?'
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

        # Extract self.expected_count from modifiers
        m = RE_MODIFIERS.match(modifiers)
        if not m:
            raise ShouldException('Error in parsing modifiers: ' + modifiers)
        self.modifiers = m.group(1) + m.group(3)
        self.expected_count = int(m.group(2)) if m.group(2) else None

        # Parse modifiers
        self.mods = parser_mod.parse_modifiers(self.modifiers)

        self.expression = expression if self.mods.ltspaces else expression.strip()
        if self.mods.blanks:
            while '  ' in self.expression:
                self.expression = self.expression.replace('  ', ' ')
            self.expression = self.expression.replace(' ', '\s+')
            self.mods.regex = True
538 539 540 541 542 543 544

        self.regex = None
        if self.mods.regex:
            if self.mods.ignore_case:
                self.regex = re.compile(self.expression, re.IGNORECASE)
            else:
                self.regex = re.compile(self.expression)
545 546 547 548 549 550 551

    def test(self, lines, variables=None, verbose=0):
        if self.mods.multi_lines:
            lines = [' '.join([l.rstrip(ENDLINE_CHARS) for l in lines])]

        expression_var = replace_variables(self.expression, variables)

552 553 554
        if not self.regex and self.mods.ignore_case:
            expression_var = expression_var.upper()

555 556 557 558 559 560 561
        self.count = 0
        for l in lines:
            if self.regex:
                if self.mods.count_all:
                    self.count += len(self.regex.findall(l))
                elif self.regex.search(l):
                    self.count += 1
562 563 564 565 566
            else:
                if self.mods.ignore_case:
                    l = l.upper()
                if expression_var in l:
                    self.count += l.count(expression_var) if self.mods.count_all else 1
567

568 569 570 571 572 573 574 575
        if self.expected_count is None:
            self.status = (self.count > 0)
        elif self.mods.less_than:
            self.status = (self.count < self.expected_count)
        elif self.mods.more_than:
            self.status = (self.count > self.expected_count)
        else:
            self.status = (self.count == self.expected_count)
576 577 578 579 580 581 582 583 584 585 586 587 588

        if self.mods.todo:
            self.status = [TODO, TODO_PASSED][self.status]

        if verbose > 0:
            print('')
            print(self.str_status(True) + ' ' + repr(self))

        return self.status

    def str_additional_status(self, verbose=False):
        s = ''

589
        if self.status in WARN_STATUS or verbose:
590 591 592
            s += ' (%s/%s%s)' % (self.count,
                                 MOD_LESS_THAN if self.mods.less_than else MOD_MORE_THAN if self.mods.more_than else '',
                                 self.expected_count if self.expected_count is not None else '+')
593 594 595 596 597 598 599

        return s

    def __repr__(self):
        return '%s%s:%s' % (self.modifiers, self.expected_count if self.expected_count is not None else '', self.expression)


600
class TestSuite():
601
    '''
602
    >>> s = TestSuite()
603 604 605 606 607 608 609 610 611 612
    >>> s.load(['echo "hello"', '$My test', ':hello'])
    >>> print(s)
    echo "hello"
    My test

    >>> s.test()
    True
    >>> s.tests[0].status
    True

613
    >>> s2 = TestSuite('r')
614
    >>> s2.variables.append(("$LAUNCHER", ""))
615
    >>> s2.variables.append(("$EXTRA", ""))
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    >>> s2.load(['echo "hello"', '$ A nice test', ':e.*o'])
    >>> s2.test(verbose = 1, colorize = False)   # doctest: +NORMALIZE_WHITESPACE
    echo "hello"
      stdout --> 1 lines
      stderr --> 0 lines
    ok - A nice test
    ok - Exit code is 0
    True

    >>> s2.str_status(colorize = False)
    '==> ok - ok:2 total:2 tests'

    >>> print(s2.tap())   # doctest: +NORMALIZE_WHITESPACE
    1..2
    ok - A nice test
    ok - Exit code is 0
    '''

634 635
    def __init__(self, modifiers = '', cd = None, name = ''):
        self.name = name
636 637
        self.requires = True
        self.requires_cmd = None
638
        self.requires_stderr = []
639 640
        self.cmds = []
        self.tests = []
641 642
        self.stdin = []
        self.stdout = []
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        self.test_lines = []
        self.status = None
        self.modifiers = modifiers
        self.variables = []
        self.stats = Stats('test')
        self.source = None
        self.cd = cd
        self.use_launcher = True
        self.expected_exit_code = 0
        self.elapsed_time = None

    def load(self, should_lines):
        name = ''
        this_cmd_continues = False
        for l in should_lines:

            l = l.lstrip().rstrip(ENDLINE_CHARS)
            if not l:
                continue

            # Comment
            if l.startswith(TOKEN_COMMENT):
                continue

            # Directive -- Requires
            if l.startswith(DIRECTIVE_REQUIRES):
                self.requires_cmd = l[len(DIRECTIVE_REQUIRES):].strip()
                continue

            # Directive -- No launcher
            if l.startswith(DIRECTIVE_NO_LAUNCHER):
                self.use_launcher = False
                continue

            # Directive -- Source
            if l.startswith(DIRECTIVE_SOURCE):
                self.source = os.path.join(self.cd if self.cd else '', l[len(DIRECTIVE_SOURCE):].strip())
                continue

            # Directive -- Options
            if l.startswith(DIRECTIVE_OPTIONS):
                opts, unknown = options.parse_known_args(l[len(DIRECTIVE_OPTIONS):].split())
685
                self.variables = populate_variables(opts.var) + self.variables
686 687
                if opts.mod:
                    self.modifiers += ''.join(opts.mod)
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
                continue

            # Directive -- Exit code
            if l.startswith(DIRECTIVE_EXIT_CODE):
                self.expected_exit_code = int(l[len(DIRECTIVE_EXIT_CODE):].strip())
                continue

            # Name
            if l.startswith(TOKEN_NAME):
                name = l[1:].strip()
                continue

            # Directive -- Command
            if l.startswith(DIRECTIVE_SCRIPT):
                l = l[len(DIRECTIVE_SCRIPT):]

            # Directive -- Others
            if l.startswith(TOKEN_DIRECTIVE):
                sys.stderr.write('! Unknown directive: %s\n' % l)
                continue

            # Test
            if RE_TEST.search(l):
                pos = l.find(TOKEN_TEST)
                modifiers, expression = l[:pos], l[pos+1:]
713
                self.tests.append(TestCase(self.modifiers + modifiers, expression, name))
714 715 716
                continue

            # Command
717
            l = l.strip()
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
            next_cmd_continues = l.endswith(CONTINUATION_CHAR)
            if next_cmd_continues:
                l = l[:-1]

            if this_cmd_continues:
                self.cmds[-1] += l
            else:
                self.cmds.append(l)

            this_cmd_continues = next_cmd_continues


    def print_stderr(self, colorize=True):
        print('  stdout --> %s lines' % len(self.stdout))
        print('  stderr --> %s lines' % len(self.stderr))
        print(color(ANSI.CYAN, ''.join(self.stderr), colorize))

735 736 737
    def skip_all(self, reason, verbose=1):
        if verbose > 0:
            print('Skipping tests: %s' % reason)
738 739
        for test in self.tests:
            test.status = SKIP
740
            self.stats.up(test.status)
741 742 743 744
        self.status = SKIP

    def test(self, variables=[], verbose=0, colorize=True):

745
        self.variables_all = self.variables + variables
746
        if verbose > 1:
747
            print_variables(self.variables_all)
748

749
        def cmd_variables_cd(cmd):
750
            cmd = replace_variables(cmd, self.variables_all)
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
            if self.cd:
                cmd = 'cd %s ; ' % self.cd + cmd
            if verbose > 0:
                print(color(ANSI.MAGENTA, cmd, colorize))
            return cmd

        self.status = True

        if self.requires_cmd:
            requires_cmd = cmd_variables_cd(self.requires_cmd)
            p = subprocess.Popen(requires_cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
            self.requires = (p.wait() == 0)
            self.requires_stderr = [l.decode(errors='replace') for l in p.stderr.readlines()]
            if verbose > 0:
                print(color(ANSI.CYAN, ''.join(self.requires_stderr), colorize))

            if not self.requires:
                self.skip_all('Condition is not met: %s' % self.requires_cmd, verbose)
                return self.status

771
        if not self.use_launcher:
772
            if replace_variables(VAR_LAUNCHER, self.variables_all):
773
                self.skip_all('%s while %s is given' % (DIRECTIVE_NO_LAUNCHER, VAR_LAUNCHER), verbose)
774 775 776 777
                return self.status

        start_time = time.time()

778
        cmd = ' ; '.join(map(pre_process, self.cmds))
779 780
        cmd = cmd_variables_cd(cmd)

781 782
        f_stdout = tempfile.TemporaryFile()
        f_stderr = tempfile.TemporaryFile()
783
        p = subprocess.Popen([cmd], shell=True,
784
                             stdout=f_stdout, stderr=f_stderr,
785 786 787 788
                             close_fds=True)

        try:
            self.exit_code = p.wait(TIMEOUT)
789
            self.tests.append(ExternalTestCase('Exit code is %d' % self.expected_exit_code, self.exit_code == self.expected_exit_code, str(self.exit_code)))
790
        except subprocess.TimeoutExpired:
791
            self.exit_code = None
792
            self.tests.append(ExternalTestCase('Exit code is %d' % self.expected_exit_code, SKIP, 'timeout after %s seconds' % TIMEOUT))
793

794 795 796 797 798 799
        f_stdout.seek(0)
        f_stderr.seek(0)
        self.stdout = [l.decode(errors='replace') for l in f_stdout.readlines()]
        self.stderr = [l.decode(errors='replace') for l in f_stderr.readlines()]
        f_stdout.close()
        f_stderr.close()
800

801 802 803 804 805 806 807

        if verbose > 0:
            self.print_stderr(colorize)

        self.test_lines = open(self.source).readlines() if self.source else self.stdout

        for test in self.tests:
808
            test.test(self.test_lines, variables=self.variables_all, verbose=verbose-1)
809
            self.stats.up(test.status)
810

811 812
            # When a test fails, the file fails
            if test.status is False:
813 814
                self.status = False

815 816 817 818
            # When the file is not failing, we may report a more sublte status
            if test.status in WARN_STATUS and self.status is True:
                self.status = test.status

819 820
            if verbose > 0 or test.status in WARN_STATUS:
                print(test.str(colorize))
821 822 823 824 825 826 827

        if self.status is False and verbose <= 0:
            print(color(ANSI.MAGENTA, cmd, colorize))
            self.print_stderr(colorize)

        if self.status is False or verbose > 1:
            print(LINE)
828 829 830 831 832 833 834
            if len(self.test_lines) <= MAX_DUMP_LINES:
                print(''.join(self.test_lines), end='')
            else:
                print(''.join(self.test_lines[:MAX_HALF_DUMP_LINES]), end='')
                print(color(ANSI.MAGENTA, '... %d other lines ...' % (len(self.test_lines) - 2*MAX_HALF_DUMP_LINES), colorize))
                print(''.join(self.test_lines[-MAX_HALF_DUMP_LINES:]), end='')

835 836 837 838 839 840 841 842 843
            print(LINE)

        self.elapsed_time = time.time() - start_time

        return self.status

    def str_status(self, colorize=True):
        return self.stats.str_status(self.status, colorize)

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    def xml(self):
        x = ET.Element('testsuite',
                       {'id': self.name,
                        'name': self.name,
                        'cmd': str(self.cmds),
                        'tests': str(self.stats.total()),
                        'failures': str(len(self.stats[False])),
                        'skipped': str(len(self.stats[SKIP])),
                        'time': self.str_elapsed_time(tag=''),
                        'timestamp': datetime.datetime.now().isoformat()
                       })
        for test in self.tests:
            x.append(test.xml())

        v = ET.Element('properties')
        for (key, val) in self.variables_all:
            v.append(ET.Element('property', {'name': key, 'value': val}))
        x.append(v)

        return x

865 866 867
    def tap(self):
        s = ''
        s += '1..%d' % len(self.tests) + '\n'
868
        s += '\n'.join(map(TestCase.tap, self.tests))
869 870 871
        s += '\n'
        return s

872 873
    def str_elapsed_time(self, tag='s'):
        return ('%.2f%s' % (self.elapsed_time, tag)) if self.elapsed_time is not None else ''
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890

    def __str__(self):
        s = ''
        s += '\n'.join(self.cmds)
        s += '\n'
        s += self.str_elapsed_time()
        s += '\n'.join(map(str,self.tests))
        if self.status is not None:
            s += '\n'
            s += self.str_status()
        return s


class FileSet():

    def __init__(self, files, modifiers = ''):
        self.files = files
891
        self.sets = []
892 893 894 895 896
        self.modifiers = modifiers
        self.status = None
        self.stats = Stats('file')
        self.stats_tests = Stats('test')

897 898 899
    def __len__(self):
        return len(self.files)

900 901 902
    def test(self, variables=None, cd=None, cd_same=False, output=None, verbose=0):
        self.status = True

903 904
        try:
          for f in self.files:
905 906 907
            if verbose > 0:
                print(f)
            cd_f = os.path.dirname(f) if cd_same else cd
908 909
            s = TestSuite(self.modifiers, cd_f, name = f)
            self.sets.append(s)
910 911 912
            s.load(open(f))

            s.test(variables, verbose - 1)
913
            self.stats.up(s.status, f)
914 915 916 917 918
            if not s.status:
                self.status = False

            self.stats_tests += s.stats

919 920
            filename_without_ext = os.path.splitext(f)[0]

921
            if output and OUT_LOG in output:
922
                write_to_file(filename_without_ext + OUT_LOG, ''.join(s.test_lines))
923 924

            if output and OUT_TAP in output:
925
                write_to_file(filename_without_ext + OUT_TAP, s.tap())
926 927 928 929 930 931 932 933 934

            if verbose > 0 or s.status is False:
                if not verbose:
                    print(f, end=' ')
                if s.elapsed_time:
                    if s.elapsed_time >= SHOW_ELAPSED_TIME_ABOVE:
                        print(s.str_elapsed_time())
                print(s.str_status())
                print('')
935 936
        except KeyboardInterrupt:
            print('==== interrupted ====\n')
937

938 939 940
        if output and OUT_XML in output:
            self.xml().write(OUT_XML)

941 942 943 944 945
        print('Summary', end=' ')
        print(self.stats.str_status(self.status))
        print('Summary', end=' ')
        print(self.stats_tests.str_status(self.status))

946 947 948 949 950 951
        for sta in self.stats.keys():
            if sta == True:
                continue
            print('files with %s:' % color(STATUS_COLORS[sta], STATUS[sta]))
            for f in self.stats[sta]:
                print('  ' + f)
952 953 954

        return self.status

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    def xml(self):
        x = ET.Element('testsuites',
                       {'id': 'Test at %s' % datetime.datetime.now().isoformat(),
                        'name': 'tested by should',
                        'tests': str(self.stats_tests.total()),
                        'failures': str(len(self.stats_tests[False])),
                       })

        for s in self.sets:
            x.append(s.xml())

        return ET.ElementTree(x)

    def write_retry(self, argv, argv_remove, verbose=1):
        '''
        If there were tests in WARN_STATUS, write the RETRY file
        with, non-file arguments and WARN_STATUS files.
        '''

        # cmd = [sys.executable, sys.argv[0]]

        files = []

        for sta in WARN_STATUS:
            files += self.stats[sta]

        if not files:
            return

        args = []
        for arg in argv:
            if arg not in argv_remove:
                args.append(arg)

        with open(RETRY, 'w') as f:
            f.write('\n'.join(args + files) + '\n')

        if verbose > 0:
            print('%s %s will relaunch these tests.' % (sys.argv[0], RETRY_FLAG))

def read_retry():
    try:
        return [l.rstrip() for l in open(RETRY).readlines()]
    except:
        return []

1001 1002 1003

if __name__ == '__main__':
    argv = (['@' + DEFAULT_CFG] + sys.argv[1:]) if os.path.exists(DEFAULT_CFG) else sys.argv[1:]
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013

    if RETRY_FLAG in argv:
        retry = read_retry()
        argv += retry
        if retry:
            print(color(ANSI.BLUE, "Retrying previous failed or warned tests"))
        else:
            print(color(ANSI.RED, "Nothing to retry"))
            sys.exit(2)

1014 1015 1016
    args = parser.parse_args(argv)
    variables = populate_variables(args.var)
    variables.append((VAR_LAUNCHER, args.launcher))
1017
    variables.append((VAR_EXTRA, args.extra))
1018 1019 1020 1021

    if args.verbose>0:
        print_variables(variables)

1022 1023 1024 1025
    if args.shuffle:
        print("Shuffling test files")
        random.shuffle(args.file)

1026 1027
    fs = FileSet(args.file, modifiers=''.join(args.mod if args.mod else []))
    status = fs.test(variables = variables, cd = args.cd, cd_same = args.cd_same, output = args.output, verbose = args.verbose)
1028

1029 1030
    if len(fs) > 1:
        retry = fs.write_retry(sys.argv[1:], args.file, verbose = args.verbose)
1031

1032 1033 1034
    sys.exit(0 if status else 1)