conftest.py 14 KB

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