oetest.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. #
  2. # Copyright (C) 2013 Intel Corporation
  3. #
  4. # SPDX-License-Identifier: MIT
  5. #
  6. # Main unittest module used by testimage.bbclass
  7. # This provides the oeRuntimeTest base class which is inherited by all tests in meta/lib/oeqa/runtime.
  8. # It also has some helper functions and it's responsible for actually starting the tests
  9. import os, re, sys
  10. import unittest
  11. import inspect
  12. import subprocess
  13. import signal
  14. import shutil
  15. import functools
  16. try:
  17. import bb
  18. except ImportError:
  19. pass
  20. import logging
  21. import oeqa.runtime
  22. # Exported test doesn't require sdkext
  23. try:
  24. import oeqa.sdkext
  25. except ImportError:
  26. pass
  27. from oeqa.utils.decorators import LogResults, gettag
  28. logger = logging.getLogger("BitBake")
  29. def getVar(obj):
  30. #extend form dict, if a variable didn't exists, need find it in testcase
  31. class VarDict(dict):
  32. def __getitem__(self, key):
  33. return gettag(obj, key)
  34. return VarDict()
  35. def checkTags(tc, tagexp):
  36. return eval(tagexp, None, getVar(tc))
  37. def filterByTagExp(testsuite, tagexp):
  38. if not tagexp:
  39. return testsuite
  40. caseList = []
  41. for each in testsuite:
  42. if not isinstance(each, unittest.BaseTestSuite):
  43. if checkTags(each, tagexp):
  44. caseList.append(each)
  45. else:
  46. caseList.append(filterByTagExp(each, tagexp))
  47. return testsuite.__class__(caseList)
  48. @LogResults
  49. class oeTest(unittest.TestCase):
  50. longMessage = True
  51. @classmethod
  52. def hasPackage(self, pkg):
  53. """
  54. True if the full package name exists in the manifest, False otherwise.
  55. """
  56. return pkg in oeTest.tc.pkgmanifest
  57. @classmethod
  58. def hasPackageMatch(self, match):
  59. """
  60. True if match exists in the manifest as a regular expression substring,
  61. False otherwise.
  62. """
  63. for s in oeTest.tc.pkgmanifest:
  64. if re.match(match, s):
  65. return True
  66. return False
  67. @classmethod
  68. def hasFeature(self,feature):
  69. if feature in oeTest.tc.imagefeatures or \
  70. feature in oeTest.tc.distrofeatures:
  71. return True
  72. else:
  73. return False
  74. class oeRuntimeTest(oeTest):
  75. def __init__(self, methodName='runTest'):
  76. self.target = oeRuntimeTest.tc.target
  77. super(oeRuntimeTest, self).__init__(methodName)
  78. def setUp(self):
  79. # Install packages in the DUT
  80. self.tc.install_uninstall_packages(self.id())
  81. # Check if test needs to run
  82. if self.tc.sigterm:
  83. self.fail("Got SIGTERM")
  84. elif (type(self.target).__name__ == "QemuTarget"):
  85. self.assertTrue(self.target.check(), msg = "Qemu not running?")
  86. self.setUpLocal()
  87. # a setup method before tests but after the class instantiation
  88. def setUpLocal(self):
  89. pass
  90. def tearDown(self):
  91. # Uninstall packages in the DUT
  92. self.tc.install_uninstall_packages(self.id(), False)
  93. self.tearDownLocal()
  94. # Method to be run after tearDown and implemented by child classes
  95. def tearDownLocal(self):
  96. pass
  97. def getmodule(pos=2):
  98. # stack returns a list of tuples containg frame information
  99. # First element of the list the is current frame, caller is 1
  100. frameinfo = inspect.stack()[pos]
  101. modname = inspect.getmodulename(frameinfo[1])
  102. #modname = inspect.getmodule(frameinfo[0]).__name__
  103. return modname
  104. def skipModule(reason, pos=2):
  105. modname = getmodule(pos)
  106. if modname not in oeTest.tc.testsrequired:
  107. raise unittest.SkipTest("%s: %s" % (modname, reason))
  108. else:
  109. raise Exception("\nTest %s wants to be skipped.\nReason is: %s" \
  110. "\nTest was required in TEST_SUITES, so either the condition for skipping is wrong" \
  111. "\nor the image really doesn't have the required feature/package when it should." % (modname, reason))
  112. def skipModuleIf(cond, reason):
  113. if cond:
  114. skipModule(reason, 3)
  115. def skipModuleUnless(cond, reason):
  116. if not cond:
  117. skipModule(reason, 3)
  118. _buffer_logger = ""
  119. def custom_verbose(msg, *args, **kwargs):
  120. global _buffer_logger
  121. if msg[-1] != "\n":
  122. _buffer_logger += msg
  123. else:
  124. _buffer_logger += msg
  125. try:
  126. bb.plain(_buffer_logger.rstrip("\n"), *args, **kwargs)
  127. except NameError:
  128. logger.info(_buffer_logger.rstrip("\n"), *args, **kwargs)
  129. _buffer_logger = ""
  130. class TestContext(object):
  131. def __init__(self, d, exported=False):
  132. self.d = d
  133. self.testsuites = self._get_test_suites()
  134. if exported:
  135. path = [os.path.dirname(os.path.abspath(__file__))]
  136. extrapath = ""
  137. else:
  138. path = d.getVar("BBPATH").split(':')
  139. extrapath = "lib/oeqa"
  140. self.testslist = self._get_tests_list(path, extrapath)
  141. self.testsrequired = self._get_test_suites_required()
  142. self.filesdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runtime/files")
  143. self.corefilesdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "files")
  144. self.imagefeatures = d.getVar("IMAGE_FEATURES").split()
  145. self.distrofeatures = d.getVar("DISTRO_FEATURES").split()
  146. # get testcase list from specified file
  147. # if path is a relative path, then relative to build/conf/
  148. def _read_testlist(self, fpath, builddir):
  149. if not os.path.isabs(fpath):
  150. fpath = os.path.join(builddir, "conf", fpath)
  151. if not os.path.exists(fpath):
  152. bb.fatal("No such manifest file: ", fpath)
  153. tcs = []
  154. for line in open(fpath).readlines():
  155. line = line.strip()
  156. if line and not line.startswith("#"):
  157. tcs.append(line)
  158. return " ".join(tcs)
  159. # return test list by type also filter if TEST_SUITES is specified
  160. def _get_tests_list(self, bbpath, extrapath):
  161. testslist = []
  162. type = self._get_test_namespace()
  163. # This relies on lib/ under each directory in BBPATH being added to sys.path
  164. # (as done by default in base.bbclass)
  165. for testname in self.testsuites:
  166. if testname != "auto":
  167. if testname.startswith("oeqa."):
  168. testslist.append(testname)
  169. continue
  170. found = False
  171. for p in bbpath:
  172. if os.path.exists(os.path.join(p, extrapath, type, testname + ".py")):
  173. testslist.append("oeqa." + type + "." + testname)
  174. found = True
  175. break
  176. elif os.path.exists(os.path.join(p, extrapath, type, testname.split(".")[0] + ".py")):
  177. testslist.append("oeqa." + type + "." + testname)
  178. found = True
  179. break
  180. if not found:
  181. bb.fatal('Test %s specified in TEST_SUITES could not be found in lib/oeqa/runtime under BBPATH' % testname)
  182. if "auto" in self.testsuites:
  183. def add_auto_list(path):
  184. files = sorted([f for f in os.listdir(path) if f.endswith('.py') and not f.startswith('_')])
  185. for f in files:
  186. module = 'oeqa.' + type + '.' + f[:-3]
  187. if module not in testslist:
  188. testslist.append(module)
  189. for p in bbpath:
  190. testpath = os.path.join(p, 'lib', 'oeqa', type)
  191. bb.debug(2, 'Searching for tests in %s' % testpath)
  192. if os.path.exists(testpath):
  193. add_auto_list(testpath)
  194. return testslist
  195. def getTestModules(self):
  196. """
  197. Returns all the test modules in the testlist.
  198. """
  199. import pkgutil
  200. modules = []
  201. for test in self.testslist:
  202. if re.search(r"\w+\.\w+\.test_\S+", test):
  203. test = '.'.join(t.split('.')[:3])
  204. module = pkgutil.get_loader(test)
  205. modules.append(module)
  206. return modules
  207. def getModulefromID(self, test_id):
  208. """
  209. Returns the test module based on a test id.
  210. """
  211. module_name = ".".join(test_id.split(".")[:3])
  212. modules = self.getTestModules()
  213. for module in modules:
  214. if module.name == module_name:
  215. return module
  216. return None
  217. def getTests(self, test):
  218. '''Return all individual tests executed when running the suite.'''
  219. # Unfortunately unittest does not have an API for this, so we have
  220. # to rely on implementation details. This only needs to work
  221. # for TestSuite containing TestCase.
  222. method = getattr(test, '_testMethodName', None)
  223. if method:
  224. # leaf case: a TestCase
  225. yield test
  226. else:
  227. # Look into TestSuite.
  228. tests = getattr(test, '_tests', [])
  229. for t1 in tests:
  230. for t2 in self.getTests(t1):
  231. yield t2
  232. def loadTests(self):
  233. setattr(oeTest, "tc", self)
  234. testloader = unittest.TestLoader()
  235. testloader.sortTestMethodsUsing = None
  236. suites = [testloader.loadTestsFromName(name) for name in self.testslist]
  237. suites = filterByTagExp(suites, getattr(self, "tagexp", None))
  238. # Determine dependencies between suites by looking for @skipUnlessPassed
  239. # method annotations. Suite A depends on suite B if any method in A
  240. # depends on a method on B.
  241. for suite in suites:
  242. suite.dependencies = []
  243. suite.depth = 0
  244. for test in self.getTests(suite):
  245. methodname = getattr(test, '_testMethodName', None)
  246. if methodname:
  247. method = getattr(test, methodname)
  248. depends_on = getattr(method, '_depends_on', None)
  249. if depends_on:
  250. for dep_suite in suites:
  251. if depends_on in [getattr(t, '_testMethodName', None) for t in self.getTests(dep_suite)]:
  252. if dep_suite not in suite.dependencies and \
  253. dep_suite is not suite:
  254. suite.dependencies.append(dep_suite)
  255. break
  256. else:
  257. logger.warning("Test %s was declared as @skipUnlessPassed('%s') but that test is either not defined or not active. Will run the test anyway." %
  258. (test, depends_on))
  259. # Use brute-force topological sort to determine ordering. Sort by
  260. # depth (higher depth = must run later), with original ordering to
  261. # break ties.
  262. def set_suite_depth(suite):
  263. for dep in suite.dependencies:
  264. new_depth = set_suite_depth(dep) + 1
  265. if new_depth > suite.depth:
  266. suite.depth = new_depth
  267. return suite.depth
  268. for index, suite in enumerate(suites):
  269. set_suite_depth(suite)
  270. suite.index = index
  271. def cmp(a, b):
  272. return (a > b) - (a < b)
  273. def cmpfunc(a, b):
  274. return cmp((a.depth, a.index), (b.depth, b.index))
  275. suites.sort(key=functools.cmp_to_key(cmpfunc))
  276. self.suite = testloader.suiteClass(suites)
  277. return self.suite
  278. def runTests(self):
  279. logger.info("Test modules %s" % self.testslist)
  280. if hasattr(self, "tagexp") and self.tagexp:
  281. logger.info("Filter test cases by tags: %s" % self.tagexp)
  282. logger.info("Found %s tests" % self.suite.countTestCases())
  283. runner = unittest.TextTestRunner(verbosity=2)
  284. if 'bb' in sys.modules:
  285. runner.stream.write = custom_verbose
  286. return runner.run(self.suite)
  287. class RuntimeTestContext(TestContext):
  288. def __init__(self, d, target, exported=False):
  289. super(RuntimeTestContext, self).__init__(d, exported)
  290. self.target = target
  291. self.pkgmanifest = {}
  292. manifest = os.path.join(d.getVar("DEPLOY_DIR_IMAGE"),
  293. d.getVar("IMAGE_LINK_NAME") + ".manifest")
  294. nomanifest = d.getVar("IMAGE_NO_MANIFEST")
  295. if nomanifest is None or nomanifest != "1":
  296. try:
  297. with open(manifest) as f:
  298. for line in f:
  299. (pkg, arch, version) = line.strip().split()
  300. self.pkgmanifest[pkg] = (version, arch)
  301. except IOError as e:
  302. bb.fatal("No package manifest file found. Did you build the image?\n%s" % e)
  303. def _get_test_namespace(self):
  304. return "runtime"
  305. def _get_test_suites(self):
  306. testsuites = []
  307. manifests = (self.d.getVar("TEST_SUITES_MANIFEST") or '').split()
  308. if manifests:
  309. for manifest in manifests:
  310. testsuites.extend(self._read_testlist(manifest,
  311. self.d.getVar("TOPDIR")).split())
  312. else:
  313. testsuites = self.d.getVar("TEST_SUITES").split()
  314. return testsuites
  315. def _get_test_suites_required(self):
  316. return [t for t in self.d.getVar("TEST_SUITES").split() if t != "auto"]
  317. def extract_packages(self):
  318. """
  319. Find packages that will be needed during runtime.
  320. """
  321. modules = self.getTestModules()
  322. bbpaths = self.d.getVar("BBPATH").split(":")
  323. shutil.rmtree(self.d.getVar("TEST_EXTRACTED_DIR"))
  324. shutil.rmtree(self.d.getVar("TEST_PACKAGED_DIR"))
  325. for module in modules:
  326. json_file = self._getJsonFile(module)
  327. if json_file:
  328. needed_packages = self._getNeededPackages(json_file)
  329. self._perform_package_extraction(needed_packages)
  330. def _perform_package_extraction(self, needed_packages):
  331. """
  332. Extract packages that will be needed during runtime.
  333. """
  334. import oe.path
  335. extracted_path = self.d.getVar("TEST_EXTRACTED_DIR")
  336. packaged_path = self.d.getVar("TEST_PACKAGED_DIR")
  337. for key,value in needed_packages.items():
  338. packages = ()
  339. if isinstance(value, dict):
  340. packages = (value, )
  341. elif isinstance(value, list):
  342. packages = value
  343. else:
  344. bb.fatal("Failed to process needed packages for %s; "
  345. "Value must be a dict or list" % key)
  346. for package in packages:
  347. pkg = package["pkg"]
  348. rm = package.get("rm", False)
  349. extract = package.get("extract", True)
  350. if extract:
  351. dst_dir = os.path.join(extracted_path, pkg)
  352. else:
  353. dst_dir = os.path.join(packaged_path)
  354. # Extract package and copy it to TEST_EXTRACTED_DIR
  355. pkg_dir = self._extract_in_tmpdir(pkg)
  356. if extract:
  357. # Same package used for more than one test,
  358. # don't need to extract again.
  359. if os.path.exists(dst_dir):
  360. continue
  361. oe.path.copytree(pkg_dir, dst_dir)
  362. shutil.rmtree(pkg_dir)
  363. # Copy package to TEST_PACKAGED_DIR
  364. else:
  365. self._copy_package(pkg)
  366. def _getJsonFile(self, module):
  367. """
  368. Returns the path of the JSON file for a module, empty if doesn't exitst.
  369. """
  370. module_file = module.path
  371. json_file = "%s.json" % module_file.rsplit(".", 1)[0]
  372. if os.path.isfile(module_file) and os.path.isfile(json_file):
  373. return json_file
  374. else:
  375. return ""
  376. def _getNeededPackages(self, json_file, test=None):
  377. """
  378. Returns a dict with needed packages based on a JSON file.
  379. If a test is specified it will return the dict just for that test.
  380. """
  381. import json
  382. needed_packages = {}
  383. with open(json_file) as f:
  384. test_packages = json.load(f)
  385. for key,value in test_packages.items():
  386. needed_packages[key] = value
  387. if test:
  388. if test in needed_packages:
  389. needed_packages = needed_packages[test]
  390. else:
  391. needed_packages = {}
  392. return needed_packages
  393. def _extract_in_tmpdir(self, pkg):
  394. """"
  395. Returns path to a temp directory where the package was
  396. extracted without dependencies.
  397. """
  398. from oeqa.utils.package_manager import get_package_manager
  399. pkg_path = os.path.join(self.d.getVar("TEST_INSTALL_TMP_DIR"), pkg)
  400. pm = get_package_manager(self.d, pkg_path)
  401. extract_dir = pm.extract(pkg)
  402. shutil.rmtree(pkg_path)
  403. return extract_dir
  404. def _copy_package(self, pkg):
  405. """
  406. Copy the RPM, DEB or IPK package to dst_dir
  407. """
  408. from oeqa.utils.package_manager import get_package_manager
  409. pkg_path = os.path.join(self.d.getVar("TEST_INSTALL_TMP_DIR"), pkg)
  410. dst_dir = self.d.getVar("TEST_PACKAGED_DIR")
  411. pm = get_package_manager(self.d, pkg_path)
  412. pkg_info = pm.package_info(pkg)
  413. file_path = pkg_info[pkg]["filepath"]
  414. shutil.copy2(file_path, dst_dir)
  415. shutil.rmtree(pkg_path)
  416. def install_uninstall_packages(self, test_id, pkg_dir, install):
  417. """
  418. Check if the test requires a package and Install/Uninstall it in the DUT
  419. """
  420. test = test_id.split(".")[4]
  421. module = self.getModulefromID(test_id)
  422. json = self._getJsonFile(module)
  423. if json:
  424. needed_packages = self._getNeededPackages(json, test)
  425. if needed_packages:
  426. self._install_uninstall_packages(needed_packages, pkg_dir, install)
  427. def _install_uninstall_packages(self, needed_packages, pkg_dir, install=True):
  428. """
  429. Install/Uninstall packages in the DUT without using a package manager
  430. """
  431. if isinstance(needed_packages, dict):
  432. packages = [needed_packages]
  433. elif isinstance(needed_packages, list):
  434. packages = needed_packages
  435. for package in packages:
  436. pkg = package["pkg"]
  437. rm = package.get("rm", False)
  438. extract = package.get("extract", True)
  439. src_dir = os.path.join(pkg_dir, pkg)
  440. # Install package
  441. if install and extract:
  442. self.target.connection.copy_dir_to(src_dir, "/")
  443. # Uninstall package
  444. elif not install and rm:
  445. self.target.connection.delete_dir_structure(src_dir, "/")
  446. class ImageTestContext(RuntimeTestContext):
  447. def __init__(self, d, target, host_dumper):
  448. super(ImageTestContext, self).__init__(d, target)
  449. self.tagexp = d.getVar("TEST_SUITES_TAGS")
  450. self.host_dumper = host_dumper
  451. self.sigterm = False
  452. self.origsigtermhandler = signal.getsignal(signal.SIGTERM)
  453. signal.signal(signal.SIGTERM, self._sigterm_exception)
  454. def _sigterm_exception(self, signum, stackframe):
  455. bb.warn("TestImage received SIGTERM, shutting down...")
  456. self.sigterm = True
  457. self.target.stop()
  458. def install_uninstall_packages(self, test_id, install=True):
  459. """
  460. Check if the test requires a package and Install/Uninstall it in the DUT
  461. """
  462. pkg_dir = self.d.getVar("TEST_EXTRACTED_DIR")
  463. super(ImageTestContext, self).install_uninstall_packages(test_id, pkg_dir, install)
  464. class ExportTestContext(RuntimeTestContext):
  465. def __init__(self, d, target, exported=False, parsedArgs={}):
  466. """
  467. This class is used when exporting tests and when are executed outside OE environment.
  468. parsedArgs can contain the following:
  469. - tag: Filter test by tag.
  470. """
  471. super(ExportTestContext, self).__init__(d, target, exported)
  472. tag = parsedArgs.get("tag", None)
  473. self.tagexp = tag if tag != None else d.getVar("TEST_SUITES_TAGS")
  474. self.sigterm = None
  475. def install_uninstall_packages(self, test_id, install=True):
  476. """
  477. Check if the test requires a package and Install/Uninstall it in the DUT
  478. """
  479. export_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  480. extracted_dir = self.d.getVar("TEST_EXPORT_EXTRACTED_DIR")
  481. pkg_dir = os.path.join(export_dir, extracted_dir)
  482. super(ExportTestContext, self).install_uninstall_packages(test_id, pkg_dir, install)