run-tests.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #!/usr/bin/env python2
  2. #
  3. # Remote test case executor
  4. # Copyright (c) 2016, Tieto Corporation
  5. #
  6. # This software may be distributed under the terms of the BSD license.
  7. # See README for more details.
  8. import os
  9. import re
  10. import sys
  11. import time
  12. import traceback
  13. import getopt
  14. from datetime import datetime
  15. import logging
  16. logger = logging.getLogger()
  17. scriptsdir = os.path.dirname(os.path.realpath(sys.modules[__name__].__file__))
  18. sys.path.append(os.path.join(scriptsdir, '..', '..', 'wpaspy'))
  19. sys.path.append(os.path.join(scriptsdir, '..', 'hwsim'))
  20. import wpaspy
  21. import config
  22. from test_devices import show_devices
  23. from test_devices import check_devices
  24. from rutils import TestSkip
  25. def usage():
  26. print "USAGE: " + sys.argv[0] + " -t devices"
  27. print "USAGE: " + sys.argv[0] + " -t check_devices"
  28. print "USAGE: " + sys.argv[0] + " -d <dut_name> -t <all|sanity|tests_to_run> [-r <ref_name>] [-c <cfg_file.py>] [-m <all|monitor_name>] [-R][-T][-P][-v]"
  29. print "USAGE: " + sys.argv[0]
  30. def get_devices(devices, duts, refs, monitors):
  31. for dut in duts:
  32. config.get_device(devices, dut, lock=True)
  33. for ref in refs:
  34. config.get_device(devices, ref, lock=True)
  35. for monitor in monitors:
  36. if monitor == "all":
  37. continue
  38. if monitor in duts:
  39. continue
  40. if monitor in refs:
  41. continue
  42. config.get_device(devices, monitor, lock=True)
  43. def put_devices(devices, duts, refs, monitors):
  44. for dut in duts:
  45. config.put_device(devices, dut)
  46. for ref in refs:
  47. config.put_device(devices, ref)
  48. for monitor in monitors:
  49. if monitor == "all":
  50. continue
  51. if monitor in duts:
  52. continue
  53. if monitor in refs:
  54. continue
  55. config.put_device(devices, monitor)
  56. def main():
  57. duts = []
  58. refs = []
  59. monitors = []
  60. filter_keys = []
  61. requested_tests = ["help"]
  62. cfg_file = "cfg.py"
  63. log_dir = "./logs/"
  64. verbose = False
  65. trace = False
  66. restart = False
  67. perf = False
  68. # parse input parameters
  69. try:
  70. opts, args = getopt.getopt(sys.argv[1:], "d:r:t:l:k:c:m:vRPT",
  71. ["dut=", "ref=", "tests=", "log-dir=",
  72. "cfg=", "key=", "monitor="])
  73. except getopt.GetoptError as err:
  74. print(err)
  75. usage()
  76. sys.exit(2)
  77. for option, argument in opts:
  78. if option == "-v":
  79. verbose = True
  80. elif option == "-R":
  81. restart = True
  82. elif option == "-T":
  83. trace = True
  84. elif option == "-P":
  85. perf = True
  86. elif option in ("-d", "--dut"):
  87. duts.append(argument)
  88. elif option in ("-r", "--ref"):
  89. refs.append(argument)
  90. elif option in ("-t", "--tests"):
  91. requested_tests = re.split('; | |, ', argument)
  92. elif option in ("-l", "--log-dir"):
  93. log_dir = argument
  94. elif option in ("-k", "--key"):
  95. filter_keys.append(argument)
  96. elif option in ("-m", "--monitor"):
  97. monitors.append(argument)
  98. elif option in ("-c", "--cfg"):
  99. cfg_file = argument
  100. else:
  101. assert False, "unhandled option"
  102. # get env configuration
  103. setup_params = config.get_setup_params(cfg_file)
  104. devices = config.get_devices(cfg_file)
  105. # put logs in log_dir
  106. symlink = os.path.join(log_dir, "current");
  107. if os.path.exists(symlink):
  108. os.unlink(symlink)
  109. log_dir = os.path.join(log_dir, time.strftime("%Y_%m_%d_%H_%M_%S"))
  110. if not os.path.exists(log_dir):
  111. os.makedirs(log_dir)
  112. os.symlink(os.path.join("../", log_dir), symlink)
  113. # setup restart/trace/perf request
  114. setup_params['local_log_dir'] = log_dir
  115. setup_params['restart_device'] = restart
  116. setup_params['trace'] = trace
  117. setup_params['perf'] = perf
  118. # configure logger
  119. logger.setLevel(logging.DEBUG)
  120. stdout_handler = logging.StreamHandler()
  121. stdout_handler.setLevel(logging.WARNING)
  122. if verbose:
  123. stdout_handler.setLevel(logging.DEBUG)
  124. logger.addHandler(stdout_handler)
  125. formatter = logging.Formatter('%(asctime)s - %(message)s')
  126. file_name = os.path.join(log_dir, 'run-tests.log')
  127. log_handler = logging.FileHandler(file_name)
  128. log_handler.setLevel(logging.DEBUG)
  129. log_handler.setFormatter(formatter)
  130. logger.addHandler(log_handler)
  131. # import available tests
  132. tests = []
  133. failed = []
  134. test_modules = []
  135. files = os.listdir(scriptsdir)
  136. for t in files:
  137. m = re.match(r'(test_.*)\.py$', t)
  138. if m:
  139. mod = __import__(m.group(1))
  140. test_modules.append(mod.__name__.replace('test_', '', 1))
  141. for key,val in mod.__dict__.iteritems():
  142. if key.startswith("test_"):
  143. tests.append(val)
  144. test_names = list(set([t.__name__.replace('test_', '', 1) for t in tests]))
  145. # sort the list
  146. test_names.sort()
  147. tests.sort()
  148. # print help
  149. if requested_tests[0] == "help":
  150. usage()
  151. print "\nAvailable Devices:"
  152. for device in devices:
  153. print "\t", device['name']
  154. print "\nAvailable tests:"
  155. for test in test_names:
  156. print "\t", test
  157. return
  158. # show/check devices
  159. if requested_tests[0] == "devices":
  160. show_devices(devices, setup_params)
  161. return
  162. # apply filters
  163. for filter_key in filter_keys:
  164. filtered_tests = []
  165. for test in tests:
  166. if re.search(filter_key, test.__name__):
  167. filtered_tests.append(test)
  168. tests = filtered_tests
  169. # setup test we should run
  170. tests_to_run = []
  171. if requested_tests[0] == "all":
  172. tests_to_run = tests
  173. elif requested_tests[0] == "sanity":
  174. for test in tests:
  175. if test.__name__.startswith("test_sanity_"):
  176. tests_to_run.append(test)
  177. else:
  178. for test in requested_tests:
  179. t = None
  180. for tt in tests:
  181. name = tt.__name__.replace('test_', '', 1)
  182. if name == test:
  183. t = tt
  184. break
  185. if not t:
  186. logger.warning("test case: " + test + " NOT-FOUND")
  187. continue
  188. tests_to_run.append(t)
  189. # lock devices
  190. try:
  191. get_devices(devices, duts, refs, monitors)
  192. except Exception, e:
  193. logger.warning("get devices failed: " + str(e))
  194. logger.info(traceback.format_exc())
  195. put_devices(devices, duts, refs, monitors)
  196. return
  197. except:
  198. logger.warning("get devices failed")
  199. logger.info(traceback.format_exc())
  200. put_devices(devices, duts, refs, monitors)
  201. return
  202. # now run test cases
  203. for dut in duts:
  204. logger.warning("DUT: " + str(dut))
  205. for ref in refs:
  206. logger.warning("REF: " + str(ref))
  207. for monitor in monitors:
  208. logger.warning("MON: " + str(monitor))
  209. # run check_devices at begining
  210. logger.warning("RUN check_devices")
  211. try:
  212. check_devices(devices, setup_params, refs, duts, monitors)
  213. except Exception, e:
  214. logger.warning("FAILED: " + str(e))
  215. logger.info(traceback.format_exc())
  216. put_devices(devices, duts, refs, monitors)
  217. return
  218. except:
  219. logger.warning("FAILED")
  220. logger.info(traceback.format_exc())
  221. put_devices(devices, duts, refs, monitors)
  222. return
  223. logger.warning("PASS")
  224. test_no = 1
  225. for test in tests_to_run:
  226. try:
  227. start = datetime.now()
  228. setup_params['tc_name'] = test.__name__.replace('test_', '', 1)
  229. logger.warning("START - " + setup_params['tc_name'] + " (" + str(test_no) + "/" + str(len(tests_to_run)) + ")")
  230. if test.__doc__:
  231. logger.info("Test: " + test.__doc__)
  232. # run tc
  233. res = test(devices, setup_params, refs, duts, monitors)
  234. end = datetime.now()
  235. logger.warning("PASS (" + res + ") - " + str((end - start).total_seconds()) + "s")
  236. except KeyboardInterrupt:
  237. put_devices(devices, duts, refs, monitors)
  238. raise
  239. except TestSkip, e:
  240. end = datetime.now()
  241. logger.warning("SKIP (" + str(e) + ") - " + str((end - start).total_seconds()) + "s")
  242. except Exception, e:
  243. end = datetime.now()
  244. logger.warning("FAILED (" + str(e) + ") - " + str((end - start).total_seconds()) + "s")
  245. logger.info(traceback.format_exc())
  246. failed.append(test.__name__.replace('test_', '', 1))
  247. except:
  248. end = datetime.now()
  249. logger.warning("FAILED - " + str((end - start).total_seconds()) + "s")
  250. logger.info(traceback.format_exc())
  251. failed.append(test.__name__.replace('test_', '', 1))
  252. test_no += 1
  253. # unlock devices
  254. put_devices(devices, duts, refs, monitors)
  255. if len(failed) > 0:
  256. logger.warning("Failed test cases:")
  257. for test in failed:
  258. logger.warning("\t" + test)
  259. if __name__ == "__main__":
  260. main()