Skip to content

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

fix tests

Nick Sweetingce264fb9f934
diff --git a/tests/ci/test_agent_sensitive_data.py b/tests/ci/test_agent_sensitive_data.py
index d2b8f664a..4edada7aa 100644
--- a/tests/ci/test_agent_sensitive_data.py
+++ b/tests/ci/test_agent_sensitive_data.py
@@ -42,7 +42,12 @@ def test_replace_sensitive_data_with_missing_keys(registry, caplog):
# Set log level to capture warnings
import logging
- caplog.set_level(logging.WARNING)
+ # Temporarily enable propagation for browser_use logger to capture logs
+ browser_use_logger = logging.getLogger('browser_use')
+ original_propagate = browser_use_logger.propagate
+ browser_use_logger.propagate = True
+
+ caplog.set_level(logging.WARNING, logger='browser_use.controller.registry.service')
# Create a simple Pydantic model with sensitive data placeholders
params = SensitiveParams(text='Please enter <secret>username</secret> and <secret>password</secret>')
@@ -83,13 +88,21 @@ def test_replace_sensitive_data_with_missing_keys(registry, caplog):
assert 'password' in caplog.text
caplog.clear()
+ # Restore original propagate setting
+ browser_use_logger.propagate = original_propagate
+
def test_simple_domain_specific_sensitive_data(registry, caplog):
"""Test the basic functionality of domain-specific sensitive data replacement"""
# Set log level to capture warnings
import logging
- caplog.set_level(logging.WARNING)
+ # Temporarily enable propagation for browser_use logger to capture logs
+ browser_use_logger = logging.getLogger('browser_use')
+ original_propagate = browser_use_logger.propagate
+ browser_use_logger.propagate = True
+
+ caplog.set_level(logging.WARNING, logger='browser_use.controller.registry.service')
# Create a simple Pydantic model with sensitive data placeholders
params = SensitiveParams(text='Please enter <secret>username</secret> and <secret>password</secret>')
@@ -115,6 +128,9 @@ def test_simple_domain_specific_sensitive_data(registry, caplog):
assert 'password' in caplog.text # Only password should be logged as missing
caplog.clear()
+ # Restore original propagate setting
+ browser_use_logger.propagate = original_propagate
+
def test_match_url_with_domain_pattern():
"""Test that the domain pattern matching utility works correctly"""
diff --git a/tests/ci/test_browser_session_start.py b/tests/ci/test_browser_session_start.py
index 86053d818..28fc6ca24 100644
--- a/tests/ci/test_browser_session_start.py
+++ b/tests/ci/test_browser_session_start.py
@@ -493,13 +493,23 @@ class TestBrowserSessionStart:
async def test_user_data_dir_not_allowed_to_corrupt_default_profile(self, caplog):
"""Test user_data_dir handling for different browser channels and version mismatches."""
+ import logging
+
+ # Temporarily enable propagation for browser_use logger to capture logs
+ browser_use_logger = logging.getLogger('browser_use')
+ original_propagate = browser_use_logger.propagate
+ browser_use_logger.propagate = True
+
+ caplog.set_level(logging.WARNING, logger='browser_use.utils')
# Test 1: Chromium with default user_data_dir and default channel should work fine
session = BrowserSession(
- headless=True,
- user_data_dir=BROWSERUSE_CHROMIUM_USER_DATA_DIR,
- channel=BROWSERUSE_DEFAULT_CHANNEL, # chromium
- keep_alive=False,
+ browser_profile=BrowserProfile(
+ headless=True,
+ user_data_dir=BROWSER_USE_DEFAULT_USER_DATA_DIR,
+ channel=BROWSERUSE_DEFAULT_CHANNEL, # chromium
+ keep_alive=False,
+ ),
)
try:
@@ -529,6 +539,9 @@ class TestBrowserSessionStart:
)
assert warning_found, 'Expected warning about changing user_data_dir was not found'
+ # Restore original propagate setting
+ browser_use_logger.propagate = original_propagate
+
# only run if `/Applications/Brave Browser.app` is installed
@pytest.mark.skipif(
not Path('~/.config/browseruse/profiles/stealth').expanduser().exists(), reason='Brave Browser not installed'
@@ -546,9 +559,11 @@ class TestBrowserSessionStart:
# await brave_session.stop()
chromium_session = BrowserSession(
- headless=True,
- user_data_dir='~/.config/browseruse/profiles/stealth',
- channel=BrowserChannel.CHROMIUM, # should crash when opened with chromium
+ browser_profile=BrowserProfile(
+ headless=True,
+ user_data_dir='~/.config/browseruse/profiles/stealth',
+ channel=BrowserChannel.CHROMIUM, # should crash when opened with chromium
+ ),
)
# open chrome with corrupted user_data_dir
@@ -652,9 +667,11 @@ class TestBrowserSessionReusePatterns:
# Create a reusable session with keep_alive
reused_session = BrowserSession(
- user_data_dir=None, # Use temp dir for testing
- headless=True,
- keep_alive=True, # Don't close browser after agent.run()
+ browser_profile=BrowserProfile(
+ user_data_dir=None, # Use temp dir for testing
+ headless=True,
+ keep_alive=True, # Don't close browser after agent.run()
+ ),
)
try:
@@ -711,10 +728,12 @@ class TestBrowserSessionReusePatterns:
storage_state_path = Path(storage_state_path)
shared_browser = BrowserSession(
- storage_state=storage_state_path,
- user_data_dir=None,
- keep_alive=True,
- headless=True,
+ browser_profile=BrowserProfile(
+ storage_state=storage_state_path,
+ user_data_dir=None,
+ keep_alive=True,
+ headless=True,
+ ),
)
try:
@@ -792,7 +811,7 @@ class TestBrowserSessionReusePatterns:
)
# Run all agents in parallel
- results = await asyncio.gather(agent1.run(), agent2.run(), agent3.run())
+ _results = await asyncio.gather(agent1.run(), agent2.run(), agent3.run())
# Verify all agents used the same browser session (using __eq__ to check browser_pid, cdp_url, wss_url)
# Debug: print the browser sessions to see what's different
@@ -826,9 +845,11 @@ class TestBrowserSessionReusePatterns:
# Create a browser session and start it first
shared_browser = BrowserSession(
- user_data_dir=None,
- headless=True,
- keep_alive=True, # Keep the browser alive for reuse
+ browser_profile=BrowserProfile(
+ user_data_dir=None,
+ headless=True,
+ keep_alive=True, # Keep the browser alive for reuse
+ ),
)
try:
@@ -857,7 +878,7 @@ class TestBrowserSessionReusePatterns:
await page.goto(httpserver.url_for('/'), wait_until='domcontentloaded')
# Run agents in parallel (may interfere with each other)
- results = await asyncio.gather(agent1.run(), agent2.run(), return_exceptions=True)
+ _results = await asyncio.gather(agent1.run(), agent2.run(), return_exceptions=True)
# Verify both agents used the same browser session
assert agent1.browser_session == agent2.browser_session
@@ -907,7 +928,7 @@ class TestBrowserSessionReusePatterns:
)
# Run agents in parallel
- results = await asyncio.gather(agent1.run(), agent2.run())
+ _results = await asyncio.gather(agent1.run(), agent2.run())
# Verify different browser sessions were used
assert agent1.browser_session is not agent2.browser_session
diff --git a/tests/ci/test_sync_agent_events.py b/tests/ci/test_sync_agent_events.py
index 2dff3c116..61790958a 100644
--- a/tests/ci/test_sync_agent_events.py
+++ b/tests/ci/test_sync_agent_events.py
@@ -5,20 +5,18 @@ Tests the most critical event flows without excessive duplication.
"""
import base64
-import json
import os
-from unittest.mock import AsyncMock, MagicMock, Mock, patch
+from unittest.mock import patch
from uuid import UUID
import pytest
from dotenv import load_dotenv
-# Load environment variables before any imports
load_dotenv()
-from langchain_core.language_models import BaseChatModel
-from langchain_core.messages import AIMessage
-from pytest_httpserver import HTTPServer
+from bubus import BaseEvent
+
+from browser_use import Agent
from browser_use.agent.cloud_events import (
MAX_TASK_LENGTH,
CreateAgentOutputFileEvent,
@@ -27,126 +25,14 @@ from browser_use.agent.cloud_events import (
CreateAgentTaskEvent,
UpdateAgentTaskEvent,
)
-
-# Skip LLM API key verification for tests
-os.environ['SKIP_LLM_API_KEY_VERIFICATION'] = 'true'
-
-from bubus import BaseEvent
-
-from browser_use import Agent
-from browser_use.browser import BrowserSession
-from browser_use.sync.service import CloudSync
-from tests.ci.mocks import create_mock_llm
-
-
-async def browser_session():
- """Create a real browser session for testing"""
- session = BrowserSession(
- headless=True,
- user_data_dir=None, # Use temporary directory
- )
- yield session
- await session.stop()
-
-
-def mock_llm():
- """Create a mock LLM that immediately returns done action"""
- llm = MagicMock(spec=BaseChatModel)
-
- # Create the JSON response that the agent would parse
- json_response = {
- 'thinking': 'null',
- 'evaluation_previous_goal': 'Starting task',
- 'memory': 'New task to complete',
- 'next_goal': 'Complete the test task',
- 'action': [{'done': {'success': True, 'text': 'Test completed successfully'}}],
- }
-
- # Create a mock response with the JSON
- mock_response = AIMessage(content=json.dumps(json_response))
-
- # Make the LLM return our mock response
- llm.invoke = lambda *args, **kwargs: mock_response
- llm.ainvoke = AsyncMock(return_value=mock_response)
-
- # Mock the with_structured_output method to return parsed objects
- structured_llm = MagicMock()
-
- async def mock_structured_ainvoke(*args, **kwargs):
- # The agent will create its own AgentOutput and ActionModel classes
- # We return the raw response and let the agent parse it
- return {
- 'raw': mock_response,
- 'parsed': None, # Let the agent parse it from the raw JSON
- }
-
- structured_llm.ainvoke = AsyncMock(side_effect=mock_structured_ainvoke)
- llm.with_structured_output = lambda *args, **kwargs: structured_llm
-
- # Set attributes that agent checks
- llm.model_name = 'gpt-4o'
- llm._verified_api_keys = True
- llm._verified_tool_calling_method = 'function_calling'
-
- return llm
-
-
-def event_collector():
- """Collect all events emitted during tests"""
- events = []
- event_order = []
-
- class EventCollector:
- def __init__(self):
- self.events = events
- self.event_order = event_order
-
- async def collect_event(self, event: BaseEvent):
- self.events.append(event)
- self.event_order.append(event.event_type)
- return 'collected'
-
- def get_events_by_type(self, event_type: str) -> list[BaseEvent]:
- return [e for e in self.events if e.event_type == event_type]
-
- def clear(self):
- self.events.clear()
- self.event_order.clear()
-
- return EventCollector()
-
-
-def mock_cloud_sync():
- """Create mocked cloud sync service."""
- sync = Mock(spec=CloudSync)
- sync.send_event = AsyncMock()
- sync.authenticate = AsyncMock(return_value=True)
- sync._authenticated = True
- sync.handle_event = AsyncMock()
- return sync
-
-
-def agent_with_cloud(browser_session, mock_cloud_sync):
- """Create agent with cloud sync enabled."""
- with patch('browser_use.sync.CloudSync', return_value=mock_cloud_sync):
- with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'true'}):
- agent = Agent(
- task='Test task',
- llm=create_mock_llm(),
- browser_session=browser_session,
- )
- return agent
+from tests.ci.conftest import create_mock_llm
class TestAgentEventLifecycle:
"""Test critical agent event flows with minimal duplication"""
- async def test_agent_lifecycle_events(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
+ @pytest.mark.usefixtures('mock_llm', 'browser_session', 'event_collector', 'httpserver')
+ async def test_agent_lifecycle_events(self, mock_llm, browser_session, event_collector, httpserver):
"""Test that all events are emitted in the correct order during agent lifecycle"""
# Setup a test page
@@ -155,23 +41,19 @@ class TestAgentEventLifecycle:
# Navigate to test page
await browser_session.navigate(httpserver.url_for('/'))
- # Patch environment variables to use localhost for CloudSync
- with patch.dict(
- os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000', 'BROWSER_USE_CLOUD_UI_URL': 'http://localhost:3000'}
- ):
- # Create agent
- agent = Agent(
- task='Test task',
- llm=mock_llm,
- browser_session=browser_session,
- generate_gif=False, # Don't generate GIF for faster test
- )
+ # Create agent (environment already set up by conftest.py)
+ agent = Agent(
+ task='Test task',
+ llm=mock_llm,
+ browser_session=browser_session,
+ generate_gif=False, # Don't generate GIF for faster test
+ )
- # Subscribe to all events
- agent.eventbus.on('*', event_collector.collect_event)
+ # Subscribe to all events
+ agent.eventbus.on('*', event_collector.collect_event)
- # Run the agent
- history = await agent.run(max_steps=5)
+ # Run the agent
+ history = await agent.run(max_steps=5)
# Verify we got a successful completion
assert history.is_done()
@@ -213,30 +95,28 @@ class TestAgentEventLifecycle:
assert update_event.id == task_event.id
assert update_event.done_output is not None
- async def test_agent_with_gif_generation(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
+ @pytest.mark.usefixtures('mock_llm', 'browser_session', 'event_collector', 'httpserver')
+ async def test_agent_with_gif_generation(self, mock_llm, browser_session, cloud_sync, event_collector, httpserver):
"""Test that GIF generation triggers CreateAgentOutputFileEvent"""
# Setup a test page
httpserver.expect_request('/').respond_with_data('<html><body><h1>GIF Test</h1></body></html>', content_type='text/html')
await browser_session.navigate(httpserver.url_for('/'))
- # Patch environment variables to use localhost for CloudSync
- with patch.dict(
- os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000', 'BROWSER_USE_CLOUD_UI_URL': 'http://localhost:3000'}
- ):
- # Create agent with GIF generation
- agent = Agent(
- task='Test task with GIF',
- llm=mock_llm,
- browser_session=browser_session,
- generate_gif=True, # Enable GIF generation
- )
+ # Create agent with GIF generation
+ agent = Agent(
+ task='Test task with GIF',
+ llm=mock_llm,
+ browser_session=browser_session,
+ generate_gif=True, # Enable GIF generation
+ cloud_sync=cloud_sync,
+ )
- # Subscribe to all events
- agent.eventbus.on('*', event_collector.collect_event)
+ # Subscribe to all events
+ agent.eventbus.on('*', event_collector.collect_event)
- # Run the agent
- history = await agent.run(max_steps=5)
+ # Run the agent
+ _history = await agent.run(max_steps=5)
# Verify CreateAgentOutputFileEvent was emitted
output_file_events = event_collector.get_events_by_type('CreateAgentOutputFileEvent')
@@ -255,7 +135,8 @@ class TestAgentEventLifecycle:
assert gif_bytes.startswith(b'GIF87a') or gif_bytes.startswith(b'GIF89a')
assert len(gif_bytes) > 100 # Should be a real GIF file
- async def test_step_screenshot_capture(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
+ @pytest.mark.usefixtures('mock_llm', 'browser_session', 'event_collector', 'httpserver')
+ async def test_step_screenshot_capture(self, mock_llm, browser_session, cloud_sync, event_collector, httpserver):
"""Test that screenshots are captured for each step"""
# Setup test page
@@ -264,23 +145,20 @@ class TestAgentEventLifecycle:
)
await browser_session.navigate(httpserver.url_for('/'))
- # Patch environment variables to use localhost for CloudSync
- with patch.dict(
- os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000', 'BROWSER_USE_CLOUD_UI_URL': 'http://localhost:3000'}
- ):
- # Create agent
- agent = Agent(
- task='Test screenshot capture',
- llm=mock_llm,
- browser_session=browser_session,
- generate_gif=False,
- )
+ # Create agent
+ agent = Agent(
+ task='Test screenshot capture',
+ llm=mock_llm,
+ browser_session=browser_session,
+ generate_gif=False,
+ cloud_sync=cloud_sync,
+ )
- # Subscribe to all events
- agent.eventbus.on('*', event_collector.collect_event)
+ # Subscribe to all events
+ agent.eventbus.on('*', event_collector.collect_event)
- # Run the agent
- await agent.run(max_steps=3)
+ # Run the agent
+ await agent.run(max_steps=3)
# Get all step events
step_events = event_collector.get_events_by_type('CreateAgentStepEvent')
@@ -304,75 +182,107 @@ class TestAgentEventLifecycle:
class TestAgentCloudIntegration:
"""Test that agent properly integrates with cloud sync service"""
- async def test_agent_emits_events_to_cloud(self, agent_with_cloud, mock_cloud_sync):
+ @pytest.mark.usefixtures('agent_with_cloud', 'event_collector', 'httpserver')
+ async def test_agent_emits_events_to_cloud(self, agent_with_cloud, event_collector, httpserver):
"""Test that agent emits all required events to cloud sync."""
+ # Set up httpserver to capture events
+ captured_events = []
+
+ def capture_events(request):
+ data = request.get_json()
+ captured_events.extend(data.get('events', []))
+ from werkzeug.wrappers import Response
+
+ return Response(
+ '{"processed": 1, "failed": 0, "results": [{"success": true}]}', status=200, mimetype='application/json'
+ )
+
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_events)
+
+ # Subscribe to eventbus to verify events
+ agent_with_cloud.eventbus.on('*', event_collector.collect_event)
+
# Run agent
await agent_with_cloud.run()
- # Check that events were sent to cloud sync
- calls = mock_cloud_sync.handle_event.call_args_list
- assert len(calls) >= 4 # At minimum: session, task, step, update
+ # Verify we have the core event types in eventbus
+ assert len(event_collector.event_order) >= 4 # At minimum: session, task, step, update
+ assert 'CreateAgentSessionEvent' in event_collector.event_order
+ assert 'CreateAgentTaskEvent' in event_collector.event_order
+ assert 'CreateAgentStepEvent' in event_collector.event_order
+ assert 'UpdateAgentTaskEvent' in event_collector.event_order
- # Verify we have the core event types
- event_types = [call.args[0].event_type for call in calls]
- assert 'CreateAgentSessionEvent' in event_types
- assert 'CreateAgentTaskEvent' in event_types
- assert 'CreateAgentStepEvent' in event_types
- assert 'UpdateAgentTaskEvent' in event_types
+ # Verify events were sent to cloud
+ assert len(captured_events) >= 4
- # Verify event content
- session_events = [call for call in calls if call.args[0].event_type == 'CreateAgentSessionEvent']
- task_events = [call for call in calls if call.args[0].event_type == 'CreateAgentTaskEvent']
- step_events = [call for call in calls if call.args[0].event_type == 'CreateAgentStepEvent']
+ # Verify event relationships using event_collector
+ session_events = event_collector.get_events_by_type('CreateAgentSessionEvent')
+ task_events = event_collector.get_events_by_type('CreateAgentTaskEvent')
+ step_events = event_collector.get_events_by_type('CreateAgentStepEvent')
assert len(session_events) == 1
assert len(task_events) == 1
assert len(step_events) >= 1
# Verify event relationships
- session_event = session_events[0].args[0]
- task_event = task_events[0].args[0]
- step_event = step_events[0].args[0]
+ session_event = session_events[0]
+ task_event = task_events[0]
+ step_event = step_events[0]
assert task_event.agent_session_id == session_event.id
assert step_event.agent_task_id == task_event.id
- async def test_agent_emits_session_start_event(self, agent_with_cloud, mock_cloud_sync):
+ @pytest.mark.usefixtures('agent_with_cloud', 'event_collector', 'httpserver')
+ async def test_agent_emits_session_start_event(self, agent_with_cloud, event_collector, httpserver):
"""Test that agent emits session start event."""
+ # Set up httpserver endpoint
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_json(
+ {'processed': 1, 'failed': 0, 'results': [{'success': True}]}
+ )
+
+ # Subscribe to events
+ agent_with_cloud.eventbus.on('*', event_collector.collect_event)
+
# Run agent
await agent_with_cloud.run()
# Check that session start event was sent
- calls = mock_cloud_sync.handle_event.call_args_list
- session_events = [call for call in calls if call.args[0].event_type == 'CreateAgentSessionEvent']
+ session_events = event_collector.get_events_by_type('CreateAgentSessionEvent')
assert len(session_events) == 1
- event = session_events[0].args[0]
+ event = session_events[0]
assert hasattr(event, 'id')
assert hasattr(event, 'browser_session_id')
- async def test_agent_emits_task_events(self, agent_with_cloud, mock_cloud_sync):
+ @pytest.mark.usefixtures('agent_with_cloud', 'event_collector', 'httpserver')
+ async def test_agent_emits_task_events(self, agent_with_cloud, event_collector, httpserver):
"""Test that agent emits task events."""
+ # Set up httpserver endpoint
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_json(
+ {'processed': 1, 'failed': 0, 'results': [{'success': True}]}
+ )
+
+ # Subscribe to events
+ agent_with_cloud.eventbus.on('*', event_collector.collect_event)
+
# Run agent
await agent_with_cloud.run()
# Check task events
- calls = mock_cloud_sync.handle_event.call_args_list
-
- # Should have CreateAgentTaskEvent
- create_task_events = [call for call in calls if call.args[0].event_type == 'CreateAgentTaskEvent']
+ create_task_events = event_collector.get_events_by_type('CreateAgentTaskEvent')
assert len(create_task_events) == 1
- create_event = create_task_events[0].args[0]
+ create_event = create_task_events[0]
assert create_event.task == 'Test task'
assert hasattr(create_event, 'agent_session_id')
# Should have UpdateAgentTaskEvent when done
- update_task_events = [call for call in calls if call.args[0].event_type == 'UpdateAgentTaskEvent']
+ update_task_events = event_collector.get_events_by_type('UpdateAgentTaskEvent')
assert len(update_task_events) >= 1
+ @pytest.mark.usefixtures('browser_session')
async def test_cloud_sync_disabled(self, browser_session):
"""Test that cloud sync can be disabled."""
- with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'false'}):
+ with patch.dict(os.environ, {'BROWSER_USE_CLOUD_SYNC': 'false'}):
agent = Agent(
task='Test task',
llm=create_mock_llm(),
@@ -384,75 +294,75 @@ class TestAgentCloudIntegration:
# Run agent - should work without cloud sync
await agent.run()
- async def test_agent_error_resilience(self, agent_with_cloud, mock_cloud_sync):
+ @pytest.mark.usefixtures('agent_with_cloud', 'httpserver')
+ async def test_agent_error_resilience(self, agent_with_cloud, httpserver):
"""Test that agent continues working even if cloud sync fails."""
- # Make cloud sync fail
- mock_cloud_sync.handle_event.side_effect = Exception('Cloud sync error')
- # Run agent - should not raise exception
+ # Make cloud endpoint fail
+ def fail_handler(request):
+ from werkzeug.wrappers import Response
+
+ return Response('Server error', status=500, mimetype='text/plain')
+
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(fail_handler)
+
+ # Run agent - should not raise exception despite cloud sync failures
result = await agent_with_cloud.run()
# Agent should complete successfully despite sync failures
assert result is not None
assert result.is_done()
- # Verify cloud sync was attempted
- assert mock_cloud_sync.handle_event.call_count > 0
-
- async def test_session_id_persistence(self, browser_session):
+ @pytest.mark.usefixtures('browser_session', 'cloud_sync', 'event_collector', 'httpserver')
+ async def test_session_id_persistence(self, browser_session, cloud_sync, event_collector, httpserver):
"""Test that agent session ID persists across runs."""
- mock_sync = Mock(spec=CloudSync)
- mock_sync.send_event = AsyncMock()
- mock_sync.handle_event = AsyncMock()
- mock_sync._authenticated = True
-
- with patch('browser_use.sync.CloudSync', return_value=mock_sync):
- with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'true'}):
- # Create first agent
- agent1 = Agent(
- task='First task',
- llm=create_mock_llm(),
- browser_session=browser_session,
- )
- agent1.cloud_sync = mock_sync
-
- # Run first agent
- await agent1.run()
-
- # Get session ID from first run
- session_calls = [
- call for call in mock_sync.handle_event.call_args_list if call.args[0].event_type == 'CreateAgentSessionEvent'
- ]
- session_id_1 = session_calls[0].args[0].id
-
- # Create second agent (will have different session ID)
- agent2 = Agent(
- task='Second task',
- llm=create_mock_llm(),
- browser_session=browser_session,
- )
- agent2.cloud_sync = mock_sync
-
- # Clear previous calls
- mock_sync.handle_event.reset_mock()
-
- # Run second agent
- await agent2.run()
-
- # Should create new session for new agent
- session_calls_2 = [
- call for call in mock_sync.handle_event.call_args_list if call.args[0].event_type == 'CreateAgentSessionEvent'
- ]
- assert len(session_calls_2) == 1 # New session created
-
- # Should create new task with new session ID
- task_calls = [
- call for call in mock_sync.handle_event.call_args_list if call.args[0].event_type == 'CreateAgentTaskEvent'
- ]
- assert len(task_calls) == 1
- session_id_2 = session_calls_2[0].args[0].id
- assert task_calls[0].args[0].agent_session_id == session_id_2
- assert session_id_2 != session_id_1 # Different session IDs
+ # Set up httpserver endpoint
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_json(
+ {'processed': 1, 'failed': 0, 'results': [{'success': True}]}
+ )
+
+ # Create first agent
+ agent1 = Agent(
+ task='First task',
+ llm=create_mock_llm(),
+ browser_session=browser_session,
+ cloud_sync=cloud_sync,
+ )
+ agent1.eventbus.on('*', event_collector.collect_event)
+
+ # Run first agent
+ await agent1.run()
+
+ # Get session ID from first run
+ session_events = event_collector.get_events_by_type('CreateAgentSessionEvent')
+ assert len(session_events) == 1
+ session_id_1 = session_events[0].id
+
+ # Clear event collector
+ event_collector.clear()
+
+ # Create second agent (will have different session ID)
+ agent2 = Agent(
+ task='Second task',
+ llm=create_mock_llm(),
+ browser_session=browser_session,
+ cloud_sync=cloud_sync,
+ )
+ agent2.eventbus.on('*', event_collector.collect_event)
+
+ # Run second agent
+ await agent2.run()
+
+ # Should create new session for new agent
+ session_events_2 = event_collector.get_events_by_type('CreateAgentSessionEvent')
+ assert len(session_events_2) == 1 # New session created
+ session_id_2 = session_events_2[0].id
+
+ # Should create new task with new session ID
+ task_events = event_collector.get_events_by_type('CreateAgentTaskEvent')
+ assert len(task_events) == 1
+ assert task_events[0].agent_session_id == session_id_2
+ assert session_id_2 != session_id_1 # Different session IDs
class TestEventValidation:
@@ -475,6 +385,10 @@ class TestEventValidation:
agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c651',
task='test',
llm_model='gpt-4o',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
),
CreateAgentStepEvent(
user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
@@ -484,6 +398,7 @@ class TestEventValidation:
memory='mem',
next_goal='next',
actions=[],
+ screenshot_url='data:image/png;...',
),
]
@@ -512,12 +427,23 @@ class TestEventValidation:
agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
llm_model='test-model',
task=long_task,
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
def test_event_type_assignment(self):
"""Test that event_type is properly set and validated"""
event = CreateAgentTaskEvent(
- user_id='test', agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659', llm_model='test-model', task='test'
+ user_id='test',
+ agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
+ llm_model='test-model',
+ task='test',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
# Event type should be automatically set
diff --git a/tests/ci/test_sync_client.py b/tests/ci/test_sync_client.py
index c5e05bd37..f541e67e3 100644
--- a/tests/ci/test_sync_client.py
+++ b/tests/ci/test_sync_client.py
@@ -21,24 +21,10 @@ def temp_config_dir():
temp_dir = Path(tmpdir) / '.config' / 'browseruse'
temp_dir.mkdir(parents=True, exist_ok=True)
- # Temporarily replace the config dir
- import browser_use.sync.auth
- import browser_use.utils
-
- original_auth = getattr(browser_use.sync.auth, 'BROWSER_USE_CONFIG_DIR', None)
- original_utils = getattr(browser_use.utils, 'BROWSER_USE_CONFIG_DIR', None)
-
- browser_use.sync.auth.BROWSER_USE_CONFIG_DIR = temp_dir
- browser_use.utils.BROWSER_USE_CONFIG_DIR = temp_dir
+ os.environ['BROWSER_USE_CONFIG_DIR'] = str(temp_dir)
yield temp_dir
- # Restore original
- if original_auth:
- browser_use.sync.auth.BROWSER_USE_CONFIG_DIR = original_auth
- if original_utils:
- browser_use.utils.BROWSER_USE_CONFIG_DIR = original_utils
-
@pytest.fixture
async def http_client(httpserver: HTTPServer):
@@ -107,7 +93,7 @@ class TestCloudSyncEventHandling:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Send event
await authenticated_sync.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Test task', priority='high'))
@@ -127,7 +113,7 @@ class TestCloudSyncEventHandling:
async def test_event_queueing_unauthenticated(self, httpserver: HTTPServer, unauthenticated_sync):
"""Test event queueing when unauthenticated."""
# Server returns 401
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_json({'error': 'unauthorized'}, status=401)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_json({'error': 'unauthorized'}, status=401)
# Send event
await unauthenticated_sync.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Queued task'))
@@ -149,7 +135,7 @@ class TestCloudSyncEventHandling:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Send event without user_id
await unauthenticated_sync.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Pre-auth task'))
@@ -185,7 +171,7 @@ class TestCloudSyncRetryLogic:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Manually add pending events (simulating 401 scenario)
sync_with_auth.pending_events.extend(
@@ -219,7 +205,7 @@ class TestCloudSyncRetryLogic:
async def test_backend_error_resilience(self, httpserver: HTTPServer, sync_with_auth):
"""Test resilience to backend errors."""
# Server returns 500 error
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_data('Internal Server Error', status=500)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_data('Internal Server Error', status=500)
# Should not raise exception
await sync_with_auth.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Task during outage'))
@@ -249,7 +235,7 @@ class TestCloudSyncRetryLogic:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Send multiple events concurrently
tasks = []
@@ -294,7 +280,7 @@ class TestCloudSyncBackendCommunication:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Create authenticated service
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
@@ -324,7 +310,7 @@ class TestCloudSyncBackendCommunication:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Test authenticated request
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
@@ -389,7 +375,7 @@ class TestCloudSyncErrorHandling:
error_codes = [400, 403, 404, 429, 500, 502, 503]
for status_code in error_codes:
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_json(
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_json(
{'error': f'Test error {status_code}'}, status=status_code
)
@@ -399,7 +385,7 @@ class TestCloudSyncErrorHandling:
async def test_invalid_response_handling(self, httpserver: HTTPServer, sync_service):
"""Test handling of invalid server responses."""
# Return invalid JSON
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_data('Not JSON', status=200)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_data('Not JSON', status=200)
# Should not raise exception
await sync_service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Invalid response test'))
@@ -415,7 +401,7 @@ class TestCloudSyncErrorHandling:
event_type: str = 'RestrictedEvent'
data: str = 'test'
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_json({'processed': 1}, status=200)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_json({'processed': 1}, status=200)
# Should not raise exception - will log debug message about not being able to set user_id
await sync_service.handle_event(RestrictedEvent())
@@ -441,7 +427,7 @@ class TestCloudSyncErrorHandling:
return Response('{"processed": 1}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(handler)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(handler)
# Send 10 events concurrently
tasks = []
diff --git a/tests/ci/test_sync_client_auth.py b/tests/ci/test_sync_client_auth.py
index 6f8055a26..72d4dfaf8 100644
--- a/tests/ci/test_sync_client_auth.py
+++ b/tests/ci/test_sync_client_auth.py
@@ -59,23 +59,23 @@ async def http_client(httpserver: HTTPServer):
class TestDeviceAuthClient:
"""Test DeviceAuthClient class."""
- async def test_init_creates_config_dir(self, temp_config_dir):
+ async def test_init_creates_config_dir(self, temp_config_dir, test_base_url):
"""Test that initialization creates config directory."""
- auth = DeviceAuthClient()
+ auth = DeviceAuthClient(base_url=test_base_url)
assert temp_config_dir.exists()
assert (temp_config_dir / 'cloud_auth.json').exists() is False
- async def test_load_credentials_no_file(self, temp_config_dir):
+ async def test_load_credentials_no_file(self, temp_config_dir, test_base_url):
"""Test loading credentials when file doesn't exist."""
- auth = DeviceAuthClient()
+ auth = DeviceAuthClient(base_url=test_base_url)
# When no file exists, auth_config should have no token/user_id
assert auth.auth_config.api_token is None
assert auth.auth_config.user_id is None
assert not auth.is_authenticated
- async def test_save_and_load_credentials(self, temp_config_dir):
+ async def test_save_and_load_credentials(self, temp_config_dir, test_base_url):
"""Test saving and loading credentials."""
- auth = DeviceAuthClient()
+ auth = DeviceAuthClient(base_url=test_base_url)
# Update auth config and save
auth.auth_config.api_token = 'test-key-123'
@@ -84,7 +84,7 @@ class TestDeviceAuthClient:
auth.auth_config.save_to_file()
# Load in a new instance
- auth2 = DeviceAuthClient()
+ auth2 = DeviceAuthClient(base_url=test_base_url)
assert auth2.auth_config.api_token == 'test-key-123'
assert auth2.auth_config.user_id == 'test-user-123'
assert auth2.is_authenticated
@@ -94,9 +94,9 @@ class TestDeviceAuthClient:
stat = (temp_config_dir / 'cloud_auth.json').stat()
assert oct(stat.st_mode)[-3:] == '600'
- async def test_is_authenticated(self, temp_config_dir):
+ async def test_is_authenticated(self, temp_config_dir, test_base_url):
"""Test authentication status check."""
- auth = DeviceAuthClient()
+ auth = DeviceAuthClient(base_url=test_base_url)
# Not authenticated initially
assert auth.is_authenticated is False
@@ -107,12 +107,12 @@ class TestDeviceAuthClient:
auth.auth_config.save_to_file()
# Reload to verify persistence
- auth2 = DeviceAuthClient()
+ auth2 = DeviceAuthClient(base_url=test_base_url)
assert auth2.is_authenticated is True
- async def test_get_credentials(self, temp_config_dir):
+ async def test_get_credentials(self, temp_config_dir, test_base_url):
"""Test getting credentials."""
- auth = DeviceAuthClient()
+ auth = DeviceAuthClient(base_url=test_base_url)
# No credentials initially
assert auth.api_token is None
@@ -299,9 +299,9 @@ class TestDeviceAuthClient:
assert result is None # Should timeout and return None
assert not auth.is_authenticated
- async def test_logout(self, temp_config_dir):
+ async def test_logout(self, temp_config_dir, test_base_url):
"""Test logout functionality."""
- auth = DeviceAuthClient()
+ auth = DeviceAuthClient(base_url=test_base_url)
# Save credentials directly using auth_config
auth.auth_config.api_token = 'test-key'
@@ -319,7 +319,7 @@ class TestDeviceAuthClient:
assert (temp_config_dir / 'cloud_auth.json').exists()
# Verify the file contains empty credentials
- auth2 = DeviceAuthClient()
+ auth2 = DeviceAuthClient(base_url=test_base_url)
assert auth2.auth_config.api_token is None
assert auth2.auth_config.user_id is None
@@ -327,14 +327,14 @@ class TestDeviceAuthClient:
class TestCloudSync:
"""Test CloudSync class."""
- async def test_init(self, temp_config_dir):
+ async def test_init(self, temp_config_dir, test_base_url):
"""Test CloudSync initialization."""
service = CloudSync(
- base_url='https://cloud.browser-use.com',
+ base_url=test_base_url,
enable_auth=True,
)
- assert service.base_url == 'https://cloud.browser-use.com'
+ assert service.base_url == test_base_url
assert service.enable_auth is True
assert service.auth_client is not None
assert isinstance(service.auth_client, DeviceAuthClient)
@@ -355,7 +355,7 @@ class TestCloudSync:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Create authenticated service
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
@@ -405,7 +405,7 @@ class TestCloudSync:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Create unauthenticated service
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
@@ -461,7 +461,7 @@ class TestCloudSync:
# Subsequent requests: success
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(handle_events_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(handle_events_request)
# Create service with unauthenticated auth client
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
@@ -503,7 +503,7 @@ class TestCloudSync:
async def test_error_handling(self, httpserver: HTTPServer, temp_config_dir):
"""Test error handling during event sending."""
# Set up server to return 500 error
- httpserver.expect_request('/api/v1/events/', method='POST').respond_with_data('Internal Server Error', status=500)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_data('Internal Server Error', status=500)
# Create service with real auth
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
@@ -645,7 +645,7 @@ class TestIntegration:
# Set up events endpoint
httpserver.expect_request(
- '/api/v1/events/',
+ '/api/v1/events',
method='POST',
).respond_with_json({'processed': 1, 'failed': 0})
@@ -715,7 +715,7 @@ class TestAuthResilience:
# Now simulate token expiry by returning 401 errors
httpserver.expect_request(
- '/api/v1/events/',
+ '/api/v1/events',
method='POST',
).respond_with_json({'error': 'unauthorized', 'detail': 'Token expired'}, status=401)
@@ -753,7 +753,7 @@ class TestAuthResilience:
# Set up events endpoint to handle unauthenticated requests
httpserver.expect_request(
- '/api/v1/events/',
+ '/api/v1/events',
method='POST',
).respond_with_json({'processed': 1, 'failed': 0})
@@ -813,7 +813,7 @@ class TestAuthResilience:
# Set up another malformed response for events
httpserver.expect_request(
- '/api/v1/events/',
+ '/api/v1/events',
method='POST',
).respond_with_data('malformed response', status=500)
diff --git a/tests/debug_page_structure.py b/tests/debug_page_structure.py
deleted file mode 100644
index 43d9658d9..000000000
--- a/tests/debug_page_structure.py
+++ /dev/null
@@ -1,124 +0,0 @@
-import asyncio
-import os
-import sys
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-from browser_use.browser.browser import Browser, BrowserConfig
-from browser_use.browser.context import BrowserContext
-
-
-async def analyze_page_structure(url: str):
- """Analyze and print the structure of a webpage with enhanced debugging"""
- browser = Browser(
- config=BrowserConfig(
- headless=False, # Set to True if you don't need to see the browser
- ),
- user_data_dir=None,
- )
-
- context = BrowserContext(browser=browser)
-
- try:
- async with context as ctx:
- # Navigate to the URL
- page = await ctx.get_current_page()
- await page.goto(url)
- await page.wait_for_load_state('networkidle')
-
- # Get viewport dimensions
- viewport_info = await page.evaluate("""() => {
- return {
- viewport: {
- width: window.innerWidth,
- height: window.innerHeight,
- scrollX: window.scrollX,
- scrollY: window.scrollY
- }
- }
- }""")
-
- print('\nViewport Information:')
- print(f'Width: {viewport_info["viewport"]["width"]}')
- print(f'Height: {viewport_info["viewport"]["height"]}')
- print(f'ScrollX: {viewport_info["viewport"]["scrollX"]}')
- print(f'ScrollY: {viewport_info["viewport"]["scrollY"]}')
-
- # Enhanced debug information for cookie consent and fixed position elements
- debug_info = await page.evaluate("""() => {
- function getElementInfo(element) {
- const rect = element.getBoundingClientRect();
- const style = window.getComputedStyle(element);
- return {
- tag: element.tagName.toLowerCase(),
- id: element.id,
- className: element.className,
- position: style.position,
- rect: {
- top: rect.top,
- right: rect.right,
- bottom: rect.bottom,
- left: rect.left,
- width: rect.width,
- height: rect.height
- },
- isFixed: style.position === 'fixed',
- isSticky: style.position === 'sticky',
- zIndex: style.zIndex,
- visibility: style.visibility,
- display: style.display,
- opacity: style.opacity
- };
- }
-
- // Find cookie-related elements
- const cookieElements = Array.from(document.querySelectorAll('[id*="cookie"], [id*="consent"], [class*="cookie"], [class*="consent"]'));
- const fixedElements = Array.from(document.querySelectorAll('*')).filter(el => {
- const style = window.getComputedStyle(el);
- return style.position === 'fixed' || style.position === 'sticky';
- });
-
- return {
- cookieElements: cookieElements.map(getElementInfo),
- fixedElements: fixedElements.map(getElementInfo)
- };
- }""")
-
- print('\nCookie-related Elements:')
- for elem in debug_info['cookieElements']:
- print(f'\nElement: {elem["tag"]}#{elem["id"]} .{elem["className"]}')
- print(f'Position: {elem["position"]}')
- print(f'Rect: {elem["rect"]}')
- print(f'Z-Index: {elem["zIndex"]}')
- print(f'Visibility: {elem["visibility"]}')
- print(f'Display: {elem["display"]}')
- print(f'Opacity: {elem["opacity"]}')
-
- print('\nFixed/Sticky Position Elements:')
- for elem in debug_info['fixedElements']:
- print(f'\nElement: {elem["tag"]}#{elem["id"]} .{elem["className"]}')
- print(f'Position: {elem["position"]}')
- print(f'Rect: {elem["rect"]}')
- print(f'Z-Index: {elem["zIndex"]}')
-
- print(f'\nPage Structure for {url}:\n')
- structure = await ctx.get_page_structure()
- print(structure)
-
- input('Press Enter to close the browser...')
- finally:
- await browser.close()
-
-
-if __name__ == '__main__':
- # You can modify this URL to analyze different pages
-
- urls = [
- 'https://www.mlb.com/yankees/stats/',
- 'https://immobilienscout24.de',
- 'https://www.zeiss.com/career/en/job-search.html?page=1',
- 'https://www.zeiss.com/career/en/job-search.html?page=1',
- 'https://reddit.com',
- ]
- for url in urls:
- asyncio.run(analyze_page_structure(url))
diff --git a/tests/sync_live.py b/tests/sync_live.py
index 24a51e72d..74397cc1d 100644
--- a/tests/sync_live.py
+++ b/tests/sync_live.py
@@ -17,7 +17,7 @@
# from browser_use import Agent
# from browser_use.browser.browser import BrowserSession
# from browser_use.sync.service import CloudSync
-# from tests.ci.mocks import create_mock_llm
+# from tests.ci.conftest import create_mock_llm
# logger = logging.getLogger(__name__)