conftest.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # SPDX-License-Identifier: GPL-2.0
  2. #
  3. # Copyright (C) 2018 Masahiro Yamada <[email protected]>
  4. #
  5. """
  6. Kconfig unit testing framework.
  7. This provides fixture functions commonly used from test files.
  8. """
  9. import os
  10. import pytest
  11. import shutil
  12. import subprocess
  13. import tempfile
  14. CONF_PATH = os.path.abspath(os.path.join('scripts', 'kconfig', 'conf'))
  15. class Conf:
  16. """Kconfig runner and result checker.
  17. This class provides methods to run text-based interface of Kconfig
  18. (scripts/kconfig/conf) and retrieve the resulted configuration,
  19. stdout, and stderr. It also provides methods to compare those
  20. results with expectations.
  21. """
  22. def __init__(self, request):
  23. """Create a new Conf instance.
  24. request: object to introspect the requesting test module
  25. """
  26. # the directory of the test being run
  27. self._test_dir = os.path.dirname(str(request.fspath))
  28. # runners
  29. def _run_conf(self, mode, dot_config=None, out_file='.config',
  30. interactive=False, in_keys=None, extra_env={}):
  31. """Run text-based Kconfig executable and save the result.
  32. mode: input mode option (--oldaskconfig, --defconfig=<file> etc.)
  33. dot_config: .config file to use for configuration base
  34. out_file: file name to contain the output config data
  35. interactive: flag to specify the interactive mode
  36. in_keys: key inputs for interactive modes
  37. extra_env: additional environments
  38. returncode: exit status of the Kconfig executable
  39. """
  40. command = [CONF_PATH, mode, 'Kconfig']
  41. # Override 'srctree' environment to make the test as the top directory
  42. extra_env['srctree'] = self._test_dir
  43. # Clear KCONFIG_DEFCONFIG_LIST to keep unit tests from being affected
  44. # by the user's environment.
  45. extra_env['KCONFIG_DEFCONFIG_LIST'] = ''
  46. # Run Kconfig in a temporary directory.
  47. # This directory is automatically removed when done.
  48. with tempfile.TemporaryDirectory() as temp_dir:
  49. # if .config is given, copy it to the working directory
  50. if dot_config:
  51. shutil.copyfile(os.path.join(self._test_dir, dot_config),
  52. os.path.join(temp_dir, '.config'))
  53. ps = subprocess.Popen(command,
  54. stdin=subprocess.PIPE,
  55. stdout=subprocess.PIPE,
  56. stderr=subprocess.PIPE,
  57. cwd=temp_dir,
  58. env=dict(os.environ, **extra_env))
  59. # If input key sequence is given, feed it to stdin.
  60. if in_keys:
  61. ps.stdin.write(in_keys.encode('utf-8'))
  62. while ps.poll() is None:
  63. # For interactive modes such as oldaskconfig, oldconfig,
  64. # send 'Enter' key until the program finishes.
  65. if interactive:
  66. ps.stdin.write(b'\n')
  67. self.retcode = ps.returncode
  68. self.stdout = ps.stdout.read().decode()
  69. self.stderr = ps.stderr.read().decode()
  70. # Retrieve the resulted config data only when .config is supposed
  71. # to exist. If the command fails, the .config does not exist.
  72. # 'listnewconfig' does not produce .config in the first place.
  73. if self.retcode == 0 and out_file:
  74. with open(os.path.join(temp_dir, out_file)) as f:
  75. self.config = f.read()
  76. else:
  77. self.config = None
  78. # Logging:
  79. # Pytest captures the following information by default. In failure
  80. # of tests, the captured log will be displayed. This will be useful to
  81. # figure out what has happened.
  82. print("[command]\n{}\n".format(' '.join(command)))
  83. print("[retcode]\n{}\n".format(self.retcode))
  84. print("[stdout]")
  85. print(self.stdout)
  86. print("[stderr]")
  87. print(self.stderr)
  88. if self.config is not None:
  89. print("[output for '{}']".format(out_file))
  90. print(self.config)
  91. return self.retcode
  92. def oldaskconfig(self, dot_config=None, in_keys=None):
  93. """Run oldaskconfig.
  94. dot_config: .config file to use for configuration base (optional)
  95. in_key: key inputs (optional)
  96. returncode: exit status of the Kconfig executable
  97. """
  98. return self._run_conf('--oldaskconfig', dot_config=dot_config,
  99. interactive=True, in_keys=in_keys)
  100. def oldconfig(self, dot_config=None, in_keys=None):
  101. """Run oldconfig.
  102. dot_config: .config file to use for configuration base (optional)
  103. in_key: key inputs (optional)
  104. returncode: exit status of the Kconfig executable
  105. """
  106. return self._run_conf('--oldconfig', dot_config=dot_config,
  107. interactive=True, in_keys=in_keys)
  108. def olddefconfig(self, dot_config=None):
  109. """Run olddefconfig.
  110. dot_config: .config file to use for configuration base (optional)
  111. returncode: exit status of the Kconfig executable
  112. """
  113. return self._run_conf('--olddefconfig', dot_config=dot_config)
  114. def defconfig(self, defconfig):
  115. """Run defconfig.
  116. defconfig: defconfig file for input
  117. returncode: exit status of the Kconfig executable
  118. """
  119. defconfig_path = os.path.join(self._test_dir, defconfig)
  120. return self._run_conf('--defconfig={}'.format(defconfig_path))
  121. def _allconfig(self, mode, all_config):
  122. if all_config:
  123. all_config_path = os.path.join(self._test_dir, all_config)
  124. extra_env = {'KCONFIG_ALLCONFIG': all_config_path}
  125. else:
  126. extra_env = {}
  127. return self._run_conf('--{}config'.format(mode), extra_env=extra_env)
  128. def allyesconfig(self, all_config=None):
  129. """Run allyesconfig.
  130. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  131. returncode: exit status of the Kconfig executable
  132. """
  133. return self._allconfig('allyes', all_config)
  134. def allmodconfig(self, all_config=None):
  135. """Run allmodconfig.
  136. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  137. returncode: exit status of the Kconfig executable
  138. """
  139. return self._allconfig('allmod', all_config)
  140. def allnoconfig(self, all_config=None):
  141. """Run allnoconfig.
  142. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  143. returncode: exit status of the Kconfig executable
  144. """
  145. return self._allconfig('allno', all_config)
  146. def alldefconfig(self, all_config=None):
  147. """Run alldefconfig.
  148. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  149. returncode: exit status of the Kconfig executable
  150. """
  151. return self._allconfig('alldef', all_config)
  152. def randconfig(self, all_config=None):
  153. """Run randconfig.
  154. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  155. returncode: exit status of the Kconfig executable
  156. """
  157. return self._allconfig('rand', all_config)
  158. def savedefconfig(self, dot_config):
  159. """Run savedefconfig.
  160. dot_config: .config file for input
  161. returncode: exit status of the Kconfig executable
  162. """
  163. return self._run_conf('--savedefconfig', out_file='defconfig')
  164. def listnewconfig(self, dot_config=None):
  165. """Run listnewconfig.
  166. dot_config: .config file to use for configuration base (optional)
  167. returncode: exit status of the Kconfig executable
  168. """
  169. return self._run_conf('--listnewconfig', dot_config=dot_config,
  170. out_file=None)
  171. # checkers
  172. def _read_and_compare(self, compare, expected):
  173. """Compare the result with expectation.
  174. compare: function to compare the result with expectation
  175. expected: file that contains the expected data
  176. """
  177. with open(os.path.join(self._test_dir, expected)) as f:
  178. expected_data = f.read()
  179. return compare(self, expected_data)
  180. def _contains(self, attr, expected):
  181. return self._read_and_compare(
  182. lambda s, e: getattr(s, attr).find(e) >= 0,
  183. expected)
  184. def _matches(self, attr, expected):
  185. return self._read_and_compare(lambda s, e: getattr(s, attr) == e,
  186. expected)
  187. def config_contains(self, expected):
  188. """Check if resulted configuration contains expected data.
  189. expected: file that contains the expected data
  190. returncode: True if result contains the expected data, False otherwise
  191. """
  192. return self._contains('config', expected)
  193. def config_matches(self, expected):
  194. """Check if resulted configuration exactly matches expected data.
  195. expected: file that contains the expected data
  196. returncode: True if result matches the expected data, False otherwise
  197. """
  198. return self._matches('config', expected)
  199. def stdout_contains(self, expected):
  200. """Check if resulted stdout contains expected data.
  201. expected: file that contains the expected data
  202. returncode: True if result contains the expected data, False otherwise
  203. """
  204. return self._contains('stdout', expected)
  205. def stdout_matches(self, expected):
  206. """Check if resulted stdout exactly matches expected data.
  207. expected: file that contains the expected data
  208. returncode: True if result matches the expected data, False otherwise
  209. """
  210. return self._matches('stdout', expected)
  211. def stderr_contains(self, expected):
  212. """Check if resulted stderr contains expected data.
  213. expected: file that contains the expected data
  214. returncode: True if result contains the expected data, False otherwise
  215. """
  216. return self._contains('stderr', expected)
  217. def stderr_matches(self, expected):
  218. """Check if resulted stderr exactly matches expected data.
  219. expected: file that contains the expected data
  220. returncode: True if result matches the expected data, False otherwise
  221. """
  222. return self._matches('stderr', expected)
  223. @pytest.fixture(scope="module")
  224. def conf(request):
  225. """Create a Conf instance and provide it to test functions."""
  226. return Conf(request)