# 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 types import ModuleType
from typing import IO, Any

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

# TODO: Remove these aliases and constants in 3.0
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."""
        result = TextTestResult(
            self.stdout,
            failfast=self.failfast or False,
            tb_locals=self.tb_locals,
            verbosity=self.verbosity,
        )
        result.startTestRun()
        try:
            return test.run(result)
        finally:
            result.stopTestRun()


# Note that we need to duplicate a lot of the upstream implementation here.
# This has been reported as https://github.com/python/cpython/issues/67049
class TestProgram(unittest.TestProgram):
    """A command-line program that runs a set of tests; this is primarily
    for making test modules conveniently executable.

    Extends unittest.TestProgram with:
    - ``-l``/``--list``: list tests rather than running them
    - ``--load-list``: filter tests to those listed in a file
    - ``stdout`` parameter: control where output goes
    - Sorted test ordering after discovery
    """

    # https://github.com/python/typeshed/pull/15559
    module: ModuleType | None = None  # narrower than parent's str | ModuleType | None
    test: Any  # set by parent's createTests(), not in typeshed
    stdout: IO[str]
    listtests: bool
    load_list: str | None

    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
        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)
        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.
            with open(self.load_list, "rb") as source:
                lines = source.readlines()
            test_ids = {line.strip().decode("utf-8") for line in lines}
            self.test = filter_by_ids(self.test, test_ids)
        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:
        # this method is not part of the type stubs
        parser: ArgumentParser = super()._getParentArgParser()  # type: ignore[misc]
        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:
        # this method is not part of the type stubs
        super()._do_discovery(argv, Loader=Loader)  # type: ignore[misc]
        self.test = sorted_tests(self.test)

    def runTests(self) -> None:
        if self.catchbreak:
            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:
        runner_or_factory = self.testRunner
        if runner_or_factory is None:
            runner_or_factory = TestToolsTestRunner

        if isinstance(runner_or_factory, TestToolsTestRunner):
            return runner_or_factory

        runner_factory: Callable[..., TestToolsTestRunner] = runner_or_factory
        return runner_factory(
            verbosity=self.verbosity,
            failfast=self.failfast,
            buffer=self.buffer,
            stdout=self.stdout,
            tb_locals=self.tb_locals,
        )


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


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