tdc.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #!/usr/bin/env python3
  2. """
  3. tdc.py - Linux tc (Traffic Control) unit test driver
  4. Copyright (C) 2017 Lucas Bates <lucasb@mojatatu.com>
  5. """
  6. import re
  7. import os
  8. import sys
  9. import argparse
  10. import json
  11. import subprocess
  12. from collections import OrderedDict
  13. from string import Template
  14. from tdc_config import *
  15. from tdc_helper import *
  16. USE_NS = True
  17. def replace_keywords(cmd):
  18. """
  19. For a given executable command, substitute any known
  20. variables contained within NAMES with the correct values
  21. """
  22. tcmd = Template(cmd)
  23. subcmd = tcmd.safe_substitute(NAMES)
  24. return subcmd
  25. def exec_cmd(command, nsonly=True):
  26. """
  27. Perform any required modifications on an executable command, then run
  28. it in a subprocess and return the results.
  29. """
  30. if (USE_NS and nsonly):
  31. command = 'ip netns exec $NS ' + command
  32. if '$' in command:
  33. command = replace_keywords(command)
  34. proc = subprocess.Popen(command,
  35. shell=True,
  36. stdout=subprocess.PIPE,
  37. stderr=subprocess.PIPE)
  38. (rawout, serr) = proc.communicate()
  39. if proc.returncode != 0:
  40. foutput = serr.decode("utf-8")
  41. else:
  42. foutput = rawout.decode("utf-8")
  43. proc.stdout.close()
  44. proc.stderr.close()
  45. return proc, foutput
  46. def prepare_env(cmdlist):
  47. """
  48. Execute the setup/teardown commands for a test case. Optionally
  49. terminate test execution if the command fails.
  50. """
  51. for cmdinfo in cmdlist:
  52. if (type(cmdinfo) == list):
  53. exit_codes = cmdinfo[1:]
  54. cmd = cmdinfo[0]
  55. else:
  56. exit_codes = [0]
  57. cmd = cmdinfo
  58. if (len(cmd) == 0):
  59. continue
  60. (proc, foutput) = exec_cmd(cmd)
  61. if proc.returncode not in exit_codes:
  62. print
  63. print("Could not execute:")
  64. print(cmd)
  65. print("\nError message:")
  66. print(foutput)
  67. print("\nAborting test run.")
  68. ns_destroy()
  69. exit(1)
  70. def test_runner(filtered_tests, args):
  71. """
  72. Driver function for the unit tests.
  73. Prints information about the tests being run, executes the setup and
  74. teardown commands and the command under test itself. Also determines
  75. success/failure based on the information in the test case and generates
  76. TAP output accordingly.
  77. """
  78. testlist = filtered_tests
  79. tcount = len(testlist)
  80. index = 1
  81. tap = str(index) + ".." + str(tcount) + "\n"
  82. for tidx in testlist:
  83. result = True
  84. tresult = ""
  85. if "flower" in tidx["category"] and args.device == None:
  86. continue
  87. print("Test " + tidx["id"] + ": " + tidx["name"])
  88. prepare_env(tidx["setup"])
  89. (p, procout) = exec_cmd(tidx["cmdUnderTest"])
  90. exit_code = p.returncode
  91. if (exit_code != int(tidx["expExitCode"])):
  92. result = False
  93. print("exit:", exit_code, int(tidx["expExitCode"]))
  94. print(procout)
  95. else:
  96. match_pattern = re.compile(str(tidx["matchPattern"]), re.DOTALL)
  97. (p, procout) = exec_cmd(tidx["verifyCmd"])
  98. match_index = re.findall(match_pattern, procout)
  99. if len(match_index) != int(tidx["matchCount"]):
  100. result = False
  101. if result == True:
  102. tresult += "ok "
  103. else:
  104. tresult += "not ok "
  105. tap += tresult + str(index) + " " + tidx["id"] + " " + tidx["name"] + "\n"
  106. if result == False:
  107. tap += procout
  108. prepare_env(tidx["teardown"])
  109. index += 1
  110. return tap
  111. def ns_create():
  112. """
  113. Create the network namespace in which the tests will be run and set up
  114. the required network devices for it.
  115. """
  116. if (USE_NS):
  117. cmd = 'ip netns add $NS'
  118. exec_cmd(cmd, False)
  119. cmd = 'ip link add $DEV0 type veth peer name $DEV1'
  120. exec_cmd(cmd, False)
  121. cmd = 'ip link set $DEV1 netns $NS'
  122. exec_cmd(cmd, False)
  123. cmd = 'ip link set $DEV0 up'
  124. exec_cmd(cmd, False)
  125. cmd = 'ip -s $NS link set $DEV1 up'
  126. exec_cmd(cmd, False)
  127. cmd = 'ip link set $DEV2 netns $NS'
  128. exec_cmd(cmd, False)
  129. cmd = 'ip -s $NS link set $DEV2 up'
  130. exec_cmd(cmd, False)
  131. def ns_destroy():
  132. """
  133. Destroy the network namespace for testing (and any associated network
  134. devices as well)
  135. """
  136. if (USE_NS):
  137. cmd = 'ip netns delete $NS'
  138. exec_cmd(cmd, False)
  139. def has_blank_ids(idlist):
  140. """
  141. Search the list for empty ID fields and return true/false accordingly.
  142. """
  143. return not(all(k for k in idlist))
  144. def load_from_file(filename):
  145. """
  146. Open the JSON file containing the test cases and return them as an
  147. ordered dictionary object.
  148. """
  149. with open(filename) as test_data:
  150. testlist = json.load(test_data, object_pairs_hook=OrderedDict)
  151. idlist = get_id_list(testlist)
  152. if (has_blank_ids(idlist)):
  153. for k in testlist:
  154. k['filename'] = filename
  155. return testlist
  156. def args_parse():
  157. """
  158. Create the argument parser.
  159. """
  160. parser = argparse.ArgumentParser(description='Linux TC unit tests')
  161. return parser
  162. def set_args(parser):
  163. """
  164. Set the command line arguments for tdc.
  165. """
  166. parser.add_argument('-p', '--path', type=str,
  167. help='The full path to the tc executable to use')
  168. parser.add_argument('-c', '--category', type=str, nargs='?', const='+c',
  169. help='Run tests only from the specified category, or if no category is specified, list known categories.')
  170. parser.add_argument('-f', '--file', type=str,
  171. help='Run tests from the specified file')
  172. parser.add_argument('-l', '--list', type=str, nargs='?', const="", metavar='CATEGORY',
  173. help='List all test cases, or those only within the specified category')
  174. parser.add_argument('-s', '--show', type=str, nargs=1, metavar='ID', dest='showID',
  175. help='Display the test case with specified id')
  176. parser.add_argument('-e', '--execute', type=str, nargs=1, metavar='ID',
  177. help='Execute the single test case with specified ID')
  178. parser.add_argument('-i', '--id', action='store_true', dest='gen_id',
  179. help='Generate ID numbers for new test cases')
  180. parser.add_argument('-d', '--device',
  181. help='Execute the test case in flower category')
  182. return parser
  183. def check_default_settings(args):
  184. """
  185. Process any arguments overriding the default settings, and ensure the
  186. settings are correct.
  187. """
  188. # Allow for overriding specific settings
  189. global NAMES
  190. if args.path != None:
  191. NAMES['TC'] = args.path
  192. if args.device != None:
  193. NAMES['DEV2'] = args.device
  194. if not os.path.isfile(NAMES['TC']):
  195. print("The specified tc path " + NAMES['TC'] + " does not exist.")
  196. exit(1)
  197. def get_id_list(alltests):
  198. """
  199. Generate a list of all IDs in the test cases.
  200. """
  201. return [x["id"] for x in alltests]
  202. def check_case_id(alltests):
  203. """
  204. Check for duplicate test case IDs.
  205. """
  206. idl = get_id_list(alltests)
  207. return [x for x in idl if idl.count(x) > 1]
  208. def does_id_exist(alltests, newid):
  209. """
  210. Check if a given ID already exists in the list of test cases.
  211. """
  212. idl = get_id_list(alltests)
  213. return (any(newid == x for x in idl))
  214. def generate_case_ids(alltests):
  215. """
  216. If a test case has a blank ID field, generate a random hex ID for it
  217. and then write the test cases back to disk.
  218. """
  219. import random
  220. for c in alltests:
  221. if (c["id"] == ""):
  222. while True:
  223. newid = str('%04x' % random.randrange(16**4))
  224. if (does_id_exist(alltests, newid)):
  225. continue
  226. else:
  227. c['id'] = newid
  228. break
  229. ufilename = []
  230. for c in alltests:
  231. if ('filename' in c):
  232. ufilename.append(c['filename'])
  233. ufilename = get_unique_item(ufilename)
  234. for f in ufilename:
  235. testlist = []
  236. for t in alltests:
  237. if 'filename' in t:
  238. if t['filename'] == f:
  239. del t['filename']
  240. testlist.append(t)
  241. outfile = open(f, "w")
  242. json.dump(testlist, outfile, indent=4)
  243. outfile.close()
  244. def get_test_cases(args):
  245. """
  246. If a test case file is specified, retrieve tests from that file.
  247. Otherwise, glob for all json files in subdirectories and load from
  248. each one.
  249. """
  250. import fnmatch
  251. if args.file != None:
  252. if not os.path.isfile(args.file):
  253. print("The specified test case file " + args.file + " does not exist.")
  254. exit(1)
  255. flist = [args.file]
  256. else:
  257. flist = []
  258. for root, dirnames, filenames in os.walk('tc-tests'):
  259. for filename in fnmatch.filter(filenames, '*.json'):
  260. flist.append(os.path.join(root, filename))
  261. alltests = list()
  262. for casefile in flist:
  263. alltests = alltests + (load_from_file(casefile))
  264. return alltests
  265. def set_operation_mode(args):
  266. """
  267. Load the test case data and process remaining arguments to determine
  268. what the script should do for this run, and call the appropriate
  269. function.
  270. """
  271. alltests = get_test_cases(args)
  272. if args.gen_id:
  273. idlist = get_id_list(alltests)
  274. if (has_blank_ids(idlist)):
  275. alltests = generate_case_ids(alltests)
  276. else:
  277. print("No empty ID fields found in test files.")
  278. exit(0)
  279. duplicate_ids = check_case_id(alltests)
  280. if (len(duplicate_ids) > 0):
  281. print("The following test case IDs are not unique:")
  282. print(str(set(duplicate_ids)))
  283. print("Please correct them before continuing.")
  284. exit(1)
  285. ucat = get_test_categories(alltests)
  286. if args.showID:
  287. show_test_case_by_id(alltests, args.showID[0])
  288. exit(0)
  289. if args.execute:
  290. target_id = args.execute[0]
  291. else:
  292. target_id = ""
  293. if args.category:
  294. if (args.category == '+c'):
  295. print("Available categories:")
  296. print_sll(ucat)
  297. exit(0)
  298. else:
  299. target_category = args.category
  300. else:
  301. target_category = ""
  302. testcases = get_categorized_testlist(alltests, ucat)
  303. if args.list:
  304. if (len(args.list) == 0):
  305. list_test_cases(alltests)
  306. exit(0)
  307. elif(len(args.list > 0)):
  308. if (args.list not in ucat):
  309. print("Unknown category " + args.list)
  310. print("Available categories:")
  311. print_sll(ucat)
  312. exit(1)
  313. list_test_cases(testcases[args.list])
  314. exit(0)
  315. if (os.geteuid() != 0):
  316. print("This script must be run with root privileges.\n")
  317. exit(1)
  318. ns_create()
  319. if (len(target_category) == 0):
  320. if (len(target_id) > 0):
  321. alltests = list(filter(lambda x: target_id in x['id'], alltests))
  322. if (len(alltests) == 0):
  323. print("Cannot find a test case with ID matching " + target_id)
  324. exit(1)
  325. catresults = test_runner(alltests, args)
  326. print("All test results: " + "\n\n" + catresults)
  327. elif (len(target_category) > 0):
  328. if (target_category == "flower") and args.device == None:
  329. print("Please specify a NIC device (-d) to run category flower")
  330. exit(1)
  331. if (target_category not in ucat):
  332. print("Specified category is not present in this file.")
  333. exit(1)
  334. else:
  335. catresults = test_runner(testcases[target_category], args)
  336. print("Category " + target_category + "\n\n" + catresults)
  337. ns_destroy()
  338. def main():
  339. """
  340. Start of execution; set up argument parser and get the arguments,
  341. and start operations.
  342. """
  343. parser = args_parse()
  344. parser = set_args(parser)
  345. (args, remaining) = parser.parse_known_args()
  346. check_default_settings(args)
  347. set_operation_mode(args)
  348. exit(0)
  349. if __name__ == "__main__":
  350. main()