#!/opt/lsb/appbat/bin/python

from pytet import *

import sys,os,re
import signal
from threading import Thread

test_dir = "test"
test_bin = "./test_base"

def startup():
        print "tc1: Calling startup"

def cleanup():
       	print "tc1: Calling cleanup"

def thread_target(ret, fd):
	ret = fd.read()

def test1():
        print "tc1: Calling test"
	try:
		os.chdir(test_dir)
		if not os.access( test_bin, os.X_OK ):	
			print "Could not access",test_bin
			tet_result(TET_FAIL)
			return
		stdout,stderr = os.popen3(test_bin)[1:]
		print "waiting for data"
		data_l, fail_l = [], []
		t1 = Thread(target=thread_target, args=(data_l, stdout))
		t2 = Thread(target=thread_target, args=(fail_l, stderr))
		t1.start()
		t2.start()
		t1.join()
		t2.join()
		data = data_l
		failings = fail_l
		stdout.close()
		ret = stderr.close()
		if failings:
			print "tc1: tested failed:"
			print failings
			tet_result(TET_FAIL)
			return
		if ret != None :
       			print "tc1: test returned non-zero",ret
			tet_result(TET_FAIL)
		else:
       			print "tc1: test passed"
			tet_result(TET_PASS)
	except Exception, e:
		print "Caught exception",e
		tet_result(TET_FAIL)

testlist = { 1:test1 }
pytet_init(testlist, startup, cleanup)
