Skip to content

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

Refactor navigation tests to improve structure and reliability

Magnus Müller9677cec34306
diff --git a/tests/ci/test_browser_event_NavigateToUrlEvent.py b/tests/ci/test_browser_event_NavigateToUrlEvent.py
index e77c10b10..3b35c9de0 100644
--- a/tests/ci/test_browser_event_NavigateToUrlEvent.py
+++ b/tests/ci/test_browser_event_NavigateToUrlEvent.py
@@ -152,28 +152,6 @@ class TestNavigateToUrlEvent:
current_url = await browser_session.get_current_page_url()
assert f'{base_url}/page2' in current_url
- async def test_navigate_relative_url(self, tools, browser_session, base_url):
- """Test navigating using relative URLs."""
- # First navigate to base URL
- action_data = {'go_to_url': GoToUrlAction(url=base_url, new_tab=False)}
-
- class GoToUrlActionModel(ActionModel):
- go_to_url: GoToUrlAction | None = None
-
- await tools.act(GoToUrlActionModel(**action_data), browser_session)
-
- # Now navigate using relative URL
- relative_action = {'go_to_url': GoToUrlAction(url='/page1', new_tab=False)}
- result = await tools.act(GoToUrlActionModel(**relative_action), browser_session)
-
- # Verify navigation worked
- assert isinstance(result, ActionResult)
- assert result.extracted_content is not None
-
- # Check we're on the right page
- current_url = await browser_session.get_current_page_url()
- assert f'{base_url}/page1' in current_url
-
async def test_navigate_javascript_url(self, tools, browser_session, base_url):
"""Test that javascript: URLs are handled appropriately."""
# Navigate to a normal page first
diff --git a/tests/ci/test_browser_event_NavigateToUrlEvent2.py b/tests/ci/test_browser_event_NavigateToUrlEvent2.py
index 0638aebb4..2b6410e8b 100644
--- a/tests/ci/test_browser_event_NavigateToUrlEvent2.py
+++ b/tests/ci/test_browser_event_NavigateToUrlEvent2.py
@@ -152,159 +152,6 @@ async def test_navigation_events_slow_page_with_timeout(httpserver):
await session.stop()
-async def test_navigation_events_history_pushstate(httpserver):
- """Test that history.pushState/popState behavior and that clicking links produces NavigationCompleteEvent."""
- # Set up a page with JavaScript that manipulates history and contains navigation links
- html_content = """
- <html>
- <head><title>History Test</title></head>
- <body>
- <h1>History and Navigation Test</h1>
- <button id="push-btn" onclick="pushState()">Push State</button>
- <button id="pop-btn" onclick="history.back()">Pop State</button>
- <a id="same-tab-link" href="/target-page">Same Tab Link</a>
- <a id="new-tab-link" href="/target-page" target="_blank">New Tab Link</a>
- <div id="status">Initial state</div>
- <script>
- function pushState() {
- history.pushState({page: 'new'}, 'New Page', '/new-path');
- document.getElementById('status').textContent = 'Pushed new state';
- }
-
- window.addEventListener('popstate', function(event) {
- document.getElementById('status').textContent = 'Popped state: ' + JSON.stringify(event.state);
- });
- </script>
- </body>
- </html>
- """
-
- target_page = """
- <html>
- <head><title>Target Page</title></head>
- <body><h1>Target Page Loaded</h1></body>
- </html>
- """
-
- httpserver.expect_request('/history-test').respond_with_data(html_content, status=200, content_type='text/html')
- httpserver.expect_request('/target-page').respond_with_data(target_page, status=200, content_type='text/html')
-
- test_url = httpserver.url_for('/history-test')
- target_url = httpserver.url_for('/target-page')
-
- profile = BrowserProfile(headless=True)
- session = BrowserSession(browser_profile=profile)
-
- # Track navigation events
- navigation_complete_events = []
- tab_created_events = []
- session.event_bus.on(NavigationCompleteEvent, lambda e: navigation_complete_events.append(e))
- session.event_bus.on(TabCreatedEvent, lambda e: tab_created_events.append(e))
-
- try:
- # Start browser
- await session.start()
-
- # Navigate to the test page
- session.event_bus.dispatch(NavigateToUrlEvent(url=test_url))
- await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
-
- # Clear previous events to focus on history and link events
- navigation_complete_events.clear()
- tab_created_events.clear()
-
- # Get browser state to interact with the page
- state = await session.get_browser_state_summary()
-
- # Test 1: history.pushState (should NOT trigger NavigationCompleteEvent)
- push_button_found = False
- for idx, element in state.dom_state.selector_map.items():
- if hasattr(element, 'attributes') and element.attributes.get('id') == 'push-btn':
- push_button_found = True
- click_element = await session.get_dom_element_by_index(idx)
- if click_element is not None:
- session.event_bus.dispatch(ClickElementEvent(node=click_element))
- break
-
- assert push_button_found, 'Should find push state button'
-
- # Wait for pushState to execute
- await asyncio.sleep(1.0)
-
- # Verify history.pushState does NOT trigger NavigationCompleteEvent (expected behavior)
- assert len(navigation_complete_events) == 0, 'history.pushState should not trigger NavigationCompleteEvent'
-
- # Test 2: Same tab link click (should trigger NavigationCompleteEvent)
- state = await session.get_browser_state_summary()
- same_tab_link_found = False
-
- for idx, element in state.dom_state.selector_map.items():
- if hasattr(element, 'attributes') and element.attributes.get('id') == 'same-tab-link':
- same_tab_link_found = True
- click_element = await session.get_dom_element_by_index(idx)
- if click_element is not None:
- session.event_bus.dispatch(ClickElementEvent(node=click_element))
- break
-
- assert same_tab_link_found, 'Should find same tab link'
-
- # Wait for navigation to complete
- nav_complete: NavigationCompleteEvent = cast(
- NavigationCompleteEvent, await session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
- )
-
- assert nav_complete.url == target_url, f'Should navigate to {target_url}'
- assert nav_complete.error_message is None, 'Link navigation should succeed'
-
- # Test 3: New tab link click (may trigger TabCreatedEvent and/or NavigationCompleteEvent)
- # Navigate back to main page first
- session.event_bus.dispatch(NavigateToUrlEvent(url=test_url))
- await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
-
- # Clear events
- navigation_complete_events.clear()
- tab_created_events.clear()
-
- state = await session.get_browser_state_summary()
- new_tab_link_found = False
-
- for idx, element in state.dom_state.selector_map.items():
- if hasattr(element, 'attributes') and element.attributes.get('id') == 'new-tab-link':
- new_tab_link_found = True
- # Use new_tab=True parameter to properly trigger new tab behavior
- click_element = await session.get_dom_element_by_index(idx)
- if click_element is not None:
- session.event_bus.dispatch(ClickElementEvent(node=click_element, while_holding_ctrl=True))
- break
-
- if new_tab_link_found:
- # Wait for either new tab creation or navigation
- await asyncio.sleep(2.0) # Give time for tab creation and navigation
-
- # Should have either tab creation or navigation event (or both)
- has_new_tab_activity = len(tab_created_events) > 0 or len(navigation_complete_events) > 0
- assert has_new_tab_activity, 'New tab link should trigger tab creation or navigation'
-
- if navigation_complete_events:
- nav_complete = navigation_complete_events[-1]
- assert target_url in nav_complete.url or nav_complete.error_message is None, (
- f'New tab navigation should succeed, got: {nav_complete.error_message}'
- )
-
- # Test 4: Verify that normal navigation still works after history manipulation
- session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>After history test</h1>'))
- nav_complete_final: NavigationCompleteEvent = cast(
- NavigationCompleteEvent, await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
- )
-
- assert nav_complete_final.url == 'data:text/html,<h1>After history test</h1>'
- assert nav_complete_final.error_message is None
-
- finally:
- await session.stop()
-
-
@pytest.mark.asyncio
async def test_navigation_events_link_clicks(httpserver):
"""Test that clicking links (same tab and new tab) triggers NavigationCompleteEvent."""
diff --git a/tests/ci/test_browser_session_element_cache.py b/tests/ci/test_browser_session_element_cache.py
index e0b733c0b..99b4d0673 100644
--- a/tests/ci/test_browser_session_element_cache.py
+++ b/tests/ci/test_browser_session_element_cache.py
@@ -166,13 +166,15 @@ async def test_assumption_3_action_gets_same_selector_map(browser_session, tools
@pytest.mark.asyncio
async def test_assumption_4_click_action_specific_issue(browser_session, tools, httpserver):
"""Test assumption 4: Specific issue with click_element_by_index action."""
- # Go to a simple page
- page = await browser_session.get_current_page()
- await page.goto(httpserver.url_for('/'))
- await page.wait_for_load_state()
+ # Go to a simple page using CDP events
+ from browser_use.browser.events import NavigateToUrlEvent
+
+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))
+ await event
+ await event.event_result(raise_if_any=True, raise_if_none=False)
# Trigger DOM processing and cache
- await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)
cached_selector_map = await browser_session.get_selector_map()
print('Pre-click state:')
@@ -201,8 +203,8 @@ async def test_assumption_4_click_action_specific_issue(browser_session, tools,
extracted_content=f'Debug: Element {index} found in map of size {len(selector_map)}', include_in_memory=False
)
- # Test with index 0
- result = await tools.registry.execute_action('test_debug_click_logic', {'index': 0}, browser_session=browser_session)
+ # Test with index 1 (elements start at 1, not 0)
+ result = await tools.registry.execute_action('test_debug_click_logic', {'index': 1}, browser_session=browser_session)
print(f'Debug click result: {result.extracted_content or result.error}')
diff --git a/tests/ci/test_registry_action_parameter_injection.py b/tests/ci/test_registry_action_parameter_injection.py
index f74dbd5b0..183ed6d57 100644
--- a/tests/ci/test_registry_action_parameter_injection.py
+++ b/tests/ci/test_registry_action_parameter_injection.py
@@ -139,13 +139,13 @@ class TestBrowserContext:
await event
# Get the current page
- page = await browser_session.get_current_page()
+ url = await browser_session.get_current_page_url()
# Verify the page URL matches what we navigated to
- assert f'{base_url}/' in page.url
+ assert f'{base_url}/' in url
# Verify the page title
- title = await page.title()
+ title = await browser_session.get_current_page_title()
assert title == 'Test Home Page'
@pytest.mark.asyncio