main.py 11 KB

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