Skip to content

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

add tests for

Nick Sweetingaed2fa27bb69
diff --git a/tests/ci/test_browser_session_start.py b/tests/ci/test_browser_session_start.py
new file mode 100644
index 000000000..e07745088
--- /dev/null
+++ b/tests/ci/test_browser_session_start.py
@@ -0,0 +1,328 @@
+"""
+Test script for BrowserSession.start() method to ensure proper initialization,
+concurrency handling, and error handling.
+
+Tests cover:
+- Calling .start() on a session that's already started
+- Simultaneously calling .start() from two parallel coroutines
+- Calling .start() on a session that's started but has a closed browser connection
+- Calling .close() on a session that hasn't been started yet
+"""
+
+import asyncio
+import logging
+
+import pytest
+
+from browser_use.browser.profile import BrowserProfile
+from browser_use.browser.session import BrowserSession
+
+# Set up test logging
+logger = logging.getLogger('browser_session_start_tests')
+# logger.setLevel(logging.DEBUG)
+
+
+class TestBrowserSessionStart:
+ """Tests for BrowserSession.start() method initialization and concurrency."""
+
+ @pytest.fixture
+ async def browser_profile(self):
+ """Create and provide a BrowserProfile with headless mode."""
+ profile = BrowserProfile(headless=True, user_data_dir=None)
+ yield profile
+
+ @pytest.fixture
+ async def browser_session(self, browser_profile):
+ """Create a BrowserSession instance without starting it."""
+ session = BrowserSession(browser_profile=browser_profile)
+ yield session
+ # Cleanup: ensure session is stopped
+ try:
+ await session.stop()
+ except Exception:
+ pass
+
+ async def test_start_already_started_session(self, browser_session):
+ """Test calling .start() on a session that's already started."""
+ # logger.info('Testing start on already started session')
+
+ # Start the session for the first time
+ result1 = await browser_session.start()
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+ assert result1 is browser_session
+
+ # Start the session again - should return immediately without re-initialization
+ result2 = await browser_session.start()
+ assert result2 is browser_session
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+
+ # Both results should be the same instance
+ assert result1 is result2
+
+ async def test_concurrent_start_calls(self, browser_session):
+ """Test simultaneously calling .start() from two parallel coroutines."""
+ # logger.info('Testing concurrent start calls')
+
+ # Track how many times the lock is actually acquired for initialization
+ original_start_lock = browser_session._start_lock
+ lock_acquire_count = 0
+
+ class CountingLock:
+ def __init__(self, original_lock):
+ self.original_lock = original_lock
+
+ async def __aenter__(self):
+ nonlocal lock_acquire_count
+ lock_acquire_count += 1
+ return await self.original_lock.__aenter__()
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ return await self.original_lock.__aexit__(exc_type, exc_val, exc_tb)
+
+ browser_session._start_lock = CountingLock(original_start_lock)
+
+ # Start two concurrent calls to start()
+ results = await asyncio.gather(browser_session.start(), browser_session.start(), return_exceptions=True)
+
+ # Both should succeed and return the same session instance
+ assert all(result is browser_session for result in results)
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+
+ # The lock should have been acquired twice (once per coroutine)
+ # but only one should have done the actual initialization
+ assert lock_acquire_count == 2
+
+ async def test_start_with_closed_browser_connection(self, browser_session):
+ """Test calling .start() on a session that's started but has a closed browser connection."""
+ # logger.info('Testing start with closed browser connection')
+
+ # Start the session normally
+ await browser_session.start()
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+
+ # Simulate a closed browser connection by closing the browser
+ if browser_session.browser:
+ await browser_session.browser.close()
+
+ # The session should detect the closed connection and reinitialize
+ result = await browser_session.start()
+ assert result is browser_session
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+
+ async def test_start_with_missing_browser_context(self, browser_session):
+ """Test calling .start() when browser_context is None but initialized is True."""
+ # logger.info('Testing start with missing browser context')
+
+ # Manually set initialized to True but leave browser_context as None
+ browser_session.initialized = True
+ browser_session.browser_context = None
+
+ # Start should detect this inconsistent state and reinitialize
+ result = await browser_session.start()
+ assert result is browser_session
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+
+ async def test_start_initialization_failure(self, browser_session):
+ """Test that initialization failure properly resets the initialized flag."""
+ # logger.info('Testing start initialization failure')
+
+ # Mock setup_playwright to raise an exception
+ original_setup_playwright = browser_session.setup_playwright
+
+ async def failing_setup_playwright():
+ raise RuntimeError('Simulated initialization failure')
+
+ browser_session.setup_playwright = failing_setup_playwright
+
+ # Start should fail and reset initialized flag
+ with pytest.raises(RuntimeError, match='Simulated initialization failure'):
+ await browser_session.start()
+
+ assert browser_session.initialized is False
+
+ # Restore the original method and try again - should work
+ browser_session.setup_playwright = original_setup_playwright
+ result = await browser_session.start()
+ assert result is browser_session
+ assert browser_session.initialized is True
+
+ async def test_close_unstarted_session(self, browser_session):
+ """Test calling .close() on a session that hasn't been started yet."""
+ # logger.info('Testing close on unstarted session')
+
+ # Ensure session is not started
+ assert browser_session.initialized is False
+ assert browser_session.browser_context is None
+
+ # Close should not raise an exception
+ await browser_session.stop()
+
+ # State should remain unchanged
+ assert browser_session.initialized is False
+ assert browser_session.browser_context is None
+
+ async def test_close_alias_method(self, browser_session):
+ """Test the deprecated .close() alias method."""
+ # logger.info('Testing deprecated close alias method')
+
+ # Start the session
+ await browser_session.start()
+ assert browser_session.initialized is True
+
+ # Use the deprecated close method
+ await browser_session.close()
+
+ # Session should be stopped
+ assert browser_session.initialized is False
+
+ async def test_context_manager_usage(self, browser_session):
+ """Test using BrowserSession as an async context manager."""
+ # logger.info('Testing context manager usage')
+
+ # Use as context manager
+ async with browser_session as session:
+ assert session is browser_session
+ assert session.initialized is True
+ assert session.browser_context is not None
+
+ # Should be stopped after exiting context
+ assert browser_session.initialized is False
+
+ async def test_multiple_concurrent_operations_after_start(self, browser_session):
+ """Test that multiple operations can run concurrently after start() completes."""
+ # logger.info('Testing multiple concurrent operations after start')
+
+ # Start the session
+ await browser_session.start()
+
+ # Run multiple operations concurrently that require initialization
+ async def get_tabs():
+ return await browser_session.get_tabs_info()
+
+ async def get_current_page():
+ return await browser_session.get_current_page()
+
+ async def take_screenshot():
+ return await browser_session.take_screenshot()
+
+ # All operations should succeed concurrently
+ results = await asyncio.gather(get_tabs(), get_current_page(), take_screenshot(), return_exceptions=True)
+
+ # Check that all operations completed successfully
+ assert len(results) == 3
+ assert all(not isinstance(r, Exception) for r in results)
+
+ async def test_start_with_keep_alive_profile(self):
+ """Test start/stop behavior with keep_alive=True profile."""
+ # logger.info('Testing start with keep_alive profile')
+
+ profile = BrowserProfile(headless=True, user_data_dir=None, keep_alive=True)
+ session = BrowserSession(browser_profile=profile)
+
+ try:
+ await session.start()
+ assert session.initialized is True
+
+ # Stop should not actually close the browser with keep_alive=True
+ await session.stop()
+ # initialized flag should still be False after stop()
+ assert session.initialized is False
+
+ finally:
+ # Force cleanup for test
+ session.browser_profile.keep_alive = False
+ await session.stop()
+
+ async def test_require_initialization_decorator_already_started(self, browser_session):
+ """Test @require_initialization decorator when session is already started."""
+ # logger.info('Testing @require_initialization decorator with already started session')
+
+ # Start the session first
+ await browser_session.start()
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+
+ # Track if start() gets called again by monitoring the lock acquisition
+ original_start_lock = browser_session._start_lock
+ lock_acquire_count = 0
+
+ class CountingLock:
+ def __init__(self, original_lock):
+ self._original_lock = original_lock
+
+ async def __aenter__(self):
+ nonlocal lock_acquire_count
+ lock_acquire_count += 1
+ return await self._original_lock.__aenter__()
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ return await self._original_lock.__aexit__(exc_type, exc_val, exc_tb)
+
+ browser_session._start_lock = CountingLock(original_start_lock)
+
+ # Call a method decorated with @require_initialization
+ # This should work without calling start() again
+ tabs_info = await browser_session.get_tabs_info()
+
+ # Verify the method worked and start() wasn't called again (lock not acquired)
+ assert isinstance(tabs_info, list)
+ assert lock_acquire_count == 0 # start() should not have been called
+ assert browser_session.initialized is True
+
+ async def test_require_initialization_decorator_not_started(self, browser_session):
+ """Test @require_initialization decorator when session is not started."""
+ # logger.info('Testing @require_initialization decorator with unstarted session')
+
+ # Ensure session is not started
+ assert browser_session.initialized is False
+ assert browser_session.browser_context is None
+
+ # Track calls to start() method
+ original_start = browser_session.start
+ start_call_count = 0
+
+ async def counting_start():
+ nonlocal start_call_count
+ start_call_count += 1
+ return await original_start()
+
+ browser_session.start = counting_start
+
+ # Call a method that requires initialization
+ tabs_info = await browser_session.get_tabs_info()
+
+ # Verify the decorator called start() and the session is now initialized
+ assert start_call_count == 1 # start() should have been called once
+ assert browser_session.initialized is True
+ assert browser_session.browser_context is not None
+ assert isinstance(tabs_info, list) # Should return valid tabs info
+
+ async def test_require_initialization_decorator_with_closed_page(self, browser_session):
+ """Test @require_initialization decorator handles closed pages correctly."""
+ # logger.info('Testing @require_initialization decorator with closed page')
+
+ # Start the session and get a page
+ await browser_session.start()
+ current_page = await browser_session.get_current_page()
+ assert current_page is not None
+ assert not current_page.is_closed()
+
+ # Close the current page
+ await current_page.close()
+
+ # Call a method decorated with @require_initialization
+ # This should create a new tab since the current page is closed
+ tabs_info = await browser_session.get_tabs_info()
+
+ # Verify a new page was created
+ assert isinstance(tabs_info, list)
+ new_current_page = await browser_session.get_current_page()
+ assert new_current_page is not None
+ assert not new_current_page.is_closed()
+ assert new_current_page != current_page # Should be a different page
diff --git a/tests/ci/test_browser_session_tab_management.py b/tests/ci/test_browser_session_tab_management.py
index 57f970549..314de66b8 100644
--- a/tests/ci/test_browser_session_tab_management.py
+++ b/tests/ci/test_browser_session_tab_management.py
@@ -14,7 +14,7 @@ from browser_use.controller.service import Controller
# Set up test logging
logger = logging.getLogger('tab_tests')
-logger.setLevel(logging.DEBUG)
+# logger.setLevel(logging.DEBUG)
class TestTabManagement:
@@ -139,11 +139,11 @@ class TestTabManagement:
async def _simulate_human_tab_change(self, page, browser_session: BrowserSession):
"""Simulate a user changing tabs by properly triggering events with Playwright."""
- logger.debug(
- f'BEFORE: agent_tab={browser_session.agent_current_page.url if browser_session.agent_current_page else "None"}, '
- f'human_current_page={browser_session.human_current_page.url if browser_session.human_current_page else "None"}'
- )
- logger.debug(f'Simulating user changing to -> {page.url}')
+ # logger.debug(
+ # f'BEFORE: agent_tab={browser_session.agent_current_page.url if browser_session.agent_current_page else "None"}, '
+ # f'human_current_page={browser_session.human_current_page.url if browser_session.human_current_page else "None"}'
+ # )
+ # logger.debug(f'Simulating user changing to -> {page.url}')
# First bring the page to front - this is the physical action a user would take
await page.bring_to_front()
@@ -177,10 +177,10 @@ class TestTabManagement:
# Give the event handlers time to process
await asyncio.sleep(0.5)
- logger.debug(
- f'AFTER: agent_tab URL={browser_session.agent_current_page.url if browser_session.agent_current_page else "None"}, '
- f'human_current_page URL={browser_session.human_current_page.url if browser_session.human_current_page else "None"}'
- )
+ # logger.debug(
+ # f'AFTER: agent_tab URL={browser_session.agent_current_page.url if browser_session.agent_current_page else "None"}, '
+ # f'human_current_page URL={browser_session.human_current_page.url if browser_session.human_current_page else "None"}'
+ # )
# Tab management tests
diff --git a/tests/ci/test_browser_session_param.py b/tests/ci/test_registry_injected_params.py
similarity index 84%
rename from tests/ci/test_browser_session_param.py
rename to tests/ci/test_registry_injected_params.py
index 87ea2f89b..ec2e978b0 100644
--- a/tests/ci/test_browser_session_param.py
+++ b/tests/ci/test_registry_injected_params.py
@@ -99,7 +99,7 @@ async def main(browser_session):
This test confirms that this approach works.
"""
- logger.info('Starting browser_session parameter test')
+ # logger.info('Starting browser_session parameter test')
# Create registry
registry = Registry[TestContext]()
@@ -111,19 +111,19 @@ async def main(browser_session):
# Use the provided real browser session
# Test with the real issue: select_cell_or_range
- logger.info('\n\n=== Test: Simulating select_cell_or_range issue with correct model ===')
+ # logger.info('\n\n=== Test: Simulating select_cell_or_range issue with correct model ===')
# Define the function without using our registry - this will be a helper function
async def _select_cell_or_range(browser_session, cell_or_range):
"""Helper function for select_cell_or_range"""
- logger.info(f'_select_cell_or_range internal implementation called with cell_or_range={cell_or_range}')
+ # logger.info(f'_select_cell_or_range internal implementation called with cell_or_range={cell_or_range}')
return f'Selected cell {cell_or_range}'
# This simulates the actual issue we're seeing in the real code
# The browser_session parameter is in both the function signature and passed as a named arg
@registry.action('Google Sheets: Select a cell or range', param_model=CellRangeParams)
async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
- logger.info(f'select_cell_or_range called with browser_session={browser_session}, cell_or_range={cell_or_range}')
+ # logger.info(f'select_cell_or_range called with browser_session={browser_session}, cell_or_range={cell_or_range}')
# PROBLEMATIC LINE: browser_session is passed by name, matching the parameter name
# This is what causes the "got multiple values" error in the real code
@@ -132,7 +132,7 @@ async def main(browser_session):
# Fix attempt: Register a version that uses positional args instead
@registry.action('Google Sheets: Select a cell or range (fixed)', param_model=CellRangeParams)
async def select_cell_or_range_fixed(browser_session: BrowserSession, cell_or_range: str):
- logger.info(f'select_cell_or_range_fixed called with browser_session={browser_session}, cell_or_range={cell_or_range}')
+ # logger.info(f'select_cell_or_range_fixed called with browser_session={browser_session}, cell_or_range={cell_or_range}')
# FIXED LINE: browser_session is passed positionally, avoiding the parameter name conflict
return await _select_cell_or_range(browser_session, cell_or_range)
@@ -140,7 +140,7 @@ async def main(browser_session):
# Another attempt: explicitly call using **kwargs to simulate what the registry does
@registry.action('Google Sheets: Select with kwargs', param_model=CellRangeParams)
async def select_with_kwargs(browser_session: BrowserSession, cell_or_range: str):
- logger.info(f'select_with_kwargs called with browser_session={browser_session}, cell_or_range={cell_or_range}')
+ # logger.info(f'select_with_kwargs called with browser_session={browser_session}, cell_or_range={cell_or_range}')
# Get params and extra_args, like in Registry.execute_action
params = {'cell_or_range': cell_or_range, 'browser_session': browser_session}
@@ -149,60 +149,60 @@ async def main(browser_session):
# Try to call _select_cell_or_range with both params and extra_args
# This will fail with "got multiple values for keyword argument 'browser_session'"
try:
- logger.info('Attempting to call with both params and extra_args (should fail):')
+ # logger.info('Attempting to call with both params and extra_args (should fail):')
await _select_cell_or_range(**params, **extra_args)
except TypeError as e:
- logger.info(f'Expected error: {e}')
+ # logger.info(f'Expected error: {e}')
# Remove browser_session from params to avoid the conflict
params_fixed = dict(params)
del params_fixed['browser_session']
- logger.info(f'Fixed params: {params_fixed}')
+ # logger.info(f'Fixed params: {params_fixed}')
# This should work
result = await _select_cell_or_range(**params_fixed, **extra_args)
- logger.info(f'Success after fix: {result}')
+ # logger.info(f'Success after fix: {result}')
return result
# Test the original problematic version
- logger.info('\n--- Testing original problematic version ---')
+ # logger.info('\n--- Testing original problematic version ---')
try:
result1 = await registry.execute_action(
'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
)
- logger.info(f'Success! Result: {result1}')
+ # logger.info(f'Success! Result: {result1}')
except Exception as e:
logger.error(f'Error: {str(e)}')
# Test the fixed version (using positional args)
- logger.info('\n--- Testing fixed version (positional args) ---')
+ # logger.info('\n--- Testing fixed version (positional args) ---')
try:
result2 = await registry.execute_action(
'select_cell_or_range_fixed', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
)
- logger.info(f'Success! Result: {result2}')
+ # logger.info(f'Success! Result: {result2}')
except Exception as e:
logger.error(f'Error: {str(e)}')
# Test with kwargs version that simulates what Registry.execute_action does
- logger.info('\n--- Testing kwargs simulation version ---')
+ # logger.info('\n--- Testing kwargs simulation version ---')
try:
result3 = await registry.execute_action(
'select_with_kwargs', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
)
- logger.info(f'Success! Result: {result3}')
+ # logger.info(f'Success! Result: {result3}')
except Exception as e:
logger.error(f'Error: {str(e)}')
# Manual test of our theory: browser_session is passed twice
- logger.info('\n--- Direct test of our theory ---')
+ # logger.info('\n--- Direct test of our theory ---')
try:
# Create the model instance
params = CellRangeParams(cell_or_range='A1:F100')
# First check if the extra_args approach works
- logger.info('Checking if extra_args approach works:')
+ # logger.info('Checking if extra_args approach works:')
extra_args = {'browser_session': browser_session}
# If we were to modify Registry.execute_action:
@@ -212,23 +212,23 @@ async def main(browser_session):
# Create params dict
param_dict = params.model_dump()
- logger.info(f'params dict before: {param_dict}')
+ # logger.info(f'params dict before: {param_dict}')
# Apply our fix: remove browser_session from params dict
for key in browser_keys:
if key in param_dict and key in extra_args:
- logger.info(f'Removing {key} from params dict')
+ # logger.info(f'Removing {key} from params dict')
del param_dict[key]
- logger.info(f'params dict after: {param_dict}')
- logger.info(f'extra_args: {extra_args}')
+ # logger.info(f'params dict after: {param_dict}')
+ # logger.info(f'extra_args: {extra_args}')
# This would be the fixed code:
# return await action.function(**param_dict, **extra_args)
# Call directly to test
result3 = await select_cell_or_range(**param_dict, **extra_args)
- logger.info(f'Success with our fix! Result: {result3}')
+ # logger.info(f'Success with our fix! Result: {result3}')
except Exception as e:
logger.error(f'Error with our manual test: {str(e)}')
diff --git a/tests/test_stress.py b/tests/test_stress.py
index 9b4a666e9..1b00bb3dc 100644
--- a/tests/test_stress.py
+++ b/tests/test_stress.py
@@ -76,14 +76,13 @@ async def test_token_limit_with_multiple_extractions(llm, controller, browser_se
@pytest.mark.slow
@pytest.mark.parametrize('max_tokens', [4000]) # 8000 20000
-async def test_open_3_tabs_and_extract_content(llm, controller, context, max_tokens):
+async def test_open_3_tabs_and_extract_content(llm, controller, browser_session, max_tokens):
"""Stress test: Open 3 tabs with urls and extract content"""
agent = Agent(
task='Open 3 tabs with https://en.wikipedia.org/wiki/Internet and extract the content from each.',
llm=llm,
controller=controller,
- browser_context=context,
+ browser_session=browser_session,
max_input_tokens=max_tokens,
save_conversation_path='tmp/stress_test/test_open_3_tabs_and_extract_content.json',
)
@@ -98,4 +97,5 @@ async def test_open_3_tabs_and_extract_content(llm, controller, context, max_tok
errors = history.errors()
assert len(errors) == 0, 'Errors occurred during the test'
# check if 3 tabs were opened
- assert len(context.current_state.tabs) >= 3, '3 tabs were not opened'
+ current_state = await browser_session.get_state_summary()
+ assert len(current_state.tabs) >= 3, '3 tabs were not opened'
diff --git a/tests/test_vision.py b/tests/test_vision.py
index f0a9e9205..a3049e010 100644
--- a/tests/test_vision.py
+++ b/tests/test_vision.py
@@ -10,15 +10,12 @@ from pprint import pprint
import pytest
-from browser_use.browser.browser import Browser, BrowserConfig
-
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-import asyncio
from langchain_openai import ChatOpenAI
-from browser_use import Agent, AgentHistoryList, Controller
+from browser_use import Agent, AgentHistoryList, BrowserSession, Controller
llm = ChatOpenAI(model='gpt-4o')
controller = Controller()
@@ -41,21 +38,13 @@ async def done(text: str) -> str:
return 'call explain_screen'
[email protected](scope='function')
-def event_loop():
- """Create an instance of the default event loop for each test case."""
- loop = asyncio.get_event_loop_policy().new_event_loop()
- yield loop
- loop.close()
-
-
@pytest.mark.skip(reason='this is for local testing only')
async def test_vision():
agent = Agent(
task='call explain_screen all the time the user asks you questions e.g. about the page like bbox which you see are labels - your task is to explain it and get the next question',
llm=llm,
controller=controller,
- browser=Browser(config=BrowserConfig(disable_security=True, headless=False)),
+ browser_session=BrowserSession(headless=False, user_data_dir=None),
)
try:
history: AgentHistoryList = await agent.run(20)