Spaces:
Running
Running
File size: 16,226 Bytes
664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb a42236e 664a5eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | 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
|