Advertisement
kernel_memory_dump

PythonWrapper

Aug 11th, 2014
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.10 KB | None | 0 0
  1. """
  2. This is a  wrapper for all calls to Python objects, it implements a Java Interface,
  3. making it possible to call it's methods
  4.        from Java
  5.    
  6. """
  7.  
  8. __author__ = 'Sebastian Novak sebastian.novak@rt-rk.com'
  9. __version__ = '0.1'
  10.  
  11. from __builtin__ import range
  12. from time import sleep
  13. import tempfile
  14.  
  15. import sys
  16. import os
  17.  
  18.  
  19. from selenium import webdriver
  20. from selenium.webdriver.common.keys import Keys
  21. from httplib import CannotSendRequest
  22. from socket import error as SocketError
  23.  
  24. from selenium.webdriver.chrome.options import Options
  25. from rtrk.miniexecutor.jython.interfaces import IJavaToPython
  26. from rtrk.miniexecutor.applets.exceptions import PyError
  27. from rtrk.miniexecutor.applets.exceptions import SyntaxErrorException
  28. from rtrk.miniexecutor.applets.exceptions import AssertFailedException
  29. from rtrk.miniexecutor.applets.exceptions import BrowserClosedException
  30. from rtrk.miniexecutor.applets.exceptions import TestStoppedException
  31.  
  32. from TestResults import TestResults
  33. import java.util.ArrayList as ArrayList
  34. from AssertFailedError import AssertFailedError
  35.  
  36. from texttable import Texttable
  37.    
  38.  
  39. class PythonWrapper(IJavaToPython):
  40.     """ Wrapper for Java calls to Python """
  41.    
  42.     def __init__(self):
  43.         self.__chrome_driver_path = ""      
  44.        
  45.        
  46.        
  47.         self.__driver = None
  48.         self.__current_browser = None
  49.         self.__errors = None
  50.         self.__stop_test = False
  51.         self.__test_code = None
  52.         self.__test_report = None
  53.         self.__test_result = None
  54.        
  55. ##############################################################################
  56.    
  57.     """ JavaToPython interface methods     """
  58.            
  59.     def setPathToChromeDriver(self, path):
  60.         """
  61.        Will be called by the applet's to set the path to the
  62.        Chrome driver, after extracting the chromedriver.exe
  63.        into the user's temporary directory.
  64.        The path will be used to construct the ChromeDriver.
  65.        """
  66.         self.__chrome_driver_path = path
  67.         print path
  68.                    
  69.  
  70.     def __execute_test(self, statements):
  71.         """  
  72.        Executes the given statements
  73.        on a previously selected browser. <br>
  74.        
  75.        """
  76.  
  77.         driver = self.__driver
  78.         test = self.__test_report
  79.         # counting the line numbers as we go
  80.         # always put the list index of the current stment in i
  81.         # the stment itself will be in stmnt
  82.         for i,stmnt in enumerate(statements):
  83.             print 'for loop entered:' + str(i) + " statement:" + stmnt
  84.             if self.__stop_test:
  85.                 error = TestStoppedException ()
  86.                 raise error
  87.             if stmnt.startswith('test'):
  88.                 test.logStatement(stmnt)            
  89.             try:
  90.                 print 'Attempting to execute statement + ' +  stmnt
  91.                 exec(stmnt)
  92.                 print 'Statement executed! ' + stmnt
  93.             except (SocketError, CannotSendRequest) as e:
  94.                 print "Browser closed during test!!!"
  95.                 browser_closed = BrowserClosedException()
  96.                 browser_closed.setLine(i+1)
  97.                 browser_closed.setControlledBrowser(self.__current_browser)
  98.                 raise browser_closed
  99.                
  100.             except (AssertFailedError) as e:
  101.                 '''
  102.                there were no Syntax exceptions so far
  103.                but an assert has failed, bringing an early end
  104.                to this test case
  105.                '''
  106.                 assert_exp = AssertFailedException()
  107.                 assert_exp.setLineNumber(i+1)
  108.                 raise assert_exp
  109.             except (AttributeError, RuntimeError, TypeError, NameError, SyntaxError) as e:  
  110.                 repr( e )    
  111.                 eStr = str(e)
  112.                 print '\n\n##########\n\n\nHandling run-time error:', eStr
  113.                 if True:
  114.                     print '\n\n### LINE NUM:' + str(i + 1)
  115.                     k =  eStr.find('line ')
  116.                     j =  eStr.find(')')
  117.                     print '\nfound line at:' + str(k)
  118.                     print '\n#line is:' + str(eStr[k + len('line ')])
  119.                     print '\nbracket found at:' + str(j)
  120.                     print '\nactual line is' + eStr[k:j-1]
  121.                     print '\n\n\n####################################'
  122.                     #logging the error
  123.                     error = PyError( i + 1, eStr )
  124.                     self.__errors.append(error)
  125.                     syntax_exp= SyntaxErrorException()
  126.                     syntax_exp.setErrors(self.__get_py_errors())
  127.                     raise syntax_exp
  128.    
  129.     def executeTest(self, test_code, selected_browsers):
  130.         """
  131.        Executes the given test code in the selected browsers.
  132.               If any errors are encountered, an exception
  133.               will be thrown and the errors themselves
  134.                logged in the
  135.               errors[] array , which can be later retrieved by the
  136.               applet by calling getErrors() on the thrown exception
  137.        """
  138.         # preparing the error log
  139.         self.__errors = []
  140.        
  141.         self.__test_report = TestResults(selected_browsers)
  142.         # enabling the user to input the code for
  143.         # the wrapper by
  144.         # typing test.verify or driver.anyMethod
  145.         # instead of self.test or self.driver
  146.         test = self.__test_report
  147.  
  148.         # removing Windows OS caused carriage returns (if any)
  149.         test_code = test_code.replace("\r", "")        
  150.         statements = test_code.split("\n")
  151.         print statements
  152.         print len(statements)
  153.        
  154.         if selected_browsers == IJavaToPython.CHROME:
  155.             self.__get_browser(IJavaToPython.CHROME)
  156.             self.__execute_test(statements)
  157.            
  158.         elif selected_browsers == IJavaToPython.FIREFOX:
  159.             self.__get_browser(IJavaToPython.FIREFOX)
  160.             self.__execute_test(statements)
  161.            
  162.         elif selected_browsers == IJavaToPython.CHROME_AND_FIREFOX:
  163.             self.__get_browser(IJavaToPython.CHROME)
  164.             self.__execute_test(statements)
  165.            
  166.             self.__get_browser(IJavaToPython.FIREFOX)
  167.             self.__execute_test(statements)
  168.  
  169.      
  170.         print "REPORT: " + self.__test_report.get_final_report()
  171.         return self.__test_report.get_final_report()
  172.    
  173.     def getTestResults(self):
  174.         return self.__test_report.get_final_report()
  175.    
  176.     def stopTest(self):
  177.         self.__stop_test = True
  178. ##############################################################################
  179.  
  180.     def __is_browser_open(self):
  181.         if self.__driver != None:
  182.             return True
  183.         else:
  184.             return False
  185.        
  186.     def __close_browser(self):
  187.         if self.__driver != None:
  188.             self.__driver.close()
  189.             self.__driver = None
  190.  
  191.        
  192.     def __get_py_errors(self):
  193.         """
  194.        Constructing a Java ArrayList  
  195.        out of Java objects that were made in Jythin
  196.        http://www.jython.org/jythonbook/en/1.0/DataTypes.html
  197.        @return An ArrayList of PyErrors
  198.        
  199.        """
  200.         list_of_errors = ArrayList()
  201.         # adding all of the PyErrs to the ArrayList
  202.         for py_err in self.__errors:
  203.             list_of_errors.add(py_err)
  204.                    
  205.         return list_of_errors
  206.    
  207.     def __get_browser(self, selected_browser):
  208.         """
  209.        Opens the selected browser by
  210.          instancing the appropriate WebDriver. <br>
  211.        The parth to the chrome driver needs to be set before
  212.        this method is called.
  213.        """
  214.        
  215.        
  216.         if self.driver != None and self.__current_browser == selected_browser:
  217.             print "Browser already present, not opening a new one"
  218.             return
  219.        
  220.        
  221.        
  222.         self.__current_browser = selected_browser
  223.         self.__test_report.set_current_browser(selected_browser)
  224.      
  225.          
  226.         if selected_browser == IJavaToPython.CHROME:
  227.             # https://code.google.com/p/chromedriver/issues/detail?id=799
  228.             # Current issue with the chrome driver
  229.             # by default it starts with the arguments
  230.             # --ignore-certifcate-errors
  231.             # which cause stability issues with the Chrome browser
  232.             # the arguments should be set like this:
  233.             # chrome_options.add_argument("--test-type")
  234.                 chrome_options = Options()
  235.                 chrome_options.add_argument("--test-type")
  236.                 try:
  237.                     self.__driver = webdriver.Chrome(self.chromeDriverPath,chrome_options=chrome_options)
  238.                 except WebDriverException as e:
  239.                     print "unable to get chrome driver"
  240.                     e = sys.exc_info()[0]
  241.  
  242.         elif selected_browser == IJavaToPython.FIREFOX:
  243.                 try:
  244.                     self.__driver = webdriver.Firefox()
  245.                 except WebDriverException as e:
  246.                     print "unable to get firefox driver"
  247.                     e = sys.exc_info()[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement