run-tests.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. #!/usr/bin/env python2
  2. #
  3. # Test case executor
  4. # Copyright (c) 2013-2014, 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 termios
  16. import logging
  17. logger = logging.getLogger()
  18. if os.path.exists('../../wpaspy'):
  19. sys.path.append('../../wpaspy')
  20. else:
  21. sys.path.append('../../../wpaspy')
  22. from wpasupplicant import WpaSupplicant
  23. from hostapd import HostapdGlobal
  24. from check_kernel import check_kernel
  25. from wlantest import Wlantest
  26. def set_term_echo(fd, enabled):
  27. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] = termios.tcgetattr(fd)
  28. if enabled:
  29. lflag |= termios.ECHO
  30. else:
  31. lflag &= ~termios.ECHO
  32. termios.tcsetattr(fd, termios.TCSANOW,
  33. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
  34. def reset_devs(dev, apdev):
  35. ok = True
  36. for d in dev:
  37. try:
  38. d.reset()
  39. except Exception, e:
  40. logger.info("Failed to reset device " + d.ifname)
  41. print str(e)
  42. ok = False
  43. try:
  44. wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
  45. ifaces = wpas.global_request("INTERFACES").splitlines()
  46. for iface in ifaces:
  47. if iface.startswith("wlan"):
  48. wpas.interface_remove(iface)
  49. except Exception, e:
  50. pass
  51. try:
  52. hapd = HostapdGlobal()
  53. hapd.flush()
  54. hapd.remove('wlan3-3')
  55. hapd.remove('wlan3-2')
  56. for ap in apdev:
  57. hapd.remove(ap['ifname'])
  58. except Exception, e:
  59. logger.info("Failed to remove hostapd interface")
  60. print str(e)
  61. ok = False
  62. return ok
  63. def add_log_file(conn, test, run, type, path):
  64. if not os.path.exists(path):
  65. return
  66. contents = None
  67. with open(path, 'r') as f:
  68. contents = f.read()
  69. if contents is None:
  70. return
  71. sql = "INSERT INTO logs(test,run,type,contents) VALUES(?, ?, ?, ?)"
  72. params = (test, run, type, contents)
  73. try:
  74. conn.execute(sql, params)
  75. conn.commit()
  76. except Exception, e:
  77. print "sqlite: " + str(e)
  78. print "sql: %r" % (params, )
  79. def report(conn, prefill, build, commit, run, test, result, duration, logdir,
  80. sql_commit=True):
  81. if conn:
  82. if not build:
  83. build = ''
  84. if not commit:
  85. commit = ''
  86. if prefill:
  87. conn.execute('DELETE FROM results WHERE test=? AND run=? AND result=?', (test, run, 'NOTRUN'))
  88. sql = "INSERT INTO results(test,result,run,time,duration,build,commitid) VALUES(?, ?, ?, ?, ?, ?, ?)"
  89. params = (test, result, run, time.time(), duration, build, commit)
  90. try:
  91. conn.execute(sql, params)
  92. if sql_commit:
  93. conn.commit()
  94. except Exception, e:
  95. print "sqlite: " + str(e)
  96. print "sql: %r" % (params, )
  97. if result == "FAIL":
  98. for log in [ "log", "log0", "log1", "log2", "log3", "log5",
  99. "hostapd", "dmesg", "hwsim0", "hwsim0.pcapng" ]:
  100. add_log_file(conn, test, run, log,
  101. logdir + "/" + test + "." + log)
  102. class DataCollector(object):
  103. def __init__(self, logdir, testname, tracing, dmesg):
  104. self._logdir = logdir
  105. self._testname = testname
  106. self._tracing = tracing
  107. self._dmesg = dmesg
  108. def __enter__(self):
  109. if self._tracing:
  110. output = os.path.abspath(os.path.join(self._logdir, '%s.dat' % (self._testname, )))
  111. self._trace_cmd = subprocess.Popen(['sudo', 'trace-cmd', 'record', '-o', output, '-e', 'mac80211', '-e', 'cfg80211', 'sh', '-c', 'echo STARTED ; read l'],
  112. stdin=subprocess.PIPE,
  113. stdout=subprocess.PIPE,
  114. stderr=open('/dev/null', 'w'),
  115. cwd=self._logdir)
  116. l = self._trace_cmd.stdout.read(7)
  117. while self._trace_cmd.poll() is None and not 'STARTED' in l:
  118. l += self._trace_cmd.stdout.read(1)
  119. res = self._trace_cmd.returncode
  120. if res:
  121. print "Failed calling trace-cmd: returned exit status %d" % res
  122. sys.exit(1)
  123. def __exit__(self, type, value, traceback):
  124. if self._tracing:
  125. self._trace_cmd.stdin.write('DONE\n')
  126. self._trace_cmd.wait()
  127. if self._dmesg:
  128. output = os.path.join(self._logdir, '%s.dmesg' % (self._testname, ))
  129. subprocess.call(['sudo', 'dmesg', '-c'], stdout=open(output, 'w'))
  130. def rename_log(logdir, basename, testname, dev):
  131. try:
  132. import getpass
  133. srcname = os.path.join(logdir, basename)
  134. dstname = os.path.join(logdir, testname + '.' + basename)
  135. num = 0
  136. while os.path.exists(dstname):
  137. dstname = os.path.join(logdir,
  138. testname + '.' + basename + '-' + str(num))
  139. num = num + 1
  140. os.rename(srcname, dstname)
  141. if dev:
  142. dev.relog()
  143. subprocess.call(['sudo', 'chown', '-f', getpass.getuser(), srcname])
  144. except Exception, e:
  145. logger.info("Failed to rename log files")
  146. logger.info(e)
  147. def main():
  148. tests = []
  149. test_modules = []
  150. if os.path.exists('run-tests.py'):
  151. files = os.listdir(".")
  152. else:
  153. files = os.listdir("..")
  154. for t in files:
  155. m = re.match(r'(test_.*)\.py$', t)
  156. if m:
  157. logger.debug("Import test cases from " + t)
  158. mod = __import__(m.group(1))
  159. test_modules.append(mod.__name__.replace('test_', '', 1))
  160. for key,val in mod.__dict__.iteritems():
  161. if key.startswith("test_"):
  162. tests.append(val)
  163. test_names = list(set([t.__name__.replace('test_', '', 1) for t in tests]))
  164. run = None
  165. parser = argparse.ArgumentParser(description='hwsim test runner')
  166. parser.add_argument('--logdir', metavar='<directory>',
  167. help='log output directory for all other options, ' +
  168. 'must be given if other log options are used')
  169. group = parser.add_mutually_exclusive_group()
  170. group.add_argument('-d', const=logging.DEBUG, action='store_const',
  171. dest='loglevel', default=logging.INFO,
  172. help="verbose debug output")
  173. group.add_argument('-q', const=logging.WARNING, action='store_const',
  174. dest='loglevel', help="be quiet")
  175. parser.add_argument('-S', metavar='<sqlite3 db>', dest='database',
  176. help='database to write results to')
  177. parser.add_argument('--prefill-tests', action='store_true', dest='prefill',
  178. help='prefill test database with NOTRUN before all tests')
  179. parser.add_argument('--commit', metavar='<commit id>',
  180. help='commit ID, only for database')
  181. parser.add_argument('-b', metavar='<build>', dest='build', help='build ID')
  182. parser.add_argument('-L', action='store_true', dest='update_tests_db',
  183. help='List tests (and update descriptions in DB)')
  184. parser.add_argument('-T', action='store_true', dest='tracing',
  185. help='collect tracing per test case (in log directory)')
  186. parser.add_argument('-D', action='store_true', dest='dmesg',
  187. help='collect dmesg per test case (in log directory)')
  188. parser.add_argument('--shuffle-tests', action='store_true',
  189. dest='shuffle_tests',
  190. help='Shuffle test cases to randomize order')
  191. parser.add_argument('--split', help='split tests for parallel execution (<server number>/<total servers>)')
  192. parser.add_argument('--no-reset', action='store_true', dest='no_reset',
  193. help='Do not reset devices at the end of the test')
  194. parser.add_argument('--long', action='store_true',
  195. help='Include test cases that take long time')
  196. parser.add_argument('-f', dest='testmodules', metavar='<test module>',
  197. help='execute only tests from these test modules',
  198. type=str, choices=[[]] + test_modules, nargs='+')
  199. parser.add_argument('-l', metavar='<modules file>', dest='mfile',
  200. help='test modules file name')
  201. parser.add_argument('-i', action='store_true', dest='stdin_ctrl',
  202. help='stdin-controlled test case execution')
  203. parser.add_argument('tests', metavar='<test>', nargs='*', type=str,
  204. help='tests to run (only valid without -f)',
  205. choices=[[]] + test_names)
  206. args = parser.parse_args()
  207. if (args.tests and args.testmodules) or (args.tests and args.mfile) or (args.testmodules and args.mfile):
  208. print 'Invalid arguments - only one of (test, test modules, modules file) can be given.'
  209. sys.exit(2)
  210. if args.database:
  211. import sqlite3
  212. conn = sqlite3.connect(args.database)
  213. conn.execute('CREATE TABLE IF NOT EXISTS results (test,result,run,time,duration,build,commitid)')
  214. conn.execute('CREATE TABLE IF NOT EXISTS tests (test,description)')
  215. conn.execute('CREATE TABLE IF NOT EXISTS logs (test,run,type,contents)')
  216. else:
  217. conn = None
  218. if conn:
  219. run = int(time.time())
  220. # read the modules from the modules file
  221. if args.mfile:
  222. args.testmodules = []
  223. with open(args.mfile) as f:
  224. for line in f.readlines():
  225. line = line.strip()
  226. if not line or line.startswith('#'):
  227. continue
  228. args.testmodules.append(line)
  229. tests_to_run = []
  230. if args.tests:
  231. for selected in args.tests:
  232. for t in tests:
  233. name = t.__name__.replace('test_', '', 1)
  234. if name == selected:
  235. tests_to_run.append(t)
  236. else:
  237. for t in tests:
  238. name = t.__name__.replace('test_', '', 1)
  239. if args.testmodules:
  240. if not t.__module__.replace('test_', '', 1) in args.testmodules:
  241. continue
  242. tests_to_run.append(t)
  243. if args.update_tests_db:
  244. for t in tests_to_run:
  245. name = t.__name__.replace('test_', '', 1)
  246. if t.__doc__ is None:
  247. print name + " - MISSING DESCRIPTION"
  248. else:
  249. print name + " - " + t.__doc__
  250. if conn:
  251. sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)'
  252. params = (name, t.__doc__)
  253. try:
  254. conn.execute(sql, params)
  255. except Exception, e:
  256. print "sqlite: " + str(e)
  257. print "sql: %r" % (params,)
  258. if conn:
  259. conn.commit()
  260. conn.close()
  261. sys.exit(0)
  262. if not args.logdir:
  263. if os.path.exists('logs/current'):
  264. args.logdir = 'logs/current'
  265. else:
  266. args.logdir = 'logs'
  267. # Write debug level log to a file and configurable verbosity to stdout
  268. logger.setLevel(logging.DEBUG)
  269. stdout_handler = logging.StreamHandler()
  270. stdout_handler.setLevel(args.loglevel)
  271. logger.addHandler(stdout_handler)
  272. file_name = os.path.join(args.logdir, 'run-tests.log')
  273. log_handler = logging.FileHandler(file_name)
  274. log_handler.setLevel(logging.DEBUG)
  275. fmt = "%(asctime)s %(levelname)s %(message)s"
  276. log_formatter = logging.Formatter(fmt)
  277. log_handler.setFormatter(log_formatter)
  278. logger.addHandler(log_handler)
  279. dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0')
  280. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  281. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  282. dev = [ dev0, dev1, dev2 ]
  283. apdev = [ ]
  284. apdev.append({"ifname": 'wlan3', "bssid": "02:00:00:00:03:00"})
  285. apdev.append({"ifname": 'wlan4', "bssid": "02:00:00:00:04:00"})
  286. for d in dev:
  287. if not d.ping():
  288. logger.info(d.ifname + ": No response from wpa_supplicant")
  289. return
  290. logger.info("DEV: " + d.ifname + ": " + d.p2p_dev_addr())
  291. for ap in apdev:
  292. logger.info("APDEV: " + ap['ifname'])
  293. passed = []
  294. skipped = []
  295. failed = []
  296. # make sure nothing is left over from previous runs
  297. # (if there were any other manual runs or we crashed)
  298. if not reset_devs(dev, apdev):
  299. if conn:
  300. conn.close()
  301. conn = None
  302. sys.exit(1)
  303. if args.dmesg:
  304. subprocess.call(['sudo', 'dmesg', '-c'], stdout=open('/dev/null', 'w'))
  305. if conn and args.prefill:
  306. for t in tests_to_run:
  307. name = t.__name__.replace('test_', '', 1)
  308. report(conn, False, args.build, args.commit, run, name, 'NOTRUN', 0,
  309. args.logdir, sql_commit=False)
  310. conn.commit()
  311. if args.split:
  312. vals = args.split.split('/')
  313. split_server = int(vals[0])
  314. split_total = int(vals[1])
  315. logger.info("Parallel execution - %d/%d" % (split_server, split_total))
  316. split_server -= 1
  317. tests_to_run.sort(key=lambda t: t.__name__)
  318. tests_to_run = [x for i,x in enumerate(tests_to_run) if i % split_total == split_server]
  319. if args.shuffle_tests:
  320. from random import shuffle
  321. shuffle(tests_to_run)
  322. count = 0
  323. if args.stdin_ctrl:
  324. print "READY"
  325. sys.stdout.flush()
  326. num_tests = 0
  327. else:
  328. num_tests = len(tests_to_run)
  329. if args.stdin_ctrl:
  330. set_term_echo(sys.stdin.fileno(), False)
  331. while True:
  332. if args.stdin_ctrl:
  333. test = sys.stdin.readline()
  334. if not test:
  335. break
  336. test = test.splitlines()[0]
  337. if test == '':
  338. break
  339. t = None
  340. for tt in tests:
  341. name = tt.__name__.replace('test_', '', 1)
  342. if name == test:
  343. t = tt
  344. break
  345. if not t:
  346. print "NOT-FOUND"
  347. sys.stdout.flush()
  348. continue
  349. else:
  350. if len(tests_to_run) == 0:
  351. break
  352. t = tests_to_run.pop(0)
  353. name = t.__name__.replace('test_', '', 1)
  354. if log_handler:
  355. log_handler.stream.close()
  356. logger.removeHandler(log_handler)
  357. file_name = os.path.join(args.logdir, name + '.log')
  358. log_handler = logging.FileHandler(file_name)
  359. log_handler.setLevel(logging.DEBUG)
  360. log_handler.setFormatter(log_formatter)
  361. logger.addHandler(log_handler)
  362. reset_ok = True
  363. with DataCollector(args.logdir, name, args.tracing, args.dmesg):
  364. count = count + 1
  365. msg = "START {} {}/{}".format(name, count, num_tests)
  366. logger.info(msg)
  367. if args.loglevel == logging.WARNING:
  368. print msg
  369. sys.stdout.flush()
  370. if t.__doc__:
  371. logger.info("Test: " + t.__doc__)
  372. start = datetime.now()
  373. for d in dev:
  374. try:
  375. d.dump_monitor()
  376. if not d.ping():
  377. raise Exception("PING failed for {}".format(d.ifname))
  378. if not d.global_ping():
  379. raise Exception("Global PING failed for {}".format(d.ifname))
  380. d.request("NOTE TEST-START " + name)
  381. except Exception, e:
  382. logger.info("Failed to issue TEST-START before " + name + " for " + d.ifname)
  383. logger.info(e)
  384. print "FAIL " + name + " - could not start test"
  385. if conn:
  386. conn.close()
  387. conn = None
  388. if args.stdin_ctrl:
  389. set_term_echo(sys.stdin.fileno(), True)
  390. sys.exit(1)
  391. try:
  392. if t.func_code.co_argcount > 2:
  393. params = {}
  394. params['logdir'] = args.logdir
  395. params['long'] = args.long
  396. res = t(dev, apdev, params)
  397. elif t.func_code.co_argcount > 1:
  398. res = t(dev, apdev)
  399. else:
  400. res = t(dev)
  401. if res == "skip":
  402. result = "SKIP"
  403. else:
  404. result = "PASS"
  405. except Exception, e:
  406. logger.info(e)
  407. if args.loglevel == logging.WARNING:
  408. print "Exception: " + str(e)
  409. result = "FAIL"
  410. for d in dev:
  411. try:
  412. d.dump_monitor()
  413. d.request("NOTE TEST-STOP " + name)
  414. except Exception, e:
  415. logger.info("Failed to issue TEST-STOP after {} for {}".format(name, d.ifname))
  416. logger.info(e)
  417. result = "FAIL"
  418. try:
  419. wpas = WpaSupplicant("/tmp/wpas-wlan5")
  420. d.dump_monitor()
  421. rename_log(args.logdir, 'log5', name, wpas)
  422. if not args.no_reset:
  423. wpas.remove_ifname()
  424. except Exception, e:
  425. pass
  426. if args.no_reset:
  427. print "Leaving devices in current state"
  428. else:
  429. reset_ok = reset_devs(dev, apdev)
  430. for i in range(0, 3):
  431. rename_log(args.logdir, 'log' + str(i), name, dev[i])
  432. try:
  433. hapd = HostapdGlobal()
  434. except Exception, e:
  435. print "Failed to connect to hostapd interface"
  436. print str(e)
  437. reset_ok = False
  438. result = "FAIL"
  439. hapd = None
  440. rename_log(args.logdir, 'hostapd', name, hapd)
  441. wt = Wlantest()
  442. rename_log(args.logdir, 'hwsim0.pcapng', name, wt)
  443. rename_log(args.logdir, 'hwsim0', name, wt)
  444. end = datetime.now()
  445. diff = end - start
  446. if result == 'PASS' and args.dmesg:
  447. if not check_kernel(os.path.join(args.logdir, name + '.dmesg')):
  448. logger.info("Kernel issue found in dmesg - mark test failed")
  449. result = 'FAIL'
  450. if result == 'PASS':
  451. passed.append(name)
  452. elif result == 'SKIP':
  453. skipped.append(name)
  454. else:
  455. failed.append(name)
  456. report(conn, args.prefill, args.build, args.commit, run, name, result,
  457. diff.total_seconds(), args.logdir)
  458. result = "{} {} {} {}".format(result, name, diff.total_seconds(), end)
  459. logger.info(result)
  460. if args.loglevel == logging.WARNING:
  461. print result
  462. sys.stdout.flush()
  463. if not reset_ok:
  464. print "Terminating early due to device reset failure"
  465. break
  466. if args.stdin_ctrl:
  467. set_term_echo(sys.stdin.fileno(), True)
  468. if log_handler:
  469. log_handler.stream.close()
  470. logger.removeHandler(log_handler)
  471. file_name = os.path.join(args.logdir, 'run-tests.log')
  472. log_handler = logging.FileHandler(file_name)
  473. log_handler.setLevel(logging.DEBUG)
  474. log_handler.setFormatter(log_formatter)
  475. logger.addHandler(log_handler)
  476. if conn:
  477. conn.close()
  478. if len(failed):
  479. logger.info("passed {} test case(s)".format(len(passed)))
  480. logger.info("skipped {} test case(s)".format(len(skipped)))
  481. logger.info("failed tests: " + ' '.join(failed))
  482. if args.loglevel == logging.WARNING:
  483. print "failed tests: " + ' '.join(failed)
  484. sys.exit(1)
  485. logger.info("passed all {} test case(s)".format(len(passed)))
  486. if len(skipped):
  487. logger.info("skipped {} test case(s)".format(len(skipped)))
  488. if args.loglevel == logging.WARNING:
  489. print "passed all {} test case(s)".format(len(passed))
  490. if len(skipped):
  491. print "skipped {} test case(s)".format(len(skipped))
  492. if __name__ == "__main__":
  493. main()