Skip to content

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

Tests

Magnus Müllerdaa74ddcfe3c
diff --git a/tests/ci/interaction/__init__.py b/tests/ci/interaction/__init__.py
deleted file mode 100644
index 99490f658..000000000
--- a/tests/ci/interaction/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Interaction tests for complex user flows with reactive frameworks."""
diff --git a/tests/ci/interaction/conftest.py b/tests/ci/interaction/conftest.py
deleted file mode 100644
index e003f21ea..000000000
--- a/tests/ci/interaction/conftest.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Fixtures for interaction tests."""
-
-import pytest
-
-from browser_use.tools.service import Tools
-
-
-def tools():
- """Create and provide a Tools instance."""
- return Tools()
diff --git a/tests/ci/interaction/test_dropdown_react_submit.py b/tests/ci/interaction/test_dropdown_react_submit.py
deleted file mode 100644
index f220e2afd..000000000
--- a/tests/ci/interaction/test_dropdown_react_submit.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""
-Test React dropdown selection with form submission.
-
-This test verifies that dropdown selections work correctly with React's
-controlled components and state management.
-"""
-
-
-class TestReactDropdownSubmit:
- """Test React dropdown with controlled components and form submission."""
-
- async def test_react_dropdown_selection_with_submit(self, tools, browser_session, httpserver):
- """Test that React dropdown selections persist and submit correctly."""
- # Simple React page with dropdown + submit button
- html_content = """
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>React Dropdown Test</title>
- <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
- <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
- <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
- <style>
- body { font-family: Arial, sans-serif; padding: 20px; }
- .container { max-width: 400px; margin: 0 auto; }
- label { display: block; margin: 10px 0 5px; font-weight: bold; }
- select { width: 100%; padding: 8px; font-size: 16px; }
- button { margin-top: 20px; padding: 10px 20px; background: #61dafb; color: #282c34; border: none; cursor: pointer; font-size: 16px; font-weight: bold; }
- button:hover { background: #4fa8c5; }
- .result { margin-top: 20px; padding: 10px; background: #f0f0f0; border-radius: 4px; }
- </style>
- </head>
- <body>
- <div id="root"></div>
-
- <script type="text/babel">
- const { useState } = React;
-
- function DropdownForm() {
- const [employmentStatus, setEmploymentStatus] = useState('fullTime');
- const [hireType, setHireType] = useState('');
- const [submitted, setSubmitted] = useState(false);
- const [submittedData, setSubmittedData] = useState({});
-
- const handleSubmit = (e) => {
- e.preventDefault();
-
- // This validates that React state properly captured the selections
- const data = {
- employmentStatus,
- hireType
- };
-
- setSubmittedData(data);
- setSubmitted(true);
-
- // Send to server for validation
- fetch('/submit', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(data)
- });
- };
-
- return (
- <div className="container">
- <h2>React Dropdown Form</h2>
-
- <form onSubmit={handleSubmit}>
- <label htmlFor="employment-status">
- Employment Status *
- </label>
- <select
- id="employment-status"
- value={employmentStatus}
- onChange={(e) => setEmploymentStatus(e.target.value)}
- required
- >
- <option value="fullTime">Full Time</option>
- <option value="partTime">Part Time</option>
- </select>
-
- <label htmlFor="hire-type">
- Hire Type *
- </label>
- <select
- id="hire-type"
- value={hireType}
- onChange={(e) => setHireType(e.target.value)}
- required
- >
- <option value="">Select Type</option>
- <option value="w-2">W-2</option>
- <option value="1099">1099</option>
- <option value="k-1">K-1</option>
- <option value="test">Test</option>
- </select>
-
- <button type="submit">Submit</button>
- </form>
-
- {submitted && (
- <div className="result">
- <h3>Form Submitted Successfully!</h3>
- <p><strong>Employment Status:</strong> {submittedData.employmentStatus}</p>
- <p><strong>Hire Type:</strong> {submittedData.hireType}</p>
- </div>
- )}
- </div>
- );
- }
-
- const root = ReactDOM.createRoot(document.getElementById('root'));
- root.render(<DropdownForm />);
- </script>
- </body>
- </html>
- """
-
- httpserver.expect_request('/react-dropdown').respond_with_data(html_content, content_type='text/html')
-
- # Server-side validation endpoint
- received_data = []
-
- def handle_submit(request):
- import json
-
- data = json.loads(request.get_data(as_text=True))
- received_data.append(data)
- return json.dumps({'success': True, 'received': data})
-
- httpserver.expect_request('/submit', method='POST').respond_with_handler(handle_submit)
-
- # Navigate to the React form
- base_url = httpserver.url_for('/')
-
- result = await tools.navigate(url=f'{base_url}react-dropdown', new_tab=False, browser_session=browser_session)
- assert result.error is None
-
- # Wait for React to initialize
- import asyncio
-
- await asyncio.sleep(1)
-
- # Get browser state to find dropdown elements
- await browser_session.get_browser_state_summary()
-
- # Find the dropdowns by ID
- employment_status_element = await browser_session.get_index_by_id('employment-status')
- hire_type_element = await browser_session.get_index_by_id('hire-type')
-
- assert employment_status_element is not None, 'Could not find employment-status dropdown'
- assert hire_type_element is not None, 'Could not find hire-type dropdown'
-
- # Select "Part Time" from employment status dropdown
- result = await tools.select_dropdown(index=employment_status_element, text='Part Time', browser_session=browser_session)
- assert result.error is None, f'Failed to select employment status: {result.error}'
-
- # Select "W-2" from hire type dropdown
- result = await tools.select_dropdown(index=hire_type_element, text='W-2', browser_session=browser_session)
- assert result.error is None, f'Failed to select hire type: {result.error}'
-
- # Find and click the submit button
- await browser_session.get_browser_state_summary()
- selector_map = await browser_session.get_selector_map()
- submit_button = None
-
- for idx, element in selector_map.items():
- if element.tag_name == 'button' and element.attributes.get('type') == 'submit':
- submit_button = idx
- break
-
- assert submit_button is not None, 'Could not find submit button'
-
- # Click the submit button
- result = await tools.click(index=submit_button, browser_session=browser_session)
- assert result.error is None, f'Failed to click submit: {result.error}'
-
- # Wait for submission
- await asyncio.sleep(1)
-
- # Verify the form was submitted with correct values
- assert len(received_data) > 0, 'No data was submitted to server'
- submitted = received_data[0]
-
- # THIS IS THE KEY TEST: React state should have captured both selections
- assert submitted['employmentStatus'] == 'partTime', f"Expected 'partTime', got {submitted['employmentStatus']}"
- assert submitted['hireType'] == 'w-2', f"Expected 'w-2', got {submitted['hireType']}"
-
- # Also verify the result is displayed on the page using CDP
- cdp_session = await browser_session.get_or_create_cdp_session()
- page_text_result = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'document.body.textContent', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- page_text = page_text_result.get('result', {}).get('value', '').lower()
-
- assert 'form submitted successfully' in page_text, 'Success message not found'
- assert 'part time' in page_text, 'Employment status not displayed in result'
- assert 'w-2' in page_text, 'Hire type not displayed in result'
diff --git a/tests/ci/interaction/test_dropdown_vue_submit.py b/tests/ci/interaction/test_dropdown_vue_submit.py
deleted file mode 100644
index 3e69713cb..000000000
--- a/tests/ci/interaction/test_dropdown_vue_submit.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""
-Test Vue.js dropdown selection with form submission.
-
-This test verifies that dropdown selections persist through Vue's v-model
-and are correctly submitted with the form. This was the bug reported in issue #3415.
-"""
-
-
-class TestVueDropdownSubmit:
- """Test Vue.js dropdown with v-model and form submission."""
-
- async def test_vue_dropdown_selection_with_submit(self, tools, browser_session, httpserver):
- """Test that Vue.js dropdown selections persist and submit correctly."""
- # Simple Vue.js page with dropdown + submit button
- html_content = """
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Vue Dropdown Test</title>
- <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js"></script>
- <style>
- body { font-family: Arial, sans-serif; padding: 20px; }
- .container { max-width: 400px; margin: 0 auto; }
- label { display: block; margin: 10px 0 5px; font-weight: bold; }
- select { width: 100%; padding: 8px; font-size: 16px; }
- button { margin-top: 20px; padding: 10px 20px; background: #4CAF50; color: white; border: none; cursor: pointer; font-size: 16px; }
- button:hover { background: #45a049; }
- #result { margin-top: 20px; padding: 10px; background: #f0f0f0; border-radius: 4px; }
- </style>
- </head>
- <body>
- <div id="app" class="container">
- <h2>Vue.js Dropdown Form</h2>
-
- <form @submit.prevent="submitForm">
- <label for="pay-frequency">Pay Frequency *</label>
- <select id="pay-frequency" v-model="payFrequency" required>
- <option value="">Select Frequency</option>
- <option value="peryear">per year</option>
- <option value="perhour">per hour</option>
- </select>
-
- <label for="hire-type">Hire Type *</label>
- <select id="hire-type" v-model="hireType" required>
- <option value="">Select Type</option>
- <option value="w-2">W-2</option>
- <option value="1099">1099</option>
- <option value="k-1">K-1</option>
- <option value="test">Test</option>
- </select>
-
- <button type="submit">Submit</button>
- </form>
-
- <div id="result" v-if="submitted">
- <h3>Form Submitted Successfully!</h3>
- <p><strong>Pay Frequency:</strong> {{ submittedData.payFrequency }}</p>
- <p><strong>Hire Type:</strong> {{ submittedData.hireType }}</p>
- </div>
- </div>
-
- <script>
- const { createApp } = Vue;
-
- createApp({
- data() {
- return {
- payFrequency: '',
- hireType: '',
- submitted: false,
- submittedData: {}
- };
- },
- methods: {
- submitForm() {
- // This validates that Vue's v-model properly captured the selections
- this.submittedData = {
- payFrequency: this.payFrequency,
- hireType: this.hireType
- };
- this.submitted = true;
-
- // Also send to server for validation
- fetch('/submit', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(this.submittedData)
- });
- }
- }
- }).mount('#app');
- </script>
- </body>
- </html>
- """
-
- httpserver.expect_request('/vue-dropdown').respond_with_data(html_content, content_type='text/html')
-
- # Server-side validation endpoint
- received_data = []
-
- def handle_submit(request):
- import json
-
- data = json.loads(request.get_data(as_text=True))
- received_data.append(data)
- return json.dumps({'success': True, 'received': data})
-
- httpserver.expect_request('/submit', method='POST').respond_with_handler(handle_submit)
-
- # Navigate to the Vue.js form
- base_url = httpserver.url_for('/')
-
- result = await tools.navigate(url=f'{base_url}vue-dropdown', new_tab=False, browser_session=browser_session)
- assert result.error is None
-
- # Wait for Vue to initialize
- import asyncio
-
- await asyncio.sleep(0.5)
-
- # Get browser state to find dropdown elements
- await browser_session.get_browser_state_summary()
-
- # Find the dropdowns by ID
- pay_freq_element = await browser_session.get_index_by_id('pay-frequency')
- hire_type_element = await browser_session.get_index_by_id('hire-type')
-
- assert pay_freq_element is not None, 'Could not find pay-frequency dropdown'
- assert hire_type_element is not None, 'Could not find hire-type dropdown'
-
- # Select "per hour" from pay frequency dropdown
- result = await tools.select_dropdown(index=pay_freq_element, text='per hour', browser_session=browser_session)
- assert result.error is None, f'Failed to select pay frequency: {result.error}'
-
- # Select "1099" from hire type dropdown
- result = await tools.select_dropdown(index=hire_type_element, text='1099', browser_session=browser_session)
- assert result.error is None, f'Failed to select hire type: {result.error}'
-
- # Find and click the submit button
- await browser_session.get_browser_state_summary()
- selector_map = await browser_session.get_selector_map()
- submit_button = None
-
- for idx, element in selector_map.items():
- if element.tag_name == 'button' and element.attributes.get('type') == 'submit':
- submit_button = idx
- break
-
- assert submit_button is not None, 'Could not find submit button'
-
- # Click the submit button
- result = await tools.click(index=submit_button, browser_session=browser_session)
- assert result.error is None, f'Failed to click submit: {result.error}'
-
- # Wait for submission
- await asyncio.sleep(1)
-
- # Verify the form was submitted with correct values
- assert len(received_data) > 0, 'No data was submitted to server'
- submitted = received_data[0]
-
- # THIS IS THE KEY TEST: Vue's v-model should have captured both selections
- assert submitted['payFrequency'] == 'perhour', f"Expected 'perhour', got {submitted['payFrequency']}"
- assert submitted['hireType'] == '1099', f"Expected '1099', got {submitted['hireType']}"
-
- # Also verify the result is displayed on the page using CDP
- cdp_session = await browser_session.get_or_create_cdp_session()
- page_text_result = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'document.body.textContent', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- page_text = page_text_result.get('result', {}).get('value', '').lower()
-
- assert 'form submitted successfully' in page_text, 'Success message not found'
- assert 'per hour' in page_text, 'Pay frequency not displayed in result'
- assert '1099' in page_text, 'Hire type not displayed in result'
diff --git a/tests/ci/test_actor_page_press.py b/tests/ci/test_actor_page_press.py
index 65475c457..6118d3fa0 100644
--- a/tests/ci/test_actor_page_press.py
+++ b/tests/ci/test_actor_page_press.py
@@ -216,7 +216,6 @@ async def test_press_key_combinations(browser_session, httpserver: HTTPServer):
assert a_down_events[0]['ctrlKey'] is True, 'Control modifier should be active when pressing "a"'
-
async def test_press_arrow_keys_game_simulation(browser_session, httpserver: HTTPServer):
"""Test arrow keys in a 2048-like game scenario."""
# Simulate a simple game that responds to arrow keys
diff --git a/tests/ci/test_browser_session_element_cache.py b/tests/ci/test_browser_session_element_cache.py
index 45b21c500..6cc94c354 100644
--- a/tests/ci/test_browser_session_element_cache.py
+++ b/tests/ci/test_browser_session_element_cache.py
@@ -3,6 +3,8 @@ Systematic debugging of the selector map issue.
Test each assumption step by step to isolate the problem.
"""
+import asyncio
+
import pytest
from browser_use.browser import BrowserSession
@@ -11,12 +13,13 @@ from browser_use.tools.service import Tools
@pytest.fixture
-def httpserver(make_httpserver):
- """Create and provide a test HTTP server that serves static content."""
- server = make_httpserver
+def test_server(httpserver):
+ """Create and provide a test HTTP server with properly configured routes."""
+ # Clear any existing expectations to avoid conflicts
+ httpserver.clear()
# Add routes for test pages
- server.expect_request('/').respond_with_data(
+ httpserver.expect_request('/').respond_with_data(
"""<html>
<head><title>Test Home Page</title></head>
<body>
@@ -30,7 +33,7 @@ def httpserver(make_httpserver):
content_type='text/html',
)
- server.expect_request('/page1').respond_with_data(
+ httpserver.expect_request('/page1').respond_with_data(
"""<html>
<head><title>Test Page 1</title></head>
<body>
@@ -42,7 +45,7 @@ def httpserver(make_httpserver):
content_type='text/html',
)
- server.expect_request('/simple').respond_with_data(
+ httpserver.expect_request('/simple').respond_with_data(
"""<html>
<head><title>Simple Page</title></head>
<body>
@@ -54,7 +57,7 @@ def httpserver(make_httpserver):
content_type='text/html',
)
- return server
+ return httpserver
@pytest.fixture
@@ -78,16 +81,18 @@ def tools():
@pytest.mark.asyncio
-async def test_assumption_1_dom_processing_works(browser_session, httpserver):
+async def test_assumption_1_dom_processing_works(browser_session, test_server):
"""Test assumption 1: DOM processing works and finds elements."""
# Go to a simple page using CDP events
from browser_use.browser.events import NavigateToUrlEvent
- event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))
+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/')))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
# Trigger DOM processing
+ # sleep for 1 second
+ await asyncio.sleep(1)
state = await browser_session.get_browser_state_summary()
print('DOM processing result:')
@@ -99,12 +104,12 @@ async def test_assumption_1_dom_processing_works(browser_session, httpserver):
@pytest.mark.asyncio
-async def test_assumption_2_cached_selector_map_persists(browser_session, httpserver):
+async def test_assumption_2_cached_selector_map_persists(browser_session, test_server):
"""Test assumption 2: Cached selector map persists after get_state_summary."""
# Go to a simple page using CDP events
from browser_use.browser.events import NavigateToUrlEvent
- event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))
+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/')))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
@@ -126,12 +131,12 @@ async def test_assumption_2_cached_selector_map_persists(browser_session, httpse
@pytest.mark.asyncio
-async def test_assumption_3_action_gets_same_selector_map(browser_session, tools, httpserver):
+async def test_assumption_3_action_gets_same_selector_map(browser_session, tools, test_server):
"""Test assumption 3: Action gets the same selector map as cached."""
# Go to a simple page using CDP events
from browser_use.browser.events import NavigateToUrlEvent
- event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))
+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/')))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
@@ -164,12 +169,12 @@ async def test_assumption_3_action_gets_same_selector_map(browser_session, tools
@pytest.mark.asyncio
-async def test_assumption_4_click_action_specific_issue(browser_session, tools, httpserver):
+async def test_assumption_4_click_action_specific_issue(browser_session, tools, test_server):
"""Test assumption 4: Specific issue with click action."""
# Go to a simple page using CDP events
from browser_use.browser.events import NavigateToUrlEvent
- event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))
+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/')))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
@@ -222,12 +227,12 @@ async def test_assumption_4_click_action_specific_issue(browser_session, tools,
@pytest.mark.asyncio
-async def test_assumption_5_multiple_get_selector_map_calls(browser_session, httpserver):
+async def test_assumption_5_multiple_get_selector_map_calls(browser_session, test_server):
"""Test assumption 5: Multiple calls to get_selector_map return consistent results."""
# Go to a simple page using CDP events
from browser_use.browser.events import NavigateToUrlEvent
- event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))
+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/')))
await event
await event.event_result(raise_if_any=True, raise_if_none=False)