Esempio n. 1
0
 def autoLogin(cls, fun):
     """
     Description:
         Decorator to check for Appliance Login Status 
     Input:
         cls (Classname): Class name of the called function
         func (Functionmane): Name of the called function
      
     Output:
         Returns function handler
      
     """
     def func_handler(*kwarg, **kwargs):
         try:
             kwarg[0].browserObject = globalVars.browserObject
             userEle = kwarg[0].browserObject.find_element_by_id(
                 "txtUsername")
             if not userEle:
                 loginObject = Login.Login(kwarg[0].browserName,
                                           kwarg[0].applianceIP)
                 globalVars.loginObject = loginObject
                 globalVars.browserObject = loginObject.loginApp(
                     kwarg[0].loginUser, kwarg[0].loginPassword)
                 kwarg[0].browserObject = globalVars.browserObject
                 kwarg[0].succeed("Logged into ASM Appliance IP:%s" %
                                  kwarg[0].applianceIP)
             result = fun(*kwarg, **kwargs)
             return result
         except AssertionError, ae:
             utility.execLog(traceback.format_exc())
             raise ae
         except SkipTest, se:
             utility.execLog(traceback.format_exc())
             raise se
Esempio n. 2
0
 def is_element_present(self, locator, value):
     try:
         self.browserObject.find_element(locator, value)
     except NoSuchElementException:
         utility.execLog("Element not found")
         return False
     return True
Esempio n. 3
0
 def __init__(self, browserObject):
     """
     Description: 
         Initializing an object of Navigation class.
     """
     Controller.__init__(self, browserObject)
     utility.execLog("Initializing Navigation...")
     self.loopCount = 3
     self.menuMap = {
         "Dashboard":
         self.NavigationObjects('Dashboard'),
         "Services":
         self.NavigationObjects('Services'),
         "Templates":
         self.NavigationObjects('Templates'),
         "Resources":
         self.NavigationObjects('Resources'),
         "Settings":
         self.NavigationObjects('Settings'),
         "Getting Started Main":
         self.NavigationObjects('GettingStartedMain'),
         "Quick Actions":
         self.NavigationObjects('QuickActions'),
         "Add-On Modules":
         self.NavigationObjects('AddOnModules'),
         "Backup and Restore":
         self.NavigationObjects('BackupRestore'),
         "Credentials Management":
         self.NavigationObjects('Credentials'),
         "Getting Started":
         self.NavigationObjects('GettingStarted'),
         "Jobs":
         self.NavigationObjects('Jobs'),
         "Logs":
         self.NavigationObjects('Logs'),
         "Networks":
         self.NavigationObjects('Networks'),
         "Repositories":
         self.NavigationObjects('Repositories'),
         "Initial Appliance Setup":
         self.NavigationObjects('InitialApplianceSetup'),
         "Users":
         self.NavigationObjects('Users'),
         "Virtual Appliance Management":
         self.NavigationObjects('VirtualApplianceManagement'),
         "Virtual Identity Pools":
         self.NavigationObjects('VirtualIdentityPools'),
         "Close":
         self.NavigationObjects('Close')
     }
     self.pageElement = {
         "Landing Page": "lnkNetworks",
         "Templates": "viewtemplatelist",
         "Dashboard": "recentActivityViewAll",
         "Resources": "tabSummary",
         "Services": "viewservicelist"
     }
Esempio n. 4
0
 def getSettingsOptions(self):
     """
     Description:
         API to Get Settings Tab Accessibility
     """
     optionList = {}
     settingTabOptions = ("Getting Started", "Logs", "Jobs", "Users",
                          "Networks", "Credentials Management",
                          "Virtual Appliance Management",
                          "Backup and Restore", "Add-On Modules",
                          "Repositories", "Virtual Identity Pools")
     try:
         eleSettings = self.handleEvent(
             EC.element_to_be_clickable(
                 (By.ID, self.NavigationObjects('ExpandSettings'))))
         # Checking if Settings Menu is Expanded or Collapsed
         if "collapsed" in eleSettings.get_attribute("class"):
             utility.execLog(
                 "Settings Menu is Collapsed...Clicking to Expand")
             self.handleEvent(EC.element_to_be_clickable(
                 (By.ID, self.NavigationObjects('ExpandSettings'))),
                              action="CLICK")
         else:
             utility.execLog("Settings Menu is Expanded")
         # Selecting Settings Option once Settings Menu is Expanded
         eleSettingsMenu = self.handleEvent(
             EC.element_to_be_clickable(
                 (By.ID, self.NavigationObjects('SettingsMenu'))))
         if "true" in eleSettingsMenu.get_attribute("aria-expanded"):
             for option in settingTabOptions:
                 utility.execLog("Verifying Settings Menu: %s" % option)
                 try:
                     menuXPATH = self.menuMap[option]
                     eleMenu = self.handleEvent(
                         EC.visibility_of_element_located(
                             (By.XPATH, menuXPATH)))
                     if eleMenu:
                         optionList[option] = "Enabled"
                     else:
                         optionList[option] = "Disabled"
                 except:
                     optionList[option] = "Disabled"
                 utility.execLog("Verified Settings Menu: %s" % option)
             utility.execLog("Settings Tab Options and Status %s" %
                             str(optionList))
             # Collapsing Settings Menu
             self.handleEvent(EC.element_to_be_clickable(
                 (By.ID, self.NavigationObjects('ExpandSettings'))),
                              action="CLICK")
             return self.browserObject, True, optionList
     except Exception as e:
         return self.browserObject, False, "Unable to Load 'Menu' :: Error -> '%s'" % (
             str(e) + format_exc())
Esempio n. 5
0
def loginAppliance(newInstance = True, browserObject = None):
    pageObject = Login.Login(globalVars.browserName, globalVars.applianceIP, newInstance=newInstance, browserObject=browserObject)
    if newInstance and not browserObject:
        globalVars.browserObject, status, result = pageObject.getBrowserHandle()
        if not status:
            utility.execLog("Failed to Login to Appliance..Try Again")
        else:
            utility.execLog(result)
    utility.execLog("globalVars.loginUser= %s and globalVars.loginPassword= %s" % (str(globalVars.loginUser), str(globalVars.loginPassword)))
    globalVars.browserObject, landingPage, status, result = pageObject.loginApp(globalVars.loginUser, globalVars.loginPassword, False)
    if not status:
        utility.execLog("Failed to Login to Appliance..Try Again")
        print "Failed to Login to Appliance..Try Again" 
        globalVars.browserObject.close()
        sys.exit(0)
    else:
        utility.execLog(result)
        return landingPage
Esempio n. 6
0
 def changeMenuToNormalView(self):
     try:
         utility.execLog("Checking Menu View: Pin/Collapsed...")
         pinView = self.handleEvent(
             EC.visibility_of_element_located(
                 (By.ID, self.NavigationObjects('Unpin'))))
         if pinView:
             utility.execLog("Menu: Pin View Active")
             utility.execLog("Changing to Normal/Collapsed View...")
             self.handleEvent(EC.element_to_be_clickable(
                 (By.XPATH, self.NavigationObjects('Unpin'))),
                              action="CLICK")
         else:
             self.handleEvent(EC.element_to_be_clickable(
                 (By.XPATH, self.NavigationObjects('ExpandMenu'))),
                              action="CLICK")
             menuExpanded = self.handleEvent(
                 EC.visibility_of_element_located(
                     (By.XPATH, self.NavigationObjects('MenuBar'))))
             if menuExpanded:
                 utility.execLog("Menu: Normal/Collapsed View Active")
                 self.handleEvent(EC.element_to_be_clickable(
                     (By.XPATH, self.NavigationObjects('ExpandMenu'))),
                                  action="CLICK")
                 return self.browserObject, True, "Menu Already in Normal/Collapsed View"
         # Validating if Normal/Collapsed View is Active
         self.handleEvent(EC.element_to_be_clickable(
             (By.XPATH, self.NavigationObjects('ExpandMenu'))),
                          action="CLICK")
         menuExpanded = self.handleEvent(
             EC.visibility_of_element_located(
                 (By.XPATH, self.NavigationObjects('MenuBar'))))
         if menuExpanded:
             utility.execLog("Menu: Collapsed View Active")
             self.handleEvent(EC.element_to_be_clickable(
                 (By.XPATH, self.NavigationObjects('ExpandMenu'))),
                              action="CLICK")
             return self.browserObject, True, "Menu Changed To Normal/Collapsed View"
         else:
             return self.browserObject, False, "Menu Could not be changed to Normal/Collapsed View"
     except Exception as e:
         return self.browserObject, False, "Exception generated while changing menu to Normal/Collapsed View :: Error -> '%s'" % (
             str(e))
Esempio n. 7
0
 def func_handler(*kwarg, **kwargs):
     try:
         kwarg[0].browserObject = globalVars.browserObject
         userEle = kwarg[0].browserObject.find_element_by_id(
             "txtUsername")
         if not userEle:
             loginObject = Login.Login(kwarg[0].browserName,
                                       kwarg[0].applianceIP)
             globalVars.loginObject = loginObject
             globalVars.browserObject = loginObject.loginApp(
                 kwarg[0].loginUser, kwarg[0].loginPassword)
             kwarg[0].browserObject = globalVars.browserObject
             kwarg[0].succeed("Logged into ASM Appliance IP:%s" %
                              kwarg[0].applianceIP)
         result = fun(*kwarg, **kwargs)
         return result
     except AssertionError, ae:
         utility.execLog(traceback.format_exc())
         raise ae
Esempio n. 8
0
    def getOptionStatus(self, optionName):
        """
        Description:
            API to Get Option Accessibility

        Deprecated starting 8.4.0:
        'Username'
        'GettingStartedMenu'
        'Logout'

        Incomplete
        """
        option = ""
        try:
            utility.execLog("Checking whether Menu is expanded")
            mainMenu = self.browserObject.find_element_by_id("navHover")
            if not mainMenu.find_element_by_id("spanBackdrop").is_displayed():
                utility.execLog("Menu is not expanded, so Clicking on Menu")
                mainMenu.click()
                time.sleep(5)
                utility.execLog("Clicked on Menu")
            utility.execLog("Verifying '%s' Option" % optionName)
            try:
                elementIdentity = self.menuMap[optionName]
                if "//" not in elementIdentity:
                    eleOption = self.browserObject.find_element_by_id(
                        elementIdentity)
                else:
                    eleOption = self.browserObject.find_element_by_id(
                        "navHover").find_element_by_xpath(
                            elementIdentity).click()
                if eleOption.is_displayed():
                    option = "Enabled"
                else:
                    option = "Disabled"
            except:
                option = "Disabled"
            utility.execLog("'%s' Option Status '%s'" % (optionName, option))
            return self.browserObject, True, option
        except Exception as e:
            return self.browserObject, False, "Unable to get Option '%s' Status :: Error -> '%s'" % (
                optionName, str(e) + format_exc())
Esempio n. 9
0
 def getMainOptions(self):
     """
     Description:
         API to Get Main Menu Options Accessibility
     """
     optionList = {}
     mainMenuOptions = ("Dashboard", "Services", "Templates", "Resources",
                        "Settings", "Quick Actions", "Getting Started Main")
     try:
         for key in mainMenuOptions:
             utility.execLog("Verifying Main Menu: %s" % key)
             try:
                 menuXPATH = self.menuMap[key]
                 eleMenu = self.handleEvent(
                     EC.visibility_of_element_located(
                         (By.XPATH, menuXPATH)))
                 if eleMenu:
                     optionList[key] = "Enabled"
                 else:
                     optionList[key] = "Disabled"
             except:
                 optionList[key] = "Disabled"
             utility.execLog("Verified Main Menu: %s" % key)
         utility.execLog("Navigation Options and Status %s" %
                         str(optionList))
         return self.browserObject, True, optionList
     except Exception as e:
         return self.browserObject, False, "Unable to Load 'Menu' :: Error -> '%s'" % (
             str(e) + format_exc())
Esempio n. 10
0
def setUp():
    
    """
    Function for loading browser , and update common variables to globalVars file.
    """
    # Remove Old Logs
    utility.removePreviousLog()
    
    # Create Execution Log and Readme Location
    execLog = os.path.join(globalVars.logsDir, "exec_log")
    statusLog = os.path.join(globalVars.logsDir, "status_log")
    screenshotLog = os.path.join(globalVars.logsDir, "screen_shots")
    if not os.path.exists(execLog):
        os.makedirs(execLog)
    if not os.path.exists(statusLog):
        os.makedirs(statusLog)
    if not os.path.exists(screenshotLog):
        os.makedirs(screenshotLog)
    
    globalVars.configInfo = utility.readConfig(globalVars.configFile)
    globalVars.browserName = globalVars.configInfo["Appliance"]["browser"]
    globalVars.applianceIP = globalVars.configInfo['Appliance']['ip']
    globalVars.loginUser = globalVars.configInfo['Appliance']['username']
    globalVars.loginPassword = globalVars.configInfo['Appliance']['password']
    
    # Login To Appliance
    landingPageID = loginAppliance()

    if landingPageID == 2:
        # Perform Initial Setup
        utility.execLog("PopUp: Initial Setup Wizard")
        # Get Required Values from config.ini
        timeZone = globalVars.configInfo['Appliance']['timezone']
        primaryNTP = globalVars.configInfo['Appliance']['ntpserver']
        secondaryNTP = globalVars.configInfo['Appliance']['secondaryntp']
        serviceTag = globalVars.configInfo['Appliance']['servicetag']
        # Initiate Initial Setup Objects
        isObject = InitialSetup.InitialSetup(globalVars.browserObject)
        # Initial Setup Wizard Setup Started
        globalVars.browserObject, status, result = isObject.processInitialSetup(timeZone, primaryNTP, secondaryNTP, serviceTag)
        if not status:
            utility.execLog("Failed during Initial Setup --> %s" % result)
            print "Failed during Initial Setup"
            utility.execLog("Continuing with Test-Case Execution.")
            # To Fail Execution due to failure of Initial Setup Wizard, uncomment the following LoCs
            # globalVars.browserObject.close()
            # sys.exit(0)
        else:
            utility.execLog(result)
Esempio n. 11
0
 def verifySubMenu(self, menuName):
     try:
         self.browserObject, status, result = self.changeMenuToNormalView()
         if status:
             utility.execLog("Clicking on Menu...")
             self.handleEvent(EC.element_to_be_clickable(
                 (By.XPATH, self.NavigationObjects('ExpandMenu'))),
                              action="CLICK")
             utility.execLog("Verifying Sub-Menu: %s" % str(menuName))
             if self.browserObject.find_element_by_xpath(
                     "//*[contains(text(),'%s')]" %
                     str(menuName)).is_displayed():
                 return self.browserObject, True, "Sub-Menu '%s' is Enabled" % str(
                     menuName)
             else:
                 return self.browserObject, False, "Sub-Menu '%s' is not Enabled" % str(
                     menuName)
         else:
             return self.browserObject, False, "Error while Verifying Sub-Menu '%s'" % str(
                 menuName)
     except Exception as e:
         return self.browserObject, False, "Exception generated while Verifying Sub-Menu %s :: Error -> '%s'" % (
             str(menuName), str(e))
Esempio n. 12
0
 def func_exec(cls, fun):
     """
     Description:
         Decorator to wrap the test_functionality method execution of the 
         test case
          
     Input:
         cls (Classname): Class name of the called function
         func (Functionmane): Name of the called function
      
     Output:
         Returns function handler
      
     """
     def func_handler(*kwarg, **kwargs):
         try:
             fun(*kwarg, **kwargs)
         except AssertionError, ae:
             utility.execLog(traceback.format_exc())
             raise ae
         except SkipTest, se:
             utility.execLog(traceback.format_exc())
             raise se
Esempio n. 13
0
 def waitLoading(self,waitSeconds):
     """
     Wait till Loader is displayed on the page
     INCOMPLETE: Requires update to web-element ID
     """
     countLoop = 0
     loaderSpinnerDisplayed = False
     while countLoop < waitSeconds:
         try:
             loaderSpinnerDisplayed = self.handleEvent(EC.presence_of_element_located((By.ID, 'loader')), action='IS_DISPLAYED')
         except:
             loaderSpinnerDisplayed = False
         if loaderSpinnerDisplayed:
             utility.execLog("Loading Page...Loader spinner is displayed")
             time.sleep(1)
         else:
             utility.execLog("Loading Page Complete")
             break
         countLoop += 1
     if loaderSpinnerDisplayed:
         utility.execLog('Loading Exceeding wait time %s seconds' % waitSeconds)
Esempio n. 14
0
 def selectOption(self, menuOption):
     """
     Description:
         API to Select Menu Option
     """
     try:
         # Settings Menu
         if menuOption in ("Getting Started", "Logs", "Jobs",
                           "Initial Appliance Setup", "Users", "Networks",
                           "Credentials Management",
                           "Virtual Appliance Management",
                           "Backup and Restore", "Add-On Modules",
                           "Repositories", "Virtual Identity Pools"):
             menuID = self.menuMap[menuOption]
             eleSettings = self.handleEvent(
                 EC.element_to_be_clickable(
                     (By.ID, self.NavigationObjects('ExpandSettings'))))
             # Checking if Settings Menu is Expanded or Collapsed
             if "collapsed" in eleSettings.get_attribute("class"):
                 utility.execLog(
                     "Settings Menu is Collapsed...Clicking to Expand")
                 self.handleEvent(EC.element_to_be_clickable(
                     (By.ID, self.NavigationObjects('ExpandSettings'))),
                                  action="CLICK")
             else:
                 utility.execLog("Settings Menu is Expanded")
             # Selecting Settings Option once Settings Menu is Expanded
             eleSettingsMenu = self.handleEvent(
                 EC.element_to_be_clickable(
                     (By.ID, self.NavigationObjects('SettingsMenu'))))
             if "true" in eleSettingsMenu.get_attribute("aria-expanded"):
                 utility.execLog("Selecting Option '%s' under Settings..." %
                                 menuOption)
                 time.sleep(2)
                 self.handleEvent(EC.element_to_be_clickable(
                     (By.XPATH, menuID)),
                                  action="CLICK")
                 utility.execLog("Selected Option: '%s'" % menuOption)
         # Main Menu
         elif menuOption in ("Dashboard", "Services", "Templates",
                             "Resources", "Settings"):
             utility.execLog("Selecting Menu Option '%s'..." % menuOption)
             menuID = self.menuMap[menuOption]
             self.handleEvent(EC.element_to_be_clickable(
                 (By.XPATH, menuID)),
                              action="CLICK")
             utility.execLog("Selected Menu Option '%s'" % menuOption)
         # Invalid Menu
         else:
             utility.execLog("Invalid Menu Option '%s'" % menuOption)
             return self.browserObject, False, "Invalid Menu Option '%s'" % menuOption
         return self.browserObject, True, "Able to Load '%s' Page" % menuOption
     except Exception as e:
         return self.browserObject, False, "Unable to Load '%s' Page :: Error -> '%s'" % (
             menuOption, str(e))
Esempio n. 15
0
 def connectSSH(self, hostType, HOST, COMMAND, userName=None, password=None, timeout=120):
     """
     Executes command on provided HOST by connecting through SSH  
     """
     connObj = None
     try:
         if (hostType == 'ToR'):
             USERNAME = "******"
             PASSWORD = "******"
         elif(hostType == 'Brocade'):
             USERNAME = "******"
             PASSWORD = "******"
         elif (hostType == 'Switch'):
             USERNAME = "******"
             PASSWORD = "******"
         else:
             USERNAME = userName
             PASSWORD = password
         if (USERNAME != "" and PASSWORD != "" and HOST != "" and COMMAND != ""):
             utility.execLog("Attempting to connect to Host '%s' using Username '%s' and Password '%s' and execute command(s) '%s'" % (HOST, USERNAME, PASSWORD, str(COMMAND)))
             connObj = SSHConnection(HOST, USERNAME, PASSWORD, 22, timeout)
             connection_result, connection_error = connObj.Connect()                
             if connection_error != "":
                 return False, connection_error
             utility.execLog("Able to connect to Host :: %s" % str(connection_result))
             utility.execLog("Executing Command(s) '%s'" % str(COMMAND))
             if type(COMMAND) is list:
                 res, err = connObj.Execute_Multiple_Commands(COMMAND)
                 utility.execLog("Execution Status :: Result '%s', Error '%s'" % (res, err))
                 if err != "":
                     return False, err
                 else:
                     return True, res 
             else:        
                 res, err = connObj.Execute(COMMAND)
                 utility.execLog("Execution Status :: Result '%s', Error '%s'" % (res, err))
                 if err != "":
                     return False, err
                 else:
                     return True, res
         else:
             return False, "One of the attributes missing HOST/USERNAME/PASSWORD//COMMAND ('%s', '%s', '%s', '%s')" % (HOST, USERNAME, PASSWORD, COMMAND)
     except Exception as e:
         return False, "Exception while executing command :: Error -> %s" % (str(e) + format_exc())
     finally:
         if connObj:
             close_res, close_err = connObj.Close()
             utility.execLog("Connection Closing Status :: Result '%s', Error '%s'" % (close_res, close_err))
Esempio n. 16
0
class TestBase(DellTestCase):
    """
    Description:
        Test class to be used as base class for the automation framework. This 
        class is derived from "unittest.TestCase" class.
    
    """
    def __init__(self, *args, **kwargs):
        """
        Description: 
            Initializing an object of this class. 
            passExpectation (Boolean): Indicating expectancy whether the testcase
                is expected to pass(True) or Fail(False)
            resultCode (String): Indicating whether the test case passed, failed,
                omitted, blocked or error
            stepCount (Int): Counter to keep track of the number of steps that
                has been performed by the test case
                
        Input:
            args (Tuple): Variable number of arguments passed as tuple
            kwargs (Dict): Variable number of arguments passed as key-value
                pair
                
        Output:
            None
        
        """
        # Initializing derived classes
        DellTestCase.__init__(self, "test_functionality")
        self.tcID = args[0]
        self.iteration = utility.iteration
        self._step_results = []
        self.logDesc(args[0])
        self.msg = []
        self.finalStatus = SUCCESS
        self.FAILED = False
        self.passExpectation = True
        self.applianceIP = globalVars.configInfo['Appliance']['ip']
        self.loginUser = globalVars.configInfo['Appliance']['username']
        self.loginPassword = globalVars.configInfo['Appliance']['password']
        #self.delResource = globalVars.configInfo['Appliance']['del_resource']
        self.browserName = globalVars.configInfo['Appliance']['browser']
        self.browserObject = globalVars.browserObject

        self._testMethodDoc = "@testcase: %s\n%s" % (self.tcID,
                                                     self.__doc__.strip())

        execLogLoc = os.path.join(utility.logsdir, "exec_log")
        self.xmlString = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"""
        self.executionTime = {}
        self.serverGroup = []
        self.runInventoryList = {}

        while True:
            if utility.getFileLists(location=execLogLoc,
                                    recursion=True,
                                    filePatt="%s_%s_log.txt" %
                                    (self.tcID, self.iteration))[1]:
                self.iteration += 1
            else:
                break

        # Setting global tcID and iteration
        utility.set_tc_id(self.tcID)
        utility.set_Iteration(self.iteration)

        disc_param["Appliance IP"] = self.applianceIP
        disc_param["Browser Name"] = globalVars.browserName
        if self.browserObject:
            disc_param["Browser Version"] = self.browserObject.capabilities[
                "version"]

        # Setting Runtime data
        for k, v in disc_param.items():
            self.add_runtime_data(k, v)

    def setUp(self):
        """
        Add Log URLs
                
        """
        # Setting global tcID and iteration
        utility.set_tc_id(self.tcID)
        utility.set_Iteration(self.iteration)

        # Building execFile location
        execFile = "%s_%s_log.txt" % (utility.tc_id, utility.iteration)
        execFile = os.path.join("exec_log", execFile)

        # Building StatusFile location
        statusFile = "%s_%s_log.html" % (utility.tc_id, utility.iteration)
        statusFile = os.path.join("status_log", statusFile)

        # Create respective URLs
        execURL = execFile.replace("\\", "/")
        stepsURL = statusFile.replace("\\", "/")

        # Adding the log URLs
        self.add_test_url("Execution log", execURL)
        self.add_test_url("Steps", stepsURL)

    def tearDown(self):
        """
        
        """
        # Generate Status file
        statusFile = os.path.join(utility.logsdir, "status_log", "%s_%s_log.html" % \
                                 (self.tcID, self.iteration))
        with open(statusFile, "w") as fptr:
            fptr.write("<html>\n<head />\n")
            fptr.write("<body>\n")
            fptr.write("<table width='100%' border='1'>\n")
            fptr.write(STATUS_HTML_HEADER_TMPL)
            counter = 1
            for elems in self._step_results:
                if elems["name"].lower() == "logheader":
                    fptr.write(STATUS_HTML_DESC_TMPL %
                               (COLOR["DESC"], elems["description"]))
                    continue
                fptr.write(STATUS_HTML_TMPL %
                           (COLOR.get(elems["result"].upper()), counter,
                            elems["name"], elems["description"],
                            elems["result"].upper()))
                counter += 1

            # Writing Final Status of the test case
            color = COLOR[STATUS[self.finalStatus]]
            if self.finalStatus == SUCCESS:
                color = "#ccff99"
                self.msg.append("No Failures")
            fptr.write(
                FINAL_STATUS_HTML_TMPL %
                (color, "<br />".join(self.msg), STATUS[self.finalStatus]))
            fptr.write("<a href='javascript:window.close()'>Close</a>\n")
            fptr.write("</body></html>")

    def failure(self, msg, nature="", resultCode=FAILURE, raiseExc=False):
        """
        Description:
            Overriding the unittest.TestCase.fail method to capture the failure 
            status(fail, omitted, blocked etc) messages in the HTML format on 
            the fly.
            
        Input:
            nature (String): Type of operation being performed like pre-run setup,
                validation, post-run cleanup etc.
            msg (String): Status message
            resultCode (Int): Result of the operation like fail, blocked etc 
                taken from global variables defined here like FAIELD, BLOCKED, 
                OMITTED etc.
                
        Output:
            None
        
        """
        self.finalStatus = min(self.finalStatus, resultCode)
        resultCode = STATUS[resultCode]
        self.add_step_result(nature, msg, resultCode)

        self.FAILED = True
        self.msg.append(msg)

        if resultCode.__contains__("OMIT"):
            if raiseExc:
                self.omit(msg)
        elif resultCode.__contains__("BLOCK"):
            if raiseExc:
                self.block(msg)
        else:
            if raiseExc:
                if self.browserObject:
                    try:
                        screenShot = "%s_%s_screenshot.png" % (self.tcID,
                                                               self.iteration)
                        screenShot = os.path.join("screen_shots", screenShot)
                        self.screenshotpath = os.path.join(
                            utility.logsdir, screenShot)
                        self.browserObject.get_screenshot_as_file(
                            self.screenshotpath)
                        srcShotURL = screenShot.replace("\\", "/")
                        self.add_test_url("screenshot", srcShotURL)
                    except Exception as e:
                        self.add_step_result(
                            "",
                            "Web Driver Exception while capturing Screenshot :: Error -> %s"
                            % str(e), resultCode)
                self.fail(msg)

    def succeed(self, msg="", nature="", resultCode=SUCCESS):
        """
        Description:
            Method to capture the success status(pass) messages in the HTML 
            format on the fly.
            
        Input:
            nature (String): Type of operation being performed like pre-run setup,
                validation, post-run cleanup etc.
            msg (String): Status message
            resultCode (Int): Result of the successful operation like pass
                taken from global variables defined here SUCCESS.
                
        Output:
            None
        
        """
        resultCode = STATUS[resultCode]
        self.add_step_result(nature, msg, resultCode)
#        if tblib:
#            tblib.tbstatus.send_message(" --> ".join([self.tcID, nature, msg,
#                                                      resultCode]))

    def failOnExpectation(self,
                          nature="",
                          msg="",
                          resultCode=FAILURE,
                          raiseExc=False):
        """
        Description:
            Method to capture the status(fail, omitted, blocked etc) messages 
            in the HTML format on the fly in case the test case is expected to 
            have failed. In such cases, failed operations are treated as success
            and successful operations are treated as failure.  
            
        Input:
            nature (String): Type of operation being performed like pre-run setup,
                validation, post-run cleanup etc.
            msg (String): Status message
            resultCode (Int): Result of the operation like fail, blocked etc 
                taken from global variables defined here like FAIELD, BLOCKED, 
                OMITTED etc.
                
        Output:
            None
        
        """
        if self.passExpectation:
            self.failure(nature, msg, resultCode, raiseExc)
        else:
            self.succeed(nature, msg)

    def succeedOnExpectation(self,
                             nature="",
                             msg="",
                             resultCode=FAILURE,
                             raiseExc=False):
        """
        Description:
            Method to capture the status(fail, omitted, blocked etc) messages 
            in the HTML format on the fly in case the test case is expected to 
            have failed. Ideally, same as succeed method.
            
        Input:
            nature (String): Type of operation being performed like pre-run setup,
                validation, post-run cleanup etc.
            msg (String): Status message
            resultCode (Int): Result of the operation like fail, blocked etc 
                taken from global variables defined here like FAIELD, BLOCKED, 
                OMITTED etc.
                
        Output:
            None
        
        """
        if self.passExpectation:
            self.succeed(nature, msg)
        else:
            self.failure(nature, msg, resultCode, raiseExc)

    def logDesc(self, description=""):
        """
        Description:
            Special formatting of the status html messages which indicates the 
            nature of operation being performed in the test case.
            
        Input:
            description (String): Header Message
            color (String): HTML hexadecmimal color codes
            
        Output:
            None
        
        """
        description = description.strip()
        if description:
            self.add_step_result("logheader", description, "")

    def getChoice(self, oldVal, validVal):
        """
        Description:
            Return a random element from validVal list which is not same as 
            the oldVal element.
        
        Input:
            validval (List): A sequence of values from which the new element 
                will be picked in random.
            oldVal (type of element in the list): The value from the 
                sequence which cannot be picked again
        
        Output:
            newVal (type of element in the list): The randomly picked value 
                from the sequence which is not same as the oldVal
        
        """
        newVal = random.choice(validVal)
        if oldVal == newVal:
            newVal = self.getChoice(oldVal, validVal)

        return newVal

    def generateValue(self, old, minVal=1, maxVal=99):
        """
        Description:
            Returns a random number within the given range defined by minVal 
            and maxVal as string which is not same as the value of old
            
        Input:
            old (String): The number in the range which cannot be picked again 
            minVal (Int): Minimum threshold of the range
            maxVal (Int): Maximum threshold of the range
        
        Output:
            newVal (String): The randomly picked value from the range which is
                not same as the old
        
        """
        old = int(old)
        newVal = random.randint(minVal, maxVal)
        if newVal == old:
            newVal = self.generateValue(old)

        return str(newVal)

    @classmethod
    def func_exec(cls, fun):
        """
        Description:
            Decorator to wrap the test_functionality method execution of the 
            test case
             
        Input:
            cls (Classname): Class name of the called function
            func (Functionmane): Name of the called function
         
        Output:
            Returns function handler
         
        """
        def func_handler(*kwarg, **kwargs):
            try:
                fun(*kwarg, **kwargs)
            except AssertionError, ae:
                utility.execLog(traceback.format_exc())
                raise ae
            except SkipTest, se:
                utility.execLog(traceback.format_exc())
                raise se
            except Exception, e:
                utility.execLog(traceback.format_exc())
                #kwarg[0].finalStatus = min(kwarg[0].finalStatus, ERROR)
                #kwarg[0].msg.append(e.__repr__())
                raise e
Esempio n. 17
0
 def func_handler(*kwarg, **kwargs):
     try:
         fun(*kwarg, **kwargs)
     except AssertionError, ae:
         utility.execLog(traceback.format_exc())
         raise ae
Esempio n. 18
0
 def handleEvent(self, reference, action=None, setValue="", setIndex=0, attributeName="", retry=True, retryCount=1, selectBy="VISIBLE_TEXT", returnContent=None, wait_time=TIME, freq=FREQUENCY):
     """
     Perform Action
     """
     wait = WebDriverWait(self.browserObject, wait_time, freq)
     try:
         if retryCount > 1:
             utility.execLog("Spinner Blocked Clicking on Element...Retry Count : %s" % str(retryCount))
         element = wait.until(reference)
         retnValue = element
         if action == "CLEAR":
             element.clear()
         elif action == "SET_TEXT":
             setValue=str(setValue)
             element.send_keys(setValue.decode("utf-8"))
         elif action == "KEY":
             element.send_keys(setValue)
         elif action == "GET_TEXT":
             try:
                 retnValue = str(element.text)
             except:
                 retnValue = str(element.text.encode('ascii', 'ignore'))
         elif action == "GET_ATTRIBUTE_VALUE":
             retnValue = str(element.get_attribute(attributeName))
         elif action == "CLICK":
             element.click()
         elif action == "SELECT":
             if selectBy == "VISIBLE_TEXT":
                 Select(element).select_by_visible_text(setValue)
             elif selectBy == "VALUE":
                 Select(element).select_by_value(setValue)
             elif selectBy == "INDEX":
                 Select(element).select_by_index(setIndex)
             else:
                 retnValue = Select(element).first_selected_option.text
         elif action == "IS_DISPLAYED":
             retnValue = element.is_displayed()
         elif action == "IS_ENABLED":
             retnValue = element.is_enabled()
         elif action == "IS_SELECTED":
             retnValue = element.is_selected()
         elif action == "GET_ELEMENTS_BY_TAG":
             if returnContent:
                 if returnContent == "TEXT":
                     retnValue = []
                     time.sleep(1)
                     elems = element.find_elements_by_tag_name(setValue)
                     for ele in elems:
                         retnValue.append(str(ele.text)) 
                 else:
                     retnValue = element.find_elements_by_tag_name(setValue)
             else:
                 retnValue = element.find_elements_by_tag_name(setValue)
         elif action in ("GET_ELEMENTS_BY_CLASS", "GET_ELEMENTS_BY_XPATH"):
             retnValue = element
         if retryCount > 1:
             utility.execLog("Event Handle was Successful on Retry Count : %s" % str(retryCount))
         return retnValue
     except AssertionError as ae:
         class_names = ["fade loading", "loader-background", "stale element", "fade in loading"]
         for class_name in class_names:
             if class_name in str(ae):
                 wait.until(EC.invisibility_of_element_located((By.XPATH, ".//*[contains(@class, '{}')]".format(class_name))))
                 if retryCount <= 3 and retry:
                     utility.execLog("Spinner Blocked Clicking on Element...Retrying")
                     retryCount += 1
                     return self.handleEvent(reference, action, setValue, attributeName=attributeName, retry=retry, retryCount=retryCount, selectBy=selectBy)
                 else:
                     utility.execLog("Spinner Blocked Clicking on Element...Maximum Retries Exceeded!")
                     utility.execLog("Exception :: %s" % str(ae) + format_exc())
                     raise ae
             else:
                 continue
         utility.execLog("Exception :: %s" % str(ae) + format_exc())
         raise ae
     except WebDriverException as we:
         class_names = ["fade loading", "loader-background", "stale element", "fade in loading"]
         for class_name in class_names:
             if class_name in str(we):
                 wait.until(EC.invisibility_of_element_located((By.XPATH, ".//*[contains(@class, '{}')]".format(class_name))))
                 if retryCount <= 3 and retry:
                     utility.execLog("Spinner Blocked Clicking on Element...Retrying")
                     retryCount += 1
                     return self.handleEvent(reference, action, setValue, attributeName=attributeName, retry=retry, retryCount=retryCount, selectBy=selectBy)
                 else:
                     utility.execLog("Spinner Blocked Clicking on Element...Maximum Retries Exceeded!")
                     utility.execLog("Exception :: %s" % str(we) + format_exc())
                     raise we
             else:
                 continue
         utility.execLog("Exception :: %s" % str(we) + format_exc())
         raise we
     except Exception as ee:
         class_names = ["fade loading", "loader-background", "stale element", "fade in loading"]
         for class_name in class_names:
             if class_name in str(ee):
                 wait.until(EC.invisibility_of_element_located((By.XPATH, ".//*[contains(@class, '{}')]".format(class_name))))
                 if retryCount <= 3 and retry:
                     utility.execLog("Spinner Blocked Clicking on Element...Retrying")
                     retryCount += 1
                     return self.handleEvent(reference, action, setValue, attributeName=attributeName, retry=retry, retryCount=retryCount, selectBy=selectBy)
                 else:
                     utility.execLog("Spinner Blocked Clicking on Element...Maximum Retries Exceeded!")
                     utility.execLog("Exception :: %s" % str(ee) + format_exc())
                     raise ee
             else:
                 continue
         if 'alert-danger' in str(reference.locator):
             utility.execLog("No Error Message was found, locator used: {}".format(reference.locator))
             raise ee
         utility.execLog("Failed to perform Action or Couldn't locate the {}".format(reference.locator))
         utility.execLog("Exception :: %s" % str(ee) + format_exc())
         raise ee
Esempio n. 19
0
         
        """
        def func_handler(*kwarg, **kwargs):
            try:
                kwarg[0].browserObject = globalVars.browserObject
                userEle = kwarg[0].browserObject.find_element_by_id(
                    "txtUsername")
                if not userEle:
                    loginObject = Login.Login(kwarg[0].browserName,
                                              kwarg[0].applianceIP)
                    globalVars.loginObject = loginObject
                    globalVars.browserObject = loginObject.loginApp(
                        kwarg[0].loginUser, kwarg[0].loginPassword)
                    kwarg[0].browserObject = globalVars.browserObject
                    kwarg[0].succeed("Logged into ASM Appliance IP:%s" %
                                     kwarg[0].applianceIP)
                result = fun(*kwarg, **kwargs)
                return result
            except AssertionError, ae:
                utility.execLog(traceback.format_exc())
                raise ae
            except SkipTest, se:
                utility.execLog(traceback.format_exc())
                raise se
            except Exception, e:
                utility.execLog(traceback.format_exc())
                raise
            return fun

        return func_handler