run-tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. #!/usr/bin/python
  2. #
  3. # AP tests
  4. # Copyright (c) 2013, Jouni Malinen <j@w1.fi>
  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. from datetime import datetime
  13. import argparse
  14. import subprocess
  15. import logging
  16. logger = logging.getLogger()
  17. sys.path.append('../../wpaspy')
  18. from wpasupplicant import WpaSupplicant
  19. from hostapd import HostapdGlobal
  20. from check_kernel import check_kernel
  21. def reset_devs(dev, apdev):
  22. hapd = HostapdGlobal()
  23. for d in dev:
  24. try:
  25. d.reset()
  26. except Exception, e:
  27. logger.info("Failed to reset device " + d.ifname)
  28. print str(e)
  29. hapd.remove('wlan3-3')
  30. hapd.remove('wlan3-2')
  31. for ap in apdev:
  32. hapd.remove(ap['ifname'])
  33. def report(conn, prefill, build, commit, run, test, result, duration):
  34. if conn:
  35. if not build:
  36. build = ''
  37. if not commit:
  38. commit = ''
  39. if prefill:
  40. conn.execute('DELETE FROM results WHERE test=? AND run=? AND result=?', (test, run, 'NOTRUN'))
  41. sql = "INSERT INTO results(test,result,run,time,duration,build,commitid) VALUES(?, ?, ?, ?, ?, ?, ?)"
  42. params = (test, result, run, time.time(), duration, build, commit)
  43. try:
  44. conn.execute(sql, params)
  45. conn.commit()
  46. except Exception, e:
  47. print "sqlite: " + str(e)
  48. print "sql: %r" % (params, )
  49. class DataCollector(object):
  50. def __init__(self, logdir, testname, tracing, dmesg):
  51. self._logdir = logdir
  52. self._testname = testname
  53. self._tracing = tracing
  54. self._dmesg = dmesg
  55. def __enter__(self):
  56. if self._tracing:
  57. output = os.path.join(self._logdir, '%s.dat' % (self._testname, ))
  58. self._trace_cmd = subprocess.Popen(['sudo', 'trace-cmd', 'record', '-o', output, '-e', 'mac80211', '-e', 'cfg80211', 'sh', '-c', 'echo STARTED ; read l'],
  59. stdin=subprocess.PIPE,
  60. stdout=subprocess.PIPE,
  61. stderr=open('/dev/null', 'w'),
  62. cwd=self._logdir)
  63. l = self._trace_cmd.stdout.read(7)
  64. while not 'STARTED' in l:
  65. l += self._trace_cmd.stdout.read(1)
  66. def __exit__(self, type, value, traceback):
  67. if self._tracing:
  68. self._trace_cmd.stdin.write('DONE\n')
  69. self._trace_cmd.wait()
  70. if self._dmesg:
  71. output = os.path.join(self._logdir, '%s.dmesg' % (self._testname, ))
  72. subprocess.call(['sudo', 'dmesg', '-c'], stdout=open(output, 'w'))
  73. def rename_log(logdir, basename, testname, dev):
  74. try:
  75. import getpass
  76. srcname = os.path.join(logdir, basename)
  77. dstname = os.path.join(logdir, testname + '.' + basename)
  78. num = 0
  79. while os.path.exists(dstname):
  80. dstname = os.path.join(logdir,
  81. testname + '.' + basename + '-' + str(num))
  82. num = num + 1
  83. os.rename(srcname, dstname)
  84. dev.relog()
  85. subprocess.call(['sudo', 'chown', '-f', getpass.getuser(), srcname])
  86. except Exception, e:
  87. logger.info("Failed to rename log files")
  88. logger.info(e)
  89. def main():
  90. tests = []
  91. test_modules = []
  92. for t in os.listdir("."):
  93. m = re.match(r'(test_.*)\.py$', t)
  94. if m:
  95. logger.debug("Import test cases from " + t)
  96. mod = __import__(m.group(1))
  97. test_modules.append(mod.__name__.replace('test_', '', 1))
  98. for s in dir(mod):
  99. if s.startswith("test_"):
  100. func = mod.__dict__.get(s)
  101. tests.append(func)
  102. test_names = list(set([t.__name__.replace('test_', '', 1) for t in tests]))
  103. run = None
  104. parser = argparse.ArgumentParser(description='hwsim test runner')
  105. parser.add_argument('--logdir', metavar='<directory>',
  106. help='log output directory for all other options, ' +
  107. 'must be given if other log options are used')
  108. group = parser.add_mutually_exclusive_group()
  109. group.add_argument('-d', const=logging.DEBUG, action='store_const',
  110. dest='loglevel', default=logging.INFO,
  111. help="verbose debug output")
  112. group.add_argument('-q', const=logging.WARNING, action='store_const',
  113. dest='loglevel', help="be quiet")
  114. parser.add_argument('-S', metavar='<sqlite3 db>', dest='database',
  115. help='database to write results to')
  116. parser.add_argument('--prefill-tests', action='store_true', dest='prefill',
  117. help='prefill test database with NOTRUN before all tests')
  118. parser.add_argument('--commit', metavar='<commit id>',
  119. help='commit ID, only for database')
  120. parser.add_argument('-b', metavar='<build>', dest='build', help='build ID')
  121. parser.add_argument('-L', action='store_true', dest='update_tests_db',
  122. help='List tests (and update descriptions in DB)')
  123. parser.add_argument('-T', action='store_true', dest='tracing',
  124. help='collect tracing per test case (in log directory)')
  125. parser.add_argument('-D', action='store_true', dest='dmesg',
  126. help='collect dmesg per test case (in log directory)')
  127. parser.add_argument('--shuffle-tests', action='store_true',
  128. dest='shuffle_tests',
  129. help='Shuffle test cases to randomize order')
  130. parser.add_argument('--no-reset', action='store_true', dest='no_reset',
  131. help='Do not reset devices at the end of the test')
  132. parser.add_argument('-f', dest='testmodules', metavar='<test module>',
  133. help='execute only tests from these test modules',
  134. type=str, choices=[[]] + test_modules, nargs='+')
  135. parser.add_argument('tests', metavar='<test>', nargs='*', type=str,
  136. help='tests to run (only valid without -f)',
  137. choices=[[]] + test_names)
  138. args = parser.parse_args()
  139. if args.tests and args.testmodules:
  140. print 'Invalid arguments - both test module and tests given'
  141. sys.exit(2)
  142. if not args.logdir:
  143. if os.path.exists('logs/current'):
  144. args.logdir = 'logs/current'
  145. else:
  146. args.logdir = 'logs'
  147. # Write debug level log to a file and configurable verbosity to stdout
  148. logger.setLevel(logging.DEBUG)
  149. stdout_handler = logging.StreamHandler()
  150. stdout_handler.setLevel(args.loglevel)
  151. logger.addHandler(stdout_handler)
  152. file_name = os.path.join(args.logdir, 'run-tests.log')
  153. log_handler = logging.FileHandler(file_name)
  154. log_handler.setLevel(logging.DEBUG)
  155. fmt = "%(asctime)s %(levelname)s %(message)s"
  156. log_formatter = logging.Formatter(fmt)
  157. log_handler.setFormatter(log_formatter)
  158. logger.addHandler(log_handler)
  159. if args.database:
  160. import sqlite3
  161. conn = sqlite3.connect(args.database)
  162. conn.execute('CREATE TABLE IF NOT EXISTS results (test,result,run,time,duration,build,commitid)')
  163. conn.execute('CREATE TABLE IF NOT EXISTS tests (test,description)')
  164. else:
  165. conn = None
  166. if conn:
  167. run = int(time.time())
  168. if args.update_tests_db:
  169. for t in tests:
  170. name = t.__name__.replace('test_', '', 1)
  171. print name + " - " + t.__doc__
  172. if conn:
  173. sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)'
  174. params = (name, t.__doc__)
  175. try:
  176. conn.execute(sql, params)
  177. except Exception, e:
  178. print "sqlite: " + str(e)
  179. print "sql: %r" % (params,)
  180. if conn:
  181. conn.commit()
  182. conn.close()
  183. sys.exit(0)
  184. dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0')
  185. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  186. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  187. dev = [ dev0, dev1, dev2 ]
  188. apdev = [ ]
  189. apdev.append({"ifname": 'wlan3', "bssid": "02:00:00:00:03:00"})
  190. apdev.append({"ifname": 'wlan4', "bssid": "02:00:00:00:04:00"})
  191. for d in dev:
  192. if not d.ping():
  193. logger.info(d.ifname + ": No response from wpa_supplicant")
  194. return
  195. logger.info("DEV: " + d.ifname + ": " + d.p2p_dev_addr())
  196. for ap in apdev:
  197. logger.info("APDEV: " + ap['ifname'])
  198. passed = []
  199. skipped = []
  200. failed = []
  201. # make sure nothing is left over from previous runs
  202. # (if there were any other manual runs or we crashed)
  203. reset_devs(dev, apdev)
  204. if args.dmesg:
  205. subprocess.call(['sudo', 'dmesg', '-c'], stdout=open('/dev/null', 'w'))
  206. tests_to_run = []
  207. for t in tests:
  208. name = t.__name__.replace('test_', '', 1)
  209. if args.tests:
  210. if not name in args.tests:
  211. continue
  212. if args.testmodules:
  213. if not t.__module__.replace('test_', '', 1) in args.testmodules:
  214. continue
  215. tests_to_run.append(t)
  216. if conn and args.prefill:
  217. for t in tests_to_run:
  218. name = t.__name__.replace('test_', '', 1)
  219. report(conn, False, args.build, args.commit, run, name, 'NOTRUN', 0)
  220. if args.shuffle_tests:
  221. from random import shuffle
  222. shuffle(tests_to_run)
  223. for t in tests_to_run:
  224. name = t.__name__.replace('test_', '', 1)
  225. if log_handler:
  226. log_handler.stream.close()
  227. logger.removeHandler(log_handler)
  228. file_name = os.path.join(args.logdir, name + '.log')
  229. log_handler = logging.FileHandler(file_name)
  230. log_handler.setLevel(logging.DEBUG)
  231. log_handler.setFormatter(log_formatter)
  232. logger.addHandler(log_handler)
  233. with DataCollector(args.logdir, name, args.tracing, args.dmesg):
  234. logger.info("START " + name)
  235. if args.loglevel == logging.WARNING:
  236. print "START " + name
  237. sys.stdout.flush()
  238. if t.__doc__:
  239. logger.info("Test: " + t.__doc__)
  240. start = datetime.now()
  241. for d in dev:
  242. try:
  243. d.request("NOTE TEST-START " + name)
  244. except Exception, e:
  245. logger.info("Failed to issue TEST-START before " + name + " for " + d.ifname)
  246. logger.info(e)
  247. print "FAIL " + name + " - could not start test"
  248. if conn:
  249. conn.close()
  250. conn = None
  251. sys.exit(1)
  252. try:
  253. if t.func_code.co_argcount > 1:
  254. res = t(dev, apdev)
  255. else:
  256. res = t(dev)
  257. if res == "skip":
  258. result = "SKIP"
  259. else:
  260. result = "PASS"
  261. except Exception, e:
  262. logger.info(e)
  263. result = "FAIL"
  264. for d in dev:
  265. try:
  266. d.request("NOTE TEST-STOP " + name)
  267. except Exception, e:
  268. logger.info("Failed to issue TEST-STOP after {} for {}".format(name, d.ifname))
  269. logger.info(e)
  270. if args.no_reset:
  271. print "Leaving devices in current state"
  272. else:
  273. reset_devs(dev, apdev)
  274. for i in range(0, 3):
  275. rename_log(args.logdir, 'log' + str(i), name, dev[i])
  276. hapd = HostapdGlobal()
  277. rename_log(args.logdir, 'hostapd', name, hapd)
  278. end = datetime.now()
  279. diff = end - start
  280. if result == 'PASS' and args.dmesg:
  281. if not check_kernel(os.path.join(args.logdir, name + '.dmesg')):
  282. result = 'FAIL'
  283. if result == 'PASS':
  284. passed.append(name)
  285. elif result == 'SKIP':
  286. skipped.append(name)
  287. else:
  288. failed.append(name)
  289. report(conn, args.prefill, args.build, args.commit, run, name, result, diff.total_seconds())
  290. result = "{} {} {} {}".format(result, name, diff.total_seconds(), end)
  291. logger.info(result)
  292. if args.loglevel == logging.WARNING:
  293. print result
  294. sys.stdout.flush()
  295. if log_handler:
  296. log_handler.stream.close()
  297. logger.removeHandler(log_handler)
  298. file_name = os.path.join(args.logdir, 'run-tests.log')
  299. log_handler = logging.FileHandler(file_name)
  300. log_handler.setLevel(logging.DEBUG)
  301. log_handler.setFormatter(log_formatter)
  302. logger.addHandler(log_handler)
  303. if conn:
  304. conn.close()
  305. if len(failed):
  306. logger.info("passed {} test case(s)".format(len(passed)))
  307. logger.info("skipped {} test case(s)".format(len(skipped)))
  308. logger.info("failed tests: " + str(failed))
  309. if args.loglevel == logging.WARNING:
  310. print "failed tests: " + str(failed)
  311. sys.exit(1)
  312. logger.info("passed all {} test case(s)".format(len(passed)))
  313. if len(skipped):
  314. logger.info("skipped {} test case(s)".format(len(skipped)))
  315. if args.loglevel == logging.WARNING:
  316. print "passed all {} test case(s)".format(len(passed))
  317. if len(skipped):
  318. print "skipped {} test case(s)".format(len(skipped))
  319. if __name__ == "__main__":
  320. main()