main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. #!/usr/bin/env python
  2. # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
  3. import importlib
  4. import os
  5. import re
  6. import shutil
  7. import subprocess
  8. import sys
  9. import time
  10. import unittest
  11. from collections.abc import Callable, Generator, Iterator, Sequence
  12. from contextlib import contextmanager
  13. from functools import lru_cache
  14. from tempfile import TemporaryDirectory
  15. from threading import Thread
  16. from typing import (
  17. Any,
  18. NoReturn,
  19. Optional,
  20. )
  21. from . import BaseTest
  22. def contents(package: str) -> Iterator[str]:
  23. try:
  24. if sys.version_info[:2] < (3, 10):
  25. raise ImportError("importlib.resources.files() doesn't work with frozen builds on python 3.9")
  26. from importlib.resources import files
  27. except ImportError:
  28. from importlib.resources import contents
  29. return iter(contents(package))
  30. return (path.name for path in files(package).iterdir())
  31. def itertests(suite: unittest.TestSuite) -> Generator[unittest.TestCase, None, None]:
  32. stack = [suite]
  33. while stack:
  34. suite = stack.pop()
  35. for test in suite:
  36. if isinstance(test, unittest.TestSuite):
  37. stack.append(test)
  38. continue
  39. if test.__class__.__name__ == 'ModuleImportFailure':
  40. raise Exception('Failed to import a test module: %s' % test)
  41. yield test
  42. def find_all_tests(package: str = '', excludes: Sequence[str] = ('main', 'gr')) -> unittest.TestSuite:
  43. suits = []
  44. if not package:
  45. package = __name__.rpartition('.')[0] if '.' in __name__ else 'kitty_tests'
  46. for x in contents(package):
  47. name, ext = os.path.splitext(x)
  48. if ext in ('.py', '.pyc') and name not in excludes:
  49. m = importlib.import_module(package + '.' + x.partition('.')[0])
  50. suits.append(unittest.defaultTestLoader.loadTestsFromModule(m))
  51. return unittest.TestSuite(suits)
  52. def filter_tests(suite: unittest.TestSuite, test_ok: Callable[[unittest.TestCase], bool]) -> unittest.TestSuite:
  53. ans = unittest.TestSuite()
  54. added: set[unittest.TestCase] = set()
  55. for test in itertests(suite):
  56. if test_ok(test) and test not in added:
  57. ans.addTest(test)
  58. added.add(test)
  59. return ans
  60. def filter_tests_by_name(suite: unittest.TestSuite, *names: str) -> unittest.TestSuite:
  61. names_ = {x if x.startswith('test_') else 'test_' + x for x in names}
  62. def q(test: unittest.TestCase) -> bool:
  63. return test._testMethodName in names_
  64. return filter_tests(suite, q)
  65. def filter_tests_by_module(suite: unittest.TestSuite, *names: str) -> unittest.TestSuite:
  66. names_ = frozenset(names)
  67. def q(test: unittest.TestCase) -> bool:
  68. m = test.__class__.__module__.rpartition('.')[-1]
  69. return m in names_
  70. return filter_tests(suite, q)
  71. @lru_cache
  72. def python_for_type_check() -> str:
  73. return shutil.which('python') or shutil.which('python3') or 'python'
  74. def type_check() -> NoReturn:
  75. from kitty.cli_stub import generate_stub # type:ignore
  76. generate_stub()
  77. from kittens.tui.operations_stub import generate_stub # type: ignore
  78. generate_stub()
  79. py = python_for_type_check()
  80. os.execlp(py, py, '-m', 'mypy', '--pretty')
  81. def run_cli(suite: unittest.TestSuite, verbosity: int = 4) -> bool:
  82. r = unittest.TextTestRunner
  83. r.resultclass = unittest.TextTestResult
  84. runner = r(verbosity=verbosity)
  85. runner.tb_locals = True # type: ignore
  86. from . import forwardable_stdio
  87. with forwardable_stdio():
  88. result = runner.run(suite)
  89. sys.stdout.flush()
  90. sys.stderr.flush()
  91. return result.wasSuccessful()
  92. def find_testable_go_packages() -> tuple[set[str], dict[str, list[str]]]:
  93. test_functions: dict[str, list[str]] = {}
  94. ans = set()
  95. base = os.getcwd()
  96. pat = re.compile(r'^func Test([A-Z]\w+)', re.MULTILINE)
  97. for (dirpath, dirnames, filenames) in os.walk(base):
  98. if 'b' in dirnames and os.path.basename(dirpath) == 'bypy':
  99. dirnames.remove('b')
  100. for f in filenames:
  101. if f.endswith('_test.go'):
  102. q = os.path.relpath(dirpath, base)
  103. ans.add(q)
  104. with open(os.path.join(dirpath, f)) as s:
  105. raw = s.read()
  106. for m in pat.finditer(raw):
  107. test_functions.setdefault(m.group(1), []).append(q)
  108. return ans, test_functions
  109. @lru_cache
  110. def go_exe() -> str:
  111. return shutil.which('go') or ''
  112. class GoProc(Thread):
  113. def __init__(self, cmd: list[str]):
  114. super().__init__(name='GoProc')
  115. from kitty.constants import kitty_exe
  116. env = os.environ.copy()
  117. env['KITTY_PATH_TO_KITTY_EXE'] = kitty_exe()
  118. self.stdout = b''
  119. self.start_time = time.monotonic()
  120. self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env)
  121. self.start()
  122. @property
  123. def runtime(self):
  124. return self.end_time - self.start_time
  125. @property
  126. def returncode(self):
  127. return self.proc.returncode
  128. def run(self) -> None:
  129. self.stdout, _ = self.proc.communicate()
  130. self.proc.stdout.close()
  131. def wait(self, timeout=None) -> None:
  132. try:
  133. self.join(timeout)
  134. except KeyboardInterrupt:
  135. self.proc.terminate()
  136. if self.proc.wait(0.1) is None:
  137. self.proc.kill()
  138. self.join()
  139. self.end_time = time.monotonic()
  140. return self.stdout.decode('utf-8', 'replace'), self.proc.returncode
  141. def run_go(packages: set[str], names: str) -> GoProc:
  142. go = go_exe()
  143. go_pkg_args = [f'kitty/{x}' for x in packages]
  144. cmd = [go, 'test', '-v']
  145. for name in names:
  146. cmd.extend(('-run', name))
  147. cmd += go_pkg_args
  148. return GoProc(cmd)
  149. def reduce_go_pkgs(module: str, names: Sequence[str]) -> set[str]:
  150. if not go_exe():
  151. raise SystemExit('go executable not found, current path: ' + repr(os.environ.get('PATH', '')))
  152. go_packages, go_functions = find_testable_go_packages()
  153. if module:
  154. go_packages &= {module}
  155. if names:
  156. pkgs = set()
  157. for name in names:
  158. pkgs |= set(go_functions.get(name, []))
  159. go_packages &= pkgs
  160. return go_packages
  161. def run_python_tests(args: Any, go_proc: 'Optional[GoProc]' = None) -> None:
  162. tests = find_all_tests()
  163. def print_go() -> None:
  164. stdout, rc = go_proc.wait()
  165. if go_proc.returncode == 0 and tests._tests:
  166. print(f'All Go tests succeeded, ran in {go_proc.runtime:.1f} seconds', flush=True)
  167. else:
  168. print(stdout, end='', flush=True)
  169. return rc
  170. if args.module:
  171. tests = filter_tests_by_module(tests, args.module)
  172. if not tests._tests:
  173. if go_proc:
  174. raise SystemExit(print_go())
  175. raise SystemExit('No test module named %s found' % args.module)
  176. if args.name:
  177. tests = filter_tests_by_name(tests, *args.name)
  178. if not tests._tests and not go_proc:
  179. raise SystemExit('No test named %s found' % args.name)
  180. if tests._tests:
  181. python_tests_ok = run_cli(tests, args.verbosity)
  182. else:
  183. python_tests_ok = True
  184. exit_code = 0 if python_tests_ok else 1
  185. if go_proc:
  186. print_go()
  187. if exit_code == 0:
  188. exit_code = go_proc.returncode
  189. if exit_code != 0:
  190. print("\x1b[31mError\x1b[39m: Some tests failed!")
  191. raise SystemExit(exit_code)
  192. def run_tests(report_env: bool = False) -> None:
  193. report_env = report_env or BaseTest.is_ci
  194. import argparse
  195. parser = argparse.ArgumentParser()
  196. parser.add_argument(
  197. 'name',
  198. nargs='*',
  199. default=[],
  200. help='The name of the test to run, for e.g. linebuf corresponds to test_linebuf. Can be specified multiple times.'
  201. ' For go tests Something corresponds to TestSometing.',
  202. )
  203. parser.add_argument('--verbosity', default=4, type=int, help='Test verbosity')
  204. parser.add_argument(
  205. '--module',
  206. default='',
  207. help='Name of a test module to restrict to. For example: ssh.' ' For Go tests this is the name of a package, for example: tools/cli',
  208. )
  209. args = parser.parse_args()
  210. if args.name and args.name[0] in ('type-check', 'type_check', 'mypy'):
  211. type_check()
  212. go_pkgs = reduce_go_pkgs(args.module, args.name)
  213. os.environ['ASAN_OPTIONS'] = 'detect_leaks=0' # ensure subprocesses dont fail because of leak detection
  214. if go_pkgs:
  215. go_proc: 'Optional[GoProc]' = run_go(go_pkgs, args.name)
  216. else:
  217. go_proc = None
  218. with env_for_python_tests(report_env):
  219. if go_pkgs:
  220. if report_env:
  221. print('Go executable:', go_exe())
  222. print('Go packages being tested:', ' '.join(go_pkgs))
  223. sys.stdout.flush()
  224. run_python_tests(args, go_proc)
  225. @contextmanager
  226. def env_vars(**kw: str) -> Iterator[None]:
  227. originals = {k: os.environ.get(k) for k in kw}
  228. os.environ.update(kw)
  229. try:
  230. yield
  231. finally:
  232. for k, v in originals.items():
  233. if v is None:
  234. os.environ.pop(k, None)
  235. else:
  236. os.environ[k] = v
  237. @contextmanager
  238. def env_for_python_tests(report_env: bool = False) -> Iterator[None]:
  239. gohome = os.path.expanduser('~/go')
  240. current_home = os.path.expanduser('~') + os.sep
  241. paths = os.environ.get('PATH', '/usr/local/sbin:/usr/local/bin:/usr/bin').split(os.pathsep)
  242. path = os.pathsep.join(x for x in paths if not x.startswith(current_home))
  243. launcher_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kitty', 'launcher')
  244. path = f'{launcher_dir}{os.pathsep}{path}'
  245. python_for_type_check()
  246. print('Running under CI:', BaseTest.is_ci)
  247. if report_env:
  248. print('Using PATH in test environment:', path)
  249. print('Python:', python_for_type_check())
  250. from kitty.fast_data_types import has_avx2, has_sse4_2
  251. print(f'Intrinsics: {has_avx2=} {has_sse4_2=}')
  252. # we need fonts installed in the user home directory as well, so initialize
  253. # fontconfig before nuking $HOME and friends
  254. from kitty.fonts.common import all_fonts_map
  255. all_fonts_map(True)
  256. with TemporaryDirectory() as tdir, env_vars(
  257. HOME=tdir,
  258. KT_ORIGINAL_HOME=os.path.expanduser('~'),
  259. USERPROFILE=tdir,
  260. PATH=path,
  261. TERM='xterm-kitty',
  262. XDG_CONFIG_HOME=os.path.join(tdir, '.config'),
  263. XDG_CONFIG_DIRS=os.path.join(tdir, '.config'),
  264. XDG_DATA_DIRS=os.path.join(tdir, '.local', 'xdg'),
  265. XDG_CACHE_HOME=os.path.join(tdir, '.cache'),
  266. XDG_RUNTIME_DIR=os.path.join(tdir, '.cache', 'run'),
  267. PYTHONWARNINGS='error',
  268. ):
  269. if os.path.isdir(gohome):
  270. os.symlink(gohome, os.path.join(tdir, os.path.basename(gohome)))
  271. yield
  272. def main() -> None:
  273. import warnings
  274. warnings.simplefilter('error')
  275. run_tests()