1"""Support functions for testing scripts in the Tools directory."""
2import contextlib
3import importlib
4import os.path
5import unittest
6from test import support
7from test.support import import_helper
8
9
10if support.check_sanitizer(address=True, memory=True):
11    # bpo-46633: Skip the test because it is too slow when Python is built
12    # with ASAN/MSAN: between 5 and 20 minutes on GitHub Actions.
13    raise unittest.SkipTest("test too slow on ASAN/MSAN build")
14
15
16if not support.has_subprocess_support:
17    raise unittest.SkipTest("test module requires subprocess")
18
19
20basepath = os.path.normpath(
21        os.path.dirname(                 # <src/install dir>
22            os.path.dirname(                # Lib
23                os.path.dirname(                # test
24                    os.path.dirname(__file__)))))    # test_tools
25
26toolsdir = os.path.join(basepath, 'Tools')
27scriptsdir = os.path.join(toolsdir, 'scripts')
28
29def skip_if_missing(tool=None):
30    if tool:
31        tooldir = os.path.join(toolsdir, tool)
32    else:
33        tool = 'scripts'
34        tooldir = scriptsdir
35    if not os.path.isdir(tooldir):
36        raise unittest.SkipTest(f'{tool} directory could not be found')
37
38@contextlib.contextmanager
39def imports_under_tool(name, *subdirs):
40    tooldir = os.path.join(toolsdir, name, *subdirs)
41    with import_helper.DirsOnSysPath(tooldir) as cm:
42        yield cm
43
44def import_tool(toolname):
45    with import_helper.DirsOnSysPath(scriptsdir):
46        return importlib.import_module(toolname)
47
48def load_tests(*args):
49    return support.load_package_tests(os.path.dirname(__file__), *args)
50