Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

add test_get_dropdown_options

Anirudha619fa9f6516975c
diff --git a/tests/test_controller.py b/tests/test_controller.py
index 7d948b4bd..54f1f0fd8 100644
--- a/tests/test_controller.py
+++ b/tests/test_controller.py
@@ -916,3 +916,150 @@ class TestControllerIntegration:
assert result.success is False
assert result.is_done is True
assert result.error is None
+
+ @pytest.mark.asyncio
+ async def test_get_dropdown_options(self, controller, browser_context):
+ """Test that get_dropdown_options correctly retrieves options from a dropdown."""
+ # Create a simple HTML file with a dropdown for testing
+ import os
+ import tempfile
+
+ # Create a temporary HTML file with a dropdown
+ with tempfile.NamedTemporaryFile(suffix='.html', delete=False, mode='w') as f:
+ f.write("""
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>Dropdown Test</title>
+ </head>
+ <body>
+ <h1>Dropdown Test</h1>
+ <select id="test-dropdown" name="test-dropdown">
+ <option value="">Please select</option>
+ <option value="option1">First Option</option>
+ <option value="option2">Second Option</option>
+ <option value="option3">Third Option</option>
+ </select>
+ </body>
+ </html>
+ """)
+ temp_path = f.name
+
+ try:
+ # Navigate to the HTML file using go_to_url
+ file_url = f'file://{temp_path.replace(os.sep, "/")}'
+ goto_action = {'go_to_url': GoToUrlAction(url=file_url)}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: GoToUrlAction | None = None
+
+ # Navigate to the page
+ await controller.act(GoToUrlActionModel(**goto_action), browser_context)
+
+ # Wait for the page to load
+ page = await browser_context.get_current_page()
+ await page.wait_for_load_state()
+
+ # Initialize the DOM state to populate the selector map
+ await browser_context.get_state(cache_clickable_elements_hashes=True)
+
+ # Interact with the dropdown to ensure it's recognized
+ await page.click('select#test-dropdown')
+
+ # Update the state after interaction
+ await browser_context.get_state(cache_clickable_elements_hashes=True)
+
+ # Get the selector map
+ selector_map = await browser_context.get_selector_map()
+
+ # Find the dropdown element in the selector map
+ dropdown_index = None
+ for idx, element in selector_map.items():
+ if element.tag_name.lower() == 'select':
+ dropdown_index = idx
+ break
+
+ # If we still can't find the dropdown in the selector map, use a direct DOM approach
+ if dropdown_index is None:
+ # Log the selector map contents for debugging
+ print('Selector map contents:', selector_map)
+
+ # Create a direct test for get_dropdown_options using the DOM API
+ @controller.action('Get dropdown options')
+ async def get_dropdown_options_test(browser: BrowserContext):
+ page = await browser.get_current_page()
+
+ # Use the same approach as the controller's get_dropdown_options function
+ options_data = await page.evaluate("""
+ () => {
+ const select = document.getElementById('test-dropdown');
+ return {
+ options: Array.from(select.options).map(opt => ({
+ text: opt.text,
+ value: opt.value,
+ index: opt.index
+ })),
+ id: select.id,
+ name: select.name
+ };
+ }
+ """)
+
+ formatted_options = []
+ for opt in options_data['options']:
+ formatted_options.append(f'{opt["index"]}: text="{opt["text"]}"')
+
+ return ActionResult(
+ extracted_content='\n'.join(formatted_options) + '\nUse the exact text string in select_dropdown_option',
+ include_in_memory=True,
+ )
+
+ # Create a model for our action
+ class GetDropdownOptionsTestModel(ActionModel):
+ get_dropdown_options_test: dict = {}
+
+ # Execute the action
+ result = await controller.act(GetDropdownOptionsTestModel(), browser_context)
+ else:
+ # Create a model for the standard get_dropdown_options action
+ class GetDropdownOptionsModel(ActionModel):
+ get_dropdown_options: dict
+
+ # Execute the action with the dropdown index
+ result = await controller.act(
+ GetDropdownOptionsModel(get_dropdown_options={'index': dropdown_index}), browser_context
+ )
+
+ # Verify the result structure
+ assert isinstance(result, ActionResult)
+
+ # Core logic validation: Verify all options are returned
+ assert 'First Option' in result.extracted_content
+ assert 'Second Option' in result.extracted_content
+ assert 'Third Option' in result.extracted_content
+
+ # Verify the instruction for using the text in select_dropdown_option is included
+ assert 'Use the exact text string in select_dropdown_option' in result.extracted_content
+
+ # Verify the actual dropdown options in the DOM
+ dropdown_options = await page.evaluate("""
+ () => {
+ const select = document.getElementById('test-dropdown');
+ return Array.from(select.options).map(opt => ({
+ text: opt.text,
+ value: opt.value
+ }));
+ }
+ """)
+
+ # Verify the dropdown has the expected options
+ assert len(dropdown_options) == 4, f'Expected 4 options, got {len(dropdown_options)}'
+ assert dropdown_options[1]['text'] == 'First Option'
+ assert dropdown_options[1]['value'] == 'option1'
+ assert dropdown_options[2]['text'] == 'Second Option'
+ assert dropdown_options[2]['value'] == 'option2'
+ assert dropdown_options[3]['text'] == 'Third Option'
+ assert dropdown_options[3]['value'] == 'option3'
+
+ finally:
+ os.unlink(temp_path)