# Copyright (c) 2004 DoCoMo Euro-Labs GmbH (Munich, Germany).
# Copyright (c) 2001-2004 LOGILAB S.A. (Paris, FRANCE).
#
# http://www.docomolab-euro.com/ -- mailto:tarlano@docomolab-euro.com
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""USAGE: %s [OPTIONS] <tests pattern>

A command line tool  to run Narval's acceptance tests
Launch all tests matching the given pattern. If the pattern is "all", run
all available test cases

OPTIONS:
  --help      display this help message and exit
  --debug     run narval in debug mode
  --keep-tmp  keep temporary files generated by the test
  --home=dir  use <dir> as narval home directory instead of $NARVAL_HOME


:version: $Revision:$  
:author: Logilab
"""

__revision__ = '$Id: autotest.py,v 1.2 2002/08/14 11:47:37 syt Exp $'
__docformat__ = "restructuredtext en"

import os
import sys
import shutil
import tempfile
import getopt
from os.path import basename

from narval.config import get_home, DEFAULT_CONFIGURATOR
from narval.apycot import NarvalChecker


def usage(status=1):
    """display usage and exit

    :type status: int
    :param status: exit status
    """
    print __doc__ % basename(sys.argv[0])
    sys.exit(status)


class InstantWriter:
    """dummy writer compliant to the Apycot API, displaying everything on stdout
    """
    
    def raw(self, klass, value):
        """get a raw value

        :type klass: str
        :param klass: the raw class

        :type value: str
        :param value: the value for the given class
        """
        print klass, ':', value
        
    def log(self, severity, path, line, msg):
        """get a log message

        :type severity: int
        :param severity: log message severity

        :type path: str
        :param path: file source of the message

        :type line: int or None
        :param line: line number in the file if known

        :type msg: str
        :param msg: content of the log message
        """
        if line is not None:
            print '%s [%s]: %s' % (path, line, msg.strip())
        else:
            print '%s: %s' % (path, msg.strip())
        
        
def run(args=None):
    """command line launcher

    :type args: list
    :param args: command line arguments, without the script name
    """
    args = args or sys.argv[1:]
    try:
        clopts, args = getopt.getopt(args, 'hdkn:', ('help', 'debug', 'keep-tmp', 'home='))
    except getopt.error,ex:
        print 'Error:', ex
        usage(1)
    options  = {'command': ' '.join(args)}
    keep_tmp_files = False
    for opt, val in clopts:
        if opt in ('-h' '--help'):
            usage(0)
        if opt in ('-d', '--debug'):
            options['debug'] = True
        if opt in ('-k', '--keep-tmp'):
            keep_tmp_files = True
        elif opt in ('-n', '--home'):
            DEFAULT_CONFIGURATOR.set_home_from_command_line(val)
    checker = NarvalChecker()
    checker.set_options(options)
    class Test:
        """fake tester.Test.Test"""
        tmpdir = tempfile.mktemp()
        class Repo:
            """fake tester.interface.IRepository"""
            path = get_home()
            def env_path(self):
                """return the repository test environment path"""
                return self.path
        repo = Repo()
    os.mkdir(Test.tmpdir)
    try:
        checker.run(Test(), InstantWriter())
    finally:
        if not keep_tmp_files:
            shutil.rmtree(Test.tmpdir)

if __name__ == '__main__':
    run(sys.argv[1:])

