#! /usr/bin/env python
# Copyright (C) 2004, 2005, 2006, 2007, 2008 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the LGPL (>=v2.1)
# Read the file COPYING coming with the software for details.

"""
Main entry point for the test suite.

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

import os
import sys
import unittest
import optparse

test_dir = os.path.dirname(__file__)
sys.path.append(os.path.join(test_dir, os.pardir))

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 whose name starts with 'test' and ends with '.py'.

    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 = ""

    suffix = ".py"
    return [prefix + name[:-len(suffix)]
            for name in os.listdir(dirname)
                if name.startswith("test") and name.endswith(suffix)]


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

    parser = optparse.OptionParser()
    parser.set_defaults(verbosity=1, test_private_metadata=False)
    parser.add_option("-v", "--verbose", action="store_const", const=2,
                      dest="verbosity")
    parser.add_option("--test-private-metadata", action="store_const",
                      const=True)
    parser.add_option("--config")
    opts, rest = parser.parse_args()

    if opts.config is not None:
        import imapsupport
        imapsupport.default_config_file = opts.config

    # 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 rest:
        names = rest
    else:
        names = find_test_modules(test_dir)
        if not opts.test_private_metadata:
            names = [name for name in names if not name.endswith("_private")]

    suite = unittest.defaultTestLoader.loadTestsFromNames(names)
    runner = unittest.TextTestRunner(verbosity=opts.verbosity)
    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())


if __name__ == "__main__":
    main()
