user911625
user911625

Reputation:

Selenium Python - locators error on missing element but I want them to fail

For example:

el = self.browser.find_element_by_css_selector('.test')
self.assertTrue(el.text, "No text in Element")

If the element with class .test is not on the page this errors at the first line. But as far as I am concerned that should be reported as a test failure not a test error. (If the element isn't on the page I want this to show as a test failure - just like it is there but has no text).

How can I achieve this.

I am completely new to Python. I thought the with statement might help but I if I try something like:

with self.browser.find_element_by_css_selector('.test') as el
    #do test

This fails because the find_element_by_css_selector does not appear to have the __enter__ and __exit__ methods required.

Should I just use a try... catch statement? If so can I manually raise a test failure in the catch block?

Upvotes: 3

Views: 870

Answers (1)

alecxe
alecxe

Reputation: 473873

You can take the EAFP approach here and catch NoSuchElementException:

from selenium.common.exceptions import NoSuchElementException

try:
    el = self.browser.find_element_by_css_selector('.test')
except NoSuchElementException:
    self.fail("No such element found")

To follow the DRY principle, you can wrap it into a method and reuse:

def find_element(self, by, value):
    try:
        return self.browser.find_element(by=by, value=value)
    except NoSuchElementException:
        self.fail("No element found using '%s' locator, value: '%s'" % (by, value))

Usage:

el = self.find_element(by=By.CSS_SELECTOR, value=".test")

Or, you can "look before you leap":

elements = self.browser.find_elements_by_css_selector('.test')
self.assertEqual(len(elements), 1)

self.assertTrue(elements[0].text, "No text in Element")

Upvotes: 3

Related Questions