from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import unittest
class TestMultiSelect(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get('https://example.com/multiselect') # Replace with actual URL
def test_multi_select_handling(self):
driver = self.driver
select_element = driver.find_element(By.ID, 'fruits')
select = Select(select_element)
# Select 'Apple' and 'Banana'
select.select_by_visible_text('Apple')
select.select_by_visible_text('Banana')
# Verify both are selected
selected_options = [opt.text for opt in select.all_selected_options]
self.assertIn('Apple', selected_options, "Apple should be selected")
self.assertIn('Banana', selected_options, "Banana should be selected")
# Deselect 'Apple'
select.deselect_by_visible_text('Apple')
# Verify only 'Banana' remains selected
selected_options_after = [opt.text for opt in select.all_selected_options]
self.assertNotIn('Apple', selected_options_after, "Apple should be deselected")
self.assertIn('Banana', selected_options_after, "Banana should still be selected")
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This test uses Selenium WebDriver with Python's unittest framework.
In setUp, the browser opens the target page with the multi-select dropdown.
We locate the dropdown by its id='fruits' and create a Select object to handle multi-select options easily.
We select 'Apple' and 'Banana' by their visible text, then check that both appear in the list of selected options.
Next, we deselect 'Apple' and verify that only 'Banana' remains selected.
Assertions ensure the test fails if the selections do not match expectations.
Finally, tearDown closes the browser to clean up.