run_test_suite.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. #!/usr/bin/env -S python3 -B
  2. # Copyright (c) 2021 Project CHIP Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import enum
  16. import logging
  17. import os
  18. import sys
  19. import time
  20. import typing
  21. from dataclasses import dataclass, field
  22. import chiptest
  23. import click
  24. import coloredlogs
  25. from chiptest.accessories import AppsRegister
  26. from chiptest.glob_matcher import GlobMatcher
  27. from chiptest.test_definition import TestRunTime, TestTag
  28. from yaml.paths_finder import PathsFinder
  29. DEFAULT_CHIP_ROOT = os.path.abspath(
  30. os.path.join(os.path.dirname(__file__), '..', '..'))
  31. class ManualHandling(enum.Enum):
  32. INCLUDE = enum.auto()
  33. SKIP = enum.auto()
  34. ONLY = enum.auto()
  35. # Supported log levels, mapping string values required for argument
  36. # parsing into logging constants
  37. __LOG_LEVELS__ = {
  38. 'debug': logging.DEBUG,
  39. 'info': logging.INFO,
  40. 'warn': logging.WARN,
  41. 'fatal': logging.FATAL,
  42. }
  43. @dataclass
  44. class RunContext:
  45. root: str
  46. tests: typing.List[chiptest.TestDefinition]
  47. in_unshare: bool
  48. chip_tool: str
  49. dry_run: bool
  50. runtime: TestRunTime
  51. # If not empty, include only the specified test tags
  52. include_tags: set(TestTag) = field(default_factory={})
  53. # If not empty, exclude tests tagged with these tags
  54. exclude_tags: set(TestTag) = field(default_factory={})
  55. @click.group(chain=True)
  56. @click.option(
  57. '--log-level',
  58. default='info',
  59. type=click.Choice(__LOG_LEVELS__.keys(), case_sensitive=False),
  60. help='Determines the verbosity of script output.')
  61. @click.option(
  62. '--dry-run',
  63. default=False,
  64. is_flag=True,
  65. help='Only print out shell commands that would be executed')
  66. @click.option(
  67. '--target',
  68. default=['all'],
  69. multiple=True,
  70. help='Test to run (use "all" to run all tests)'
  71. )
  72. @click.option(
  73. '--target-glob',
  74. default='',
  75. help='What targets to accept (glob)'
  76. )
  77. @click.option(
  78. '--target-skip-glob',
  79. default='',
  80. help='What targets to skip (glob)'
  81. )
  82. @click.option(
  83. '--no-log-timestamps',
  84. default=False,
  85. is_flag=True,
  86. help='Skip timestaps in log output')
  87. @click.option(
  88. '--root',
  89. default=DEFAULT_CHIP_ROOT,
  90. help='Default directory path for CHIP. Used to copy run configurations')
  91. @click.option(
  92. '--internal-inside-unshare',
  93. hidden=True,
  94. is_flag=True,
  95. default=False,
  96. help='Internal flag for running inside a unshared environment'
  97. )
  98. @click.option(
  99. '--include-tags',
  100. type=click.Choice(TestTag.__members__.keys(), case_sensitive=False),
  101. multiple=True,
  102. help='What test tags to include when running. Equivalent to "exlcude all except these" for priority purpuses.',
  103. )
  104. @click.option(
  105. '--exclude-tags',
  106. type=click.Choice(TestTag.__members__.keys(), case_sensitive=False),
  107. multiple=True,
  108. help='What test tags to exclude when running. Exclude options takes precedence over include.',
  109. )
  110. @click.option(
  111. '--runner',
  112. type=click.Choice(['codegen', 'chip_repl_python', 'chip_tool_python'], case_sensitive=False),
  113. default='codegen',
  114. help='Run YAML tests using the specified runner.')
  115. @click.option(
  116. '--chip-tool',
  117. help='Binary path of chip tool app to use to run the test')
  118. @click.pass_context
  119. def main(context, dry_run, log_level, target, target_glob, target_skip_glob,
  120. no_log_timestamps, root, internal_inside_unshare, include_tags, exclude_tags, runner, chip_tool):
  121. # Ensures somewhat pretty logging of what is going on
  122. log_fmt = '%(asctime)s.%(msecs)03d %(levelname)-7s %(message)s'
  123. if no_log_timestamps:
  124. log_fmt = '%(levelname)-7s %(message)s'
  125. coloredlogs.install(level=__LOG_LEVELS__[log_level], fmt=log_fmt)
  126. runtime = TestRunTime.CHIP_TOOL_BUILTIN
  127. if runner == 'chip_repl_python':
  128. runtime = TestRunTime.CHIP_REPL_PYTHON
  129. elif runner == 'chip_tool_python':
  130. runtime = TestRunTime.CHIP_TOOL_PYTHON
  131. elif chip_tool is not None and os.path.basename(chip_tool) == "darwin-framework-tool":
  132. runtime = TestRunTime.DARWIN_FRAMEWORK_TOOL_BUILTIN
  133. if chip_tool is None and not runtime == TestRunTime.CHIP_REPL_PYTHON:
  134. # non yaml tests REQUIRE chip-tool. Yaml tests should not require chip-tool
  135. paths_finder = PathsFinder()
  136. chip_tool = paths_finder.get('chip-tool')
  137. if include_tags:
  138. include_tags = set([TestTag.__members__[t] for t in include_tags])
  139. if exclude_tags:
  140. exclude_tags = set([TestTag.__members__[t] for t in exclude_tags])
  141. # Figures out selected test that match the given name(s)
  142. if runtime == TestRunTime.CHIP_REPL_PYTHON:
  143. all_tests = [test for test in chiptest.AllReplYamlTests()]
  144. elif runtime == TestRunTime.CHIP_TOOL_PYTHON and os.path.basename(chip_tool) != "darwin-framework-tool":
  145. all_tests = [test for test in chiptest.AllChipToolYamlTests()]
  146. else:
  147. all_tests = [test for test in chiptest.AllChipToolTests(chip_tool)]
  148. tests = all_tests
  149. # If just defaults specified, do not run manual and in development
  150. # Specific target basically includes everything
  151. if 'all' in target and not include_tags and not exclude_tags:
  152. exclude_tags = {
  153. TestTag.MANUAL,
  154. TestTag.IN_DEVELOPMENT,
  155. TestTag.FLAKY,
  156. TestTag.EXTRA_SLOW,
  157. TestTag.PURPOSEFUL_FAILURE,
  158. }
  159. if runtime != TestRunTime.CHIP_TOOL_PYTHON:
  160. exclude_tags.add(TestTag.CHIP_TOOL_PYTHON_ONLY)
  161. if 'all' not in target:
  162. tests = []
  163. for name in target:
  164. targeted = [test for test in all_tests if test.name.lower()
  165. == name.lower()]
  166. if len(targeted) == 0:
  167. logging.error("Unknown target: %s" % name)
  168. tests.extend(targeted)
  169. if target_glob:
  170. matcher = GlobMatcher(target_glob.lower())
  171. tests = [test for test in tests if matcher.matches(test.name.lower())]
  172. if len(tests) == 0:
  173. logging.error("No targets match, exiting.")
  174. logging.error("Valid targets are (case-insensitive): %s" %
  175. (", ".join(test.name for test in all_tests)))
  176. exit(1)
  177. if target_skip_glob:
  178. matcher = GlobMatcher(target_skip_glob.lower())
  179. tests = [test for test in tests if not matcher.matches(
  180. test.name.lower())]
  181. tests.sort(key=lambda x: x.name)
  182. context.obj = RunContext(root=root, tests=tests,
  183. in_unshare=internal_inside_unshare,
  184. chip_tool=chip_tool, dry_run=dry_run,
  185. runtime=runtime,
  186. include_tags=include_tags,
  187. exclude_tags=exclude_tags)
  188. @main.command(
  189. 'list', help='List available test suites')
  190. @click.pass_context
  191. def cmd_list(context):
  192. for test in context.obj.tests:
  193. tags = test.tags_str()
  194. if tags:
  195. tags = f" ({tags})"
  196. print("%s%s" % (test.name, tags))
  197. @main.command(
  198. 'run', help='Execute the tests')
  199. @click.option(
  200. '--iterations',
  201. default=1,
  202. help='Number of iterations to run')
  203. @click.option(
  204. '--all-clusters-app',
  205. help='what all clusters app to use')
  206. @click.option(
  207. '--lock-app',
  208. help='what lock app to use')
  209. @click.option(
  210. '--ota-provider-app',
  211. help='what ota provider app to use')
  212. @click.option(
  213. '--ota-requestor-app',
  214. help='what ota requestor app to use')
  215. @click.option(
  216. '--tv-app',
  217. help='what tv app to use')
  218. @click.option(
  219. '--bridge-app',
  220. help='what bridge app to use')
  221. @click.option(
  222. '--chip-repl-yaml-tester',
  223. help='what python script to use for running yaml tests using chip-repl as controller')
  224. @click.option(
  225. '--chip-tool-with-python',
  226. help='what python script to use for running yaml tests using chip-tool as controller')
  227. @click.option(
  228. '--pics-file',
  229. type=click.Path(exists=True),
  230. default="src/app/tests/suites/certification/ci-pics-values",
  231. show_default=True,
  232. help='PICS file to use for test runs.')
  233. @click.option(
  234. '--keep-going',
  235. is_flag=True,
  236. default=False,
  237. show_default=True,
  238. help='Keep running the rest of the tests even if a test fails.')
  239. @click.option(
  240. '--test-timeout-seconds',
  241. default=None,
  242. type=int,
  243. help='If provided, fail if a test runs for longer than this time')
  244. @click.option(
  245. '--expected-failures',
  246. type=int,
  247. default=0,
  248. show_default=True,
  249. help='Number of tests that are expected to fail in each iteration. Overall test will pass if the number of failures matches this. Nonzero values require --keep-going')
  250. @click.pass_context
  251. def cmd_run(context, iterations, all_clusters_app, lock_app, ota_provider_app, ota_requestor_app,
  252. tv_app, bridge_app, chip_repl_yaml_tester, chip_tool_with_python, pics_file, keep_going, test_timeout_seconds, expected_failures):
  253. if expected_failures != 0 and not keep_going:
  254. logging.exception(f"'--expected-failures {expected_failures}' used without '--keep-going'")
  255. sys.exit(2)
  256. runner = chiptest.runner.Runner()
  257. paths_finder = PathsFinder()
  258. if all_clusters_app is None:
  259. all_clusters_app = paths_finder.get('chip-all-clusters-app')
  260. if lock_app is None:
  261. lock_app = paths_finder.get('chip-lock-app')
  262. if ota_provider_app is None:
  263. ota_provider_app = paths_finder.get('chip-ota-provider-app')
  264. if ota_requestor_app is None:
  265. ota_requestor_app = paths_finder.get('chip-ota-requestor-app')
  266. if tv_app is None:
  267. tv_app = paths_finder.get('chip-tv-app')
  268. if bridge_app is None:
  269. bridge_app = paths_finder.get('chip-bridge-app')
  270. if chip_repl_yaml_tester is None:
  271. chip_repl_yaml_tester = paths_finder.get('yamltest_with_chip_repl_tester.py')
  272. if chip_tool_with_python is None:
  273. if context.obj.chip_tool and os.path.basename(context.obj.chip_tool) == "darwin-framework-tool":
  274. chip_tool_with_python = paths_finder.get('darwinframeworktool.py')
  275. else:
  276. chip_tool_with_python = paths_finder.get('chiptool.py')
  277. # Command execution requires an array
  278. paths = chiptest.ApplicationPaths(
  279. chip_tool=[context.obj.chip_tool],
  280. all_clusters_app=[all_clusters_app],
  281. lock_app=[lock_app],
  282. ota_provider_app=[ota_provider_app],
  283. ota_requestor_app=[ota_requestor_app],
  284. tv_app=[tv_app],
  285. bridge_app=[bridge_app],
  286. chip_repl_yaml_tester_cmd=['python3'] + [chip_repl_yaml_tester],
  287. chip_tool_with_python_cmd=['python3'] + [chip_tool_with_python],
  288. )
  289. if sys.platform == 'linux':
  290. chiptest.linux.PrepareNamespacesForTestExecution(
  291. context.obj.in_unshare)
  292. paths = chiptest.linux.PathsWithNetworkNamespaces(paths)
  293. logging.info("Each test will be executed %d times" % iterations)
  294. apps_register = AppsRegister()
  295. apps_register.init()
  296. def cleanup():
  297. apps_register.uninit()
  298. if sys.platform == 'linux':
  299. chiptest.linux.ShutdownNamespaceForTestExecution()
  300. for i in range(iterations):
  301. logging.info("Starting iteration %d" % (i+1))
  302. observed_failures = 0
  303. for test in context.obj.tests:
  304. if context.obj.include_tags:
  305. if not (test.tags & context.obj.include_tags):
  306. logging.debug("Test %s not included" % test.name)
  307. continue
  308. if context.obj.exclude_tags:
  309. if test.tags & context.obj.exclude_tags:
  310. logging.debug("Test %s excluded" % test.name)
  311. continue
  312. test_start = time.monotonic()
  313. try:
  314. if context.obj.dry_run:
  315. logging.info("Would run test: %s" % test.name)
  316. continue
  317. logging.info('%-20s - Starting test' % (test.name))
  318. test.Run(
  319. runner, apps_register, paths, pics_file, test_timeout_seconds, context.obj.dry_run,
  320. test_runtime=context.obj.runtime)
  321. test_end = time.monotonic()
  322. logging.info('%-30s - Completed in %0.2f seconds' %
  323. (test.name, (test_end - test_start)))
  324. except Exception:
  325. test_end = time.monotonic()
  326. logging.exception('%-30s - FAILED in %0.2f seconds' %
  327. (test.name, (test_end - test_start)))
  328. observed_failures += 1
  329. if not keep_going:
  330. cleanup()
  331. sys.exit(2)
  332. if observed_failures != expected_failures:
  333. logging.exception(f'Iteration {i}: expected failure count {expected_failures}, but got {observed_failures}')
  334. cleanup()
  335. sys.exit(2)
  336. cleanup()
  337. # On linux, allow an execution shell to be prepared
  338. if sys.platform == 'linux':
  339. @main.command(
  340. 'shell',
  341. help=('Execute a bash shell in the environment (useful to test '
  342. 'network namespaces)'))
  343. @click.pass_context
  344. def cmd_shell(context):
  345. chiptest.linux.PrepareNamespacesForTestExecution(
  346. context.obj.in_unshare)
  347. os.execvpe("bash", ["bash"], os.environ.copy())
  348. if __name__ == '__main__':
  349. main(auto_envvar_prefix='CHIP')