from selenium import webdriver
from selenium.webdriver.support.ui import Select
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 TestDropdownSelect(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get('https://example.com/dropdown') # Replace with actual URL
self.wait = WebDriverWait(self.driver, 10)
def test_select_dropdown_options(self):
driver = self.driver
wait = self.wait
# Wait for dropdown to be present
dropdown_element = wait.until(EC.presence_of_element_located((By.ID, 'country-select')))
select = Select(dropdown_element)
# Select by visible text 'Canada'
select.select_by_visible_text('Canada')
selected_option = select.first_selected_option.text
self.assertEqual(selected_option, 'Canada', f"Expected 'Canada', got '{selected_option}'")
# Select by value 'mexico'
select.select_by_value('mexico')
selected_option = select.first_selected_option.text
self.assertEqual(selected_option, 'Mexico', f"Expected 'Mexico', got '{selected_option}'")
# Select by index 0 (should be 'USA')
select.select_by_index(0)
selected_option = select.first_selected_option.text
self.assertEqual(selected_option, 'USA', f"Expected 'USA', got '{selected_option}'")
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This test script uses Selenium WebDriver with Python's unittest framework.
First, it opens the browser and navigates to the page with the dropdown.
It waits explicitly for the dropdown element with id 'country-select' to be present to avoid timing issues.
Then it creates a Select object to interact with the dropdown.
It selects options by visible text, value, and index, verifying after each selection that the correct option is selected using assertions.
Finally, it closes the browser in tearDown to clean up.