b.liu | e958203 | 2025-04-17 19:18:16 +0800 | [diff] [blame^] | 1 | #!/usr/bin/env python3 |
| 2 | # |
| 3 | # Test case executor |
| 4 | # Copyright (c) 2013-2019, 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 | |
| 9 | import os |
| 10 | import re |
| 11 | import gc |
| 12 | import sys |
| 13 | import time |
| 14 | from datetime import datetime |
| 15 | import argparse |
| 16 | import subprocess |
| 17 | import termios |
| 18 | |
| 19 | import logging |
| 20 | logger = logging.getLogger() |
| 21 | |
| 22 | try: |
| 23 | import sqlite3 |
| 24 | sqlite3_imported = True |
| 25 | except ImportError: |
| 26 | sqlite3_imported = False |
| 27 | |
| 28 | scriptsdir = os.path.dirname(os.path.realpath(sys.modules[__name__].__file__)) |
| 29 | sys.path.append(os.path.join(scriptsdir, '..', '..', 'wpaspy')) |
| 30 | |
| 31 | from wpasupplicant import WpaSupplicant |
| 32 | from hostapd import HostapdGlobal |
| 33 | from check_kernel import check_kernel |
| 34 | from wlantest import Wlantest |
| 35 | from utils import HwsimSkip |
| 36 | |
| 37 | def set_term_echo(fd, enabled): |
| 38 | [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] = termios.tcgetattr(fd) |
| 39 | if enabled: |
| 40 | lflag |= termios.ECHO |
| 41 | else: |
| 42 | lflag &= ~termios.ECHO |
| 43 | termios.tcsetattr(fd, termios.TCSANOW, |
| 44 | [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) |
| 45 | |
| 46 | def reset_devs(dev, apdev): |
| 47 | ok = True |
| 48 | for d in dev: |
| 49 | try: |
| 50 | d.reset() |
| 51 | except Exception as e: |
| 52 | logger.info("Failed to reset device " + d.ifname) |
| 53 | print(str(e)) |
| 54 | ok = False |
| 55 | |
| 56 | wpas = None |
| 57 | try: |
| 58 | wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5', monitor=False) |
| 59 | ifaces = wpas.global_request("INTERFACES").splitlines() |
| 60 | for iface in ifaces: |
| 61 | if iface.startswith("wlan"): |
| 62 | wpas.interface_remove(iface) |
| 63 | except Exception as e: |
| 64 | pass |
| 65 | if wpas: |
| 66 | wpas.close_ctrl() |
| 67 | del wpas |
| 68 | |
| 69 | try: |
| 70 | hapd = HostapdGlobal() |
| 71 | hapd.flush() |
| 72 | ifaces = hapd.request("INTERFACES").splitlines() |
| 73 | for iface in ifaces: |
| 74 | if iface.startswith("wlan"): |
| 75 | hapd.remove(iface) |
| 76 | hapd.remove('as-erp') |
| 77 | except Exception as e: |
| 78 | logger.info("Failed to remove hostapd interface") |
| 79 | print(str(e)) |
| 80 | ok = False |
| 81 | return ok |
| 82 | |
| 83 | def add_log_file(conn, test, run, type, path): |
| 84 | if not os.path.exists(path): |
| 85 | return |
| 86 | contents = None |
| 87 | with open(path, 'rb') as f: |
| 88 | contents = f.read() |
| 89 | if contents is None: |
| 90 | return |
| 91 | sql = "INSERT INTO logs(test,run,type,contents) VALUES(?, ?, ?, ?)" |
| 92 | params = (test, run, type, sqlite3.Binary(contents)) |
| 93 | try: |
| 94 | conn.execute(sql, params) |
| 95 | conn.commit() |
| 96 | except Exception as e: |
| 97 | print("sqlite: " + str(e)) |
| 98 | print("sql: %r" % (params, )) |
| 99 | |
| 100 | def report(conn, prefill, build, commit, run, test, result, duration, logdir, |
| 101 | sql_commit=True): |
| 102 | if conn: |
| 103 | if not build: |
| 104 | build = '' |
| 105 | if not commit: |
| 106 | commit = '' |
| 107 | if prefill: |
| 108 | conn.execute('DELETE FROM results WHERE test=? AND run=? AND result=?', (test, run, 'NOTRUN')) |
| 109 | sql = "INSERT INTO results(test,result,run,time,duration,build,commitid) VALUES(?, ?, ?, ?, ?, ?, ?)" |
| 110 | params = (test, result, run, time.time(), duration, build, commit) |
| 111 | try: |
| 112 | conn.execute(sql, params) |
| 113 | if sql_commit: |
| 114 | conn.commit() |
| 115 | except Exception as e: |
| 116 | print("sqlite: " + str(e)) |
| 117 | print("sql: %r" % (params, )) |
| 118 | |
| 119 | if result == "FAIL": |
| 120 | for log in ["log", "log0", "log1", "log2", "log3", "log5", |
| 121 | "hostapd", "dmesg", "hwsim0", "hwsim0.pcapng"]: |
| 122 | add_log_file(conn, test, run, log, |
| 123 | logdir + "/" + test + "." + log) |
| 124 | |
| 125 | class DataCollector(object): |
| 126 | def __init__(self, logdir, testname, args): |
| 127 | self._logdir = logdir |
| 128 | self._testname = testname |
| 129 | self._tracing = args.tracing |
| 130 | self._dmesg = args.dmesg |
| 131 | self._dbus = args.dbus |
| 132 | def __enter__(self): |
| 133 | if self._tracing: |
| 134 | output = os.path.abspath(os.path.join(self._logdir, '%s.dat' % (self._testname, ))) |
| 135 | self._trace_cmd = subprocess.Popen(['trace-cmd', 'record', '-o', output, '-e', 'mac80211', '-e', 'cfg80211', '-e', 'printk', 'sh', '-c', 'echo STARTED ; read l'], |
| 136 | stdin=subprocess.PIPE, |
| 137 | stdout=subprocess.PIPE, |
| 138 | stderr=open('/dev/null', 'w'), |
| 139 | cwd=self._logdir) |
| 140 | l = self._trace_cmd.stdout.read(7) |
| 141 | while self._trace_cmd.poll() is None and b'STARTED' not in l: |
| 142 | l += self._trace_cmd.stdout.read(1) |
| 143 | res = self._trace_cmd.returncode |
| 144 | if res: |
| 145 | print("Failed calling trace-cmd: returned exit status %d" % res) |
| 146 | sys.exit(1) |
| 147 | if self._dbus: |
| 148 | output = os.path.abspath(os.path.join(self._logdir, '%s.dbus' % (self._testname, ))) |
| 149 | self._dbus_cmd = subprocess.Popen(['dbus-monitor', '--system'], |
| 150 | stdout=open(output, 'w'), |
| 151 | stderr=open('/dev/null', 'w'), |
| 152 | cwd=self._logdir) |
| 153 | res = self._dbus_cmd.returncode |
| 154 | if res: |
| 155 | print("Failed calling dbus-monitor: returned exit status %d" % res) |
| 156 | sys.exit(1) |
| 157 | def __exit__(self, type, value, traceback): |
| 158 | if self._tracing: |
| 159 | self._trace_cmd.stdin.write(b'DONE\n') |
| 160 | self._trace_cmd.stdin.flush() |
| 161 | self._trace_cmd.wait() |
| 162 | if self._dmesg: |
| 163 | output = os.path.join(self._logdir, '%s.dmesg' % (self._testname, )) |
| 164 | num = 0 |
| 165 | while os.path.exists(output): |
| 166 | output = os.path.join(self._logdir, '%s.dmesg-%d' % (self._testname, num)) |
| 167 | num += 1 |
| 168 | subprocess.call(['dmesg', '-c'], stdout=open(output, 'w')) |
| 169 | |
| 170 | def rename_log(logdir, basename, testname, dev): |
| 171 | try: |
| 172 | import getpass |
| 173 | srcname = os.path.join(logdir, basename) |
| 174 | dstname = os.path.join(logdir, testname + '.' + basename) |
| 175 | num = 0 |
| 176 | while os.path.exists(dstname): |
| 177 | dstname = os.path.join(logdir, |
| 178 | testname + '.' + basename + '-' + str(num)) |
| 179 | num = num + 1 |
| 180 | os.rename(srcname, dstname) |
| 181 | if dev: |
| 182 | dev.relog() |
| 183 | subprocess.call(['chown', '-f', getpass.getuser(), srcname]) |
| 184 | except Exception as e: |
| 185 | logger.info("Failed to rename log files") |
| 186 | logger.info(e) |
| 187 | |
| 188 | def is_long_duration_test(t): |
| 189 | return hasattr(t, "long_duration_test") and t.long_duration_test |
| 190 | |
| 191 | def get_test_description(t): |
| 192 | if t.__doc__ is None: |
| 193 | desc = "MISSING DESCRIPTION" |
| 194 | else: |
| 195 | desc = t.__doc__ |
| 196 | if is_long_duration_test(t): |
| 197 | desc += " [long]" |
| 198 | return desc |
| 199 | |
| 200 | def main(): |
| 201 | tests = [] |
| 202 | test_modules = [] |
| 203 | files = os.listdir(scriptsdir) |
| 204 | for t in files: |
| 205 | m = re.match(r'(test_.*)\.py$', t) |
| 206 | if m: |
| 207 | logger.debug("Import test cases from " + t) |
| 208 | mod = __import__(m.group(1)) |
| 209 | test_modules.append(mod.__name__.replace('test_', '', 1)) |
| 210 | for key, val in mod.__dict__.items(): |
| 211 | if key.startswith("test_"): |
| 212 | tests.append(val) |
| 213 | test_names = list(set([t.__name__.replace('test_', '', 1) for t in tests])) |
| 214 | |
| 215 | run = None |
| 216 | |
| 217 | parser = argparse.ArgumentParser(description='hwsim test runner') |
| 218 | parser.add_argument('--logdir', metavar='<directory>', |
| 219 | help='log output directory for all other options, ' + |
| 220 | 'must be given if other log options are used') |
| 221 | group = parser.add_mutually_exclusive_group() |
| 222 | group.add_argument('-d', const=logging.DEBUG, action='store_const', |
| 223 | dest='loglevel', default=logging.INFO, |
| 224 | help="verbose debug output") |
| 225 | group.add_argument('-q', const=logging.WARNING, action='store_const', |
| 226 | dest='loglevel', help="be quiet") |
| 227 | |
| 228 | parser.add_argument('-S', metavar='<sqlite3 db>', dest='database', |
| 229 | help='database to write results to') |
| 230 | parser.add_argument('--prefill-tests', action='store_true', dest='prefill', |
| 231 | help='prefill test database with NOTRUN before all tests') |
| 232 | parser.add_argument('--commit', metavar='<commit id>', |
| 233 | help='commit ID, only for database') |
| 234 | parser.add_argument('-b', metavar='<build>', dest='build', help='build ID') |
| 235 | parser.add_argument('-L', action='store_true', dest='update_tests_db', |
| 236 | help='List tests (and update descriptions in DB)') |
| 237 | parser.add_argument('-T', action='store_true', dest='tracing', |
| 238 | help='collect tracing per test case (in log directory)') |
| 239 | parser.add_argument('-D', action='store_true', dest='dmesg', |
| 240 | help='collect dmesg per test case (in log directory)') |
| 241 | parser.add_argument('--dbus', action='store_true', dest='dbus', |
| 242 | help='collect dbus per test case (in log directory)') |
| 243 | parser.add_argument('--shuffle-tests', action='store_true', |
| 244 | dest='shuffle_tests', |
| 245 | help='Shuffle test cases to randomize order') |
| 246 | parser.add_argument('--split', help='split tests for parallel execution (<server number>/<total servers>)') |
| 247 | parser.add_argument('--no-reset', action='store_true', dest='no_reset', |
| 248 | help='Do not reset devices at the end of the test') |
| 249 | parser.add_argument('--long', action='store_true', |
| 250 | help='Include test cases that take long time') |
| 251 | parser.add_argument('-f', dest='testmodules', metavar='<test module>', |
| 252 | help='execute only tests from these test modules', |
| 253 | type=str, choices=[[]] + test_modules, nargs='+') |
| 254 | parser.add_argument('-l', metavar='<modules file>', dest='mfile', |
| 255 | help='test modules file name') |
| 256 | parser.add_argument('-i', action='store_true', dest='stdin_ctrl', |
| 257 | help='stdin-controlled test case execution') |
| 258 | parser.add_argument('tests', metavar='<test>', nargs='*', type=str, |
| 259 | help='tests to run (only valid without -f)') |
| 260 | |
| 261 | args = parser.parse_args() |
| 262 | |
| 263 | if (args.tests and args.testmodules) or (args.tests and args.mfile) or (args.testmodules and args.mfile): |
| 264 | print('Invalid arguments - only one of (test, test modules, modules file) can be given.') |
| 265 | sys.exit(2) |
| 266 | |
| 267 | if args.tests: |
| 268 | fail = False |
| 269 | for t in args.tests: |
| 270 | if t.endswith('*'): |
| 271 | prefix = t.rstrip('*') |
| 272 | found = False |
| 273 | for tn in test_names: |
| 274 | if tn.startswith(prefix): |
| 275 | found = True |
| 276 | break |
| 277 | if not found: |
| 278 | print('Invalid arguments - test "%s" wildcard did not match' % t) |
| 279 | fail = True |
| 280 | elif t not in test_names: |
| 281 | print('Invalid arguments - test "%s" not known' % t) |
| 282 | fail = True |
| 283 | if fail: |
| 284 | sys.exit(2) |
| 285 | |
| 286 | if args.database: |
| 287 | if not sqlite3_imported: |
| 288 | print("No sqlite3 module found") |
| 289 | sys.exit(2) |
| 290 | conn = sqlite3.connect(args.database) |
| 291 | conn.execute('CREATE TABLE IF NOT EXISTS results (test,result,run,time,duration,build,commitid)') |
| 292 | conn.execute('CREATE TABLE IF NOT EXISTS tests (test,description)') |
| 293 | conn.execute('CREATE TABLE IF NOT EXISTS logs (test,run,type,contents)') |
| 294 | else: |
| 295 | conn = None |
| 296 | |
| 297 | if conn: |
| 298 | run = int(time.time()) |
| 299 | |
| 300 | # read the modules from the modules file |
| 301 | if args.mfile: |
| 302 | args.testmodules = [] |
| 303 | with open(args.mfile) as f: |
| 304 | for line in f.readlines(): |
| 305 | line = line.strip() |
| 306 | if not line or line.startswith('#'): |
| 307 | continue |
| 308 | args.testmodules.append(line) |
| 309 | |
| 310 | tests_to_run = [] |
| 311 | if args.tests: |
| 312 | for selected in args.tests: |
| 313 | for t in tests: |
| 314 | name = t.__name__.replace('test_', '', 1) |
| 315 | if selected.endswith('*'): |
| 316 | prefix = selected.rstrip('*') |
| 317 | if name.startswith(prefix): |
| 318 | tests_to_run.append(t) |
| 319 | elif name == selected: |
| 320 | tests_to_run.append(t) |
| 321 | else: |
| 322 | for t in tests: |
| 323 | name = t.__name__.replace('test_', '', 1) |
| 324 | if args.testmodules: |
| 325 | if t.__module__.replace('test_', '', 1) not in args.testmodules: |
| 326 | continue |
| 327 | tests_to_run.append(t) |
| 328 | |
| 329 | if args.update_tests_db: |
| 330 | for t in tests_to_run: |
| 331 | name = t.__name__.replace('test_', '', 1) |
| 332 | print(name + " - " + get_test_description(t)) |
| 333 | if conn: |
| 334 | sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)' |
| 335 | params = (name, get_test_description(t)) |
| 336 | try: |
| 337 | conn.execute(sql, params) |
| 338 | except Exception as e: |
| 339 | print("sqlite: " + str(e)) |
| 340 | print("sql: %r" % (params,)) |
| 341 | if conn: |
| 342 | conn.commit() |
| 343 | conn.close() |
| 344 | sys.exit(0) |
| 345 | |
| 346 | if not args.logdir: |
| 347 | if os.path.exists('logs/current'): |
| 348 | args.logdir = 'logs/current' |
| 349 | else: |
| 350 | args.logdir = 'logs' |
| 351 | |
| 352 | # Write debug level log to a file and configurable verbosity to stdout |
| 353 | logger.setLevel(logging.DEBUG) |
| 354 | |
| 355 | stdout_handler = logging.StreamHandler() |
| 356 | stdout_handler.setLevel(args.loglevel) |
| 357 | logger.addHandler(stdout_handler) |
| 358 | |
| 359 | file_name = os.path.join(args.logdir, 'run-tests.log') |
| 360 | log_handler = logging.FileHandler(file_name, encoding='utf-8') |
| 361 | log_handler.setLevel(logging.DEBUG) |
| 362 | fmt = "%(asctime)s %(levelname)s %(message)s" |
| 363 | log_formatter = logging.Formatter(fmt) |
| 364 | log_handler.setFormatter(log_formatter) |
| 365 | logger.addHandler(log_handler) |
| 366 | |
| 367 | dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0') |
| 368 | dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1') |
| 369 | dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2') |
| 370 | dev = [dev0, dev1, dev2] |
| 371 | apdev = [] |
| 372 | apdev.append({"ifname": 'wlan3', "bssid": "02:00:00:00:03:00"}) |
| 373 | apdev.append({"ifname": 'wlan4', "bssid": "02:00:00:00:04:00"}) |
| 374 | |
| 375 | for d in dev: |
| 376 | if not d.ping(): |
| 377 | logger.info(d.ifname + ": No response from wpa_supplicant") |
| 378 | return |
| 379 | logger.info("DEV: " + d.ifname + ": " + d.p2p_dev_addr()) |
| 380 | for ap in apdev: |
| 381 | logger.info("APDEV: " + ap['ifname']) |
| 382 | |
| 383 | passed = [] |
| 384 | skipped = [] |
| 385 | failed = [] |
| 386 | |
| 387 | # make sure nothing is left over from previous runs |
| 388 | # (if there were any other manual runs or we crashed) |
| 389 | if not reset_devs(dev, apdev): |
| 390 | if conn: |
| 391 | conn.close() |
| 392 | conn = None |
| 393 | sys.exit(1) |
| 394 | |
| 395 | if args.dmesg: |
| 396 | subprocess.call(['dmesg', '-c'], stdout=open('/dev/null', 'w')) |
| 397 | |
| 398 | if conn and args.prefill: |
| 399 | for t in tests_to_run: |
| 400 | name = t.__name__.replace('test_', '', 1) |
| 401 | report(conn, False, args.build, args.commit, run, name, 'NOTRUN', 0, |
| 402 | args.logdir, sql_commit=False) |
| 403 | conn.commit() |
| 404 | |
| 405 | if args.split: |
| 406 | vals = args.split.split('/') |
| 407 | split_server = int(vals[0]) |
| 408 | split_total = int(vals[1]) |
| 409 | logger.info("Parallel execution - %d/%d" % (split_server, split_total)) |
| 410 | split_server -= 1 |
| 411 | tests_to_run.sort(key=lambda t: t.__name__) |
| 412 | tests_to_run = [x for i, x in enumerate(tests_to_run) if i % split_total == split_server] |
| 413 | |
| 414 | if args.shuffle_tests: |
| 415 | from random import shuffle |
| 416 | shuffle(tests_to_run) |
| 417 | |
| 418 | count = 0 |
| 419 | if args.stdin_ctrl: |
| 420 | print("READY") |
| 421 | sys.stdout.flush() |
| 422 | num_tests = 0 |
| 423 | else: |
| 424 | num_tests = len(tests_to_run) |
| 425 | if args.stdin_ctrl: |
| 426 | set_term_echo(sys.stdin.fileno(), False) |
| 427 | |
| 428 | check_country_00 = True |
| 429 | for d in dev: |
| 430 | if d.get_driver_status_field("country") != "00": |
| 431 | check_country_00 = False |
| 432 | |
| 433 | while True: |
| 434 | if args.stdin_ctrl: |
| 435 | test = sys.stdin.readline() |
| 436 | if not test: |
| 437 | break |
| 438 | test = test.splitlines()[0] |
| 439 | if test == '': |
| 440 | break |
| 441 | t = None |
| 442 | for tt in tests: |
| 443 | name = tt.__name__.replace('test_', '', 1) |
| 444 | if name == test: |
| 445 | t = tt |
| 446 | break |
| 447 | if not t: |
| 448 | print("NOT-FOUND") |
| 449 | sys.stdout.flush() |
| 450 | continue |
| 451 | else: |
| 452 | if len(tests_to_run) == 0: |
| 453 | break |
| 454 | t = tests_to_run.pop(0) |
| 455 | |
| 456 | if dev[0].get_driver_status_field("country") == "98": |
| 457 | # Work around cfg80211 regulatory issues in clearing intersected |
| 458 | # country code 98. Need to make station disconnect without any |
| 459 | # other wiphy being active in the system. |
| 460 | logger.info("country=98 workaround - try to clear state") |
| 461 | id = dev[1].add_network() |
| 462 | dev[1].set_network(id, "mode", "2") |
| 463 | dev[1].set_network_quoted(id, "ssid", "country98") |
| 464 | dev[1].set_network(id, "key_mgmt", "NONE") |
| 465 | dev[1].set_network(id, "frequency", "2412") |
| 466 | dev[1].set_network(id, "scan_freq", "2412") |
| 467 | dev[1].select_network(id) |
| 468 | ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"]) |
| 469 | if ev: |
| 470 | dev[0].connect("country98", key_mgmt="NONE", scan_freq="2412") |
| 471 | dev[1].request("DISCONNECT") |
| 472 | dev[0].wait_disconnected() |
| 473 | dev[0].disconnect_and_stop_scan() |
| 474 | dev[0].reset() |
| 475 | dev[1].reset() |
| 476 | dev[0].dump_monitor() |
| 477 | dev[1].dump_monitor() |
| 478 | |
| 479 | name = t.__name__.replace('test_', '', 1) |
| 480 | open('/dev/kmsg', 'w').write('running hwsim test case %s\n' % name) |
| 481 | if log_handler: |
| 482 | log_handler.stream.close() |
| 483 | logger.removeHandler(log_handler) |
| 484 | file_name = os.path.join(args.logdir, name + '.log') |
| 485 | log_handler = logging.FileHandler(file_name, encoding='utf-8') |
| 486 | log_handler.setLevel(logging.DEBUG) |
| 487 | log_handler.setFormatter(log_formatter) |
| 488 | logger.addHandler(log_handler) |
| 489 | |
| 490 | reset_ok = True |
| 491 | with DataCollector(args.logdir, name, args): |
| 492 | count = count + 1 |
| 493 | msg = "START {} {}/{}".format(name, count, num_tests) |
| 494 | logger.info(msg) |
| 495 | if args.loglevel == logging.WARNING: |
| 496 | print(msg) |
| 497 | sys.stdout.flush() |
| 498 | if t.__doc__: |
| 499 | logger.info("Test: " + t.__doc__) |
| 500 | start = datetime.now() |
| 501 | open('/dev/kmsg', 'w').write('TEST-START %s @%.6f\n' % (name, time.time())) |
| 502 | for d in dev: |
| 503 | try: |
| 504 | d.dump_monitor() |
| 505 | if not d.ping(): |
| 506 | raise Exception("PING failed for {}".format(d.ifname)) |
| 507 | if not d.global_ping(): |
| 508 | raise Exception("Global PING failed for {}".format(d.ifname)) |
| 509 | d.request("NOTE TEST-START " + name) |
| 510 | except Exception as e: |
| 511 | logger.info("Failed to issue TEST-START before " + name + " for " + d.ifname) |
| 512 | logger.info(e) |
| 513 | print("FAIL " + name + " - could not start test") |
| 514 | if conn: |
| 515 | conn.close() |
| 516 | conn = None |
| 517 | if args.stdin_ctrl: |
| 518 | set_term_echo(sys.stdin.fileno(), True) |
| 519 | sys.exit(1) |
| 520 | skip_reason = None |
| 521 | try: |
| 522 | if is_long_duration_test(t) and not args.long: |
| 523 | raise HwsimSkip("Skip test case with long duration due to --long not specified") |
| 524 | if t.__code__.co_argcount > 2: |
| 525 | params = {} |
| 526 | params['logdir'] = args.logdir |
| 527 | params['name'] = name |
| 528 | params['prefix'] = os.path.join(args.logdir, name) |
| 529 | t(dev, apdev, params) |
| 530 | elif t.__code__.co_argcount > 1: |
| 531 | t(dev, apdev) |
| 532 | else: |
| 533 | t(dev) |
| 534 | result = "PASS" |
| 535 | if check_country_00: |
| 536 | for d in dev: |
| 537 | country = d.get_driver_status_field("country") |
| 538 | if country is None: |
| 539 | logger.info(d.ifname + ": Could not fetch country code after the test case run") |
| 540 | elif country != "00": |
| 541 | d.dump_monitor() |
| 542 | logger.info(d.ifname + ": Country code not reset back to 00: is " + country) |
| 543 | print(d.ifname + ": Country code not reset back to 00: is " + country) |
| 544 | result = "FAIL" |
| 545 | |
| 546 | # Try to wait for cfg80211 regulatory state to |
| 547 | # clear. |
| 548 | d.cmd_execute(['iw', 'reg', 'set', '00']) |
| 549 | for i in range(5): |
| 550 | time.sleep(1) |
| 551 | country = d.get_driver_status_field("country") |
| 552 | if country == "00": |
| 553 | break |
| 554 | if country == "00": |
| 555 | print(d.ifname + ": Country code cleared back to 00") |
| 556 | logger.info(d.ifname + ": Country code cleared back to 00") |
| 557 | else: |
| 558 | print("Country code remains set - expect following test cases to fail") |
| 559 | logger.info("Country code remains set - expect following test cases to fail") |
| 560 | break |
| 561 | except HwsimSkip as e: |
| 562 | logger.info("Skip test case: %s" % e) |
| 563 | skip_reason = e |
| 564 | result = "SKIP" |
| 565 | except NameError as e: |
| 566 | import traceback |
| 567 | logger.info(e) |
| 568 | traceback.print_exc() |
| 569 | result = "FAIL" |
| 570 | except Exception as e: |
| 571 | import traceback |
| 572 | logger.info(e) |
| 573 | traceback.print_exc() |
| 574 | if args.loglevel == logging.WARNING: |
| 575 | print("Exception: " + str(e)) |
| 576 | result = "FAIL" |
| 577 | |
| 578 | # Work around some objects having __del__, we really should |
| 579 | # use context managers, but that's complex. Doing this here |
| 580 | # will (on cpython at least) at make sure those objects that |
| 581 | # are no longer reachable will be collected now, invoking |
| 582 | # __del__() on them. This then ensures that __del__() isn't |
| 583 | # invoked at a bad time, e.g. causing recursion in locking. |
| 584 | gc.collect() |
| 585 | |
| 586 | open('/dev/kmsg', 'w').write('TEST-STOP %s @%.6f\n' % (name, time.time())) |
| 587 | for d in dev: |
| 588 | try: |
| 589 | d.dump_monitor() |
| 590 | d.request("NOTE TEST-STOP " + name) |
| 591 | except Exception as e: |
| 592 | logger.info("Failed to issue TEST-STOP after {} for {}".format(name, d.ifname)) |
| 593 | logger.info(e) |
| 594 | result = "FAIL" |
| 595 | if args.no_reset: |
| 596 | print("Leaving devices in current state") |
| 597 | else: |
| 598 | reset_ok = reset_devs(dev, apdev) |
| 599 | wpas = None |
| 600 | try: |
| 601 | wpas = WpaSupplicant(global_iface="/tmp/wpas-wlan5", |
| 602 | monitor=False) |
| 603 | rename_log(args.logdir, 'log5', name, wpas) |
| 604 | if not args.no_reset: |
| 605 | wpas.remove_ifname() |
| 606 | except Exception as e: |
| 607 | pass |
| 608 | if wpas: |
| 609 | wpas.close_ctrl() |
| 610 | del wpas |
| 611 | |
| 612 | for i in range(0, 3): |
| 613 | rename_log(args.logdir, 'log' + str(i), name, dev[i]) |
| 614 | try: |
| 615 | hapd = HostapdGlobal() |
| 616 | except Exception as e: |
| 617 | print("Failed to connect to hostapd interface") |
| 618 | print(str(e)) |
| 619 | reset_ok = False |
| 620 | result = "FAIL" |
| 621 | hapd = None |
| 622 | rename_log(args.logdir, 'hostapd', name, hapd) |
| 623 | if hapd: |
| 624 | del hapd |
| 625 | hapd = None |
| 626 | |
| 627 | # Use None here since this instance of Wlantest() will never be |
| 628 | # used for remote host hwsim tests on real hardware. |
| 629 | Wlantest.setup(None) |
| 630 | wt = Wlantest() |
| 631 | rename_log(args.logdir, 'hwsim0.pcapng', name, wt) |
| 632 | rename_log(args.logdir, 'hwsim0', name, wt) |
| 633 | if os.path.exists(os.path.join(args.logdir, 'fst-wpa_supplicant')): |
| 634 | rename_log(args.logdir, 'fst-wpa_supplicant', name, None) |
| 635 | if os.path.exists(os.path.join(args.logdir, 'fst-hostapd')): |
| 636 | rename_log(args.logdir, 'fst-hostapd', name, None) |
| 637 | if os.path.exists(os.path.join(args.logdir, 'wmediumd.log')): |
| 638 | rename_log(args.logdir, 'wmediumd.log', name, None) |
| 639 | |
| 640 | end = datetime.now() |
| 641 | diff = end - start |
| 642 | |
| 643 | if result == 'PASS' and args.dmesg: |
| 644 | if not check_kernel(os.path.join(args.logdir, name + '.dmesg')): |
| 645 | logger.info("Kernel issue found in dmesg - mark test failed") |
| 646 | result = 'FAIL' |
| 647 | |
| 648 | if result == 'PASS': |
| 649 | passed.append(name) |
| 650 | elif result == 'SKIP': |
| 651 | skipped.append(name) |
| 652 | else: |
| 653 | failed.append(name) |
| 654 | |
| 655 | report(conn, args.prefill, args.build, args.commit, run, name, result, |
| 656 | diff.total_seconds(), args.logdir) |
| 657 | result = "{} {} {} {}".format(result, name, diff.total_seconds(), end) |
| 658 | logger.info(result) |
| 659 | if args.loglevel == logging.WARNING: |
| 660 | print(result) |
| 661 | if skip_reason: |
| 662 | print("REASON", skip_reason) |
| 663 | sys.stdout.flush() |
| 664 | |
| 665 | if not reset_ok: |
| 666 | print("Terminating early due to device reset failure") |
| 667 | break |
| 668 | if args.stdin_ctrl: |
| 669 | set_term_echo(sys.stdin.fileno(), True) |
| 670 | |
| 671 | if log_handler: |
| 672 | log_handler.stream.close() |
| 673 | logger.removeHandler(log_handler) |
| 674 | file_name = os.path.join(args.logdir, 'run-tests.log') |
| 675 | log_handler = logging.FileHandler(file_name, encoding='utf-8') |
| 676 | log_handler.setLevel(logging.DEBUG) |
| 677 | log_handler.setFormatter(log_formatter) |
| 678 | logger.addHandler(log_handler) |
| 679 | |
| 680 | if conn: |
| 681 | conn.close() |
| 682 | |
| 683 | if len(failed): |
| 684 | logger.info("passed {} test case(s)".format(len(passed))) |
| 685 | logger.info("skipped {} test case(s)".format(len(skipped))) |
| 686 | logger.info("failed tests: " + ' '.join(failed)) |
| 687 | if args.loglevel == logging.WARNING: |
| 688 | print("failed tests: " + ' '.join(failed)) |
| 689 | sys.exit(1) |
| 690 | logger.info("passed all {} test case(s)".format(len(passed))) |
| 691 | if len(skipped): |
| 692 | logger.info("skipped {} test case(s)".format(len(skipped))) |
| 693 | if args.loglevel == logging.WARNING: |
| 694 | print("passed all {} test case(s)".format(len(passed))) |
| 695 | if len(skipped): |
| 696 | print("skipped {} test case(s)".format(len(skipped))) |
| 697 | |
| 698 | if __name__ == "__main__": |
| 699 | main() |