conftest.py 30 KB

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