conftest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. # SPDX-License-Identifier: GPL-2.0
  2. #
  3. # Copyright (C) 2018 Masahiro Yamada <yamada.masahiro@socionext.com>
  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. try:
  67. ps.stdin.write(b'\n')
  68. ps.stdin.flush()
  69. except (BrokenPipeError, OSError):
  70. # Process has exited, stop sending input
  71. break
  72. # Close stdin gracefully
  73. try:
  74. ps.stdin.close()
  75. except (BrokenPipeError, OSError):
  76. # Ignore broken pipe on close
  77. pass
  78. # Wait for process to complete
  79. ps.wait()
  80. self.retcode = ps.returncode
  81. self.stdout = ps.stdout.read().decode()
  82. self.stderr = ps.stderr.read().decode()
  83. # Retrieve the resulted config data only when .config is supposed
  84. # to exist. If the command fails, the .config does not exist.
  85. # 'listnewconfig' does not produce .config in the first place.
  86. if self.retcode == 0 and out_file:
  87. with open(os.path.join(temp_dir, out_file)) as f:
  88. self.config = f.read()
  89. else:
  90. self.config = None
  91. # Logging:
  92. # Pytest captures the following information by default. In failure
  93. # of tests, the captured log will be displayed. This will be useful to
  94. # figure out what has happened.
  95. print("[command]\n{}\n".format(' '.join(command)))
  96. print("[retcode]\n{}\n".format(self.retcode))
  97. print("[stdout]")
  98. print(self.stdout)
  99. print("[stderr]")
  100. print(self.stderr)
  101. if self.config is not None:
  102. print("[output for '{}']".format(out_file))
  103. print(self.config)
  104. return self.retcode
  105. def oldaskconfig(self, dot_config=None, in_keys=None):
  106. """Run oldaskconfig.
  107. dot_config: .config file to use for configuration base (optional)
  108. in_key: key inputs (optional)
  109. returncode: exit status of the Kconfig executable
  110. """
  111. return self._run_conf('--oldaskconfig', dot_config=dot_config,
  112. interactive=True, in_keys=in_keys)
  113. def oldconfig(self, dot_config=None, in_keys=None):
  114. """Run oldconfig.
  115. dot_config: .config file to use for configuration base (optional)
  116. in_key: key inputs (optional)
  117. returncode: exit status of the Kconfig executable
  118. """
  119. return self._run_conf('--oldconfig', dot_config=dot_config,
  120. interactive=True, in_keys=in_keys)
  121. def olddefconfig(self, dot_config=None):
  122. """Run olddefconfig.
  123. dot_config: .config file to use for configuration base (optional)
  124. returncode: exit status of the Kconfig executable
  125. """
  126. return self._run_conf('--olddefconfig', dot_config=dot_config)
  127. def defconfig(self, defconfig):
  128. """Run defconfig.
  129. defconfig: defconfig file for input
  130. returncode: exit status of the Kconfig executable
  131. """
  132. defconfig_path = os.path.join(self._test_dir, defconfig)
  133. return self._run_conf('--defconfig={}'.format(defconfig_path))
  134. def _allconfig(self, mode, all_config, extra_env={}):
  135. if all_config:
  136. all_config_path = os.path.join(self._test_dir, all_config)
  137. extra_env['KCONFIG_ALLCONFIG'] = all_config_path
  138. return self._run_conf('--{}config'.format(mode), extra_env=extra_env)
  139. def allyesconfig(self, all_config=None):
  140. """Run allyesconfig.
  141. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  142. returncode: exit status of the Kconfig executable
  143. """
  144. return self._allconfig('allyes', all_config)
  145. def allmodconfig(self, all_config=None):
  146. """Run allmodconfig.
  147. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  148. returncode: exit status of the Kconfig executable
  149. """
  150. return self._allconfig('allmod', all_config)
  151. def allnoconfig(self, all_config=None):
  152. """Run allnoconfig.
  153. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  154. returncode: exit status of the Kconfig executable
  155. """
  156. return self._allconfig('allno', all_config)
  157. def alldefconfig(self, all_config=None):
  158. """Run alldefconfig.
  159. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  160. returncode: exit status of the Kconfig executable
  161. """
  162. return self._allconfig('alldef', all_config)
  163. def randconfig(self, all_config=None, seed=None):
  164. """Run randconfig.
  165. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  166. seed: the seed for randconfig (optional)
  167. returncode: exit status of the Kconfig executable
  168. """
  169. if seed is not None:
  170. extra_env = {'KCONFIG_SEED': hex(seed)}
  171. else:
  172. extra_env = {}
  173. return self._allconfig('rand', all_config, extra_env=extra_env)
  174. def savedefconfig(self, dot_config):
  175. """Run savedefconfig.
  176. dot_config: .config file for input
  177. returncode: exit status of the Kconfig executable
  178. """
  179. return self._run_conf('--savedefconfig', out_file='defconfig')
  180. def listnewconfig(self, dot_config=None):
  181. """Run listnewconfig.
  182. dot_config: .config file to use for configuration base (optional)
  183. returncode: exit status of the Kconfig executable
  184. """
  185. return self._run_conf('--listnewconfig', dot_config=dot_config,
  186. out_file=None)
  187. # checkers
  188. def _read_and_compare(self, compare, expected):
  189. """Compare the result with expectation.
  190. compare: function to compare the result with expectation
  191. expected: file that contains the expected data
  192. """
  193. with open(os.path.join(self._test_dir, expected)) as f:
  194. expected_data = f.read()
  195. return compare(self, expected_data)
  196. def _contains(self, attr, expected):
  197. return self._read_and_compare(
  198. lambda s, e: getattr(s, attr).find(e) >= 0,
  199. expected)
  200. def _matches(self, attr, expected):
  201. return self._read_and_compare(lambda s, e: getattr(s, attr) == e,
  202. expected)
  203. def config_contains(self, expected):
  204. """Check if resulted configuration contains expected data.
  205. expected: file that contains the expected data
  206. returncode: True if result contains the expected data, False otherwise
  207. """
  208. return self._contains('config', expected)
  209. def config_matches(self, expected):
  210. """Check if resulted configuration exactly matches expected data.
  211. expected: file that contains the expected data
  212. returncode: True if result matches the expected data, False otherwise
  213. """
  214. return self._matches('config', expected)
  215. def stdout_contains(self, expected):
  216. """Check if resulted stdout contains expected data.
  217. expected: file that contains the expected data
  218. returncode: True if result contains the expected data, False otherwise
  219. """
  220. return self._contains('stdout', expected)
  221. def stdout_matches(self, expected):
  222. """Check if resulted stdout exactly matches expected data.
  223. expected: file that contains the expected data
  224. returncode: True if result matches the expected data, False otherwise
  225. """
  226. return self._matches('stdout', expected)
  227. def stderr_contains(self, expected):
  228. """Check if resulted stderr contains expected data.
  229. expected: file that contains the expected data
  230. returncode: True if result contains the expected data, False otherwise
  231. """
  232. return self._contains('stderr', expected)
  233. def stderr_matches(self, expected):
  234. """Check if resulted stderr exactly matches expected data.
  235. expected: file that contains the expected data
  236. returncode: True if result matches the expected data, False otherwise
  237. """
  238. return self._matches('stderr', expected)
  239. @pytest.fixture(scope="module")
  240. def conf(request):
  241. """Create a Conf instance and provide it to test functions."""
  242. return Conf(request)