conftest.py 11 KB

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