idf_ci_utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # internal use only for CI
  2. # some CI related util functions
  3. #
  4. # SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  5. # SPDX-License-Identifier: Apache-2.0
  6. #
  7. import contextlib
  8. import io
  9. import logging
  10. import os
  11. import subprocess
  12. import sys
  13. from contextlib import redirect_stdout
  14. from dataclasses import dataclass
  15. from pathlib import Path
  16. from typing import TYPE_CHECKING, Any, List, Optional, Set, Union
  17. try:
  18. from idf_py_actions.constants import PREVIEW_TARGETS, SUPPORTED_TARGETS
  19. except ImportError:
  20. sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
  21. from idf_py_actions.constants import PREVIEW_TARGETS, SUPPORTED_TARGETS
  22. if TYPE_CHECKING:
  23. from _pytest.python import Function
  24. IDF_PATH = os.path.abspath(os.getenv('IDF_PATH', os.path.join(os.path.dirname(__file__), '..', '..')))
  25. def get_submodule_dirs(full_path: bool = False) -> List[str]:
  26. """
  27. To avoid issue could be introduced by multi-os or additional dependency,
  28. we use python and git to get this output
  29. :return: List of submodule dirs
  30. """
  31. dirs = []
  32. try:
  33. lines = (
  34. subprocess.check_output(
  35. [
  36. 'git',
  37. 'config',
  38. '--file',
  39. os.path.realpath(os.path.join(IDF_PATH, '.gitmodules')),
  40. '--get-regexp',
  41. 'path',
  42. ]
  43. )
  44. .decode('utf8')
  45. .strip()
  46. .split('\n')
  47. )
  48. for line in lines:
  49. _, path = line.split(' ')
  50. if full_path:
  51. dirs.append(os.path.join(IDF_PATH, path))
  52. else:
  53. dirs.append(path)
  54. except Exception as e: # pylint: disable=W0703
  55. logging.warning(str(e))
  56. return dirs
  57. def _check_git_filemode(full_path: str) -> bool:
  58. try:
  59. stdout = subprocess.check_output(['git', 'ls-files', '--stage', full_path]).strip().decode('utf-8')
  60. except subprocess.CalledProcessError:
  61. return True
  62. mode = stdout.split(' ', 1)[0] # e.g. 100644 for a rw-r--r--
  63. if any([int(i, 8) & 1 for i in mode[-3:]]):
  64. return True
  65. return False
  66. def is_executable(full_path: str) -> bool:
  67. """
  68. os.X_OK will always return true on windows. Use git to check file mode.
  69. :param full_path: file full path
  70. :return: True is it's an executable file
  71. """
  72. if sys.platform == 'win32':
  73. return _check_git_filemode(full_path)
  74. return os.access(full_path, os.X_OK)
  75. def get_git_files(path: str = IDF_PATH, full_path: bool = False) -> List[str]:
  76. """
  77. Get the result of git ls-files
  78. :param path: path to run git ls-files
  79. :param full_path: return full path if set to True
  80. :return: list of file paths
  81. """
  82. try:
  83. # this is a workaround when using under worktree
  84. # if you're using worktree, when running git commit a new environment variable GIT_DIR would be declared,
  85. # the value should be <origin_repo_path>/.git/worktrees/<worktree name>
  86. # This would affect the return value of `git ls-files`, unset this would use the `cwd`value or its parent
  87. # folder if no `.git` folder found in `cwd`.
  88. workaround_env = os.environ.copy()
  89. workaround_env.pop('GIT_DIR', None)
  90. files = (
  91. subprocess.check_output(['git', 'ls-files'], cwd=path, env=workaround_env)
  92. .decode('utf8')
  93. .strip()
  94. .split('\n')
  95. )
  96. except Exception as e: # pylint: disable=W0703
  97. logging.warning(str(e))
  98. files = []
  99. return [os.path.join(path, f) for f in files] if full_path else files
  100. def is_in_directory(file_path: str, folder: str) -> bool:
  101. return os.path.realpath(file_path).startswith(os.path.realpath(folder) + os.sep)
  102. def to_list(s: Any) -> List[Any]:
  103. if isinstance(s, (set, tuple)):
  104. return list(s)
  105. if isinstance(s, list):
  106. return s
  107. return [s]
  108. ####################
  109. # Pytest Utilities #
  110. ####################
  111. @dataclass
  112. class PytestApp:
  113. path: str
  114. target: str
  115. config: str
  116. def __hash__(self) -> int:
  117. return hash((self.path, self.target, self.config))
  118. @dataclass
  119. class PytestCase:
  120. path: str
  121. name: str
  122. apps: Set[PytestApp]
  123. nightly_run: bool
  124. def __hash__(self) -> int:
  125. return hash((self.path, self.name, self.apps, self.nightly_run))
  126. class PytestCollectPlugin:
  127. def __init__(self, target: str) -> None:
  128. self.target = target
  129. self.cases: List[PytestCase] = []
  130. @staticmethod
  131. def get_param(item: 'Function', key: str, default: Any = None) -> Any:
  132. if not hasattr(item, 'callspec'):
  133. raise ValueError(f'Function {item} does not have params')
  134. return item.callspec.params.get(key, default) or default
  135. def pytest_report_collectionfinish(self, items: List['Function']) -> None:
  136. from pytest_embedded.plugin import parse_multi_dut_args
  137. for item in items:
  138. count = 1
  139. case_path = str(item.path)
  140. case_name = item.originalname
  141. target = self.target
  142. # funcargs is not calculated while collection
  143. if hasattr(item, 'callspec'):
  144. count = item.callspec.params.get('count', 1)
  145. app_paths = to_list(
  146. parse_multi_dut_args(
  147. count,
  148. self.get_param(item, 'app_path', os.path.dirname(case_path)),
  149. )
  150. )
  151. configs = to_list(parse_multi_dut_args(count, self.get_param(item, 'config', 'default')))
  152. targets = to_list(parse_multi_dut_args(count, self.get_param(item, 'target', target)))
  153. else:
  154. app_paths = [os.path.dirname(case_path)]
  155. configs = ['default']
  156. targets = [target]
  157. case_apps = set()
  158. for i in range(count):
  159. case_apps.add(PytestApp(app_paths[i], targets[i], configs[i]))
  160. self.cases.append(
  161. PytestCase(
  162. case_path,
  163. case_name,
  164. case_apps,
  165. 'nightly_run' in [marker.name for marker in item.iter_markers()],
  166. )
  167. )
  168. def get_pytest_files(paths: List[str]) -> List[str]:
  169. # this is a workaround to solve pytest collector super slow issue
  170. # benchmark with
  171. # - time pytest -m esp32 --collect-only
  172. # user=15.57s system=1.35s cpu=95% total=17.741
  173. # - time { find -name 'pytest_*.py'; } | xargs pytest -m esp32 --collect-only
  174. # user=0.11s system=0.63s cpu=36% total=2.044
  175. # user=1.76s system=0.22s cpu=43% total=4.539
  176. # use glob.glob would also save a bunch of time
  177. pytest_scripts: Set[str] = set()
  178. for p in paths:
  179. path = Path(p)
  180. pytest_scripts.update(str(_p) for _p in path.glob('**/pytest_*.py') if 'managed_components' not in _p.parts)
  181. return list(pytest_scripts)
  182. def get_pytest_cases(
  183. paths: Union[str, List[str]],
  184. target: str = 'all',
  185. marker_expr: Optional[str] = None,
  186. filter_expr: Optional[str] = None,
  187. ) -> List[PytestCase]:
  188. import pytest
  189. from _pytest.config import ExitCode
  190. if target == 'all':
  191. targets = SUPPORTED_TARGETS + PREVIEW_TARGETS
  192. else:
  193. targets = [target]
  194. paths = to_list(paths)
  195. origin_include_nightly_run_env = os.getenv('INCLUDE_NIGHTLY_RUN')
  196. origin_nightly_run_env = os.getenv('NIGHTLY_RUN')
  197. # disable the env vars to get all test cases
  198. if 'INCLUDE_NIGHTLY_RUN' in os.environ:
  199. os.environ.pop('INCLUDE_NIGHTLY_RUN')
  200. if 'NIGHTLY_RUN' in os.environ:
  201. os.environ.pop('NIGHTLY_RUN')
  202. # collect all cases
  203. os.environ['INCLUDE_NIGHTLY_RUN'] = '1'
  204. cases = [] # type: List[PytestCase]
  205. pytest_scripts = get_pytest_files(paths)
  206. if not pytest_scripts:
  207. print(f'WARNING: no pytest scripts found for target {target} under paths {", ".join(paths)}')
  208. return cases
  209. for target in targets:
  210. collector = PytestCollectPlugin(target)
  211. with io.StringIO() as buf:
  212. with redirect_stdout(buf):
  213. cmd = ['--collect-only', *pytest_scripts, '--target', target, '-q']
  214. if marker_expr:
  215. cmd.extend(['-m', marker_expr])
  216. if filter_expr:
  217. cmd.extend(['-k', filter_expr])
  218. res = pytest.main(cmd, plugins=[collector])
  219. if res.value != ExitCode.OK:
  220. if res.value == ExitCode.NO_TESTS_COLLECTED:
  221. print(f'WARNING: no pytest app found for target {target} under paths {", ".join(paths)}')
  222. else:
  223. print(buf.getvalue())
  224. raise RuntimeError(
  225. f'pytest collection failed at {", ".join(paths)} with command \"{" ".join(cmd)}\"'
  226. )
  227. cases.extend(collector.cases)
  228. # revert back the env vars
  229. if origin_include_nightly_run_env is not None:
  230. os.environ['INCLUDE_NIGHTLY_RUN'] = origin_include_nightly_run_env
  231. if origin_nightly_run_env is not None:
  232. os.environ['NIGHTLY_RUN'] = origin_nightly_run_env
  233. return cases
  234. ##################
  235. # TTFW Utilities #
  236. ##################
  237. def get_ttfw_cases(paths: Union[str, List[str]]) -> List[Any]:
  238. """
  239. Get the test cases from ttfw_idf under the given paths
  240. :param paths: list of paths to search
  241. """
  242. try:
  243. from ttfw_idf.IDFAssignTest import IDFAssignTest
  244. except ImportError:
  245. sys.path.append(os.path.join(IDF_PATH, 'tools', 'ci', 'python_packages'))
  246. from ttfw_idf.IDFAssignTest import IDFAssignTest
  247. # mock CI_JOB_ID if not exists
  248. if not os.environ.get('CI_JOB_ID'):
  249. os.environ['CI_JOB_ID'] = '1'
  250. cases = []
  251. for path in to_list(paths):
  252. assign = IDFAssignTest(path, os.path.join(IDF_PATH, '.gitlab', 'ci', 'target-test.yml'))
  253. with contextlib.redirect_stdout(None): # swallow stdout
  254. try:
  255. cases += assign.search_cases()
  256. except ImportError as e:
  257. logging.error(str(e))
  258. return cases
  259. def get_ttfw_app_paths(paths: Union[str, List[str]], target: Optional[str] = None) -> Set[str]:
  260. """
  261. Get the app paths from ttfw_idf under the given paths
  262. """
  263. from idf_build_apps import CMakeApp
  264. cases = get_ttfw_cases(paths)
  265. res: Set[str] = set()
  266. for case in cases:
  267. if not target or target == case.case_info['target'].lower():
  268. # ttfw has no good way to detect the app path for master-slave tests
  269. # the apps real location may be the sub folder of the test script path
  270. # check if the current folder is an app, if it's not, add all its subfolders if they are apps
  271. # only one level down
  272. _app_dir = case.case_info['app_dir']
  273. if CMakeApp.is_app(_app_dir):
  274. res.add(_app_dir)
  275. else:
  276. for child in os.listdir(_app_dir):
  277. sub_path = os.path.join(_app_dir, child)
  278. if os.path.isdir(sub_path) and CMakeApp.is_app(sub_path):
  279. res.add(sub_path)
  280. return res