Skip to main content

_python

Example

For this example we will use a dropdown list from the-internet. In this list there a few options to select, one which should be disabled. Let's find this element and assert that it is disabled. First let's require our dependent libraries (import unittest for our test framework and from selenium import webdriver to drive the browser), declare our test class, and wire up some test setUp and tearDown methods.

# filename: disabled_elements.py
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest


class DisabledElements(unittest.TestCase):

def setUp(self):
self.driver = webdriver.Firefox()

def tearDown(self):
self.driver.quit()
# ...

Now let's wire up our test.

# filename: disabled_elements.py
# ...
def test_dropdown(self):
driver = self.driver
driver.get('http://the-internet.herokuapp.com/dropdown')
wait = WebDriverWait(driver, 10)
dropdown_list = wait.until(
EC.presence_of_all_elements_located((By.ID, 'dropdown')))
assert not dropdown_list[0].is_enabled() is False


if __name__ == "__main__":
unittest.main()

After loading the page, we find all the elements that have an option tag (which are all the items in the dropdown list). This returns a list of elements, so we use the first one (which is the one with the text of 'Please select an option').

Once we have the element we want we see if it's enabled (with .is_enabled) and assert based on the response.

And since we grabbed all the dropdown list options, we can easily test the opposite case by checking the second or third option in the list.

        assert dropdown_list[1].is_enabled() is True

Expected Behavior

When we save this file and run it (e.g., python disabled_elements.py from the command-line) here is what will happen:

  • Open a browser
  • Visit the page
  • Grab all dropdown list elements
  • Assert that the first element in the list is not enabled
  • Assert that the second element in the list is enabled
  • Close the browser

Summary

Hopefully this tip has helped make the task of seeing whether an element is enabled or disabled more approachable.

Happy Testing!