from os.path import join
import os
import subprocess

TESTS = [
    'cholesky',
    'geomap',
    'lintransform',
    'surface',
    'triangles',
    'xycoincide',
    'xysort',
    'xyxymatch',
    'xyxymatch_triangles']

def build(bld):
    test_args = {
        'features': 'cc cprogram',
        'includes': [join(bld.path.abspath(), '../include')],
        'lib': ['m', 'stdc++'],
        'uselib_local': 'stimage'
        }

    for test in TESTS:
        bld(
            source = 'test_%s.c' % test,
            target = 'test_%s' % test,
            **test_args)

def do_tests(ctx):
    import nose

    return nose.runmodule(argv = ["nosetests", "test_c"])

def valgrind(ctx):
    if not os.path.exists("valgrind"):
        os.mkdir("valgrind")

    for test in TESTS:
        print "Valgrinding %s" % test,
        path = join("build", "default", "test_c", "test_%s" % test)
        retcode = subprocess.call(
            "valgrind --log-file=valgrind/%s.vg.log --leak-check=yes %s" %
            (test, path), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            shell=True)
        if retcode != 0:
            raise RuntimeError("Test returned code %d" % retcode)

        fd = open("valgrind/%s.vg.log" % test, 'r')
        data = fd.read()
        fd.close()

        if 'are definitely lost' in data:
            print "LEAKING MEMORY"
        else:
            print
