should.py 30 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 42 43 44 45 46

# 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'
47 48
RETRY = 'should.retry'
RETRY_FLAG = '--retry'
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

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'
64
VAR_EXTRA = '$EXTRA'
65 66 67 68

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

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

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

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

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

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

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',
}

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

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

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

121 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

# 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'),
158
    (MOD_IGNORE_CASE, 'ignore-case', 'ignore case changes'),
159 160 161
    (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'),
162 163 164

    (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'),
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
]



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])
185 186
        for m in unknown:
            sys.stderr.write("! Unknown modifier '%s'\n" % m[1])
187 188 189 190 191 192 193 194
        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)

195 196 197 198 199 200 201 202
    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)
203 204 205 206 207 208

# Main argument parser

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

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

215 216 217 218 219 220
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)
221
    p.add_argument('--extra', metavar='ARG', default='', help='extra argument after the first word of each command (or replacing %s)' % VAR_EXTRA)
222 223 224
    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)')

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

227 228 229 230
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')
231
output.add_argument('--xml', action='append_const', dest='output', const=OUT_XML, help='outputs JUnit-like XML into %s' % OUT_XML)
232 233 234 235
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)''')
236
parser.add_argument(RETRY_FLAG, action='store_true', help='launch again the last failed or warned tests')
237 238 239 240 241 242 243 244 245 246

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)

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


# 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)


264 265 266 267 268 269 270 271 272 273 274 275 276 277
# Variables definition and expansion

def populate_variables(var):
    '''
    >>> populate_variables(['ab=cd', 'ef=xyz'])
    [('$ab', 'cd'), ('$ef', 'xyz')]
    '''

    variables = []

    if var:
        for v in var:
            try:
                key, var = v.split('=')
278
                variables = [('$' + key, var)] + variables
279 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

            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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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




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

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

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

        return s

394 395 396 397 398 399 400
    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

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

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

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

        return ' - '.join(s)

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

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

418 419
    def __repr__(self):
        raise NotImplemented
420

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

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

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

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


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

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

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

    >>> test.status
    False

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


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

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

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


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

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

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

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

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

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

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

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

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

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


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

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

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

        # 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
537 538 539 540 541 542 543

        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)
544 545 546 547 548 549 550

    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)

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

554 555 556 557 558 559 560
        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
561 562 563 564 565
            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
566

567 568 569 570 571 572 573 574
        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)
575 576 577 578 579 580 581 582 583 584 585 586 587

        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 = ''

588
        if self.status in WARN_STATUS or verbose:
589 590 591
            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 '+')
592 593 594 595 596 597 598

        return s

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


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

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

612
    >>> s2 = TestSuite('r')
613
    >>> s2.variables.append(("$LAUNCHER", ""))
614
    >>> s2.variables.append(("$EXTRA", ""))
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    >>> 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
    '''

633 634
    def __init__(self, modifiers = '', cd = None, name = ''):
        self.name = name
635 636
        self.requires = True
        self.requires_cmd = None
637
        self.requires_stderr = []
638 639
        self.cmds = []
        self.tests = []
640 641
        self.stdin = []
        self.stdout = []
642 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
        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())
684
                self.variables = populate_variables(opts.var) + self.variables
685 686
                if opts.mod:
                    self.modifiers += ''.join(opts.mod)
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                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:]
712
                self.tests.append(TestCase(self.modifiers + modifiers, expression, name))
713 714 715
                continue

            # Command
716
            l = l.strip()
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
            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))

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

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

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

748
        def cmd_variables_cd(cmd):
749
            cmd = replace_variables(cmd, self.variables_all)
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
            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

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

        start_time = time.time()

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

780 781 782 783 784 785
        p = subprocess.Popen([cmd], shell=True,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             close_fds=True)

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

        self.stdout = [l.decode(errors='replace') for l in p.stdout.readlines()]
        self.stderr = [l.decode(errors='replace') for l in p.stderr.readlines()]

794

795 796 797 798 799 800 801

        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:
802
            test.test(self.test_lines, variables=self.variables_all, verbose=verbose-1)
803
            self.stats.up(test.status)
804

805 806
            # When a test fails, the file fails
            if test.status is False:
807 808
                self.status = False

809 810 811 812
            # 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

813 814
            if verbose > 0 or test.status in WARN_STATUS:
                print(test.str(colorize))
815 816 817 818 819 820 821

        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)
822 823 824 825 826 827 828
            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='')

829 830 831 832 833 834 835 836 837
            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)

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    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

859 860 861
    def tap(self):
        s = ''
        s += '1..%d' % len(self.tests) + '\n'
862
        s += '\n'.join(map(TestCase.tap, self.tests))
863 864 865
        s += '\n'
        return s

866 867
    def str_elapsed_time(self, tag='s'):
        return ('%.2f%s' % (self.elapsed_time, tag)) if self.elapsed_time is not None else ''
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884

    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
885
        self.sets = []
886 887 888 889 890
        self.modifiers = modifiers
        self.status = None
        self.stats = Stats('file')
        self.stats_tests = Stats('test')

891 892 893
    def __len__(self):
        return len(self.files)

894 895 896
    def test(self, variables=None, cd=None, cd_same=False, output=None, verbose=0):
        self.status = True

897 898
        try:
          for f in self.files:
899 900 901
            if verbose > 0:
                print(f)
            cd_f = os.path.dirname(f) if cd_same else cd
902 903
            s = TestSuite(self.modifiers, cd_f, name = f)
            self.sets.append(s)
904 905 906
            s.load(open(f))

            s.test(variables, verbose - 1)
907
            self.stats.up(s.status, f)
908 909 910 911 912
            if not s.status:
                self.status = False

            self.stats_tests += s.stats

913 914
            filename_without_ext = os.path.splitext(f)[0]

915
            if output and OUT_LOG in output:
916
                write_to_file(filename_without_ext + OUT_LOG, ''.join(s.test_lines))
917 918

            if output and OUT_TAP in output:
919
                write_to_file(filename_without_ext + OUT_TAP, s.tap())
920 921 922 923 924 925 926 927 928

            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('')
929 930
        except KeyboardInterrupt:
            print('==== interrupted ====\n')
931

932 933 934
        if output and OUT_XML in output:
            self.xml().write(OUT_XML)

935 936 937 938 939
        print('Summary', end=' ')
        print(self.stats.str_status(self.status))
        print('Summary', end=' ')
        print(self.stats_tests.str_status(self.status))

940 941 942 943 944 945
        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)
946 947 948

        return self.status

949 950 951 952 953 954 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
    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 []

995 996 997

if __name__ == '__main__':
    argv = (['@' + DEFAULT_CFG] + sys.argv[1:]) if os.path.exists(DEFAULT_CFG) else sys.argv[1:]
998 999 1000 1001 1002 1003 1004 1005 1006 1007

    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)

1008 1009 1010
    args = parser.parse_args(argv)
    variables = populate_variables(args.var)
    variables.append((VAR_LAUNCHER, args.launcher))
1011
    variables.append((VAR_EXTRA, args.extra))
1012 1013 1014 1015

    if args.verbose>0:
        print_variables(variables)

1016 1017 1018 1019
    if args.shuffle:
        print("Shuffling test files")
        random.shuffle(args.file)

1020 1021
    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)
1022

1023 1024
    if len(fs) > 1:
        retry = fs.write_retry(sys.argv[1:], args.file, verbose = args.verbose)
1025

1026 1027 1028
    sys.exit(0 if status else 1)