Chris Lovell
Chris Lovell

Reputation: 23

Fragile Test in Selenium with Python

I am working on learning python and selenium for some QA automation tasks. I am working on the navigation portion of my framework, and I have a test that is very inconsistent. With no changes to the test or site it sometimes passes and sometimes fails. It looks like it is failing to perform the Hover action, and then throws an exception when it can't find the submenu link.

Goto Function:

    def goto(driver, section, subsection):
        if subsection != "None":
            hover_over = driver.find_element_by_link_text(section)
            hover = selenium.webdriver.ActionChains(driver).move_to_element(hover_over)
            hover.perform()
            driver.find_element_by_link_text(subsection).click()
        else:
            driver.find_element_by_link_text(section).click()

Basically the section variable is the first menu item which needs to be hovered over to open the submenu. The subsection variable is the text of the submenu link to be clicked on.

The only reason I could think of for it being so fragile is poor site response times, but doesn't Selenium wait for previous actions to finish before moving on to the next one?

Upvotes: 1

Views: 155

Answers (1)

alecxe
alecxe

Reputation: 473833

Yeah, this sounds like a timing issue.

Let's make it more reliable by adding an explicit wait before clicking the submenu:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def goto(driver, section, subsection):
    if subsection != "None":
        hover_over = driver.find_element_by_link_text(section)
        hover = selenium.webdriver.ActionChains(driver).move_to_element(hover_over)
        hover.perform()

        # IMPROVEMENT HERE
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, subsection))).click()
    else:
        driver.find_element_by_link_text(section).click()

Upvotes: 1

Related Questions