conftest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. # SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. # pylint: disable=W0621 # redefined-outer-name
  4. # This file is a pytest root configuration file and provide the following functionalities:
  5. # 1. Defines a few fixtures that could be used under the whole project.
  6. # 2. Defines a few hook functions.
  7. #
  8. # IDF is using [pytest](https://github.com/pytest-dev/pytest) and
  9. # [pytest-embedded plugin](https://github.com/espressif/pytest-embedded) as its example test framework.
  10. #
  11. # This is an experimental feature, and if you found any bug or have any question, please report to
  12. # https://github.com/espressif/pytest-embedded/issues
  13. import logging
  14. import os
  15. import sys
  16. import xml.etree.ElementTree as ET
  17. from fnmatch import fnmatch
  18. from typing import Callable, List, Optional, Tuple
  19. import pytest
  20. from _pytest.config import Config
  21. from _pytest.fixtures import FixtureRequest
  22. from _pytest.main import Session
  23. from _pytest.nodes import Item
  24. from _pytest.python import Function
  25. from _pytest.reports import TestReport
  26. from _pytest.runner import CallInfo
  27. from _pytest.terminal import TerminalReporter
  28. from pytest_embedded.plugin import parse_configuration
  29. from pytest_embedded.utils import find_by_suffix
  30. SUPPORTED_TARGETS = ['esp32', 'esp32s2', 'esp32c3', 'esp32s3']
  31. PREVIEW_TARGETS = ['linux', 'esp32h2', 'esp32c2']
  32. DEFAULT_SDKCONFIG = 'default'
  33. ##################
  34. # Help Functions #
  35. ##################
  36. def is_target_marker(marker: str) -> bool:
  37. if marker.startswith('esp32'):
  38. return True
  39. if marker.startswith('esp8'):
  40. return True
  41. return False
  42. def format_case_id(target: Optional[str], config: Optional[str], case: str) -> str:
  43. return f'{target}.{config}.{case}'
  44. def item_marker_names(item: Item) -> List[str]:
  45. return [marker.name for marker in item.iter_markers()]
  46. ############
  47. # Fixtures #
  48. ############
  49. @pytest.fixture
  50. def config(request: FixtureRequest) -> str:
  51. return getattr(request, 'param', None) or DEFAULT_SDKCONFIG
  52. @pytest.fixture
  53. def test_func_name(request: FixtureRequest) -> str:
  54. return request.node.function.__name__ # type: ignore
  55. @pytest.fixture
  56. def test_case_name(request: FixtureRequest, target: str, config: str) -> str:
  57. return format_case_id(target, config, request.node.originalname)
  58. @pytest.fixture
  59. @parse_configuration
  60. def build_dir(
  61. request: FixtureRequest, app_path: str, target: Optional[str], config: Optional[str]
  62. ) -> str:
  63. """
  64. Check local build dir with the following priority:
  65. 1. build_<target>_<config>
  66. 2. build_<target>
  67. 3. build_<config>
  68. 4. build
  69. Args:
  70. request: pytest fixture
  71. app_path: app path
  72. target: target
  73. config: config
  74. Returns:
  75. valid build directory
  76. """
  77. param_or_cli: str = getattr(request, 'param', None) or request.config.getoption(
  78. 'build_dir'
  79. )
  80. if param_or_cli is not None: # respect the param and the cli
  81. return param_or_cli
  82. check_dirs = []
  83. if target is not None and config is not None:
  84. check_dirs.append(f'build_{target}_{config}')
  85. if target is not None:
  86. check_dirs.append(f'build_{target}')
  87. if config is not None:
  88. check_dirs.append(f'build_{config}')
  89. check_dirs.append('build')
  90. for check_dir in check_dirs:
  91. binary_path = os.path.join(app_path, check_dir)
  92. if os.path.isdir(binary_path):
  93. logging.info(f'find valid binary path: {binary_path}')
  94. return check_dir
  95. logging.warning(
  96. 'checking binary path: %s... missing... try another place', binary_path
  97. )
  98. recommend_place = check_dirs[0]
  99. logging.error(
  100. f'no build dir valid. Please build the binary via "idf.py -B {recommend_place} build" and run pytest again'
  101. )
  102. sys.exit(1)
  103. @pytest.fixture(autouse=True)
  104. def junit_properties(
  105. test_case_name: str, record_xml_attribute: Callable[[str, object], None]
  106. ) -> None:
  107. """
  108. This fixture is autoused and will modify the junit report test case name to <target>.<config>.<case_name>
  109. """
  110. record_xml_attribute('name', test_case_name)
  111. ##################
  112. # Hook functions #
  113. ##################
  114. def pytest_addoption(parser: pytest.Parser) -> None:
  115. base_group = parser.getgroup('idf')
  116. base_group.addoption(
  117. '--sdkconfig',
  118. help='sdkconfig postfix, like sdkconfig.ci.<config>. (Default: None, which would build all found apps)',
  119. )
  120. base_group.addoption(
  121. '--known-failure-cases-file', help='known failure cases file path'
  122. )
  123. _idf_pytest_embedded_key = pytest.StashKey['IdfPytestEmbedded']
  124. def pytest_configure(config: Config) -> None:
  125. config.stash[_idf_pytest_embedded_key] = IdfPytestEmbedded(
  126. target=config.getoption('target'),
  127. sdkconfig=config.getoption('sdkconfig'),
  128. known_failure_cases_file=config.getoption('known_failure_cases_file'),
  129. )
  130. config.pluginmanager.register(config.stash[_idf_pytest_embedded_key])
  131. def pytest_unconfigure(config: Config) -> None:
  132. _pytest_embedded = config.stash.get(_idf_pytest_embedded_key, None)
  133. if _pytest_embedded:
  134. del config.stash[_idf_pytest_embedded_key]
  135. config.pluginmanager.unregister(_pytest_embedded)
  136. class IdfPytestEmbedded:
  137. def __init__(
  138. self,
  139. target: Optional[str] = None,
  140. sdkconfig: Optional[str] = None,
  141. known_failure_cases_file: Optional[str] = None,
  142. ):
  143. # CLI options to filter the test cases
  144. self.target = target
  145. self.sdkconfig = sdkconfig
  146. self.known_failure_patterns = self._parse_known_failure_cases_file(
  147. known_failure_cases_file
  148. )
  149. self._failed_cases: List[
  150. Tuple[str, bool]
  151. ] = [] # (test_case_name, is_known_failure_cases)
  152. @property
  153. def failed_cases(self) -> List[str]:
  154. return [case for case, is_known in self._failed_cases if not is_known]
  155. @property
  156. def known_failure_cases(self) -> List[str]:
  157. return [case for case, is_known in self._failed_cases if is_known]
  158. @staticmethod
  159. def _parse_known_failure_cases_file(
  160. known_failure_cases_file: Optional[str] = None,
  161. ) -> List[str]:
  162. if not known_failure_cases_file or not os.path.isfile(known_failure_cases_file):
  163. return []
  164. patterns = []
  165. with open(known_failure_cases_file) as fr:
  166. for line in fr.readlines():
  167. if not line:
  168. continue
  169. if not line.strip():
  170. continue
  171. without_comments = line.split('#')[0].strip()
  172. if without_comments:
  173. patterns.append(without_comments)
  174. return patterns
  175. @pytest.hookimpl(tryfirst=True)
  176. def pytest_sessionstart(self, session: Session) -> None:
  177. if self.target:
  178. self.target = self.target.lower()
  179. session.config.option.target = self.target
  180. @pytest.hookimpl(tryfirst=True)
  181. def pytest_collection_modifyitems(self, items: List[Function]) -> None:
  182. # sort by file path and callspec.config
  183. # implement like this since this is a limitation of pytest, couldn't get fixture values while collecting
  184. # https://github.com/pytest-dev/pytest/discussions/9689
  185. def _get_param_config(_item: Function) -> str:
  186. if hasattr(_item, 'callspec'):
  187. return _item.callspec.params.get('config', DEFAULT_SDKCONFIG) # type: ignore
  188. return DEFAULT_SDKCONFIG
  189. items.sort(key=lambda x: (os.path.dirname(x.path), _get_param_config(x)))
  190. # add markers for special markers
  191. for item in items:
  192. if 'supported_targets' in item_marker_names(item):
  193. for _target in SUPPORTED_TARGETS:
  194. item.add_marker(_target)
  195. if 'preview_targets' in item_marker_names(item):
  196. for _target in PREVIEW_TARGETS:
  197. item.add_marker(_target)
  198. if 'all_targets' in item_marker_names(item):
  199. for _target in [*SUPPORTED_TARGETS, *PREVIEW_TARGETS]:
  200. item.add_marker(_target)
  201. # filter all the test cases with "--target"
  202. if self.target:
  203. items[:] = [
  204. item for item in items if self.target in item_marker_names(item)
  205. ]
  206. # filter all the test cases with cli option "config"
  207. if self.sdkconfig:
  208. items[:] = [
  209. item for item in items if _get_param_config(item) == self.sdkconfig
  210. ]
  211. def pytest_runtest_makereport(
  212. self, item: Function, call: CallInfo[None]
  213. ) -> Optional[TestReport]:
  214. if call.when == 'setup':
  215. return None
  216. report = TestReport.from_item_and_call(item, call)
  217. if report.outcome == 'failed':
  218. test_case_name = item.funcargs.get('test_case_name', '')
  219. is_known_failure = self._is_known_failure(test_case_name)
  220. self._failed_cases.append((test_case_name, is_known_failure))
  221. return report
  222. def _is_known_failure(self, case_id: str) -> bool:
  223. for pattern in self.known_failure_patterns:
  224. if case_id == pattern:
  225. return True
  226. if fnmatch(case_id, pattern):
  227. return True
  228. return False
  229. @pytest.hookimpl(trylast=True)
  230. def pytest_runtest_teardown(self, item: Function) -> None:
  231. """
  232. Format the test case generated junit reports
  233. """
  234. tempdir = item.funcargs.get('test_case_tempdir')
  235. if not tempdir:
  236. return
  237. junits = find_by_suffix('.xml', tempdir)
  238. if not junits:
  239. return
  240. target = item.funcargs['target']
  241. config = item.funcargs['config']
  242. for junit in junits:
  243. xml = ET.parse(junit)
  244. testcases = xml.findall('.//testcase')
  245. for case in testcases:
  246. case.attrib['name'] = format_case_id(
  247. target, config, case.attrib['name']
  248. )
  249. if 'file' in case.attrib:
  250. case.attrib['file'] = case.attrib['file'].replace(
  251. '/IDF/', ''
  252. ) # our unity test framework
  253. xml.write(junit)
  254. def pytest_sessionfinish(self, session: Session, exitstatus: int) -> None:
  255. if exitstatus != 0 and self.known_failure_cases and not self.failed_cases:
  256. session.exitstatus = 0
  257. def pytest_terminal_summary(self, terminalreporter: TerminalReporter) -> None:
  258. if self.known_failure_cases:
  259. terminalreporter.section('Known failure cases', bold=True, yellow=True)
  260. terminalreporter.line('\n'.join(self.known_failure_cases))
  261. if self.failed_cases:
  262. terminalreporter.section('Failed cases', bold=True, red=True)
  263. terminalreporter.line('\n'.join(self.failed_cases))