prepend test directory to sys path so runtest will be able to locate tests catch valueerror to catch io unsupportedoperation on textiobase and valueerror on a closed stream catch attributeerror for stderr being none display the python traceback on fatal errors e g segfault display the python traceback on sigalrm or sigusr1 signal some times path and file are not absolute e g while running from lib and if we change the cwd to run the tests in a temporary dir some imports might fail this affects only the modules imported before os chdir these modules are searched first in sys path0 so the cwd and if they are found in the cwd their file and path will be relative this happens before the chdir all the modules imported after the chdir are not found in the cwd and since the other paths in sys path1 are absolute site py absolutize them the file and path will be absolute too therefore it is necessary to absolutize manually the file and path of the packages to prevent later imports to fail when the cwd is different add an auditing hook for all tests to ensure pysysaudit is tested ensure there s a nonascii character in env vars at all times to force tests consider this case see bpo44647 for details for a slow buildbot worker increase shorttimeout and longtimeout don t increase internettimeout if timeout is short reduce timeouts private attribute that mypy doesn t know about prepend test directory to sys path so runtest will be able to locate tests catch valueerror to catch io unsupportedoperation on textiobase and valueerror on a closed stream catch attributeerror for stderr being none display the python traceback on fatal errors e g segfault display the python traceback on sigalrm or sigusr1 signal some times __path__ and __file__ are not absolute e g while running from lib and if we change the cwd to run the tests in a temporary dir some imports might fail this affects only the modules imported before os chdir these modules are searched first in sys path 0 so the cwd and if they are found in the cwd their __file__ and __path__ will be relative this happens before the chdir all the modules imported after the chdir are not found in the cwd and since the other paths in sys path 1 are absolute site py absolutize them the __file__ and __path__ will be absolute too therefore it is necessary to absolutize manually the __file__ and __path__ of the packages to prevent later imports to fail when the cwd is different add an auditing hook for all tests to ensure pysys_audit is tested ensure there s a non ascii character in env vars at all times to force tests consider this case see bpo 44647 for details for a slow buildbot worker increase short_timeout and long_timeout don t increase internet_timeout if timeout is short reduce timeouts private attribute that mypy doesn t know about type ignore attr defined
import faulthandler
import gc
import os
import random
import signal
import sys
import unittest
from test import support
from test.support.os_helper import TESTFN_UNDECODABLE, FS_NONASCII

from .filter import set_match_tests
from .runtests import RunTests
from .utils import (
    setup_unraisable_hook, setup_threading_excepthook, fix_umask,
    adjust_rlimit_nofile)


UNICODE_GUARD_ENV = "PYTHONREGRTEST_UNICODE_GUARD"


def setup_test_dir(testdir: str | None) -> None:
    if testdir:
        
        
        sys.path.insert(0, os.path.abspath(testdir))


def setup_process():
    fix_umask()

    try:
        stderr_fd = sys.__stderr__.fileno()
    except (ValueError, AttributeError):
        
        
        
        
        stderr_fd = None
    else:
        
        faulthandler.enable(all_threads=True, file=stderr_fd)

        
        signals = []
        if hasattr(signal, 'SIGALRM'):
            signals.append(signal.SIGALRM)
        if hasattr(signal, 'SIGUSR1'):
            signals.append(signal.SIGUSR1)
        for signum in signals:
            faulthandler.register(signum, chain=True, file=stderr_fd)

    adjust_rlimit_nofile()

    support.record_original_stdout(sys.stdout)

    
    
    
    
    
    
    
    
    
    
    for module in sys.modules.values():
        if hasattr(module, '__path__'):
            for index, path in enumerate(module.__path__):
                module.__path__[index] = os.path.abspath(path)
        if getattr(module, '__file__', None):
            module.__file__ = os.path.abspath(module.__file__)

    if hasattr(sys, 'addaudithook'):
        
        def _test_audit_hook(name, args):
            pass
        sys.addaudithook(_test_audit_hook)

    setup_unraisable_hook()
    setup_threading_excepthook()

    
    
    if TESTFN_UNDECODABLE and os.supports_bytes_environ:
        os.environb.setdefault(UNICODE_GUARD_ENV.encode(), TESTFN_UNDECODABLE)
    elif FS_NONASCII:
        os.environ.setdefault(UNICODE_GUARD_ENV, FS_NONASCII)


def setup_tests(runtests: RunTests):
    support.verbose = runtests.verbose
    support.failfast = runtests.fail_fast
    support.PGO = runtests.pgo
    support.PGO_EXTENDED = runtests.pgo_extended

    set_match_tests(runtests.match_tests)

    if runtests.use_junit:
        support.junit_xml_list = []
        from .testresult import RegressionTestResult
        RegressionTestResult.USE_XML = True
    else:
        support.junit_xml_list = None

    if runtests.memory_limit is not None:
        support.set_memlimit(runtests.memory_limit)

    support.suppress_msvcrt_asserts(runtests.verbose >= 2)

    support.use_resources = runtests.use_resources

    timeout = runtests.timeout
    if timeout is not None:
        
        support.LOOPBACK_TIMEOUT = max(support.LOOPBACK_TIMEOUT, timeout / 120)
        
        support.SHORT_TIMEOUT = max(support.SHORT_TIMEOUT, timeout / 40)
        support.LONG_TIMEOUT = max(support.LONG_TIMEOUT, timeout / 4)

        
        support.LOOPBACK_TIMEOUT = min(support.LOOPBACK_TIMEOUT, timeout)
        support.INTERNET_TIMEOUT = min(support.INTERNET_TIMEOUT, timeout)
        support.SHORT_TIMEOUT = min(support.SHORT_TIMEOUT, timeout)
        support.LONG_TIMEOUT = min(support.LONG_TIMEOUT, timeout)

    if runtests.hunt_refleak:
        
        unittest.BaseTestSuite._cleanup = False  

    if runtests.gc_threshold is not None:
        gc.set_threshold(runtests.gc_threshold)

    random.seed(runtests.random_seed)