# -*- python -*-
##
## SConscript  -  SCons buildscript for the Testsuite (called by SConstruct)
##

import os
from os import path
from Buildhelper import srcSubtree
from Buildhelper import scanSubtree
from Buildhelper import globRootdirs

Import('env','artifacts','core')

# temp fix to add test.h  -- wouldn't it be better to put this header be into src/lib ?  
env = env.Clone()
env.Append(CPPPATH='#/.')  # add Rootdir to Includepath, so test/test.h is found
# temp fix------------- 

def testExecutable(env,tree, exeName=None, obj=None):
    """ declare all targets needed to create a standalone
        Test executable of the given Sub-tree. Note that
        each subdir is built in its own Environment.
    """
    env = env.Clone()
    env.Append(CPPPATH=tree) # add Subdir to Includepath 
    tree = env.subst(tree)  # expand Construction Vars
    if obj:
        obj = [path.join(tree,name) for name in obj]
    else:
        obj = srcSubtree(env,tree, isShared=False) # use all sourcefiles found in subtree
    if not exeName:
        exeName = 'test-%s' % tree
    return env.Program('#$BINDIR/'+exeName, obj + core)


def testCollection(env,dir):
    """ treat a Directory containing a collection of standalone tests.
        Link each of them into an independent executable
    """
    srcpatt = ['test-*.c']
    exeName = lambda p: path.basename(path.splitext(p)[0])
    buildIt = lambda p: env.Program("#$BINDIR/"+exeName(p), [p] + core)
    return [buildIt(f) for f in scanSubtree(dir,srcpatt)] 


def treatPluginTestcase(env):
    """ Special case: the test-plugin executable
    """
    tree = 'plugin'
    env = env.Clone()
    env.Append(CPPPATH=tree, CPPDEFINES='LUMIERA_PLUGIN')
    prfx = path.join(tree,'example_plugin')
    oC   = env.SharedObject(prfx,        prfx+'.c')
    oCPP = env.SharedObject(prfx+'_cpp', prfx+'.cpp')
    testplugin = ( env.LoadableModule('#$LIBDIR/examplepluginc',    oC, SHLIBPREFIX='')
#                + env.SharedLibrary('#$LIBDIR/exampleplugincpp', oCPP, SHLIBPREFIX='')
# doesn't compile yet...
                 )
    
    return testplugin
        #-- it depends (at the moment) on a specific isolated test-plugin,
        #   which is not integrated in the "normal procedure" for building Plugins
        #   (which is not yet implemented as of 8/07)
        #   TODO: handle this case automatically


# 
# build a Test-Executable out of every subdir...
moduledirs = globRootdirs('*')

# but have to treat some subdirs individually.
specials = ['plugin','lib','components']



artifacts['testsuite'] = ts = ( [ testExecutable(env, dir) for dir in ['lib','components'] ] 
                              + treatPluginTestcase(env)
                              + [ testCollection(env, dir) for dir in moduledirs if not dir in specials]
                              ) 
                              





#
# actually run the Testsuite
#
#  - the product of running the Testsuite is the ",testlog"
#  - it depends on all artifacts defined as "ts" above
#  - if not set via options switch, the environment variable TESTSUITES
#    is explicitly propagated to test.sh
#
testEnv = env.Clone()

valgrind = os.environ.get('VALGRINDFLAGS', '') # unset if not defined
if not valgrind and not env['VALGRIND']:
    valgrind = 'DISABLE'

testEnv.Append(ENV = { 'VALGRINDFLAGS' : valgrind
                     , 'LUMIERA_CONFIG_PATH' : './' 
                     })
    
testsuites = env['TESTSUITES'] or os.environ.get('TESTSUITES')
if testsuites:
    testEnv['ENV']['TESTSUITES'] = testsuites 
    
pluginpath = os.environ.get('LUMIERA_PLUGIN_PATH')
if testsuites:
    testEnv['ENV']['LUMIERA_PLUGIN_PATH'] = pluginpath 
 
testDir = env.Dir('#$BINDIR')
runTest = env.File("test.sh").abspath

runTs = testEnv.Command(',testlog', ts, runTest,  chdir=testDir)



#
# define Phony targets
#  - 'scons testcode' triggers building of the Testsuite
#  - 'scons check' triggers building and running
#
env.Alias('testcode', ts )
env.Alias('check', runTs )

# allow tempfiles of test.sh to be cleaned  
env.Clean ('check', [',testlog.pre',',expect_stdout',',stdout',',stderr',',testtmp','.libs']) 
