tdc.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. """
  4. tdc.py - Linux tc (Traffic Control) unit test driver
  5. Copyright (C) 2017 Lucas Bates <lucasb@mojatatu.com>
  6. """
  7. import re
  8. import os
  9. import sys
  10. import argparse
  11. import importlib
  12. import json
  13. import subprocess
  14. import time
  15. import traceback
  16. from collections import OrderedDict
  17. from string import Template
  18. from tdc_config import *
  19. from tdc_helper import *
  20. import TdcPlugin
  21. class PluginMgrTestFail(Exception):
  22. def __init__(self, stage, output, message):
  23. self.stage = stage
  24. self.output = output
  25. self.message = message
  26. class PluginMgr:
  27. def __init__(self, argparser):
  28. super().__init__()
  29. self.plugins = {}
  30. self.plugin_instances = []
  31. self.args = []
  32. self.argparser = argparser
  33. # TODO, put plugins in order
  34. plugindir = os.getenv('TDC_PLUGIN_DIR', './plugins')
  35. for dirpath, dirnames, filenames in os.walk(plugindir):
  36. for fn in filenames:
  37. if (fn.endswith('.py') and
  38. not fn == '__init__.py' and
  39. not fn.startswith('#') and
  40. not fn.startswith('.#')):
  41. mn = fn[0:-3]
  42. foo = importlib.import_module('plugins.' + mn)
  43. self.plugins[mn] = foo
  44. self.plugin_instances.append(foo.SubPlugin())
  45. def call_pre_suite(self, testcount, testidlist):
  46. for pgn_inst in self.plugin_instances:
  47. pgn_inst.pre_suite(testcount, testidlist)
  48. def call_post_suite(self, index):
  49. for pgn_inst in reversed(self.plugin_instances):
  50. pgn_inst.post_suite(index)
  51. def call_pre_case(self, test_ordinal, testid):
  52. for pgn_inst in self.plugin_instances:
  53. try:
  54. pgn_inst.pre_case(test_ordinal, testid)
  55. except Exception as ee:
  56. print('exception {} in call to pre_case for {} plugin'.
  57. format(ee, pgn_inst.__class__))
  58. print('test_ordinal is {}'.format(test_ordinal))
  59. print('testid is {}'.format(testid))
  60. raise
  61. def call_post_case(self):
  62. for pgn_inst in reversed(self.plugin_instances):
  63. pgn_inst.post_case()
  64. def call_pre_execute(self):
  65. for pgn_inst in self.plugin_instances:
  66. pgn_inst.pre_execute()
  67. def call_post_execute(self):
  68. for pgn_inst in reversed(self.plugin_instances):
  69. pgn_inst.post_execute()
  70. def call_add_args(self, parser):
  71. for pgn_inst in self.plugin_instances:
  72. parser = pgn_inst.add_args(parser)
  73. return parser
  74. def call_check_args(self, args, remaining):
  75. for pgn_inst in self.plugin_instances:
  76. pgn_inst.check_args(args, remaining)
  77. def call_adjust_command(self, stage, command):
  78. for pgn_inst in self.plugin_instances:
  79. command = pgn_inst.adjust_command(stage, command)
  80. return command
  81. @staticmethod
  82. def _make_argparser(args):
  83. self.argparser = argparse.ArgumentParser(
  84. description='Linux TC unit tests')
  85. def replace_keywords(cmd):
  86. """
  87. For a given executable command, substitute any known
  88. variables contained within NAMES with the correct values
  89. """
  90. tcmd = Template(cmd)
  91. subcmd = tcmd.safe_substitute(NAMES)
  92. return subcmd
  93. def exec_cmd(args, pm, stage, command):
  94. """
  95. Perform any required modifications on an executable command, then run
  96. it in a subprocess and return the results.
  97. """
  98. if len(command.strip()) == 0:
  99. return None, None
  100. if '$' in command:
  101. command = replace_keywords(command)
  102. command = pm.call_adjust_command(stage, command)
  103. if args.verbose > 0:
  104. print('command "{}"'.format(command))
  105. proc = subprocess.Popen(command,
  106. shell=True,
  107. stdout=subprocess.PIPE,
  108. stderr=subprocess.PIPE,
  109. env=ENVIR)
  110. (rawout, serr) = proc.communicate()
  111. if proc.returncode != 0 and len(serr) > 0:
  112. foutput = serr.decode("utf-8", errors="ignore")
  113. else:
  114. foutput = rawout.decode("utf-8", errors="ignore")
  115. proc.stdout.close()
  116. proc.stderr.close()
  117. return proc, foutput
  118. def prepare_env(args, pm, stage, prefix, cmdlist, output = None):
  119. """
  120. Execute the setup/teardown commands for a test case.
  121. Optionally terminate test execution if the command fails.
  122. """
  123. if args.verbose > 0:
  124. print('{}'.format(prefix))
  125. for cmdinfo in cmdlist:
  126. if isinstance(cmdinfo, list):
  127. exit_codes = cmdinfo[1:]
  128. cmd = cmdinfo[0]
  129. else:
  130. exit_codes = [0]
  131. cmd = cmdinfo
  132. if not cmd:
  133. continue
  134. (proc, foutput) = exec_cmd(args, pm, stage, cmd)
  135. if proc and (proc.returncode not in exit_codes):
  136. print('', file=sys.stderr)
  137. print("{} *** Could not execute: \"{}\"".format(prefix, cmd),
  138. file=sys.stderr)
  139. print("\n{} *** Error message: \"{}\"".format(prefix, foutput),
  140. file=sys.stderr)
  141. print("returncode {}; expected {}".format(proc.returncode,
  142. exit_codes))
  143. print("\n{} *** Aborting test run.".format(prefix), file=sys.stderr)
  144. print("\n\n{} *** stdout ***".format(proc.stdout), file=sys.stderr)
  145. print("\n\n{} *** stderr ***".format(proc.stderr), file=sys.stderr)
  146. raise PluginMgrTestFail(
  147. stage, output,
  148. '"{}" did not complete successfully'.format(prefix))
  149. def run_one_test(pm, args, index, tidx):
  150. global NAMES
  151. result = True
  152. tresult = ""
  153. tap = ""
  154. if args.verbose > 0:
  155. print("\t====================\n=====> ", end="")
  156. print("Test " + tidx["id"] + ": " + tidx["name"])
  157. # populate NAMES with TESTID for this test
  158. NAMES['TESTID'] = tidx['id']
  159. pm.call_pre_case(index, tidx['id'])
  160. prepare_env(args, pm, 'setup', "-----> prepare stage", tidx["setup"])
  161. if (args.verbose > 0):
  162. print('-----> execute stage')
  163. pm.call_pre_execute()
  164. (p, procout) = exec_cmd(args, pm, 'execute', tidx["cmdUnderTest"])
  165. if p:
  166. exit_code = p.returncode
  167. else:
  168. exit_code = None
  169. pm.call_post_execute()
  170. if (exit_code is None or exit_code != int(tidx["expExitCode"])):
  171. result = False
  172. print("exit: {!r}".format(exit_code))
  173. print("exit: {}".format(int(tidx["expExitCode"])))
  174. #print("exit: {!r} {}".format(exit_code, int(tidx["expExitCode"])))
  175. print(procout)
  176. else:
  177. if args.verbose > 0:
  178. print('-----> verify stage')
  179. match_pattern = re.compile(
  180. str(tidx["matchPattern"]), re.DOTALL | re.MULTILINE)
  181. (p, procout) = exec_cmd(args, pm, 'verify', tidx["verifyCmd"])
  182. if procout:
  183. match_index = re.findall(match_pattern, procout)
  184. if len(match_index) != int(tidx["matchCount"]):
  185. result = False
  186. elif int(tidx["matchCount"]) != 0:
  187. result = False
  188. if not result:
  189. tresult += 'not '
  190. tresult += 'ok {} - {} # {}\n'.format(str(index), tidx['id'], tidx['name'])
  191. tap += tresult
  192. if result == False:
  193. if procout:
  194. tap += procout
  195. else:
  196. tap += 'No output!\n'
  197. prepare_env(args, pm, 'teardown', '-----> teardown stage', tidx['teardown'], procout)
  198. pm.call_post_case()
  199. index += 1
  200. # remove TESTID from NAMES
  201. del(NAMES['TESTID'])
  202. return tap
  203. def test_runner(pm, args, filtered_tests):
  204. """
  205. Driver function for the unit tests.
  206. Prints information about the tests being run, executes the setup and
  207. teardown commands and the command under test itself. Also determines
  208. success/failure based on the information in the test case and generates
  209. TAP output accordingly.
  210. """
  211. testlist = filtered_tests
  212. tcount = len(testlist)
  213. index = 1
  214. tap = ''
  215. badtest = None
  216. stage = None
  217. emergency_exit = False
  218. emergency_exit_message = ''
  219. if args.notap:
  220. if args.verbose:
  221. tap = 'notap requested: omitting test plan\n'
  222. else:
  223. tap = str(index) + ".." + str(tcount) + "\n"
  224. try:
  225. pm.call_pre_suite(tcount, [tidx['id'] for tidx in testlist])
  226. except Exception as ee:
  227. ex_type, ex, ex_tb = sys.exc_info()
  228. print('Exception {} {} (caught in pre_suite).'.
  229. format(ex_type, ex))
  230. # when the extra print statements are uncommented,
  231. # the traceback does not appear between them
  232. # (it appears way earlier in the tdc.py output)
  233. # so don't bother ...
  234. # print('--------------------(')
  235. # print('traceback')
  236. traceback.print_tb(ex_tb)
  237. # print('--------------------)')
  238. emergency_exit_message = 'EMERGENCY EXIT, call_pre_suite failed with exception {} {}\n'.format(ex_type, ex)
  239. emergency_exit = True
  240. stage = 'pre-SUITE'
  241. if emergency_exit:
  242. pm.call_post_suite(index)
  243. return emergency_exit_message
  244. if args.verbose > 1:
  245. print('give test rig 2 seconds to stabilize')
  246. time.sleep(2)
  247. for tidx in testlist:
  248. if "flower" in tidx["category"] and args.device == None:
  249. if args.verbose > 1:
  250. print('Not executing test {} {} because DEV2 not defined'.
  251. format(tidx['id'], tidx['name']))
  252. continue
  253. try:
  254. badtest = tidx # in case it goes bad
  255. tap += run_one_test(pm, args, index, tidx)
  256. except PluginMgrTestFail as pmtf:
  257. ex_type, ex, ex_tb = sys.exc_info()
  258. stage = pmtf.stage
  259. message = pmtf.message
  260. output = pmtf.output
  261. print(message)
  262. print('Exception {} {} (caught in test_runner, running test {} {} {} stage {})'.
  263. format(ex_type, ex, index, tidx['id'], tidx['name'], stage))
  264. print('---------------')
  265. print('traceback')
  266. traceback.print_tb(ex_tb)
  267. print('---------------')
  268. if stage == 'teardown':
  269. print('accumulated output for this test:')
  270. if pmtf.output:
  271. print(pmtf.output)
  272. print('---------------')
  273. break
  274. index += 1
  275. # if we failed in setup or teardown,
  276. # fill in the remaining tests with ok-skipped
  277. count = index
  278. if not args.notap:
  279. tap += 'about to flush the tap output if tests need to be skipped\n'
  280. if tcount + 1 != index:
  281. for tidx in testlist[index - 1:]:
  282. msg = 'skipped - previous {} failed'.format(stage)
  283. tap += 'ok {} - {} # {} {} {}\n'.format(
  284. count, tidx['id'], msg, index, badtest.get('id', '--Unknown--'))
  285. count += 1
  286. tap += 'done flushing skipped test tap output\n'
  287. if args.pause:
  288. print('Want to pause\nPress enter to continue ...')
  289. if input(sys.stdin):
  290. print('got something on stdin')
  291. pm.call_post_suite(index)
  292. return tap
  293. def has_blank_ids(idlist):
  294. """
  295. Search the list for empty ID fields and return true/false accordingly.
  296. """
  297. return not(all(k for k in idlist))
  298. def load_from_file(filename):
  299. """
  300. Open the JSON file containing the test cases and return them
  301. as list of ordered dictionary objects.
  302. """
  303. try:
  304. with open(filename) as test_data:
  305. testlist = json.load(test_data, object_pairs_hook=OrderedDict)
  306. except json.JSONDecodeError as jde:
  307. print('IGNORING test case file {}\n\tBECAUSE: {}'.format(filename, jde))
  308. testlist = list()
  309. else:
  310. idlist = get_id_list(testlist)
  311. if (has_blank_ids(idlist)):
  312. for k in testlist:
  313. k['filename'] = filename
  314. return testlist
  315. def args_parse():
  316. """
  317. Create the argument parser.
  318. """
  319. parser = argparse.ArgumentParser(description='Linux TC unit tests')
  320. return parser
  321. def set_args(parser):
  322. """
  323. Set the command line arguments for tdc.
  324. """
  325. parser.add_argument(
  326. '-p', '--path', type=str,
  327. help='The full path to the tc executable to use')
  328. sg = parser.add_argument_group(
  329. 'selection', 'select which test cases: ' +
  330. 'files plus directories; filtered by categories plus testids')
  331. ag = parser.add_argument_group(
  332. 'action', 'select action to perform on selected test cases')
  333. sg.add_argument(
  334. '-D', '--directory', nargs='+', metavar='DIR',
  335. help='Collect tests from the specified directory(ies) ' +
  336. '(default [tc-tests])')
  337. sg.add_argument(
  338. '-f', '--file', nargs='+', metavar='FILE',
  339. help='Run tests from the specified file(s)')
  340. sg.add_argument(
  341. '-c', '--category', nargs='*', metavar='CATG', default=['+c'],
  342. help='Run tests only from the specified category/ies, ' +
  343. 'or if no category/ies is/are specified, list known categories.')
  344. sg.add_argument(
  345. '-e', '--execute', nargs='+', metavar='ID',
  346. help='Execute the specified test cases with specified IDs')
  347. ag.add_argument(
  348. '-l', '--list', action='store_true',
  349. help='List all test cases, or those only within the specified category')
  350. ag.add_argument(
  351. '-s', '--show', action='store_true', dest='showID',
  352. help='Display the selected test cases')
  353. ag.add_argument(
  354. '-i', '--id', action='store_true', dest='gen_id',
  355. help='Generate ID numbers for new test cases')
  356. parser.add_argument(
  357. '-v', '--verbose', action='count', default=0,
  358. help='Show the commands that are being run')
  359. parser.add_argument(
  360. '-N', '--notap', action='store_true',
  361. help='Suppress tap results for command under test')
  362. parser.add_argument('-d', '--device',
  363. help='Execute the test case in flower category')
  364. parser.add_argument(
  365. '-P', '--pause', action='store_true',
  366. help='Pause execution just before post-suite stage')
  367. return parser
  368. def check_default_settings(args, remaining, pm):
  369. """
  370. Process any arguments overriding the default settings,
  371. and ensure the settings are correct.
  372. """
  373. # Allow for overriding specific settings
  374. global NAMES
  375. if args.path != None:
  376. NAMES['TC'] = args.path
  377. if args.device != None:
  378. NAMES['DEV2'] = args.device
  379. if not os.path.isfile(NAMES['TC']):
  380. print("The specified tc path " + NAMES['TC'] + " does not exist.")
  381. exit(1)
  382. pm.call_check_args(args, remaining)
  383. def get_id_list(alltests):
  384. """
  385. Generate a list of all IDs in the test cases.
  386. """
  387. return [x["id"] for x in alltests]
  388. def check_case_id(alltests):
  389. """
  390. Check for duplicate test case IDs.
  391. """
  392. idl = get_id_list(alltests)
  393. return [x for x in idl if idl.count(x) > 1]
  394. def does_id_exist(alltests, newid):
  395. """
  396. Check if a given ID already exists in the list of test cases.
  397. """
  398. idl = get_id_list(alltests)
  399. return (any(newid == x for x in idl))
  400. def generate_case_ids(alltests):
  401. """
  402. If a test case has a blank ID field, generate a random hex ID for it
  403. and then write the test cases back to disk.
  404. """
  405. import random
  406. for c in alltests:
  407. if (c["id"] == ""):
  408. while True:
  409. newid = str('{:04x}'.format(random.randrange(16**4)))
  410. if (does_id_exist(alltests, newid)):
  411. continue
  412. else:
  413. c['id'] = newid
  414. break
  415. ufilename = []
  416. for c in alltests:
  417. if ('filename' in c):
  418. ufilename.append(c['filename'])
  419. ufilename = get_unique_item(ufilename)
  420. for f in ufilename:
  421. testlist = []
  422. for t in alltests:
  423. if 'filename' in t:
  424. if t['filename'] == f:
  425. del t['filename']
  426. testlist.append(t)
  427. outfile = open(f, "w")
  428. json.dump(testlist, outfile, indent=4)
  429. outfile.write("\n")
  430. outfile.close()
  431. def filter_tests_by_id(args, testlist):
  432. '''
  433. Remove tests from testlist that are not in the named id list.
  434. If id list is empty, return empty list.
  435. '''
  436. newlist = list()
  437. if testlist and args.execute:
  438. target_ids = args.execute
  439. if isinstance(target_ids, list) and (len(target_ids) > 0):
  440. newlist = list(filter(lambda x: x['id'] in target_ids, testlist))
  441. return newlist
  442. def filter_tests_by_category(args, testlist):
  443. '''
  444. Remove tests from testlist that are not in a named category.
  445. '''
  446. answer = list()
  447. if args.category and testlist:
  448. test_ids = list()
  449. for catg in set(args.category):
  450. if catg == '+c':
  451. continue
  452. print('considering category {}'.format(catg))
  453. for tc in testlist:
  454. if catg in tc['category'] and tc['id'] not in test_ids:
  455. answer.append(tc)
  456. test_ids.append(tc['id'])
  457. return answer
  458. def get_test_cases(args):
  459. """
  460. If a test case file is specified, retrieve tests from that file.
  461. Otherwise, glob for all json files in subdirectories and load from
  462. each one.
  463. Also, if requested, filter by category, and add tests matching
  464. certain ids.
  465. """
  466. import fnmatch
  467. flist = []
  468. testdirs = ['tc-tests']
  469. if args.file:
  470. # at least one file was specified - remove the default directory
  471. testdirs = []
  472. for ff in args.file:
  473. if not os.path.isfile(ff):
  474. print("IGNORING file " + ff + "\n\tBECAUSE does not exist.")
  475. else:
  476. flist.append(os.path.abspath(ff))
  477. if args.directory:
  478. testdirs = args.directory
  479. for testdir in testdirs:
  480. for root, dirnames, filenames in os.walk(testdir):
  481. for filename in fnmatch.filter(filenames, '*.json'):
  482. candidate = os.path.abspath(os.path.join(root, filename))
  483. if candidate not in testdirs:
  484. flist.append(candidate)
  485. alltestcases = list()
  486. for casefile in flist:
  487. alltestcases = alltestcases + (load_from_file(casefile))
  488. allcatlist = get_test_categories(alltestcases)
  489. allidlist = get_id_list(alltestcases)
  490. testcases_by_cats = get_categorized_testlist(alltestcases, allcatlist)
  491. idtestcases = filter_tests_by_id(args, alltestcases)
  492. cattestcases = filter_tests_by_category(args, alltestcases)
  493. cat_ids = [x['id'] for x in cattestcases]
  494. if args.execute:
  495. if args.category:
  496. alltestcases = cattestcases + [x for x in idtestcases if x['id'] not in cat_ids]
  497. else:
  498. alltestcases = idtestcases
  499. else:
  500. if cat_ids:
  501. alltestcases = cattestcases
  502. else:
  503. # just accept the existing value of alltestcases,
  504. # which has been filtered by file/directory
  505. pass
  506. return allcatlist, allidlist, testcases_by_cats, alltestcases
  507. def set_operation_mode(pm, args):
  508. """
  509. Load the test case data and process remaining arguments to determine
  510. what the script should do for this run, and call the appropriate
  511. function.
  512. """
  513. ucat, idlist, testcases, alltests = get_test_cases(args)
  514. if args.gen_id:
  515. if (has_blank_ids(idlist)):
  516. alltests = generate_case_ids(alltests)
  517. else:
  518. print("No empty ID fields found in test files.")
  519. exit(0)
  520. duplicate_ids = check_case_id(alltests)
  521. if (len(duplicate_ids) > 0):
  522. print("The following test case IDs are not unique:")
  523. print(str(set(duplicate_ids)))
  524. print("Please correct them before continuing.")
  525. exit(1)
  526. if args.showID:
  527. for atest in alltests:
  528. print_test_case(atest)
  529. exit(0)
  530. if isinstance(args.category, list) and (len(args.category) == 0):
  531. print("Available categories:")
  532. print_sll(ucat)
  533. exit(0)
  534. if args.list:
  535. if args.list:
  536. list_test_cases(alltests)
  537. exit(0)
  538. if len(alltests):
  539. catresults = test_runner(pm, args, alltests)
  540. else:
  541. catresults = 'No tests found\n'
  542. if args.notap:
  543. print('Tap output suppression requested\n')
  544. else:
  545. print('All test results: \n\n{}'.format(catresults))
  546. def main():
  547. """
  548. Start of execution; set up argument parser and get the arguments,
  549. and start operations.
  550. """
  551. parser = args_parse()
  552. parser = set_args(parser)
  553. pm = PluginMgr(parser)
  554. parser = pm.call_add_args(parser)
  555. (args, remaining) = parser.parse_known_args()
  556. args.NAMES = NAMES
  557. check_default_settings(args, remaining, pm)
  558. if args.verbose > 2:
  559. print('args is {}'.format(args))
  560. set_operation_mode(pm, args)
  561. exit(0)
  562. if __name__ == "__main__":
  563. main()