main.py 11 KB

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