Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- This is a wrapper for all calls to Python objects, it implements a Java Interface,
- making it possible to call it's methods
- from Java
- """
- __author__ = 'Sebastian Novak sebastian.novak@rt-rk.com'
- __version__ = '0.1'
- from __builtin__ import range
- from time import sleep
- import tempfile
- import sys
- import os
- from selenium import webdriver
- from selenium.webdriver.common.keys import Keys
- from httplib import CannotSendRequest
- from socket import error as SocketError
- from selenium.webdriver.chrome.options import Options
- from rtrk.miniexecutor.jython.interfaces import IJavaToPython
- from rtrk.miniexecutor.applets.exceptions import PyError
- from rtrk.miniexecutor.applets.exceptions import SyntaxErrorException
- from rtrk.miniexecutor.applets.exceptions import AssertFailedException
- from rtrk.miniexecutor.applets.exceptions import BrowserClosedException
- from rtrk.miniexecutor.applets.exceptions import TestStoppedException
- from TestResults import TestResults
- import java.util.ArrayList as ArrayList
- from AssertFailedError import AssertFailedError
- from texttable import Texttable
- class PythonWrapper(IJavaToPython):
- """ Wrapper for Java calls to Python """
- def __init__(self):
- self.__chrome_driver_path = ""
- self.__driver = None
- self.__current_browser = None
- self.__errors = None
- self.__stop_test = False
- self.__test_code = None
- self.__test_report = None
- self.__test_result = None
- ##############################################################################
- """ JavaToPython interface methods """
- def setPathToChromeDriver(self, path):
- """
- Will be called by the applet's to set the path to the
- Chrome driver, after extracting the chromedriver.exe
- into the user's temporary directory.
- The path will be used to construct the ChromeDriver.
- """
- self.__chrome_driver_path = path
- print path
- def __execute_test(self, statements):
- """
- Executes the given statements
- on a previously selected browser. <br>
- """
- driver = self.__driver
- test = self.__test_report
- # counting the line numbers as we go
- # always put the list index of the current stment in i
- # the stment itself will be in stmnt
- for i,stmnt in enumerate(statements):
- print 'for loop entered:' + str(i) + " statement:" + stmnt
- if self.__stop_test:
- error = TestStoppedException ()
- raise error
- if stmnt.startswith('test'):
- test.logStatement(stmnt)
- try:
- print 'Attempting to execute statement + ' + stmnt
- exec(stmnt)
- print 'Statement executed! ' + stmnt
- except (SocketError, CannotSendRequest) as e:
- print "Browser closed during test!!!"
- browser_closed = BrowserClosedException()
- browser_closed.setLine(i+1)
- browser_closed.setControlledBrowser(self.__current_browser)
- raise browser_closed
- except (AssertFailedError) as e:
- '''
- there were no Syntax exceptions so far
- but an assert has failed, bringing an early end
- to this test case
- '''
- assert_exp = AssertFailedException()
- assert_exp.setLineNumber(i+1)
- raise assert_exp
- except (AttributeError, RuntimeError, TypeError, NameError, SyntaxError) as e:
- repr( e )
- eStr = str(e)
- print '\n\n##########\n\n\nHandling run-time error:', eStr
- if True:
- print '\n\n### LINE NUM:' + str(i + 1)
- k = eStr.find('line ')
- j = eStr.find(')')
- print '\nfound line at:' + str(k)
- print '\n#line is:' + str(eStr[k + len('line ')])
- print '\nbracket found at:' + str(j)
- print '\nactual line is' + eStr[k:j-1]
- print '\n\n\n####################################'
- #logging the error
- error = PyError( i + 1, eStr )
- self.__errors.append(error)
- syntax_exp= SyntaxErrorException()
- syntax_exp.setErrors(self.__get_py_errors())
- raise syntax_exp
- def executeTest(self, test_code, selected_browsers):
- """
- Executes the given test code in the selected browsers.
- If any errors are encountered, an exception
- will be thrown and the errors themselves
- logged in the
- errors[] array , which can be later retrieved by the
- applet by calling getErrors() on the thrown exception
- """
- # preparing the error log
- self.__errors = []
- self.__test_report = TestResults(selected_browsers)
- # enabling the user to input the code for
- # the wrapper by
- # typing test.verify or driver.anyMethod
- # instead of self.test or self.driver
- test = self.__test_report
- # removing Windows OS caused carriage returns (if any)
- test_code = test_code.replace("\r", "")
- statements = test_code.split("\n")
- print statements
- print len(statements)
- if selected_browsers == IJavaToPython.CHROME:
- self.__get_browser(IJavaToPython.CHROME)
- self.__execute_test(statements)
- elif selected_browsers == IJavaToPython.FIREFOX:
- self.__get_browser(IJavaToPython.FIREFOX)
- self.__execute_test(statements)
- elif selected_browsers == IJavaToPython.CHROME_AND_FIREFOX:
- self.__get_browser(IJavaToPython.CHROME)
- self.__execute_test(statements)
- self.__get_browser(IJavaToPython.FIREFOX)
- self.__execute_test(statements)
- print "REPORT: " + self.__test_report.get_final_report()
- return self.__test_report.get_final_report()
- def getTestResults(self):
- return self.__test_report.get_final_report()
- def stopTest(self):
- self.__stop_test = True
- ##############################################################################
- def __is_browser_open(self):
- if self.__driver != None:
- return True
- else:
- return False
- def __close_browser(self):
- if self.__driver != None:
- self.__driver.close()
- self.__driver = None
- def __get_py_errors(self):
- """
- Constructing a Java ArrayList
- out of Java objects that were made in Jythin
- http://www.jython.org/jythonbook/en/1.0/DataTypes.html
- @return An ArrayList of PyErrors
- """
- list_of_errors = ArrayList()
- # adding all of the PyErrs to the ArrayList
- for py_err in self.__errors:
- list_of_errors.add(py_err)
- return list_of_errors
- def __get_browser(self, selected_browser):
- """
- Opens the selected browser by
- instancing the appropriate WebDriver. <br>
- The parth to the chrome driver needs to be set before
- this method is called.
- """
- if self.driver != None and self.__current_browser == selected_browser:
- print "Browser already present, not opening a new one"
- return
- self.__current_browser = selected_browser
- self.__test_report.set_current_browser(selected_browser)
- if selected_browser == IJavaToPython.CHROME:
- # https://code.google.com/p/chromedriver/issues/detail?id=799
- # Current issue with the chrome driver
- # by default it starts with the arguments
- # --ignore-certifcate-errors
- # which cause stability issues with the Chrome browser
- # the arguments should be set like this:
- # chrome_options.add_argument("--test-type")
- chrome_options = Options()
- chrome_options.add_argument("--test-type")
- try:
- self.__driver = webdriver.Chrome(self.chromeDriverPath,chrome_options=chrome_options)
- except WebDriverException as e:
- print "unable to get chrome driver"
- e = sys.exc_info()[0]
- elif selected_browser == IJavaToPython.FIREFOX:
- try:
- self.__driver = webdriver.Firefox()
- except WebDriverException as e:
- print "unable to get firefox driver"
- e = sys.exc_info()[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement