tdc.py 19.4 KB
Newer Older
L
Lucas Bates 已提交
1
#!/usr/bin/env python3
2
# SPDX-License-Identifier: GPL-2.0
L
Lucas Bates 已提交
3 4 5 6 7 8 9 10 11 12 13

"""
tdc.py - Linux tc (Traffic Control) unit test driver

Copyright (C) 2017 Lucas Bates <lucasb@mojatatu.com>
"""

import re
import os
import sys
import argparse
14
import importlib
L
Lucas Bates 已提交
15 16
import json
import subprocess
17
import time
18
import traceback
L
Lucas Bates 已提交
19 20 21 22 23 24
from collections import OrderedDict
from string import Template

from tdc_config import *
from tdc_helper import *

25
import TdcPlugin
L
Lucas Bates 已提交
26

27 28 29 30 31 32 33

class PluginMgrTestFail(Exception):
    def __init__(self, stage, output, message):
        self.stage = stage
        self.output = output
        self.message = message

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
class PluginMgr:
    def __init__(self, argparser):
        super().__init__()
        self.plugins = {}
        self.plugin_instances = []
        self.args = []
        self.argparser = argparser

        # TODO, put plugins in order
        plugindir = os.getenv('TDC_PLUGIN_DIR', './plugins')
        for dirpath, dirnames, filenames in os.walk(plugindir):
            for fn in filenames:
                if (fn.endswith('.py') and
                    not fn == '__init__.py' and
                    not fn.startswith('#') and
                    not fn.startswith('.#')):
                    mn = fn[0:-3]
                    foo = importlib.import_module('plugins.' + mn)
                    self.plugins[mn] = foo
                    self.plugin_instances.append(foo.SubPlugin())

    def call_pre_suite(self, testcount, testidlist):
        for pgn_inst in self.plugin_instances:
            pgn_inst.pre_suite(testcount, testidlist)

    def call_post_suite(self, index):
        for pgn_inst in reversed(self.plugin_instances):
            pgn_inst.post_suite(index)

    def call_pre_case(self, test_ordinal, testid):
        for pgn_inst in self.plugin_instances:
            try:
                pgn_inst.pre_case(test_ordinal, testid)
            except Exception as ee:
                print('exception {} in call to pre_case for {} plugin'.
                      format(ee, pgn_inst.__class__))
                print('test_ordinal is {}'.format(test_ordinal))
                print('testid is {}'.format(testid))
                raise

    def call_post_case(self):
        for pgn_inst in reversed(self.plugin_instances):
            pgn_inst.post_case()

    def call_pre_execute(self):
        for pgn_inst in self.plugin_instances:
            pgn_inst.pre_execute()

    def call_post_execute(self):
        for pgn_inst in reversed(self.plugin_instances):
            pgn_inst.post_execute()

    def call_add_args(self, parser):
        for pgn_inst in self.plugin_instances:
            parser = pgn_inst.add_args(parser)
        return parser

    def call_check_args(self, args, remaining):
        for pgn_inst in self.plugin_instances:
            pgn_inst.check_args(args, remaining)

    def call_adjust_command(self, stage, command):
        for pgn_inst in self.plugin_instances:
            command = pgn_inst.adjust_command(stage, command)
        return command

    @staticmethod
    def _make_argparser(args):
        self.argparser = argparse.ArgumentParser(
            description='Linux TC unit tests')

L
Lucas Bates 已提交
105 106 107 108 109 110 111 112 113 114 115

def replace_keywords(cmd):
    """
    For a given executable command, substitute any known
    variables contained within NAMES with the correct values
    """
    tcmd = Template(cmd)
    subcmd = tcmd.safe_substitute(NAMES)
    return subcmd


B
Brenda J. Butler 已提交
116
def exec_cmd(args, pm, stage, command):
L
Lucas Bates 已提交
117 118 119 120
    """
    Perform any required modifications on an executable command, then run
    it in a subprocess and return the results.
    """
121 122
    if len(command.strip()) == 0:
        return None, None
L
Lucas Bates 已提交
123 124 125
    if '$' in command:
        command = replace_keywords(command)

126 127 128
    command = pm.call_adjust_command(stage, command)
    if args.verbose > 0:
        print('command "{}"'.format(command))
L
Lucas Bates 已提交
129 130 131
    proc = subprocess.Popen(command,
        shell=True,
        stdout=subprocess.PIPE,
132 133
        stderr=subprocess.PIPE,
        env=ENVIR)
L
Lucas Bates 已提交
134 135
    (rawout, serr) = proc.communicate()

136
    if proc.returncode != 0 and len(serr) > 0:
L
Lucas Bates 已提交
137 138 139 140 141 142 143 144 145
        foutput = serr.decode("utf-8")
    else:
        foutput = rawout.decode("utf-8")

    proc.stdout.close()
    proc.stderr.close()
    return proc, foutput


146
def prepare_env(args, pm, stage, prefix, cmdlist, output = None):
L
Lucas Bates 已提交
147
    """
148 149
    Execute the setup/teardown commands for a test case.
    Optionally terminate test execution if the command fails.
L
Lucas Bates 已提交
150
    """
151 152
    if args.verbose > 0:
        print('{}'.format(prefix))
L
Lucas Bates 已提交
153
    for cmdinfo in cmdlist:
154
        if isinstance(cmdinfo, list):
L
Lucas Bates 已提交
155 156 157 158 159 160
            exit_codes = cmdinfo[1:]
            cmd = cmdinfo[0]
        else:
            exit_codes = [0]
            cmd = cmdinfo

161
        if not cmd:
L
Lucas Bates 已提交
162 163
            continue

164
        (proc, foutput) = exec_cmd(args, pm, stage, cmd)
L
Lucas Bates 已提交
165

166 167 168 169 170 171 172 173 174
        if proc and (proc.returncode not in exit_codes):
            print('', file=sys.stderr)
            print("{} *** Could not execute: \"{}\"".format(prefix, cmd),
                  file=sys.stderr)
            print("\n{} *** Error message: \"{}\"".format(prefix, foutput),
                  file=sys.stderr)
            print("\n{} *** Aborting test run.".format(prefix), file=sys.stderr)
            print("\n\n{} *** stdout ***".format(proc.stdout), file=sys.stderr)
            print("\n\n{} *** stderr ***".format(proc.stderr), file=sys.stderr)
175 176 177
            raise PluginMgrTestFail(
                stage, output,
                '"{}" did not complete successfully'.format(prefix))
178

179
def run_one_test(pm, args, index, tidx):
180 181 182
    result = True
    tresult = ""
    tap = ""
183 184
    if args.verbose > 0:
        print("\t====================\n=====> ", end="")
185
    print("Test " + tidx["id"] + ": " + tidx["name"])
186 187 188 189 190 191 192 193

    pm.call_pre_case(index, tidx['id'])
    prepare_env(args, pm, 'setup', "-----> prepare stage", tidx["setup"])

    if (args.verbose > 0):
        print('-----> execute stage')
    pm.call_pre_execute()
    (p, procout) = exec_cmd(args, pm, 'execute', tidx["cmdUnderTest"])
194
    exit_code = p.returncode
195
    pm.call_post_execute()
196 197 198 199 200 201

    if (exit_code != int(tidx["expExitCode"])):
        result = False
        print("exit:", exit_code, int(tidx["expExitCode"]))
        print(procout)
    else:
202 203 204 205 206
        if args.verbose > 0:
            print('-----> verify stage')
        match_pattern = re.compile(
            str(tidx["matchPattern"]), re.DOTALL | re.MULTILINE)
        (p, procout) = exec_cmd(args, pm, 'verify', tidx["verifyCmd"])
207 208 209 210 211
        if procout:
            match_index = re.findall(match_pattern, procout)
            if len(match_index) != int(tidx["matchCount"]):
                result = False
        elif int(tidx["matchCount"]) != 0:
212 213 214
            result = False

    if not result:
215 216
        tresult += 'not '
    tresult += 'ok {} - {} # {}\n'.format(str(index), tidx['id'], tidx['name'])
217
    tap += tresult
L
Lucas Bates 已提交
218

219
    if result == False:
220 221 222 223
        if procout:
            tap += procout
        else:
            tap += 'No output!\n'
224

225
    prepare_env(args, pm, 'teardown', '-----> teardown stage', tidx['teardown'], procout)
226 227
    pm.call_post_case()

228 229 230
    index += 1

    return tap
L
Lucas Bates 已提交
231

232
def test_runner(pm, args, filtered_tests):
L
Lucas Bates 已提交
233 234 235 236 237 238 239 240 241 242 243 244
    """
    Driver function for the unit tests.

    Prints information about the tests being run, executes the setup and
    teardown commands and the command under test itself. Also determines
    success/failure based on the information in the test case and generates
    TAP output accordingly.
    """
    testlist = filtered_tests
    tcount = len(testlist)
    index = 1
    tap = str(index) + ".." + str(tcount) + "\n"
245
    badtest = None
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    stage = None
    emergency_exit = False
    emergency_exit_message = ''

    try:
        pm.call_pre_suite(tcount, [tidx['id'] for tidx in testlist])
    except Exception as ee:
        ex_type, ex, ex_tb = sys.exc_info()
        print('Exception {} {} (caught in pre_suite).'.
              format(ex_type, ex))
        # when the extra print statements are uncommented,
        # the traceback does not appear between them
        # (it appears way earlier in the tdc.py output)
        # so don't bother ...
        # print('--------------------(')
        # print('traceback')
        traceback.print_tb(ex_tb)
        # print('--------------------)')
        emergency_exit_message = 'EMERGENCY EXIT, call_pre_suite failed with exception {} {}\n'.format(ex_type, ex)
        emergency_exit = True
        stage = 'pre-SUITE'

    if emergency_exit:
        pm.call_post_suite(index)
        return emergency_exit_message
271
    if args.verbose > 1:
272 273
        print('give test rig 2 seconds to stabilize')
    time.sleep(2)
L
Lucas Bates 已提交
274
    for tidx in testlist:
275
        if "flower" in tidx["category"] and args.device == None:
276 277 278
            if args.verbose > 1:
                print('Not executing test {} {} because DEV2 not defined'.
                      format(tidx['id'], tidx['name']))
279
            continue
280 281
        try:
            badtest = tidx  # in case it goes bad
282
            tap += run_one_test(pm, args, index, tidx)
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        except PluginMgrTestFail as pmtf:
            ex_type, ex, ex_tb = sys.exc_info()
            stage = pmtf.stage
            message = pmtf.message
            output = pmtf.output
            print(message)
            print('Exception {} {} (caught in test_runner, running test {} {} {} stage {})'.
                  format(ex_type, ex, index, tidx['id'], tidx['name'], stage))
            print('---------------')
            print('traceback')
            traceback.print_tb(ex_tb)
            print('---------------')
            if stage == 'teardown':
                print('accumulated output for this test:')
                if pmtf.output:
                    print(pmtf.output)
            print('---------------')
300 301
            break
        index += 1
L
Lucas Bates 已提交
302

303
    # if we failed in setup or teardown,
304
    # fill in the remaining tests with ok-skipped
305 306 307 308
    count = index
    tap += 'about to flush the tap output if tests need to be skipped\n'
    if tcount + 1 != index:
        for tidx in testlist[index - 1:]:
309
            msg = 'skipped - previous {} failed'.format(stage)
310
            tap += 'ok {} - {} # {} {} {}\n'.format(
311 312
                count, tidx['id'], msg, index, badtest.get('id', '--Unknown--'))
            count += 1
L
Lucas Bates 已提交
313

314
    tap += 'done flushing skipped test tap output\n'
315
    pm.call_post_suite(index)
L
Lucas Bates 已提交
316 317 318 319 320 321 322 323 324 325 326 327

    return tap

def has_blank_ids(idlist):
    """
    Search the list for empty ID fields and return true/false accordingly.
    """
    return not(all(k for k in idlist))


def load_from_file(filename):
    """
328 329 330 331 332 333 334 335 336 337 338 339 340 341
    Open the JSON file containing the test cases and return them
    as list of ordered dictionary objects.
    """
    try:
        with open(filename) as test_data:
            testlist = json.load(test_data, object_pairs_hook=OrderedDict)
    except json.JSONDecodeError as jde:
        print('IGNORING test case file {}\n\tBECAUSE:  {}'.format(filename, jde))
        testlist = list()
    else:
        idlist = get_id_list(testlist)
        if (has_blank_ids(idlist)):
            for k in testlist:
                k['filename'] = filename
L
Lucas Bates 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    return testlist


def args_parse():
    """
    Create the argument parser.
    """
    parser = argparse.ArgumentParser(description='Linux TC unit tests')
    return parser


def set_args(parser):
    """
    Set the command line arguments for tdc.
    """
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    parser.add_argument(
        '-p', '--path', type=str,
        help='The full path to the tc executable to use')
    sg = parser.add_argument_group(
        'selection', 'select which test cases: ' +
        'files plus directories; filtered by categories plus testids')
    ag = parser.add_argument_group(
        'action', 'select action to perform on selected test cases')

    sg.add_argument(
        '-D', '--directory', nargs='+', metavar='DIR',
        help='Collect tests from the specified directory(ies) ' +
        '(default [tc-tests])')
    sg.add_argument(
        '-f', '--file', nargs='+', metavar='FILE',
        help='Run tests from the specified file(s)')
    sg.add_argument(
        '-c', '--category', nargs='*', metavar='CATG', default=['+c'],
        help='Run tests only from the specified category/ies, ' +
        'or if no category/ies is/are specified, list known categories.')
    sg.add_argument(
        '-e', '--execute', nargs='+', metavar='ID',
        help='Execute the specified test cases with specified IDs')
    ag.add_argument(
        '-l', '--list', action='store_true',
        help='List all test cases, or those only within the specified category')
    ag.add_argument(
        '-s', '--show', action='store_true', dest='showID',
        help='Display the selected test cases')
    ag.add_argument(
        '-i', '--id', action='store_true', dest='gen_id',
        help='Generate ID numbers for new test cases')
    parser.add_argument(
        '-v', '--verbose', action='count', default=0,
        help='Show the commands that are being run')
392 393
    parser.add_argument('-d', '--device',
                        help='Execute the test case in flower category')
L
Lucas Bates 已提交
394 395 396
    return parser


397
def check_default_settings(args, remaining, pm):
L
Lucas Bates 已提交
398
    """
399 400
    Process any arguments overriding the default settings,
    and ensure the settings are correct.
L
Lucas Bates 已提交
401 402 403 404 405
    """
    # Allow for overriding specific settings
    global NAMES

    if args.path != None:
406
        NAMES['TC'] = args.path
407
    if args.device != None:
408
        NAMES['DEV2'] = args.device
L
Lucas Bates 已提交
409 410 411 412
    if not os.path.isfile(NAMES['TC']):
        print("The specified tc path " + NAMES['TC'] + " does not exist.")
        exit(1)

413 414
    pm.call_check_args(args, remaining)

L
Lucas Bates 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

def get_id_list(alltests):
    """
    Generate a list of all IDs in the test cases.
    """
    return [x["id"] for x in alltests]


def check_case_id(alltests):
    """
    Check for duplicate test case IDs.
    """
    idl = get_id_list(alltests)
    return [x for x in idl if idl.count(x) > 1]


def does_id_exist(alltests, newid):
    """
    Check if a given ID already exists in the list of test cases.
    """
    idl = get_id_list(alltests)
    return (any(newid == x for x in idl))


def generate_case_ids(alltests):
    """
    If a test case has a blank ID field, generate a random hex ID for it
    and then write the test cases back to disk.
    """
    import random
    for c in alltests:
        if (c["id"] == ""):
            while True:
                newid = str('%04x' % random.randrange(16**4))
                if (does_id_exist(alltests, newid)):
                    continue
                else:
                    c['id'] = newid
                    break

    ufilename = []
    for c in alltests:
        if ('filename' in c):
            ufilename.append(c['filename'])
    ufilename = get_unique_item(ufilename)
    for f in ufilename:
        testlist = []
        for t in alltests:
            if 'filename' in t:
                if t['filename'] == f:
                    del t['filename']
                    testlist.append(t)
        outfile = open(f, "w")
        json.dump(testlist, outfile, indent=4)
        outfile.close()

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
def filter_tests_by_id(args, testlist):
    '''
    Remove tests from testlist that are not in the named id list.
    If id list is empty, return empty list.
    '''
    newlist = list()
    if testlist and args.execute:
        target_ids = args.execute

        if isinstance(target_ids, list) and (len(target_ids) > 0):
            newlist = list(filter(lambda x: x['id'] in target_ids, testlist))
    return newlist

def filter_tests_by_category(args, testlist):
    '''
    Remove tests from testlist that are not in a named category.
    '''
    answer = list()
    if args.category and testlist:
        test_ids = list()
        for catg in set(args.category):
            if catg == '+c':
                continue
            print('considering category {}'.format(catg))
            for tc in testlist:
                if catg in tc['category'] and tc['id'] not in test_ids:
                    answer.append(tc)
                    test_ids.append(tc['id'])

    return answer
L
Lucas Bates 已提交
501 502 503 504 505 506

def get_test_cases(args):
    """
    If a test case file is specified, retrieve tests from that file.
    Otherwise, glob for all json files in subdirectories and load from
    each one.
507 508
    Also, if requested, filter by category, and add tests matching
    certain ids.
L
Lucas Bates 已提交
509 510
    """
    import fnmatch
511 512 513 514 515 516 517 518 519 520

    flist = []
    testdirs = ['tc-tests']

    if args.file:
        # at least one file was specified - remove the default directory
        testdirs = []

        for ff in args.file:
            if not os.path.isfile(ff):
521
                print("IGNORING file " + ff + "\n\tBECAUSE does not exist.")
522 523 524 525 526 527 528 529
            else:
                flist.append(os.path.abspath(ff))

    if args.directory:
        testdirs = args.directory

    for testdir in testdirs:
        for root, dirnames, filenames in os.walk(testdir):
L
Lucas Bates 已提交
530
            for filename in fnmatch.filter(filenames, '*.json'):
531 532 533 534 535
                candidate = os.path.abspath(os.path.join(root, filename))
                if candidate not in testdirs:
                    flist.append(candidate)

    alltestcases = list()
L
Lucas Bates 已提交
536
    for casefile in flist:
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
        alltestcases = alltestcases + (load_from_file(casefile))

    allcatlist = get_test_categories(alltestcases)
    allidlist = get_id_list(alltestcases)

    testcases_by_cats = get_categorized_testlist(alltestcases, allcatlist)
    idtestcases = filter_tests_by_id(args, alltestcases)
    cattestcases = filter_tests_by_category(args, alltestcases)

    cat_ids = [x['id'] for x in cattestcases]
    if args.execute:
        if args.category:
            alltestcases = cattestcases + [x for x in idtestcases if x['id'] not in cat_ids]
        else:
            alltestcases = idtestcases
    else:
        if cat_ids:
            alltestcases = cattestcases
        else:
            # just accept the existing value of alltestcases,
            # which has been filtered by file/directory
            pass

    return allcatlist, allidlist, testcases_by_cats, alltestcases
L
Lucas Bates 已提交
561 562


563
def set_operation_mode(pm, args):
L
Lucas Bates 已提交
564 565 566 567 568
    """
    Load the test case data and process remaining arguments to determine
    what the script should do for this run, and call the appropriate
    function.
    """
569
    ucat, idlist, testcases, alltests = get_test_cases(args)
L
Lucas Bates 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

    if args.gen_id:
        if (has_blank_ids(idlist)):
            alltests = generate_case_ids(alltests)
        else:
            print("No empty ID fields found in test files.")
        exit(0)

    duplicate_ids = check_case_id(alltests)
    if (len(duplicate_ids) > 0):
        print("The following test case IDs are not unique:")
        print(str(set(duplicate_ids)))
        print("Please correct them before continuing.")
        exit(1)

    if args.showID:
586 587
        for atest in alltests:
            print_test_case(atest)
L
Lucas Bates 已提交
588 589
        exit(0)

590 591 592 593
    if isinstance(args.category, list) and (len(args.category) == 0):
        print("Available categories:")
        print_sll(ucat)
        exit(0)
L
Lucas Bates 已提交
594 595

    if args.list:
596
        if args.list:
L
Lucas Bates 已提交
597 598 599
            list_test_cases(alltests)
            exit(0)

600 601 602 603
    if len(alltests):
        catresults = test_runner(pm, args, alltests)
    else:
        catresults = 'No tests found\n'
604
    print('All test results: \n\n{}'.format(catresults))
L
Lucas Bates 已提交
605 606 607 608 609 610 611 612

def main():
    """
    Start of execution; set up argument parser and get the arguments,
    and start operations.
    """
    parser = args_parse()
    parser = set_args(parser)
613 614
    pm = PluginMgr(parser)
    parser = pm.call_add_args(parser)
L
Lucas Bates 已提交
615
    (args, remaining) = parser.parse_known_args()
616 617 618 619
    args.NAMES = NAMES
    check_default_settings(args, remaining, pm)
    if args.verbose > 2:
        print('args is {}'.format(args))
L
Lucas Bates 已提交
620

621
    set_operation_mode(pm, args)
L
Lucas Bates 已提交
622 623 624 625 626 627

    exit(0)


if __name__ == "__main__":
    main()