oe-selftest 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #!/usr/bin/env python
  2. # Copyright (c) 2013 Intel Corporation
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License version 2 as
  6. # published by the Free Software Foundation.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along
  14. # with this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. # DESCRIPTION
  17. # This script runs tests defined in meta/lib/selftest/
  18. # It's purpose is to automate the testing of different bitbake tools.
  19. # To use it you just need to source your build environment setup script and
  20. # add the meta-selftest layer to your BBLAYERS.
  21. # Call the script as: "oe-selftest" to run all the tests in in meta/lib/selftest/
  22. # Call the script as: "oe-selftest <module>.<Class>.<method>" to run just a single test
  23. # E.g: "oe-selftest bboutput.BitbakeLayers" will run just the BitbakeLayers class from meta/lib/selftest/bboutput.py
  24. import os
  25. import sys
  26. import unittest
  27. import logging
  28. import argparse
  29. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'meta/lib')))
  30. import oeqa.selftest
  31. import oeqa.utils.ftools as ftools
  32. from oeqa.utils.commands import runCmd, get_bb_var, get_test_layer
  33. from oeqa.selftest.base import oeSelfTest
  34. def logger_create():
  35. log = logging.getLogger("selftest")
  36. log.setLevel(logging.DEBUG)
  37. fh = logging.FileHandler(filename='oe-selftest.log', mode='w')
  38. fh.setLevel(logging.DEBUG)
  39. ch = logging.StreamHandler(sys.stdout)
  40. ch.setLevel(logging.INFO)
  41. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  42. fh.setFormatter(formatter)
  43. ch.setFormatter(formatter)
  44. log.addHandler(fh)
  45. log.addHandler(ch)
  46. return log
  47. log = logger_create()
  48. def get_args_parser():
  49. description = "Script that runs unit tests agains bitbake and other Yocto related tools. The goal is to validate tools functionality and metadata integrity. Refer to https://wiki.yoctoproject.org/wiki/Oe-selftest for more information."
  50. parser = argparse.ArgumentParser(description=description)
  51. group = parser.add_mutually_exclusive_group(required=True)
  52. group.add_argument('--run-tests', required=False, action='store', nargs='*', dest="run_tests", default=None, help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
  53. group.add_argument('--run-all-tests', required=False, action="store_true", dest="run_all_tests", default=False, help='Run all (unhidden) tests')
  54. group.add_argument('--list-modules', required=False, action="store_true", dest="list_modules", default=False, help='List all available test modules.')
  55. group.add_argument('--list-classes', required=False, action="store_true", dest="list_allclasses", default=False, help='List all available test classes.')
  56. return parser
  57. def preflight_check():
  58. log.info("Checking that everything is in order before running the tests")
  59. if not os.environ.get("BUILDDIR"):
  60. log.error("BUILDDIR isn't set. Did you forget to source your build environment setup script?")
  61. return False
  62. builddir = os.environ.get("BUILDDIR")
  63. if os.getcwd() != builddir:
  64. log.info("Changing cwd to %s" % builddir)
  65. os.chdir(builddir)
  66. if not "meta-selftest" in get_bb_var("BBLAYERS"):
  67. log.error("You don't seem to have the meta-selftest layer in BBLAYERS")
  68. return False
  69. log.info("Running bitbake -p")
  70. runCmd("bitbake -p")
  71. return True
  72. def add_include():
  73. builddir = os.environ.get("BUILDDIR")
  74. if "#include added by oe-selftest.py" \
  75. not in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
  76. log.info("Adding: \"include selftest.inc\" in local.conf")
  77. ftools.append_file(os.path.join(builddir, "conf/local.conf"), \
  78. "\n#include added by oe-selftest.py\ninclude selftest.inc")
  79. def remove_include():
  80. builddir = os.environ.get("BUILDDIR")
  81. if builddir is None:
  82. return
  83. if "#include added by oe-selftest.py" \
  84. in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
  85. log.info("Removing the include from local.conf")
  86. ftools.remove_from_file(os.path.join(builddir, "conf/local.conf"), \
  87. "#include added by oe-selftest.py\ninclude selftest.inc")
  88. def remove_inc_files():
  89. try:
  90. os.remove(os.path.join(os.environ.get("BUILDDIR"), "conf/selftest.inc"))
  91. for root, _, files in os.walk(get_test_layer()):
  92. for f in files:
  93. if f == 'test_recipe.inc':
  94. os.remove(os.path.join(root, f))
  95. except (AttributeError, OSError,) as e: # AttributeError may happen if BUILDDIR is not set
  96. pass
  97. def get_tests(exclusive_modules=[], include_hidden=False):
  98. testslist = []
  99. for x in exclusive_modules:
  100. testslist.append('oeqa.selftest.' + x)
  101. if not testslist:
  102. testpath = os.path.abspath(os.path.dirname(oeqa.selftest.__file__))
  103. files = sorted([f for f in os.listdir(testpath) if f.endswith('.py') and not (f.startswith('_') and not include_hidden) and not f.startswith('__') and f != 'base.py'])
  104. for f in files:
  105. module = 'oeqa.selftest.' + f[:-3]
  106. testslist.append(module)
  107. return testslist
  108. def main():
  109. parser = get_args_parser()
  110. args = parser.parse_args()
  111. if args.list_allclasses:
  112. args.list_modules = True
  113. if args.list_modules:
  114. log.info('Listing all available test modules:')
  115. testslist = get_tests(include_hidden=True)
  116. for test in testslist:
  117. module = test.split('.')[-1]
  118. info = ''
  119. if module.startswith('_'):
  120. info = ' (hidden)'
  121. print module + info
  122. if args.list_allclasses:
  123. try:
  124. import importlib
  125. modlib = importlib.import_module(test)
  126. for v in vars(modlib):
  127. t = vars(modlib)[v]
  128. if isinstance(t, type(oeSelfTest)) and issubclass(t, oeSelfTest) and t!=oeSelfTest:
  129. print " --", v
  130. for method in dir(t):
  131. if method.startswith("test_"):
  132. print " -- --", method
  133. except (AttributeError, ImportError) as e:
  134. print e
  135. pass
  136. if args.run_tests or args.run_all_tests:
  137. if not preflight_check():
  138. return 1
  139. testslist = get_tests(exclusive_modules=(args.run_tests or []), include_hidden=False)
  140. suite = unittest.TestSuite()
  141. loader = unittest.TestLoader()
  142. loader.sortTestMethodsUsing = None
  143. runner = unittest.TextTestRunner(verbosity=2)
  144. # we need to do this here, otherwise just loading the tests
  145. # will take 2 minutes (bitbake -e calls)
  146. oeSelfTest.testlayer_path = get_test_layer()
  147. for test in testslist:
  148. log.info("Loading tests from: %s" % test)
  149. try:
  150. suite.addTests(loader.loadTestsFromName(test))
  151. except AttributeError as e:
  152. log.error("Failed to import %s" % test)
  153. log.error(e)
  154. return 1
  155. add_include()
  156. result = runner.run(suite)
  157. log.info("Finished")
  158. if result.wasSuccessful():
  159. return 0
  160. else:
  161. return 1
  162. if __name__ == "__main__":
  163. try:
  164. ret = main()
  165. except Exception:
  166. ret = 1
  167. import traceback
  168. traceback.print_exc(5)
  169. finally:
  170. remove_include()
  171. remove_inc_files()
  172. sys.exit(ret)