# Copyright (c) 2009 testtools developers. See LICENSE for details.

"""python -m testtools.run testspec [testspec...]

Run some tests with the testtools extended API.

For instance, to run the testtools test suite.
 $ python -m testtools.run tests.test_suite
"""

import os.path
import sys
import unittest
from argparse import ArgumentParser
from collections.abc import Callable
from functools import partial
from types import ModuleType
from typing import IO, Any, TextIO

from testtools import TextTestResult
from testtools.compat import unicode_output_stream
from testtools.testsuite import filter_by_ids, iterate_tests, sorted_tests

# unittest.TestProgram has these methods but mypy's stubs don't include them
# We'll just use unittest.TestProgram directly and ignore the type errors

defaultTestLoader = unittest.defaultTestLoader
defaultTestLoaderCls = unittest.TestLoader
have_discover = True
discover_impl = getattr(unittest, "loader", None)

# Kept for API compatibility, but no longer used.
BUFFEROUTPUT = ""
CATCHBREAK = ""
FAILFAST = ""
USAGE_AS_MAIN = ""


def list_test(
    test: unittest.TestSuite | unittest.TestCase,
) -> tuple[list[str], list[str]]:
    """Return the test ids that would be run if test() was run.

    When things fail to import they can be represented as well, though
    we use an ugly hack (see http://bugs.python.org/issue19746 for details)
    to determine that. The difference matters because if a user is
    filtering tests to run on the returned ids, a failed import can reduce
    the visible tests but it can be impossible to tell that the selected
    test would have been one of the imported ones.

    :return: A tuple of test ids that would run and error strings
        describing things that failed to import.
    """
    unittest_import_strs = {
        "unittest.loader.ModuleImportFailure.",
        "discover.ModuleImportFailure.",
    }
    test_ids: list[str] = []
    errors: list[str] = []
    for single_test in iterate_tests(test):
        # Much ugly.
        for prefix in unittest_import_strs:
            if single_test.id().startswith(prefix):
                errors.append(single_test.id()[len(prefix) :])
                break
        else:
            test_ids.append(single_test.id())
    return test_ids, errors


class TestToolsTestRunner:
    """A thunk object to support unittest.TestProgram."""

    verbosity: int
    failfast: bool | None
    stdout: IO[str]
    tb_locals: bool

    def __init__(
        self,
        verbosity: int | None = None,
        failfast: bool | None = None,
        buffer: bool | None = None,
        stdout: IO[str] | None = None,
        tb_locals: bool = False,
        **kwargs: Any,
    ) -> None:
        """Create a TestToolsTestRunner.

        :param verbosity: Verbosity level. 0 for quiet, 1 for normal (dots, default),
            2 for verbose (test names).
        :param failfast: Stop running tests at the first failure.
        :param buffer: Ignored.
        :param stdout: Stream to use for stdout.
        :param tb_locals: If True include local variables in tracebacks.
        """
        self.verbosity = verbosity if verbosity is not None else 1
        self.failfast = failfast
        if stdout is None:
            stdout = sys.stdout
        self.stdout = stdout
        self.tb_locals = tb_locals

    def list(
        self,
        test: unittest.TestSuite | unittest.TestCase,
        loader: unittest.TestLoader | None = None,
    ) -> None:
        """List the tests that would be run if test() was run."""
        test_ids, _ = list_test(test)
        for test_id in test_ids:
            self.stdout.write(f"{test_id}\n")
        if loader is not None:
            errors = loader.errors
            if errors:
                for error in errors:
                    self.stdout.write(f"{error}\n")
                sys.exit(2)

    def run(
        self, test: unittest.TestSuite | unittest.TestCase
    ) -> unittest.TestResult | None:
        """Run the given test case or test suite."""
        stream: TextIO = unicode_output_stream(self.stdout)  # type: ignore[assignment]
        result = TextTestResult(
            stream,
            failfast=self.failfast or False,
            tb_locals=self.tb_locals,
            verbosity=self.verbosity,
        )
        result.startTestRun()
        try:
            return test.run(result)
        finally:
            result.stopTestRun()


####################
# Taken from python 2.7 and slightly modified for compatibility with
# older versions. Delete when 2.7 is the oldest supported version.
# Modifications:
#  - If --catch is given, check that installHandler is available, as
#    it won't be on old python versions or python builds without signals.
#  - --list has been added which can list tests (should be upstreamed).
#  - --load-list has been added which can reduce the tests used (should be
#    upstreamed).


class TestProgram(unittest.TestProgram):
    """A command-line program that runs a set of tests; this is primarily
    for making test modules conveniently executable.
    """

    # defaults for testing
    module: ModuleType | None = None
    verbosity: int = 1
    failfast: bool | None = None
    catchbreak: bool | None = None
    buffer: bool | None = None
    progName: str | None = None
    _discovery_parser: ArgumentParser | None = None
    test: Any  # Set by parent class
    stdout: IO[str]
    exit: bool
    tb_locals: bool
    defaultTest: str | None
    listtests: bool
    load_list: str | None
    testRunner: Callable[..., TestToolsTestRunner] | TestToolsTestRunner | None
    testLoader: unittest.TestLoader
    result: unittest.TestResult

    def __init__(
        self,
        module: str | ModuleType | None = __name__,
        defaultTest: str | None = None,
        argv: list[str] | None = None,
        testRunner: Callable[..., TestToolsTestRunner]
        | TestToolsTestRunner
        | None = None,
        testLoader: unittest.TestLoader = defaultTestLoader,
        exit: bool = True,
        verbosity: int = 1,
        failfast: bool | None = None,
        catchbreak: bool | None = None,
        buffer: bool | None = None,
        stdout: IO[str] | None = None,
        tb_locals: bool = False,
    ) -> None:
        if module == __name__:
            self.module = None
        elif isinstance(module, str):
            self.module = __import__(module)
            for part in module.split(".")[1:]:
                self.module = getattr(self.module, part)
        else:
            self.module = module
        if argv is None:
            argv = sys.argv
        if stdout is None:
            stdout = sys.stdout
        self.stdout = stdout

        self.exit = exit
        self.failfast = failfast
        self.catchbreak = catchbreak
        self.verbosity = verbosity
        self.buffer = buffer
        self.tb_locals = tb_locals
        self.defaultTest = defaultTest
        # XXX: Local edit (see http://bugs.python.org/issue22860)
        self.listtests = False
        self.load_list = None
        self.testRunner = testRunner
        self.testLoader = testLoader
        progName = argv[0]
        if progName.endswith(f"{os.path.sep}run.py"):
            elements = progName.split(os.path.sep)
            progName = f"{elements[-2]}.run"
        else:
            progName = os.path.basename(argv[0])
        self.progName = progName
        self.parseArgs(argv)
        # XXX: Local edit (see http://bugs.python.org/issue22860)
        if self.load_list:
            # TODO: preserve existing suites (like testresources does in
            # OptimisingTestSuite.add, but with a standard protocol).
            # This is needed because the load_tests hook allows arbitrary
            # suites, even if that is rarely used.
            source = open(self.load_list, "rb")
            try:
                lines = source.readlines()
            finally:
                source.close()
            test_ids = {line.strip().decode("utf-8") for line in lines}
            self.test = filter_by_ids(self.test, test_ids)
        # XXX: Local edit (see http://bugs.python.org/issue22860)
        if not self.listtests:
            self.runTests()
        else:
            runner = self._get_runner()
            if hasattr(runner, "list"):
                runner.list(self.test, loader=self.testLoader)
            else:
                for test in iterate_tests(self.test):
                    self.stdout.write(f"{test.id()}\n")
        del self.testLoader.errors[:]

    def _getParentArgParser(self) -> ArgumentParser:
        parser: ArgumentParser = super()._getParentArgParser()  # type: ignore[misc]
        # XXX: Local edit (see http://bugs.python.org/issue22860)
        parser.add_argument(
            "-l",
            "--list",
            dest="listtests",
            default=False,
            action="store_true",
            help="List tests rather than executing them",
        )
        parser.add_argument(
            "--load-list",
            dest="load_list",
            default=None,
            help="Specifies a file containing test ids, only tests matching "
            "those ids are executed",
        )
        return parser

    def _do_discovery(
        self, argv: list[str], Loader: type[unittest.TestLoader] | None = None
    ) -> None:
        super()._do_discovery(argv, Loader=Loader)  # type: ignore[misc]
        # XXX: Local edit (see http://bugs.python.org/issue22860)
        self.test = sorted_tests(self.test)

    def runTests(self) -> None:
        # XXX: Local edit (see http://bugs.python.org/issue22860)
        if self.catchbreak and getattr(unittest, "installHandler", None) is not None:
            unittest.installHandler()
        testRunner = self._get_runner()
        result = testRunner.run(self.test)
        if result is not None:
            self.result = result
        if self.exit:
            sys.exit(not self.result.wasSuccessful())

    def _get_runner(self) -> TestToolsTestRunner:
        # XXX: Local edit (see http://bugs.python.org/issue22860)
        runner_or_factory = self.testRunner
        if runner_or_factory is None:
            runner_or_factory = TestToolsTestRunner

        # If it's already an instance, return it directly
        if isinstance(runner_or_factory, TestToolsTestRunner):
            return runner_or_factory

        # It's a callable (class or factory function)
        runner_factory: Callable[..., TestToolsTestRunner] = runner_or_factory
        try:
            try:
                testRunner = runner_factory(
                    verbosity=self.verbosity,
                    failfast=self.failfast,
                    buffer=self.buffer,
                    stdout=self.stdout,
                    tb_locals=self.tb_locals,
                )
            except TypeError:
                # didn't accept the tb_locals parameter
                testRunner = runner_factory(
                    verbosity=self.verbosity,
                    failfast=self.failfast,
                    buffer=self.buffer,
                    stdout=self.stdout,
                )
        except TypeError:
            # didn't accept the verbosity, buffer, failfast or stdout arguments
            # Try with the prior contract
            try:
                testRunner = runner_factory(
                    verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer
                )
            except TypeError:
                # Now try calling it with defaults
                testRunner = runner_factory()
        return testRunner


################


def main(argv: list[str], stdout: IO[str]) -> None:
    TestProgram(
        argv=argv, testRunner=partial(TestToolsTestRunner, stdout=stdout), stdout=stdout
    )


if __name__ == "__main__":
    main(sys.argv, sys.stdout)
