断言元素不存在的更快方法

软件测试 网络驱动程序 Python
2022-01-18 18:18:45

我测试的目标是断言在某些操作后不会出现弹出窗口。以前为了测试弹出窗口是否存在,我使用了异常处理。

try:

    self.driver.find_element_by_id("fancybox-close").click()

except Exception ('ElementNotVisibleException'):

    print "No popup"

这适用于测试:断言是否存在弹出窗口。

但是一旦我将目标更改为:断言是否弹出不存在

异常处理解决方案变得非常昂贵(异常处理在 python 中需要大量时间),并且将在 3 秒内执行的测试现在需要一分钟。

有没有解决的办法?使用 webdriver python binding 检查元素是否不存在的更快方法?

4个回答

我没有使用过 Python 绑定,但据我所知,它们应该等同于 Java 绑定。

如果我是你,我会尝试在 Java 绑定中找到findElements()和 的 Python 等价物。isDisplayed()

例如,我会做类似的事情:

// ...
myElementList = driver.findElements(By.Id("fancybox-close"))
if (myElementList.isEmpty()) {
    // The element doesn't exist. findElements, in plural, returns a list of the matching elements, or an empty list if no one is found
else {
    // We know it exists, now we need to know if it's displayed (visible) or not
    if (myElementList[0].isDisplayed()) {
        // This means the element is visible
    else {
        // ...
    }

}

希望能帮助到你

测试缓慢不是因为异常处理缓慢,而是因为驱动程序等待未找到的元素。在这种情况下,驱动程序会等待弹出窗口 - 也许它会出现。

尝试使用self.driver.implicitly_wait(0)

如果找不到某些元素,这将告诉驱动程序不要等待。

这是另一个示例,与 Ignacio 中的示例非常相似,但使用 C#:

    //Displayed
    public static bool IsElementDisplayed(this IWebDriver driver, By element)
    {
        if (driver.FindElements(element).Count > 0)
        {
            if (driver.FindElement(element).Displayed)
                return true;
            else
                return false;
        }
        else
        {
            return false;
        }
    }

    //Enabled
    public static bool IsElementEnabled(this IWebDriver driver, By element)
    {
        if (driver.FindElements(element).Count > 0)
        {
            if (driver.FindElement(element).Enabled)
                return true;
            else
                return false;
        }
        else
        {
            return false;
        }
    }

您可以使用多种方式加速它:

  • 隐式等待 这是 tstempko 提到的。然而,隐式等待有一个缺点。这使得驱动程序在设置为“0”时不会等待所有 UI 元素。在您的情况下,这并不理想。有时您可能确实需要等待 UI 元素出现,然后您的测试将无缘无故地中断。
  • 显式等待 您可以仅为此调用设置显式等待。这允许以更稳健的方式等待 UI 元素出现。
  • 对我来说 Javascript 执行器,有一些网络元素太“不可靠”而无法一直检测到。我将使用的是这样的 javascript 执行器:

    String cmd = "$('#header-username').click()";
    ((JavascriptExecutor)driver).executeScript(cmd);
    

    JavaScriptExcutor 的好处是,只要加载了 javascript,就可以执行它。浏览器不需要等待元素被渲染。这样做的缺点是它不能模仿用户的行为。我只使用它来进入我感兴趣的下一个测试区域。

在旁注中,您可能想尝试以这种方式编写代码,而不是您拥有的 try-except 方法:

wait = new WebDriverWait(driver, TIMEOUT);
e = wait.until(ExpectedConditions.visibilityOf(oldPasswordField))
e.click()

不幸的是,我的代码是用 Java 编写的。我认为 Python 等效项中有类似的方法。