import os
import re

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['CPPPATH'].remove(Dir('..'))
    env_test.PrependUnique(CPPPATH=env['includedir'], delete_existing=1)
    env_test['lib_includes'] = []
    lib_dir = env['libdir']
else:
    # build unit tests for this code repository
    Import('libdiffpy')
    lib_dir = libdiffpy[0].dir.abspath

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

# Use only libraries needed for building the unit tests.
pat = 'diffpy|boost_serialization|ObjCryst'
keeplibs = lambda s: re.search(pat, str(s))
env_test.Replace(LIBS=filter(keeplibs, env_test['LIBS']))

# 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') is not None:
        rv = rv and any(t.lower() in fl
                for t in Split(env_test['tests']))
    return rv

# alltests -- the unit test driver source files
test_sources = filter(srcincluded, GlobSources('Test*.hpp'))

# 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 = filter(srcsupported, test_helpers)

alltests = env_test.CxxTest('alltests', test_sources + test_helpers)
Alias('alltests', [alltests, env['lib_includes']])

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

# vim: ft=python
