#!/usr/local/bin/python3.12
# -*- coding: utf-8 -*-

"""run_test.py [options]

as_run unittests

For example, use: ASTER_ROOT=/usr/local/aster run_test.py
"""

import os
import unittest
from glob      import glob
from optparse  import OptionParser
from pprint import pprint

import common

DEFAULT = [
    "010_misc", "015_package", "020_object", "030_server",
    "050_build_export", "060_thread", "065_system",
    "100_study", "110_server",
    "200_client", "210_multi",
    # TODO remove these obsolete tests
    # "300_development", "310_study_dvp", "320_astout_dvp",
]
if os.name != "posix":
    DEFAULT.remove("system")

LONG = [
    "150_astout", "160_parametric",
    "301_development_long",
]

ALL = DEFAULT + LONG


def def_suite(*l_mod):
    suite = unittest.TestSuite()
    #for module in l_mod:
        #suite.addTest(unittest.TestLoader().loadTestsFromName(module))
    suite.addTest(unittest.TestLoader().loadTestsFromNames(l_mod))
    return suite


def _set_verbosity(option, opt, value, parser, *args):
    parser.values.verbose = args[0]


if __name__ == "__main__":
    parser = OptionParser(usage=__doc__)
    parser.add_option("-q", action="callback", callback=_set_verbosity, callback_args=(0,),
            dest="verbose", default=2, help="run silently")
    parser.add_option("-v", action="callback", callback=_set_verbosity, callback_args=(2,),
            help="add trace")
    parser.add_option('--all', dest='all', action='store_true', default=False,
            help="run all testcases")
    parser.add_option('--long', dest='long', action='store_true', default=False,
            help="run only long testcases")
    parser.add_option('--vers', dest='vers', action='store', default=None,
            help="use the specify version")
    parser.add_option('--host', dest='host', action='store', default=None,
            help="list of hosts (comma separated) to check remote features with "
                 "their ASTER_ROOT directory. Example : "
                 "--host=computer1:/usr/local/aster,server2:/aster "
                 "(using a different username is not yet supported)")
    opts, l_args = parser.parse_args()

    common.init(opts.host)
    if opts.vers:
        common.set_version(opts.vers)
    print('Temporary directory :', common.tmpdir)
    print("Configuration for unittests :")
    pprint(common.dict_conf)
    if opts.host:
        from data import available_hosts
        print('Available remote hosts : ', ', '.join(list(available_hosts.keys())))
    print()

    if opts.all:
        l_args = ALL
    elif opts.long:
        l_args = LONG
    elif len(l_args) == 0:
        l_args = DEFAULT
    l_test = [test.replace(".py", "") for test in l_args]
    l_test.sort()
    if "clean" in l_test:
        l_test = ["999_clean"]

    suite = def_suite(*l_test)
    unittest.TextTestRunner(verbosity=opts.verbose).run(suite)
