import sys
import time
import unittest
import logging
from cStringIO import StringIO
from modules.SeleniumWrapper import SeleniumWrapper
import settings

class BasicExploit(unittest.TestCase):
	result = "FAILURE"
	time_spent = "0.0"
	startup_ok = "SUCCESS"
	Log = StringIO()
	
	attributes = {'Name' :		  '',
				  'Description' : '',
				  'References' :  [['http://does-not-exist']], 
				  'Target' :	  '',
				  'Container': '',
				  'TargetLicense' : '',
				  'Plugin' : '',
				  'VulWikiPage' : "",
				  'Type' : ''
				  }

 
	def get_test_result(self):
		test_result = sys.exc_info()
		if (test_result == (None, None, None)):
			return "SUCCESS"
		else:
			return "FAILURE"
  
	def __del__(self):
		self.Log.truncate(0)

	def runTest(self):
		pass

	def runExploit(self):
		pass

	def exploit(self, logging_level = "INFO"):		 
		self.__class__.LoggingLevel = getattr(logging, logging_level)
		sys.exc_clear()
		try:
			self.wrapper = SeleniumWrapper(settings.browser_visible)	  
			log_format = logging.Formatter("[%(asctime)s]: %(message)s")
			self.stream = logging.StreamHandler(self.Log)
			self.shell = logging.StreamHandler()		  
			self.stream.setFormatter(log_format)
			self.shell.setFormatter(log_format)
			self.logger = logging.getLogger(self.attributes["Name"])
			self.logger.setLevel(self.__class__.LoggingLevel)
			self.logger.addHandler(self.stream)    
			self.logger.addHandler(self.shell)
			self.wrapper.set_logger(self.logger)	  
			self.logger.info("------------------------------------------------------------")
			for key, value in self.attributes.items():
				self.logger.info("%s: %s", key, value)	 
			self.logger.info("------------------------------------------------------------")	  
			self.startTime = time.time()
			self.wrapper.open_browser()
		except Exception as error:
			self.startup_ok = "FAILURE"
			self.logger.debug("ERROR: failed at init!")
			self.logger.debug(error)
			pass   
		try:
			self.logger.debug("STARTUP: %s" % self.startup_ok)
			self.runExploit()
			time_spent = time.time() - self.startTime		
			self.logger.info("------------------------------------------------------------")
			self.result = self.get_test_result()
			self.time_spent = "%.3f" % time_spent	 
		except Exception as error:
			self.logger.debug(error)
			pass
		finally: 
			self.logger.info("RESULT : %s" % self.result)
			self.wrapper.kill_browser()



