# Copyright (c) 2002, 2003, 2004, 2005, 2006 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
Main entry point for the Thuban test suite.

Just run this file as a python script to execute all tests
"""

__version__ = "$Revision: 2705 $"
# $Source$
# $Id: runtests.py 2705 2006-09-24 18:55:30Z bernhard $

import os

# It should be possible to run the Thuban testsuite without an X
# connection, so we remove the DISPLAY environment variable which should
# lead to an error if the wxGTK module is imported accidentally. The
# DISPLAY variable is not always set so we catch and ignore the KeyError
try:
    del os.environ["DISPLAY"]
except KeyError:
    pass

import sys
import warnings
import unittest
import getopt

import support
support.initthuban()
import Thuban.Lib.connector

def find_test_modules(dirname, package = None):
    """Return a list the names of the test modules in the directory dirname

    The return value is a list of names that can be passed to
    unittest.defaultTestLoader.loadTestsFromNames.  Each name of the
    list is the name of a pure python module, one for each file in
    dirname that starts with 'test'.

    The optional parameter package should be the name of the python
    package whose directory is dirname.  If package is given all names
    in the returned list will be prefixed with package and a dot.
    """
    if package:
        prefix = package + "."
    else:
        prefix = ""

    return [prefix + name[:-3]
            for name in os.listdir(dirname)
                if name[:4] == "test" and name[-3:] == ".py"]


def main():
    """Run all the tests in the Thuban test suite"""

    # Turn Thuban's deprecation warnings into errors so they're caught
    # by the tests
    #
    # Maintenance: Keep a warning filter until the backwards
    # compatibility code is removed at which time using the old
    # interfaces should lead to other errors anyway.

    # The layer attributes table, shapetable, shapefile and filename are
    # deprecated.
    warnings.filterwarnings("error", "The Layer attribute.*is deprecated",
                            DeprecationWarning)

    verbosity = 1

    opts, args = getopt.getopt(sys.argv[1:], 'v',
                ['verbose', 'setdecimalcommalocale', "internal-encoding="])
    for optchar, value in opts:
        if optchar in ("-v", "--verbose"):
            verbosity = 2
        elif optchar == "--internal-encoding":
            Thuban.set_internal_encoding(value)
        elif optchar == "--setdecimalcommalocale":
            import localessupport
            oldlocale = localessupport.setdecimalcommalocale()
            if oldlocale == None:
                print>>sys.stderr, "Did not find a locale with comma."
        else:
            print>>sys.stderr, "Unknown option", optchar

    # Build the list of test names.  If names were given on the command
    # line, run exactly those.  Othwerwise build a default list of
    # names.
    if args:
        names = args
    else:
        # All Python files starting with 'test' in the current directory
        # and some directories in Extensions contain test cases.
        # FIXME: It should be possible to run runtests.py even when not in
        # the test directory
        names = find_test_modules(".")
        names += find_test_modules("../Extensions/svgexport/test",
                                   "Extensions.svgexport.test")
        names += find_test_modules("../Extensions/ogr/test",
                                   "Extensions.ogr.test")
    suite = unittest.defaultTestLoader.loadTestsFromNames(names)
    runner = support.ThubanTestRunner(verbosity = verbosity)
    result = support.execute_as_testsuite(runner.run, suite)

    sys.exit(not result.wasSuccessful())


if __name__ == "__main__":
    main()
