tdc.py (6fac733d9d07c4fcc349a44add75c6435cc3f18c) | tdc.py (93707cbabcc8baf2b2b5f4a99c1f08ee83eb7abd) |
---|---|
1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0 3 4""" 5tdc.py - Linux tc (Traffic Control) unit test driver 6 7Copyright (C) 2017 Lucas Bates <lucasb@mojatatu.com> 8""" 9 10import re 11import os 12import sys 13import argparse | 1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0 3 4""" 5tdc.py - Linux tc (Traffic Control) unit test driver 6 7Copyright (C) 2017 Lucas Bates <lucasb@mojatatu.com> 8""" 9 10import re 11import os 12import sys 13import argparse |
14import importlib |
|
14import json 15import subprocess | 15import json 16import subprocess |
17import time |
|
16from collections import OrderedDict 17from string import Template 18 19from tdc_config import * 20from tdc_helper import * 21 | 18from collections import OrderedDict 19from string import Template 20 21from tdc_config import * 22from tdc_helper import * 23 |
24import TdcPlugin |
|
22 23USE_NS = True 24 | 25 26USE_NS = True 27 |
28class PluginMgr: 29 def __init__(self, argparser): 30 super().__init__() 31 self.plugins = {} 32 self.plugin_instances = [] 33 self.args = [] 34 self.argparser = argparser |
|
25 | 35 |
36 # TODO, put plugins in order 37 plugindir = os.getenv('TDC_PLUGIN_DIR', './plugins') 38 for dirpath, dirnames, filenames in os.walk(plugindir): 39 for fn in filenames: 40 if (fn.endswith('.py') and 41 not fn == '__init__.py' and 42 not fn.startswith('#') and 43 not fn.startswith('.#')): 44 mn = fn[0:-3] 45 foo = importlib.import_module('plugins.' + mn) 46 self.plugins[mn] = foo 47 self.plugin_instances.append(foo.SubPlugin()) 48 49 def call_pre_suite(self, testcount, testidlist): 50 for pgn_inst in self.plugin_instances: 51 pgn_inst.pre_suite(testcount, testidlist) 52 53 def call_post_suite(self, index): 54 for pgn_inst in reversed(self.plugin_instances): 55 pgn_inst.post_suite(index) 56 57 def call_pre_case(self, test_ordinal, testid): 58 for pgn_inst in self.plugin_instances: 59 try: 60 pgn_inst.pre_case(test_ordinal, testid) 61 except Exception as ee: 62 print('exception {} in call to pre_case for {} plugin'. 63 format(ee, pgn_inst.__class__)) 64 print('test_ordinal is {}'.format(test_ordinal)) 65 print('testid is {}'.format(testid)) 66 raise 67 68 def call_post_case(self): 69 for pgn_inst in reversed(self.plugin_instances): 70 pgn_inst.post_case() 71 72 def call_pre_execute(self): 73 for pgn_inst in self.plugin_instances: 74 pgn_inst.pre_execute() 75 76 def call_post_execute(self): 77 for pgn_inst in reversed(self.plugin_instances): 78 pgn_inst.post_execute() 79 80 def call_add_args(self, parser): 81 for pgn_inst in self.plugin_instances: 82 parser = pgn_inst.add_args(parser) 83 return parser 84 85 def call_check_args(self, args, remaining): 86 for pgn_inst in self.plugin_instances: 87 pgn_inst.check_args(args, remaining) 88 89 def call_adjust_command(self, stage, command): 90 for pgn_inst in self.plugin_instances: 91 command = pgn_inst.adjust_command(stage, command) 92 return command 93 94 @staticmethod 95 def _make_argparser(args): 96 self.argparser = argparse.ArgumentParser( 97 description='Linux TC unit tests') 98 99 |
|
26def replace_keywords(cmd): 27 """ 28 For a given executable command, substitute any known 29 variables contained within NAMES with the correct values 30 """ 31 tcmd = Template(cmd) 32 subcmd = tcmd.safe_substitute(NAMES) 33 return subcmd 34 35 | 100def replace_keywords(cmd): 101 """ 102 For a given executable command, substitute any known 103 variables contained within NAMES with the correct values 104 """ 105 tcmd = Template(cmd) 106 subcmd = tcmd.safe_substitute(NAMES) 107 return subcmd 108 109 |
36def exec_cmd(command, nsonly=True): | 110def exec_cmd(args, pm, stage, command, nsonly=True): |
37 """ 38 Perform any required modifications on an executable command, then run 39 it in a subprocess and return the results. 40 """ | 111 """ 112 Perform any required modifications on an executable command, then run 113 it in a subprocess and return the results. 114 """ |
115 if len(command.strip()) == 0: 116 return None, None |
|
41 if (USE_NS and nsonly): 42 command = 'ip netns exec $NS ' + command 43 44 if '$' in command: 45 command = replace_keywords(command) 46 | 117 if (USE_NS and nsonly): 118 command = 'ip netns exec $NS ' + command 119 120 if '$' in command: 121 command = replace_keywords(command) 122 |
123 command = pm.call_adjust_command(stage, command) 124 if args.verbose > 0: 125 print('command "{}"'.format(command)) |
|
47 proc = subprocess.Popen(command, 48 shell=True, 49 stdout=subprocess.PIPE, | 126 proc = subprocess.Popen(command, 127 shell=True, 128 stdout=subprocess.PIPE, |
50 stderr=subprocess.PIPE) | 129 stderr=subprocess.PIPE, 130 env=ENVIR) |
51 (rawout, serr) = proc.communicate() 52 53 if proc.returncode != 0 and len(serr) > 0: 54 foutput = serr.decode("utf-8") 55 else: 56 foutput = rawout.decode("utf-8") 57 58 proc.stdout.close() 59 proc.stderr.close() 60 return proc, foutput 61 62 | 131 (rawout, serr) = proc.communicate() 132 133 if proc.returncode != 0 and len(serr) > 0: 134 foutput = serr.decode("utf-8") 135 else: 136 foutput = rawout.decode("utf-8") 137 138 proc.stdout.close() 139 proc.stderr.close() 140 return proc, foutput 141 142 |
63def prepare_env(cmdlist): | 143def prepare_env(args, pm, stage, prefix, cmdlist): |
64 """ | 144 """ |
65 Execute the setup/teardown commands for a test case. Optionally 66 terminate test execution if the command fails. | 145 Execute the setup/teardown commands for a test case. 146 Optionally terminate test execution if the command fails. |
67 """ | 147 """ |
148 if args.verbose > 0: 149 print('{}'.format(prefix)) |
|
68 for cmdinfo in cmdlist: | 150 for cmdinfo in cmdlist: |
69 if (type(cmdinfo) == list): | 151 if isinstance(cmdinfo, list): |
70 exit_codes = cmdinfo[1:] 71 cmd = cmdinfo[0] 72 else: 73 exit_codes = [0] 74 cmd = cmdinfo 75 | 152 exit_codes = cmdinfo[1:] 153 cmd = cmdinfo[0] 154 else: 155 exit_codes = [0] 156 cmd = cmdinfo 157 |
76 if (len(cmd) == 0): | 158 if not cmd: |
77 continue 78 | 159 continue 160 |
79 (proc, foutput) = exec_cmd(cmd) | 161 (proc, foutput) = exec_cmd(args, pm, stage, cmd) |
80 | 162 |
81 if proc.returncode not in exit_codes: 82 print 83 print("Could not execute:") 84 print(cmd) 85 print("\nError message:") 86 print(foutput) 87 print("\nAborting test run.") 88 # ns_destroy() 89 raise Exception('prepare_env did not complete successfully') | 163 if proc and (proc.returncode not in exit_codes): 164 print('', file=sys.stderr) 165 print("{} *** Could not execute: \"{}\"".format(prefix, cmd), 166 file=sys.stderr) 167 print("\n{} *** Error message: \"{}\"".format(prefix, foutput), 168 file=sys.stderr) 169 print("\n{} *** Aborting test run.".format(prefix), file=sys.stderr) 170 print("\n\n{} *** stdout ***".format(proc.stdout), file=sys.stderr) 171 print("\n\n{} *** stderr ***".format(proc.stderr), file=sys.stderr) 172 raise Exception('"{}" did not complete successfully'.format(prefix)) |
90 | 173 |
91def run_one_test(index, tidx): | 174def run_one_test(pm, args, index, tidx): |
92 result = True 93 tresult = "" 94 tap = "" | 175 result = True 176 tresult = "" 177 tap = "" |
178 if args.verbose > 0: 179 print("\t====================\n=====> ", end="") |
|
95 print("Test " + tidx["id"] + ": " + tidx["name"]) | 180 print("Test " + tidx["id"] + ": " + tidx["name"]) |
96 prepare_env(tidx["setup"]) 97 (p, procout) = exec_cmd(tidx["cmdUnderTest"]) | 181 182 pm.call_pre_case(index, tidx['id']) 183 prepare_env(args, pm, 'setup', "-----> prepare stage", tidx["setup"]) 184 185 if (args.verbose > 0): 186 print('-----> execute stage') 187 pm.call_pre_execute() 188 (p, procout) = exec_cmd(args, pm, 'execute', tidx["cmdUnderTest"]) |
98 exit_code = p.returncode | 189 exit_code = p.returncode |
190 pm.call_post_execute() |
|
99 100 if (exit_code != int(tidx["expExitCode"])): 101 result = False 102 print("exit:", exit_code, int(tidx["expExitCode"])) 103 print(procout) 104 else: | 191 192 if (exit_code != int(tidx["expExitCode"])): 193 result = False 194 print("exit:", exit_code, int(tidx["expExitCode"])) 195 print(procout) 196 else: |
105 match_pattern = re.compile(str(tidx["matchPattern"]), 106 re.DOTALL | re.MULTILINE) 107 (p, procout) = exec_cmd(tidx["verifyCmd"]) | 197 if args.verbose > 0: 198 print('-----> verify stage') 199 match_pattern = re.compile( 200 str(tidx["matchPattern"]), re.DOTALL | re.MULTILINE) 201 (p, procout) = exec_cmd(args, pm, 'verify', tidx["verifyCmd"]) |
108 match_index = re.findall(match_pattern, procout) 109 if len(match_index) != int(tidx["matchCount"]): 110 result = False 111 112 if not result: | 202 match_index = re.findall(match_pattern, procout) 203 if len(match_index) != int(tidx["matchCount"]): 204 result = False 205 206 if not result: |
113 tresult += "not " 114 tresult += "ok {} - {} # {}\n".format(str(index), tidx['id'], tidx["name"]) | 207 tresult += 'not ' 208 tresult += 'ok {} - {} # {}\n'.format(str(index), tidx['id'], tidx['name']) |
115 tap += tresult 116 117 if result == False: 118 tap += procout 119 | 209 tap += tresult 210 211 if result == False: 212 tap += procout 213 |
120 prepare_env(tidx["teardown"]) | 214 prepare_env(args, pm, 'teardown', '-----> teardown stage', tidx['teardown']) 215 pm.call_post_case() 216 |
121 index += 1 122 123 return tap 124 | 217 index += 1 218 219 return tap 220 |
125def test_runner(filtered_tests, args): | 221def test_runner(pm, args, filtered_tests): |
126 """ 127 Driver function for the unit tests. 128 129 Prints information about the tests being run, executes the setup and 130 teardown commands and the command under test itself. Also determines 131 success/failure based on the information in the test case and generates 132 TAP output accordingly. 133 """ 134 testlist = filtered_tests 135 tcount = len(testlist) 136 index = 1 137 tap = str(index) + ".." + str(tcount) + "\n" | 222 """ 223 Driver function for the unit tests. 224 225 Prints information about the tests being run, executes the setup and 226 teardown commands and the command under test itself. Also determines 227 success/failure based on the information in the test case and generates 228 TAP output accordingly. 229 """ 230 testlist = filtered_tests 231 tcount = len(testlist) 232 index = 1 233 tap = str(index) + ".." + str(tcount) + "\n" |
234 badtest = None |
|
138 | 235 |
236 pm.call_pre_suite(tcount, [tidx['id'] for tidx in testlist]) 237 238 if args.verbose > 1: 239 print('Run tests here') |
|
139 for tidx in testlist: 140 if "flower" in tidx["category"] and args.device == None: 141 continue 142 try: 143 badtest = tidx # in case it goes bad | 240 for tidx in testlist: 241 if "flower" in tidx["category"] and args.device == None: 242 continue 243 try: 244 badtest = tidx # in case it goes bad |
144 tap += run_one_test(index, tidx) | 245 tap += run_one_test(pm, args, index, tidx) |
145 except Exception as ee: 146 print('Exception {} (caught in test_runner, running test {} {} {})'. 147 format(ee, index, tidx['id'], tidx['name'])) 148 break 149 index += 1 150 | 246 except Exception as ee: 247 print('Exception {} (caught in test_runner, running test {} {} {})'. 248 format(ee, index, tidx['id'], tidx['name'])) 249 break 250 index += 1 251 |
252 # if we failed in setup or teardown, 253 # fill in the remaining tests with not ok |
|
151 count = index 152 tap += 'about to flush the tap output if tests need to be skipped\n' 153 if tcount + 1 != index: 154 for tidx in testlist[index - 1:]: 155 msg = 'skipped - previous setup or teardown failed' | 254 count = index 255 tap += 'about to flush the tap output if tests need to be skipped\n' 256 if tcount + 1 != index: 257 for tidx in testlist[index - 1:]: 258 msg = 'skipped - previous setup or teardown failed' |
156 tap += 'ok {} - {} # {} {} {} \n'.format( | 259 tap += 'ok {} - {} # {} {} {}\n'.format( |
157 count, tidx['id'], msg, index, badtest.get('id', '--Unknown--')) 158 count += 1 159 160 tap += 'done flushing skipped test tap output\n' | 260 count, tidx['id'], msg, index, badtest.get('id', '--Unknown--')) 261 count += 1 262 263 tap += 'done flushing skipped test tap output\n' |
264 pm.call_post_suite(index) |
|
161 162 return tap 163 164 | 265 266 return tap 267 268 |
165def ns_create(): | 269def ns_create(args, pm): |
166 """ 167 Create the network namespace in which the tests will be run and set up 168 the required network devices for it. 169 """ 170 if (USE_NS): 171 cmd = 'ip netns add $NS' | 270 """ 271 Create the network namespace in which the tests will be run and set up 272 the required network devices for it. 273 """ 274 if (USE_NS): 275 cmd = 'ip netns add $NS' |
172 exec_cmd(cmd, False) | 276 exec_cmd(args, pm, 'pre', cmd, False) |
173 cmd = 'ip link add $DEV0 type veth peer name $DEV1' | 277 cmd = 'ip link add $DEV0 type veth peer name $DEV1' |
174 exec_cmd(cmd, False) | 278 exec_cmd(args, pm, 'pre', cmd, False) |
175 cmd = 'ip link set $DEV1 netns $NS' | 279 cmd = 'ip link set $DEV1 netns $NS' |
176 exec_cmd(cmd, False) | 280 exec_cmd(args, pm, 'pre', cmd, False) |
177 cmd = 'ip link set $DEV0 up' | 281 cmd = 'ip link set $DEV0 up' |
178 exec_cmd(cmd, False) | 282 exec_cmd(args, pm, 'pre', cmd, False) |
179 cmd = 'ip -n $NS link set $DEV1 up' | 283 cmd = 'ip -n $NS link set $DEV1 up' |
180 exec_cmd(cmd, False) | 284 exec_cmd(args, pm, 'pre', cmd, False) |
181 cmd = 'ip link set $DEV2 netns $NS' | 285 cmd = 'ip link set $DEV2 netns $NS' |
182 exec_cmd(cmd, False) | 286 exec_cmd(args, pm, 'pre', cmd, False) |
183 cmd = 'ip -n $NS link set $DEV2 up' | 287 cmd = 'ip -n $NS link set $DEV2 up' |
184 exec_cmd(cmd, False) | 288 exec_cmd(args, pm, 'pre', cmd, False) |
185 186 | 289 290 |
187def ns_destroy(): | 291def ns_destroy(args, pm): |
188 """ 189 Destroy the network namespace for testing (and any associated network 190 devices as well) 191 """ 192 if (USE_NS): 193 cmd = 'ip netns delete $NS' | 292 """ 293 Destroy the network namespace for testing (and any associated network 294 devices as well) 295 """ 296 if (USE_NS): 297 cmd = 'ip netns delete $NS' |
194 exec_cmd(cmd, False) | 298 exec_cmd(args, pm, 'post', cmd, False) |
195 196 197def has_blank_ids(idlist): 198 """ 199 Search the list for empty ID fields and return true/false accordingly. 200 """ 201 return not(all(k for k in idlist)) 202 --- 64 unchanged lines hidden (view full) --- 267 parser.add_argument( 268 '-v', '--verbose', action='count', default=0, 269 help='Show the commands that are being run') 270 parser.add_argument('-d', '--device', 271 help='Execute the test case in flower category') 272 return parser 273 274 | 299 300 301def has_blank_ids(idlist): 302 """ 303 Search the list for empty ID fields and return true/false accordingly. 304 """ 305 return not(all(k for k in idlist)) 306 --- 64 unchanged lines hidden (view full) --- 371 parser.add_argument( 372 '-v', '--verbose', action='count', default=0, 373 help='Show the commands that are being run') 374 parser.add_argument('-d', '--device', 375 help='Execute the test case in flower category') 376 return parser 377 378 |
275def check_default_settings(args): | 379def check_default_settings(args, remaining, pm): |
276 """ | 380 """ |
277 Process any arguments overriding the default settings, and ensure the 278 settings are correct. | 381 Process any arguments overriding the default settings, 382 and ensure the settings are correct. |
279 """ 280 # Allow for overriding specific settings 281 global NAMES 282 283 if args.path != None: 284 NAMES['TC'] = args.path 285 if args.device != None: 286 NAMES['DEV2'] = args.device 287 if not os.path.isfile(NAMES['TC']): 288 print("The specified tc path " + NAMES['TC'] + " does not exist.") 289 exit(1) 290 | 383 """ 384 # Allow for overriding specific settings 385 global NAMES 386 387 if args.path != None: 388 NAMES['TC'] = args.path 389 if args.device != None: 390 NAMES['DEV2'] = args.device 391 if not os.path.isfile(NAMES['TC']): 392 print("The specified tc path " + NAMES['TC'] + " does not exist.") 393 exit(1) 394 |
395 pm.call_check_args(args, remaining) |
|
291 | 396 |
397 |
|
292def get_id_list(alltests): 293 """ 294 Generate a list of all IDs in the test cases. 295 """ 296 return [x["id"] for x in alltests] 297 298 299def check_case_id(alltests): 300 """ 301 Check for duplicate test case IDs. 302 """ 303 idl = get_id_list(alltests) | 398def get_id_list(alltests): 399 """ 400 Generate a list of all IDs in the test cases. 401 """ 402 return [x["id"] for x in alltests] 403 404 405def check_case_id(alltests): 406 """ 407 Check for duplicate test case IDs. 408 """ 409 idl = get_id_list(alltests) |
304 # print('check_case_id: idl is {}'.format(idl)) 305 # answer = list() 306 # for x in idl: 307 # print('Looking at {}'.format(x)) 308 # print('what the heck is idl.count(x)??? {}'.format(idl.count(x))) 309 # if idl.count(x) > 1: 310 # answer.append(x) 311 # print(' ... append it {}'.format(x)) | |
312 return [x for x in idl if idl.count(x) > 1] | 410 return [x for x in idl if idl.count(x) > 1] |
313 return answer | |
314 315 316def does_id_exist(alltests, newid): 317 """ 318 Check if a given ID already exists in the list of test cases. 319 """ 320 idl = get_id_list(alltests) 321 return (any(newid == x for x in idl)) --- 76 unchanged lines hidden (view full) --- 398 testdirs = ['tc-tests'] 399 400 if args.file: 401 # at least one file was specified - remove the default directory 402 testdirs = [] 403 404 for ff in args.file: 405 if not os.path.isfile(ff): | 411 412 413def does_id_exist(alltests, newid): 414 """ 415 Check if a given ID already exists in the list of test cases. 416 """ 417 idl = get_id_list(alltests) 418 return (any(newid == x for x in idl)) --- 76 unchanged lines hidden (view full) --- 495 testdirs = ['tc-tests'] 496 497 if args.file: 498 # at least one file was specified - remove the default directory 499 testdirs = [] 500 501 for ff in args.file: 502 if not os.path.isfile(ff): |
406 print("IGNORING file " + ff + " \n\tBECAUSE does not exist.") | 503 print("IGNORING file " + ff + "\n\tBECAUSE does not exist.") |
407 else: 408 flist.append(os.path.abspath(ff)) 409 410 if args.directory: 411 testdirs = args.directory 412 413 for testdir in testdirs: 414 for root, dirnames, filenames in os.walk(testdir): --- 25 unchanged lines hidden (view full) --- 440 else: 441 # just accept the existing value of alltestcases, 442 # which has been filtered by file/directory 443 pass 444 445 return allcatlist, allidlist, testcases_by_cats, alltestcases 446 447 | 504 else: 505 flist.append(os.path.abspath(ff)) 506 507 if args.directory: 508 testdirs = args.directory 509 510 for testdir in testdirs: 511 for root, dirnames, filenames in os.walk(testdir): --- 25 unchanged lines hidden (view full) --- 537 else: 538 # just accept the existing value of alltestcases, 539 # which has been filtered by file/directory 540 pass 541 542 return allcatlist, allidlist, testcases_by_cats, alltestcases 543 544 |
448def set_operation_mode(args): | 545def set_operation_mode(pm, args): |
449 """ 450 Load the test case data and process remaining arguments to determine 451 what the script should do for this run, and call the appropriate 452 function. 453 """ 454 ucat, idlist, testcases, alltests = get_test_cases(args) 455 456 if args.gen_id: --- 24 unchanged lines hidden (view full) --- 481 if args.list: 482 list_test_cases(alltests) 483 exit(0) 484 485 if (os.geteuid() != 0): 486 print("This script must be run with root privileges.\n") 487 exit(1) 488 | 546 """ 547 Load the test case data and process remaining arguments to determine 548 what the script should do for this run, and call the appropriate 549 function. 550 """ 551 ucat, idlist, testcases, alltests = get_test_cases(args) 552 553 if args.gen_id: --- 24 unchanged lines hidden (view full) --- 578 if args.list: 579 list_test_cases(alltests) 580 exit(0) 581 582 if (os.geteuid() != 0): 583 print("This script must be run with root privileges.\n") 584 exit(1) 585 |
489 ns_create() | 586 ns_create(args, pm) |
490 | 587 |
491 catresults = test_runner(alltests, args) | 588 if len(alltests): 589 catresults = test_runner(pm, args, alltests) 590 else: 591 catresults = 'No tests found\n' |
492 print('All test results: \n\n{}'.format(catresults)) 493 | 592 print('All test results: \n\n{}'.format(catresults)) 593 |
494 ns_destroy() | 594 ns_destroy(args, pm) |
495 496 497def main(): 498 """ 499 Start of execution; set up argument parser and get the arguments, 500 and start operations. 501 """ 502 parser = args_parse() 503 parser = set_args(parser) | 595 596 597def main(): 598 """ 599 Start of execution; set up argument parser and get the arguments, 600 and start operations. 601 """ 602 parser = args_parse() 603 parser = set_args(parser) |
604 pm = PluginMgr(parser) 605 parser = pm.call_add_args(parser) |
|
504 (args, remaining) = parser.parse_known_args() | 606 (args, remaining) = parser.parse_known_args() |
505 check_default_settings(args) | 607 args.NAMES = NAMES 608 check_default_settings(args, remaining, pm) 609 if args.verbose > 2: 610 print('args is {}'.format(args)) |
506 | 611 |
507 set_operation_mode(args) | 612 set_operation_mode(pm, args) |
508 509 exit(0) 510 511 512if __name__ == "__main__": 513 main() | 613 614 exit(0) 615 616 617if __name__ == "__main__": 618 main() |