Skip to content

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

Remove event tests because inside tools

Magnus Müller01dd419eaf92
diff --git a/tests/ci/test_browser_event_ClickElementEvent.py b/tests/ci/test_browser_event_ClickElementEvent.py
deleted file mode 100644
index c049ca1df..000000000
--- a/tests/ci/test_browser_event_ClickElementEvent.py
+++ /dev/null
@@ -1,959 +0,0 @@
-import asyncio
-import tempfile
-from pathlib import Path
-
-import pytest
-from pytest_httpserver import HTTPServer
-
-from browser_use.agent.views import ActionResult
-from browser_use.browser import BrowserSession
-from browser_use.browser.profile import BrowserProfile
-from browser_use.tools.service import Tools
-
-
[email protected](scope='session')
-def http_server():
- """Create and provide a test HTTP server that serves static content."""
- server = HTTPServer()
- server.start()
-
- # Add routes for common test pages
- server.expect_request('/').respond_with_data(
- '<html><head><title>Test Home Page</title></head><body><h1>Test Home Page</h1><p>Welcome to the test site</p></body></html>',
- content_type='text/html',
- )
-
- server.expect_request('/page1').respond_with_data(
- '<html><head><title>Test Page 1</title></head><body><h1>Test Page 1</h1><p>This is test page 1</p></body></html>',
- content_type='text/html',
- )
-
- server.expect_request('/page2').respond_with_data(
- '<html><head><title>Test Page 2</title></head><body><h1>Test Page 2</h1><p>This is test page 2</p></body></html>',
- content_type='text/html',
- )
-
- yield server
- server.stop()
-
-
[email protected](scope='session')
-def base_url(http_server):
- """Return the base URL for the test HTTP server."""
- return f'http://{http_server.host}:{http_server.port}'
-
-
[email protected](scope='module')
-async def browser_session():
- """Create and provide a Browser instance with security disabled."""
- browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=True,
- user_data_dir=None,
- keep_alive=True,
- )
- )
- await browser_session.start()
- yield browser_session
- await browser_session.kill()
-
-
[email protected](scope='function')
-def tools():
- """Create and provide a Tools instance."""
- return Tools()
-
-
-class TestClickElementEvent:
- """Test cases for ClickElementEvent and click action."""
-
- async def test_click_element_by_index(self, tools, browser_session, base_url, http_server):
- """Test that click correctly clicks an element and handles different outcomes."""
- # Add route for clickable elements test page
- http_server.expect_request('/clickable').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Click Test</title>
- <style>
- .clickable {
- margin: 10px;
- padding: 10px;
- border: 1px solid #ccc;
- cursor: pointer;
- }
- #result {
- margin-top: 20px;
- padding: 10px;
- border: 1px solid #ddd;
- min-height: 20px;
- }
- </style>
- </head>
- <body>
- <h1>Click Test</h1>
- <div class="clickable" id="button1" onclick="updateResult('Button 1 clicked')">Button 1</div>
- <div class="clickable" id="button2" onclick="updateResult('Button 2 clicked')">Button 2</div>
- <a href="#" class="clickable" id="link1" onclick="updateResult('Link 1 clicked'); return false;">Link 1</a>
- <div id="result"></div>
-
- <script>
- function updateResult(text) {
- document.getElementById('result').textContent = text;
- }
- </script>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the clickable elements test page
- await tools.navigate(url=f'{base_url}/clickable', new_tab=False, browser_session=browser_session)
-
- # Wait for the page to load
- await asyncio.sleep(0.5) # Give page time to load
-
- # Initialize the DOM state to populate the selector map
- await browser_session.get_browser_state_summary()
-
- # Find the clickable button by ID
- button_index = await browser_session.get_index_by_id('button1')
-
- # Verify we found a clickable element
- assert button_index is not None, 'Could not find button1 element'
-
- # Define expected test data
- expected_result_text = 'Button 1 clicked'
-
- # Execute the action with the button index
- result = await tools.click(index=button_index, browser_session=browser_session)
-
- # Verify the result structure
- assert isinstance(result, ActionResult), 'Result should be an ActionResult instance'
- assert result.error is None, f'Expected no error but got: {result.error}'
- result_text = result.extracted_content or result.long_term_memory
- # Core logic validation: Verify click was successful
- assert result_text is not None
- assert 'Clicked element' in result_text, f'Expected click confirmation in result content, got: {result_text}'
- # Note: The click action doesn't include button text in the result, only the index
-
- # Verify the click actually had an effect on the page using CDP
- cdp_session = await browser_session.get_or_create_cdp_session()
- result_js = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- result_text = result_js.get('result', {}).get('value', '')
- assert result_text == expected_result_text, f"Expected result text '{expected_result_text}', got '{result_text}'"
-
- async def test_inline_element_mostly_offscreen(self, tools, browser_session, base_url, http_server):
- """Test clicking an inline element that's mostly outside the viewport."""
- # Add route for test page with inline element extending beyond viewport
- http_server.expect_request('/inline_offscreen').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Inline Offscreen Test</title>
- <style>
- body { margin: 0; padding: 20px; }
- .container { position: relative; width: 200%; }
- .inline-link {
- display: inline;
- position: absolute;
- left: -100px;
- width: 500px;
- padding: 10px;
- background: #007bff;
- color: white;
- cursor: pointer;
- }
- #result { margin-top: 100px; }
- </style>
- </head>
- <body>
- <div class="container">
- <span class="inline-link" onclick="document.getElementById('result').textContent = 'Inline clicked'">
- This is a very long inline element that extends way beyond the viewport edge
- </span>
- </div>
- <div id="result">Not clicked</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the page
- await tools.navigate(url=f'{base_url}/inline_offscreen', new_tab=False, browser_session=browser_session)
- await asyncio.sleep(0.5)
-
- # Get the clickable elements
- await browser_session.get_browser_state_summary()
-
- # Find the inline element by class
- inline_index = await browser_session.get_index_by_class('inline-link')
-
- assert inline_index is not None, 'Could not find inline element'
-
- # Click the element - should click the visible portion
- result = await tools.click(index=inline_index, browser_session=browser_session)
-
- assert result.error is None, f'Click failed: {result.error}'
-
- # Verify click worked using CDP
- cdp_session = await browser_session.get_or_create_cdp_session()
- result_js = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- assert result_js.get('result', {}).get('value') == 'Inline clicked'
-
- async def test_block_inside_inline_multiline(self, tools, browser_session, base_url, http_server):
- """Test clicking a block element inside an inline element that spans multiple lines."""
- # Add route for complex nested layout
- http_server.expect_request('/block_in_inline').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Block in Inline Test</title>
- <style>
- body { margin: 20px; width: 300px; }
- .inline-wrapper {
- display: inline;
- background: #f0f0f0;
- line-height: 1.5;
- }
- .block-inside {
- display: block;
- margin: 10px 0;
- padding: 10px;
- background: #007bff;
- color: white;
- cursor: pointer;
- }
- #result { margin-top: 50px; }
- </style>
- </head>
- <body>
- <span class="inline-wrapper">
- This is some text that wraps around and contains
- <div class="block-inside" onclick="document.getElementById('result').textContent = 'Block clicked'">
- Click this block element
- </div>
- and continues after the block element with more text that will wrap to multiple lines
- </span>
- <div id="result">Not clicked</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the page
- await tools.navigate(url=f'{base_url}/block_in_inline', new_tab=False, browser_session=browser_session)
- await asyncio.sleep(0.5)
-
- # Get the clickable elements
- await browser_session.get_browser_state_summary()
-
- # Find the block element by class
- block_index = await browser_session.get_index_by_class('block-inside')
-
- assert block_index is not None, 'Could not find block element'
-
- # Click the block element
- result = await tools.click(index=block_index, browser_session=browser_session)
-
- assert result.error is None, f'Click failed: {result.error}'
-
- # Verify click worked
- cdp_session = await browser_session.get_or_create_cdp_session()
- result_js = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- assert result_js.get('result', {}).get('value') == 'Block clicked'
-
- async def test_element_covered_by_overlay(self, tools, browser_session, base_url, http_server):
- """Test clicking an element that's mostly covered by another element."""
- # Add route for overlapping elements
- http_server.expect_request('/covered_element').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Covered Element Test</title>
- <style>
- body { margin: 20px; position: relative; }
- .target {
- position: absolute;
- top: 50px;
- left: 50px;
- width: 200px;
- height: 100px;
- padding: 20px;
- background: #28a745;
- color: white;
- cursor: pointer;
- z-index: 1;
- }
- .overlay {
- position: absolute;
- top: 60px;
- left: 60px;
- width: 180px;
- height: 80px;
- background: rgba(255, 0, 0, 0.7);
- z-index: 2;
- pointer-events: none; /* Allow clicks through */
- }
- #result { margin-top: 200px; }
- </style>
- </head>
- <body>
- <div class="target" onclick="document.getElementById('result').textContent = 'Target clicked'">
- Click me (partially covered)
- </div>
- <div class="overlay">Overlaying element</div>
- <div id="result">Not clicked</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the page
- await tools.navigate(url=f'{base_url}/covered_element', new_tab=False, browser_session=browser_session)
- await asyncio.sleep(0.5)
-
- # Get the clickable elements
- await browser_session.get_browser_state_summary()
-
- # Find the target element by class
- target_index = await browser_session.get_index_by_class('target')
-
- assert target_index is not None, 'Could not find target element'
-
- # Click should still work on the visible portion
- result = await tools.click(index=target_index, browser_session=browser_session)
-
- assert result.error is None, f'Click failed: {result.error}'
-
- # Verify click worked
- cdp_session = await browser_session.get_or_create_cdp_session()
- result_js = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- assert result_js.get('result', {}).get('value') == 'Target clicked'
-
- async def test_file_input_click_prevention(self, tools, browser_session, base_url, http_server):
- """Test that clicking a file input element raises an exception."""
- # Add route with file input
- http_server.expect_request('/file_input').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>File Input Test</title>
- </head>
- <body>
- <h1>File Upload Test</h1>
- <input type="file" id="fileInput" />
- <div id="result">No file selected</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the page
- await tools.navigate(url=f'{base_url}/file_input', new_tab=False, browser_session=browser_session)
- await asyncio.sleep(0.5)
-
- # Get the clickable elements
- await browser_session.get_browser_state_summary()
-
- # Find the file input by ID
- file_input_index = await browser_session.get_index_by_id('fileInput')
-
- assert file_input_index is not None, 'Could not find file input element'
-
- # Attempt to click should raise an error
- result = await tools.click(index=file_input_index, browser_session=browser_session)
-
- # Should have an error about file inputs
- assert result.error is not None, 'Expected error for file input click'
- assert 'file input' in result.error.lower() or 'file upload' in result.error.lower(), (
- f'Error message should mention file input, got: {result.error}'
- )
-
- async def test_select_dropdown_click_prevention(self, tools, browser_session, base_url, http_server):
- """Test that clicking a select dropdown element raises an exception."""
- # Add route with select dropdown
- http_server.expect_request('/select_dropdown').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Select Dropdown Test</title>
- </head>
- <body>
- <h1>Select Test</h1>
- <select id="testSelect">
- <option value="">Choose one</option>
- <option value="opt1">Option 1</option>
- <option value="opt2">Option 2</option>
- </select>
- <div id="result">Nothing selected</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the page
- await tools.navigate(url=f'{base_url}/select_dropdown', new_tab=False, browser_session=browser_session)
- await asyncio.sleep(0.5)
-
- # Get the clickable elements
- await browser_session.get_browser_state_summary()
-
- # Find the select element by ID
- select_index = await browser_session.get_index_by_id('testSelect')
-
- assert select_index is not None, 'Could not find select element'
-
- # Attempt to click should provide dropdown options
- result = await tools.click(index=select_index, browser_session=browser_session)
-
- # Should automatically provide dropdown options instead of an error
- assert result.error is None, 'Should not have error - should provide dropdown options automatically'
- assert result.extracted_content is not None, 'Should have dropdown options content'
- assert 'dropdown' in result.extracted_content.lower(), f'Should contain dropdown options, got: {result.extracted_content}'
-
- @pytest.mark.skip(reason='Dialog system validation bug - DialogOpenedEvent.frame_id expects string but gets None')
- async def test_click_triggers_alert_popup(self, browser_session, base_url, http_server):
- """Test that clicking a button triggers an alert dialog that is auto-accepted."""
- from browser_use.browser.events import BrowserStateRequestEvent, ClickElementEvent, DialogOpenedEvent, NavigateToUrlEvent
-
- # Add route with alert dialog
- http_server.expect_request('/alert_test').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Alert Test</title>
- </head>
- <body>
- <h1>Alert Dialog Test</h1>
- <button id="alertButton" onclick="alert('This is an alert!'); document.getElementById('result').textContent = 'Alert shown';">
- Show Alert
- </button>
- <div id="result">No popup shown</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the alert test page using events
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=f'{base_url}/alert_test'))
- await nav_event
- await asyncio.sleep(0.5)
-
- # Get the browser state to find clickable elements
- state_event = browser_session.event_bus.dispatch(BrowserStateRequestEvent())
- browser_state = await state_event.event_result(raise_if_none=True, raise_if_any=True)
-
- # Find the alert button
- alert_button = None
- for element in browser_state.dom_state.selector_map.values():
- if element.attributes and element.attributes.get('id') == 'alertButton':
- alert_button = element
- break
-
- assert alert_button is not None, 'Could not find alert button'
-
- # Expect the DialogOpenedEvent
- dialog_event_future = browser_session.event_bus.expect(DialogOpenedEvent)
-
- # Click the alert button using ClickElementEvent
- click_event = browser_session.event_bus.dispatch(ClickElementEvent(node=alert_button))
- await click_event
-
- # Wait for and verify DialogOpenedEvent was dispatched
- dialog_event = await asyncio.wait_for(dialog_event_future, timeout=2.0)
- assert dialog_event.dialog_type == 'alert'
- assert 'This is an alert!' in dialog_event.message
-
- # Verify the page updated after alert was accepted
- cdp_session = await browser_session.get_or_create_cdp_session()
- result_js = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- assert result_js.get('result', {}).get('value') == 'Alert shown'
-
- @pytest.mark.skip(reason='Dialog system validation bug - DialogOpenedEvent.frame_id expects string but gets None')
- async def test_click_triggers_confirm_popup(self, browser_session, base_url, http_server):
- """Test that clicking a button triggers a confirm dialog that is auto-accepted."""
- from browser_use.browser.events import BrowserStateRequestEvent, ClickElementEvent, DialogOpenedEvent, NavigateToUrlEvent
-
- # Add route with confirm dialog
- http_server.expect_request('/confirm_test').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Confirm Test</title>
- </head>
- <body>
- <h1>Confirm Dialog Test</h1>
- <button id="confirmButton" onclick="if(confirm('Are you sure?')) { document.getElementById('result').textContent = 'Confirmed'; } else { document.getElementById('result').textContent = 'Cancelled'; }">
- Show Confirm
- </button>
- <div id="result">No popup shown</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the confirm test page
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=f'{base_url}/confirm_test'))
- await nav_event
- await asyncio.sleep(0.5)
-
- # Get the browser state
- state_event = browser_session.event_bus.dispatch(BrowserStateRequestEvent())
- browser_state = await state_event.event_result(raise_if_none=True, raise_if_any=True)
-
- # Find the confirm button
- confirm_button = None
- for element in browser_state.dom_state.selector_map.values():
- if element.attributes and element.attributes.get('id') == 'confirmButton':
- confirm_button = element
- break
-
- assert confirm_button is not None, 'Could not find confirm button'
-
- # Expect the DialogOpenedEvent
- dialog_event_future = browser_session.event_bus.expect(DialogOpenedEvent)
-
- # Click the confirm button
- click_event = browser_session.event_bus.dispatch(ClickElementEvent(node=confirm_button))
- await click_event
-
- # Wait for and verify DialogOpenedEvent was dispatched
- dialog_event = await asyncio.wait_for(dialog_event_future, timeout=2.0)
- assert dialog_event.dialog_type == 'confirm'
- assert 'Are you sure?' in dialog_event.message
-
- # Verify the page updated after confirm was accepted (auto-accepts with True)
- cdp_session = await browser_session.get_or_create_cdp_session()
- result_js = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- assert result_js.get('result', {}).get('value') == 'Confirmed'
-
- @pytest.mark.skip(reason='Dialog system validation bug - DialogOpenedEvent.frame_id expects string but gets None')
- async def test_page_usable_after_popup_confirm(self, browser_session, base_url, http_server):
- """Test that the page remains usable after handling confirm dialogs."""
- from browser_use.browser.events import BrowserStateRequestEvent, ClickElementEvent, DialogOpenedEvent, NavigateToUrlEvent
-
- # Add route with confirm dialog and navigation
- http_server.expect_request('/popup_nav_test').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Popup Navigation Test</title>
- </head>
- <body>
- <h1>Popup and Navigation Test</h1>
- <button id="confirmButton" onclick="if(confirm('Continue to navigation?')) { document.getElementById('result').textContent = 'Ready to navigate'; }">
- Show Confirm
- </button>
- <a href="/page1" id="navLink">Navigate to Page 1</a>
- <div id="result">No popup shown</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the test page
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=f'{base_url}/popup_nav_test'))
- await nav_event
- await asyncio.sleep(0.5)
-
- # Get browser state
- state_event = browser_session.event_bus.dispatch(BrowserStateRequestEvent())
- browser_state = await state_event
-
- # Find and click the confirm button
- confirm_button = None
- for element in browser_state.dom_state.selector_map.values():
- if element.attributes and element.attributes.get('id') == 'confirmButton':
- confirm_button = element
- break
-
- assert confirm_button is not None, 'Could not find confirm button'
-
- # Expect dialog event
- dialog_event_future = browser_session.event_bus.expect(DialogOpenedEvent)
-
- # Click confirm button
- click_event = browser_session.event_bus.dispatch(ClickElementEvent(node=confirm_button))
- await click_event
-
- # Wait for dialog event
- dialog_event = await asyncio.wait_for(dialog_event_future, timeout=2.0)
- assert dialog_event.dialog_type == 'confirm'
-
- # Verify page was updated
- cdp_session = await browser_session.get_or_create_cdp_session()
- result_js = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- assert result_js.get('result', {}).get('value') == 'Ready to navigate'
-
- # Refresh browser state after handling dialog
- browser_state = await browser_session.get_browser_state_summary()
-
- # Find and click navigation link to verify page is still usable
- nav_link = None
- for element in browser_state.dom_state.selector_map.values():
- if element.attributes and element.attributes.get('id') == 'navLink':
- nav_link = element
- break
-
- assert nav_link is not None, 'Could not find navigation link'
-
- # Click the navigation link
- click_event = browser_session.event_bus.dispatch(ClickElementEvent(node=nav_link))
- await click_event
- await asyncio.sleep(1)
-
- # Verify navigation succeeded
- current_url = await browser_session.get_current_page_url()
- assert f'{base_url}/page1' in current_url, f'Navigation failed, current URL: {current_url}'
-
- # Verify browser is still responsive
- current_title = await browser_session.get_current_page_title()
- assert 'Test Page 1' in current_title, f'Page title incorrect: {current_title}'
-
- @pytest.mark.skip(reason='Dialog system validation bug - DialogOpenedEvent.frame_id expects string but gets None')
- async def test_click_triggers_onbeforeunload_popup(self, browser_session, base_url, http_server):
- """Test that navigating away from a page with onbeforeunload triggers a dialog."""
- from browser_use.browser.events import ClickElementEvent, DialogOpenedEvent, NavigateToUrlEvent
-
- # Add route with onbeforeunload handler
- http_server.expect_request('/beforeunload_test').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>BeforeUnload Test</title>
- <script>
- window.onbeforeunload = function(e) {
- e.preventDefault();
- e.returnValue = 'You have unsaved changes!';
- return 'You have unsaved changes!';
- };
- </script>
- </head>
- <body>
- <h1>BeforeUnload Test</h1>
- <p>This page has unsaved changes.</p>
- <a href="/page1" id="navLink">Navigate Away</a>
- <div id="result">Page loaded</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the beforeunload test page
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=f'{base_url}/beforeunload_test'))
- await nav_event
- await asyncio.sleep(0.5)
-
- # Get browser state
- browser_state = await browser_session.get_browser_state_summary()
-
- # Find the navigation link
- nav_link = None
- for element in browser_state.dom_state.selector_map.values():
- if element.attributes and element.attributes.get('id') == 'navLink':
- nav_link = element
- break
-
- assert nav_link is not None, 'Could not find navigation link'
-
- # Expect the DialogOpenedEvent for beforeunload
- dialog_event_future = browser_session.event_bus.expect(DialogOpenedEvent)
-
- # Click the navigation link - should trigger beforeunload popup
- click_event = browser_session.event_bus.dispatch(ClickElementEvent(node=nav_link))
- await click_event
-
- # Wait for and verify DialogOpenedEvent was dispatched
- dialog_event = await asyncio.wait_for(dialog_event_future, timeout=2.0)
- assert dialog_event.dialog_type == 'beforeunload'
- # Note: beforeunload messages are often browser-controlled and may not match our custom message
-
- # Wait a bit for navigation to complete after dialog is auto-accepted
- await asyncio.sleep(1)
-
- # Verify navigation succeeded after beforeunload was accepted
- current_url = await browser_session.get_current_page_url()
- assert f'{base_url}/page1' in current_url, (
- f'Navigation should have succeeded after beforeunload was accepted, current URL: {current_url}'
- )
-
- async def test_file_upload_click_and_verify(self, tools, browser_session, base_url, http_server):
- """Test that clicking a file upload element and uploading a file works correctly."""
- # Create a temporary test file
- import tempfile as temp_module
-
- with temp_module.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as temp_file:
- temp_file.write('Test file content for upload')
- temp_file_path = temp_file.name
-
- try:
- # Add route for file upload test page
- http_server.expect_request('/fileupload').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>File Upload Test</title>
- <style>
- .upload-section {
- margin: 20px;
- padding: 20px;
- border: 2px dashed #ccc;
- }
- #fileInfo {
- margin-top: 20px;
- padding: 10px;
- border: 1px solid #ddd;
- min-height: 50px;
- }
- .upload-label {
- display: inline-block;
- padding: 10px 20px;
- background-color: #4CAF50;
- color: white;
- cursor: pointer;
- border-radius: 4px;
- }
- .upload-label:hover {
- background-color: #45a049;
- }
- input[type="file"] {
- /* Hide the default file input */
- display: none;
- }
- </style>
- </head>
- <body>
- <h1>File Upload Test</h1>
- <div class="upload-section">
- <p>Click the button below to select a file:</p>
- <label for="fileInput" class="upload-label">Choose File</label>
- <input type="file" id="fileInput" name="fileInput" />
- <div id="fileInfo">
- <p id="fileName">No file selected</p>
- <p id="fileSize"></p>
- <p id="fileType"></p>
- </div>
- </div>
-
- <script>
- document.getElementById('fileInput').addEventListener('change', function(e) {
- const file = e.target.files[0];
- if (file) {
- document.getElementById('fileName').textContent = 'File name: ' + file.name;
- document.getElementById('fileSize').textContent = 'File size: ' + file.size + ' bytes';
- document.getElementById('fileType').textContent = 'File type: ' + (file.type || 'unknown');
- } else {
- document.getElementById('fileName').textContent = 'No file selected';
- document.getElementById('fileSize').textContent = '';
- document.getElementById('fileType').textContent = '';
- }
- });
- </script>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the file upload test page
- await tools.navigate(url=f'{base_url}/fileupload', new_tab=False, browser_session=browser_session)
-
- # Wait for the page to load
- await asyncio.sleep(0.5)
-
- # Initialize the DOM state to populate the selector map
- await browser_session.get_browser_state_summary()
-
- # Find the label element that triggers the file input by class
- label_index = await browser_session.get_index_by_class('upload-label')
-
- assert label_index is not None, 'Could not find file upload label element'
-
- # Create a temporary FileSystem for the test
- import tempfile
-
- from browser_use.filesystem.file_system import FileSystem
-
- with tempfile.TemporaryDirectory() as temp_dir:
- file_system = FileSystem(base_dir=temp_dir)
-
- # Upload the file using the label index (should find the associated file input)
- result = await tools.upload_file(
- index=label_index,
- path=temp_file_path,
- browser_session=browser_session,
- available_file_paths=[temp_file_path], # Pass the file path as available
- file_system=file_system, # Pass the required file_system parameter
- )
-
- # Verify the upload action succeeded
- assert result.error is None, f'File upload failed: {result.error}'
- assert result.extracted_content is not None
- assert 'Successfully uploaded file' in result.extracted_content
-
- # Wait a moment for the JavaScript to process the file
- await asyncio.sleep(0.5)
-
- # Verify the file was actually selected using CDP Runtime.evaluate
- cdp_session = await browser_session.get_or_create_cdp_session()
-
- # Check if the file input has a file selected
- file_check_js = await browser_session.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': """
- (() => {
- const input = document.getElementById('fileInput');
- if (!input || !input.files || input.files.length === 0) {
- return { hasFile: false };
- }
- const file = input.files[0];
- return {
- hasFile: true,
- fileName: file.name,
- fileSize: file.size,
- fileType: file.type || 'text/plain'
- };
- })()
- """,
- 'returnByValue': True,
- },
- session_id=cdp_session.session_id,
- )
-
- file_info = file_check_js.get('result', {}).get('value', {})
-
- # Verify file was selected
- assert file_info.get('hasFile') is True, 'File was not properly selected in the input element'
- assert file_info.get('fileName', '').endswith('.txt'), f'Expected .txt file, got: {file_info.get("fileName")}'
- assert file_info.get('fileSize', 0) > 0, 'File size should be greater than 0'
-
- # Also verify the UI was updated (the file info div)
- ui_check_js = await browser_session.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': """
- (() => {
- const fileName = document.getElementById('fileName').textContent;
- const fileSize = document.getElementById('fileSize').textContent;
- return {
- fileNameText: fileName,
- fileSizeText: fileSize,
- hasFileInfo: !fileName.includes('No file selected')
- };
- })()
- """,
- 'returnByValue': True,
- },
- session_id=cdp_session.session_id,
- )
-
- ui_info = ui_check_js.get('result', {}).get('value', {})
-
- # Verify UI was updated
- assert ui_info.get('hasFileInfo') is True, 'UI was not updated with file information'
- assert '.txt' in ui_info.get('fileNameText', ''), f'File name not shown in UI: {ui_info.get("fileNameText")}'
- assert 'bytes' in ui_info.get('fileSizeText', ''), f'File size not shown in UI: {ui_info.get("fileSizeText")}'
-
- finally:
- # Clean up the temporary file
- Path(temp_file_path).unlink(missing_ok=True)
-
- async def test_file_upload_path_validation(self, tools, browser_session, base_url, http_server):
- """Test that file upload validates paths correctly with available_file_paths, downloaded_files, and FileSystem."""
- from pathlib import Path
-
- from browser_use.browser.views import BrowserError
- from browser_use.filesystem.file_system import FileSystem
-
- # Create a temporary test file that's NOT in available_file_paths
- with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as temp_file:
- temp_file.write('Test file content')
- test_file_path = temp_file.name
-
- try:
- # Set up test page with file input
- http_server.expect_request('/upload-test').respond_with_data(
- """
- <html>
- <body>
- <h1>File Upload Test</h1>
- <input type="file" id="fileInput" />
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to the test page
- await tools.navigate(url=f'{base_url}/upload-test', new_tab=False, browser_session=browser_session)
- await asyncio.sleep(0.5)
-
- # Get browser state to populate selector map
- from browser_use.browser.events import BrowserStateRequestEvent
-
- event = browser_session.event_bus.dispatch(BrowserStateRequestEvent())
- state = await event
-
- # Create a temporary FileSystem for all tests
- with tempfile.TemporaryDirectory() as temp_dir:
- file_system = FileSystem(base_dir=temp_dir)
-
- try:
- # This should fail because the file is not in available_file_paths
- result = await tools.upload_file(
- index=1,
- path=test_file_path,
- browser_session=browser_session,
- available_file_paths=[], # Empty available_file_paths
- file_system=file_system,
- )
- assert result.error is not None, 'Upload should have failed for file not in available_file_paths'
- assert 'not available' in result.error, f'Error message should mention file not available: {result.error}'
- except BrowserError as e:
- assert 'not available' in str(e), f'Error should mention file not available: {e}'
-
- finally:
- # Clean up the temporary file
- Path(test_file_path).unlink(missing_ok=True)
diff --git a/tests/ci/test_browser_event_NavigateToUrlEvent.py b/tests/ci/test_browser_event_NavigateToUrlEvent.py
deleted file mode 100644
index de7b45183..000000000
--- a/tests/ci/test_browser_event_NavigateToUrlEvent.py
+++ /dev/null
@@ -1,351 +0,0 @@
-import asyncio
-
-import pytest
-from pytest_httpserver import HTTPServer
-
-from browser_use.agent.views import ActionResult
-from browser_use.browser import BrowserSession
-from browser_use.browser.profile import BrowserProfile
-from browser_use.tools.service import Tools
-
-
[email protected](scope='session')
-def http_server():
- """Create and provide a test HTTP server that serves static content."""
- server = HTTPServer()
- server.start()
-
- # Add routes for common test pages
- server.expect_request('/').respond_with_data(
- '<html><head><title>Test Home Page</title></head><body><h1>Test Home Page</h1><p>Welcome to the test site</p></body></html>',
- content_type='text/html',
- )
-
- server.expect_request('/page1').respond_with_data(
- '<html><head><title>Test Page 1</title></head><body><h1>Test Page 1</h1><p>This is test page 1</p></body></html>',
- content_type='text/html',
- )
-
- server.expect_request('/page2').respond_with_data(
- '<html><head><title>Test Page 2</title></head><body><h1>Test Page 2</h1><p>This is test page 2</p></body></html>',
- content_type='text/html',
- )
-
- yield server
- server.stop()
-
-
[email protected](scope='session')
-def base_url(http_server):
- """Return the base URL for the test HTTP server."""
- return f'http://{http_server.host}:{http_server.port}'
-
-
[email protected](scope='module')
-async def browser_session():
- """Create and provide a Browser instance with security disabled."""
- profile = BrowserProfile(headless=True, disable_security=True, cross_origin_iframes=False)
- session = BrowserSession(browser_profile=profile)
- await session.start()
- yield session
- await session.kill()
-
-
-def tools():
- """Create and provide a Tools instance."""
- return Tools()
-
-
-class TestNavigateToUrlEvent:
- """Test NavigateToUrlEvent and navigate action functionality."""
-
- async def test_navigate_action(self, tools, browser_session: BrowserSession, base_url):
- """Test that GoToUrlAction navigates to the specified URL and test both state summary methods."""
- # Test successful navigation to a valid page
- result = await tools.navigate(url=f'{base_url}/page1', new_tab=False, browser_session=browser_session)
-
- # Verify the successful navigation result
- assert isinstance(result, ActionResult)
- assert result.extracted_content is not None
- assert f'Navigated to {base_url}' in result.extracted_content
-
- async def test_navigate_network_error(self, tools, browser_session: BrowserSession):
- """Test that navigate handles network errors gracefully instead of throwing hard errors."""
- # Execute the action - should return soft error instead of throwing
- result = await tools.navigate(url='https://www.nonexistentdndbeyond.com/', new_tab=False, browser_session=browser_session)
-
- # Verify the result
- assert isinstance(result, ActionResult)
- # The navigation should fail with an error for non-existent domain
-
- # Test that get_state_summary works
- try:
- await browser_session.get_browser_state_summary()
- assert False, 'Expected throw error when navigating to non-existent page'
- except Exception as e:
- pass
-
- # Test that browser state recovery works after error
- summary = await browser_session.get_browser_state_summary(include_screenshot=False)
- assert summary is not None
-
- async def test_navigate_to_url_event_directly(self, browser_session, base_url):
- """Test NavigateToUrlEvent directly through the event bus."""
- from browser_use.browser.events import NavigateToUrlEvent
-
- # Test navigation to a valid URL
- event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=f'{base_url}/page1'))
- result = await asyncio.wait_for(event, timeout=3.0)
- # NavigateToUrlEvent handlers don't return values, just wait for completion
- assert result is not None
-
- # Wait a bit for navigation to complete
- await asyncio.sleep(0.5)
-
- # Verify we're on the correct page
- current_url = await browser_session.get_current_page_url()
- assert f'{base_url}/page1' in current_url
-
- async def test_navigate_new_tab(self, tools, browser_session, base_url):
- """Test that GoToUrlAction with new_tab=True opens URL in a new tab."""
- # Get initial tab count
- initial_tabs = await browser_session.get_tabs()
- initial_tab_count = len(initial_tabs)
-
- # Navigate to URL in new tab
- result = await tools.navigate(url=f'{base_url}/page2', new_tab=True, browser_session=browser_session)
- await asyncio.sleep(0.5)
-
- # Verify result
- assert isinstance(result, ActionResult)
- assert result.extracted_content is not None
- assert 'Opened new tab with url' in result.extracted_content or 'Navigated to' in result.extracted_content
-
- # Verify new tab was created
- final_tabs = await browser_session.get_tabs()
- final_tab_count = len(final_tabs)
- assert final_tab_count == initial_tab_count + 1
-
- # Verify we're on the new page
- current_url = await browser_session.get_current_page_url()
- assert f'{base_url}/page2' in current_url
-
- async def test_navigate_javascript_url(self, tools, browser_session, base_url):
- """Test that javascript: URLs are handled appropriately."""
- # Navigate to a normal page first
- await tools.navigate(url=f'{base_url}/page1', new_tab=False, browser_session=browser_session)
-
- # Try to navigate to javascript: URL (should be handled gracefully)
- result = await tools.navigate(url='javascript:alert("test")', new_tab=False, browser_session=browser_session)
-
- # Should either succeed or fail gracefully
- assert isinstance(result, ActionResult)
-
- async def test_navigate_data_url(self, tools, browser_session):
- """Test navigating to a data: URL."""
- # Create a simple data URL
- data_url = 'data:text/html,<html><head><title>Data URL Test</title></head><body><h1>Data URL Content</h1></body></html>'
-
- result = await tools.navigate(url=data_url, new_tab=False, browser_session=browser_session)
-
- # Verify navigation
- assert isinstance(result, ActionResult)
- assert result.extracted_content is not None
-
- # Verify we can get the page title using CDP
- title = await browser_session.get_current_page_title()
- assert title == 'Data URL Test'
-
- async def test_navigate_with_hash(self, tools, browser_session, base_url, http_server):
- """Test navigating to URLs with hash fragments."""
- # Add a page with anchors
- http_server.expect_request('/page-with-anchors').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head><title>Page with Anchors</title></head>
- <body>
- <h1 id="top">Top of Page</h1>
- <div style="height: 2000px;">Content</div>
- <h2 id="section1">Section 1</h2>
- <div style="height: 1000px;">More content</div>
- <h2 id="section2">Section 2</h2>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to page with hash
- result = await tools.navigate(
- url=f'{base_url}/page-with-anchors#section1', new_tab=False, browser_session=browser_session
- )
-
- # Verify navigation
- assert isinstance(result, ActionResult)
- assert result.extracted_content is not None
-
- # Verify URL includes hash
- current_url = await browser_session.get_current_page_url()
- assert '#section1' in current_url
-
- async def test_navigate_with_query_params(self, tools, browser_session, base_url, http_server):
- """Test navigating to URLs with query parameters."""
- # Add a page that shows query params
- http_server.expect_request('/search').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head><title>Search Page</title></head>
- <body>
- <h1>Search Results</h1>
- <div id="query"></div>
- <script>
- const params = new URLSearchParams(window.location.search);
- document.getElementById('query').textContent = 'Query: ' + params.get('q');
- </script>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate with query parameters
- result = await tools.navigate(
- url=f'{base_url}/search?q=test+query&page=1', new_tab=False, browser_session=browser_session
- )
-
- # Verify navigation
- assert isinstance(result, ActionResult)
- assert result.extracted_content is not None
-
- # Verify URL includes query params
- current_url = await browser_session.get_current_page_url()
- assert 'q=test+query' in current_url or 'q=test%20query' in current_url
- assert 'page=1' in current_url
-
- @pytest.mark.skip(reason='Tab count assertion failures - tab management logic changed')
- async def test_navigate_multiple_tabs(self, tools, browser_session, base_url):
- """Test navigating in multiple tabs sequentially."""
- # Navigate to first page in current tab
- await tools.navigate(url=f'{base_url}/page1', new_tab=False, browser_session=browser_session)
-
- # Open second page in new tab
- await tools.navigate(url=f'{base_url}/page2', new_tab=True, browser_session=browser_session)
-
- # Open home page in yet another new tab
- await tools.navigate(url=base_url, new_tab=True, browser_session=browser_session)
-
- # Should have 3 tabs now
- tabs = await browser_session.get_tabs()
- assert len(tabs) == 3
-
- # Current tab should be the last one opened
- current_url = await browser_session.get_current_page_url()
- assert base_url in current_url and '/page' not in current_url
-
- async def test_navigate_timeout_handling(self, tools, browser_session):
- """Test that navigation timeouts are handled gracefully."""
- # Try to navigate to a URL that will likely timeout
- # Using a private IP that's unlikely to respond
- timeout_url = 'http://192.0.2.1:8080/timeout'
-
- # This should complete without hanging indefinitely
- result = await tools.navigate(url=timeout_url, new_tab=False, browser_session=browser_session)
-
- # Should get a result (possibly with error)
- assert isinstance(result, ActionResult)
-
- async def test_navigate_redirect(self, tools, browser_session, base_url, http_server):
- """Test navigating to a URL that redirects."""
- # Add a redirect endpoint
- http_server.expect_request('/redirect').respond_with_data(
- '',
- status=302,
- headers={'Location': f'{base_url}/page2'},
- )
-
- # Navigate to redirect URL
- result = await tools.navigate(url=f'{base_url}/redirect', new_tab=False, browser_session=browser_session)
-
- # Verify navigation succeeded
- assert isinstance(result, ActionResult)
- assert result.extracted_content is not None
-
- # Should end up on page2 after redirect
- await asyncio.sleep(0.5) # Give redirect time to complete
- current_url = await browser_session.get_current_page_url()
- assert '/page2' in current_url
-
- async def test_navigate_to_url_event_with_new_tab_and_tab_created_event(self, browser_session, base_url):
- """Test NavigateToUrlEvent with new_tab=True and verify TabCreatedEvent is emitted."""
- from browser_use.browser.events import NavigateToUrlEvent, TabCreatedEvent
-
- initial_tabs = await browser_session.get_tabs()
- initial_tab_count = len(initial_tabs)
-
- # Navigate to URL in new tab via direct event
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=f'{base_url}/page2', new_tab=True))
- await nav_event
-
- # Verify new tab was created
- final_tabs = await browser_session.get_tabs()
- assert len(final_tabs) == initial_tab_count + 1
-
- # Check that current page is the new tab
- current_url = await browser_session.get_current_page_url()
- assert f'{base_url}/page2' in current_url
-
- # Check event history for TabCreatedEvent
- event_history = list(browser_session.event_bus.event_history.values())
- created_events = [e for e in event_history if isinstance(e, TabCreatedEvent)]
- assert len(created_events) >= 1
-
- async def test_navigate_with_new_tab_focuses_properly(self, browser_session):
- """Test that NavigateToUrlEvent with new_tab=True properly switches focus."""
- from browser_use.browser.events import NavigateToUrlEvent
-
- # Get initial state
- initial_tabs = await browser_session.get_tabs()
- initial_tabs_count = len(initial_tabs)
- initial_url = await browser_session.get_current_page_url()
-
- # Navigate to a URL in a new tab
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url='https://example.com', new_tab=True))
- await nav_event
-
- # Small delay to ensure navigation completes
- await asyncio.sleep(1)
-
- # Get browser state after navigation
- current_url = await browser_session.get_current_page_url()
-
- # Verify a new tab was created
- final_tabs = await browser_session.get_tabs()
- assert len(final_tabs) == initial_tabs_count + 1
-
- # Verify focus switched to the new tab
- assert 'example.com' in current_url
- assert current_url != initial_url
-
- async def test_navigate_and_verify_page_properties(self, browser_session, base_url):
- """Test that NavigateToUrlEvent changes the URL and page properties are accessible."""
- from browser_use.browser.events import NavigateToUrlEvent
-
- # Navigate to the test page
- event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=f'{base_url}/'))
- await event
-
- # Wait for navigation to complete
- await asyncio.sleep(0.5)
-
- # Get the current page URL
- current_url = await browser_session.get_current_page_url()
-
- # Verify the page URL matches what we navigated to
- assert f'{base_url}/' in current_url
-
- # Verify the page title using the new API
- title = await browser_session.get_current_page_title()
- assert title == 'Test Home Page'
diff --git a/tests/ci/test_browser_event_ScrollEvent.py b/tests/ci/test_browser_event_ScrollEvent.py
deleted file mode 100644
index 2a9bfb2b2..000000000
--- a/tests/ci/test_browser_event_ScrollEvent.py
+++ /dev/null
@@ -1,381 +0,0 @@
-import asyncio
-
-import pytest
-from pytest_httpserver import HTTPServer
-
-from browser_use.agent.views import ActionResult
-from browser_use.browser import BrowserSession
-from browser_use.browser.profile import BrowserProfile
-from browser_use.tools.service import Tools
-
-
[email protected](scope='session')
-def http_server():
- """Create and provide a test HTTP server that serves static content."""
- server = HTTPServer()
- server.start()
-
- # Add routes for common test pages
- server.expect_request('/').respond_with_data(
- '<html><head><title>Test Home Page</title></head><body><h1>Test Home Page</h1><p>Welcome to the test site</p></body></html>',
- content_type='text/html',
- )
-
- server.expect_request('/scrollable').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Scrollable Page</title>
- <style>
- body { margin: 0; padding: 20px; }
- .content { height: 3000px; background: linear-gradient(to bottom, #f0f0f0, #333); }
- .marker { padding: 20px; background: #007bff; color: white; margin: 500px 0; }
- </style>
- </head>
- <body>
- <h1>Scrollable Test Page</h1>
- <div class="content">
- <div class="marker" id="marker1">Marker 1</div>
- <div class="marker" id="marker2">Marker 2</div>
- <div class="marker" id="marker3">Marker 3</div>
- </div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- yield server
- server.stop()
-
-
[email protected](scope='session')
-def base_url(http_server):
- """Return the base URL for the test HTTP server."""
- return f'http://{http_server.host}:{http_server.port}'
-
-
[email protected](scope='module')
-async def browser_session():
- """Create and provide a Browser instance with security disabled."""
- profile = BrowserProfile(headless=True, disable_security=True, cross_origin_iframes=False)
- session = BrowserSession(browser_profile=profile)
- await session.start()
- yield session
- await session.kill()
-
-
-def tools():
- """Create and provide a Tools instance."""
- return Tools()
-
-
-class TestScrollActions:
- """Test scroll-related actions and events."""
-
- async def test_scroll_actions(self, tools, browser_session, base_url, http_server):
- """Test basic scroll action functionality."""
-
- # Navigate to scrollable page
- await tools.navigate(url=f'{base_url}/scrollable', new_tab=False, browser_session=browser_session)
-
- # Test 1: Basic page scroll down
- result = await tools.scroll(down=True, pages=1.0, browser_session=browser_session)
-
- # Verify scroll down succeeded
- assert isinstance(result, ActionResult)
- assert result.error is None, f'Scroll down failed: {result.error}'
- assert result.extracted_content is not None
- assert 'Scrolled down' in result.extracted_content
- assert 'px' in result.extracted_content
-
- # Test 2: Basic page scroll up
- result = await tools.scroll(down=False, pages=0.5, browser_session=browser_session)
-
- assert isinstance(result, ActionResult)
- assert result.error is None, f'Scroll up failed: {result.error}'
- assert result.extracted_content is not None
- assert 'Scrolled up' in result.extracted_content
- assert '0.5 pages' in result.extracted_content
-
- # Test 3: Test with invalid element index (should error)
- result = await tools.scroll(down=True, pages=1.0, index=999, browser_session=browser_session)
-
- # This should fail with error about element not found
- assert isinstance(result, ActionResult)
- assert result.error is not None, 'Expected error for invalid element index'
-
- async def test_scroll_with_cross_origin_disabled(self, browser_session, base_url):
- """Test that scroll works when cross_origin_iframes is disabled."""
- from browser_use.browser.events import ScrollEvent
-
- # Navigate to a page
- await browser_session._cdp_navigate(f'{base_url}/scrollable')
- await asyncio.sleep(0.5)
-
- # Test simple scroll - should not hang
- event = browser_session.event_bus.dispatch(ScrollEvent(direction='down', amount=500))
- result = await asyncio.wait_for(event, timeout=3.0)
- assert result is not None
-
- # Test scroll up
- event = browser_session.event_bus.dispatch(ScrollEvent(direction='up', amount=200))
- result = await asyncio.wait_for(event, timeout=3.0)
- assert result is not None
-
- async def test_scroll_non_scrollable_page(self, browser_session, base_url, http_server):
- """Test scrolling a page that's only 100px tall (not scrollable)."""
- from browser_use.browser.events import ScrollEvent
-
- # Add a non-scrollable page (content fits in viewport)
- http_server.expect_request('/non-scrollable').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Non-Scrollable Page</title>
- <style>
- body { margin: 0; padding: 10px; height: 80px; overflow: hidden; }
- .content { height: 60px; background: #f0f0f0; }
- </style>
- </head>
- <body>
- <div class="content">This page is too small to scroll</div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to non-scrollable page
- await browser_session._cdp_navigate(f'{base_url}/non-scrollable')
- await asyncio.sleep(0.5)
-
- # Get initial scroll position
- cdp_session = await browser_session.get_or_create_cdp_session()
- initial_scroll = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'window.pageYOffset', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- initial_y = initial_scroll.get('result', {}).get('value', 0)
-
- # Try to scroll down - should succeed but not actually move
- event = browser_session.event_bus.dispatch(ScrollEvent(direction='down', amount=500))
- await event
- result = await event.event_result(raise_if_any=True, raise_if_none=False)
- assert result is None
-
- # Check scroll position didn't change (page isn't scrollable)
- final_scroll = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'window.pageYOffset', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- final_y = final_scroll.get('result', {}).get('value', 0)
- assert final_y == initial_y, f'Scroll position changed on non-scrollable page: {initial_y} -> {final_y}'
-
- async def test_scroll_very_long_page(self, browser_session, base_url, http_server):
- """Test scrolling a very long page (over 10,000px) by 8,000px."""
- from browser_use.browser.events import ScrollEvent
-
- # Add a very long page
- http_server.expect_request('/very-long').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Very Long Page</title>
- <style>
- body { margin: 0; padding: 20px; }
- .content { height: 12000px; background: linear-gradient(to bottom, #f0f0f0, #333); }
- .marker { padding: 20px; background: #007bff; color: white; margin: 2000px 0; }
- </style>
- </head>
- <body>
- <h1 id="top">Very Long Page - Top</h1>
- <div class="content">
- <div class="marker" id="marker1">Marker 1 at 2000px</div>
- <div class="marker" id="marker2">Marker 2 at 4000px</div>
- <div class="marker" id="marker3">Marker 3 at 6000px</div>
- <div class="marker" id="marker4">Marker 4 at 8000px</div>
- <div class="marker" id="marker5">Marker 5 at 10000px</div>
- </div>
- <h1 id="bottom">Very Long Page - Bottom</h1>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to very long page
- await browser_session._cdp_navigate(f'{base_url}/very-long')
- await asyncio.sleep(0.5)
-
- # Get initial scroll position
- cdp_session = await browser_session.get_or_create_cdp_session()
- initial_scroll = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'window.pageYOffset', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- initial_y = initial_scroll.get('result', {}).get('value', 0)
- assert initial_y == 0, f'Page should start at top, but pageYOffset is {initial_y}'
-
- # Scroll down by 8000px
- event = browser_session.event_bus.dispatch(ScrollEvent(direction='down', amount=8000))
- await event
- result = await event.event_result(raise_if_any=True, raise_if_none=False)
- assert result is None # ScrollEvent does not return a result
-
- # Wait a bit for scroll to take effect
- await asyncio.sleep(0.5)
-
- # Check scroll position moved significantly
- final_scroll = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'window.pageYOffset', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- final_y = final_scroll.get('result', {}).get('value', 0)
-
- # Get page height to understand constraints
- page_height = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'document.body.scrollHeight', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- scroll_height = page_height.get('result', {}).get('value', 0)
-
- # Should have scrolled down significantly (might not be exactly 8000 due to viewport constraints)
- assert final_y > 5000, f'Expected to scroll significantly (page height: {scroll_height}px), but only at {final_y}px'
-
- # Verify we can see marker 4 which is at 8000px
- marker4_visible = await browser_session.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': """
- (() => {
- const marker = document.getElementById('marker4');
- const rect = marker.getBoundingClientRect();
- return rect.top >= 0 && rect.top <= window.innerHeight;
- })()
- """,
- 'returnByValue': True,
- },
- session_id=cdp_session.session_id,
- )
- assert marker4_visible.get('result', {}).get('value', False), 'Marker 4 should be visible after scrolling 8000px'
-
- async def test_scroll_iframe_content(self, browser_session, base_url, http_server):
- """Test scrolling inside a same-origin iframe."""
- from browser_use.browser.events import ScrollEvent
-
- # Add iframe content page
- http_server.expect_request('/iframe-content').respond_with_data(
- """
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- body { margin: 0; padding: 10px; }
- .content { height: 2000px; background: linear-gradient(to bottom, #e0e0e0, #666); }
- </style>
- </head>
- <body>
- <h2 id="iframe-top">Iframe Content - Top</h2>
- <div class="content">
- <div style="margin-top: 900px;">Middle of iframe content</div>
- <div style="margin-top: 900px;">Bottom of iframe content</div>
- </div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Add main page with iframe
- http_server.expect_request('/page-with-iframe').respond_with_data(
- f"""
- <!DOCTYPE html>
- <html>
- <head>
- <title>Page with Iframe</title>
- <style>
- body {{ margin: 0; padding: 20px; }}
- #main-content {{ height: 200px; background: #f0f0f0; }}
- #scrollable-iframe {{
- width: 100%;
- height: 400px;
- border: 2px solid #333;
- }}
- </style>
- </head>
- <body>
- <div id="main-content">
- <h1>Main Page Content</h1>
- <p>This is the main page with an embedded iframe below.</p>
- </div>
- <iframe id="scrollable-iframe" src="{base_url}/iframe-content"></iframe>
- <div style="height: 200px; background: #e0e0e0;">
- <p>Content after iframe</p>
- </div>
- </body>
- </html>
- """,
- content_type='text/html',
- )
-
- # Navigate to page with iframe
- await browser_session._cdp_navigate(f'{base_url}/page-with-iframe')
- await asyncio.sleep(1.0) # Give iframe time to load
-
- # Get initial scroll position of main page and iframe
- cdp_session = await browser_session.get_or_create_cdp_session()
-
- # Check main page scroll
- main_scroll = await browser_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'window.pageYOffset', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- main_y = main_scroll.get('result', {}).get('value', 0)
-
- # Check iframe scroll (should start at 0)
- iframe_initial = await browser_session.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': """
- (() => {
- const iframe = document.getElementById('scrollable-iframe');
- if (iframe && iframe.contentWindow) {
- return iframe.contentWindow.pageYOffset || 0;
- }
- return -1;
- })()
- """,
- 'returnByValue': True,
- },
- session_id=cdp_session.session_id,
- )
- iframe_y = iframe_initial.get('result', {}).get('value', -1)
- assert iframe_y == 0, f'Iframe should start at top, but pageYOffset is {iframe_y}'
-
- # Scroll the main page first to bring iframe into view
- event = browser_session.event_bus.dispatch(ScrollEvent(direction='down', amount=100))
- await asyncio.wait_for(event, timeout=3.0)
-
- # Now try to scroll inside the iframe
- # Note: This would require finding the iframe element and scrolling it specifically
- # For now, we just verify the iframe exists and is scrollable
- iframe_scrollable = await browser_session.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': """
- (() => {
- const iframe = document.getElementById('scrollable-iframe');
- if (iframe && iframe.contentDocument) {
- const iframeBody = iframe.contentDocument.body;
- return iframeBody.scrollHeight > iframe.clientHeight;
- }
- return false;
- })()
- """,
- 'returnByValue': True,
- },
- session_id=cdp_session.session_id,
- )
- assert iframe_scrollable.get('result', {}).get('value', False), 'Iframe should be scrollable'
diff --git a/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py b/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py
deleted file mode 100644
index a427c25d6..000000000
--- a/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py
+++ /dev/null
@@ -1,342 +0,0 @@
-"""Test full circle: download a file and then upload it back, verifying hash matches"""
-
-import asyncio
-import hashlib
-import tempfile
-from pathlib import Path
-
-import pytest
-from pytest_httpserver import HTTPServer
-
-from browser_use.browser import BrowserSession
-from browser_use.browser.events import BrowserStateRequestEvent, FileDownloadedEvent
-from browser_use.browser.profile import BrowserProfile
-from browser_use.filesystem.file_system import FileSystem
-from browser_use.tools.service import Tools
-
-
[email protected](scope='function')
-def download_upload_server():
- """Create a test HTTP server with download and upload endpoints."""
- server = HTTPServer()
- server.start()
-
- # Test file content and hash
- test_content = b'This is a test file for download-upload verification. Random: 12345'
- test_hash = hashlib.sha256(test_content).hexdigest()
-
- # Store uploaded files data
- uploaded_files = []
-
- # Add download endpoint
- server.expect_request('/download/test-file.txt').respond_with_data(
- test_content, content_type='text/plain', headers={'Content-Disposition': 'attachment; filename="test-file.txt"'}
- )
-
- # Add upload page
- upload_page_html = """
- <!DOCTYPE html>
- <html>
- <head>
- <title>Upload Test Page</title>
- </head>
- <body>
- <h1>File Upload Test</h1>
- <form id="uploadForm" action="/upload" method="POST" enctype="multipart/form-data">
- <input type="file" id="fileInput" name="file" />
- <button type="submit" id="submitButton">Upload File</button>
- </form>
- <div id="result"></div>
-
- <script>
- document.getElementById('uploadForm').addEventListener('submit', async (e) => {
- e.preventDefault();
- const formData = new FormData(e.target);
- const file = formData.get('file');
-
- if (file) {
- // Read file content
- const content = await file.text();
-
- // Calculate SHA256 hash
- const encoder = new TextEncoder();
- const data = encoder.encode(content);
- const hashBuffer = await crypto.subtle.digest('SHA-256', data);
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
-
- // Display result
- document.getElementById('result').innerHTML = `
- <p>File uploaded successfully!</p>
- <p>Filename: <span id="uploadedFileName">${file.name}</span></p>
- <p>Size: <span id="uploadedFileSize">${file.size}</span> bytes</p>
- <p>SHA256: <span id="uploadedFileHash">${hashHex}</span></p>
- `;
-
- // Send to server for verification
- fetch('/upload', {
- method: 'POST',
- body: formData
- });
- }
- });
- </script>
- </body>
- </html>
- """
-
- server.expect_request('/upload-page').respond_with_data(upload_page_html, content_type='text/html')
-
- # Handle upload POST request (for server-side verification)
- def handle_upload(request):
- # Store uploaded file info for verification
- if request.files and 'file' in request.files:
- file_data = request.files['file'][0]
- uploaded_files.append(
- {
- 'filename': file_data['filename'],
- 'content': file_data['body'],
- 'hash': hashlib.sha256(file_data['body']).hexdigest(),
- }
- )
- return request.make_response({'status': 'ok'})
-
- server.expect_request('/upload', method='POST').respond_with_handler(handle_upload)
-
- # Add download page with link
- download_page_html = f"""
- <!DOCTYPE html>
- <html>
- <head>
- <title>Download Test Page</title>
- </head>
- <body>
- <h1>File Download Test</h1>
- <a id="downloadLink" href="/download/test-file.txt">Download Test File</a>
- <p>Original file SHA256: <span id="originalHash">{test_hash}</span></p>
- </body>
- </html>
- """
-
- server.expect_request('/download-page').respond_with_data(download_page_html, content_type='text/html')
-
- # stop
- server.stop()
- # Skip complex HTTPServer attribute assignment - not supported
- pytest.skip('Complex HTTPServer attribute assignment not supported')
-
- yield server
- server.stop()
-
-
-class TestDownloadUploadFullCircle:
- """Test full circle: download a file and then upload it back"""
-
- async def test_download_then_upload_with_hash_verification(self, download_upload_server):
- """Download a file, then upload it to another page, verify hash matches"""
-
- # Create temporary directory for downloads
- with tempfile.TemporaryDirectory() as tmpdir:
- downloads_path = Path(tmpdir) / 'downloads'
- downloads_path.mkdir()
-
- # Create browser session with downloads enabled
- browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=True,
- downloads_path=str(downloads_path),
- user_data_dir=None,
- )
- )
-
- await browser_session.start()
-
- # Create tools and file system
- tools = Tools()
- file_system = FileSystem(base_dir=tmpdir)
-
- try:
- base_url = f'http://{download_upload_server.host}:{download_upload_server.port}'
-
- # Step 1: Navigate to download page
- result = await tools.navigate(url=f'{base_url}/download-page', new_tab=False, browser_session=browser_session)
- assert result.error is None, f'Navigation to download page failed: {result.error}'
-
- await asyncio.sleep(0.5)
-
- # Get browser state to find download link
- event = browser_session.event_bus.dispatch(BrowserStateRequestEvent())
- state_result = await event.event_result()
- assert state_result is not None
- assert state_result.dom_state is not None
-
- # Find download link by ID
- download_link_index = await browser_session.get_index_by_id('downloadLink')
- assert download_link_index is not None, 'Download link not found'
-
- # Step 2: Click download link and wait for download
- result = await tools.click(index=download_link_index, browser_session=browser_session)
- assert result.error is None, f'Click on download link failed: {result.error}'
-
- # Wait for the download event
- try:
- download_event = await browser_session.event_bus.expect(FileDownloadedEvent, timeout=10.0)
- downloaded_file_path = download_event.path
- except TimeoutError:
- pytest.fail('Download did not complete within timeout')
-
- assert downloaded_file_path is not None, 'Downloaded file path is None'
- assert Path(downloaded_file_path).exists(), f'Downloaded file does not exist: {downloaded_file_path}'
-
- # Verify download is tracked by browser_session
- assert downloaded_file_path in browser_session.downloaded_files, (
- f'Downloaded file not tracked by browser_session: {downloaded_file_path}'
- )
-
- # Calculate hash of downloaded file
- downloaded_content = Path(downloaded_file_path).read_bytes()
- downloaded_hash = hashlib.sha256(downloaded_content).hexdigest()
-
- print(f'✅ File downloaded: {downloaded_file_path}')
- print(f' Original hash: {download_upload_server.test_hash}')
- print(f' Downloaded hash: {downloaded_hash}')
- assert downloaded_hash == download_upload_server.test_hash, "Downloaded file hash doesn't match original"
-
- # Step 3: Navigate to upload page in a new tab
- print(f'\n🔄 Opening upload page in new tab: {base_url}/upload-page')
-
- # Debug: Check how many tabs we have before navigation
- tabs_before = await browser_session.get_tabs()
- print(f'📑 Tabs before navigation: {len(tabs_before)} tabs')
- for i, tab in enumerate(tabs_before):
- print(f' Tab {i}: {tab.url}')
- result = await tools.navigate(url=f'{base_url}/upload-page', new_tab=True, browser_session=browser_session)
- assert result.error is None, f'Navigation to upload page failed: {result.error}'
- print(f'✅ Navigation result: {result.extracted_content}')
-
- # The new tab should be automatically focused after opening
- await asyncio.sleep(2.0) # Give more time for the new tab to load and focus
-
- # Debug: Get all tabs
- tabs = await browser_session.get_tabs()
- print('\n📑 All tabs after opening upload page:')
- for i, tab in enumerate(tabs):
- print(f' Tab {i}: {tab.url} - {tab.title}')
-
- # Get browser state to find file input
- event = browser_session.event_bus.dispatch(BrowserStateRequestEvent())
- await event
- state_result = await event.event_result(raise_if_any=True, raise_if_none=False)
- assert state_result is not None
- assert state_result.dom_state is not None
- assert state_result.dom_state.selector_map is not None
-
- # Debug: print page URL and title
- print('\n🔍 Getting DOM state:')
- print(f' Current page URL: {state_result.url}')
- print(f' Current page title: {state_result.title}')
-
- # Find file input
- file_input_index = None
- input_elements = []
- for idx, element in state_result.dom_state.selector_map.items():
- if element.tag_name and element.tag_name.lower() == 'input':
- input_elements.append((idx, element.attributes))
- if element.attributes and element.attributes.get('type') == 'file':
- file_input_index = idx
- break
-
- print(f'Found {len(input_elements)} input elements: {input_elements}')
- assert file_input_index is not None, 'File input not found'
-
- # Step 4: Upload the downloaded file
- # The downloaded file should be automatically available for upload
- result = await tools.upload_file(
- index=file_input_index,
- path=downloaded_file_path,
- browser_session=browser_session,
- available_file_paths=[], # Empty, but file is in downloaded_files
- file_system=file_system,
- )
- assert result.error is None, f'File upload failed: {result.error}'
-
- # Step 4b: Click the submit button to trigger the form submission
- # Get browser state to find submit button
- event = browser_session.event_bus.dispatch(BrowserStateRequestEvent())
- state_result = await event.event_result()
-
- # Find submit button
- submit_button_index = None
- if state_result and state_result.dom_state:
- for idx, element in state_result.dom_state.selector_map.items():
- if (
- element.tag_name
- and element.tag_name.lower() == 'button'
- and element.attributes
- and element.attributes.get('id') == 'submitButton'
- ):
- submit_button_index = idx
- break
-
- assert submit_button_index is not None, 'Submit button not found'
-
- # Click the submit button
- result = await tools.click(index=submit_button_index, browser_session=browser_session)
- assert result.error is None, f'Click on submit button failed: {result.error}'
-
- # Wait for JavaScript to process the upload
- await asyncio.sleep(1.0)
-
- # Step 5: Verify upload via JavaScript (client-side hash)
- cdp_session = await browser_session.get_or_create_cdp_session()
-
- # Get uploaded file details from the page
- upload_verification = await browser_session.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': """
- (() => {
- const fileName = document.getElementById('uploadedFileName')?.textContent;
- const fileSize = document.getElementById('uploadedFileSize')?.textContent;
- const fileHash = document.getElementById('uploadedFileHash')?.textContent;
-
- return {
- fileName: fileName || null,
- fileSize: fileSize || null,
- fileHash: fileHash || null,
- hasResult: !!document.getElementById('result').textContent.includes('successfully')
- };
- })()
- """,
- 'returnByValue': True,
- },
- session_id=cdp_session.session_id,
- )
-
- upload_info = upload_verification.get('result', {}).get('value', {})
-
- # Verify upload was successful
- assert upload_info.get('hasResult') is True, 'Upload result not displayed'
- assert upload_info.get('fileName') == 'test-file.txt', (
- f'Uploaded filename mismatch: {upload_info.get("fileName")}'
- )
- assert upload_info.get('fileHash') == download_upload_server.test_hash, (
- f'Uploaded file hash mismatch. Expected: {download_upload_server.test_hash}, Got: {upload_info.get("fileHash")}'
- )
-
- print('✅ File uploaded successfully!')
- print(f' Uploaded filename: {upload_info.get("fileName")}')
- print(f' Uploaded hash: {upload_info.get("fileHash")}')
- print(f' Hash matches original: {upload_info.get("fileHash") == download_upload_server.test_hash}')
-
- # Step 6: Verify server-side upload (if needed)
- if download_upload_server.uploaded_files:
- server_file = download_upload_server.uploaded_files[0]
- assert server_file['hash'] == download_upload_server.test_hash, (
- f'Server-side hash mismatch. Expected: {download_upload_server.test_hash}, Got: {server_file["hash"]}'
- )
- print('✅ Server-side verification passed!')
-
- print('\n🎉 Full circle test passed: Download → Upload with hash verification!')
-
- finally:
- await browser_session.stop()