Import('env', 'GlobSources')

# Environment for building unit test driver
env_test = env.Clone(CXXTEST_SUFFIX='.hpp')
env_test.Tool('cxxtest')

if env['test_installed']:
    # build unit tests for the installed library
    env_test.PrependUnique(CPPPATH=env['includedir'], delete_existing=1)
    lib_dir = env['libdir']
else:
    # link unit tests with our library.
    Import('libdiffpy')
    lib_dir = libdiffpy[0].dir.abspath
use_our_library = not env['test_installed']

env_test.PrependUnique(LIBS='diffpy', LIBPATH=lib_dir, delete_existing=1)
env_test.PrependUnique(LINKFLAGS="-Wl,-rpath,%r" % lib_dir)

# Targets --------------------------------------------------------------------

def srcsupported(f):
    rv = env.get('has_objcryst') or 'objcryst' not in str(f).lower()
    return rv

def srcincluded(f):
    fl = str(f).lower()
    rv = srcsupported(f)
    rv = rv and f.srcnode().isfile()
    if env_test.get('tests'):
        tpatterns = Split(env_test['tests'].lower().replace(',', ' '))
        rv = rv and any(tp in fl for tp in tpatterns)
    return rv

# alltests -- the unit test driver source files
test_sources = [f for f in GlobSources('Test*.hpp') if srcincluded(f)]
if not test_sources:
    ts = env_test.get('tests', '')
    print("Cannot find any test matching 'tests={}'.".format(ts))
    Exit(1)

# Define the DIFFPYTESTSDIRPATH macro required for test_helpers.cpp
thisdir = Dir('.').srcnode().abspath
env_th = env_test.Clone()
env_th.AppendUnique(CPPDEFINES=dict(DIFFPYTESTSDIRPATH=thisdir))
thobj = env_th.Object('test_helpers.cpp')

test_helpers = thobj + ['objcryst_helpers.cpp']
test_helpers = [f for f in test_helpers if srcsupported(f)]

alltests = env_test.CxxTest('alltests', test_sources + test_helpers)
if use_our_library:
    env_test.Depends(alltests, libdiffpy)

# Clean up .gcda and .gcno files from coverage analysis.
env_test.Clean(alltests, Glob('*.gc??'))

env_test.Alias('alltests', alltests)

# test -- alias for executing unit tests.
test = env_test.Alias('test', alltests, alltests[0].abspath)
AlwaysBuild(test)

# vim: ft=python
