"""
super class of all web interface unittests for the cryptobox

just inherit this class and add some test functions
"""

import unittest
import twill
import cherrypy 
import cryptobox.web.dataset

## we do the following, for easy surfing
## e.g. use: cbx.go(your_url)
## commands api: http://twill.idyll.org/commands.html
CBXHOST="localhost"
CBXPORT=8081
CBX_URL="http://%s:%d/" % (CBXHOST, CBXPORT)
LOG_FILE="/tmp/twill.log"

class WebInterfaceTestClass(unittest.TestCase):
	'''this class checks the webserver, using "twill"

	the tests in this class are from the browsers point of view, so not
	really unittests.
	fetch twill from: http://twill.idyll.org
	one way to manually run twill code is through the python
	interpreter commandline e.g.:

	import twill
	twill.shell.main()
	go http://localhost:8080
	find "my very special html content"
	help
	'''

	def setUp(self):
		'''configures the cherrypy server that it works nice with twill
		'''
		cherrypy.config.update({ 
					'server.logToScreen' : False,
					'autoreload.on': False,
					'server.threadPool': 1,
					'server.environment': 'production',
					})
		cherrypy.root = cryptobox.web.dataset.WebInterfaceSites()
		cherrypy.server.start(initOnly=True, serverClass=None)

		from cherrypy._cpwsgi import wsgiApp 
		twill.add_wsgi_intercept(CBXHOST, CBXPORT, lambda: wsgiApp) 

		# grab the output of twill commands
		self.output = open(LOG_FILE,"a")
		twill.set_output(self.output)
		self.cmd = twill.commands
		self.URL = CBX_URL
		self.cbox = cherrypy.root.cbox
		self.globals, self.locals = twill.namespaces.get_twill_glocals()


	def tearDown(self):
		'''clean up the room when leaving'''
		# remove intercept.
		twill.remove_wsgi_intercept(CBXHOST, CBXPORT)
		# shut down the cherrypy server.
		cherrypy.server.stop()
		self.output.close()


	def __get_soup():
		browser = twill.commands.get_browser()
		soup = BeautifulSoup(browser.get_html())
		return soup


	def register_auth(self, url, user="admin", password="admin"):
		self.cmd.add_auth("CryptoBox", url, user, password)

