conftest.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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 typing import Callable, List, Optional
  18. import pytest
  19. from _pytest.config import Config
  20. from _pytest.fixtures import FixtureRequest
  21. from _pytest.nodes import Item
  22. from _pytest.python import Function
  23. from pytest_embedded.plugin import parse_configuration
  24. from pytest_embedded.utils import find_by_suffix
  25. SUPPORTED_TARGETS = ['esp32', 'esp32s2', 'esp32c3', 'esp32s3']
  26. PREVIEW_TARGETS = ['linux', 'esp32h2', 'esp32c2']
  27. ##################
  28. # Help Functions #
  29. ##################
  30. def is_target_marker(marker: str) -> bool:
  31. if marker.startswith('esp32'):
  32. return True
  33. if marker.startswith('esp8'):
  34. return True
  35. return False
  36. def format_case_id(target: Optional[str], config: Optional[str], case: str) -> str:
  37. return f'{target}.{config}.{case}'
  38. def item_marker_names(item: Item) -> List[str]:
  39. return [marker.name for marker in item.iter_markers()]
  40. ############
  41. # Fixtures #
  42. ############
  43. @pytest.fixture
  44. def config(request: FixtureRequest) -> str:
  45. return getattr(request, 'param', None) or request.config.getoption('config', 'default') # type: ignore
  46. @pytest.fixture
  47. def test_case_name(request: FixtureRequest, target: str, config: str) -> str:
  48. return format_case_id(target, config, request.node.originalname)
  49. @pytest.fixture
  50. @parse_configuration
  51. def build_dir(request: FixtureRequest, app_path: str, target: Optional[str], config: Optional[str]) -> str:
  52. """
  53. Check local build dir with the following priority:
  54. 1. build_<target>_<config>
  55. 2. build_<target>
  56. 3. build_<config>
  57. 4. build
  58. Args:
  59. request: pytest fixture
  60. app_path: app path
  61. target: target
  62. config: config
  63. Returns:
  64. valid build directory
  65. """
  66. param_or_cli: str = getattr(request, 'param', None) or request.config.option.__dict__.get('build_dir')
  67. if param_or_cli is not None: # respect the parametrize and the cli
  68. return param_or_cli
  69. check_dirs = []
  70. if target is not None and config is not None:
  71. check_dirs.append(f'build_{target}_{config}')
  72. if target is not None:
  73. check_dirs.append(f'build_{target}')
  74. if config is not None:
  75. check_dirs.append(f'build_{config}')
  76. check_dirs.append('build')
  77. for check_dir in check_dirs:
  78. binary_path = os.path.join(app_path, check_dir)
  79. if os.path.isdir(binary_path):
  80. logging.info(f'find valid binary path: {binary_path}')
  81. return check_dir
  82. logging.warning(f'checking binary path: {binary_path}... missing... try another place')
  83. recommend_place = check_dirs[0]
  84. logging.error(
  85. f'no build dir valid. Please build the binary via "idf.py -B {recommend_place} build" and run pytest again')
  86. sys.exit(1)
  87. @pytest.fixture(autouse=True)
  88. def junit_properties(test_case_name: str, record_xml_attribute: Callable[[str, object], None]) -> None:
  89. """
  90. This fixture is autoused and will modify the junit report test case name to <target>.<config>.<case_name>
  91. """
  92. record_xml_attribute('name', test_case_name)
  93. ##################
  94. # Hook functions #
  95. ##################
  96. @pytest.hookimpl(tryfirst=True)
  97. def pytest_collection_modifyitems(config: Config, items: List[Item]) -> None:
  98. target = config.getoption('target', None) # use the `build` dir
  99. if not target:
  100. return
  101. # add markers for special markers
  102. for item in items:
  103. if 'supported_targets' in item_marker_names(item):
  104. for _target in SUPPORTED_TARGETS:
  105. item.add_marker(_target)
  106. if 'preview_targets' in item_marker_names(item):
  107. for _target in PREVIEW_TARGETS:
  108. item.add_marker(_target)
  109. if 'all_targets' in item_marker_names(item):
  110. for _target in [*SUPPORTED_TARGETS, *PREVIEW_TARGETS]:
  111. item.add_marker(_target)
  112. # filter all the test cases with "--target"
  113. items[:] = [item for item in items if target in item_marker_names(item)]
  114. @pytest.hookimpl(trylast=True)
  115. def pytest_runtest_teardown(item: Function) -> None:
  116. """
  117. Format the test case generated junit reports
  118. """
  119. tempdir = item.funcargs.get('test_case_tempdir')
  120. if not tempdir:
  121. return
  122. junits = find_by_suffix('.xml', tempdir)
  123. if not junits:
  124. return
  125. target = item.funcargs['target']
  126. config = item.funcargs['config']
  127. for junit in junits:
  128. xml = ET.parse(junit)
  129. testcases = xml.findall('.//testcase')
  130. for case in testcases:
  131. case.attrib['name'] = format_case_id(target, config, case.attrib['name'])
  132. if 'file' in case.attrib:
  133. case.attrib['file'] = case.attrib['file'].replace('/IDF/', '') # our unity test framework
  134. xml.write(junit)