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
fix registry test fixture scopes
Nick Sweetingaf85850b41ce
diff --git a/pyproject.toml b/pyproject.tomlindex 32b37aa25..9243c230d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -159,6 +159,6 @@ dev-dependencies = ["codespell>=2.4.1","pyright>=1.1.399","ty>=0.0.1a1",- "pytest-playwright-asyncio>=0.7.0",+ # "pytest-playwright-asyncio>=0.7.0", # not actually needed I think"pytest-xdist>=3.7.0",]diff --git a/tests/ci/test_registry.py b/tests/ci/test_registry.pyindex a0ff8ea00..557e644f4 100644--- a/tests/ci/test_registry.py+++ b/tests/ci/test_registry.py@@ -101,7 +101,7 @@ def registry():return Registry[TestContext]()[email protected](scope='module')[email protected](scope='session')async def browser_session(base_url):"""Create a real BrowserSession for testing"""browser_session = BrowserSession(@@ -111,7 +111,7 @@ async def browser_session(base_url):await browser_session.start()await browser_session.create_new_tab(f'{base_url}/test')yield browser_session- await browser_session.kill()+ # await browser_session.kill()class TestActionRegistryParameterPatterns:@@ -783,7 +783,7 @@ class TestValidationRules:class TestDecoratedFunctionBehavior:"""Test behavior of decorated action functions (from normalization tests)"""- def test_decorated_function_only_accepts_kwargs(self):+ async def test_decorated_function_only_accepts_kwargs(self):"""Decorated functions should only accept kwargs, no positional args"""registry = Registry()@@ -797,11 +797,9 @@ class TestDecoratedFunctionBehavior:# Should raise error when called with positional argswith pytest.raises(TypeError, match='positional arguments'):- import asyncio+ await click(5, MockBrowserSession())- asyncio.run(click(5, MockBrowserSession()))-- def test_decorated_function_accepts_params_model(self):+ async def test_decorated_function_accepts_params_model(self):"""Decorated function should accept params as model"""registry = Registry()@@ -818,12 +816,10 @@ class TestDecoratedFunctionBehavior:ParamsModel = action.param_model# Should work with params model- import asyncio-- result = asyncio.run(input_text(params=ParamsModel(index=5, text='hello'), browser_session=MockBrowserSession()))+ result = await input_text(params=ParamsModel(index=5, text='hello'), browser_session=MockBrowserSession())assert result.extracted_content == '5:hello'- def test_decorated_function_ignores_extra_kwargs(self):+ async def test_decorated_function_ignores_extra_kwargs(self):"""Decorated function should ignore extra kwargs for easy unpacking"""registry = Registry()@@ -846,9 +842,7 @@ class TestDecoratedFunctionBehavior:action = registry.registry.actions['simple_action']ParamsModel = action.param_model- import asyncio-- result = asyncio.run(simple_action(params=ParamsModel(value=42), **special_context))+ result = await simple_action(params=ParamsModel(value=42), **special_context)assert result.extracted_content == '42'@@ -1005,3 +999,193 @@ class TestParameterOrdering:# Verify the action was properly registeredassert action.name == 'extract_content'assert action.description == 'Extract content from page'+++class TestParamsModelArgsAndKwargs:+ async def test_browser_session_double_kwarg(self):+ """Run the test to diagnose browser_session parameter issue++ This test demonstrates the problem and our fix. The issue happens because:++ 1. In controller/service.py, we have:+ ```python+ @registry.action('Google Sheets: Select a specific cell or range of cells')+ async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):+ return await _select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)+ ```++ 2. When registry.execute_action calls this function, it adds browser_session to extra_args:+ ```python+ # In registry/service.py+ if 'browser_session' in parameter_names:+ extra_args['browser_session'] = browser_session+ ```++ 3. Then later, when calling action.function:+ ```python+ return await action.function(**params_dict, **extra_args)+ ```++ 4. This effectively means browser_session is passed twice:+ - Once through extra_args['browser_session']+ - And again through params_dict['browser_session'] (from the original function)++ The fix is to pass browser_session positionally in select_cell_or_range:+ ```python+ return await _select_cell_or_range(browser_session, cell_or_range)+ ```++ This test confirms that this approach works.+ """++ from browser_use.controller.registry.service import Registry+ from browser_use.controller.registry.views import ActionModel++ # Simple context for testing+ class TestContext:+ pass++ class MockBrowserSession:+ async def get_current_page(self):+ return None++ browser_session = MockBrowserSession()++ # Create registry+ registry = Registry[TestContext]()++ # Model that doesn't include browser_session (renamed to avoid pytest collecting it)+ class CellActionParams(ActionModel):+ value: str = Field(description='Test value')++ # Model that includes browser_session+ class ModelWithBrowser(ActionModel):+ value: str = Field(description='Test value')+ browser_session: BrowserSession = None++ # Create a custom param model for select_cell_or_range+ class CellRangeParams(ActionModel):+ cell_or_range: str = Field(description='Cell or range to select')++ # Use the provided real browser session++ # Test with the real issue: select_cell_or_range+ # logger.info('\n\n=== Test: Simulating select_cell_or_range issue with correct model ===')++ # Define the function without using our registry - this will be a helper function+ async def _select_cell_or_range(browser_session, cell_or_range):+ """Helper function for select_cell_or_range"""+ return f'Selected cell {cell_or_range}'++ # This simulates the actual issue we're seeing in the real code+ # The browser_session parameter is in both the function signature and passed as a named arg+ @registry.action('Google Sheets: Select a cell or range', param_model=CellRangeParams)+ async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):+ # logger.info(f'select_cell_or_range called with browser_session={browser_session}, cell_or_range={cell_or_range}')++ # PROBLEMATIC LINE: browser_session is passed by name, matching the parameter name+ # This is what causes the "got multiple values" error in the real code+ return await _select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)++ # Fix attempt: Register a version that uses positional args instead+ @registry.action('Google Sheets: Select a cell or range (fixed)', param_model=CellRangeParams)+ async def select_cell_or_range_fixed(browser_session: BrowserSession, cell_or_range: str):+ # logger.info(f'select_cell_or_range_fixed called with browser_session={browser_session}, cell_or_range={cell_or_range}')++ # FIXED LINE: browser_session is passed positionally, avoiding the parameter name conflict+ return await _select_cell_or_range(browser_session, cell_or_range)++ # Another attempt: explicitly call using **kwargs to simulate what the registry does+ @registry.action('Google Sheets: Select with kwargs', param_model=CellRangeParams)+ async def select_with_kwargs(browser_session: BrowserSession, cell_or_range: str):+ # logger.info(f'select_with_kwargs called with browser_session={browser_session}, cell_or_range={cell_or_range}')++ # Get params and extra_args, like in Registry.execute_action+ params = {'cell_or_range': cell_or_range, 'browser_session': browser_session}+ extra_args = {'browser_session': browser_session}++ # Try to call _select_cell_or_range with both params and extra_args+ # This will fail with "got multiple values for keyword argument 'browser_session'"+ try:+ # logger.info('Attempting to call with both params and extra_args (should fail):')+ await _select_cell_or_range(**params, **extra_args)+ except TypeError as e:+ # logger.info(f'Expected error: {e}')++ # Remove browser_session from params to avoid the conflict+ params_fixed = dict(params)+ del params_fixed['browser_session']++ # logger.info(f'Fixed params: {params_fixed}')++ # This should work+ result = await _select_cell_or_range(**params_fixed, **extra_args)+ # logger.info(f'Success after fix: {result}')+ return result++ # Test the original problematic version+ # logger.info('\n--- Testing original problematic version ---')+ try:+ result1 = await registry.execute_action(+ 'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=browser_session+ )+ # logger.info(f'Success! Result: {result1}')+ except Exception as e:+ logger.error(f'Error: {str(e)}')++ # Test the fixed version (using positional args)+ # logger.info('\n--- Testing fixed version (positional args) ---')+ try:+ result2 = await registry.execute_action(+ 'select_cell_or_range_fixed', {'cell_or_range': 'A1:F100'}, browser_session=browser_session+ )+ # logger.info(f'Success! Result: {result2}')+ except Exception as e:+ logger.error(f'Error: {str(e)}')++ # Test with kwargs version that simulates what Registry.execute_action does+ # logger.info('\n--- Testing kwargs simulation version ---')+ try:+ result3 = await registry.execute_action(+ 'select_with_kwargs', {'cell_or_range': 'A1:F100'}, browser_session=browser_session+ )+ # logger.info(f'Success! Result: {result3}')+ except Exception as e:+ logger.error(f'Error: {str(e)}')++ # Manual test of our theory: browser_session is passed twice+ # logger.info('\n--- Direct test of our theory ---')+ try:+ # Create the model instance+ params = CellRangeParams(cell_or_range='A1:F100')++ # First check if the extra_args approach works+ # logger.info('Checking if extra_args approach works:')+ extra_args = {'browser_session': browser_session}++ # If we were to modify Registry.execute_action:+ # 1. Check if the function parameter needs browser_session+ parameter_names = ['browser_session', 'cell_or_range']+ browser_keys = ['browser_session', 'browser', 'browser_context']++ # Create params dict+ param_dict = params.model_dump()+ # logger.info(f'params dict before: {param_dict}')++ # Apply our fix: remove browser_session from params dict+ for key in browser_keys:+ if key in param_dict and key in extra_args:+ # logger.info(f'Removing {key} from params dict')+ del param_dict[key]++ # logger.info(f'params dict after: {param_dict}')+ # logger.info(f'extra_args: {extra_args}')++ # This would be the fixed code:+ # return await action.function(**param_dict, **extra_args)++ # Call directly to test+ result3 = await select_cell_or_range(**param_dict, **extra_args)+ # logger.info(f'Success with our fix! Result: {result3}')+ except Exception as e:+ logger.error(f'Error with our manual test: {str(e)}')diff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.pyindex 3f4411062..438e39f6f 100644--- a/tests/test_core_functionality.py+++ b/tests/test_core_functionality.py@@ -1,25 +1,20 @@-import asyncio-import pytestfrom langchain_openai import ChatOpenAIfrom pytest_httpserver import HTTPServer+from browser_use import setup_logging++setup_logging()+from browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryList-from browser_use.browser import BrowserProfile, BrowserSession+from browser_use.browser import BrowserSessionclass TestCoreFunctionality:"""Tests for core functionality of the Agent using real 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')+ @pytest.fixture(scope='session')def http_server(self):"""Create and provide a test HTTP server that serves static content."""server = HTTPServer()@@ -65,24 +60,19 @@ class TestCoreFunctionality:yield serverserver.stop()- @pytest.fixture+ @pytest.fixture(scope='session')def base_url(self, http_server):"""Return the base URL for the test HTTP server."""return f'http://{http_server.host}:{http_server.port}'@pytest.fixture(scope='module')- async def browser_session(self, event_loop):+ async def browser_session(self):"""Create and provide a BrowserSession instance with security disabled."""- browser_session = BrowserSession(- browser_profile=BrowserProfile(- headless=True,- disable_security=True,- )- )+ browser_session = BrowserSession(headless=True, user_data_dir=None)yield browser_session- await browser_session.stop()+ await browser_session.kill()- @pytest.fixture+ @pytest.fixture(scope='module')def llm(self):"""Initialize language model for testing with minimal settings."""return ChatOpenAI(@@ -90,7 +80,6 @@ class TestCoreFunctionality:temperature=0.0,)- @pytest.mark.asyncioasync def test_search_google(self, llm, browser_session, base_url):"""Test 'Search Google' action using a mock search page."""agent = Agent(@@ -103,7 +92,6 @@ class TestCoreFunctionality:assert 'go_to_url' in action_namesassert any('input_text' in action or 'click_element_by_index' in action for action in action_names)- @pytest.mark.asyncioasync def test_go_to_url(self, llm, browser_session, base_url):"""Test 'Navigate to URL' action."""agent = Agent(@@ -119,7 +107,6 @@ class TestCoreFunctionality:page = await browser_session.get_current_page()assert f'{base_url}/page1' in page.url- @pytest.mark.asyncioasync def test_go_back(self, llm, browser_session, base_url):"""Test 'Go back' action."""# First navigate to page1, then to page2, then go back@@ -137,7 +124,6 @@ class TestCoreFunctionality:page = await browser_session.get_current_page()assert f'{base_url}/page1' in page.url- @pytest.mark.asyncioasync def test_click_element(self, llm, browser_session, base_url):"""Test 'Click element' action."""agent = Agent(@@ -154,7 +140,6 @@ class TestCoreFunctionality:page = await browser_session.get_current_page()assert f'{base_url}/page2' in page.url- @pytest.mark.asyncioasync def test_input_text(self, llm, browser_session, base_url):"""Test 'Input text' action."""agent = Agent(@@ -172,7 +157,6 @@ class TestCoreFunctionality:search_value = await page.evaluate("document.getElementById('search-box').value")assert 'OpenAI' in search_value- @pytest.mark.asyncioasync def test_switch_tab(self, llm, browser_session, base_url):"""Test 'Switch tab' action."""agent = Agent(@@ -190,7 +174,6 @@ class TestCoreFunctionality:page = await browser_session.get_current_page()assert f'{base_url}/page1' in page.url- @pytest.mark.asyncioasync def test_open_new_tab(self, llm, browser_session, base_url):"""Test 'Open new tab' action."""agent = Agent(@@ -210,7 +193,6 @@ class TestCoreFunctionality:page = await browser_session.get_current_page()assert f'{base_url}/page2' in page.url- @pytest.mark.asyncioasync def test_extract_page_content(self, llm, browser_session, base_url):"""Test 'Extract page content' action."""agent = Agent(@@ -232,7 +214,6 @@ class TestCoreFunctionality:assert extracted_content is not None, 'Expected content not found in extraction'- @pytest.mark.asyncioasync def test_done_action(self, llm, browser_session, base_url):"""Test 'Complete task' action."""agent = Agent(@@ -248,7 +229,6 @@ class TestCoreFunctionality:# Verify the task was marked as successfulassert history.is_successful()- @pytest.mark.asyncioasync def test_scroll_down(self, llm, browser_session, base_url, http_server):"""Test 'Scroll down' action and validate that the page actually scrolled."""# Create a test page with scrollable content