conftest.py 14 KB

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