import json from unittest.mock import AsyncMock, patch import httpx import pytest from httpx import ASGITransport, MockTransport import ai_cache import ai_provider import llm_reviewer from main import app from routers.github_sync import ( commit_file_to_github_async, github_api_request_async, ) from sandbox import run_python_sandbox_async _real_async_client = httpx.AsyncClient @pytest.mark.asyncio async def test_run_python_sandbox_async(): """Verify non-blocking execution of python sandbox via run_python_sandbox_async.""" user_code = """ def solve(nums): return sum(nums) """ test_cases = [ {"input": [[1, 2, 3]], "expected": 6}, {"input": [[-1, 1]], "expected": 0}, ] result = await run_python_sandbox_async(user_code, test_cases, timeout=5.0) assert result["success"] is True assert len(result["results"]) == 2 assert result["results"][0]["status"] == "passed" assert result["results"][1]["status"] == "passed" @pytest.mark.asyncio async def test_run_python_sandbox_async_failure(): """Verify sandbox reports failed test case asynchronously.""" user_code = """ def solve(nums): return len(nums) """ test_cases = [ {"input": [[1, 2, 3]], "expected": 6}, ] result = await run_python_sandbox_async(user_code, test_cases, timeout=5.0) assert result["success"] is True assert result["results"][0]["status"] == "failed" @pytest.mark.asyncio async def test_generate_ai_content_async_mock(): """Verify generate_ai_content_async dispatches and returns expected text asynchronously.""" with patch( "ai_provider.call_gemini_async", new=AsyncMock(return_value="Async Gemini Response"), ): text, provider = await ai_provider.generate_ai_content_async( system_instruction="System prompt", user_prompt="User message", custom_provider="gemini", custom_api_key="test-api-key", ) assert text == "Async Gemini Response" assert "gemini" in provider @pytest.mark.asyncio async def test_stream_ai_content_async_mock(): """Verify stream_ai_content_async yields streaming chunks asynchronously.""" async def mock_stream(*args, **kwargs): yield "Chunk 1" yield " Chunk 2" with patch("ai_provider.stream_gemini_async", side_effect=mock_stream): chunks = [] async for chunk, _prov in ai_provider.stream_ai_content_async( system_instruction="System prompt", user_prompt="User message", custom_provider="gemini", custom_api_key="test-gemini-key", ): chunks.append(chunk) assert "".join(chunks) == "Chunk 1 Chunk 2" @pytest.mark.asyncio async def test_stream_ai_content_async_prevents_duplicate_on_partial_failure(): """Verify stream_ai_content_async does not yield full-text fallback if chunks were already emitted.""" async def failing_stream(*args, **kwargs): yield "Partial chunk" raise ConnectionResetError("Stream dropped midway") with ( patch("ai_provider.get_secret", return_value="fake_server_key"), patch("ai_provider.stream_gemini_async", side_effect=failing_stream), patch( "ai_provider.generate_ai_content_async", new=AsyncMock(return_value=("Full Fallback Text", "fallback")), ) as mock_gen, ): chunks = [] async for chunk, _prov in ai_provider.stream_ai_content_async( system_instruction="System", user_prompt="Prompt", ): chunks.append(chunk) # Chunks should contain only the partial chunk, NOT the duplicate full fallback text assert chunks == ["Partial chunk"] mock_gen.assert_not_called() @pytest.mark.asyncio async def test_call_groq_async_success_and_error_handling(): """Verify call_groq_async returns content on 200 and surfaces HTTP status errors on failure.""" # 1. Success case def handler_success(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"choices": [{"message": {"content": "Groq Response"}}]}) mock_transport = MockTransport(handler_success) with patch( "httpx.AsyncClient", side_effect=lambda *args, **kwargs: _real_async_client(transport=mock_transport), ): res = await ai_provider.call_groq_async("test_key", "system", "user") assert res == "Groq Response" # 2. HTTP 429 Rate Limit error case def handler_rate_limited(request: httpx.Request) -> httpx.Response: return httpx.Response(429, text="Rate limit exceeded: 30 requests per minute") mock_transport_err = MockTransport(handler_rate_limited) with patch( "httpx.AsyncClient", side_effect=lambda *args, **kwargs: _real_async_client(transport=mock_transport_err), ): with pytest.raises(RuntimeError) as exc_info: await ai_provider.call_groq_async("test_key", "system", "user") assert "429" in str(exc_info.value) assert "Rate limit" in str(exc_info.value) @pytest.mark.asyncio async def test_call_openrouter_async_success_and_error_handling(): """Verify call_openrouter_async returns content on 200 and surfaces HTTP status errors on failure.""" def handler_success(request: httpx.Request) -> httpx.Response: return httpx.Response( 200, json={"choices": [{"message": {"content": "OpenRouter Response"}}]} ) mock_transport = MockTransport(handler_success) with patch( "httpx.AsyncClient", side_effect=lambda *args, **kwargs: _real_async_client(transport=mock_transport), ): res = await ai_provider.call_openrouter_async("test_key", "system", "user") assert res == "OpenRouter Response" def handler_auth_error(request: httpx.Request) -> httpx.Response: return httpx.Response(401, text="Invalid API key provided") mock_transport_err = MockTransport(handler_auth_error) with patch( "httpx.AsyncClient", side_effect=lambda *args, **kwargs: _real_async_client(transport=mock_transport_err), ): with pytest.raises(RuntimeError) as exc_info: await ai_provider.call_openrouter_async("test_key", "system", "user") assert "401" in str(exc_info.value) assert "Invalid API key" in str(exc_info.value) @pytest.mark.asyncio async def test_llm_reviewer_evaluate_code_async(): """Verify evaluate_code_async parses structured JSON evaluation asynchronously.""" fake_eval = { "is_correct": True, "detected_complexity": {"time": "O(N)", "space": "O(1)"}, "bugs": [], "key_suggestion": "Great job!", } with patch( "ai_provider.generate_ai_content_async", new=AsyncMock(return_value=(json.dumps(fake_eval), "mock_provider")), ): res = await llm_reviewer.evaluate_code_async( problem_name="Two Sum", pattern_name="Arrays & Hashing", expected_time="O(N)", expected_space="O(1)", candidate_code="def twoSum(nums, target): pass", ) assert res["is_correct"] is True assert res["detected_complexity"]["time"] == "O(N)" assert res["_provider_used"] == "mock_provider" @pytest.mark.asyncio async def test_llm_reviewer_explain_code_async(): """Verify explain_code_async returns explanations asynchronously.""" with patch( "ai_provider.generate_ai_content_async", new=AsyncMock(return_value=("Detailed step-by-step code explanation", "mock_provider")), ): res = await llm_reviewer.explain_code_async( problem_name="Two Sum", code="def twoSum(): pass", optimal_time="O(N)", optimal_space="O(1)", ) assert "explanation" in res assert res["explanation"] == "Detailed step-by-step code explanation" @pytest.mark.asyncio async def test_generate_challenges_async(): """Verify daily python and sql challenge async generators.""" py_challenge = { "title": "Reverse Linked List", "description": "Reverse list", "difficulty": "Easy", "points": 100, "starter_code": "def solve(head): pass", "test_cases": [{"input": [[]], "expected": []}], } sql_challenge = { "title": "Top Department Salaries", "objective": "Query salaries", "ddl": "CREATE TABLE emp(id INT, salary INT);", "inserts": "INSERT INTO emp VALUES (1, 1000);", "validation_query": "SELECT * FROM emp;", "challenge_type": "SELECT", "points": 150, } with ( patch("ai_cache.get_daily_python_challenge_async", new=AsyncMock(return_value=None)), patch("ai_cache.set_daily_python_challenge_async", new=AsyncMock()), patch( "ai_provider.generate_ai_content_async", new=AsyncMock(return_value=(json.dumps(py_challenge), "mock_gemini")), ), ): p_res = await llm_reviewer.generate_daily_python_challenge_async() assert p_res["title"] == "Reverse Linked List" assert p_res["points"] == 100 with ( patch("ai_cache.get_daily_sql_challenge_async", new=AsyncMock(return_value=None)), patch("ai_cache.set_daily_sql_challenge_async", new=AsyncMock()), patch( "ai_provider.generate_ai_content_async", new=AsyncMock(return_value=(json.dumps(sql_challenge), "mock_gemini")), ), ): s_res = await llm_reviewer.generate_sql_challenge_async() assert s_res["title"] == "Top Department Salaries" assert s_res["challenge_type"] == "SELECT" @pytest.mark.asyncio async def test_fetch_leetcode_problem_async_graphql(): """Verify fetch_leetcode_problem_async handles GraphQL responses via httpx asynchronously.""" mock_problem_json = { "problem_number": 1, "title": "Two Sum", "difficulty": "Easy", "pattern": "Array, Hash Table", "optimal_time": "O(N)", "optimal_space": "O(N)", "description": "Given an array of integers nums and an integer target...", "how_to_solve": "Use a hash map to look up complements in O(1) time.", "examples": [{"input": "nums = [2,7,11,15], target = 9", "output": "[0,1]"}], "constraints": ["2 <= nums.length <= 10^4"], "starter_code": "class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n pass", "reference_code": "class Solution:\n def twoSum(self, nums, target):\n pass", } with ( patch("ai_cache.get_leetcode_problem_async", new=AsyncMock(return_value=None)), patch("ai_cache.set_leetcode_problem_async", new=AsyncMock()), patch( "ai_provider.generate_ai_content_async", new=AsyncMock(return_value=(json.dumps(mock_problem_json), "mock_provider")), ), ): res = await llm_reviewer.fetch_leetcode_problem_async("two-sum") assert res.get("problem_number") == 1 assert res.get("title") == "Two Sum" assert res.get("difficulty") == "Easy" assert "Array" in res.get("pattern", "") @pytest.mark.asyncio async def test_ai_cache_async_helpers(): """Verify ai_cache get_cached_item_async and set_cached_item_async.""" cache_key = "test_key_unit" test_val = {"key": "val_async_test"} # Set cache item await ai_cache.set_cached_item_async(cache_key, test_val) # Get cache item (memory cache hit) retrieved = await ai_cache.get_cached_item_async(cache_key) assert retrieved == test_val @pytest.mark.asyncio async def test_github_api_request_and_commit_async(): """Verify github_api_request_async and commit_file_to_github_async work via httpx mock.""" def gh_handler(request: httpx.Request) -> httpx.Response: url_str = str(request.url) if "/user" in url_str: return httpx.Response(200, json={"login": "octocat", "name": "The Octocat"}) if "/contents/test.py" in url_str: if request.method == "GET": return httpx.Response(404, json={"message": "Not found"}) return httpx.Response( 201, json={ "content": {"html_url": "https://github.com/octocat/repo/blob/main/test.py"}, "commit": {"sha": "abc123commit"}, }, ) return httpx.Response(404, json={"message": "Not found"}) mock_transport = MockTransport(gh_handler) with patch( "httpx.AsyncClient", side_effect=lambda *args, **kwargs: _real_async_client(transport=mock_transport), ): status, user_res = await github_api_request_async("/user", "fake_token") assert status == 200 assert user_res["login"] == "octocat" success, msg, data = await commit_file_to_github_async( "octocat", "test_repo", "test.py", "print('hello')", "test commit", "main", "fake_token" ) assert success is True assert "abc123commit" in data["sha"] @pytest.mark.asyncio async def test_async_fastapi_endpoints(): """Verify calling async FastAPI endpoints directly via httpx AsyncClient.""" transport = ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: # 1. Config endpoint resp = await client.get("/api/config") assert resp.status_code == 200 data = resp.json() assert "apiKey" in data assert "projectId" in data # 2. GitHub oauth status endpoint resp_gh = await client.get("/api/github/oauth/status") assert resp_gh.status_code == 200 assert "configured" in resp_gh.json() # 3. Companion telemetry log & read telemetry_payload = { "tool_name": "hint_requested", "args": {"test": "async_val"}, "success": True, } resp_post = await client.post("/api/companion/telemetry", json=telemetry_payload) assert resp_post.status_code == 200 resp_get = await client.get("/api/companion/telemetry") assert resp_get.status_code == 200 data = resp_get.json() assert "recent_events" in data assert any(e.get("tool_name") == "hint_requested" for e in data["recent_events"]) # 4. Reviews test-run async endpoint test_run_payload = { "code": "class Solution:\n def twoSum(self, nums, target):\n return [0, 1]", "test_cases": [{"input": "nums = [2,7,11,15], target = 9", "expected": "[0, 1]"}], } resp_run = await client.post( "/api/reviews/test-run", json=test_run_payload, headers={"Authorization": "Bearer sandbox"}, ) assert resp_run.status_code == 200 run_data = resp_run.json() assert "success" in run_data # 5. Reviews due endpoint resp_due = await client.get( "/api/reviews/due", headers={"Authorization": "Bearer sandbox"}, ) assert resp_due.status_code == 200 assert isinstance(resp_due.json(), list) # 6. Companion chat stream endpoint (SSE) companion_payload = { "current_floor": 10, "streak_days": 3, "target_goal": "FAANG Prep", "chat_history": [{"sender": "user", "text": "Hi Princess"}], } async def mock_stream_chunks(*args, **kwargs): yield '{"text": "Hello Hero!", "emotion": "smiling_warmly"}', "gemini" with patch("ai_provider.stream_ai_content_async", side_effect=mock_stream_chunks): resp_chat_stream = await client.post( "/api/companion/chat/stream", json=companion_payload, headers={"Authorization": "Bearer sandbox"}, ) assert resp_chat_stream.status_code == 200 assert "text/event-stream" in resp_chat_stream.headers["content-type"] body = resp_chat_stream.text assert "event: done" in body