conftest.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 multi_dut_argument, multi_dut_fixture
  30. from pytest_embedded.utils import find_by_suffix
  31. from pytest_embedded_idf.dut import IdfDut
  32. SUPPORTED_TARGETS = ['esp32', 'esp32s2', 'esp32c3', 'esp32s3', 'esp32c2']
  33. PREVIEW_TARGETS = ['linux', 'esp32h2']
  34. DEFAULT_SDKCONFIG = 'default'
  35. ##################
  36. # Help Functions #
  37. ##################
  38. def is_target_marker(marker: str) -> bool:
  39. if marker.startswith('esp32') or marker.startswith('esp8') or marker == 'linux':
  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. def get_target_marker(markexpr: str) -> str:
  47. candidates = set()
  48. # we use `-m "esp32 and generic"` in our CI to filter the test cases
  49. for marker in markexpr.split('and'):
  50. marker = marker.strip()
  51. if is_target_marker(marker):
  52. candidates.add(marker)
  53. if len(candidates) > 1:
  54. raise ValueError(
  55. f'Specified more than one target markers: {candidates}. Please specify no more than one.'
  56. )
  57. elif len(candidates) == 1:
  58. return candidates.pop()
  59. else:
  60. raise ValueError(
  61. 'Please specify one target marker via "--target [TARGET]" or via "-m [TARGET]"'
  62. )
  63. ############
  64. # Fixtures #
  65. ############
  66. _TEST_SESSION_TMPDIR = os.path.join(
  67. os.path.dirname(__file__),
  68. 'pytest_embedded_log',
  69. datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
  70. )
  71. os.makedirs(_TEST_SESSION_TMPDIR, exist_ok=True)
  72. @pytest.fixture(scope='session', autouse=True)
  73. def session_tempdir() -> str:
  74. return _TEST_SESSION_TMPDIR
  75. @pytest.fixture()
  76. def log_minimum_free_heap_size(dut: IdfDut, config: str) -> Callable[..., None]:
  77. def real_func() -> None:
  78. res = dut.expect(r'Minimum free heap size: (\d+) bytes')
  79. logging.info(
  80. '\n------ heap size info ------\n'
  81. '[app_name] {}\n'
  82. '[config_name] {}\n'
  83. '[target] {}\n'
  84. '[minimum_free_heap_size] {} Bytes\n'
  85. '------ heap size end ------'.format(
  86. os.path.basename(dut.app.app_path),
  87. config,
  88. dut.target,
  89. res.group(1).decode('utf8'),
  90. )
  91. )
  92. return real_func
  93. @pytest.fixture
  94. @multi_dut_argument
  95. def config(request: FixtureRequest) -> str:
  96. return getattr(request, 'param', None) or DEFAULT_SDKCONFIG
  97. @pytest.fixture
  98. def test_func_name(request: FixtureRequest) -> str:
  99. return request.node.function.__name__ # type: ignore
  100. @pytest.fixture
  101. def test_case_name(request: FixtureRequest, target: str, config: str) -> str:
  102. return format_case_id(target, config, request.node.originalname)
  103. @pytest.fixture
  104. @multi_dut_fixture
  105. def build_dir(app_path: str, target: Optional[str], config: Optional[str]) -> str:
  106. """
  107. Check local build dir with the following priority:
  108. 1. build_<target>_<config>
  109. 2. build_<target>
  110. 3. build_<config>
  111. 4. build
  112. Args:
  113. app_path: app path
  114. target: target
  115. config: config
  116. Returns:
  117. valid build directory
  118. """
  119. check_dirs = []
  120. if target is not None and config is not None:
  121. check_dirs.append(f'build_{target}_{config}')
  122. if target is not None:
  123. check_dirs.append(f'build_{target}')
  124. if config is not None:
  125. check_dirs.append(f'build_{config}')
  126. check_dirs.append('build')
  127. for check_dir in check_dirs:
  128. binary_path = os.path.join(app_path, check_dir)
  129. if os.path.isdir(binary_path):
  130. logging.info(f'find valid binary path: {binary_path}')
  131. return check_dir
  132. logging.warning(
  133. 'checking binary path: %s... missing... try another place', binary_path
  134. )
  135. recommend_place = check_dirs[0]
  136. logging.error(
  137. f'no build dir valid. Please build the binary via "idf.py -B {recommend_place} build" and run pytest again'
  138. )
  139. sys.exit(1)
  140. @pytest.fixture(autouse=True)
  141. @multi_dut_fixture
  142. def junit_properties(
  143. test_case_name: str, record_xml_attribute: Callable[[str, object], None]
  144. ) -> None:
  145. """
  146. This fixture is autoused and will modify the junit report test case name to <target>.<config>.<case_name>
  147. """
  148. record_xml_attribute('name', test_case_name)
  149. ##################
  150. # Hook functions #
  151. ##################
  152. def pytest_addoption(parser: pytest.Parser) -> None:
  153. base_group = parser.getgroup('idf')
  154. base_group.addoption(
  155. '--sdkconfig',
  156. help='sdkconfig postfix, like sdkconfig.ci.<config>. (Default: None, which would build all found apps)',
  157. )
  158. base_group.addoption(
  159. '--known-failure-cases-file', help='known failure cases file path'
  160. )
  161. _idf_pytest_embedded_key = pytest.StashKey['IdfPytestEmbedded']
  162. def pytest_configure(config: Config) -> None:
  163. # cli option "--target"
  164. target = config.getoption('target') or ''
  165. help_commands = ['--help', '--fixtures', '--markers', '--version']
  166. for cmd in help_commands:
  167. if cmd in config.invocation_params.args:
  168. target = 'unneeded'
  169. break
  170. if not target: # also could specify through markexpr via "-m"
  171. target = get_target_marker(config.getoption('markexpr') or '')
  172. config.stash[_idf_pytest_embedded_key] = IdfPytestEmbedded(
  173. target=target,
  174. sdkconfig=config.getoption('sdkconfig'),
  175. known_failure_cases_file=config.getoption('known_failure_cases_file'),
  176. )
  177. config.pluginmanager.register(config.stash[_idf_pytest_embedded_key])
  178. def pytest_unconfigure(config: Config) -> None:
  179. _pytest_embedded = config.stash.get(_idf_pytest_embedded_key, None)
  180. if _pytest_embedded:
  181. del config.stash[_idf_pytest_embedded_key]
  182. config.pluginmanager.unregister(_pytest_embedded)
  183. class IdfPytestEmbedded:
  184. def __init__(
  185. self,
  186. target: Optional[str] = None,
  187. sdkconfig: Optional[str] = None,
  188. known_failure_cases_file: Optional[str] = None,
  189. ):
  190. # CLI options to filter the test cases
  191. self.target = target
  192. self.sdkconfig = sdkconfig
  193. self.known_failure_patterns = self._parse_known_failure_cases_file(
  194. known_failure_cases_file
  195. )
  196. self._failed_cases: List[
  197. Tuple[str, bool, bool]
  198. ] = [] # (test_case_name, is_known_failure_cases, is_xfail)
  199. @property
  200. def failed_cases(self) -> List[str]:
  201. return [
  202. case
  203. for case, is_known, is_xfail in self._failed_cases
  204. if not is_known and not is_xfail
  205. ]
  206. @property
  207. def known_failure_cases(self) -> List[str]:
  208. return [case for case, is_known, _ in self._failed_cases if is_known]
  209. @property
  210. def xfail_cases(self) -> List[str]:
  211. return [case for case, _, is_xfail in self._failed_cases if is_xfail]
  212. @staticmethod
  213. def _parse_known_failure_cases_file(
  214. known_failure_cases_file: Optional[str] = None,
  215. ) -> List[str]:
  216. if not known_failure_cases_file or not os.path.isfile(known_failure_cases_file):
  217. return []
  218. patterns = []
  219. with open(known_failure_cases_file) as fr:
  220. for line in fr.readlines():
  221. if not line:
  222. continue
  223. if not line.strip():
  224. continue
  225. without_comments = line.split('#')[0].strip()
  226. if without_comments:
  227. patterns.append(without_comments)
  228. return patterns
  229. @pytest.hookimpl(tryfirst=True)
  230. def pytest_sessionstart(self, session: Session) -> None:
  231. if self.target:
  232. self.target = self.target.lower()
  233. session.config.option.target = self.target
  234. @pytest.hookimpl(tryfirst=True)
  235. def pytest_collection_modifyitems(self, items: List[Function]) -> None:
  236. # sort by file path and callspec.config
  237. # implement like this since this is a limitation of pytest, couldn't get fixture values while collecting
  238. # https://github.com/pytest-dev/pytest/discussions/9689
  239. def _get_param_config(_item: Function) -> str:
  240. if hasattr(_item, 'callspec'):
  241. return _item.callspec.params.get('config', DEFAULT_SDKCONFIG) # type: ignore
  242. return DEFAULT_SDKCONFIG
  243. items.sort(key=lambda x: (os.path.dirname(x.path), _get_param_config(x)))
  244. # add markers for special markers
  245. for item in items:
  246. if 'supported_targets' in item.keywords:
  247. for _target in SUPPORTED_TARGETS:
  248. item.add_marker(_target)
  249. if 'preview_targets' in item.keywords:
  250. for _target in PREVIEW_TARGETS:
  251. item.add_marker(_target)
  252. if 'all_targets' in item.keywords:
  253. for _target in [*SUPPORTED_TARGETS, *PREVIEW_TARGETS]:
  254. item.add_marker(_target)
  255. # filter all the test cases with "nightly_run" marker
  256. if os.getenv('INCLUDE_NIGHTLY_RUN') == '1':
  257. # Do not filter nightly_run cases
  258. pass
  259. elif os.getenv('NIGHTLY_RUN') == '1':
  260. items[:] = [
  261. item for item in items if 'nightly_run' in item_marker_names(item)
  262. ]
  263. else:
  264. items[:] = [
  265. item for item in items if 'nightly_run' not in item_marker_names(item)
  266. ]
  267. # filter all the test cases with "--target"
  268. if self.target:
  269. items[:] = [
  270. item for item in items if self.target in item_marker_names(item)
  271. ]
  272. # filter all the test cases with cli option "config"
  273. if self.sdkconfig:
  274. items[:] = [
  275. item for item in items if _get_param_config(item) == self.sdkconfig
  276. ]
  277. def pytest_runtest_makereport(
  278. self, item: Function, call: CallInfo[None]
  279. ) -> Optional[TestReport]:
  280. if call.when == 'setup':
  281. return None
  282. report = TestReport.from_item_and_call(item, call)
  283. if report.outcome == 'failed':
  284. test_case_name = item.funcargs.get('test_case_name', '')
  285. is_known_failure = self._is_known_failure(test_case_name)
  286. is_xfail = report.keywords.get('xfail', False)
  287. self._failed_cases.append((test_case_name, is_known_failure, is_xfail))
  288. return report
  289. def _is_known_failure(self, case_id: str) -> bool:
  290. for pattern in self.known_failure_patterns:
  291. if case_id == pattern:
  292. return True
  293. if fnmatch(case_id, pattern):
  294. return True
  295. return False
  296. @pytest.hookimpl(trylast=True)
  297. def pytest_runtest_teardown(self, item: Function) -> None:
  298. """
  299. Format the test case generated junit reports
  300. """
  301. tempdir = item.funcargs.get('test_case_tempdir')
  302. if not tempdir:
  303. return
  304. junits = find_by_suffix('.xml', tempdir)
  305. if not junits:
  306. return
  307. target = item.funcargs['target']
  308. config = item.funcargs['config']
  309. for junit in junits:
  310. xml = ET.parse(junit)
  311. testcases = xml.findall('.//testcase')
  312. for case in testcases:
  313. case.attrib['name'] = format_case_id(
  314. target, config, case.attrib['name']
  315. )
  316. if 'file' in case.attrib:
  317. case.attrib['file'] = case.attrib['file'].replace(
  318. '/IDF/', ''
  319. ) # our unity test framework
  320. xml.write(junit)
  321. def pytest_sessionfinish(self, session: Session, exitstatus: int) -> None:
  322. if exitstatus != 0 and self.known_failure_cases and not self.failed_cases:
  323. session.exitstatus = 0
  324. def pytest_terminal_summary(self, terminalreporter: TerminalReporter) -> None:
  325. if self.known_failure_cases:
  326. terminalreporter.section('Known failure cases', bold=True, yellow=True)
  327. terminalreporter.line('\n'.join(self.known_failure_cases))
  328. if self.xfail_cases:
  329. terminalreporter.section('xfail cases', bold=True, yellow=True)
  330. terminalreporter.line('\n'.join(self.xfail_cases))
  331. if self.failed_cases:
  332. terminalreporter.section('Failed cases', bold=True, red=True)
  333. terminalreporter.line('\n'.join(self.failed_cases))