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