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
change test_tab_management to use pytest-httpserver for more deterministic tests
Nick Sweetingcef1d43cbfe9
diff --git a/README.md b/README.mdindex 6bd3fcbe7..ce72d3c61 100644--- a/README.md+++ b/README.md@@ -36,7 +36,7 @@ pip install "browser-use[memory]"Install Patchright:```bash-patchright install chromium+patchright install chromium --with-deps --no-shell```Spin up your agent:diff --git a/pyproject.toml b/pyproject.tomlindex 296fb53d6..0f994f8d0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -108,6 +108,7 @@ dev-dependencies = ["build>=1.2.2","pytest>=8.3.5","pytest-asyncio>=0.24.0",+ "pytest-httpserver>=1.0.8","fastapi>=0.115.8","inngest>=0.4.19","uvicorn>=0.34.0",diff --git a/tests/test_tab_management.py b/tests/test_tab_management.pyindex 63c382d7f..8c3bc0072 100644--- a/tests/test_tab_management.py+++ b/tests/test_tab_management.py@@ -3,6 +3,7 @@ import loggingimport pytestfrom dotenv import load_dotenv+from pytest_httpserver import HTTPServerload_dotenv()@@ -32,6 +33,29 @@ class TestTabManagement:yield looploop.close()+ @pytest.fixture(scope='module')+ def http_server(self):+ """Create and provide a test HTTP server that serves static content."""+ server = HTTPServer()+ server.start()++ # Add routes for test pages+ server.expect_request('/page1').respond_with_data(+ '<html><head><title>Test Page 1</title></head><body><h1>Test Page 1</h1></body></html>', content_type='text/html'+ )+ server.expect_request('/page2').respond_with_data(+ '<html><head><title>Test Page 2</title></head><body><h1>Test Page 2</h1></body></html>', content_type='text/html'+ )+ server.expect_request('/page3').respond_with_data(+ '<html><head><title>Test Page 3</title></head><body><h1>Test Page 3</h1></body></html>', content_type='text/html'+ )+ server.expect_request('/page4').respond_with_data(+ '<html><head><title>Test Page 4</title></head><body><h1>Test Page 4</h1></body></html>', content_type='text/html'+ )++ yield server+ server.stop()+@pytest.fixture(scope='module')async def browser(self, event_loop):"""Create and provide a Browser instance with security disabled."""@@ -44,7 +68,7 @@ class TestTabManagement:await browser_instance.close()@pytest.fixture- async def browser_context(self, browser):+ async def browser_context(self, browser, http_server):"""Create and provide a BrowserContext instance with a properly initialized tab."""context = BrowserContext(browser=browser)@@ -56,13 +80,14 @@ class TestTabManagement:await page.close()# Create an initial tab and wait for it to load completely- await context.create_new_tab('https://example.com/page1')+ base_url = f'http://{http_server.host}:{http_server.port}'+ await context.create_new_tab(f'{base_url}/page1')await asyncio.sleep(1) # Wait for the tab to fully initialize# Verify that agent_current_page and human_current_page are properly setassert context.agent_current_page is not Noneassert context.human_current_page is not None- assert 'example.com' in context.agent_current_page.url+ assert f'{http_server.host}:{http_server.port}' in context.agent_current_page.urlyield contextawait context.close()@@ -72,6 +97,11 @@ class TestTabManagement:"""Create and provide a Controller instance."""return Controller()+ @pytest.fixture+ def base_url(self, http_server):+ """Return the base URL for the test HTTP server."""+ return f'http://{http_server.host}:{http_server.port}'+# Helper methodsasync def _execute_action(self, controller, browser_context, action_data):@@ -95,7 +125,7 @@ class TestTabManagement:return result- async def _ensure_synchronized_state(self, browser_context):+ async def _ensure_synchronized_state(self, browser_context, base_url):"""Helper to ensure tab references are properly synchronized before tests."""# Make sure agent_current_page and human_current_page are set and validsession = await browser_context.get_session()@@ -104,8 +134,8 @@ class TestTabManagement:if session.context.pages:browser_context.agent_current_page = session.context.pages[0]else:- # Create a tab with a real website- await browser_context.create_new_tab('https://example.com/page1')+ # Create a tab with the test server+ await browser_context.create_new_tab(f'{base_url}/page1')await asyncio.sleep(1) # Wait longer for tab to initializeif not browser_context.human_current_page or browser_context.human_current_page not in session.context.pages:@@ -139,10 +169,10 @@ class TestTabManagement:# Tab management tests@pytest.mark.asyncio- async def test_open_tab_updates_both_references(self, browser_context):+ async def test_open_tab_updates_both_references(self, browser_context, base_url):"""Test that open_tab correctly updates both tab references."""# Ensure tab references are synchronized- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Store initial tab count and referencessession = await browser_context.get_session()@@ -150,7 +180,7 @@ class TestTabManagement:initial_agent_tab = browser_context.agent_current_page# Open a new tab directly via BrowserContext- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')# Give time for events to processawait asyncio.sleep(1)@@ -164,20 +194,20 @@ class TestTabManagement:assert browser_context.agent_current_page is not Noneassert browser_context.human_current_page == browser_context.agent_current_pageassert initial_agent_tab != browser_context.agent_current_page- assert 'example.com/page2' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.agent_current_page.url@pytest.mark.asyncio- async def test_switch_tab_updates_both_references(self, browser_context):+ async def test_switch_tab_updates_both_references(self, browser_context, base_url):"""Test that switch_tab updates both tab references."""# Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Create a new tab in addition to existing one- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')await asyncio.sleep(1)# Verify we now have the second tab active- assert 'example.com/page2' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.agent_current_page.url# Switch to the first tabsession = await browser_context.get_session()@@ -190,26 +220,26 @@ class TestTabManagement:assert browser_context.agent_current_page is not Noneassert browser_context.human_current_page == browser_context.agent_current_pageassert browser_context.agent_current_page == first_tab- assert 'example.com/page1' in browser_context.agent_current_page.url+ assert f'{base_url}/page1' in browser_context.agent_current_page.url# Verify the underlying page is correct by checking we can interact with itpage = await browser_context.get_agent_current_page()title = await page.title()- assert 'Example' in title+ assert 'Test Page 1' in title@pytest.mark.asyncio- async def test_close_tab_handles_references_correctly(self, browser_context):+ async def test_close_tab_handles_references_correctly(self, browser_context, base_url):"""Test that closing a tab updates references correctly."""# Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Create two tabs with different URLsinitial_tab = browser_context.agent_current_page- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')await asyncio.sleep(1)# Verify the second tab is now active- assert 'example.com/page2' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.agent_current_page.url# Close the current tabawait browser_context.close_current_tab()@@ -221,18 +251,18 @@ class TestTabManagement:assert browser_context.human_current_page == browser_context.agent_current_pageassert browser_context.agent_current_page == initial_tabassert not browser_context.human_current_page.is_closed()- assert 'example.com/page1' in browser_context.human_current_page.url+ assert f'{base_url}/page1' in browser_context.human_current_page.url@pytest.mark.asyncio- async def test_user_changes_tab(self, browser_context):+ async def test_user_changes_tab(self, browser_context, base_url):"""Test that agent_current_page is preserved when user changes the foreground tab."""# Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Create a second tab with a different URL- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')await asyncio.sleep(1)- assert 'example.com/page2' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.agent_current_page.url# Switch back to the first tab for the agentsession = await browser_context.get_session()@@ -243,7 +273,7 @@ class TestTabManagement:# Store agent's active tabagent_tab = browser_context.agent_current_page- assert 'example.com/page1' in agent_tab.url+ assert f'{base_url}/page1' in agent_tab.url# Simulate user switching to the second tabsession = await browser_context.get_session()@@ -262,17 +292,17 @@ class TestTabManagement:# Verify agent_current_page remains unchanged while human_current_page changedassert browser_context.agent_current_page == agent_tabassert browser_context.human_current_page != browser_context.agent_current_page- assert 'example.com/page1' in browser_context.agent_current_page.url- assert 'example.com/page2' in browser_context.human_current_page.url+ assert f'{base_url}/page1' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.human_current_page.url@pytest.mark.asyncio- async def test_get_agent_current_page(self, browser_context):+ async def test_get_agent_current_page(self, browser_context, base_url):"""Test that get_agent_current_page returns agent_current_page regardless of human_current_page."""# Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Create a second tab with a different URL- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')await asyncio.sleep(1)# Switch back to the first tab for the agent@@ -288,20 +318,20 @@ class TestTabManagement:agent_page = await browser_context.get_agent_current_page()assert agent_page == browser_context.agent_current_pageassert agent_page != browser_context.human_current_page- assert 'example.com/page1' in agent_page.url+ assert f'{base_url}/page1' in agent_page.url# Call a method on the page to verify it's fully functionaltitle = await agent_page.title()- assert 'Example' in title+ assert 'Test Page 1' in title@pytest.mark.asyncio- async def test_browser_operations_use_agent_current_page(self, browser_context):+ async def test_browser_operations_use_agent_current_page(self, browser_context, base_url):"""Test that browser operations use agent_current_page, not human_current_page."""# Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Create a second tab with a different URL- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')await asyncio.sleep(1)# Switch back to the first tab for the agent@@ -315,27 +345,27 @@ class TestTabManagement:# Verify we have the setup we wantassert browser_context.human_current_page != browser_context.agent_current_page- assert 'example.com/page2' in browser_context.human_current_page.url- assert 'example.com/page1' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.human_current_page.url+ assert f'{base_url}/page1' in browser_context.agent_current_page.url# Execute a navigation directly on agent's tabagent_page = await browser_context.get_agent_current_page()- await agent_page.goto('https://bing.com')+ await agent_page.goto(f'{base_url}/page3')await asyncio.sleep(0.5)# Verify navigation happened on agent_current_page- assert 'bing.com' in browser_context.agent_current_page.url+ assert f'{base_url}/page3' in browser_context.agent_current_page.url# But human_current_page remains unchanged- assert 'example.com/page2' in browser_context.human_current_page.url+ assert f'{base_url}/page2' in browser_context.human_current_page.url@pytest.mark.asyncio- async def test_tab_reference_recovery(self, browser_context):+ async def test_tab_reference_recovery(self, browser_context, base_url):"""Test recovery when a tab reference becomes invalid."""# Ensure we start with at least one valid tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Create a second tab so we have multiple- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')await asyncio.sleep(1)# Deliberately corrupt the agent_current_page reference@@ -357,10 +387,10 @@ class TestTabManagement:assert browser_context.human_current_page is not None@pytest.mark.asyncio- async def test_reconcile_tab_state_handles_both_invalid(self, browser_context):+ async def test_reconcile_tab_state_handles_both_invalid(self, browser_context, base_url):"""Test that reconcile_tab_state can recover when both tab references are invalid."""# Ensure we start with at least one valid tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Corrupt both referencesbrowser_context.agent_current_page = None@@ -378,15 +408,15 @@ class TestTabManagement:assert not browser_context.agent_current_page.is_closed()@pytest.mark.asyncio- async def test_race_condition_resilience(self, browser_context):+ async def test_race_condition_resilience(self, browser_context, base_url):"""Test resilience against race conditions in tab operations."""# Ensure we start with at least one valid tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Create two more tabs to have three in total- await browser_context.create_new_tab('https://example.com/page2')+ await browser_context.create_new_tab(f'{base_url}/page2')await asyncio.sleep(0.5)- await browser_context.create_new_tab('https://example.com/page3')+ await browser_context.create_new_tab(f'{base_url}/page3')await asyncio.sleep(0.5)# Verify we have at least 3 tabs@@ -407,17 +437,17 @@ class TestTabManagement:# Verify we can still navigate on the final tabpage = await browser_context.get_agent_current_page()- await page.goto('https://example.com/page4')- assert 'example.com/page4' in page.url+ await page.goto(f'{base_url}/page4')+ assert f'{base_url}/page4' in page.url@pytest.mark.asyncio- async def test_tab_management_using_controller_actions(self, browser_context, controller):+ async def test_tab_management_using_controller_actions(self, browser_context, controller, base_url):"""Test tab management using Controller actions instead of directly calling browser_context methods,ensuring that both human and agent tab detection works correctly."""# Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context)+ await self._ensure_synchronized_state(browser_context, base_url)# Make sure we have a clean single tab to start withsession = await browser_context.get_session()@@ -443,25 +473,25 @@ class TestTabManagement:close_tab: CloseTabAction | None = None# Create second tab with OpenTabAction- open_tab_action = {'open_tab': OpenTabAction(url='https://example.com/page2')}+ open_tab_action = {'open_tab': OpenTabAction(url=f'{base_url}/page2')}await controller.act(OpenTabActionModel(**open_tab_action), browser_context)await asyncio.sleep(1) # Wait for the tab to fully initialize# Verify the second tab is opened and active for both agent and humansecond_tab = browser_context.agent_current_pageassert browser_context.human_current_page == browser_context.agent_current_page- assert 'example.com/page2' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.agent_current_page.urlsecond_tab_id = second_tab.page_id if hasattr(second_tab, 'page_id') else 1# Create third tab with OpenTabAction- open_tab_action2 = {'open_tab': OpenTabAction(url='https://example.com/page3')}+ open_tab_action2 = {'open_tab': OpenTabAction(url=f'{base_url}/page3')}await controller.act(OpenTabActionModel(**open_tab_action2), browser_context)await asyncio.sleep(1) # Wait for the tab to fully initialize# Verify the third tab is opened and activethird_tab = browser_context.agent_current_pageassert browser_context.human_current_page == browser_context.agent_current_page- assert 'example.com/page3' in browser_context.agent_current_page.url+ assert f'{base_url}/page3' in browser_context.agent_current_page.urlthird_tab_id = third_tab.page_id if hasattr(third_tab, 'page_id') else 2# Use SwitchTabAction to go back to the first tab (for the agent)@@ -471,7 +501,7 @@ class TestTabManagement:# Verify agent is now on the first tabassert browser_context.agent_current_page == initial_tab- assert 'example.com/page1' in browser_context.agent_current_page.url+ assert f'{base_url}/page1' in browser_context.agent_current_page.urlassert browser_context.human_current_page == browser_context.agent_current_page# Simulate human switching to the second tab@@ -482,21 +512,21 @@ class TestTabManagement:assert browser_context.human_current_page == second_tabassert browser_context.agent_current_page == initial_tabassert browser_context.human_current_page != browser_context.agent_current_page- assert 'example.com/page2' in browser_context.human_current_page.url- assert 'example.com/page1' in browser_context.agent_current_page.url+ assert f'{base_url}/page2' in browser_context.human_current_page.url+ assert f'{base_url}/page1' in browser_context.agent_current_page.url# Use GoToUrlAction to navigate the agent's tab to a new URL- goto_action = {'go_to_url': GoToUrlAction(url='https://example.com/page4')}+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/page4')}await controller.act(GoToUrlActionModel(**goto_action), browser_context)await asyncio.sleep(0.5)# Refresh the agent's page reference and verify navigationagent_page = await browser_context.get_agent_current_page()assert agent_page is not None- assert 'example.com/page4' in agent_page.url+ assert f'{base_url}/page4' in agent_page.url# Verify human's tab remains unchanged- assert 'example.com/page2' in browser_context.human_current_page.url+ assert f'{base_url}/page2' in browser_context.human_current_page.url# Use CloseTabAction to close the third tabclose_tab_action = {'close_tab': CloseTabAction(page_id=third_tab_id)}@@ -524,4 +554,4 @@ class TestTabManagement:# Verify the URL of the remaining tabfinal_page = await browser_context.get_current_page()- assert 'example.com' in final_page.url+ assert f'{base_url}' in final_page.url