run-tests.py 14 KB

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