conftest.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 re
  16. import sys
  17. import xml.etree.ElementTree as ET
  18. from datetime import datetime
  19. from fnmatch import fnmatch
  20. from typing import Callable, List, Optional, Tuple
  21. import pytest
  22. from _pytest.config import Config, ExitCode
  23. from _pytest.fixtures import FixtureRequest
  24. from _pytest.main import Session
  25. from _pytest.nodes import Item
  26. from _pytest.python import Function
  27. from _pytest.reports import TestReport
  28. from _pytest.runner import CallInfo
  29. from _pytest.terminal import TerminalReporter
  30. from pytest_embedded.plugin import multi_dut_argument, multi_dut_fixture
  31. from pytest_embedded.utils import find_by_suffix
  32. from pytest_embedded_idf.dut import IdfDut
  33. try:
  34. from idf_ci_utils import to_list
  35. from idf_unity_tester import CaseTester
  36. except ImportError:
  37. sys.path.append(os.path.join(os.path.dirname(__file__), 'tools', 'ci'))
  38. from idf_ci_utils import to_list
  39. from idf_unity_tester import CaseTester
  40. try:
  41. import common_test_methods # noqa: F401
  42. except ImportError:
  43. sys.path.append(os.path.join(os.path.dirname(__file__), 'tools', 'ci', 'python_packages'))
  44. import common_test_methods # noqa: F401
  45. SUPPORTED_TARGETS = ['esp32', 'esp32s2', 'esp32c3', 'esp32s3', 'esp32c2', 'esp32c6', 'esp32h2']
  46. PREVIEW_TARGETS = ['esp32h4'] # this PREVIEW_TARGETS excludes 'linux' target
  47. DEFAULT_SDKCONFIG = 'default'
  48. TARGET_MARKERS = {
  49. 'esp32': 'support esp32 target',
  50. 'esp32s2': 'support esp32s2 target',
  51. 'esp32s3': 'support esp32s3 target',
  52. 'esp32c3': 'support esp32c3 target',
  53. 'esp32c2': 'support esp32c2 target',
  54. 'esp32c6': 'support esp32c6 target',
  55. 'esp32h4': 'support esp32h4 target',
  56. 'esp32h2': 'support esp32h2 target',
  57. 'linux': 'support linux target',
  58. }
  59. SPECIAL_MARKERS = {
  60. 'supported_targets': "support all officially announced supported targets ('esp32', 'esp32s2', 'esp32c3', 'esp32s3', 'esp32c2', 'esp32c6')",
  61. 'preview_targets': "support all preview targets ('esp32h4')",
  62. 'all_targets': 'support all targets, including supported ones and preview ones',
  63. 'temp_skip_ci': 'temp skip tests for specified targets only in ci',
  64. 'temp_skip': 'temp skip tests for specified targets both in ci and locally',
  65. 'nightly_run': 'tests should be executed as part of the nightly trigger pipeline',
  66. 'host_test': 'tests which should not be built at the build stage, and instead built in host_test stage',
  67. 'qemu': 'build and test using qemu-system-xtensa, not real target',
  68. }
  69. ENV_MARKERS = {
  70. # single-dut markers
  71. 'generic': 'tests should be run on generic runners',
  72. 'flash_suspend': 'support flash suspend feature',
  73. 'ip101': 'connected via wired 10/100M ethernet',
  74. 'lan8720': 'connected via LAN8720 ethernet transceiver',
  75. 'quad_psram': 'runners with quad psram',
  76. 'octal_psram': 'runners with octal psram',
  77. 'usb_host': 'usb host runners',
  78. 'usb_host_flash_disk': 'usb host runners with USB flash disk attached',
  79. 'usb_device': 'usb device runners',
  80. 'ethernet_ota': 'ethernet OTA runners',
  81. 'flash_encryption': 'Flash Encryption runners',
  82. 'flash_encryption_f4r8': 'Flash Encryption runners with 4-line flash and 8-line psram',
  83. 'flash_encryption_f8r8': 'Flash Encryption runners with 8-line flash and 8-line psram',
  84. 'flash_multi': 'Multiple flash chips tests',
  85. 'psram': 'Chip has 4-line psram',
  86. 'ir_transceiver': 'runners with a pair of IR transmitter and receiver',
  87. 'twai_transceiver': 'runners with a TWAI PHY transceiver',
  88. 'flash_encryption_wifi_high_traffic': 'Flash Encryption runners with wifi high traffic support',
  89. 'ethernet': 'ethernet runner',
  90. 'ethernet_flash_8m': 'ethernet runner with 8mb flash',
  91. 'ethernet_router': 'both the runner and dut connect to the same router through ethernet NIC',
  92. 'wifi_ap': 'a wifi AP in the environment',
  93. 'wifi_router': 'both the runner and dut connect to the same wifi router',
  94. 'wifi_high_traffic': 'wifi high traffic runners',
  95. 'wifi_wlan': 'wifi runner with a wireless NIC',
  96. 'Example_ShieldBox_Basic': 'basic configuration of the AP and ESP DUT placed in shielded box',
  97. 'Example_ShieldBox': 'multiple shielded APs connected to shielded ESP DUT via RF cable with programmable attenuator',
  98. 'xtal_26mhz': 'runner with 26MHz xtal on board',
  99. 'xtal_40mhz': 'runner with 40MHz xtal on board',
  100. 'external_flash': 'external flash memory connected via VSPI (FSPI)',
  101. 'sdcard_sdmode': 'sdcard running in SD mode',
  102. 'sdcard_spimode': 'sdcard running in SPI mode',
  103. 'MSPI_F8R8': 'runner with Octal Flash and Octal PSRAM',
  104. 'MSPI_F4R8': 'runner with Quad Flash and Octal PSRAM',
  105. 'MSPI_F4R4': 'runner with Quad Flash and Quad PSRAM',
  106. 'jtag': 'runner where the chip is accessible through JTAG as well',
  107. 'adc': 'ADC related tests should run on adc runners',
  108. 'xtal32k': 'Runner with external 32k crystal connected',
  109. 'no32kXtal': 'Runner with no external 32k crystal connected',
  110. 'multi_dut_modbus_rs485': 'a pair of runners connected by RS485 bus',
  111. 'psramv0': 'Runner with PSRAM version 0',
  112. # multi-dut markers
  113. 'ieee802154': 'ieee802154 related tests should run on ieee802154 runners.',
  114. 'openthread_br': 'tests should be used for openthread border router.',
  115. 'wifi_two_dut': 'tests should be run on runners which has two wifi duts connected.',
  116. 'generic_multi_device': 'generic multiple devices whose corresponding gpio pins are connected to each other.',
  117. 'twai_network': 'multiple runners form a TWAI network.',
  118. 'sdio_master_slave': 'Test sdio multi board.',
  119. }
  120. ##################
  121. # Help Functions #
  122. ##################
  123. def format_case_id(target: Optional[str], config: Optional[str], case: str) -> str:
  124. return f'{target}.{config}.{case}'
  125. def item_marker_names(item: Item) -> List[str]:
  126. return [marker.name for marker in item.iter_markers()]
  127. def item_target_marker_names(item: Item) -> List[str]:
  128. res = set()
  129. for marker in item.iter_markers():
  130. if marker.name in TARGET_MARKERS:
  131. res.add(marker.name)
  132. return sorted(res)
  133. def item_env_marker_names(item: Item) -> List[str]:
  134. res = set()
  135. for marker in item.iter_markers():
  136. if marker.name in ENV_MARKERS:
  137. res.add(marker.name)
  138. return sorted(res)
  139. def item_skip_targets(item: Item) -> List[str]:
  140. def _get_temp_markers_disabled_targets(marker_name: str) -> List[str]:
  141. temp_marker = item.get_closest_marker(marker_name)
  142. if not temp_marker:
  143. return []
  144. # temp markers should always use keyword arguments `targets` and `reason`
  145. if not temp_marker.kwargs.get('targets') or not temp_marker.kwargs.get('reason'):
  146. raise ValueError(
  147. f'`{marker_name}` should always use keyword arguments `targets` and `reason`. '
  148. f'For example: '
  149. f'`@pytest.mark.{marker_name}(targets=["esp32"], reason="IDF-xxxx, will fix it ASAP")`'
  150. )
  151. return to_list(temp_marker.kwargs['targets']) # type: ignore
  152. temp_skip_ci_targets = _get_temp_markers_disabled_targets('temp_skip_ci')
  153. temp_skip_targets = _get_temp_markers_disabled_targets('temp_skip')
  154. # in CI we skip the union of `temp_skip` and `temp_skip_ci`
  155. if os.getenv('CI_JOB_ID'):
  156. skip_targets = list(set(temp_skip_ci_targets).union(set(temp_skip_targets)))
  157. else: # we use `temp_skip` locally
  158. skip_targets = temp_skip_targets
  159. return skip_targets
  160. def get_target_marker_from_expr(markexpr: str) -> str:
  161. candidates = set()
  162. # we use `-m "esp32 and generic"` in our CI to filter the test cases
  163. # this doesn't cover all use cases, but fit what we do in CI.
  164. for marker in markexpr.split('and'):
  165. marker = marker.strip()
  166. if marker in TARGET_MARKERS:
  167. candidates.add(marker)
  168. if len(candidates) > 1:
  169. raise ValueError(f'Specified more than one target markers: {candidates}. Please specify no more than one.')
  170. elif len(candidates) == 1:
  171. return candidates.pop()
  172. else:
  173. raise ValueError('Please specify one target marker via "--target [TARGET]" or via "-m [TARGET]"')
  174. ############
  175. # Fixtures #
  176. ############
  177. @pytest.fixture(scope='session')
  178. def idf_path() -> str:
  179. return os.path.dirname(__file__)
  180. @pytest.fixture(scope='session', autouse=True)
  181. def session_tempdir() -> str:
  182. _tmpdir = os.path.join(
  183. os.path.dirname(__file__),
  184. 'pytest_embedded_log',
  185. datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
  186. )
  187. os.makedirs(_tmpdir, exist_ok=True)
  188. return _tmpdir
  189. @pytest.fixture
  190. def case_tester(dut: IdfDut, **kwargs): # type: ignore
  191. yield CaseTester(dut, **kwargs)
  192. @pytest.fixture
  193. @multi_dut_argument
  194. def config(request: FixtureRequest) -> str:
  195. return getattr(request, 'param', None) or DEFAULT_SDKCONFIG
  196. @pytest.fixture
  197. def test_func_name(request: FixtureRequest) -> str:
  198. return request.node.function.__name__ # type: ignore
  199. @pytest.fixture
  200. def test_case_name(request: FixtureRequest, target: str, config: str) -> str:
  201. return format_case_id(target, config, request.node.originalname)
  202. @pytest.fixture
  203. @multi_dut_fixture
  204. def build_dir(app_path: str, target: Optional[str], config: Optional[str]) -> str:
  205. """
  206. Check local build dir with the following priority:
  207. 1. build_<target>_<config>
  208. 2. build_<target>
  209. 3. build_<config>
  210. 4. build
  211. Args:
  212. app_path: app path
  213. target: target
  214. config: config
  215. Returns:
  216. valid build directory
  217. """
  218. if target == 'linux':
  219. # IDF-6644
  220. # hard-coded in components/esp_partition/partition_linux.c
  221. # const char *partition_table_file_name = "build/partition_table/partition-table.bin";
  222. check_dirs = ['build']
  223. else:
  224. check_dirs = []
  225. if target is not None and config is not None:
  226. check_dirs.append(f'build_{target}_{config}')
  227. if target is not None:
  228. check_dirs.append(f'build_{target}')
  229. if config is not None:
  230. check_dirs.append(f'build_{config}')
  231. check_dirs.append('build')
  232. for check_dir in check_dirs:
  233. binary_path = os.path.join(app_path, check_dir)
  234. if os.path.isdir(binary_path):
  235. logging.info(f'find valid binary path: {binary_path}')
  236. return check_dir
  237. logging.warning('checking binary path: %s... missing... try another place', binary_path)
  238. recommend_place = check_dirs[0]
  239. raise ValueError(
  240. f'no build dir valid. Please build the binary via "idf.py -B {recommend_place} build" and run pytest again'
  241. )
  242. @pytest.fixture(autouse=True)
  243. def linux_cd_into_app_folder(app_path: str, target: Optional[str]) -> None:
  244. # IDF-6644
  245. # hard-coded in components/esp_partition/partition_linux.c
  246. # const char *partition_table_file_name = "build/partition_table/partition-table.bin";
  247. if target == 'linux':
  248. os.chdir(app_path)
  249. @pytest.fixture(autouse=True)
  250. @multi_dut_fixture
  251. def junit_properties(test_case_name: str, record_xml_attribute: Callable[[str, object], None]) -> None:
  252. """
  253. This fixture is autoused and will modify the junit report test case name to <target>.<config>.<case_name>
  254. """
  255. record_xml_attribute('name', test_case_name)
  256. ######################
  257. # Log Util Functions #
  258. ######################
  259. @pytest.fixture
  260. def log_performance(record_property: Callable[[str, object], None]) -> Callable[[str, str], None]:
  261. """
  262. log performance item with pre-defined format to the console
  263. and record it under the ``properties`` tag in the junit report if available.
  264. """
  265. def real_func(item: str, value: str) -> None:
  266. """
  267. :param item: performance item name
  268. :param value: performance value
  269. """
  270. logging.info('[Performance][%s]: %s', item, value)
  271. record_property(item, value)
  272. return real_func
  273. @pytest.fixture
  274. def check_performance(idf_path: str) -> Callable[[str, float, str], None]:
  275. """
  276. check if the given performance item meets the passing standard or not
  277. """
  278. def real_func(item: str, value: float, target: str) -> None:
  279. """
  280. :param item: performance item name
  281. :param value: performance item value
  282. :param target: target chip
  283. :raise: AssertionError: if check fails
  284. """
  285. def _find_perf_item(operator: str, path: str) -> float:
  286. with open(path, 'r') as f:
  287. data = f.read()
  288. match = re.search(r'#define\s+IDF_PERFORMANCE_{}_{}\s+([\d.]+)'.format(operator, item.upper()), data)
  289. return float(match.group(1)) # type: ignore
  290. def _check_perf(operator: str, standard_value: float) -> None:
  291. if operator == 'MAX':
  292. ret = value <= standard_value
  293. else:
  294. ret = value >= standard_value
  295. if not ret:
  296. raise AssertionError(
  297. "[Performance] {} value is {}, doesn't meet pass standard {}".format(item, value, standard_value)
  298. )
  299. path_prefix = os.path.join(idf_path, 'components', 'idf_test', 'include')
  300. performance_files = (
  301. os.path.join(path_prefix, target, 'idf_performance_target.h'),
  302. os.path.join(path_prefix, 'idf_performance.h'),
  303. )
  304. found_item = False
  305. for op in ['MIN', 'MAX']:
  306. for performance_file in performance_files:
  307. try:
  308. standard = _find_perf_item(op, performance_file)
  309. except (IOError, AttributeError):
  310. # performance file doesn't exist or match is not found in it
  311. continue
  312. _check_perf(op, standard)
  313. found_item = True
  314. break
  315. if not found_item:
  316. raise AssertionError('Failed to get performance standard for {}'.format(item))
  317. return real_func
  318. @pytest.fixture
  319. def log_minimum_free_heap_size(dut: IdfDut, config: str) -> Callable[..., None]:
  320. def real_func() -> None:
  321. res = dut.expect(r'Minimum free heap size: (\d+) bytes')
  322. logging.info(
  323. '\n------ heap size info ------\n'
  324. '[app_name] {}\n'
  325. '[config_name] {}\n'
  326. '[target] {}\n'
  327. '[minimum_free_heap_size] {} Bytes\n'
  328. '------ heap size end ------'.format(
  329. os.path.basename(dut.app.app_path),
  330. config,
  331. dut.target,
  332. res.group(1).decode('utf8'),
  333. )
  334. )
  335. return real_func
  336. ##################
  337. # Hook functions #
  338. ##################
  339. def pytest_addoption(parser: pytest.Parser) -> None:
  340. base_group = parser.getgroup('idf')
  341. base_group.addoption(
  342. '--sdkconfig',
  343. help='sdkconfig postfix, like sdkconfig.ci.<config>. (Default: None, which would build all found apps)',
  344. )
  345. base_group.addoption('--known-failure-cases-file', help='known failure cases file path')
  346. _idf_pytest_embedded_key = pytest.StashKey['IdfPytestEmbedded']
  347. def pytest_configure(config: Config) -> None:
  348. # cli option "--target"
  349. target = config.getoption('target') or ''
  350. help_commands = ['--help', '--fixtures', '--markers', '--version']
  351. for cmd in help_commands:
  352. if cmd in config.invocation_params.args:
  353. target = 'unneeded'
  354. break
  355. if not target: # also could specify through markexpr via "-m"
  356. target = get_target_marker_from_expr(config.getoption('markexpr') or '')
  357. config.stash[_idf_pytest_embedded_key] = IdfPytestEmbedded(
  358. target=target,
  359. sdkconfig=config.getoption('sdkconfig'),
  360. known_failure_cases_file=config.getoption('known_failure_cases_file'),
  361. )
  362. config.pluginmanager.register(config.stash[_idf_pytest_embedded_key])
  363. for name, description in {**TARGET_MARKERS, **ENV_MARKERS, **SPECIAL_MARKERS}.items():
  364. config.addinivalue_line('markers', f'{name}: {description}')
  365. def pytest_unconfigure(config: Config) -> None:
  366. _pytest_embedded = config.stash.get(_idf_pytest_embedded_key, None)
  367. if _pytest_embedded:
  368. del config.stash[_idf_pytest_embedded_key]
  369. config.pluginmanager.unregister(_pytest_embedded)
  370. class IdfPytestEmbedded:
  371. def __init__(
  372. self,
  373. target: str,
  374. sdkconfig: Optional[str] = None,
  375. known_failure_cases_file: Optional[str] = None,
  376. ):
  377. # CLI options to filter the test cases
  378. self.target = target.lower()
  379. self.sdkconfig = sdkconfig
  380. self.known_failure_patterns = self._parse_known_failure_cases_file(known_failure_cases_file)
  381. self._failed_cases: List[Tuple[str, bool, bool]] = [] # (test_case_name, is_known_failure_cases, is_xfail)
  382. @property
  383. def failed_cases(self) -> List[str]:
  384. return [case for case, is_known, is_xfail in self._failed_cases if not is_known and not is_xfail]
  385. @property
  386. def known_failure_cases(self) -> List[str]:
  387. return [case for case, is_known, _ in self._failed_cases if is_known]
  388. @property
  389. def xfail_cases(self) -> List[str]:
  390. return [case for case, _, is_xfail in self._failed_cases if is_xfail]
  391. @staticmethod
  392. def _parse_known_failure_cases_file(
  393. known_failure_cases_file: Optional[str] = None,
  394. ) -> List[str]:
  395. if not known_failure_cases_file or not os.path.isfile(known_failure_cases_file):
  396. return []
  397. patterns = []
  398. with open(known_failure_cases_file) as fr:
  399. for line in fr.readlines():
  400. if not line:
  401. continue
  402. if not line.strip():
  403. continue
  404. without_comments = line.split('#')[0].strip()
  405. if without_comments:
  406. patterns.append(without_comments)
  407. return patterns
  408. @pytest.hookimpl(tryfirst=True)
  409. def pytest_sessionstart(self, session: Session) -> None:
  410. # same behavior for vanilla pytest-embedded '--target'
  411. session.config.option.target = self.target
  412. @pytest.hookimpl(tryfirst=True)
  413. def pytest_collection_modifyitems(self, items: List[Function]) -> None:
  414. # sort by file path and callspec.config
  415. # implement like this since this is a limitation of pytest, couldn't get fixture values while collecting
  416. # https://github.com/pytest-dev/pytest/discussions/9689
  417. # after sort the test apps, the test may use the app cache to reduce the flash times.
  418. def _get_param_config(_item: Function) -> str:
  419. if hasattr(_item, 'callspec'):
  420. return _item.callspec.params.get('config', DEFAULT_SDKCONFIG) # type: ignore
  421. return DEFAULT_SDKCONFIG
  422. items.sort(key=lambda x: (os.path.dirname(x.path), _get_param_config(x)))
  423. # set default timeout 10 minutes for each case
  424. for item in items:
  425. if 'timeout' not in item.keywords:
  426. item.add_marker(pytest.mark.timeout(10 * 60))
  427. # add markers for special markers
  428. for item in items:
  429. if 'supported_targets' in item.keywords:
  430. for _target in SUPPORTED_TARGETS:
  431. item.add_marker(_target)
  432. if 'preview_targets' in item.keywords:
  433. for _target in PREVIEW_TARGETS:
  434. item.add_marker(_target)
  435. if 'all_targets' in item.keywords:
  436. for _target in [*SUPPORTED_TARGETS, *PREVIEW_TARGETS]:
  437. item.add_marker(_target)
  438. # add 'xtal_40mhz' tag as a default tag for esp32c2 target
  439. # only add this marker for esp32c2 cases
  440. if (
  441. self.target == 'esp32c2'
  442. and 'esp32c2' in item_marker_names(item)
  443. and 'xtal_26mhz' not in item_marker_names(item)
  444. ):
  445. item.add_marker('xtal_40mhz')
  446. # filter all the test cases with "nightly_run" marker
  447. if os.getenv('INCLUDE_NIGHTLY_RUN') == '1':
  448. # Do not filter nightly_run cases
  449. pass
  450. elif os.getenv('NIGHTLY_RUN') == '1':
  451. items[:] = [item for item in items if 'nightly_run' in item_marker_names(item)]
  452. else:
  453. items[:] = [item for item in items if 'nightly_run' not in item_marker_names(item)]
  454. # filter all the test cases with target and skip_targets
  455. items[:] = [
  456. item
  457. for item in items
  458. if self.target in item_marker_names(item) and self.target not in item_skip_targets(item)
  459. ]
  460. # filter all the test cases with cli option "config"
  461. if self.sdkconfig:
  462. items[:] = [item for item in items if _get_param_config(item) == self.sdkconfig]
  463. def pytest_runtest_makereport(self, item: Function, call: CallInfo[None]) -> Optional[TestReport]:
  464. report = TestReport.from_item_and_call(item, call)
  465. if report.outcome == 'failed':
  466. test_case_name = item.funcargs.get('test_case_name', '')
  467. is_known_failure = self._is_known_failure(test_case_name)
  468. is_xfail = report.keywords.get('xfail', False)
  469. self._failed_cases.append((test_case_name, is_known_failure, is_xfail))
  470. return report
  471. def _is_known_failure(self, case_id: str) -> bool:
  472. for pattern in self.known_failure_patterns:
  473. if case_id == pattern:
  474. return True
  475. if fnmatch(case_id, pattern):
  476. return True
  477. return False
  478. @pytest.hookimpl(trylast=True)
  479. def pytest_runtest_teardown(self, item: Function) -> None:
  480. """
  481. Format the test case generated junit reports
  482. """
  483. tempdir = item.funcargs.get('test_case_tempdir')
  484. if not tempdir:
  485. return
  486. junits = find_by_suffix('.xml', tempdir)
  487. if not junits:
  488. return
  489. target = item.funcargs['target']
  490. config = item.funcargs['config']
  491. for junit in junits:
  492. xml = ET.parse(junit)
  493. testcases = xml.findall('.//testcase')
  494. for case in testcases:
  495. case.attrib['name'] = format_case_id(target, config, case.attrib['name'])
  496. if 'file' in case.attrib:
  497. case.attrib['file'] = case.attrib['file'].replace('/IDF/', '') # our unity test framework
  498. xml.write(junit)
  499. def pytest_sessionfinish(self, session: Session, exitstatus: int) -> None:
  500. if exitstatus != 0:
  501. if exitstatus == ExitCode.NO_TESTS_COLLECTED:
  502. session.exitstatus = 0
  503. elif self.known_failure_cases and not self.failed_cases:
  504. session.exitstatus = 0
  505. def pytest_terminal_summary(self, terminalreporter: TerminalReporter) -> None:
  506. if self.known_failure_cases:
  507. terminalreporter.section('Known failure cases', bold=True, yellow=True)
  508. terminalreporter.line('\n'.join(self.known_failure_cases))
  509. if self.xfail_cases:
  510. terminalreporter.section('xfail cases', bold=True, yellow=True)
  511. terminalreporter.line('\n'.join(self.xfail_cases))
  512. if self.failed_cases:
  513. terminalreporter.section('Failed cases', bold=True, red=True)
  514. terminalreporter.line('\n'.join(self.failed_cases))