eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

run-tests (28187B)


      1 #!/usr/bin/python3
      2 
      3 import os
      4 import shutil
      5 import sys
      6 import subprocess
      7 import atexit
      8 import time
      9 import unittest
     10 import importlib
     11 from unittest.result import TestResult
     12 import multiprocessing
     13 import re
     14 import traceback
     15 
     16 from configparser import ConfigParser
     17 from prettytable import PrettyTable
     18 from termcolor import colored
     19 from glob import glob
     20 from collections import namedtuple
     21 import dbus.mainloop.glib
     22 from gi.repository import GLib
     23 
     24 from runner import Runner
     25 from utils import Process, Namespace, BarChart
     26 
     27 config = None
     28 intf_id = 0
     29 
     30 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
     31 
     32 def dbg(*s, **kwargs):
     33 	'''
     34 		Allows prints if stdout has been re-directed
     35 	'''
     36 	print(*s, **kwargs, file=sys.__stdout__)
     37 
     38 def write_results(file, results):
     39 	with open(file, 'w') as f:
     40 		for test, results in results.items():
     41 			if results.failures != 0 or results.errors != 0:
     42 				f.write('%s:FAIL\n' % test)
     43 			else:
     44 				f.write('%s:PASS\n' % test)
     45 
     46 def exit_vm():
     47 	if config:
     48 		for p in Process.get_all():
     49 			print("Process %s still running!" % p.args[0])
     50 			p.kill()
     51 
     52 		if config.ctx and config.ctx.results:
     53 			success = print_results(config.ctx.results, int(config.ctx.args.timeout))
     54 
     55 			if config.ctx.args.result:
     56 				write_results(config.ctx.args.result, config.ctx.results)
     57 
     58 	os.sync()
     59 
     60 	runner.stop()
     61 
     62 class Interface:
     63 	def __init__(self, name, config, ns):
     64 		self.name = name
     65 		self.ctrl_interface = '/var/run/hostapd/' + name
     66 		self.config = config
     67 		self.ns = ns
     68 
     69 	def __del__(self):
     70 		Process(['iw', 'dev', self.name, 'del'], namespace=self.ns.name).wait()
     71 
     72 	def set_interface_state(self, state):
     73 		Process(['ip', 'link', 'set', self.name, state], namespace=self.ns.name).wait()
     74 
     75 class Radio:
     76 	def __init__(self, name, default_ns, used_by='iwd'):
     77 		self.name = name
     78 		# hostapd will reset this if this radio is used by it
     79 		self.use = used_by
     80 		self.interface = None
     81 		self.ns = default_ns
     82 
     83 	def __del__(self):
     84 		print("Removing radio %s" % self.name)
     85 		self.interface = None
     86 
     87 	def set_namespace(self, ns):
     88 		self.ns = ns
     89 		Process(['iw', 'phy', self.name, 'set', 'netns', 'name', ns.name]).wait()
     90 
     91 	def create_interface(self, config, use):
     92 		global intf_id
     93 
     94 		ifname = 'wln%s' % intf_id
     95 
     96 		intf_id += 1
     97 
     98 		self.interface = Interface(ifname, config, self.ns)
     99 		self.use = use
    100 
    101 		Process(['iw', 'phy', self.name, 'interface', 'add', ifname,
    102 				'type', 'managed'], namespace=self.ns.name).wait()
    103 
    104 		return self.interface
    105 
    106 	def __str__(self):
    107 		ret = self.name + ':\n'
    108 		ret += '\tUsed By: %s' % self.use
    109 		if self.interface:
    110 			ret += ' (%s)' % self.interface.name
    111 		if self.ns is not None:
    112 			ret += ' (ns=%s)' % self.ns.name
    113 
    114 		ret += '\n'
    115 
    116 		return ret
    117 
    118 class VirtualRadio(Radio):
    119 	'''
    120 		A subclass of 'Radio' specific to mac80211_hwsim radios.
    121 
    122 		TODO: Using D-Bus to create and destroy radios is more desirable
    123 		than the command line.
    124 	'''
    125 
    126 	def __init__(self, name, default_ns, cfg=None):
    127 		global config
    128 
    129 		self.disable_cipher = None
    130 		self.disable_iftype = None
    131 
    132 		self.hwsim = config.hwsim.Hwsim()
    133 
    134 		used_by = 'iwd'
    135 
    136 		if cfg:
    137 			self.disable_iftype = cfg.get('iftype_disable', None)
    138 			self.disable_cipher = cfg.get('cipher_disable', None)
    139 			used_by = cfg.get('reserve', 'iwd')
    140 
    141 		self._radio = self.hwsim.radios.create(name, p2p_device=True,
    142 					iftype_disable=self.disable_iftype,
    143 					cipher_disable=self.disable_cipher)
    144 
    145 		super().__init__(self._radio.name, default_ns, used_by)
    146 
    147 	def __del__(self):
    148 		super().__del__()
    149 
    150 		# If the radio was moved into a namespace this will fail
    151 		try:
    152 			self._radio.remove()
    153 		except:
    154 			pass
    155 
    156 		self._radio = None
    157 
    158 	def __str__(self):
    159 		ret = super().__str__()
    160 
    161 		if self.disable_iftype:
    162 			ret += '\tDisabled interface types: %s\n' % self.disable_iftype
    163 
    164 		if self.disable_cipher:
    165 			ret += '\tDisabled ciphers: %s\n' % self.disable_cipher
    166 
    167 		ret += '\tPath: %s' % self._radio.path
    168 
    169 		ret += '\n'
    170 
    171 		return ret
    172 
    173 class HostapdInstance:
    174 	'''
    175 		A single instance of hostapd. In reality all hostapd instances
    176 		are started as a single process. This class just makes things
    177 		convenient for communicating with one of the hostapd APs.
    178 	'''
    179 	def __init__(self, config, radio):
    180 		self.radio = radio
    181 		self.config = config
    182 		self.cli = None
    183 
    184 		self.intf = radio.create_interface(self.config, 'hostapd')
    185 		self.intf.set_interface_state('up')
    186 
    187 	def __del__(self):
    188 		print("Removing HostapdInstance %s" % self.config)
    189 		self.intf.set_interface_state('down')
    190 		self.radio = None
    191 		self.intf = None
    192 
    193 	def __str__(self):
    194 		ret = 'Hostapd (%s)\n' % self.intf.name
    195 		ret += '\tConfig: %s\n' % self.config
    196 
    197 		return ret
    198 
    199 class Hostapd:
    200 	'''
    201 		A set of running hostapd instances. This is really just a single
    202 		process since hostapd can be started with multiple config files.
    203 	'''
    204 	def __init__(self, ns, radios, configs, radius):
    205 		if len(configs) != len(radios):
    206 			raise Exception("Config (%d) and radio (%d) list length not equal" % \
    207 						(len(configs), len(radios)))
    208 
    209 		print("Initializing hostapd instances")
    210 
    211 		Process(['ip', 'link', 'set', 'eth0', 'up']).wait()
    212 		Process(['ip', 'link', 'set', 'eth1', 'up']).wait()
    213 
    214 		self.ns = ns
    215 		self.global_ctrl_iface = '/var/run/hostapd/ctrl' + (str(ns.name) if ns.name else 'main')
    216 		self.instances = [HostapdInstance(c, r) for c, r in zip(configs, radios)]
    217 
    218 		ifaces = [rad.interface.name for rad in radios]
    219 		ifaces = ','.join(ifaces)
    220 
    221 		args = ['hostapd', '-g', self.global_ctrl_iface]
    222 
    223 		if ifaces:
    224 			args.extend(['-i', ifaces])
    225 
    226 		#
    227 		# Config files should already be present in /tmp. This appends
    228 		# ctrl_interface and does any variable replacement. Currently
    229 		# this is just any $ifaceN occurrences.
    230 		#
    231 		for c in configs:
    232 			full_path = '/tmp/%s' % c
    233 			args.append(full_path)
    234 
    235 			self._rewrite_config(full_path)
    236 
    237 		if radius:
    238 			args.append(radius)
    239 
    240 		if Process.is_verbose('hostapd'):
    241 			args.append('-d')
    242 
    243 		self.process = Process(args, namespace=ns.name)
    244 
    245 		self.process.wait_for_socket(self.global_ctrl_iface, 30)
    246 
    247 		for hapd in self.instances:
    248 			self.process.wait_for_socket(hapd.intf.ctrl_interface, 30)
    249 
    250 	def attach_cli(self):
    251 		global config
    252 
    253 		for hapd in self.instances:
    254 			hapd.cli = config.hostapd.HostapdCLI(config=hapd.config)
    255 
    256 	def _rewrite_config(self, config):
    257 		'''
    258 			Replaces any $ifaceN values with the correct interface
    259 			names as well as appends the ctrl_interface path to
    260 			the config file.
    261 		'''
    262 		with open(config, 'r+') as f:
    263 			data = f.read()
    264 			to_replace = []
    265 			for match in re.finditer(r'\$iface[0-9]+', data):
    266 				tag = data[match.start():match.end()]
    267 				idx = tag.split('iface')[1]
    268 
    269 				to_replace.append((tag, self.instances[int(idx)].intf.name))
    270 
    271 			for r in to_replace:
    272 				data = data.replace(r[0], r[1], 1)
    273 
    274 			data += '\nctrl_interface=/var/run/hostapd\n'
    275 
    276 			f.write(data)
    277 
    278 	def __getitem__(self, config):
    279 		if not config:
    280 			return self.instances[0]
    281 
    282 		for hapd in self.instances:
    283 			if hapd.config == config:
    284 				return hapd
    285 
    286 		return None
    287 
    288 	def __del__(self):
    289 		print("Removing Hostapd")
    290 		try:
    291 			os.remove(self.global_ctrl_iface)
    292 		except:
    293 			print("Failed to remove %s" % self.global_ctrl_iface)
    294 
    295 		for hapd in self.instances:
    296 			GLib.source_remove(hapd.cli.io_watch)
    297 
    298 		# Hostapd may have already been stopped
    299 		if self.process:
    300 			self.process.kill()
    301 
    302 		# Hostapd creates simdb sockets for EAP-SIM/AKA tests but does not
    303 		# clean them up.
    304 		for f in glob("/tmp/eap_sim_db*"):
    305 			os.remove(f)
    306 
    307 class TestContext(Namespace):
    308 	'''
    309 		Contains all information for a given set of tests being run
    310 		such as processes, radios, interfaces and test results.
    311 	'''
    312 	def __init__(self, args):
    313 		self.name = None
    314 		self.args = args
    315 		self.hw_config = None
    316 		self.hostapd = None
    317 		self.wpas_interfaces = None
    318 		self.radios = []
    319 		self.results = {}
    320 		self.namespaces = []
    321 		self._last_mem_available = 0
    322 		self._mem_chart = BarChart()
    323 
    324 	def start_dbus_monitor(self):
    325 		if not Process.is_verbose('dbus-monitor'):
    326 			return
    327 
    328 		self.start_process(['dbus-monitor', '--address', self.dbus_address])
    329 
    330 	def start_haveged(self):
    331 		self.start_process(['haveged', '-F'])
    332 
    333 	def create_radios(self):
    334 		setup = self.hw_config['SETUP']
    335 		nradios = int(setup['num_radios'])
    336 		args = ['hwsim']
    337 
    338 		if self.hw_config['SETUP'].get('hwsim_medium', 'no') in ['no', '0', 'false']:
    339 			# register hwsim as medium
    340 			args.extend(['--no-register'])
    341 
    342 		proc = self.start_process(args)
    343 		proc.wait_for_service(self, 'net.connman.hwsim', 20)
    344 
    345 		for i in range(nradios):
    346 			name = 'rad%u' % i
    347 
    348 			# Get any [radX] sections. These are for configuring
    349 			# any special radios. This no longer requires a
    350 			# radio_conf list, we just assume radios start rad0
    351 			# and increment.
    352 			rad_config = None
    353 			if self.hw_config.has_section(name):
    354 				rad_config = self.hw_config[name]
    355 
    356 			self.radios.append(VirtualRadio(name, self, rad_config))
    357 
    358 	def discover_radios(self):
    359 		import pyroute2
    360 
    361 		phys = []
    362 
    363 		try:
    364 			iw = pyroute2.iwutil.IW()
    365 		except:
    366 			iw = pyroute2.IW()
    367 
    368 		attrs = [phy['attrs'] for phy in iw.list_wiphy()]
    369 
    370 		for attr in attrs:
    371 			for key, value in attr:
    372 				if key == 'NL80211_ATTR_WIPHY_NAME':
    373 					if value not in phys:
    374 						phys.append(value)
    375 					break
    376 
    377 		print('Discovered radios: %s' % str(phys))
    378 		self.radios = [Radio(name, self) for name in phys]
    379 
    380 	def start_radios(self):
    381 		reg_domain = self.hw_config['SETUP'].get('reg_domain', None)
    382 		if reg_domain:
    383 			Process(['iw', 'reg', 'set', reg_domain]).wait()
    384 
    385 		if self.args.hw:
    386 			self.discover_radios()
    387 		else:
    388 			self.create_radios()
    389 
    390 	def start_hostapd(self):
    391 		if not 'HOSTAPD' in self.hw_config:
    392 			return
    393 
    394 		settings = self.hw_config['HOSTAPD']
    395 
    396 		if self.args.hw:
    397 			# Just grab the first N radios. It gets rather
    398 			# complicated trying to map radX radios specified in
    399 			# hw.conf so any passed through physical adapters are
    400 			# just given to hostapd/IWD as they appear during
    401 			# discovery.
    402 			#
    403 			# TODO: It may be desirable to map PCI/USB adapters to
    404 			#       specific radX radios specified in the config but
    405 			#       there are really 2 separate use cases here.
    406 			#       1. You want to test a *specific* radio with IWD
    407 			#          or hostapd. For this you would want radX
    408 			#          to map to a specific radio
    409 			#       2. You have many adapters in use to run multiple
    410 			#          tests. In this case you would not care what
    411 			#          was using each radio, just that there was
    412 			#          enough to run all tests.
    413 			hapd_configs = [conf for rad, conf in settings.items() if rad != 'radius_server']
    414 			hapd_processes = [(self, self.radios[:len(hapd_configs)], hapd_configs)]
    415 		else:
    416 			hapd_processes = []
    417 			for ns in [self] + self.namespaces:
    418 				ns_radios = [rad for rad in ns.radios if rad.name in settings]
    419 				if len(ns_radios):
    420 					ns_configs = [settings[rad.name] for rad in ns_radios]
    421 					hapd_processes.append((ns, ns_radios, ns_configs))
    422 			if not hapd_processes:
    423 				hapd_processes.append((self, [], []))
    424 
    425 		radius_config = settings.get('radius_server', None)
    426 
    427 		self.hostapd = [Hostapd(ns, radios, configs, radius_config)
    428 				for ns, radios, configs in hapd_processes]
    429 
    430 		for hapd in self.hostapd:
    431 			hapd.attach_cli()
    432 
    433 	def get_frequencies(self):
    434 		frequencies = []
    435 
    436 		for hapd in self.hostapd:
    437 			frequencies += [instance.cli.frequency for instance in hapd.instances]
    438 
    439 		return frequencies
    440 
    441 	def get_hapd_instance(self, config=None):
    442 		instances = [i for hapd in self.hostapd for i in hapd.instances]
    443 
    444 		if config is None:
    445 			return instances[0]
    446 
    447 		for hapd in instances:
    448 			if hapd.config == config:
    449 				return hapd
    450 
    451 	def start_wpas_interfaces(self):
    452 		if 'WPA_SUPPLICANT' not in self.hw_config:
    453 			return
    454 
    455 		if not shutil.which('wpa_supplicant'):
    456 			print('wpa_supplicant not found, dependent tests will be skipped')
    457 			return
    458 
    459 		settings = self.hw_config['WPA_SUPPLICANT']
    460 
    461 		if self.args.hw:
    462 			nradios = len(settings.items())
    463 
    464 			wpas_radios = self.radios[:nradios]
    465 			self.wpas_interfaces = []
    466 
    467 			#
    468 			# Physical radios most likely will use a different name
    469 			# than 'rad#' but the config file is referenced by these
    470 			# 'rad#' names. Iterate through both the settings and
    471 			# physical radios to create interfaces associated with
    472 			# each config file.
    473 			#
    474 			for vrad, hwrad in zip(settings.items(), wpas_radios):
    475 				self.wpas_interfaces.append(hwrad.create_interface(vrad[1], 'wpas'))
    476 
    477 		else:
    478 			wpas_radios = [rad for rad in self.radios if rad.name in settings]
    479 			self.wpas_interfaces = [rad.create_interface(settings[rad.name], 'wpas') \
    480 						for rad in wpas_radios]
    481 
    482 	def start_ofono(self):
    483 		sim_keys = self.hw_config['SETUP'].get('sim_keys', None)
    484 		if not sim_keys:
    485 			print("Ofono not required")
    486 			return
    487 		elif sim_keys != 'ofono':
    488 			os.environ['IWD_SIM_KEYS'] = sim_keys
    489 			return
    490 
    491 		if not shutil.which('ofonod') or not shutil.which('phonesim'):
    492 			print("Ofono or Phonesim not found, skipping test")
    493 			return
    494 
    495 		os.environ['OFONO_PHONESIM_CONFIG'] = '/tmp/phonesim.conf'
    496 
    497 		phonesim_args = ['phonesim', '-p', '12345', '/usr/share/phonesim/default.xml']
    498 
    499 		self.start_process(phonesim_args)
    500 
    501 		#
    502 		# TODO:
    503 		# Is there something to wait for? Without this phonesim rejects
    504 		# connections on all but the fist test.
    505 		#
    506 		time.sleep(3)
    507 
    508 		ofono_args = ['ofonod', '-n', '--plugin=atmodem,phonesim']
    509 		if Process.is_verbose('ofonod'):
    510 			ofono_args.append('-d')
    511 
    512 		self.start_process(ofono_args)
    513 
    514 		print("Ofono started")
    515 
    516 	def create_namespaces(self):
    517 		if not self.hw_config.has_section('NameSpaces'):
    518 			return
    519 
    520 		for key, value in self.hw_config.items('NameSpaces'):
    521 			radio_names = value.split(',')
    522 			# Gather up radio objects for this namespace
    523 			radios = [rad for rad in self.radios if rad.name in radio_names]
    524 
    525 			# Remove radios from 'root' namespace
    526 			self.radios = list(set(self.radios) - set(radios))
    527 
    528 			self.namespaces.append(Namespace(self.args, key, radios))
    529 
    530 	def get_namespace(self, ns):
    531 		for n in self.namespaces:
    532 			if n.name == ns:
    533 				return n
    534 
    535 		return None
    536 
    537 	def stop_test_processes(self):
    538 		for n in self.namespaces:
    539 			n.reset()
    540 
    541 		self.namespaces = []
    542 		self.hostapd = None
    543 		self.wpas_interfaces = None
    544 
    545 		self.reset()
    546 
    547 	def meminfo_to_dict(self):
    548 		def removesuffix(string, suffix):
    549 			if string.endswith(suffix):
    550 				return string[:-len(suffix)]
    551 			return string
    552 
    553 		ret = {}
    554 
    555 		with open('/proc/meminfo', 'r') as f:
    556 			data = f.read().strip().split('\n')
    557 
    558 		for l in data:
    559 			entry = l.split(':')
    560 			ret[entry[0]] = int(removesuffix(entry[1], 'kB'))
    561 
    562 		return ret
    563 
    564 	def __str__(self):
    565 		ret = 'Arguments:\n'
    566 		for arg in vars(self.args):
    567 			ret += '\t --%s %s\n' % (arg, str(getattr(self.args, arg)))
    568 
    569 		if self.hostapd:
    570 			for hapd in self.hostapd:
    571 				ret += 'Hostapd (ns=%s):\n' % (hapd.ns.name,)
    572 				for h in hapd.instances:
    573 					ret += '\t%s\n' % (str(h),)
    574 		else:
    575 			ret += 'Hostapd:\n'
    576 			ret += '\tNo Hostapd instances\n'
    577 
    578 		info = self.meminfo_to_dict()
    579 		self._mem_chart.add_value(info['MemAvailable'])
    580 
    581 		ret += 'Available Memory: %u kB\n' % info['MemAvailable']
    582 		ret += 'Last Test Delta: %+d kB\n' % (info['MemAvailable'] - self._last_mem_available)
    583 		ret += 'Per-test Usage:\n'
    584 		ret += str(self._mem_chart)
    585 
    586 		self._last_mem_available = info['MemAvailable']
    587 
    588 		ret += super().__str__()
    589 
    590 		for n in self.namespaces:
    591 			ret += n.__str__()
    592 
    593 		return ret
    594 
    595 def build_unit_list(args):
    596 	'''
    597 		Build list of unit tests based on passed arguments. This first
    598 		checks for literal names provided in the arguments, then if
    599 		no matches were found, checks for a glob match.
    600 	'''
    601 	tests = []
    602 	test_root = args.testhome + '/unit'
    603 
    604 	for unit in args.unit_tests.split(','):
    605 		path = '%s/%s' % (test_root, unit)
    606 		if os.access(unit, os.X_OK):
    607 			tests.append(unit)
    608 		elif os.access(path, os.X_OK):
    609 			tests.append(path)
    610 		else:
    611 			# Full list or glob, first build up valid list of tests
    612 			matches = glob(path)
    613 			if matches == []:
    614 				raise Exception("Could not find test %s" % unit)
    615 
    616 			matches = [exe for exe in matches if os.access(exe, os.X_OK)]
    617 
    618 			tests.extend(matches)
    619 
    620 	return sorted(tests)
    621 
    622 def build_test_list(args):
    623 	'''
    624 		Build list of auto test directories based on passed arguments.
    625 		First check for absolute paths, then look in <iwd>/autotests,
    626 		then glob match.
    627 	'''
    628 	tests = []
    629 	test_root = args.testhome + '/autotests'
    630 
    631 	# Run all tests
    632 	if not args.autotests:
    633 		# Get list of all autotests (committed in git)
    634 		Process(['git', 'config', '--system', '--add', 'safe.directory',
    635 					os.path.normpath(args.testhome)]).wait()
    636 		tests = os.popen('git -C %s ls-files autotests/ | cut -f2 -d"/" \
    637 					| grep "^test" | uniq' % args.testhome).read() \
    638 					.strip().split('\n')
    639 		tests = [test_root + '/' + t for t in tests]
    640 	else:
    641 		print("Generating partial test list")
    642 
    643 		full_list = sorted(os.listdir(test_root))
    644 
    645 		for t in args.autotests.split(','):
    646 			path = '%s/%s' % (test_root, t)
    647 			if t.endswith('+'):
    648 				t = t.split('+')[0]
    649 				i = full_list.index(t)
    650 
    651 				tests = [test_root + '/' + x for x in full_list[i:] \
    652 							if x.startswith('test')]
    653 			elif os.path.exists(t):
    654 				if t not in tests:
    655 					tests.append(t)
    656 			elif os.path.exists(path):
    657 				if path not in tests:
    658 					tests.append(path)
    659 			else:
    660 				matches = glob(path)
    661 				if matches == []:
    662 					raise Exception("Could not find test %s" % t)
    663 
    664 				tests.extend(list(set(matches) - set(tests)))
    665 
    666 	return sorted(tests)
    667 
    668 SimpleResult = namedtuple('SimpleResult', 'run failures errors skipped time')
    669 
    670 def start_test(ctx, subtests, rqueue):
    671 	'''
    672 		Run an individual test. 'subtests' are parsed prior to calling
    673 		but these effectively make up a single test. 'rqueue' is the
    674 		results queue which is required since this is using
    675 		multiprocessing.
    676 	'''
    677 	run = 0
    678 	errors = 0
    679 	failures = 0
    680 	skipped = 0
    681 
    682 	start = time.time()
    683 	#
    684 	# Iterate through each individual python test.
    685 	#
    686 	for s in subtests:
    687 		loader = unittest.TestLoader()
    688 		try:
    689 			module = importlib.import_module(os.path.splitext(s)[0])
    690 		except OSError as e:
    691 			dbg(subprocess.check_output("cat /proc/buddyinfo", shell=True).decode('utf-8'))
    692 			dbg(subprocess.check_output("dmesg | tail -80", shell=True).decode('utf-8'))
    693 			print(ctx)
    694 			raise e
    695 
    696 		subtest = loader.loadTestsFromModule(module)
    697 
    698 		# The test suite is being (ab)used to get a bit more granularity
    699 		# with individual tests. The 'normal' way to use unittest is to
    700 		# just create a test suite and run them. The problem here is that
    701 		# test results are queued and printed at the very end so its
    702 		# difficult to know *where* a test failed (python gives a stack
    703 		# trace but printing the exception/failure immediately shows
    704 		# where in the debug logs something failed). More so if there are
    705 		# several test functions inside a single python file they run
    706 		# as a single test and it is difficult (again) to know where
    707 		# something failed.
    708 
    709 		# Iterating through each python test file
    710 		for test in subtest:
    711 			limit_funcs = []
    712 
    713 			if ctx.args.sub_tests:
    714 				for i in ctx.args.sub_tests:
    715 					if len(i.split('.')) == 2:
    716 						limit_funcs.append(i.split('.')[1])
    717 
    718 			# Iterating through individual test functions inside a
    719 			# Test() class. Due to the nature of unittest we have
    720 			# to jump through some hoops to set up the test class
    721 			# only once by turning the enumeration into a list, then
    722 			# enumerating (again) to keep track of the index (just
    723 			# enumerating the test class doesn't allow len() because
    724 			# it is not a list).
    725 			tlist = list(enumerate(test))
    726 			for index, t in enumerate(tlist):
    727 				# enumerate is returning a tuple, index 1 is our
    728 				# actual object.
    729 				t = t[1]
    730 
    731 				func, file = str(t).split(' ')
    732 				#
    733 				# TODO: There may be a better way of doing this
    734 				# but stringifying the test class gives us a string:
    735 				# <function> (<file>.<class>)
    736 				#
    737 				file = file.strip('()').split('.')[0] + '.py'
    738 
    739 				# Create an empty result here in case the test fails
    740 				result = TestResult()
    741 
    742 				try:
    743 					skip = len(limit_funcs) > 0 and func not in limit_funcs
    744 
    745 					# Set up class only on first test
    746 					if index == 0:
    747 						if not skip:
    748 							dbg("%s\n\t%s RUNNING" % (file, str(func)), end='')
    749 						t.setUpClass()
    750 					else:
    751 						if not skip:
    752 							dbg("\t%s RUNNING" % str(func), end='')
    753 
    754 					sys.__stdout__.flush()
    755 
    756 					name = os.path.basename(os.getcwd())
    757 
    758 					Process.write_separators(name, "\n====== %s:%s:%s ======\n\n" %
    759 									(name, file, func))
    760 
    761 					if not skip:
    762 						# Run test (setUp/tearDown run automatically)
    763 						result = t()
    764 
    765 					# Tear down class only on last test
    766 					if index == len(tlist) - 1:
    767 						t.tearDownClass()
    768 
    769 					if skip:
    770 						continue
    771 				except unittest.SkipTest as e:
    772 					result.skipped.append(t)
    773 				except Exception as e:
    774 					dbg('\n%s threw an uncaught exception:' % func)
    775 					traceback.print_exc(file=sys.__stdout__)
    776 
    777 				run += result.testsRun
    778 				errors += len(result.errors)
    779 				failures += len(result.failures)
    780 				skipped += len(result.skipped)
    781 
    782 				if len(result.skipped) > 0:
    783 					dbg(colored(" SKIPPED", "cyan"))
    784 				elif run == 0 or len(result.errors) > 0 or len(result.failures) > 0:
    785 					dbg(colored(" FAILED", "red"))
    786 					for e in result.errors:
    787 						dbg(e[1])
    788 					for f in result.failures:
    789 						dbg(f[1])
    790 				else:
    791 					dbg(colored(" PASSED", "green"))
    792 
    793 		# Prevents future test modules with the same name (e.g.
    794 		# connection_test.py) from being loaded from the cache
    795 		sys.modules.pop(module.__name__)
    796 
    797 	#
    798 	# The multiprocessing queue is picky with what objects it will serialize
    799 	# and send between processes. Because of this we put the important bits
    800 	# of the result into our own 'SimpleResult' tuple.
    801 	#
    802 	sresult = SimpleResult(run=run, failures=failures, errors=errors,
    803 				skipped=skipped, time=time.time() - start)
    804 	rqueue.put(sresult)
    805 
    806 	# This may not be required since we are manually popping sys.modules
    807 	importlib.invalidate_caches()
    808 
    809 def pre_test(ctx, test, copied):
    810 	'''
    811 		Copy test files, start processes, and any other pre test work.
    812 	'''
    813 	os.chdir(test)
    814 
    815 	dbg("\nStarting %s" % colored(os.path.basename(test), "white", attrs=['bold']))
    816 	if not os.path.exists(test + '/hw.conf'):
    817 		raise Exception("No hw.conf found for %s" % test)
    818 
    819 	ctx.hw_config = ConfigParser()
    820 	ctx.hw_config.read(test + '/hw.conf')
    821 	#
    822 	# We have two types of test files: tests and everything else. Rather
    823 	# than require each test to specify the files needing to be copied to
    824 	# /tmp (previously 'tmpfs_extra_stuff'), we just copy everything which
    825 	# isn't a test. There is really no reason not to do this as any file
    826 	# present in a test directory should be needed by the test.
    827 	#
    828 	# All files
    829 	files = os.listdir(test)
    830 	# Tests (starts or ends with 'test')
    831 	subtests = [f for f in files if f.startswith('test') or \
    832 			os.path.splitext(f)[0].endswith('test')]
    833 	# Everything else (except .py files)
    834 	to_copy = [f for f in list(set(files) - set(subtests)) if not f.endswith('.py') \
    835 								and f != '__pycache__']
    836 	for f in to_copy:
    837 		if os.path.isdir(f):
    838 			shutil.copytree(f, '/tmp/' + f)
    839 		else:
    840 			shutil.copy(f, '/tmp')
    841 		copied.append(f)
    842 
    843 	# Prune down any subtests if needed
    844 	if ctx.args.sub_tests:
    845 		ctx.args.sub_tests = ctx.args.sub_tests.split(',')
    846 
    847 		to_run = [x.split('.')[0] for x in ctx.args.sub_tests]
    848 		pruned = []
    849 
    850 		for s in subtests:
    851 			no_ext = s
    852 			# Handle <file>.<test function> format
    853 			if '.' in s:
    854 				no_ext = s.split('.')[0]
    855 
    856 			if no_ext in to_run:
    857 				pruned.append(no_ext + '.py')
    858 
    859 		subtests = pruned
    860 
    861 	if ctx.args.log:
    862 		ctx.start_process(['iwmon', '--nowiphy'])
    863 	elif ctx.args.monitor:
    864 		ctx.start_process(['iwmon'], outfile=ctx.args.monitor)
    865 
    866 	ctx.start_dbus()
    867 	ctx.start_haveged()
    868 	ctx.start_dbus_monitor()
    869 	ctx.start_radios()
    870 	ctx.create_namespaces()
    871 	ctx.start_hostapd()
    872 	ctx.start_wpas_interfaces()
    873 	ctx.start_ofono()
    874 
    875 	if ctx.hw_config.getboolean('SETUP', 'start_iwd', fallback=True):
    876 		ctx.start_iwd()
    877 
    878 	print(ctx)
    879 
    880 	sys.path.insert(1, test)
    881 
    882 	return sorted(subtests)
    883 
    884 def post_test(ctx, to_copy):
    885 	'''
    886 		Remove copied files, and stop test processes.
    887 	'''
    888 	try:
    889 		for f in to_copy:
    890 			if os.path.isdir('/tmp/' + f):
    891 				shutil.rmtree('/tmp/' + f)
    892 			elif os.path.exists('/tmp/' + f):
    893 				os.remove('/tmp/' + f)
    894 
    895 	except Exception as e:
    896 		print("Exception thrown in post_test")
    897 	finally:
    898 		ctx.stop_test_processes()
    899 
    900 	if ctx.args.valgrind:
    901 		for f in os.listdir('/tmp'):
    902 			if not f.startswith("valgrind.log."):
    903 				continue
    904 
    905 			with open('/tmp/' + f, 'r') as v:
    906 				result = v.read()
    907 
    908 			# Don't print out the result if there were no issues
    909 			if "0 errors from 0 contexts" not in result:
    910 				dbg(result)
    911 				dbg("\n")
    912 
    913 			os.remove('/tmp/' + f)
    914 
    915 	# Special case for when logging is enabled
    916 	if os.path.isfile('/tmp/iwd-tls-debug-server-cert.pem'):
    917 		os.remove('/tmp/iwd-tls-debug-server-cert.pem')
    918 
    919 	allowed = ['phonesim.conf', 'certs', 'secrets', 'iwd']
    920 	for f in [f for f in os.listdir('/tmp') if f not in allowed]:
    921 		dbg("File %s was not cleaned up!" % f)
    922 		try:
    923 			os.remove('/tmp/' + f)
    924 		except:
    925 			pass
    926 
    927 def print_results(results, max_timeout):
    928 	table = PrettyTable(['Test', colored('Passed', 'green'), colored('Failed', 'red'), \
    929 				colored('Skipped', 'cyan'), colored('Time', 'yellow')])
    930 
    931 	total_pass = 0
    932 	total_fail = 0
    933 	total_skip = 0
    934 	total_time = 0
    935 
    936 	for test, result in results.items():
    937 
    938 		if result.time == max_timeout:
    939 			failed = "Timed out"
    940 			passed = "Timed out"
    941 		elif result.time == 0:
    942 			failed = "Exception"
    943 			passed = "Exception"
    944 		else:
    945 			failed = result.failures + result.errors
    946 			passed = result.run - failed
    947 
    948 			total_pass += passed
    949 			total_fail += failed
    950 			total_skip += result.skipped
    951 
    952 		total_time += result.time
    953 
    954 		time = '%.2f' % result.time
    955 
    956 		table.add_row([test, colored(passed, 'green'), colored(failed, 'red'), \
    957 				colored(result.skipped, 'cyan'), colored(time, 'yellow')])
    958 
    959 	total_time = '%.2f' % total_time
    960 
    961 	table.add_row(['Total', colored(total_pass, 'green'), colored(total_fail, 'red'), \
    962 			colored(total_skip, 'cyan'), colored(total_time, 'yellow')])
    963 
    964 	dbg(table)
    965 
    966 	return total_fail == 0
    967 
    968 def run_auto_tests(ctx, args):
    969 	tests = build_test_list(args)
    970 
    971 	for test in tests:
    972 		copied = []
    973 		try:
    974 			subtests = pre_test(ctx, test, copied)
    975 
    976 			if len(subtests) < 1:
    977 				dbg("No tests to run")
    978 				sys.exit()
    979 
    980 			rqueue = multiprocessing.Queue()
    981 			p = multiprocessing.Process(target=start_test, args=(ctx, subtests, rqueue))
    982 			p.start()
    983 			# Rather than time each subtest we just time the total but
    984 			# multiply the default time by the number of tests being run.
    985 			p.join(int(args.timeout) * len(subtests))
    986 
    987 			if p.is_alive():
    988 				# Timeout
    989 				p.terminate()
    990 
    991 				ctx.results[os.path.basename(test)] = SimpleResult(run=0,
    992 								failures=0, errors=0,
    993 								skipped=0, time=int(args.timeout))
    994 			else:
    995 				ctx.results[os.path.basename(test)] = rqueue.get()
    996 
    997 		except Exception as ex:
    998 			dbg("%s threw an uncaught exception" % test)
    999 			traceback.print_exc(file=sys.__stdout__)
   1000 			ctx.results[os.path.basename(test)] = SimpleResult(run=0, failures=0,
   1001 								errors=0, skipped=0, time=0)
   1002 		finally:
   1003 			post_test(ctx, copied)
   1004 
   1005 def run_unit_tests(ctx, args):
   1006 	os.chdir(args.testhome + '/unit')
   1007 	units = build_unit_list(args)
   1008 
   1009 	for u in units:
   1010 		p = ctx.start_process([u]).wait()
   1011 		if p.returncode != 0:
   1012 			dbg("Unit test %s failed" % os.path.basename(u))
   1013 		else:
   1014 			dbg("Unit test %s passed" % os.path.basename(u))
   1015 
   1016 def run_tests(args):
   1017 	global config
   1018 
   1019 	os.chdir(args.testhome)
   1020 
   1021 	#
   1022 	# This allows all autotest utils (iwd/hostapd/etc) to access the
   1023 	# TestContext. Any other module or script (in the same interpreter) can
   1024 	# simply import config.ctx and access all live test information,
   1025 	# start/stop processes, see active radios etc.
   1026 	#
   1027 	config = importlib.import_module('config')
   1028 	config.ctx = TestContext(args)
   1029 
   1030 	# Must import these after config so ctx gets set
   1031 	config.hwsim = importlib.import_module('hwsim')
   1032 	config.hostapd = importlib.import_module('hostapd')
   1033 
   1034 	# Start writing out kernel log
   1035 	config.ctx.start_process(["dmesg", '--follow'])
   1036 
   1037 	if args.unit_tests is None:
   1038 		run_auto_tests(config.ctx, args)
   1039 	else:
   1040 		run_unit_tests(config.ctx, args)
   1041 
   1042 runner = Runner()
   1043 
   1044 atexit.register(exit_vm)
   1045 runner.prepare_environment()
   1046 
   1047 if runner.args.start:
   1048 	ctx = TestContext(runner.args)
   1049 	ctx.start_dbus()
   1050 	os.chdir(runner.args.testhome)
   1051 	os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = ctx.dbus_address
   1052 
   1053 	subprocess.run([runner.args.start])
   1054 else:
   1055 	run_tests(runner.args)
   1056 
   1057 runner.cleanup_environment()