testcase.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. # Test class and utilities for functional tests
  2. #
  3. # Copyright 2018, 2024 Red Hat, Inc.
  4. #
  5. # Original Author (Avocado-based tests):
  6. # Cleber Rosa <crosa@redhat.com>
  7. #
  8. # Adaption for standalone version:
  9. # Thomas Huth <thuth@redhat.com>
  10. #
  11. # This work is licensed under the terms of the GNU GPL, version 2 or
  12. # later. See the COPYING file in the top-level directory.
  13. import logging
  14. import os
  15. from pathlib import Path
  16. import pycotap
  17. import shutil
  18. from subprocess import run
  19. import sys
  20. import tempfile
  21. import unittest
  22. import uuid
  23. from qemu.machine import QEMUMachine
  24. from qemu.utils import kvm_available, tcg_available
  25. from .archive import archive_extract
  26. from .asset import Asset
  27. from .config import BUILD_DIR, dso_suffix
  28. from .uncompress import uncompress
  29. class QemuBaseTest(unittest.TestCase):
  30. arch = None
  31. workdir = None
  32. log = None
  33. logdir = None
  34. '''
  35. @params compressed: filename, Asset, or file-like object to uncompress
  36. @params format: optional compression format (gzip, lzma)
  37. Uncompresses @compressed into the scratch directory.
  38. If @format is None, heuristics will be applied to guess the format
  39. from the filename or Asset URL. @format must be non-None if @uncompressed
  40. is a file-like object.
  41. Returns the fully qualified path to the uncompressed file
  42. '''
  43. def uncompress(self, compressed, format=None):
  44. self.log.debug(f"Uncompress {compressed} format={format}")
  45. if type(compressed) == Asset:
  46. compressed.fetch()
  47. (name, ext) = os.path.splitext(str(compressed))
  48. uncompressed = self.scratch_file(os.path.basename(name))
  49. uncompress(compressed, uncompressed, format)
  50. return uncompressed
  51. '''
  52. @params archive: filename, Asset, or file-like object to extract
  53. @params format: optional archive format (tar, zip, deb, cpio)
  54. @params sub_dir: optional sub-directory to extract into
  55. @params member: optional member file to limit extraction to
  56. Extracts @archive into the scratch directory, or a directory beneath
  57. named by @sub_dir. All files are extracted unless @member specifies
  58. a limit.
  59. If @format is None, heuristics will be applied to guess the format
  60. from the filename or Asset URL. @format must be non-None if @archive
  61. is a file-like object.
  62. If @member is non-None, returns the fully qualified path to @member
  63. '''
  64. def archive_extract(self, archive, format=None, sub_dir=None, member=None):
  65. self.log.debug(f"Extract {archive} format={format}" +
  66. f"sub_dir={sub_dir} member={member}")
  67. if type(archive) == Asset:
  68. archive.fetch()
  69. if sub_dir is None:
  70. archive_extract(archive, self.scratch_file(), format, member)
  71. else:
  72. archive_extract(archive, self.scratch_file(sub_dir),
  73. format, member)
  74. if member is not None:
  75. return self.scratch_file(member)
  76. return None
  77. '''
  78. Create a temporary directory suitable for storing UNIX
  79. socket paths.
  80. Returns: a tempfile.TemporaryDirectory instance
  81. '''
  82. def socket_dir(self):
  83. if self.socketdir is None:
  84. self.socketdir = tempfile.TemporaryDirectory(
  85. prefix="qemu_func_test_sock_")
  86. return self.socketdir
  87. '''
  88. @params args list of zero or more subdirectories or file
  89. Construct a path for accessing a data file located
  90. relative to the source directory that is the root for
  91. functional tests.
  92. @args may be an empty list to reference the root dir
  93. itself, may be a single element to reference a file in
  94. the root directory, or may be multiple elements to
  95. reference a file nested below. The path components
  96. will be joined using the platform appropriate path
  97. separator.
  98. Returns: string representing a file path
  99. '''
  100. def data_file(self, *args):
  101. return str(Path(Path(__file__).parent.parent, *args))
  102. '''
  103. @params args list of zero or more subdirectories or file
  104. Construct a path for accessing a data file located
  105. relative to the build directory root.
  106. @args may be an empty list to reference the build dir
  107. itself, may be a single element to reference a file in
  108. the build directory, or may be multiple elements to
  109. reference a file nested below. The path components
  110. will be joined using the platform appropriate path
  111. separator.
  112. Returns: string representing a file path
  113. '''
  114. def build_file(self, *args):
  115. return str(Path(BUILD_DIR, *args))
  116. '''
  117. @params args list of zero or more subdirectories or file
  118. Construct a path for accessing/creating a scratch file
  119. located relative to a temporary directory dedicated to
  120. this test case. The directory and its contents will be
  121. purged upon completion of the test.
  122. @args may be an empty list to reference the scratch dir
  123. itself, may be a single element to reference a file in
  124. the scratch directory, or may be multiple elements to
  125. reference a file nested below. The path components
  126. will be joined using the platform appropriate path
  127. separator.
  128. Returns: string representing a file path
  129. '''
  130. def scratch_file(self, *args):
  131. return str(Path(self.workdir, *args))
  132. '''
  133. @params args list of zero or more subdirectories or file
  134. Construct a path for accessing/creating a log file
  135. located relative to a temporary directory dedicated to
  136. this test case. The directory and its log files will be
  137. preserved upon completion of the test.
  138. @args may be an empty list to reference the log dir
  139. itself, may be a single element to reference a file in
  140. the log directory, or may be multiple elements to
  141. reference a file nested below. The path components
  142. will be joined using the platform appropriate path
  143. separator.
  144. Returns: string representing a file path
  145. '''
  146. def log_file(self, *args):
  147. return str(Path(self.outputdir, *args))
  148. '''
  149. @params plugin name
  150. Return the full path to the plugin taking into account any host OS
  151. specific suffixes.
  152. '''
  153. def plugin_file(self, plugin_name):
  154. sfx = dso_suffix()
  155. return os.path.join('tests', 'tcg', 'plugins', f'{plugin_name}.{sfx}')
  156. def assets_available(self):
  157. for name, asset in vars(self.__class__).items():
  158. if name.startswith("ASSET_") and type(asset) == Asset:
  159. if not asset.available():
  160. self.log.debug(f"Asset {asset.url} not available")
  161. return False
  162. return True
  163. def setUp(self):
  164. self.qemu_bin = os.getenv('QEMU_TEST_QEMU_BINARY')
  165. self.assertIsNotNone(self.qemu_bin, 'QEMU_TEST_QEMU_BINARY must be set')
  166. self.arch = self.qemu_bin.split('-')[-1]
  167. self.socketdir = None
  168. self.outputdir = self.build_file('tests', 'functional',
  169. self.arch, self.id())
  170. self.workdir = os.path.join(self.outputdir, 'scratch')
  171. os.makedirs(self.workdir, exist_ok=True)
  172. self.log_filename = self.log_file('base.log')
  173. self.log = logging.getLogger('qemu-test')
  174. self.log.setLevel(logging.DEBUG)
  175. self._log_fh = logging.FileHandler(self.log_filename, mode='w')
  176. self._log_fh.setLevel(logging.DEBUG)
  177. fileFormatter = logging.Formatter(
  178. '%(asctime)s - %(levelname)s: %(message)s')
  179. self._log_fh.setFormatter(fileFormatter)
  180. self.log.addHandler(self._log_fh)
  181. # Capture QEMUMachine logging
  182. self.machinelog = logging.getLogger('qemu.machine')
  183. self.machinelog.setLevel(logging.DEBUG)
  184. self.machinelog.addHandler(self._log_fh)
  185. if not self.assets_available():
  186. self.skipTest('One or more assets is not available')
  187. def tearDown(self):
  188. if "QEMU_TEST_KEEP_SCRATCH" not in os.environ:
  189. shutil.rmtree(self.workdir)
  190. if self.socketdir is not None:
  191. shutil.rmtree(self.socketdir.name)
  192. self.socketdir = None
  193. self.machinelog.removeHandler(self._log_fh)
  194. self.log.removeHandler(self._log_fh)
  195. def main():
  196. path = os.path.basename(sys.argv[0])[:-3]
  197. cache = os.environ.get("QEMU_TEST_PRECACHE", None)
  198. if cache is not None:
  199. Asset.precache_suites(path, cache)
  200. return
  201. tr = pycotap.TAPTestRunner(message_log = pycotap.LogMode.LogToError,
  202. test_output_log = pycotap.LogMode.LogToError)
  203. res = unittest.main(module = None, testRunner = tr, exit = False,
  204. argv=["__dummy__", path])
  205. for (test, message) in res.result.errors + res.result.failures:
  206. if hasattr(test, "log_filename"):
  207. print('More information on ' + test.id() + ' could be found here:'
  208. '\n %s' % test.log_filename, file=sys.stderr)
  209. if hasattr(test, 'console_log_name'):
  210. print(' %s' % test.console_log_name, file=sys.stderr)
  211. sys.exit(not res.result.wasSuccessful())
  212. class QemuUserTest(QemuBaseTest):
  213. def setUp(self):
  214. super().setUp()
  215. self._ldpath = []
  216. def add_ldpath(self, ldpath):
  217. self._ldpath.append(os.path.abspath(ldpath))
  218. def run_cmd(self, bin_path, args=[]):
  219. return run([self.qemu_bin]
  220. + ["-L %s" % ldpath for ldpath in self._ldpath]
  221. + [bin_path]
  222. + args,
  223. text=True, capture_output=True)
  224. class QemuSystemTest(QemuBaseTest):
  225. """Facilitates system emulation tests."""
  226. cpu = None
  227. machine = None
  228. _machinehelp = None
  229. def setUp(self):
  230. self._vms = {}
  231. super().setUp()
  232. console_log = logging.getLogger('console')
  233. console_log.setLevel(logging.DEBUG)
  234. self.console_log_name = self.log_file('console.log')
  235. self._console_log_fh = logging.FileHandler(self.console_log_name,
  236. mode='w')
  237. self._console_log_fh.setLevel(logging.DEBUG)
  238. fileFormatter = logging.Formatter('%(asctime)s: %(message)s')
  239. self._console_log_fh.setFormatter(fileFormatter)
  240. console_log.addHandler(self._console_log_fh)
  241. def set_machine(self, machinename):
  242. # TODO: We should use QMP to get the list of available machines
  243. if not self._machinehelp:
  244. self._machinehelp = run(
  245. [self.qemu_bin, '-M', 'help'],
  246. capture_output=True, check=True, encoding='utf8').stdout
  247. if self._machinehelp.find(machinename) < 0:
  248. self.skipTest('no support for machine ' + machinename)
  249. self.machine = machinename
  250. def require_accelerator(self, accelerator):
  251. """
  252. Requires an accelerator to be available for the test to continue
  253. It takes into account the currently set qemu binary.
  254. If the check fails, the test is canceled. If the check itself
  255. for the given accelerator is not available, the test is also
  256. canceled.
  257. :param accelerator: name of the accelerator, such as "kvm" or "tcg"
  258. :type accelerator: str
  259. """
  260. checker = {'tcg': tcg_available,
  261. 'kvm': kvm_available}.get(accelerator)
  262. if checker is None:
  263. self.skipTest("Don't know how to check for the presence "
  264. "of accelerator %s" % accelerator)
  265. if not checker(qemu_bin=self.qemu_bin):
  266. self.skipTest("%s accelerator does not seem to be "
  267. "available" % accelerator)
  268. def require_netdev(self, netdevname):
  269. help = run([self.qemu_bin,
  270. '-M', 'none', '-netdev', 'help'],
  271. capture_output=True, check=True, encoding='utf8').stdout;
  272. if help.find('\n' + netdevname + '\n') < 0:
  273. self.skipTest('no support for " + netdevname + " networking')
  274. def require_device(self, devicename):
  275. help = run([self.qemu_bin,
  276. '-M', 'none', '-device', 'help'],
  277. capture_output=True, check=True, encoding='utf8').stdout;
  278. if help.find(devicename) < 0:
  279. self.skipTest('no support for device ' + devicename)
  280. def _new_vm(self, name, *args):
  281. vm = QEMUMachine(self.qemu_bin,
  282. name=name,
  283. base_temp_dir=self.workdir,
  284. log_dir=self.log_file())
  285. self.log.debug('QEMUMachine "%s" created', name)
  286. self.log.debug('QEMUMachine "%s" temp_dir: %s', name, vm.temp_dir)
  287. sockpath = os.environ.get("QEMU_TEST_QMP_BACKDOOR", None)
  288. if sockpath is not None:
  289. vm.add_args("-chardev",
  290. f"socket,id=backdoor,path={sockpath},server=on,wait=off",
  291. "-mon", "chardev=backdoor,mode=control")
  292. if args:
  293. vm.add_args(*args)
  294. return vm
  295. @property
  296. def vm(self):
  297. return self.get_vm(name='default')
  298. def get_vm(self, *args, name=None):
  299. if not name:
  300. name = str(uuid.uuid4())
  301. if self._vms.get(name) is None:
  302. self._vms[name] = self._new_vm(name, *args)
  303. if self.cpu is not None:
  304. self._vms[name].add_args('-cpu', self.cpu)
  305. if self.machine is not None:
  306. self._vms[name].set_machine(self.machine)
  307. return self._vms[name]
  308. def set_vm_arg(self, arg, value):
  309. """
  310. Set an argument to list of extra arguments to be given to the QEMU
  311. binary. If the argument already exists then its value is replaced.
  312. :param arg: the QEMU argument, such as "-cpu" in "-cpu host"
  313. :type arg: str
  314. :param value: the argument value, such as "host" in "-cpu host"
  315. :type value: str
  316. """
  317. if not arg or not value:
  318. return
  319. if arg not in self.vm.args:
  320. self.vm.args.extend([arg, value])
  321. else:
  322. idx = self.vm.args.index(arg) + 1
  323. if idx < len(self.vm.args):
  324. self.vm.args[idx] = value
  325. else:
  326. self.vm.args.append(value)
  327. def tearDown(self):
  328. for vm in self._vms.values():
  329. vm.shutdown()
  330. logging.getLogger('console').removeHandler(self._console_log_fh)
  331. super().tearDown()