import sys from unittest.mock import MagicMock # Stub browser_use before it's imported by browser_agent (not installed locally) sys.modules.setdefault("browser_use", MagicMock()) import pytest import asyncio from unittest.mock import patch, AsyncMock import os os.environ.setdefault("OPENROUTER_API_KEY", "test-key") @pytest.mark.asyncio async def test_run_task_returns_result_dict(): mock_agent = MagicMock() mock_agent.run = AsyncMock(return_value="Found pricing: $29/mo starter") with patch("browser_agent.Agent", return_value=mock_agent): import browser_agent result = await browser_agent.run_task("find pricing on example.com") assert result["result"] == "Found pricing: $29/mo starter" assert "screenshots" in result assert result["screenshots"] == [] @pytest.mark.asyncio async def test_run_task_retries_with_fallback_on_429(): call_count = 0 async def flaky_execute(llm, task, timeout): nonlocal call_count call_count += 1 if call_count == 1: raise Exception("Error 429: rate limit exceeded") return {"result": "fallback worked", "screenshots": []} with patch("browser_agent._execute", side_effect=flaky_execute): import browser_agent result = await browser_agent.run_task("test task") assert result["result"] == "fallback worked" assert call_count == 2 @pytest.mark.asyncio async def test_run_task_raises_on_non_rate_limit_error(): async def failing_execute(llm, task, timeout): raise ValueError("unexpected error") with patch("browser_agent._execute", side_effect=failing_execute): import browser_agent with pytest.raises(ValueError, match="unexpected error"): await browser_agent.run_task("test task")