tdc.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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. import random
  17. from multiprocessing import Pool
  18. from collections import OrderedDict
  19. from string import Template
  20. from tdc_config import *
  21. from tdc_helper import *
  22. import TdcPlugin
  23. from TdcResults import *
  24. class PluginDependencyException(Exception):
  25. def __init__(self, missing_pg):
  26. self.missing_pg = missing_pg
  27. class PluginMgrTestFail(Exception):
  28. def __init__(self, stage, output, message):
  29. self.stage = stage
  30. self.output = output
  31. self.message = message
  32. class PluginMgr:
  33. def __init__(self, argparser):
  34. super().__init__()
  35. self.plugins = set()
  36. self.plugin_instances = []
  37. self.failed_plugins = {}
  38. self.argparser = argparser
  39. plugindir = os.getenv('TDC_PLUGIN_DIR', './plugins')
  40. for dirpath, dirnames, filenames in os.walk(plugindir):
  41. for fn in filenames:
  42. if (fn.endswith('.py') and
  43. not fn == '__init__.py' and
  44. not fn.startswith('#') and
  45. not fn.startswith('.#')):
  46. mn = fn[0:-3]
  47. foo = importlib.import_module('plugins.' + mn)
  48. self.plugins.add(mn)
  49. self.plugin_instances[mn] = foo.SubPlugin()
  50. def load_plugin(self, pgdir, pgname):
  51. pgname = pgname[0:-3]
  52. self.plugins.add(pgname)
  53. foo = importlib.import_module('{}.{}'.format(pgdir, pgname))
  54. # nsPlugin must always be the first one
  55. if pgname == "nsPlugin":
  56. self.plugin_instances.insert(0, (pgname, foo.SubPlugin()))
  57. self.plugin_instances[0][1].check_args(self.args, None)
  58. else:
  59. self.plugin_instances.append((pgname, foo.SubPlugin()))
  60. self.plugin_instances[-1][1].check_args(self.args, None)
  61. def get_required_plugins(self, testlist):
  62. '''
  63. Get all required plugins from the list of test cases and return
  64. all unique items.
  65. '''
  66. reqs = set()
  67. for t in testlist:
  68. try:
  69. if 'requires' in t['plugins']:
  70. if isinstance(t['plugins']['requires'], list):
  71. reqs.update(set(t['plugins']['requires']))
  72. else:
  73. reqs.add(t['plugins']['requires'])
  74. t['plugins'] = t['plugins']['requires']
  75. else:
  76. t['plugins'] = []
  77. except KeyError:
  78. t['plugins'] = []
  79. continue
  80. return reqs
  81. def load_required_plugins(self, reqs, parser, args, remaining):
  82. '''
  83. Get all required plugins from the list of test cases and load any plugin
  84. that is not already enabled.
  85. '''
  86. pgd = ['plugin-lib', 'plugin-lib-custom']
  87. pnf = []
  88. for r in reqs:
  89. if r not in self.plugins:
  90. fname = '{}.py'.format(r)
  91. source_path = []
  92. for d in pgd:
  93. pgpath = '{}/{}'.format(d, fname)
  94. if os.path.isfile(pgpath):
  95. source_path.append(pgpath)
  96. if len(source_path) == 0:
  97. print('ERROR: unable to find required plugin {}'.format(r))
  98. pnf.append(fname)
  99. continue
  100. elif len(source_path) > 1:
  101. print('WARNING: multiple copies of plugin {} found, using version found')
  102. print('at {}'.format(source_path[0]))
  103. pgdir = source_path[0]
  104. pgdir = pgdir.split('/')[0]
  105. self.load_plugin(pgdir, fname)
  106. if len(pnf) > 0:
  107. raise PluginDependencyException(pnf)
  108. parser = self.call_add_args(parser)
  109. (args, remaining) = parser.parse_known_args(args=remaining, namespace=args)
  110. return args
  111. def call_pre_suite(self, testcount, testidlist):
  112. for (_, pgn_inst) in self.plugin_instances:
  113. pgn_inst.pre_suite(testcount, testidlist)
  114. def call_post_suite(self, index):
  115. for (_, pgn_inst) in reversed(self.plugin_instances):
  116. pgn_inst.post_suite(index)
  117. def call_pre_case(self, caseinfo, *, test_skip=False):
  118. for (pgn, pgn_inst) in self.plugin_instances:
  119. if pgn not in caseinfo['plugins']:
  120. continue
  121. try:
  122. pgn_inst.pre_case(caseinfo, test_skip)
  123. except Exception as ee:
  124. print('exception {} in call to pre_case for {} plugin'.
  125. format(ee, pgn_inst.__class__))
  126. print('testid is {}'.format(caseinfo['id']))
  127. raise
  128. def call_post_case(self, caseinfo):
  129. for (pgn, pgn_inst) in reversed(self.plugin_instances):
  130. if pgn not in caseinfo['plugins']:
  131. continue
  132. pgn_inst.post_case()
  133. def call_pre_execute(self, caseinfo):
  134. for (pgn, pgn_inst) in self.plugin_instances:
  135. if pgn not in caseinfo['plugins']:
  136. continue
  137. pgn_inst.pre_execute()
  138. def call_post_execute(self, caseinfo):
  139. for (pgn, pgn_inst) in reversed(self.plugin_instances):
  140. if pgn not in caseinfo['plugins']:
  141. continue
  142. pgn_inst.post_execute()
  143. def call_add_args(self, parser):
  144. for (pgn, pgn_inst) in self.plugin_instances:
  145. parser = pgn_inst.add_args(parser)
  146. return parser
  147. def call_check_args(self, args, remaining):
  148. for (pgn, pgn_inst) in self.plugin_instances:
  149. pgn_inst.check_args(args, remaining)
  150. def call_adjust_command(self, caseinfo, stage, command):
  151. for (pgn, pgn_inst) in self.plugin_instances:
  152. if pgn not in caseinfo['plugins']:
  153. continue
  154. command = pgn_inst.adjust_command(stage, command)
  155. return command
  156. def set_args(self, args):
  157. self.args = args
  158. @staticmethod
  159. def _make_argparser(args):
  160. self.argparser = argparse.ArgumentParser(
  161. description='Linux TC unit tests')
  162. def replace_keywords(cmd):
  163. """
  164. For a given executable command, substitute any known
  165. variables contained within NAMES with the correct values
  166. """
  167. tcmd = Template(cmd)
  168. subcmd = tcmd.safe_substitute(NAMES)
  169. return subcmd
  170. def exec_cmd(caseinfo, args, pm, stage, command):
  171. """
  172. Perform any required modifications on an executable command, then run
  173. it in a subprocess and return the results.
  174. """
  175. if len(command.strip()) == 0:
  176. return None, None
  177. if '$' in command:
  178. command = replace_keywords(command)
  179. command = pm.call_adjust_command(caseinfo, stage, command)
  180. if args.verbose > 0:
  181. print('command "{}"'.format(command))
  182. proc = subprocess.Popen(command,
  183. shell=True,
  184. stdout=subprocess.PIPE,
  185. stderr=subprocess.PIPE,
  186. env=ENVIR)
  187. try:
  188. (rawout, serr) = proc.communicate(timeout=NAMES['TIMEOUT'])
  189. if proc.returncode != 0 and len(serr) > 0:
  190. foutput = serr.decode("utf-8", errors="ignore")
  191. else:
  192. foutput = rawout.decode("utf-8", errors="ignore")
  193. except subprocess.TimeoutExpired:
  194. foutput = "Command \"{}\" timed out\n".format(command)
  195. proc.returncode = 255
  196. proc.stdout.close()
  197. proc.stderr.close()
  198. return proc, foutput
  199. def prepare_env(caseinfo, args, pm, stage, prefix, cmdlist, output = None):
  200. """
  201. Execute the setup/teardown commands for a test case.
  202. Optionally terminate test execution if the command fails.
  203. """
  204. if args.verbose > 0:
  205. print('{}'.format(prefix))
  206. for cmdinfo in cmdlist:
  207. if isinstance(cmdinfo, list):
  208. exit_codes = cmdinfo[1:]
  209. cmd = cmdinfo[0]
  210. else:
  211. exit_codes = [0]
  212. cmd = cmdinfo
  213. if not cmd:
  214. continue
  215. (proc, foutput) = exec_cmd(caseinfo, args, pm, stage, cmd)
  216. if proc and (proc.returncode not in exit_codes):
  217. print('', file=sys.stderr)
  218. print("{} *** Could not execute: \"{}\"".format(prefix, cmd),
  219. file=sys.stderr)
  220. print("\n{} *** Error message: \"{}\"".format(prefix, foutput),
  221. file=sys.stderr)
  222. print("returncode {}; expected {}".format(proc.returncode,
  223. exit_codes))
  224. print("\n{} *** Aborting test run.".format(prefix), file=sys.stderr)
  225. print("\n\n{} *** stdout ***".format(proc.stdout), file=sys.stderr)
  226. print("\n\n{} *** stderr ***".format(proc.stderr), file=sys.stderr)
  227. raise PluginMgrTestFail(
  228. stage, output,
  229. '"{}" did not complete successfully'.format(prefix))
  230. def verify_by_json(procout, res, tidx, args, pm):
  231. try:
  232. outputJSON = json.loads(procout)
  233. except json.JSONDecodeError:
  234. res.set_result(ResultState.fail)
  235. res.set_failmsg('Cannot decode verify command\'s output. Is it JSON?')
  236. return res
  237. matchJSON = json.loads(json.dumps(tidx['matchJSON']))
  238. if type(outputJSON) != type(matchJSON):
  239. failmsg = 'Original output and matchJSON value are not the same type: output: {} != matchJSON: {} '
  240. failmsg = failmsg.format(type(outputJSON).__name__, type(matchJSON).__name__)
  241. res.set_result(ResultState.fail)
  242. res.set_failmsg(failmsg)
  243. return res
  244. if len(matchJSON) > len(outputJSON):
  245. failmsg = "Your matchJSON value is an array, and it contains more elements than the command under test\'s output:\ncommand output (length: {}):\n{}\nmatchJSON value (length: {}):\n{}"
  246. failmsg = failmsg.format(len(outputJSON), outputJSON, len(matchJSON), matchJSON)
  247. res.set_result(ResultState.fail)
  248. res.set_failmsg(failmsg)
  249. return res
  250. res = find_in_json(res, outputJSON, matchJSON, 0)
  251. return res
  252. def find_in_json(res, outputJSONVal, matchJSONVal, matchJSONKey=None):
  253. if res.get_result() == ResultState.fail:
  254. return res
  255. if type(matchJSONVal) == list:
  256. res = find_in_json_list(res, outputJSONVal, matchJSONVal, matchJSONKey)
  257. elif type(matchJSONVal) == dict:
  258. res = find_in_json_dict(res, outputJSONVal, matchJSONVal)
  259. else:
  260. res = find_in_json_other(res, outputJSONVal, matchJSONVal, matchJSONKey)
  261. if res.get_result() != ResultState.fail:
  262. res.set_result(ResultState.success)
  263. return res
  264. return res
  265. def find_in_json_list(res, outputJSONVal, matchJSONVal, matchJSONKey=None):
  266. if (type(matchJSONVal) != type(outputJSONVal)):
  267. failmsg = 'Original output and matchJSON value are not the same type: output: {} != matchJSON: {}'
  268. failmsg = failmsg.format(outputJSONVal, matchJSONVal)
  269. res.set_result(ResultState.fail)
  270. res.set_failmsg(failmsg)
  271. return res
  272. if len(matchJSONVal) > len(outputJSONVal):
  273. failmsg = "Your matchJSON value is an array, and it contains more elements than the command under test\'s output:\ncommand output (length: {}):\n{}\nmatchJSON value (length: {}):\n{}"
  274. failmsg = failmsg.format(len(outputJSONVal), outputJSONVal, len(matchJSONVal), matchJSONVal)
  275. res.set_result(ResultState.fail)
  276. res.set_failmsg(failmsg)
  277. return res
  278. for matchJSONIdx, matchJSONVal in enumerate(matchJSONVal):
  279. res = find_in_json(res, outputJSONVal[matchJSONIdx], matchJSONVal,
  280. matchJSONKey)
  281. return res
  282. def find_in_json_dict(res, outputJSONVal, matchJSONVal):
  283. for matchJSONKey, matchJSONVal in matchJSONVal.items():
  284. if type(outputJSONVal) == dict:
  285. if matchJSONKey not in outputJSONVal:
  286. failmsg = 'Key not found in json output: {}: {}\nMatching against output: {}'
  287. failmsg = failmsg.format(matchJSONKey, matchJSONVal, outputJSONVal)
  288. res.set_result(ResultState.fail)
  289. res.set_failmsg(failmsg)
  290. return res
  291. else:
  292. failmsg = 'Original output and matchJSON value are not the same type: output: {} != matchJSON: {}'
  293. failmsg = failmsg.format(type(outputJSON).__name__, type(matchJSON).__name__)
  294. res.set_result(ResultState.fail)
  295. res.set_failmsg(failmsg)
  296. return rest
  297. if type(outputJSONVal) == dict and (type(outputJSONVal[matchJSONKey]) == dict or
  298. type(outputJSONVal[matchJSONKey]) == list):
  299. if len(matchJSONVal) > 0:
  300. res = find_in_json(res, outputJSONVal[matchJSONKey], matchJSONVal, matchJSONKey)
  301. # handling corner case where matchJSONVal == [] or matchJSONVal == {}
  302. else:
  303. res = find_in_json_other(res, outputJSONVal, matchJSONVal, matchJSONKey)
  304. else:
  305. res = find_in_json(res, outputJSONVal, matchJSONVal, matchJSONKey)
  306. return res
  307. def find_in_json_other(res, outputJSONVal, matchJSONVal, matchJSONKey=None):
  308. if matchJSONKey in outputJSONVal:
  309. if matchJSONVal != outputJSONVal[matchJSONKey]:
  310. failmsg = 'Value doesn\'t match: {}: {} != {}\nMatching against output: {}'
  311. failmsg = failmsg.format(matchJSONKey, matchJSONVal, outputJSONVal[matchJSONKey], outputJSONVal)
  312. res.set_result(ResultState.fail)
  313. res.set_failmsg(failmsg)
  314. return res
  315. return res
  316. def run_one_test(pm, args, index, tidx):
  317. global NAMES
  318. ns = NAMES['NS']
  319. dev0 = NAMES['DEV0']
  320. dev1 = NAMES['DEV1']
  321. dummy = NAMES['DUMMY']
  322. result = True
  323. tresult = ""
  324. tap = ""
  325. res = TestResult(tidx['id'], tidx['name'])
  326. if args.verbose > 0:
  327. print("\t====================\n=====> ", end="")
  328. print("Test " + tidx["id"] + ": " + tidx["name"])
  329. if 'skip' in tidx:
  330. if tidx['skip'] == 'yes':
  331. res = TestResult(tidx['id'], tidx['name'])
  332. res.set_result(ResultState.skip)
  333. res.set_errormsg('Test case designated as skipped.')
  334. pm.call_pre_case(tidx, test_skip=True)
  335. pm.call_post_execute(tidx)
  336. return res
  337. if 'dependsOn' in tidx:
  338. if (args.verbose > 0):
  339. print('probe command for test skip')
  340. (p, procout) = exec_cmd(tidx, args, pm, 'execute', tidx['dependsOn'])
  341. if p:
  342. if (p.returncode != 0):
  343. res = TestResult(tidx['id'], tidx['name'])
  344. res.set_result(ResultState.skip)
  345. res.set_errormsg('probe command: test skipped.')
  346. pm.call_pre_case(tidx, test_skip=True)
  347. pm.call_post_execute(tidx)
  348. return res
  349. # populate NAMES with TESTID for this test
  350. NAMES['TESTID'] = tidx['id']
  351. NAMES['NS'] = '{}-{}'.format(NAMES['NS'], tidx['random'])
  352. NAMES['DEV0'] = '{}id{}'.format(NAMES['DEV0'], tidx['id'])
  353. NAMES['DEV1'] = '{}id{}'.format(NAMES['DEV1'], tidx['id'])
  354. NAMES['DUMMY'] = '{}id{}'.format(NAMES['DUMMY'], tidx['id'])
  355. pm.call_pre_case(tidx)
  356. prepare_env(tidx, args, pm, 'setup', "-----> prepare stage", tidx["setup"])
  357. if (args.verbose > 0):
  358. print('-----> execute stage')
  359. pm.call_pre_execute(tidx)
  360. (p, procout) = exec_cmd(tidx, args, pm, 'execute', tidx["cmdUnderTest"])
  361. if p:
  362. exit_code = p.returncode
  363. else:
  364. exit_code = None
  365. pm.call_post_execute(tidx)
  366. if (exit_code is None or exit_code != int(tidx["expExitCode"])):
  367. print("exit: {!r}".format(exit_code))
  368. print("exit: {}".format(int(tidx["expExitCode"])))
  369. #print("exit: {!r} {}".format(exit_code, int(tidx["expExitCode"])))
  370. res.set_result(ResultState.fail)
  371. res.set_failmsg('Command exited with {}, expected {}\n{}'.format(exit_code, tidx["expExitCode"], procout))
  372. print(procout)
  373. else:
  374. if args.verbose > 0:
  375. print('-----> verify stage')
  376. (p, procout) = exec_cmd(tidx, args, pm, 'verify', tidx["verifyCmd"])
  377. if procout:
  378. if 'matchJSON' in tidx:
  379. verify_by_json(procout, res, tidx, args, pm)
  380. elif 'matchPattern' in tidx:
  381. match_pattern = re.compile(
  382. str(tidx["matchPattern"]), re.DOTALL | re.MULTILINE)
  383. match_index = re.findall(match_pattern, procout)
  384. if len(match_index) != int(tidx["matchCount"]):
  385. res.set_result(ResultState.fail)
  386. res.set_failmsg('Could not match regex pattern. Verify command output:\n{}'.format(procout))
  387. else:
  388. res.set_result(ResultState.success)
  389. else:
  390. res.set_result(ResultState.fail)
  391. res.set_failmsg('Must specify a match option: matchJSON or matchPattern\n{}'.format(procout))
  392. elif int(tidx["matchCount"]) != 0:
  393. res.set_result(ResultState.fail)
  394. res.set_failmsg('No output generated by verify command.')
  395. else:
  396. res.set_result(ResultState.success)
  397. prepare_env(tidx, args, pm, 'teardown', '-----> teardown stage', tidx['teardown'], procout)
  398. pm.call_post_case(tidx)
  399. index += 1
  400. # remove TESTID from NAMES
  401. del(NAMES['TESTID'])
  402. # Restore names
  403. NAMES['NS'] = ns
  404. NAMES['DEV0'] = dev0
  405. NAMES['DEV1'] = dev1
  406. NAMES['DUMMY'] = dummy
  407. return res
  408. def prepare_run(pm, args, testlist):
  409. tcount = len(testlist)
  410. emergency_exit = False
  411. emergency_exit_message = ''
  412. try:
  413. pm.call_pre_suite(tcount, testlist)
  414. except Exception as ee:
  415. ex_type, ex, ex_tb = sys.exc_info()
  416. print('Exception {} {} (caught in pre_suite).'.
  417. format(ex_type, ex))
  418. traceback.print_tb(ex_tb)
  419. emergency_exit_message = 'EMERGENCY EXIT, call_pre_suite failed with exception {} {}\n'.format(ex_type, ex)
  420. emergency_exit = True
  421. if emergency_exit:
  422. pm.call_post_suite(1)
  423. return emergency_exit_message
  424. def purge_run(pm, index):
  425. pm.call_post_suite(index)
  426. def test_runner(pm, args, filtered_tests):
  427. """
  428. Driver function for the unit tests.
  429. Prints information about the tests being run, executes the setup and
  430. teardown commands and the command under test itself. Also determines
  431. success/failure based on the information in the test case and generates
  432. TAP output accordingly.
  433. """
  434. testlist = filtered_tests
  435. tcount = len(testlist)
  436. index = 1
  437. tap = ''
  438. badtest = None
  439. stage = None
  440. tsr = TestSuiteReport()
  441. for tidx in testlist:
  442. if "flower" in tidx["category"] and args.device == None:
  443. errmsg = "Tests using the DEV2 variable must define the name of a "
  444. errmsg += "physical NIC with the -d option when running tdc.\n"
  445. errmsg += "Test has been skipped."
  446. if args.verbose > 1:
  447. print(errmsg)
  448. res = TestResult(tidx['id'], tidx['name'])
  449. res.set_result(ResultState.skip)
  450. res.set_errormsg(errmsg)
  451. tsr.add_resultdata(res)
  452. index += 1
  453. continue
  454. try:
  455. badtest = tidx # in case it goes bad
  456. res = run_one_test(pm, args, index, tidx)
  457. tsr.add_resultdata(res)
  458. except PluginMgrTestFail as pmtf:
  459. ex_type, ex, ex_tb = sys.exc_info()
  460. stage = pmtf.stage
  461. message = pmtf.message
  462. output = pmtf.output
  463. res = TestResult(tidx['id'], tidx['name'])
  464. res.set_result(ResultState.fail)
  465. res.set_errormsg(pmtf.message)
  466. res.set_failmsg(pmtf.output)
  467. tsr.add_resultdata(res)
  468. index += 1
  469. print(message)
  470. print('Exception {} {} (caught in test_runner, running test {} {} {} stage {})'.
  471. format(ex_type, ex, index, tidx['id'], tidx['name'], stage))
  472. print('---------------')
  473. print('traceback')
  474. traceback.print_tb(ex_tb)
  475. print('---------------')
  476. if stage == 'teardown':
  477. print('accumulated output for this test:')
  478. if pmtf.output:
  479. print(pmtf.output)
  480. print('---------------')
  481. break
  482. index += 1
  483. # if we failed in setup or teardown,
  484. # fill in the remaining tests with ok-skipped
  485. count = index
  486. if tcount + 1 != count:
  487. for tidx in testlist[count - 1:]:
  488. res = TestResult(tidx['id'], tidx['name'])
  489. res.set_result(ResultState.skip)
  490. msg = 'skipped - previous {} failed {} {}'.format(stage,
  491. index, badtest.get('id', '--Unknown--'))
  492. res.set_errormsg(msg)
  493. tsr.add_resultdata(res)
  494. count += 1
  495. if args.pause:
  496. print('Want to pause\nPress enter to continue ...')
  497. if input(sys.stdin):
  498. print('got something on stdin')
  499. return (index, tsr)
  500. def mp_bins(alltests):
  501. serial = []
  502. parallel = []
  503. for test in alltests:
  504. if 'nsPlugin' not in test['plugins']:
  505. serial.append(test)
  506. else:
  507. # We can only create one netdevsim device at a time
  508. if 'netdevsim/new_device' in str(test['setup']):
  509. serial.append(test)
  510. else:
  511. parallel.append(test)
  512. return (serial, parallel)
  513. def __mp_runner(tests):
  514. (_, tsr) = test_runner(mp_pm, mp_args, tests)
  515. return tsr._testsuite
  516. def test_runner_mp(pm, args, alltests):
  517. prepare_run(pm, args, alltests)
  518. (serial, parallel) = mp_bins(alltests)
  519. batches = [parallel[n : n + 32] for n in range(0, len(parallel), 32)]
  520. batches.insert(0, serial)
  521. print("Executing {} tests in parallel and {} in serial".format(len(parallel), len(serial)))
  522. print("Using {} batches and {} workers".format(len(batches), args.mp))
  523. # We can't pickle these objects so workaround them
  524. global mp_pm
  525. mp_pm = pm
  526. global mp_args
  527. mp_args = args
  528. with Pool(args.mp) as p:
  529. pres = p.map(__mp_runner, batches)
  530. tsr = TestSuiteReport()
  531. for trs in pres:
  532. for res in trs:
  533. tsr.add_resultdata(res)
  534. # Passing an index is not useful in MP
  535. purge_run(pm, None)
  536. return tsr
  537. def test_runner_serial(pm, args, alltests):
  538. prepare_run(pm, args, alltests)
  539. if args.verbose:
  540. print("Executing {} tests in serial".format(len(alltests)))
  541. (index, tsr) = test_runner(pm, args, alltests)
  542. purge_run(pm, index)
  543. return tsr
  544. def has_blank_ids(idlist):
  545. """
  546. Search the list for empty ID fields and return true/false accordingly.
  547. """
  548. return not(all(k for k in idlist))
  549. def load_from_file(filename):
  550. """
  551. Open the JSON file containing the test cases and return them
  552. as list of ordered dictionary objects.
  553. """
  554. try:
  555. with open(filename) as test_data:
  556. testlist = json.load(test_data, object_pairs_hook=OrderedDict)
  557. except json.JSONDecodeError as jde:
  558. print('IGNORING test case file {}\n\tBECAUSE: {}'.format(filename, jde))
  559. testlist = list()
  560. else:
  561. idlist = get_id_list(testlist)
  562. if (has_blank_ids(idlist)):
  563. for k in testlist:
  564. k['filename'] = filename
  565. return testlist
  566. def identity(string):
  567. return string
  568. def args_parse():
  569. """
  570. Create the argument parser.
  571. """
  572. parser = argparse.ArgumentParser(description='Linux TC unit tests')
  573. parser.register('type', None, identity)
  574. return parser
  575. def set_args(parser):
  576. """
  577. Set the command line arguments for tdc.
  578. """
  579. parser.add_argument(
  580. '--outfile', type=str,
  581. help='Path to the file in which results should be saved. ' +
  582. 'Default target is the current directory.')
  583. parser.add_argument(
  584. '-p', '--path', type=str,
  585. help='The full path to the tc executable to use')
  586. sg = parser.add_argument_group(
  587. 'selection', 'select which test cases: ' +
  588. 'files plus directories; filtered by categories plus testids')
  589. ag = parser.add_argument_group(
  590. 'action', 'select action to perform on selected test cases')
  591. sg.add_argument(
  592. '-D', '--directory', nargs='+', metavar='DIR',
  593. help='Collect tests from the specified directory(ies) ' +
  594. '(default [tc-tests])')
  595. sg.add_argument(
  596. '-f', '--file', nargs='+', metavar='FILE',
  597. help='Run tests from the specified file(s)')
  598. sg.add_argument(
  599. '-c', '--category', nargs='*', metavar='CATG', default=['+c'],
  600. help='Run tests only from the specified category/ies, ' +
  601. 'or if no category/ies is/are specified, list known categories.')
  602. sg.add_argument(
  603. '-e', '--execute', nargs='+', metavar='ID',
  604. help='Execute the specified test cases with specified IDs')
  605. ag.add_argument(
  606. '-l', '--list', action='store_true',
  607. help='List all test cases, or those only within the specified category')
  608. ag.add_argument(
  609. '-s', '--show', action='store_true', dest='showID',
  610. help='Display the selected test cases')
  611. ag.add_argument(
  612. '-i', '--id', action='store_true', dest='gen_id',
  613. help='Generate ID numbers for new test cases')
  614. parser.add_argument(
  615. '-v', '--verbose', action='count', default=0,
  616. help='Show the commands that are being run')
  617. parser.add_argument(
  618. '--format', default='tap', const='tap', nargs='?',
  619. choices=['none', 'xunit', 'tap'],
  620. help='Specify the format for test results. (Default: TAP)')
  621. parser.add_argument('-d', '--device',
  622. help='Execute test cases that use a physical device, ' +
  623. 'where DEVICE is its name. (If not defined, tests ' +
  624. 'that require a physical device will be skipped)')
  625. parser.add_argument(
  626. '-P', '--pause', action='store_true',
  627. help='Pause execution just before post-suite stage')
  628. parser.add_argument(
  629. '-J', '--multiprocess', type=int, default=1, dest='mp',
  630. help='Run tests in parallel whenever possible')
  631. return parser
  632. def check_default_settings(args, remaining, pm):
  633. """
  634. Process any arguments overriding the default settings,
  635. and ensure the settings are correct.
  636. """
  637. # Allow for overriding specific settings
  638. global NAMES
  639. if args.path != None:
  640. NAMES['TC'] = args.path
  641. if args.device != None:
  642. NAMES['DEV2'] = args.device
  643. if 'TIMEOUT' not in NAMES:
  644. NAMES['TIMEOUT'] = None
  645. if not os.path.isfile(NAMES['TC']):
  646. print("The specified tc path " + NAMES['TC'] + " does not exist.")
  647. exit(1)
  648. pm.call_check_args(args, remaining)
  649. def get_id_list(alltests):
  650. """
  651. Generate a list of all IDs in the test cases.
  652. """
  653. return [x["id"] for x in alltests]
  654. def check_case_id(alltests):
  655. """
  656. Check for duplicate test case IDs.
  657. """
  658. idl = get_id_list(alltests)
  659. return [x for x in idl if idl.count(x) > 1]
  660. def does_id_exist(alltests, newid):
  661. """
  662. Check if a given ID already exists in the list of test cases.
  663. """
  664. idl = get_id_list(alltests)
  665. return (any(newid == x for x in idl))
  666. def generate_case_ids(alltests):
  667. """
  668. If a test case has a blank ID field, generate a random hex ID for it
  669. and then write the test cases back to disk.
  670. """
  671. for c in alltests:
  672. if (c["id"] == ""):
  673. while True:
  674. newid = str('{:04x}'.format(random.randrange(16**4)))
  675. if (does_id_exist(alltests, newid)):
  676. continue
  677. else:
  678. c['id'] = newid
  679. break
  680. ufilename = []
  681. for c in alltests:
  682. if ('filename' in c):
  683. ufilename.append(c['filename'])
  684. ufilename = get_unique_item(ufilename)
  685. for f in ufilename:
  686. testlist = []
  687. for t in alltests:
  688. if 'filename' in t:
  689. if t['filename'] == f:
  690. del t['filename']
  691. testlist.append(t)
  692. outfile = open(f, "w")
  693. json.dump(testlist, outfile, indent=4)
  694. outfile.write("\n")
  695. outfile.close()
  696. def filter_tests_by_id(args, testlist):
  697. '''
  698. Remove tests from testlist that are not in the named id list.
  699. If id list is empty, return empty list.
  700. '''
  701. newlist = list()
  702. if testlist and args.execute:
  703. target_ids = args.execute
  704. if isinstance(target_ids, list) and (len(target_ids) > 0):
  705. newlist = list(filter(lambda x: x['id'] in target_ids, testlist))
  706. return newlist
  707. def filter_tests_by_category(args, testlist):
  708. '''
  709. Remove tests from testlist that are not in a named category.
  710. '''
  711. answer = list()
  712. if args.category and testlist:
  713. test_ids = list()
  714. for catg in set(args.category):
  715. if catg == '+c':
  716. continue
  717. print('considering category {}'.format(catg))
  718. for tc in testlist:
  719. if catg in tc['category'] and tc['id'] not in test_ids:
  720. answer.append(tc)
  721. test_ids.append(tc['id'])
  722. return answer
  723. def set_random(alltests):
  724. for tidx in alltests:
  725. tidx['random'] = random.getrandbits(32)
  726. def get_test_cases(args):
  727. """
  728. If a test case file is specified, retrieve tests from that file.
  729. Otherwise, glob for all json files in subdirectories and load from
  730. each one.
  731. Also, if requested, filter by category, and add tests matching
  732. certain ids.
  733. """
  734. import fnmatch
  735. flist = []
  736. testdirs = ['tc-tests']
  737. if args.file:
  738. # at least one file was specified - remove the default directory
  739. testdirs = []
  740. for ff in args.file:
  741. if not os.path.isfile(ff):
  742. print("IGNORING file " + ff + "\n\tBECAUSE does not exist.")
  743. else:
  744. flist.append(os.path.abspath(ff))
  745. if args.directory:
  746. testdirs = args.directory
  747. for testdir in testdirs:
  748. for root, dirnames, filenames in os.walk(testdir):
  749. for filename in fnmatch.filter(filenames, '*.json'):
  750. candidate = os.path.abspath(os.path.join(root, filename))
  751. if candidate not in testdirs:
  752. flist.append(candidate)
  753. alltestcases = list()
  754. for casefile in flist:
  755. alltestcases = alltestcases + (load_from_file(casefile))
  756. allcatlist = get_test_categories(alltestcases)
  757. allidlist = get_id_list(alltestcases)
  758. testcases_by_cats = get_categorized_testlist(alltestcases, allcatlist)
  759. idtestcases = filter_tests_by_id(args, alltestcases)
  760. cattestcases = filter_tests_by_category(args, alltestcases)
  761. cat_ids = [x['id'] for x in cattestcases]
  762. if args.execute:
  763. if args.category:
  764. alltestcases = cattestcases + [x for x in idtestcases if x['id'] not in cat_ids]
  765. else:
  766. alltestcases = idtestcases
  767. else:
  768. if cat_ids:
  769. alltestcases = cattestcases
  770. else:
  771. # just accept the existing value of alltestcases,
  772. # which has been filtered by file/directory
  773. pass
  774. return allcatlist, allidlist, testcases_by_cats, alltestcases
  775. def set_operation_mode(pm, parser, args, remaining):
  776. """
  777. Load the test case data and process remaining arguments to determine
  778. what the script should do for this run, and call the appropriate
  779. function.
  780. """
  781. ucat, idlist, testcases, alltests = get_test_cases(args)
  782. if args.gen_id:
  783. if (has_blank_ids(idlist)):
  784. alltests = generate_case_ids(alltests)
  785. else:
  786. print("No empty ID fields found in test files.")
  787. exit(0)
  788. duplicate_ids = check_case_id(alltests)
  789. if (len(duplicate_ids) > 0):
  790. print("The following test case IDs are not unique:")
  791. print(str(set(duplicate_ids)))
  792. print("Please correct them before continuing.")
  793. exit(1)
  794. if args.showID:
  795. for atest in alltests:
  796. print_test_case(atest)
  797. exit(0)
  798. if isinstance(args.category, list) and (len(args.category) == 0):
  799. print("Available categories:")
  800. print_sll(ucat)
  801. exit(0)
  802. if args.list:
  803. list_test_cases(alltests)
  804. exit(0)
  805. set_random(alltests)
  806. exit_code = 0 # KSFT_PASS
  807. if len(alltests):
  808. req_plugins = pm.get_required_plugins(alltests)
  809. try:
  810. args = pm.load_required_plugins(req_plugins, parser, args, remaining)
  811. except PluginDependencyException as pde:
  812. print('The following plugins were not found:')
  813. print('{}'.format(pde.missing_pg))
  814. if args.mp > 1:
  815. catresults = test_runner_mp(pm, args, alltests)
  816. else:
  817. catresults = test_runner_serial(pm, args, alltests)
  818. if catresults.count_failures() != 0:
  819. exit_code = 1 # KSFT_FAIL
  820. if args.format == 'none':
  821. print('Test results output suppression requested\n')
  822. else:
  823. print('\nAll test results: \n')
  824. if args.format == 'xunit':
  825. suffix = 'xml'
  826. res = catresults.format_xunit()
  827. elif args.format == 'tap':
  828. suffix = 'tap'
  829. res = catresults.format_tap()
  830. print(res)
  831. print('\n\n')
  832. if not args.outfile:
  833. fname = 'test-results.{}'.format(suffix)
  834. else:
  835. fname = args.outfile
  836. with open(fname, 'w') as fh:
  837. fh.write(res)
  838. fh.close()
  839. if os.getenv('SUDO_UID') is not None:
  840. os.chown(fname, uid=int(os.getenv('SUDO_UID')),
  841. gid=int(os.getenv('SUDO_GID')))
  842. else:
  843. print('No tests found\n')
  844. exit_code = 4 # KSFT_SKIP
  845. exit(exit_code)
  846. def main():
  847. """
  848. Start of execution; set up argument parser and get the arguments,
  849. and start operations.
  850. """
  851. import resource
  852. if sys.version_info.major < 3 or sys.version_info.minor < 8:
  853. sys.exit("tdc requires at least python 3.8")
  854. resource.setrlimit(resource.RLIMIT_NOFILE, (1048576, 1048576))
  855. parser = args_parse()
  856. parser = set_args(parser)
  857. pm = PluginMgr(parser)
  858. parser = pm.call_add_args(parser)
  859. (args, remaining) = parser.parse_known_args()
  860. args.NAMES = NAMES
  861. args.mp = min(args.mp, 4)
  862. pm.set_args(args)
  863. check_default_settings(args, remaining, pm)
  864. if args.verbose > 2:
  865. print('args is {}'.format(args))
  866. try:
  867. set_operation_mode(pm, parser, args, remaining)
  868. except KeyboardInterrupt:
  869. # Cleanup on Ctrl-C
  870. pm.call_post_suite(None)
  871. if __name__ == "__main__":
  872. main()