#! /usr/bin/env python
# encoding: utf-8
# Richard Quirk, 2008

"""
execute tests during the build
requires cppunit
"""

from waflib.Tools import waf_unit_test

top = '.'
out = 'build'

def options(opt):
	opt.load('compiler_cxx')
	opt.load('waf_unit_test')
	opt.add_option('--onlytests', action='store_true', default=True, help='Exec unit tests only', dest='only_tests')

def configure(conf):
	conf.load('compiler_cxx')
	conf.load('waf_unit_test')

	# the demo files require cppunit - but the waf tool does not
	conf.check_cfg(package='cppunit', args='--cflags --libs', mandatory=True)
	if 'dl' not in conf.env.LIB_CPPUNIT:
		l = conf.check(lib='dl', uselib_store='CPPUNIT')

from waflib import Logs
def summary(bld):
	lst = getattr(bld, 'utest_results', [])
	if lst:
		total = len(lst)
		tfail = len([x for x in lst if x[1]])

		val = 100 * (total - tfail) / (1.0 * total)
		Logs.pprint('CYAN', 'test report %3.0f%% success' % val)

		Logs.pprint('CYAN', '  tests that fail %d/%d' % (tfail, total))
		for (f, code, out, err) in lst:
			if code:
				Logs.pprint('CYAN', '    %s' % f)
				Logs.pprint('RED', 'status: %r' % code)
				if out: Logs.pprint('RED', 'out: %r' % out)
				if err: Logs.pprint('RED', 'err: %r' % err)

def build(bld):
	bld.recurse('src tests')

	# unittestw.summary is a pretty ugly function for displaying a report (feel free to improve!)
	# results -> bld.utest_results [(filename, returncode, stdout, stderr), (..., ), ...]
	#bld.add_post_fun(waf_unit_test.summary)
	bld.add_post_fun(summary)

	# to execute all tests:
	# $ waf --alltests
	# to set this behaviour permanenly:
	bld.options.all_tests = True

	# debugging zone:
	# $ waf --zones=ut
	# setting the cwd for a unit test execution: see tests/test1/wscript_build (ut_cwd)

