conftest.py 12 KB

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