tdc.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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):
  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. print("Test " + tidx["id"] + ": " + tidx["name"])
  86. prepare_env(tidx["setup"])
  87. (p, procout) = exec_cmd(tidx["cmdUnderTest"])
  88. exit_code = p.returncode
  89. if (exit_code != int(tidx["expExitCode"])):
  90. result = False
  91. print("exit:", exit_code, int(tidx["expExitCode"]))
  92. print(procout)
  93. else:
  94. match_pattern = re.compile(str(tidx["matchPattern"]), re.DOTALL)
  95. (p, procout) = exec_cmd(tidx["verifyCmd"])
  96. match_index = re.findall(match_pattern, procout)
  97. if len(match_index) != int(tidx["matchCount"]):
  98. result = False
  99. if result == True:
  100. tresult += "ok "
  101. else:
  102. tresult += "not ok "
  103. tap += tresult + str(index) + " " + tidx["id"] + " " + tidx["name"] + "\n"
  104. if result == False:
  105. tap += procout
  106. prepare_env(tidx["teardown"])
  107. index += 1
  108. return tap
  109. def ns_create():
  110. """
  111. Create the network namespace in which the tests will be run and set up
  112. the required network devices for it.
  113. """
  114. if (USE_NS):
  115. cmd = 'ip netns add $NS'
  116. exec_cmd(cmd, False)
  117. cmd = 'ip link add $DEV0 type veth peer name $DEV1'
  118. exec_cmd(cmd, False)
  119. cmd = 'ip link set $DEV1 netns $NS'
  120. exec_cmd(cmd, False)
  121. cmd = 'ip link set $DEV0 up'
  122. exec_cmd(cmd, False)
  123. cmd = 'ip -s $NS link set $DEV1 up'
  124. exec_cmd(cmd, False)
  125. def ns_destroy():
  126. """
  127. Destroy the network namespace for testing (and any associated network
  128. devices as well)
  129. """
  130. if (USE_NS):
  131. cmd = 'ip netns delete $NS'
  132. exec_cmd(cmd, False)
  133. def has_blank_ids(idlist):
  134. """
  135. Search the list for empty ID fields and return true/false accordingly.
  136. """
  137. return not(all(k for k in idlist))
  138. def load_from_file(filename):
  139. """
  140. Open the JSON file containing the test cases and return them as an
  141. ordered dictionary object.
  142. """
  143. with open(filename) as test_data:
  144. testlist = json.load(test_data, object_pairs_hook=OrderedDict)
  145. idlist = get_id_list(testlist)
  146. if (has_blank_ids(idlist)):
  147. for k in testlist:
  148. k['filename'] = filename
  149. return testlist
  150. def args_parse():
  151. """
  152. Create the argument parser.
  153. """
  154. parser = argparse.ArgumentParser(description='Linux TC unit tests')
  155. return parser
  156. def set_args(parser):
  157. """
  158. Set the command line arguments for tdc.
  159. """
  160. parser.add_argument('-p', '--path', type=str,
  161. help='The full path to the tc executable to use')
  162. parser.add_argument('-c', '--category', type=str, nargs='?', const='+c',
  163. help='Run tests only from the specified category, or if no category is specified, list known categories.')
  164. parser.add_argument('-f', '--file', type=str,
  165. help='Run tests from the specified file')
  166. parser.add_argument('-l', '--list', type=str, nargs='?', const="", metavar='CATEGORY',
  167. help='List all test cases, or those only within the specified category')
  168. parser.add_argument('-s', '--show', type=str, nargs=1, metavar='ID', dest='showID',
  169. help='Display the test case with specified id')
  170. parser.add_argument('-e', '--execute', type=str, nargs=1, metavar='ID',
  171. help='Execute the single test case with specified ID')
  172. parser.add_argument('-i', '--id', action='store_true', dest='gen_id',
  173. help='Generate ID numbers for new test cases')
  174. return parser
  175. return parser
  176. def check_default_settings(args):
  177. """
  178. Process any arguments overriding the default settings, and ensure the
  179. settings are correct.
  180. """
  181. # Allow for overriding specific settings
  182. global NAMES
  183. if args.path != None:
  184. NAMES['TC'] = args.path
  185. if not os.path.isfile(NAMES['TC']):
  186. print("The specified tc path " + NAMES['TC'] + " does not exist.")
  187. exit(1)
  188. def get_id_list(alltests):
  189. """
  190. Generate a list of all IDs in the test cases.
  191. """
  192. return [x["id"] for x in alltests]
  193. def check_case_id(alltests):
  194. """
  195. Check for duplicate test case IDs.
  196. """
  197. idl = get_id_list(alltests)
  198. return [x for x in idl if idl.count(x) > 1]
  199. def does_id_exist(alltests, newid):
  200. """
  201. Check if a given ID already exists in the list of test cases.
  202. """
  203. idl = get_id_list(alltests)
  204. return (any(newid == x for x in idl))
  205. def generate_case_ids(alltests):
  206. """
  207. If a test case has a blank ID field, generate a random hex ID for it
  208. and then write the test cases back to disk.
  209. """
  210. import random
  211. for c in alltests:
  212. if (c["id"] == ""):
  213. while True:
  214. newid = str('%04x' % random.randrange(16**4))
  215. if (does_id_exist(alltests, newid)):
  216. continue
  217. else:
  218. c['id'] = newid
  219. break
  220. ufilename = []
  221. for c in alltests:
  222. if ('filename' in c):
  223. ufilename.append(c['filename'])
  224. ufilename = get_unique_item(ufilename)
  225. for f in ufilename:
  226. testlist = []
  227. for t in alltests:
  228. if 'filename' in t:
  229. if t['filename'] == f:
  230. del t['filename']
  231. testlist.append(t)
  232. outfile = open(f, "w")
  233. json.dump(testlist, outfile, indent=4)
  234. outfile.close()
  235. def get_test_cases(args):
  236. """
  237. If a test case file is specified, retrieve tests from that file.
  238. Otherwise, glob for all json files in subdirectories and load from
  239. each one.
  240. """
  241. import fnmatch
  242. if args.file != None:
  243. if not os.path.isfile(args.file):
  244. print("The specified test case file " + args.file + " does not exist.")
  245. exit(1)
  246. flist = [args.file]
  247. else:
  248. flist = []
  249. for root, dirnames, filenames in os.walk('tc-tests'):
  250. for filename in fnmatch.filter(filenames, '*.json'):
  251. flist.append(os.path.join(root, filename))
  252. alltests = list()
  253. for casefile in flist:
  254. alltests = alltests + (load_from_file(casefile))
  255. return alltests
  256. def set_operation_mode(args):
  257. """
  258. Load the test case data and process remaining arguments to determine
  259. what the script should do for this run, and call the appropriate
  260. function.
  261. """
  262. alltests = get_test_cases(args)
  263. if args.gen_id:
  264. idlist = get_id_list(alltests)
  265. if (has_blank_ids(idlist)):
  266. alltests = generate_case_ids(alltests)
  267. else:
  268. print("No empty ID fields found in test files.")
  269. exit(0)
  270. duplicate_ids = check_case_id(alltests)
  271. if (len(duplicate_ids) > 0):
  272. print("The following test case IDs are not unique:")
  273. print(str(set(duplicate_ids)))
  274. print("Please correct them before continuing.")
  275. exit(1)
  276. ucat = get_test_categories(alltests)
  277. if args.showID:
  278. show_test_case_by_id(alltests, args.showID[0])
  279. exit(0)
  280. if args.execute:
  281. target_id = args.execute[0]
  282. else:
  283. target_id = ""
  284. if args.category:
  285. if (args.category == '+c'):
  286. print("Available categories:")
  287. print_sll(ucat)
  288. exit(0)
  289. else:
  290. target_category = args.category
  291. else:
  292. target_category = ""
  293. testcases = get_categorized_testlist(alltests, ucat)
  294. if args.list:
  295. if (len(args.list) == 0):
  296. list_test_cases(alltests)
  297. exit(0)
  298. elif(len(args.list > 0)):
  299. if (args.list not in ucat):
  300. print("Unknown category " + args.list)
  301. print("Available categories:")
  302. print_sll(ucat)
  303. exit(1)
  304. list_test_cases(testcases[args.list])
  305. exit(0)
  306. if (os.geteuid() != 0):
  307. print("This script must be run with root privileges.\n")
  308. exit(1)
  309. ns_create()
  310. if (len(target_category) == 0):
  311. if (len(target_id) > 0):
  312. alltests = list(filter(lambda x: target_id in x['id'], alltests))
  313. if (len(alltests) == 0):
  314. print("Cannot find a test case with ID matching " + target_id)
  315. exit(1)
  316. catresults = test_runner(alltests)
  317. print("All test results: " + "\n\n" + catresults)
  318. elif (len(target_category) > 0):
  319. if (target_category not in ucat):
  320. print("Specified category is not present in this file.")
  321. exit(1)
  322. else:
  323. catresults = test_runner(testcases[target_category])
  324. print("Category " + target_category + "\n\n" + catresults)
  325. ns_destroy()
  326. def main():
  327. """
  328. Start of execution; set up argument parser and get the arguments,
  329. and start operations.
  330. """
  331. parser = args_parse()
  332. parser = set_args(parser)
  333. (args, remaining) = parser.parse_known_args()
  334. check_default_settings(args)
  335. set_operation_mode(args)
  336. exit(0)
  337. if __name__ == "__main__":
  338. main()