#!/usr/bin/python

# Copyright (c) 2005 by Matthias Urlichs <smurf@smurf.noris.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of Version 2 of the GNU General Public License as
# published by the Free Software Foundation. See the file COPYING.txt
# or (on Debian systems) /usr/share/common-licenses/GPL-2 for details.

"""\
This test script grabs a number of interesting key maps from
keymapper.fakemaps, generates a decision tree, saves that in an
in-memory file, and then runs each key map against the file's
interpreter to see if the correct map is returned.
"""

from keymapper.fakemaps import maps
from keymapper.tree import Tree, gen_report
from keymapper.file import FileReporter
from keymapper.graph import GraphReporter
from keymapper.script import Script
from keymapper.fakequery import FakeQuery

import sys

try:
	from cStringIO import StringIO
except ImportError:
	from StringIO import StringIO

keymaps = []
t = Tree()
for k in maps():
	t.add(k)
	keymaps.append(k)
t.gen_tree()

buf = StringIO()
gen_report(t,FileReporter(buf))

g = open("test.dot","w")
gen_report(t,GraphReporter(g))

# 'buf' now contains our script.

buf.seek(0,0)
print buf.read(),

err = 0
for k in keymaps:
	buf.seek(0,0)
	print "Testing keymap %s" % (k.dump(),)
	s = Script(buf,FakeQuery(k))
	name = s.run()
	if name != k.name:
		print "SCRIPT ERROR: %s != %s" % (name,k.name)
		err += 1
	else:
		print "... OK."
	print

if err:
	print "%d errors found!" % err
	sys.exit(1)
else:
	print "Everything works."
	sys.exit(0)

