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
move old tests to old folder
Nick Sweeting340bafdd29f5
diff --git a/CLAUDE.md b/CLAUDE.mdindex 74263642e..9de9a0c29 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5,20 +5,22 @@ We want our library APIs to be ergonomic, intuitive, and hard to get wrong.- Use async python- Use tabs for indentation in all python code, not spaces-- Use the modern python >3.12 typing style, e.g. use `str | None` instead of `Optional[str]`, and `list[str]` instead of `List[str]`+- Use the modern python >3.12 typing style, e.g. use `str | None` instead of `Optional[str]`, and `list[str]` instead of `List[str]`, `dict[str, Any]` instead of `Dict[str, Any]`- Try to keep all console logging logic in separate methods all prefixed with `_log_...`, e.g. `def _log_pretty_path(path: Path) -> str` so as not to clutter up the main logic.- Use pydantic v2 models to represent internal data, and any user-facing API parameter that might otherwise be a dict- In pydantic models Use `model_config = ConfigDict(extra='forbid', validate_by_name=True, validate_by_alias=True, ...)` etc. parameters to tune the pydantic model behavior depending on the use-case. Use `Annotated[..., AfterValidator(...)]` to encode as much validation logic as possible instead of helper methods on the model.- We keep the main code for each sub-component in a `service.py` file usually, and we keep most pydantic models in `views.py` files unless they are long enough deserve their own file- Use runtime assertions at the start and end of functions to enforce constraints and assumptions- Prefer `from uuid_extensions import uuid7str` + `id: str = Field(default_factory=uuid7str)` for all new id fields+- Run tests using `uv run pytest -vx tests/ci`+- Run the type checker using `uv run pyright`## Keep Examples & Tests Up-To-Date- Make sure to read relevant examples in the `examples/` directory for context and keep them up-to-date when making changes.- Make sure to read the relevant tests in the `tests/` directory (especially `tests/ci/*.py`) and keep them up-to-date as well.- Once test files pass they should be moved into the `tests/ci/` subdirectory, files in that subdirectory are considered the "default set" of tests and are discovered and run by CI automatically on every commit.-- Try to almost never use mocks in tests, instead use pytest fixtures to set up real objects+- Never use mocks in tests other than for the llm, instead use pytest fixtures to set up real objects and pytest-httpserver- Never use real remote URLs in tests (e.g. `https://google.com` or `https://example.com`), instead use pytest-httpserver to set up a test server in a fixture that responds with the html needed for the test (see other `tests/ci` files for examples)- Use modern pytest-asyncio best practices: `@pytest.mark.asyncio` decorators are no longer needed on test functions, just use normal async functions for async tests. Use `loop = asyncio.get_event_loop()` inside tests that need it instead of passing `event_loop` as a function argument. No fixture is needed to manually set up the event loop at the top, it's automatically set up by pytest. Fixture functions (even async ones) only need a simple `@pytest.fixture` decorator with no arguments.diff --git a/browser_use/agent/message_manager/tests.py b/browser_use/agent/message_manager/tests.pydeleted file mode 100644index 77f84c5d5..000000000--- a/browser_use/agent/message_manager/tests.py+++ /dev/null@@ -1,246 +0,0 @@-import pytest-from langchain_anthropic import ChatAnthropic-from langchain_core.messages import AIMessage, HumanMessage, SystemMessage-from langchain_openai import AzureChatOpenAI, ChatOpenAI--from browser_use.agent.message_manager.service import MessageManager, MessageManagerSettings-from browser_use.agent.views import ActionResult-from browser_use.browser.views import BrowserStateSummary, TabInfo-from browser_use.dom.views import DOMElementNode, DOMTextNode-from browser_use.filesystem.file_system import FileSystem--- params=[- ChatOpenAI(model='gpt-4o-mini'),- AzureChatOpenAI(model='gpt-4o', api_version='2024-02-15-preview'),- ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=100, temperature=0.0, stop=None),- ],- ids=['gpt-4o-mini', 'gpt-4o', 'claude-3-5-sonnet'],-)-def message_manager(request: pytest.FixtureRequest):- task = 'Test task'- action_descriptions = 'Test actions'-- import os- import tempfile- import uuid-- base_tmp = tempfile.gettempdir() # e.g., /tmp on Unix- file_system_path = os.path.join(base_tmp, str(uuid.uuid4()))- return MessageManager(- task=task,- system_message=SystemMessage(content=action_descriptions),- settings=MessageManagerSettings(- max_input_tokens=1000,- estimated_characters_per_token=3,- image_tokens=800,- ),- file_system=FileSystem(file_system_path),- )---def test_initial_messages(message_manager: MessageManager):- """Test that message manager initializes with system and task messages"""- messages = message_manager.get_messages()- assert len(messages) == 2- assert isinstance(messages[0], SystemMessage)- assert isinstance(messages[1], HumanMessage)- assert 'Test task' in messages[1].content---def test_add_state_message(message_manager: MessageManager):- """Test adding browser state message"""- state = BrowserStateSummary(- url='https://test.com',- title='Test Page',- element_tree=DOMElementNode(- tag_name='div',- attributes={},- children=[],- is_visible=True,- parent=None,- xpath='//div',- ),- selector_map={},- tabs=[TabInfo(page_id=1, url='https://test.com', title='Test Page')],- )- message_manager.add_state_message(browser_state_summary=state)-- messages = message_manager.get_messages()- assert len(messages) == 3- assert isinstance(messages[2], HumanMessage)- assert 'https://test.com' in messages[2].content---def test_add_state_with_memory_result(message_manager: MessageManager):- """Test adding state with result that should be included in memory"""- state = BrowserStateSummary(- url='https://test.com',- title='Test Page',- element_tree=DOMElementNode(- tag_name='div',- attributes={},- children=[],- is_visible=True,- parent=None,- xpath='//div',- ),- selector_map={},- tabs=[TabInfo(page_id=1, url='https://test.com', title='Test Page')],- )- result = ActionResult(extracted_content='Important content', include_in_memory=True)-- message_manager.add_state_message(browser_state_summary=state, result=[result])- messages = message_manager.get_messages()-- # Should have system, task, extracted content, and state messages- assert len(messages) == 4- assert 'Important content' in messages[2].content- assert isinstance(messages[2], HumanMessage)- assert isinstance(messages[3], HumanMessage)- assert 'Important content' not in messages[3].content---def test_add_state_with_non_memory_result(message_manager: MessageManager):- """Test adding state with result that should not be included in memory"""- state = BrowserStateSummary(- url='https://test.com',- title='Test Page',- element_tree=DOMElementNode(- tag_name='div',- attributes={},- children=[],- is_visible=True,- parent=None,- xpath='//div',- ),- selector_map={},- tabs=[TabInfo(page_id=1, url='https://test.com', title='Test Page')],- )- result = ActionResult(extracted_content='Temporary content', include_in_memory=False)-- message_manager.add_state_message(browser_state_summary=state, result=[result])- messages = message_manager.get_messages()-- # Should have system, task, and combined state+result message- assert len(messages) == 3- assert 'Temporary content' in messages[2].content- assert isinstance(messages[2], HumanMessage)--[email protected]('not sure how to fix this')[email protected]('max_tokens', [100000, 10000, 5000])-def test_token_overflow_handling_with_real_flow(message_manager: MessageManager, max_tokens):- """Test handling of token overflow in a realistic message flow"""- # Set more realistic token limit- message_manager.settings.max_input_tokens = max_tokens-- # Create a long sequence of interactions- for i in range(200): # Simulate 40 steps of interaction- # Create state with varying content length- state = BrowserStateSummary(- url=f'https://test{i}.com',- title=f'Test Page {i}',- element_tree=DOMElementNode(- tag_name='div',- attributes={},- children=[- DOMTextNode(- text=f'Content {j} ' * (10 + i), # Increasing content length- is_visible=True,- parent=None,- )- for j in range(5) # Multiple DOM items- ],- is_visible=True,- parent=None,- xpath='//div',- ),- selector_map={},- tabs=[TabInfo(page_id=1, url=f'https://test{i}.com', title=f'Test Page {i}')],- )-- # Alternate between different types of results- result = None- if i % 2 == 0: # Every other iteration- result = ActionResult(- extracted_content=f'Important content from step {i}' * 5,- include_in_memory=i % 4 == 0, # Include in memory every 4th message- )-- # Add state message- if result:- message_manager.add_state_message(browser_state_summary=state, result=[result])- else:- message_manager.add_state_message(browser_state_summary=state)-- try:- messages = message_manager.get_messages()- except ValueError as e:- if 'Max token limit reached - history is too long' in str(e):- return # If error occurs, end the test- else:- raise e-- assert message_manager.state.history.current_tokens <= message_manager.settings.max_input_tokens + 100-- last_msg = messages[-1]- assert isinstance(last_msg, HumanMessage)-- if i % 4 == 0:- assert isinstance(message_manager.state.history.messages[-2].message, HumanMessage)- if i % 2 == 0 and not i % 4 == 0:- if isinstance(last_msg.content, list):- assert any(- 'Current url: https://test' in item.get('text', '') for item in last_msg.content if isinstance(item, dict)- )- else:- assert 'Current url: https://test' in last_msg.content-- # Add model output every time- from browser_use.agent.views import AgentOutput-- output = AgentOutput(- thinking=f'Thinking for step {i}',- evaluation_previous_goal=f'Success in step {i}',- memory=f'Memory from step {i}',- next_goal=f'Goal for step {i + 1}',- action=[], # Empty action list - ActionModel requires specific action parameters- )- message_manager._remove_last_state_message()- message_manager.add_model_output(output)-- # Get messages and verify after each addition- messages = [m.message for m in message_manager.state.history.messages]-- # Verify token limit is respected-- # Verify essential messages are preserved- assert isinstance(messages[0], SystemMessage) # System prompt always first- assert isinstance(messages[1], HumanMessage) # Task always second- assert 'Test task' in messages[1].content-- # Verify structure of latest messages- assert isinstance(messages[-1], AIMessage) # Last message should be model output- assert f'step {i}' in messages[-1].content # Should contain current step info-- # Log token usage for debugging- token_usage = message_manager.state.history.current_tokens- token_limit = message_manager.settings.max_input_tokens- # print(f'Step {i}: Using {token_usage}/{token_limit} tokens')-- # go through all messages and verify that the token count and total tokens is correct- total_tokens = 0- real_tokens = []- stored_tokens = []- for msg in message_manager.state.history.messages:- total_tokens += msg.metadata.tokens- stored_tokens.append(msg.metadata.tokens)- real_tokens.append(message_manager._count_tokens(msg.message))- assert total_tokens == sum(real_tokens)- assert stored_tokens == real_tokens- assert message_manager.state.history.current_tokens == total_tokens---# pytest -s browser_use/agent/message_manager/tests.pydiff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.pyindex 15d81fe12..2ee9070cb 100644--- a/browser_use/agent/message_manager/utils.py+++ b/browser_use/agent/message_manager/utils.py@@ -31,12 +31,17 @@ def is_model_without_tool_support(model_name: str) -> bool:def extract_json_from_model_output(content: str | BaseMessage) -> dict:"""Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON."""try:+ # Extract string content from BaseMessage if needed+ content_str: strif isinstance(content, BaseMessage):# for langchain_core.messages.BaseMessage- content = content.content- # Ensure content is a string- if isinstance(content, list):- content = str(content[0]) if content else ''+ msg_content = content.content+ if isinstance(msg_content, list):+ content_str = str(msg_content[0]) if msg_content else ''+ else:+ content_str = msg_content+ else:+ content_str = content# If content is wrapped in code blocks, extract just the JSON partif '```' in content:# Find the JSON content between code blocksdiff --git a/browser_use/agent/tests.py b/browser_use/agent/tests.pydeleted file mode 100644index 5f58a8e21..000000000--- a/browser_use/agent/tests.py+++ /dev/null@@ -1,197 +0,0 @@-import pytest--from browser_use.agent.views import (- ActionResult,- AgentBrain,- AgentHistory,- AgentHistoryList,- AgentOutput,-)-from browser_use.browser.views import BrowserStateHistory, BrowserStateSummary, TabInfo-from browser_use.controller.registry.service import Registry-from browser_use.controller.views import ClickElementAction, DoneAction, ExtractPageContentAction-from browser_use.dom.views import DOMElementNode---def sample_browser_state():- return BrowserStateSummary(- url='https://example.com',- title='Example Page',- tabs=[TabInfo(url='https://example.com', title='Example Page', page_id=1)],- screenshot='screenshot1.png',- element_tree=DOMElementNode(- tag_name='root',- is_visible=True,- parent=None,- xpath='',- attributes={},- children=[],- ),- selector_map={},- )---def action_registry():- registry = Registry()-- # Register the actions we need for testing- @registry.action(description='Click an element', param_model=ClickElementAction)- def click_element(params: ClickElementAction, browser=None):- pass-- @registry.action(- description='Extract page content',- param_model=ExtractPageContentAction,- )- def extract_page_content(params: ExtractPageContentAction, browser=None):- pass-- @registry.action(description='Mark task as done', param_model=DoneAction)- def done(params: DoneAction):- pass-- # Create the dynamic ActionModel with all registered actions- return registry.create_action_model()---def sample_history(action_registry):- # Create actions with nested params structure- click_action = action_registry(click_element={'index': 1})-- extract_action = action_registry(extract_page_content={'value': 'text'})-- done_action = action_registry(done={'text': 'Task completed'})-- histories = [- AgentHistory(- model_output=AgentOutput(- current_state=AgentBrain(- evaluation_previous_goal='None',- memory='Started task',- next_goal='Click button',- ),- action=[click_action],- ),- result=[ActionResult(is_done=False)],- state=BrowserStateHistory(- url='https://example.com',- title='Page 1',- tabs=[TabInfo(url='https://example.com', title='Page 1', page_id=1)],- screenshot='screenshot1.png',- interacted_element=[{'xpath': '//button[1]'}],- ),- ),- AgentHistory(- model_output=AgentOutput(- current_state=AgentBrain(- evaluation_previous_goal='Clicked button',- memory='Button clicked',- next_goal='Extract content',- ),- action=[extract_action],- ),- result=[- ActionResult(- is_done=False,- extracted_content='Extracted text',- error='Failed to extract completely',- )- ],- state=BrowserStateHistory(- url='https://example.com/page2',- title='Page 2',- tabs=[TabInfo(url='https://example.com/page2', title='Page 2', page_id=2)],- screenshot='screenshot2.png',- interacted_element=[{'xpath': '//div[1]'}],- ),- ),- AgentHistory(- model_output=AgentOutput(- current_state=AgentBrain(- evaluation_previous_goal='Extracted content',- memory='Content extracted',- next_goal='Finish task',- ),- action=[done_action],- ),- result=[ActionResult(is_done=True, extracted_content='Task completed', error=None)],- state=BrowserStateHistory(- url='https://example.com/page2',- title='Page 2',- tabs=[TabInfo(url='https://example.com/page2', title='Page 2', page_id=2)],- screenshot='screenshot3.png',- interacted_element=[{'xpath': '//div[1]'}],- ),- ),- ]- return AgentHistoryList(history=histories)---def test_last_model_output(sample_history: AgentHistoryList):- last_output = sample_history.last_action()- print(last_output)- assert last_output == {'done': {'text': 'Task completed'}}---def test_get_errors(sample_history: AgentHistoryList):- errors = sample_history.errors()- assert len(errors) == 1- assert errors[0] == 'Failed to extract completely'---def test_final_result(sample_history: AgentHistoryList):- assert sample_history.final_result() == 'Task completed'---def test_is_done(sample_history: AgentHistoryList):- assert sample_history.is_done() is True---def test_urls(sample_history: AgentHistoryList):- urls = sample_history.urls()- assert 'https://example.com' in urls- assert 'https://example.com/page2' in urls---def test_all_screenshots(sample_history: AgentHistoryList):- screenshots = sample_history.screenshots()- assert len(screenshots) == 3- assert screenshots == ['screenshot1.png', 'screenshot2.png', 'screenshot3.png']---def test_all_model_outputs(sample_history: AgentHistoryList):- outputs = sample_history.model_actions()- print(f'DEBUG: {outputs[0]}')- assert len(outputs) == 3- # get first key value pair- assert dict([next(iter(outputs[0].items()))]) == {'click_element': {'index': 1}}- assert dict([next(iter(outputs[1].items()))]) == {'extract_page_content': {'value': 'text'}}- assert dict([next(iter(outputs[2].items()))]) == {'done': {'text': 'Task completed'}}---def test_all_model_outputs_filtered(sample_history: AgentHistoryList):- filtered = sample_history.model_actions_filtered(include=['click_element'])- assert len(filtered) == 1- assert filtered[0]['click_element']['index'] == 1---def test_empty_history():- empty_history = AgentHistoryList(history=[])- assert empty_history.last_action() is None- assert empty_history.final_result() is None- assert empty_history.is_done() is False- assert len(empty_history.urls()) == 0---# Add a test to verify action creation-def test_action_creation(action_registry):- click_action = action_registry(click_element={'index': 1})-- assert click_action.model_dump(exclude_none=True) == {'click_element': {'index': 1}}---# run this with:-# pytest browser_use/agent/tests.pydiff --git a/browser_use/utils.py b/browser_use/utils.pyindex 9c8c0be94..5ed31adfe 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -26,7 +26,7 @@ except ImportError:OpenAIBadRequestError = Nonetry:- from groq import BadRequestError as GroqBadRequestError+ from groq import BadRequestError as GroqBadRequestError # type: ignore[import-not-found]except ImportError:GroqBadRequestError = None@@ -558,10 +558,10 @@ def handle_llm_error(e: Exception) -> tuple[dict[str, Any], Any | None]:OpenAIBadRequestErrorand isinstance(e, OpenAIBadRequestError)and hasattr(e, 'body')- and e.body- and 'failed_generation' in e.body+ and e.body # type: ignore[attr-defined]+ and 'failed_generation' in e.body # type: ignore[operator]):- raw = e.body['failed_generation']+ raw = e.body['failed_generation'] # type: ignore[index]response = {'raw': raw, 'parsed': None}parsed = Nonelogger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')diff --git a/pyproject.toml b/pyproject.tomlindex 8b0f4ba3e..45e826a0e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -115,6 +115,8 @@ skip-magic-trailing-comma = false[tool.pyright]typeCheckingMode = "basic"+exclude = ["tests/old/", ".venv/", ".git/", "node_mo"]+[tool.hatch.build]include = [@@ -123,6 +125,7 @@ include = ["!browser_use/**/tests.py","browser_use/agent/system_prompt.md","browser_use/dom/buildDomTree.js",+ "!tests/**/*.py",][tool.pytest.ini_options]diff --git a/tests/extraction_test.py b/tests/old/extraction_test.pysimilarity index 93%rename from tests/extraction_test.pyrename to tests/old/extraction_test.pyindex 38890d8c9..31c125ae6 100644--- a/tests/extraction_test.py+++ b/tests/old/extraction_test.py@@ -7,6 +7,7 @@ from langchain_openai import ChatOpenAIfrom browser_use.agent.prompts import AgentMessagePromptfrom browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.dom.service import DomService+from browser_use.filesystem.file_system import FileSystemdef count_string_tokens(string: str, model: str) -> tuple[int, float]:@@ -101,7 +102,7 @@ async def test_focus_vs_all_elements():# print(all_elements_state.element_tree.clickable_elements_to_string())prompt = AgentMessagePrompt(browser_state_summary=all_elements_state,- result=None,+ file_system=FileSystem(working_dir='./tmp'),include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,step_info=None,)@@ -110,9 +111,15 @@ async def test_focus_vs_all_elements():user_message = prompt.get_user_message(use_vision=False).contentos.makedirs('./tmp', exist_ok=True)async with await anyio.open_file('./tmp/user_message.txt', 'w', encoding='utf-8') as f:- await f.write(user_message)+ if isinstance(user_message, str):+ await f.write(user_message)+ else:+ await f.write(str(user_message))- token_count, price = count_string_tokens(user_message, model='gpt-4o')+ if isinstance(user_message, str):+ token_count, price = count_string_tokens(user_message, model='gpt-4o')+ else:+ token_count, price = count_string_tokens(str(user_message), model='gpt-4o')print(f'Prompt token count: {token_count}, price: {round(price, 4)} USD')print('User message written to ./tmp/user_message.txt')diff --git a/tests/httpx_client_test.py b/tests/old/httpx_client_test.pysimilarity index 100%rename from tests/httpx_client_test.pyrename to tests/old/httpx_client_test.pydiff --git a/tests/process_dom_test.py b/tests/old/process_dom_test.pysimilarity index 100%rename from tests/process_dom_test.pyrename to tests/old/process_dom_test.pydiff --git a/tests/screenshot_test.py b/tests/old/screenshot_test.pysimilarity index 100%rename from tests/screenshot_test.pyrename to tests/old/screenshot_test.pydiff --git a/tests/sync_live.py b/tests/old/sync_live.pysimilarity index 100%rename from tests/sync_live.pyrename to tests/old/sync_live.pydiff --git a/tests/test_action_filters.py b/tests/old/test_action_filters.pysimilarity index 100%rename from tests/test_action_filters.pyrename to tests/old/test_action_filters.pydiff --git a/tests/test_agent_actions.py b/tests/old/test_agent_actions.pysimilarity index 100%rename from tests/test_agent_actions.pyrename to tests/old/test_agent_actions.pydiff --git a/tests/test_clicks.py b/tests/old/test_clicks.pysimilarity index 100%rename from tests/test_clicks.pyrename to tests/old/test_clicks.pydiff --git a/tests/test_core_functionality.py b/tests/old/test_core_functionality.pysimilarity index 100%rename from tests/test_core_functionality.pyrename to tests/old/test_core_functionality.pydiff --git a/tests/test_dropdown.py b/tests/old/test_dropdown.pysimilarity index 100%rename from tests/test_dropdown.pyrename to tests/old/test_dropdown.pydiff --git a/tests/test_dropdown_complex.py b/tests/old/test_dropdown_complex.pysimilarity index 100%rename from tests/test_dropdown_complex.pyrename to tests/old/test_dropdown_complex.pydiff --git a/tests/test_dropdown_error.py b/tests/old/test_dropdown_error.pysimilarity index 100%rename from tests/test_dropdown_error.pyrename to tests/old/test_dropdown_error.pydiff --git a/tests/test_excluded_actions.py b/tests/old/test_excluded_actions.pysimilarity index 100%rename from tests/test_excluded_actions.pyrename to tests/old/test_excluded_actions.pydiff --git a/tests/test_full_screen.py b/tests/old/test_full_screen.pysimilarity index 100%rename from tests/test_full_screen.pyrename to tests/old/test_full_screen.pydiff --git a/tests/test_gif_path.py b/tests/old/test_gif_path.pysimilarity index 100%rename from tests/test_gif_path.pyrename to tests/old/test_gif_path.pydiff --git a/tests/test_google_sheets_real.py b/tests/old/test_google_sheets_real.pysimilarity index 100%rename from tests/test_google_sheets_real.pyrename to tests/old/test_google_sheets_real.pydiff --git a/tests/test_mind2web.py b/tests/old/test_mind2web.pysimilarity index 100%rename from tests/test_mind2web.pyrename to tests/old/test_mind2web.pydiff --git a/tests/test_models.py b/tests/old/test_models.pysimilarity index 100%rename from tests/test_models.pyrename to tests/old/test_models.pydiff --git a/tests/test_qwen.py b/tests/old/test_qwen.pysimilarity index 100%rename from tests/test_qwen.pyrename to tests/old/test_qwen.pydiff --git a/tests/test_react_dropdown.py b/tests/old/test_react_dropdown.pysimilarity index 100%rename from tests/test_react_dropdown.pyrename to tests/old/test_react_dropdown.pydiff --git a/tests/test_self_registered_actions.py b/tests/old/test_self_registered_actions.pysimilarity index 100%rename from tests/test_self_registered_actions.pyrename to tests/old/test_self_registered_actions.pydiff --git a/tests/test_vision.py b/tests/old/test_vision.pysimilarity index 100%rename from tests/test_vision.pyrename to tests/old/test_vision.pydiff --git a/tests/test_wait_for_element.py b/tests/old/test_wait_for_element.pysimilarity index 100%rename from tests/test_wait_for_element.pyrename to tests/old/test_wait_for_element.pydiff --git a/tests/test_action_params.py b/tests/test_action_params.pydeleted file mode 100644index d8f051065..000000000--- a/tests/test_action_params.py+++ /dev/null@@ -1,91 +0,0 @@-import asyncio-import logging-from inspect import signature--import pytest-from pydantic import BaseModel, Field--from browser_use.browser import BrowserSession-from browser_use.controller.registry.service import Registry-from browser_use.controller.registry.views import ActionModel--# Configure logging-logging.basicConfig(level=logging.DEBUG)-logger = logging.getLogger(__name__)---# Test model - renamed to avoid pytest collection warnings-class TestActionParamsModel(ActionModel):- value: str = Field(description='Test value')---# Our Context type for the Registry - renamed to avoid pytest collection warnings-class TestContextHelper:- def __init__(self, value):- self.value = value---async def test_registry_param_handling():- """Test how Registry handles parameter passing for different function signatures."""- # Create a Registry instance- registry = Registry[TestContextHelper]()-- # Create test functions with different signatures-- # 1. Function with browser_session as a positional parameter- @registry.action('Test action with browser_session', param_model=TestActionParamsModel)- async def action_with_browser_session(params: TestActionParamsModel, browser_session: BrowserSession):- logger.debug(f'action_with_browser_session called with params={params}, browser_session={browser_session}')- return {'params': params.model_dump(), 'has_browser': browser_session is not None}-- # 2. Function with browser_session in the model- class ModelWithBrowserSession(BaseModel):- value: str- browser_session: BrowserSession = None-- @registry.action('Test action with browser_session in model')- async def action_with_browser_in_model(params: ModelWithBrowserSession):- logger.debug(f'action_with_browser_in_model called with params={params}')- return {'params': params.model_dump(), 'has_browser': params.browser_session is not None}-- # 3. Function using **kwargs- @registry.action('Test action with kwargs')- async def action_with_kwargs(params: TestActionParamsModel, **kwargs):- logger.debug(f'action_with_kwargs called with params={params}, kwargs={kwargs}')- return {'params': params.model_dump(), 'kwargs': kwargs}-- # Create a mock browser session- mock_browser_session = object() # Just a placeholder-- # Execute the actions- logger.debug('\n\n=== Testing action_with_browser_session ===')- result1 = await registry.execute_action(- 'action_with_browser_session', {'value': 'test1'}, browser_session=mock_browser_session- )- logger.debug(f'Result: {result1}')-- logger.debug('\n\n=== Testing action_with_browser_in_model ===')- result2 = await registry.execute_action(- 'action_with_browser_in_model',- {'value': 'test2', 'browser_session': None}, # Browser session in model is None- browser_session=mock_browser_session, # Browser session in execute_action is provided- )- logger.debug(f'Result: {result2}')-- logger.debug('\n\n=== Testing action_with_kwargs ===')- result3 = await registry.execute_action('action_with_kwargs', {'value': 'test3'}, browser_session=mock_browser_session)- logger.debug(f'Result: {result3}')-- # Print all signatures- logger.debug('\n\n=== Function Signatures ===')- logger.debug(f'action_with_browser_session: {signature(action_with_browser_session)}')- logger.debug(f'action_with_browser_in_model: {signature(action_with_browser_in_model)}')- logger.debug(f'action_with_kwargs: {signature(action_with_kwargs)}')-- return result1, result2, result3---if __name__ == '__main__':- # Run the test- asyncio.run(test_registry_param_handling())diff --git a/tests/test_stress.py b/tests/test_stress.pydeleted file mode 100644index 1b00bb3dc..000000000--- a/tests/test_stress.py+++ /dev/null@@ -1,101 +0,0 @@-import os-import random-import string-import time--import pytest-from langchain_openai import AzureChatOpenAI-from pydantic import SecretStr--from browser_use.agent.service import Agent-from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.controller.service import Controller---async def browser_session():- browser_session = BrowserSession(- browser_profile=BrowserProfile(- headless=True,- )- )- await browser_session.start()- yield browser_session- await browser_session.stop()---def llm():- """Initialize the language model"""- model = AzureChatOpenAI(- api_version='2024-10-21',- model='gpt-4o',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),- )- return model---def generate_random_text(length: int) -> str:- """Generate random text of specified length"""- return ''.join(random.choices(string.ascii_letters + string.digits + ' ', k=length))---async def controller():- """Initialize the controller"""- controller = Controller()- large_text = generate_random_text(10000)-- @controller.action('call this magical function to get very special text')- def get_very_special_text():- return large_text-- yield controller---async def test_token_limit_with_multiple_extractions(llm, controller, browser_session):- """Test handling of multiple smaller extractions accumulating tokens"""- agent = Agent(- task='Call the magical function to get very special text 5 times',- llm=llm,- controller=controller,- browser_session=browser_session,- max_input_tokens=2000,- save_conversation_path='tmp/stress_test/test_token_limit_with_multiple_extractions.json',- )-- history = await agent.run(max_steps=5)-- # check if 5 times called get_special_text- calls = [a for a in history.action_names() if a == 'get_very_special_text']- assert len(calls) == 5- # check the message history should be max 3 messages- assert len(agent.message_manager.history.messages) > 3--[email protected]('max_tokens', [4000]) # 8000 20000-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_session=browser_session,- max_input_tokens=max_tokens,- save_conversation_path='tmp/stress_test/test_open_3_tabs_and_extract_content.json',- )- start_time = time.time()- history = await agent.run(max_steps=7)- end_time = time.time()-- total_time = end_time - start_time-- print(f'Total time: {total_time:.2f} seconds')- # Check for errors- errors = history.errors()- assert len(errors) == 0, 'Errors occurred during the test'- # check if 3 tabs were opened- current_state = await browser_session.get_state_summary()- assert len(current_state.tabs) >= 3, '3 tabs were not opened'