Skip to content

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

more tests cleanup

Nick Sweeting5b2023bcff09
diff --git a/tests/ci/test_sensitive_data.py b/tests/ci/test_agent_sensitive_data.py
similarity index 100%
rename from tests/ci/test_sensitive_data.py
rename to tests/ci/test_agent_sensitive_data.py
diff --git a/tests/ci/test_tab_management.py b/tests/ci/test_browser_session_tab_management.py
similarity index 100%
rename from tests/ci/test_tab_management.py
rename to tests/ci/test_browser_session_tab_management.py
diff --git a/tests/ci/test_browser_via_cdp.py b/tests/ci/test_browser_session_via_cdp.py
similarity index 100%
rename from tests/ci/test_browser_via_cdp.py
rename to tests/ci/test_browser_session_via_cdp.py
diff --git a/tests/ci/test_browser_viewport_and_proxy.py b/tests/ci/test_browser_session_viewport_and_proxy.py
similarity index 100%
rename from tests/ci/test_browser_viewport_and_proxy.py
rename to tests/ci/test_browser_session_viewport_and_proxy.py
diff --git a/tests/ci/test_special_action_parameter_injection.py b/tests/ci/test_controller_action_parameter_injection.py
similarity index 100%
rename from tests/ci/test_special_action_parameter_injection.py
rename to tests/ci/test_controller_action_parameter_injection.py
diff --git a/tests/ci/test_action_registry.py b/tests/ci/test_registry.py
similarity index 100%
rename from tests/ci/test_action_registry.py
rename to tests/ci/test_registry.py
diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.py
index 3e63d15cf..0c27955b0 100644
--- a/tests/test_agent_actions.py
+++ b/tests/test_agent_actions.py
@@ -35,21 +35,15 @@ async def browser_session():
await browser_session.stop()
-async def context(browser_session):
- # BrowserSession manages its own context
- yield browser_session
-
-
# pytest tests/test_agent_actions.py -v -k "test_ecommerce_interaction" --capture=no
# @pytest.mark.asyncio
@pytest.mark.skip(reason='Kinda expensive to run')
-async def test_ecommerce_interaction(llm, context):
+async def test_ecommerce_interaction(llm, browser_session):
"""Test complex ecommerce interaction sequence"""
agent = Agent(
task="Go to amazon.com, search for 'laptop', filter by 4+ stars, and find the price of the first result",
llm=llm,
- browser_context=context,
+ browser_session=browser_session,
save_conversation_path='tmp/test_ecommerce_interaction/conversation',
)
@@ -81,13 +75,12 @@ async def test_ecommerce_interaction(llm, context):
assert 'input_exact_correct' in action_sequence or 'correct_in_input' in action_sequence
-# @pytest.mark.asyncio
-async def test_error_recovery(llm, context):
+async def test_error_recovery(llm, browser_session):
"""Test agent's ability to recover from errors"""
agent = Agent(
task='Navigate to nonexistent-site.com and then recover by going to google.com ',
llm=llm,
- browser_context=context,
+ browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(max_steps=10)
@@ -102,13 +95,12 @@ async def test_error_recovery(llm, context):
break
-# @pytest.mark.asyncio
-async def test_find_contact_email(llm, context):
+async def test_find_contact_email(llm, browser_session):
"""Test agent's ability to find contact email on a website"""
agent = Agent(
task='Go to https://browser-use.com/ and find out the contact email',
llm=llm,
- browser_context=context,
+ browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(max_steps=10)
@@ -123,13 +115,12 @@ async def test_find_contact_email(llm, context):
pytest.fail(f'{extracted_content} does not contain {email}')
-# @pytest.mark.asyncio
-async def test_agent_finds_installation_command(llm, context):
+async def test_agent_finds_installation_command(llm, browser_session):
"""Test agent's ability to find the pip installation command for browser-use on the web"""
agent = Agent(
task='Find the pip installation command for the browser-use repo',
llm=llm,
- browser_context=context,
+ browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(max_steps=10)
@@ -153,7 +144,6 @@ class CaptchaTest(BaseModel):
# run 3 test: python -m pytest tests/test_agent_actions.py -v -k "test_captcha_solver" --capture=no --log-cli-level=INFO
# pytest tests/test_agent_actions.py -v -k "test_captcha_solver" --capture=no --log-cli-level=INFO
@pytest.mark.parametrize(
'captcha',
[
@@ -181,20 +171,20 @@ class CaptchaTest(BaseModel):
),
],
)
-async def test_captcha_solver(llm, context, captcha: CaptchaTest):
+async def test_captcha_solver(llm, browser_session, captcha: CaptchaTest):
"""Test agent's ability to solve different types of captchas"""
agent = Agent(
task=f'Go to {captcha.url} and solve the captcha. {captcha.additional_text}',
llm=llm,
- browser_context=context,
+ browser_session=browser_session,
)
from browser_use.agent.views import AgentHistoryList
history: AgentHistoryList = await agent.run(max_steps=7)
- state = await context.get_state_summary()
-
- all_text = state.element_tree.get_all_text_till_next_clickable_element()
+ # Get page content to verify success
+ page = await browser_session.get_current_page()
+ all_text = await page.content()
if not all_text:
all_text = ''
diff --git a/tests/test_clicks.py b/tests/test_clicks.py
index eb6182d95..74788f9eb 100644
--- a/tests/test_clicks.py
+++ b/tests/test_clicks.py
@@ -2,9 +2,8 @@ import asyncio
import json
import anyio
-import pytest
-from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.dom.views import DOMBaseNode, DOMElementNode, DOMTextNode
from browser_use.utils import time_execution_sync
@@ -29,12 +28,11 @@ class ElementTreeSerializer:
# run with: pytest browser_use/browser/tests/test_clicks.py
async def test_highlight_elements():
- browser = Browser(config=BrowserConfig(headless=False, disable_security=True, user_data_dir=None))
-
- async with await browser.new_context() as context:
- page = await context.get_current_page()
+ browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True))
+ await browser_session.start()
+ try:
+ page = await browser_session.get_current_page()
# await page.goto('https://immobilienscout24.de')
# await page.goto('https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/service-plans')
# await page.goto('https://google.com/search?q=elon+musk')
@@ -49,7 +47,7 @@ async def test_highlight_elements():
while True:
try:
# await asyncio.sleep(10)
- state = await context.get_state_summary(True)
+ state = await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
async with await anyio.open_file('./tmp/page.json', 'w') as f:
await f.write(
@@ -84,13 +82,15 @@ async def test_highlight_elements():
print(state.element_tree.clickable_elements_to_string())
action = input('Select next action: ')
- await time_execution_sync('remove_highlight_elements')(context.remove_highlights)()
+ await time_execution_sync('remove_highlight_elements')(browser_session.remove_highlights)()
node_element = state.selector_map[int(action)]
# check if index of selector map are the same as index of items in dom_items
- await context._click_element_node(node_element)
+ await browser_session._click_element_node(node_element)
except Exception as e:
print(e)
+ finally:
+ await browser_session.stop()
diff --git a/tests/test_dropdown_error.py b/tests/test_dropdown_error.py
index fe1a28d6d..ff6226753 100644
--- a/tests/test_dropdown_error.py
+++ b/tests/test_dropdown_error.py
@@ -7,8 +7,7 @@ Simple try of the agent.
import os
import sys
-from browser_use.browser.browser import Browser, BrowserConfig
-from browser_use.browser.context import BrowserContext
+from browser_use.browser import BrowserProfile, BrowserSession
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -17,24 +16,23 @@ from langchain_openai import ChatOpenAI
from browser_use import Agent, AgentHistoryList
llm = ChatOpenAI(model='gpt-4o')
-# browser = Browser(config=BrowserConfig(headless=False))
+browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True))
agent = Agent(
task=('go to https://codepen.io/shyam-king/pen/emOyjKm and select number "4" and return the output of "selected value"'),
llm=llm,
- browser_context=BrowserContext(
- browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),
- ),
+ browser_session=browser_session,
)
async def test_dropdown():
- history: AgentHistoryList = await agent.run(20)
- # await controller.browser.close(force=True)
-
- result = history.final_result()
- assert result is not None
- assert '4' in result
- print(result)
-
- # await browser.close()
+ await browser_session.start()
+ try:
+ history: AgentHistoryList = await agent.run(20)
+
+ result = history.final_result()
+ assert result is not None
+ assert '4' in result
+ print(result)
+ finally:
+ await browser_session.stop()
diff --git a/tests/test_excluded_actions.py b/tests/test_excluded_actions.py
index d4544283b..193a05a28 100644
--- a/tests/test_excluded_actions.py
+++ b/tests/test_excluded_actions.py
@@ -1,58 +1,43 @@
-import asyncio
-import os
-
import pytest
-from langchain_openai import AzureChatOpenAI
-from pydantic import SecretStr
from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
-from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser import BrowserSession
from browser_use.controller.service import Controller
# run with:
# python -m pytest tests/test_excluded_actions.py -v -k "test_only_open_tab_allowed" --capture=no
[email protected](scope='session')
-def event_loop():
- """Create an instance of the default event loop for each test case."""
- loop = asyncio.get_event_loop_policy().new_event_loop()
- yield loop
- loop.close()
+class MockLLM:
+ """Mock LLM for testing"""
+ async def ainvoke(self, prompt):
+ class MockResponse:
+ content = 'Mocked LLM response'
[email protected](scope='session')
-async def browser(event_loop):
- browser_instance = Browser(
- config=BrowserConfig(
- headless=True,
- )
- )
- yield browser_instance
- await browser_instance.close()
+ return MockResponse()
-async def context(browser):
- async with await browser.new_context() as context:
- yield context
[email protected](scope='module')
+async def browser_session():
+ browser_session = BrowserSession(
+ headless=True,
+ user_data_dir=None,
+ )
+ await browser_session.start()
+ yield browser_session
+ await browser_session.stop()
@pytest.fixture
def llm():
"""Initialize language model for testing"""
- return AzureChatOpenAI(
- model='gpt-4o',
- api_version='2024-10-21',
- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),
- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),
- )
+ return MockLLM()
# pytest tests/test_excluded_actions.py -v -k "test_only_open_tab_allowed" --capture=no
-async def test_only_open_tab_allowed(llm, context):
+async def test_only_open_tab_allowed(llm, browser_session):
"""Test that only open_tab action is available while others are excluded"""
# Create list of all default actions except open_tab
@@ -80,7 +65,7 @@ async def test_only_open_tab_allowed(llm, context):
agent = Agent(
task="Go to google.com and search for 'python programming'",
llm=llm,
- browser_context=context,
+ browser_session=browser_session,
controller=controller,
)
diff --git a/tests/test_gif_path.py b/tests/test_gif_path.py
index d9e327695..84d4b441a 100644
--- a/tests/test_gif_path.py
+++ b/tests/test_gif_path.py
@@ -7,8 +7,7 @@ Simple try of the agent.
import os
import sys
-from browser_use.browser.browser import Browser, BrowserConfig
-from browser_use.browser.context import BrowserContext
+from browser_use.browser import BrowserProfile, BrowserSession
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -18,12 +17,12 @@ from browser_use import Agent, AgentHistoryList
llm = ChatOpenAI(model='gpt-4o')
+browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, disable_security=True))
+
agent = Agent(
task=('go to google.com and search for text "hi there"'),
llm=llm,
- browser_context=BrowserContext(
- browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),
- ),
+ browser_session=browser_session,
generate_gif='./google.gif',
)
@@ -32,9 +31,13 @@ async def test_gif_path():
if os.path.exists('./google.gif'):
os.unlink('./google.gif')
- history: AgentHistoryList = await agent.run(20)
+ await browser_session.start()
+ try:
+ history: AgentHistoryList = await agent.run(20)
- result = history.final_result()
- assert result is not None
+ result = history.final_result()
+ assert result is not None
- assert os.path.exists('./google.gif'), 'google.gif was not created'
+ assert os.path.exists('./google.gif'), 'google.gif was not created'
+ finally:
+ await browser_session.stop()
diff --git a/tests/test_mind2web.py b/tests/test_mind2web.py
index 1e8db557d..8b62cf1db 100644
--- a/tests/test_mind2web.py
+++ b/tests/test_mind2web.py
@@ -2,7 +2,6 @@
Test browser automation using Mind2Web dataset tasks with pytest framework.
"""
-import asyncio
import json
import os
from typing import Any
@@ -12,7 +11,7 @@ from langchain_openai import AzureChatOpenAI
from pydantic import SecretStr
from browser_use.agent.service import Agent
-from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.utils import logger
# Constants
@@ -20,31 +19,19 @@ MAX_STEPS = 50
TEST_SUBSET_SIZE = 10
[email protected](scope='session')
-def event_loop():
- loop = asyncio.get_event_loop_policy().new_event_loop()
- yield loop
- loop.close()
-
-
[email protected](scope='session')
-async def browser(event_loop):
- browser_instance = Browser(
- config=BrowserConfig(
+async def browser_session():
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
headless=True,
)
)
- yield browser_instance
- await browser_instance.close()
+ await browser_session.start()
+ yield browser_session
+ await browser_session.stop()
@pytest.fixture
-async def context(browser):
- async with await browser.new_context() as new_context:
- yield new_context
-
-
[email protected](scope='session')
def test_cases() -> list[dict[str, Any]]:
"""Load test cases from Mind2Web dataset"""
file_path = os.path.join(os.path.dirname(__file__), 'mind2web_data/processed.json')
@@ -72,8 +59,7 @@ def llm():
# run with: pytest -s -v tests/test_mind2web.py:test_random_samples
-async def test_random_samples(test_cases: list[dict[str, Any]], llm, context, validator):
+async def test_random_samples(test_cases: list[dict[str, Any]], llm, browser_session):
"""Test a random sampling of tasks across different websites"""
import random
@@ -87,7 +73,7 @@ async def test_random_samples(test_cases: list[dict[str, Any]], llm, context, va
logger.info(f'--- Random Sample {i}/{len(samples)} ---')
logger.info(f'Task: {task}\n')
- agent = Agent(task, llm, browser_context=context)
+ agent = Agent(task, llm, browser_session=browser_session)
await agent.run()
diff --git a/tests/test_models.py b/tests/test_models.py
index 2ffed8286..8afd6ce1b 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -1,4 +1,3 @@
-import asyncio
import os
import httpx
@@ -11,32 +10,19 @@ from pydantic import SecretStr
from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
-from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser import BrowserProfile, BrowserSession
[email protected](scope='function')
-def event_loop():
- """Create an instance of the default event loop for each test case."""
- loop = asyncio.get_event_loop_policy().new_event_loop()
- yield loop
- loop.close()
-
-
[email protected](scope='function')
-async def browser(event_loop):
- browser_instance = Browser(
- config=BrowserConfig(
+async def browser_session():
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
headless=True,
)
)
- yield browser_instance
- await browser_instance.close()
-
-
-async def context(browser):
- async with await browser.new_context() as context:
- yield context
+ await browser_session.start()
+ yield browser_session
+ await browser_session.stop()
api_key_gemini = SecretStr(os.getenv('GOOGLE_API_KEY') or '')
@@ -105,8 +91,7 @@ async def llm(request):
return request.param
-async def test_model_search(llm, context):
+async def test_model_search(llm, browser_session):
"""Test 'Search Google' action"""
model_name = llm.model if hasattr(llm, 'model') else llm.model_name
print(f'\nTesting model: {model_name}')
@@ -134,7 +119,7 @@ async def test_model_search(llm, context):
agent = Agent(
task="Search Google for 'elon musk' then click on the first result and scroll down.",
llm=llm,
- browser_context=context,
+ browser_session=browser_session,
max_failures=2,
use_vision=use_vision,
)
diff --git a/tests/test_qwen.py b/tests/test_qwen.py
index 7a3334307..f847a4453 100644
--- a/tests/test_qwen.py
+++ b/tests/test_qwen.py
@@ -1,11 +1,9 @@
-import asyncio
-
import pytest
from langchain_ollama import ChatOllama
from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
-from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser import BrowserProfile, BrowserSession
@pytest.fixture
@@ -20,38 +18,25 @@ def llm():
)
[email protected](scope='session')
-def event_loop():
- """Create an instance of the default event loop for each test case."""
- loop = asyncio.get_event_loop_policy().new_event_loop()
- yield loop
- loop.close()
-
-
[email protected](scope='session')
-async def browser(event_loop):
- browser_instance = Browser(
- config=BrowserConfig(
+async def browser_session():
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
headless=True,
)
)
- yield browser_instance
- await browser_instance.close()
-
-
-async def context(browser):
- async with await browser.new_context() as context:
- yield context
+ await browser_session.start()
+ yield browser_session
+ await browser_session.stop()
# pytest tests/test_qwen.py -v -k "test_qwen_url" --capture=no
-# @pytest.mark.asyncio
-async def test_qwen_url(llm, context):
+async def test_qwen_url(llm, browser_session):
"""Test complex ecommerce interaction sequence"""
agent = Agent(
task='go_to_url amazon.com',
llm=llm,
+ browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(max_steps=3)