#!/usr/bin/env python
import sys, os
lineno = 0
	
def test_lines(lines, expected_outs=None):
        global lineno
	last_out = ""
	start_index = 0
	for index in range(len(lines)):
		if lines[index][:3] == "***":
			start_index = index+1

	for index in range(len(lines)):
	        lineno = lineno + 1
		line = lines[index]
		if line[:3] == "***": continue

		if line[0] == ">":
			print line, line[1:-1]
			# line[1:-1] better not evaluate to a defined
			# variable in this program.
			try: test = repr(eval(line[1:-1]))
			except: test = line[1:-1]
			if test != last_out:
				print "Error, wrong answer."
				print '*** Test line', lineno,'failed'
				form = \
"""
%s
 doesn't match expected 
%s
""" 
				raise ValueError, form % (last_out, line[1:-1])
			continue

		try:
			try:
				out = eval(line)
			except(ValueError, IndexError, TypeError, ZeroDivisionError):
				out = "%s: %s" % (sys.exc_type, sys.exc_value)
				print out
			
			if out == None:
				exec(line)
			else:
				if type(out) != type(""):
					out = repr(out)
				else:
					try: out = repr(eval(out))
					except: pass
				print out
				last_out = out
				if index > start_index:
					print last_out

		except(SyntaxError):
			exec(line)

# designed to be run either from this directory or ..
print 'Starting Testing Suite'
test_log='testlog.txt'
fout = open(test_log, 'w')
sys.stdout = fout
test_file = 'test_items'
try:
    fp = open(test_file)
except IOError:
    os.chdir('Test')
    fp = open(test_file)
test_lines(fp.readlines())
fp.close()
sys.stderr.write('Starting puttest\n')
execfile('puttest.py')
print "*"*10+" Test Completed Successfully! "+"*"*10
fout.close()
sys.stderr.write("*"*10+" Test Completed Successfully! "+"*"*10+'\n')
sys.stderr.write('Log file written: ')
sys.stderr.write(test_log)
sys.stderr.write('\n')


