Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
centralize LLM mocking for tests into mocks.py
Nick Sweeting7f49b4aa1de3
diff --git a/tests/ci/test_agent_multiprocessing.py b/tests/ci/test_agent_multiprocessing.pyindex a799e146a..32e353aa3 100644--- a/tests/ci/test_agent_multiprocessing.py+++ b/tests/ci/test_agent_multiprocessing.py@@ -23,105 +23,16 @@ from playwright.async_api import async_playwrightfrom browser_use import Agent, setup_loggingfrom browser_use.browser import BrowserProfile, BrowserSession+from tests.ci.mocks import create_mock_llm# Set up test loggingsetup_logging()logger = logging.getLogger(__name__)-def create_mock_llm():- """Create a mock LLM that returns a done action"""- mock = AsyncMock(spec=BaseChatModel)- mock._verified_api_keys = True- mock._verified_tool_calling_method = 'raw'-- # Add model_name attribute for logging- mock.model_name = 'mock-llm'-- # Create the response- response_content = """- {- "current_state": {- "evaluation_previous_goal": "Starting the task",- "memory": "Task completed",- "next_goal": "Complete the task"- },- "action": [- {- "done": {- "text": "Task completed successfully",- "success": true- }- }- ]- }- """-- # Mock the invoke method to return an AIMessage- mock.invoke.return_value = AIMessage(content=response_content)-- # Make ainvoke return a coroutine that returns the AIMessage- async def async_invoke(*args, **kwargs):- return AIMessage(content=response_content)-- mock.ainvoke.side_effect = async_invoke-- return mock---def create_mock_llm_with_actions(action_sequence):- """Factory to create mock LLMs with specific action sequences"""- mock = AsyncMock(spec=BaseChatModel)- mock._verified_api_keys = True- mock._verified_tool_calling_method = 'raw'-- # Add model_name attribute for logging- mock.model_name = 'mock-llm'-- action_index = 0-- def mock_invoke(*args, **kwargs):- nonlocal action_index- if action_index < len(action_sequence):- content = action_sequence[action_index]- action_index += 1- else:- # Default to done action- content = """- {- "current_state": {- "evaluation_previous_goal": "All actions completed",- "memory": "Task completed",- "next_goal": "Complete the task"- },- "action": [- {- "done": {- "text": "Task completed successfully",- "success": true- }- }- ]- }- """- return AIMessage(content=content)-- # Create async version for ainvoke- async def async_mock_invoke(*args, **kwargs):- return mock_invoke(*args, **kwargs)-- mock.invoke.side_effect = mock_invoke- mock.ainvoke.side_effect = async_mock_invoke- return mock--def run_agent_in_subprocess_module(task_description):"""Module-level function to run an agent in a subprocess"""import asyncio- from unittest.mock import AsyncMock-- from langchain_core.language_models.chat_models import BaseChatModel- from langchain_core.messages import AIMessagefrom browser_use import Agent@@ -487,8 +398,8 @@ class TestParallelism:"""# Create mocks with tab creation actions- mock_llm1 = create_mock_llm_with_actions([tab_action, done_action])- mock_llm2 = create_mock_llm_with_actions([tab_action, done_action])+ mock_llm1 = create_mock_llm([tab_action, done_action])+ mock_llm2 = create_mock_llm([tab_action, done_action])# Create shared browser sessionshared_session = BrowserSession(diff --git a/tests/ci/test_browser_session_start.py b/tests/ci/test_browser_session_start.pyindex 97e5cd485..b558735bf 100644--- a/tests/ci/test_browser_session_start.py+++ b/tests/ci/test_browser_session_start.py@@ -10,6 +10,7 @@ Tests cover:"""import asyncio+import jsonimport loggingfrom pathlib import Path@@ -22,6 +23,7 @@ from browser_use.browser.profile import (BrowserProfile,)from browser_use.browser.session import BrowserSession+from tests.ci.mocks import create_mock_llm# Set up test logginglogger = logging.getLogger('browser_session_start_tests')@@ -605,61 +607,6 @@ class TestBrowserSessionReusePatterns:return mock- def create_mock_llm_with_actions(self, action_sequence):- """Factory to create mock LLMs with specific action sequences"""- from unittest.mock import MagicMock-- from langchain_core.language_models.chat_models import BaseChatModel-- # Create a MagicMock that supports dictionary-style access- mock = MagicMock(spec=BaseChatModel)-- # Skip verification by setting these attributes- mock._verified_api_keys = True- mock._verified_tool_calling_method = 'raw'-- # Track which action to return next- action_index = 0-- # Mock the invoke method to return actions in sequence- def mock_invoke(*args, **kwargs):- nonlocal action_index- response = MagicMock()-- if action_index < len(action_sequence):- response.content = action_sequence[action_index]- action_index += 1- else:- # Default to done action if we run out of actions- response.content = """- {- "current_state": {- "evaluation_previous_goal": "All actions completed",- "memory": "Task completed",- "next_goal": "Complete the task"- },- "action": [- {- "done": {- "text": "Task completed successfully",- "success": true- }- }- ]- }- """- return response-- mock.invoke = mock_invoke-- # Create an async version of the mock_invoke- async def mock_ainvoke(*args, **kwargs):- return mock_invoke(*args, **kwargs)-- mock.ainvoke = mock_ainvoke-- return mock-async def test_sequential_agents_same_profile_different_browser(self, mock_llm):"""Test Sequential Agents, Same Profile, Different Browser pattern"""from browser_use import Agent@@ -821,9 +768,9 @@ class TestBrowserSessionReusePatterns:# Create 3 agents sharing the same browser session# Each gets its own mock LLM with the same action sequence- mock_llm1 = self.create_mock_llm_with_actions([tab_creation_action, done_action])- mock_llm2 = self.create_mock_llm_with_actions([tab_creation_action, done_action])- mock_llm3 = self.create_mock_llm_with_actions([tab_creation_action, done_action])+ mock_llm1 = create_mock_llm([tab_creation_action, done_action])+ mock_llm2 = create_mock_llm([tab_creation_action, done_action])+ mock_llm3 = create_mock_llm([tab_creation_action, done_action])agent1 = Agent(task='First parallel task...',@@ -933,7 +880,7 @@ class TestBrowserSessionReusePatterns:# Create a shared profile with storage statewith tempfile.NamedTemporaryFile(suffix='.json', delete=False, mode='w') as f:# Write minimal valid storage state- f.write('{"cookies": [], "origins": []}')+ f.write('{"cookies": [], "origins": [{"origin": "example.com", "localStorage": {"testkey": "testvalue"}}]}')auth_json_path = f.name# Convert to Path object@@ -980,6 +927,11 @@ class TestBrowserSessionReusePatterns:# Verify storage state file existsassert Path(auth_json_path).exists()+ # Verify storage state file was not wiped+ storage_state = json.loads(auth_json_path.read_text())+ assert 'origins' in storage_state+ assert len(storage_state['origins']) > 0+finally:await window1.kill()await window2.kill()diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.pyindex e19e3105c..97c32f4c1 100644--- a/tests/ci/test_controller.py+++ b/tests/ci/test_controller.py@@ -1338,3 +1338,107 @@ class TestControllerIntegration:# Verify the click actually had an effect on the pageresult_text = await page.evaluate("document.getElementById('result').textContent")assert result_text == expected_result_text, f"Expected result text '{expected_result_text}', got '{result_text}'"++ async def test_empty_css_selector_fallback(self, controller, browser_session, httpserver):+ """Test that clicking elements with empty CSS selectors falls back to XPath."""+ # Create a test page with an element that would produce an empty CSS selector+ # This could happen with elements that have no tag name or unusual XPath structures+ httpserver.expect_request('/empty_css_test').respond_with_data(+ """+ <html>+ <head><title>Empty CSS Selector Test</title></head>+ <body>+ <div id="container">+ <!-- Element with minimal attributes that might produce empty CSS selector -->+ <custom-element>Click Me</custom-element>+ <div id="result">Not clicked</div>+ </div>+ <script>+ // Add click handler to the custom element+ document.querySelector('custom-element').addEventListener('click', function() {+ document.getElementById('result').textContent = 'Clicked!';+ });+ </script>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ # Navigate to the test page+ page = await browser_session.get_current_page()+ await page.goto(httpserver.url_for('/empty_css_test'))+ await page.wait_for_load_state()++ # Get the page state which includes clickable elements+ state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)++ # Find the custom element index+ custom_element_index = None+ for index, element in state.selector_map.items():+ if element.tag_name == 'custom-element':+ custom_element_index = index+ break++ assert custom_element_index is not None, 'Could not find custom-element in selector map'++ # Mock a scenario where CSS selector generation returns empty string+ # by temporarily patching the method (we'll test the actual fallback behavior)+ original_method = browser_session._enhanced_css_selector_for_element+ empty_css_called = False++ def mock_css_selector(element, include_dynamic_attributes=True):+ nonlocal empty_css_called+ # Return empty string for our custom element to trigger fallback+ if element.tag_name == 'custom-element':+ empty_css_called = True+ return ''+ return original_method(element, include_dynamic_attributes)++ # Temporarily replace the method+ browser_session._enhanced_css_selector_for_element = mock_css_selector++ try:+ # Create click action for the custom element+ click_action = {'click_element_by_index': ClickElementAction(index=custom_element_index)}++ class ClickActionModel(ActionModel):+ click_element_by_index: ClickElementAction | None = None++ # Execute the click - should use XPath fallback+ result = await controller.act(ClickActionModel(**click_action), browser_session)++ # Verify the click succeeded+ assert result.error is None, f'Click failed with error: {result.error}'+ assert result.success is True, 'Click was not successful'+ assert empty_css_called, 'CSS selector method was not called'++ # Verify the element was actually clicked by checking the result+ result_text = await page.evaluate("document.getElementById('result').textContent")+ assert result_text == 'Clicked!', f'Element was not clicked, result text: {result_text}'++ finally:+ # Restore the original method+ browser_session._enhanced_css_selector_for_element = original_method++ async def test_go_to_url_network_error(self, controller, browser_session):+ """Test that go_to_url handles network errors gracefully instead of throwing hard errors."""+ # Create action model for go_to_url with an invalid domain+ action_data = {'go_to_url': GoToUrlAction(url='https://www.nonexistentdndbeyond.com/')}++ # Create the ActionModel instance+ class GoToUrlActionModel(ActionModel):+ go_to_url: GoToUrlAction | None = None++ action_model = GoToUrlActionModel(**action_data)++ # Execute the action - should return soft error instead of throwing+ result = await controller.act(action_model, browser_session)++ # Verify the result+ assert isinstance(result, ActionResult)+ assert result.success is False, 'Expected success=False for network error'+ assert result.error is not None, 'Expected error message to be set'+ assert 'Site unavailable' in result.error, f"Expected 'Site unavailable' in error message, got: {result.error}"+ assert 'nonexistentdndbeyond.com' in result.error, 'Expected URL in error message'+ assert result.include_in_memory is True, 'Network errors should be included in memory'diff --git a/tests/ci/test_registry.py b/tests/ci/test_registry.pyindex da35c0640..8aedd9c5b 100644--- a/tests/ci/test_registry.py+++ b/tests/ci/test_registry.py@@ -29,22 +29,13 @@ from browser_use.controller.views import (NoParamsAction,SearchGoogleAction,)+from tests.ci.mocks import create_mock_llm# Configure logginglogging.basicConfig(level=logging.DEBUG)logger = logging.getLogger(__name__)-class MockLLM:- """Mock LLM for testing"""-- async def ainvoke(self, prompt):- class MockResponse:- content = 'Mocked LLM response'-- return MockResponse()--class TestContext:"""Simple context for testing"""@@ -92,7 +83,7 @@ def base_url(http_server):@pytest.fixture(scope='module')def mock_llm():"""Create a mock LLM"""- return MockLLM()+ return create_mock_llm()@pytest.fixture(scope='function')@@ -834,7 +825,7 @@ class TestDecoratedFunctionBehavior:special_context = {'page': MockPage(),'browser_session': None,- 'page_extraction_llm': MockLLM(),+ 'page_extraction_llm': create_mock_llm(),'context': {'extra': 'data'},'unknown_param': 'ignored',}diff --git a/tests/test_save_conversation.py b/tests/test_save_conversation.pydeleted file mode 100644index 94b6d1c1c..000000000--- a/tests/test_save_conversation.py+++ /dev/null@@ -1,91 +0,0 @@-"""-Simple try of the agent.--@dev You need to add OPENAI_API_KEY to your environment variables.-"""--import os-import shutil-import sys--from browser_use.browser import BrowserProfile, BrowserSession--sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))--from langchain_openai import ChatOpenAI--from browser_use import Agent, AgentHistoryList--llm = ChatOpenAI(model='gpt-4o')---async def test_save_conversation_contains_slash():- if os.path.exists('./logs'):- shutil.rmtree('./logs')-- browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, disable_security=True))- await browser_session.start()- try:- agent = Agent(- task=('go to google.com and search for text "hi there"'),- llm=llm,- browser_session=browser_session,- save_conversation_path='logs/conversation',- )- history: AgentHistoryList = await agent.run(20)-- result = history.final_result()- assert result is not None-- assert os.path.exists('./logs'), 'logs directory was not created'- assert os.path.exists('./logs/conversation_2.txt'), 'logs file was not created'- finally:- await browser_session.stop()---async def test_save_conversation_not_contains_slash():- if os.path.exists('./logs'):- shutil.rmtree('./logs')-- browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, disable_security=True))- await browser_session.start()- try:- agent = Agent(- task=('go to google.com and search for text "hi there"'),- llm=llm,- browser_session=browser_session,- save_conversation_path='logs',- )- history: AgentHistoryList = await agent.run(20)-- result = history.final_result()- assert result is not None-- assert os.path.exists('./logs'), 'logs directory was not created'- assert os.path.exists('./logs/_2.txt'), 'logs file was not created'- finally:- await browser_session.stop()---async def test_save_conversation_deep_directory():- if os.path.exists('./logs'):- shutil.rmtree('./logs')-- browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, disable_security=True))- await browser_session.start()- try:- agent = Agent(- task=('go to google.com and search for text "hi there"'),- llm=llm,- browser_session=browser_session,- save_conversation_path='logs/deep/directory/conversation',- )- history: AgentHistoryList = await agent.run(20)-- result = history.final_result()- assert result is not None-- assert os.path.exists('./logs/deep/directory'), 'logs directory was not created'- assert os.path.exists('./logs/deep/directory/conversation_2.txt'), 'logs file was not created'- finally:- await browser_session.stop()