conftest.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. 'emmc': 'eMMC card',
  104. 'MSPI_F8R8': 'runner with Octal Flash and Octal PSRAM',
  105. 'MSPI_F4R8': 'runner with Quad Flash and Octal PSRAM',
  106. 'MSPI_F4R4': 'runner with Quad Flash and Quad PSRAM',
  107. 'jtag': 'runner where the chip is accessible through JTAG as well',
  108. 'usb_serial_jtag': 'runner where the chip is accessible through builtin JTAG as well',
  109. 'adc': 'ADC related tests should run on adc runners',
  110. 'xtal32k': 'Runner with external 32k crystal connected',
  111. 'no32kXtal': 'Runner with no external 32k crystal connected',
  112. 'multi_dut_modbus_rs485': 'a pair of runners connected by RS485 bus',
  113. 'psramv0': 'Runner with PSRAM version 0',
  114. 'esp32eco3': 'Runner with esp32 eco3 connected',
  115. 'ecdsa_efuse': 'Runner with test ECDSA private keys programmed in efuse',
  116. 'ccs811': 'Runner with CCS811 connected',
  117. 'ethernet_w5500': 'SPI Ethernet module with two W5500',
  118. # multi-dut markers
  119. 'ieee802154': 'ieee802154 related tests should run on ieee802154 runners.',
  120. 'openthread_br': 'tests should be used for openthread border router.',
  121. 'wifi_two_dut': 'tests should be run on runners which has two wifi duts connected.',
  122. 'generic_multi_device': 'generic multiple devices whose corresponding gpio pins are connected to each other.',
  123. 'twai_network': 'multiple runners form a TWAI network.',
  124. 'sdio_master_slave': 'Test sdio multi board.',
  125. }
  126. ##################
  127. # Help Functions #
  128. ##################
  129. def format_case_id(target: Optional[str], config: Optional[str], case: str) -> str:
  130. return f'{target}.{config}.{case}'
  131. def item_marker_names(item: Item) -> List[str]:
  132. return [marker.name for marker in item.iter_markers()]
  133. def item_target_marker_names(item: Item) -> List[str]:
  134. res = set()
  135. for marker in item.iter_markers():
  136. if marker.name in TARGET_MARKERS:
  137. res.add(marker.name)
  138. return sorted(res)
  139. def item_env_marker_names(item: Item) -> List[str]:
  140. res = set()
  141. for marker in item.iter_markers():
  142. if marker.name in ENV_MARKERS:
  143. res.add(marker.name)
  144. return sorted(res)
  145. def item_skip_targets(item: Item) -> List[str]:
  146. def _get_temp_markers_disabled_targets(marker_name: str) -> List[str]:
  147. temp_marker = item.get_closest_marker(marker_name)
  148. if not temp_marker:
  149. return []
  150. # temp markers should always use keyword arguments `targets` and `reason`
  151. if not temp_marker.kwargs.get('targets') or not temp_marker.kwargs.get('reason'):
  152. raise ValueError(
  153. f'`{marker_name}` should always use keyword arguments `targets` and `reason`. '
  154. f'For example: '
  155. f'`@pytest.mark.{marker_name}(targets=["esp32"], reason="IDF-xxxx, will fix it ASAP")`'
  156. )
  157. return to_list(temp_marker.kwargs['targets']) # type: ignore
  158. temp_skip_ci_targets = _get_temp_markers_disabled_targets('temp_skip_ci')
  159. temp_skip_targets = _get_temp_markers_disabled_targets('temp_skip')
  160. # in CI we skip the union of `temp_skip` and `temp_skip_ci`
  161. if os.getenv('CI_JOB_ID'):
  162. skip_targets = list(set(temp_skip_ci_targets).union(set(temp_skip_targets)))
  163. else: # we use `temp_skip` locally
  164. skip_targets = temp_skip_targets
  165. return skip_targets
  166. def get_target_marker_from_expr(markexpr: str) -> str:
  167. candidates = set()
  168. # we use `-m "esp32 and generic"` in our CI to filter the test cases
  169. # this doesn't cover all use cases, but fit what we do in CI.
  170. for marker in markexpr.split('and'):
  171. marker = marker.strip()
  172. if marker in TARGET_MARKERS:
  173. candidates.add(marker)
  174. if len(candidates) > 1:
  175. raise ValueError(f'Specified more than one target markers: {candidates}. Please specify no more than one.')
  176. elif len(candidates) == 1:
  177. return candidates.pop()
  178. else:
  179. raise ValueError('Please specify one target marker via "--target [TARGET]" or via "-m [TARGET]"')
  180. ############
  181. # Fixtures #
  182. ############
  183. @pytest.fixture(scope='session')
  184. def idf_path() -> str:
  185. return os.path.dirname(__file__)
  186. @pytest.fixture(scope='session', autouse=True)
  187. def session_tempdir() -> str:
  188. _tmpdir = os.path.join(
  189. os.path.dirname(__file__),
  190. 'pytest_embedded_log',
  191. datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
  192. )
  193. os.makedirs(_tmpdir, exist_ok=True)
  194. return _tmpdir
  195. @pytest.fixture
  196. def case_tester(dut: IdfDut, **kwargs): # type: ignore
  197. yield CaseTester(dut, **kwargs)
  198. @pytest.fixture
  199. @multi_dut_argument
  200. def config(request: FixtureRequest) -> str:
  201. return getattr(request, 'param', None) or DEFAULT_SDKCONFIG
  202. @pytest.fixture
  203. def test_func_name(request: FixtureRequest) -> str:
  204. return request.node.function.__name__ # type: ignore
  205. @pytest.fixture
  206. def test_case_name(request: FixtureRequest, target: str, config: str) -> str:
  207. return format_case_id(target, config, request.node.originalname)
  208. @pytest.fixture
  209. @multi_dut_fixture
  210. def build_dir(app_path: str, target: Optional[str], config: Optional[str]) -> str:
  211. """
  212. Check local build dir with the following priority:
  213. 1. build_<target>_<config>
  214. 2. build_<target>
  215. 3. build_<config>
  216. 4. build
  217. Args:
  218. app_path: app path
  219. target: target
  220. config: config
  221. Returns:
  222. valid build directory
  223. """
  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. @multi_dut_fixture
  244. def junit_properties(test_case_name: str, record_xml_attribute: Callable[[str, object], None]) -> None:
  245. """
  246. This fixture is autoused and will modify the junit report test case name to <target>.<config>.<case_name>
  247. """
  248. record_xml_attribute('name', test_case_name)
  249. ######################
  250. # Log Util Functions #
  251. ######################
  252. @pytest.fixture
  253. def log_performance(record_property: Callable[[str, object], None]) -> Callable[[str, str], None]:
  254. """
  255. log performance item with pre-defined format to the console
  256. and record it under the ``properties`` tag in the junit report if available.
  257. """
  258. def real_func(item: str, value: str) -> None:
  259. """
  260. :param item: performance item name
  261. :param value: performance value
  262. """
  263. logging.info('[Performance][%s]: %s', item, value)
  264. record_property(item, value)
  265. return real_func
  266. @pytest.fixture
  267. def check_performance(idf_path: str) -> Callable[[str, float, str], None]:
  268. """
  269. check if the given performance item meets the passing standard or not
  270. """
  271. def real_func(item: str, value: float, target: str) -> None:
  272. """
  273. :param item: performance item name
  274. :param value: performance item value
  275. :param target: target chip
  276. :raise: AssertionError: if check fails
  277. """
  278. def _find_perf_item(operator: str, path: str) -> float:
  279. with open(path, 'r') as f:
  280. data = f.read()
  281. match = re.search(r'#define\s+IDF_PERFORMANCE_{}_{}\s+([\d.]+)'.format(operator, item.upper()), data)
  282. return float(match.group(1)) # type: ignore
  283. def _check_perf(operator: str, standard_value: float) -> None:
  284. if operator == 'MAX':
  285. ret = value <= standard_value
  286. else:
  287. ret = value >= standard_value
  288. if not ret:
  289. raise AssertionError(
  290. "[Performance] {} value is {}, doesn't meet pass standard {}".format(item, value, standard_value)
  291. )
  292. path_prefix = os.path.join(idf_path, 'components', 'idf_test', 'include')
  293. performance_files = (
  294. os.path.join(path_prefix, target, 'idf_performance_target.h'),
  295. os.path.join(path_prefix, 'idf_performance.h'),
  296. )
  297. found_item = False
  298. for op in ['MIN', 'MAX']:
  299. for performance_file in performance_files:
  300. try:
  301. standard = _find_perf_item(op, performance_file)
  302. except (IOError, AttributeError):
  303. # performance file doesn't exist or match is not found in it
  304. continue
  305. _check_perf(op, standard)
  306. found_item = True
  307. break
  308. if not found_item:
  309. raise AssertionError('Failed to get performance standard for {}'.format(item))
  310. return real_func
  311. @pytest.fixture
  312. def log_minimum_free_heap_size(dut: IdfDut, config: str) -> Callable[..., None]:
  313. def real_func() -> None:
  314. res = dut.expect(r'Minimum free heap size: (\d+) bytes')
  315. logging.info(
  316. '\n------ heap size info ------\n'
  317. '[app_name] {}\n'
  318. '[config_name] {}\n'
  319. '[target] {}\n'
  320. '[minimum_free_heap_size] {} Bytes\n'
  321. '------ heap size end ------'.format(
  322. os.path.basename(dut.app.app_path),
  323. config,
  324. dut.target,
  325. res.group(1).decode('utf8'),
  326. )
  327. )
  328. return real_func
  329. @pytest.fixture
  330. def dev_password(request: FixtureRequest) -> str:
  331. return request.config.getoption('dev_passwd') or ''
  332. @pytest.fixture
  333. def dev_user(request: FixtureRequest) -> str:
  334. return request.config.getoption('dev_user') or ''
  335. ##################
  336. # Hook functions #
  337. ##################
  338. def pytest_addoption(parser: pytest.Parser) -> None:
  339. base_group = parser.getgroup('idf')
  340. base_group.addoption(
  341. '--sdkconfig',
  342. help='sdkconfig postfix, like sdkconfig.ci.<config>. (Default: None, which would build all found apps)',
  343. )
  344. base_group.addoption('--known-failure-cases-file', help='known failure cases file path')
  345. base_group.addoption(
  346. '--dev-user',
  347. help='user name associated with some specific device/service used during the test execution',
  348. )
  349. base_group.addoption(
  350. '--dev-passwd',
  351. help='password associated with some specific device/service used during the test execution',
  352. )
  353. _idf_pytest_embedded_key = pytest.StashKey['IdfPytestEmbedded']()
  354. _item_failed_cases_key = pytest.StashKey[list]()
  355. _item_failed_key = pytest.StashKey[bool]()
  356. def pytest_configure(config: Config) -> None:
  357. # cli option "--target"
  358. target = config.getoption('target') or ''
  359. help_commands = ['--help', '--fixtures', '--markers', '--version']
  360. for cmd in help_commands:
  361. if cmd in config.invocation_params.args:
  362. target = 'unneeded'
  363. break
  364. if not target: # also could specify through markexpr via "-m"
  365. target = get_target_marker_from_expr(config.getoption('markexpr') or '')
  366. config.stash[_idf_pytest_embedded_key] = IdfPytestEmbedded(
  367. target=target,
  368. sdkconfig=config.getoption('sdkconfig'),
  369. known_failure_cases_file=config.getoption('known_failure_cases_file'),
  370. )
  371. config.pluginmanager.register(config.stash[_idf_pytest_embedded_key])
  372. for name, description in {**TARGET_MARKERS, **ENV_MARKERS, **SPECIAL_MARKERS}.items():
  373. config.addinivalue_line('markers', f'{name}: {description}')
  374. def pytest_unconfigure(config: Config) -> None:
  375. _pytest_embedded = config.stash.get(_idf_pytest_embedded_key, None)
  376. if _pytest_embedded:
  377. del config.stash[_idf_pytest_embedded_key]
  378. config.pluginmanager.unregister(_pytest_embedded)
  379. class IdfPytestEmbedded:
  380. def __init__(
  381. self,
  382. target: str,
  383. sdkconfig: Optional[str] = None,
  384. known_failure_cases_file: Optional[str] = None,
  385. ):
  386. # CLI options to filter the test cases
  387. self.target = target.lower()
  388. self.sdkconfig = sdkconfig
  389. self.known_failure_patterns = self._parse_known_failure_cases_file(known_failure_cases_file)
  390. self._failed_cases: List[Tuple[str, bool, bool]] = [] # (test_case_name, is_known_failure_cases, is_xfail)
  391. @property
  392. def failed_cases(self) -> List[str]:
  393. return [case for case, is_known, is_xfail in self._failed_cases if not is_known and not is_xfail]
  394. @property
  395. def known_failure_cases(self) -> List[str]:
  396. return [case for case, is_known, _ in self._failed_cases if is_known]
  397. @property
  398. def xfail_cases(self) -> List[str]:
  399. return [case for case, _, is_xfail in self._failed_cases if is_xfail]
  400. @staticmethod
  401. def _parse_known_failure_cases_file(
  402. known_failure_cases_file: Optional[str] = None,
  403. ) -> List[str]:
  404. if not known_failure_cases_file or not os.path.isfile(known_failure_cases_file):
  405. return []
  406. patterns = []
  407. with open(known_failure_cases_file) as fr:
  408. for line in fr.readlines():
  409. if not line:
  410. continue
  411. if not line.strip():
  412. continue
  413. without_comments = line.split('#')[0].strip()
  414. if without_comments:
  415. patterns.append(without_comments)
  416. return patterns
  417. @pytest.hookimpl(tryfirst=True)
  418. def pytest_sessionstart(self, session: Session) -> None:
  419. # same behavior for vanilla pytest-embedded '--target'
  420. session.config.option.target = self.target
  421. @pytest.hookimpl(tryfirst=True)
  422. def pytest_collection_modifyitems(self, items: List[Function]) -> None:
  423. # sort by file path and callspec.config
  424. # implement like this since this is a limitation of pytest, couldn't get fixture values while collecting
  425. # https://github.com/pytest-dev/pytest/discussions/9689
  426. # after sort the test apps, the test may use the app cache to reduce the flash times.
  427. def _get_param_config(_item: Function) -> str:
  428. if hasattr(_item, 'callspec'):
  429. return _item.callspec.params.get('config', DEFAULT_SDKCONFIG) # type: ignore
  430. return DEFAULT_SDKCONFIG
  431. items.sort(key=lambda x: (os.path.dirname(x.path), _get_param_config(x)))
  432. # set default timeout 10 minutes for each case
  433. for item in items:
  434. if 'timeout' not in item.keywords:
  435. item.add_marker(pytest.mark.timeout(10 * 60))
  436. # add markers for special markers
  437. for item in items:
  438. if 'supported_targets' in item.keywords:
  439. for _target in SUPPORTED_TARGETS:
  440. item.add_marker(_target)
  441. if 'preview_targets' in item.keywords:
  442. for _target in PREVIEW_TARGETS:
  443. item.add_marker(_target)
  444. if 'all_targets' in item.keywords:
  445. for _target in [*SUPPORTED_TARGETS, *PREVIEW_TARGETS]:
  446. item.add_marker(_target)
  447. # add 'xtal_40mhz' tag as a default tag for esp32c2 target
  448. # only add this marker for esp32c2 cases
  449. if (
  450. self.target == 'esp32c2'
  451. and 'esp32c2' in item_marker_names(item)
  452. and 'xtal_26mhz' not in item_marker_names(item)
  453. ):
  454. item.add_marker('xtal_40mhz')
  455. # filter all the test cases with "nightly_run" marker
  456. if os.getenv('INCLUDE_NIGHTLY_RUN') == '1':
  457. # Do not filter nightly_run cases
  458. pass
  459. elif os.getenv('NIGHTLY_RUN') == '1':
  460. items[:] = [item for item in items if 'nightly_run' in item_marker_names(item)]
  461. else:
  462. items[:] = [item for item in items if 'nightly_run' not in item_marker_names(item)]
  463. # filter all the test cases with target and skip_targets
  464. items[:] = [
  465. item
  466. for item in items
  467. if self.target in item_marker_names(item) and self.target not in item_skip_targets(item)
  468. ]
  469. # filter all the test cases with cli option "config"
  470. if self.sdkconfig:
  471. items[:] = [item for item in items if _get_param_config(item) == self.sdkconfig]
  472. def pytest_runtest_makereport(self, item: Function, call: CallInfo[None]) -> Optional[TestReport]:
  473. report = TestReport.from_item_and_call(item, call)
  474. if item.stash.get(_item_failed_key, None) is None:
  475. item.stash[_item_failed_key] = False
  476. if report.outcome == 'failed':
  477. # Mark the failed test cases
  478. #
  479. # This hook function would be called in 3 phases, setup, call, teardown.
  480. # the report.outcome is the outcome of the single call of current phase, which is independent
  481. # the call phase outcome is the test result
  482. item.stash[_item_failed_key] = True
  483. if call.when == 'teardown':
  484. item_failed = item.stash[_item_failed_key]
  485. if item_failed:
  486. # unity real test cases
  487. failed_sub_cases = item.stash.get(_item_failed_cases_key, [])
  488. if failed_sub_cases:
  489. for test_case_name in failed_sub_cases:
  490. self._failed_cases.append((test_case_name, self._is_known_failure(test_case_name), False))
  491. else: # the case iteself is failing
  492. test_case_name = item.funcargs.get('test_case_name', '')
  493. if test_case_name:
  494. self._failed_cases.append(
  495. (test_case_name, self._is_known_failure(test_case_name), report.keywords.get('xfail', False))
  496. )
  497. return report
  498. def _is_known_failure(self, case_id: str) -> bool:
  499. for pattern in self.known_failure_patterns:
  500. if case_id == pattern:
  501. return True
  502. if fnmatch(case_id, pattern):
  503. return True
  504. return False
  505. @pytest.hookimpl(trylast=True)
  506. def pytest_runtest_teardown(self, item: Function) -> None:
  507. """
  508. Format the test case generated junit reports
  509. """
  510. tempdir = item.funcargs.get('test_case_tempdir')
  511. if not tempdir:
  512. return
  513. junits = find_by_suffix('.xml', tempdir)
  514. if not junits:
  515. return
  516. failed_sub_cases = []
  517. target = item.funcargs['target']
  518. config = item.funcargs['config']
  519. for junit in junits:
  520. xml = ET.parse(junit)
  521. testcases = xml.findall('.//testcase')
  522. for case in testcases:
  523. # modify the junit files
  524. new_case_name = format_case_id(target, config, case.attrib['name'])
  525. case.attrib['name'] = new_case_name
  526. if 'file' in case.attrib:
  527. case.attrib['file'] = case.attrib['file'].replace('/IDF/', '') # our unity test framework
  528. # collect real failure cases
  529. if case.find('failure') is not None:
  530. failed_sub_cases.append(new_case_name)
  531. xml.write(junit)
  532. item.stash[_item_failed_cases_key] = failed_sub_cases
  533. def pytest_sessionfinish(self, session: Session, exitstatus: int) -> None:
  534. if exitstatus != 0:
  535. if exitstatus == ExitCode.NO_TESTS_COLLECTED:
  536. session.exitstatus = 0
  537. elif self.known_failure_cases and not self.failed_cases:
  538. session.exitstatus = 0
  539. def pytest_terminal_summary(self, terminalreporter: TerminalReporter) -> None:
  540. if self.known_failure_cases:
  541. terminalreporter.section('Known failure cases', bold=True, yellow=True)
  542. terminalreporter.line('\n'.join(self.known_failure_cases))
  543. if self.xfail_cases:
  544. terminalreporter.section('xfail cases', bold=True, yellow=True)
  545. terminalreporter.line('\n'.join(self.xfail_cases))
  546. if self.failed_cases:
  547. terminalreporter.section('Failed cases', bold=True, red=True)
  548. terminalreporter.line('\n'.join(self.failed_cases))