conftest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. 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, extra_env={}):
  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. return self._run_conf('--{}config'.format(mode), extra_env=extra_env)
  126. def allyesconfig(self, all_config=None):
  127. """Run allyesconfig.
  128. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  129. returncode: exit status of the Kconfig executable
  130. """
  131. return self._allconfig('allyes', all_config)
  132. def allmodconfig(self, all_config=None):
  133. """Run allmodconfig.
  134. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  135. returncode: exit status of the Kconfig executable
  136. """
  137. return self._allconfig('allmod', all_config)
  138. def allnoconfig(self, all_config=None):
  139. """Run allnoconfig.
  140. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  141. returncode: exit status of the Kconfig executable
  142. """
  143. return self._allconfig('allno', all_config)
  144. def alldefconfig(self, all_config=None):
  145. """Run alldefconfig.
  146. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  147. returncode: exit status of the Kconfig executable
  148. """
  149. return self._allconfig('alldef', all_config)
  150. def randconfig(self, all_config=None, seed=None):
  151. """Run randconfig.
  152. all_config: fragment config file for KCONFIG_ALLCONFIG (optional)
  153. seed: the seed for randconfig (optional)
  154. returncode: exit status of the Kconfig executable
  155. """
  156. if seed is not None:
  157. extra_env = {'KCONFIG_SEED': hex(seed)}
  158. else:
  159. extra_env = {}
  160. return self._allconfig('rand', all_config, extra_env=extra_env)
  161. def savedefconfig(self, dot_config):
  162. """Run savedefconfig.
  163. dot_config: .config file for input
  164. returncode: exit status of the Kconfig executable
  165. """
  166. return self._run_conf('--savedefconfig', out_file='defconfig')
  167. def listnewconfig(self, dot_config=None):
  168. """Run listnewconfig.
  169. dot_config: .config file to use for configuration base (optional)
  170. returncode: exit status of the Kconfig executable
  171. """
  172. return self._run_conf('--listnewconfig', dot_config=dot_config,
  173. out_file=None)
  174. # checkers
  175. def _read_and_compare(self, compare, expected):
  176. """Compare the result with expectation.
  177. compare: function to compare the result with expectation
  178. expected: file that contains the expected data
  179. """
  180. with open(os.path.join(self._test_dir, expected)) as f:
  181. expected_data = f.read()
  182. return compare(self, expected_data)
  183. def _contains(self, attr, expected):
  184. return self._read_and_compare(
  185. lambda s, e: getattr(s, attr).find(e) >= 0,
  186. expected)
  187. def _matches(self, attr, expected):
  188. return self._read_and_compare(lambda s, e: getattr(s, attr) == e,
  189. expected)
  190. def config_contains(self, expected):
  191. """Check if resulted configuration contains expected data.
  192. expected: file that contains the expected data
  193. returncode: True if result contains the expected data, False otherwise
  194. """
  195. return self._contains('config', expected)
  196. def config_matches(self, expected):
  197. """Check if resulted configuration exactly matches expected data.
  198. expected: file that contains the expected data
  199. returncode: True if result matches the expected data, False otherwise
  200. """
  201. return self._matches('config', expected)
  202. def stdout_contains(self, expected):
  203. """Check if resulted stdout contains expected data.
  204. expected: file that contains the expected data
  205. returncode: True if result contains the expected data, False otherwise
  206. """
  207. return self._contains('stdout', expected)
  208. def stdout_matches(self, expected):
  209. """Check if resulted stdout exactly matches expected data.
  210. expected: file that contains the expected data
  211. returncode: True if result matches the expected data, False otherwise
  212. """
  213. return self._matches('stdout', expected)
  214. def stderr_contains(self, expected):
  215. """Check if resulted stderr contains expected data.
  216. expected: file that contains the expected data
  217. returncode: True if result contains the expected data, False otherwise
  218. """
  219. return self._contains('stderr', expected)
  220. def stderr_matches(self, expected):
  221. """Check if resulted stderr exactly matches expected data.
  222. expected: file that contains the expected data
  223. returncode: True if result matches the expected data, False otherwise
  224. """
  225. return self._matches('stderr', expected)
  226. @pytest.fixture(scope="module")
  227. def conf(request):
  228. """Create a Conf instance and provide it to test functions."""
  229. return Conf(request)