Skip to content

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

add controller test

Anirudha619a65a66d5b6e2
diff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.py
index 247067df0..768aca494 100644
--- a/browser_use/agent/message_manager/utils.py
+++ b/browser_use/agent/message_manager/utils.py
@@ -17,17 +17,14 @@ from langchain_core.messages import (
logger = logging.getLogger(__name__)
MODELS_WITHOUT_TOOL_SUPPORT_PATTERNS = [
- "deepseek-reasoner",
- "deepseek-r1",
- ".*gemma.*-it",
+ 'deepseek-reasoner',
+ 'deepseek-r1',
+ '.*gemma.*-it',
]
def is_model_without_tool_support(model_name: str) -> bool:
- return any(
- re.match(pattern, model_name)
- for pattern in MODELS_WITHOUT_TOOL_SUPPORT_PATTERNS
- )
+ return any(re.match(pattern, model_name) for pattern in MODELS_WITHOUT_TOOL_SUPPORT_PATTERNS)
def extract_json_from_model_output(content: str) -> dict:
@@ -51,7 +48,7 @@ def convert_input_messages(input_messages: list[BaseMessage], model_name: Option
"""Convert input messages to a format that is compatible with the planner model"""
if model_name is None:
return input_messages
-
+
if is_model_without_tool_support(model_name):
converted_input_messages = _convert_messages_for_non_function_calling_models(input_messages)
merged_input_messages = _merge_successive_messages(converted_input_messages, HumanMessage)
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 67cc52c92..9693d8268 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -26,7 +26,12 @@ from browser_use.agent.gif import create_history_gif
from browser_use.agent.memory.service import Memory
from browser_use.agent.memory.views import MemoryConfig
from browser_use.agent.message_manager.service import MessageManager, MessageManagerSettings
-from browser_use.agent.message_manager.utils import convert_input_messages, extract_json_from_model_output, save_conversation, is_model_without_tool_support
+from browser_use.agent.message_manager.utils import (
+ convert_input_messages,
+ extract_json_from_model_output,
+ is_model_without_tool_support,
+ save_conversation,
+)
from browser_use.agent.prompts import AgentMessagePrompt, PlannerPrompt, SystemPrompt
from browser_use.agent.views import (
REQUIRED_LLM_API_ENV_VARS,
@@ -373,7 +378,7 @@ class Agent(Generic[Context]):
def _set_tool_calling_method(self) -> Optional[ToolCallingMethod]:
tool_calling_method = self.settings.tool_calling_method
if tool_calling_method == 'auto':
- if (is_model_without_tool_support(self.model_name)):
+ if is_model_without_tool_support(self.model_name):
return 'raw'
elif self.chat_model_library == 'ChatGoogleGenerativeAI':
return None
diff --git a/tests/test_controller.py b/tests/test_controller.py
new file mode 100644
index 000000000..c3d8adcf3
--- /dev/null
+++ b/tests/test_controller.py
@@ -0,0 +1,304 @@
+import asyncio
+import time
+from typing import Optional
+
+import pytest
+from pydantic import BaseModel
+
+from browser_use.agent.views import ActionModel, ActionResult
+from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser.context import BrowserContext
+from browser_use.controller.service import Controller
+from browser_use.controller.views import ClickElementAction, GoToUrlAction, InputTextAction, NoParamsAction, ScrollAction
+
+
+class TestControllerIntegration:
+ """Integration tests for Controller using actual browser instances."""
+
+ @pytest.fixture(scope='module')
+ def event_loop(self):
+ """Create and provide an event loop for async tests."""
+ loop = asyncio.get_event_loop_policy().new_event_loop()
+ yield loop
+ loop.close()
+
+ @pytest.fixture(scope='module')
+ async def browser(self, event_loop):
+ """Create and provide a Browser instance."""
+ browser_instance = Browser(config=BrowserConfig(headless=True, disable_security=True))
+ yield browser_instance
+ await browser_instance.close()
+
+ @pytest.fixture
+ async def browser_context(self, browser):
+ """Create and provide a BrowserContext instance."""
+ context = BrowserContext(browser=browser)
+ yield context
+ await context.close()
+
+ @pytest.fixture
+ def controller(self):
+ """Create and provide a Controller instance."""
+ return Controller()
+
+ @pytest.mark.asyncio
+ async def test_go_to_url_action(self, controller, browser_context):
+ """Test that GoToUrlAction navigates to the specified URL."""
+ # Create action model for go_to_url
+ action_data = {'go_to_url': GoToUrlAction(url='https://google.com')}
+
+ # Create the ActionModel instance
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: Optional[GoToUrlAction] = None
+
+ action_model = GoToUrlActionModel(**action_data)
+
+ # Execute the action
+ result = await controller.act(action_model, browser_context)
+
+ # Verify the result
+ assert isinstance(result, ActionResult)
+ assert 'Navigated to https://google.com' in result.extracted_content
+
+ # Verify the current page URL
+ page = await browser_context.get_current_page()
+ assert 'google.com' in page.url
+
+ @pytest.mark.asyncio
+ async def test_scroll_actions(self, controller, browser_context):
+ """Test that scroll actions correctly scroll the page."""
+ # First navigate to a page
+ goto_action = {'go_to_url': GoToUrlAction(url='https://google.com')}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: Optional[GoToUrlAction] = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_context)
+
+ # Create scroll down action
+ scroll_action = {'scroll_down': ScrollAction(amount=200)}
+
+ class ScrollActionModel(ActionModel):
+ scroll_down: Optional[ScrollAction] = None
+
+ # Execute scroll down
+ result = await controller.act(ScrollActionModel(**scroll_action), browser_context)
+
+ # Verify the result
+ assert isinstance(result, ActionResult)
+ assert 'Scrolled down' in result.extracted_content
+
+ # Create scroll up action
+ scroll_up_action = {'scroll_up': ScrollAction(amount=100)}
+
+ class ScrollUpActionModel(ActionModel):
+ scroll_up: Optional[ScrollAction] = None
+
+ # Execute scroll up
+ result = await controller.act(ScrollUpActionModel(**scroll_up_action), browser_context)
+
+ # Verify the result
+ assert isinstance(result, ActionResult)
+ assert 'Scrolled up' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_registry_actions(self, controller, browser_context):
+ """Test that the registry contains the expected default actions."""
+ # Check that common actions are registered
+ common_actions = [
+ 'go_to_url',
+ 'search_google',
+ 'click_element_by_index',
+ 'input_text',
+ 'scroll_down',
+ 'scroll_up',
+ 'go_back',
+ 'switch_tab',
+ 'open_tab',
+ 'close_tab',
+ 'wait',
+ ]
+
+ for action in common_actions:
+ assert action in controller.registry.registry.actions
+ assert controller.registry.registry.actions[action].function is not None
+ assert controller.registry.registry.actions[action].description is not None
+
+ @pytest.mark.asyncio
+ async def test_custom_action_registration(self, controller, browser_context):
+ """Test registering a custom action and executing it."""
+
+ # Define a custom action
+ class CustomParams(BaseModel):
+ text: str
+
+ @controller.action('Test custom action', param_model=CustomParams)
+ async def custom_action(params: CustomParams, browser):
+ page = await browser.get_current_page()
+ return ActionResult(extracted_content=f'Custom action executed with: {params.text} on {page.url}')
+
+ # Navigate to a page first
+ goto_action = {'go_to_url': GoToUrlAction(url='https://google.com')}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: Optional[GoToUrlAction] = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_context)
+
+ # Create the custom action model
+ custom_action_data = {'custom_action': CustomParams(text='test_value')}
+
+ class CustomActionModel(ActionModel):
+ custom_action: Optional[CustomParams] = None
+
+ # Execute the custom action
+ result = await controller.act(CustomActionModel(**custom_action_data), browser_context)
+
+ # Verify the result
+ assert isinstance(result, ActionResult)
+ assert 'Custom action executed with: test_value on' in result.extracted_content
+ assert 'google.com' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_excluded_actions(self, browser_context):
+ """Test that excluded actions are not registered."""
+ # Create controller with excluded actions
+ excluded_controller = Controller(exclude_actions=['search_google', 'open_tab'])
+
+ # Verify excluded actions are not in the registry
+ assert 'search_google' not in excluded_controller.registry.registry.actions
+ assert 'open_tab' not in excluded_controller.registry.registry.actions
+
+ # But other actions are still there
+ assert 'go_to_url' in excluded_controller.registry.registry.actions
+ assert 'click_element_by_index' in excluded_controller.registry.registry.actions
+
+ @pytest.mark.asyncio
+ async def test_input_text_action(self, controller, browser_context):
+ """Test that InputTextAction correctly inputs text into form fields."""
+ # Navigate to a page with a form
+ goto_action = {'go_to_url': GoToUrlAction(url='https://yahoo.com')}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: Optional[GoToUrlAction] = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_context)
+
+ # Get the search input field index
+ page = await browser_context.get_current_page()
+ selector_map = await browser_context.get_selector_map()
+
+ # Find the search input field - this requires examining the DOM
+ # We'll mock this part since we can't rely on specific element indices
+ # In a real test, you would get the actual index from the selector map
+
+ # For demonstration, we'll just use a hard-coded mock value
+ # and check that the controller processes the action correctly
+ mock_input_index = 1 # This would normally be determined dynamically
+
+ # Create input text action
+ input_action = {'input_text': InputTextAction(index=mock_input_index, text='Python programming')}
+
+ class InputTextActionModel(ActionModel):
+ input_text: Optional[InputTextAction] = None
+
+ # The actual input might fail if the page structure changes or in headless mode
+ # So we'll just verify the controller correctly processes the action
+ try:
+ result = await controller.act(InputTextActionModel(**input_action), browser_context)
+ # If successful, verify the result
+ assert isinstance(result, ActionResult)
+ assert 'Input' in result.extracted_content
+ except Exception as e:
+ # If it fails due to DOM issues, that's expected in a test environment
+ assert 'Element index' in str(e) or 'does not exist' in str(e)
+
+ @pytest.mark.asyncio
+ async def test_error_handling(self, controller, browser_context):
+ """Test error handling when an action fails."""
+ # Create an action with an invalid index
+ invalid_action = {'click_element_by_index': ClickElementAction(index=9999)}
+
+ class ClickActionModel(ActionModel):
+ click_element_by_index: Optional[ClickElementAction] = None
+
+ # This should fail since the element doesn't exist
+ with pytest.raises(Exception) as excinfo:
+ await controller.act(ClickActionModel(**invalid_action), browser_context)
+
+ # Verify that an appropriate error is raised
+ assert 'does not exist' in str(excinfo.value) or 'Element with index' in str(excinfo.value)
+
+ @pytest.mark.asyncio
+ async def test_wait_action(self, controller, browser_context):
+ """Test that the wait action correctly waits for the specified duration."""
+ # Create wait action for 1 second - fix to use a dictionary
+ wait_action = {'wait': {'seconds': 1}} # Corrected format
+
+ class WaitActionModel(ActionModel):
+ wait: Optional[dict] = None
+
+ # Record start time
+ start_time = time.time()
+
+ # Execute wait action
+ result = await controller.act(WaitActionModel(**wait_action), browser_context)
+
+ # Record end time
+ end_time = time.time()
+
+ # Verify the result
+ assert isinstance(result, ActionResult)
+ assert 'Waiting for' in result.extracted_content
+
+ # Verify that at least 1 second has passed
+ assert end_time - start_time >= 0.9 # Allow some timing margin
+
+ @pytest.mark.asyncio
+ async def test_go_back_action(self, controller, browser_context):
+ """Test that go_back action navigates to the previous page."""
+ # Navigate to first page
+ goto_action1 = {'go_to_url': GoToUrlAction(url='https://google.com')}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: Optional[GoToUrlAction] = None
+
+ await controller.act(GoToUrlActionModel(**goto_action1), browser_context)
+
+ # Store the first page URL
+ page1 = await browser_context.get_current_page()
+ first_url = page1.url
+ print(f'First page URL: {first_url}')
+
+ # Navigate to second page
+ goto_action2 = {'go_to_url': GoToUrlAction(url='https://yahoo.com')}
+ await controller.act(GoToUrlActionModel(**goto_action2), browser_context)
+
+ # Verify we're on the second page
+ page2 = await browser_context.get_current_page()
+ second_url = page2.url
+ print(f'Second page URL: {second_url}')
+ assert 'yahoo.com' in second_url.lower()
+
+ # Execute go back action
+ go_back_action = {'go_back': NoParamsAction()}
+
+ class GoBackActionModel(ActionModel):
+ go_back: Optional[NoParamsAction] = None
+
+ result = await controller.act(GoBackActionModel(**go_back_action), browser_context)
+
+ # Verify the result
+ assert isinstance(result, ActionResult)
+ assert 'Navigated back' in result.extracted_content
+
+ # Add another delay to allow the navigation to complete
+ await asyncio.sleep(1)
+
+ # Verify we're back on a different page than before
+ page3 = await browser_context.get_current_page()
+ final_url = page3.url
+ print(f'Final page URL after going back: {final_url}')
+
+ # Try to verify we're back on the first page, but don't fail the test if not
+ assert 'google.com' in final_url, f'Expected to return to Google but got {final_url}'