import json import csv import io import os import tempfile import threading import unittest from pathlib import Path import re from types import SimpleNamespace from unittest.mock import MagicMock, patch from urllib.parse import parse_qs, urlsplit from uuid import uuid4 from fastapi.testclient import TestClient import backend.app as api from architect import repo_cloner from architect.private_artifacts import ensure_private_workspace_dir, private_workspace_dir from challenge_runtime import ChallengeWorkspace COMPREHENSION = {"comprehension_question": "Why does it fail?", "comprehension_model_answer": "The return value is wrong."} class BackendApiTests(unittest.TestCase): def test_free_mentoring_and_function_name_remain_available_after_hints(self): with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root): workspace = Path(root) / "challenge" workspace.mkdir() (workspace / "main.py").write_text("def render(value): return value\n", encoding="utf-8") (workspace / "challenge_state.json").write_text(json.dumps({"target_file": "main.py", "bug_func_names": ["render"], "original_bug_func_sources_list": ["PRIVATE CORRECT SOURCE"]}), encoding="utf-8") session = self.add_session(workspace_path=str(workspace)) session.hints_per_student = 1 session.hints_used = 1 self.mentoring_chat.return_value = {"kind": "chat", "response": "מחרוזת פורמט משלבת ערכים בטקסט."} with patch.object(api, "_persist_challenge_progress"), patch.object(api, "get_hint") as hint: location = self.client.post("/api/challenge/hints", json={"message": "באיזו פונקציה הבעיה?"}).json() explanation = self.client.post("/api/challenge/hints", json={"message": "מה זו מחרוזת פורמט?"}).json() exhausted = self.client.post("/api/challenge/hints", json={"message": "אפשר עוד רמז?"}).json() self.assertIn("render", location["response"]) self.assertIn("מחרוזת פורמט", explanation["response"]) self.assertIn("מכסת הרמזים", exhausted["response"]) for result in (location, explanation, exhausted): self.assertEqual(result["hints_used"], 1) self.assertFalse(result["gave_hint"]) self.assertFalse(result["confirmation_pending"]) hint.assert_not_called() self.assertNotIn("PRIVATE CORRECT SOURCE", str((location, explanation, exhausted))) self.assertIn("PRIVATE CORRECT SOURCE", str(self.mentoring_chat.call_args)) def test_free_chat_does_not_trigger_hint_confirmation(self): with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root): workspace = Path(root) / "challenge" workspace.mkdir() (workspace / "main.py").write_text("value = 0\n", encoding="utf-8") (workspace / "challenge_state.json").write_text(json.dumps({"target_file": "main.py"}), encoding="utf-8") session = self.add_session(workspace_path=str(workspace)) self.mentoring_chat.return_value = {"kind": "chat", "response": "Try running the public tests first."} with patch.object(api, "_persist_challenge_progress"), patch.object(api, "get_hint") as hint: result = self.client.post("/api/challenge/hints", json={"message": "How can I get started?"}).json() self.assertEqual(result["response"], "Try running the public tests first.") self.assertEqual(result["hints_used"], 0) self.assertFalse(result["confirmation_pending"]) self.assertEqual(session.hint_log, []) hint.assert_not_called() def test_mentoring_model_receives_visible_context_and_fails_closed(self): from orchestrator.hint_graph import get_mentoring_chat model = MagicMock() model.invoke.return_value.content = '{"kind":"hint","response":"PRIVATE CLUE"}' with patch("orchestrator.hint_graph.get_llm", return_value=model): result = get_mentoring_chat("help private@example.com", [], "def run(): pass", "public test", ["run"]) self.assertEqual(result, {"kind": "hint", "response": ""}) self.assertNotIn("private@example.com", str(model.invoke.call_args)) self.assertIn("public test", str(model.invoke.call_args)) model.invoke.return_value.content = '{"kind":"chat","response":"הפונקציה אמורה להחזיר את הערך המקורי."}' result = get_mentoring_chat("איך כדאי להתחיל?", [], "def run(): pass", "", ["run"]) self.assertNotIn("הערך המקורי", result["response"]) model.invoke.side_effect = [SimpleNamespace(content='{"kind":"chat","response":"The answer should be 42."}'), SimpleNamespace(content='{"contains_hint":true}')] result = get_mentoring_chat("How should I start?", [], "def run(): pass", "", ["run"], {"correct_functions": ["private fix"]}) self.assertEqual(result["kind"], "chat") self.assertNotIn("42", result["response"]) self.assertNotIn("private fix", result["response"]) model.invoke.side_effect = None model.invoke.return_value.content = "unstructured private clue" self.assertEqual(get_mentoring_chat("help", [], "", "", [])["kind"], "error") def test_hebrew_greeting_is_free_and_does_not_offer_a_hint(self): with tempfile.TemporaryDirectory() as root: session = self.add_session(workspace_path=root) with patch.object(api, "get_hint") as model, patch.object(api, "_persist_challenge_progress"): response = self.client.post("/api/challenge/hints", json={"message": "שלום"}) model.assert_not_called() self.assertEqual(response.status_code, 200) self.assertFalse(response.json()["gave_hint"]) self.assertFalse(response.json()["confirmation_pending"]) self.assertEqual(response.json()["hints_used"], 0) self.assertIn("שלום", response.json()["response"]) self.assertEqual(session.hint_log, []) def test_submitted_result_requires_owner_and_is_not_cached(self): workspace_id = str(uuid4()) path = f"/api/challenges/{workspace_id}/result" self.assertEqual(self.client.get(path).status_code, 401) self.add_session() with patch.object(api, "get_submitted_attempt_result", return_value=None): self.assertEqual(self.client.get(path).status_code, 404) with patch.object(api, "get_submitted_attempt_result", return_value={"round_id": "round", "result": {"score": 80}}) as lookup: response = self.client.get(path) self.assertEqual(response.json()["result"]["score"], 80) self.assertEqual(response.headers["cache-control"], "no-store") self.assertEqual(lookup.call_args.args[1]["user_id"], "test-user") def test_approved_retry_is_claimed_for_current_student_and_job(self): session = self.add_session(api_key="") round_id, request_id = str(uuid4()), str(uuid4()) executor = MagicMock() api.app.state.executor = executor with patch.object(api, "claim_approved_retry", return_value={"admitted": True, "hints_per_student": 5, "hints_used": 2}) as claim: response = self.client.post("/api/challenges", json={"round_id": round_id, "retry_request_id": request_id}) self.assertEqual(response.status_code, 202) job_id = response.json()["job_id"] claim.assert_called_once_with(round_id, request_id, "local", session.identity, job_id) self.assertEqual(executor.submit.call_args.args[-2:], (5, 2)) def test_unavailable_retry_cannot_start_and_failed_queue_releases_claim(self): session = self.add_session(api_key="") round_id, request_id = str(uuid4()), str(uuid4()) api.app.state.executor = MagicMock() with patch.object(api, "claim_approved_retry", return_value={"admitted": False, "reason": "retry_unavailable"}): self.assertEqual(self.client.post("/api/challenges", json={"round_id": round_id, "retry_request_id": request_id}).status_code, 409) with patch.object(api, "claim_approved_retry", return_value={"admitted": True, "hints_per_student": 5, "hints_used": 1}) as claim, patch.object(api, "release_approved_retry") as release: api.app.state.executor.submit.side_effect = RuntimeError("queue unavailable") with self.assertRaises(RuntimeError): self.client.post("/api/challenges", json={"round_id": round_id, "retry_request_id": request_id}) release.assert_called_once_with(request_id, "local", session.identity, claim.call_args.args[-1]) def test_retry_review_requires_instructor_and_pending_authorized_request(self): self.add_session() path = f"/api/instructor/rounds/{uuid4()}/retry-requests/{uuid4()}/review" self.assertEqual(self.client.post(path, json={"decision": "approved"}).status_code, 403) with patch.object(api, "_is_course_instructor", return_value=True), patch.object(api, "review_retry_request", return_value=None): self.assertEqual(self.client.post(path, json={"decision": "approved"}).status_code, 404) self.assertEqual(self.client.post(path, json={"decision": "other"}).status_code, 422) with patch.object(api, "_is_course_instructor", return_value=True), patch.object(api, "review_retry_request", return_value={"status": "denied", "lecturer_response": "Please contact me"}): response = self.client.post(path, json={"decision": "denied", "response": "Please contact me"}) self.assertEqual(response.json(), {"status": "denied", "lecturer_response": "Please contact me"}) self.assertEqual(response.headers["cache-control"], "no-store") def test_retry_request_api_requires_session_and_instructor_role(self): submission_id, round_id = "20261202_120000_123456", str(uuid4()) student_path = f"/api/submissions/{submission_id}/retry-request" instructor_path = f"/api/instructor/rounds/{round_id}/retry-requests" self.assertEqual(self.client.get(student_path).status_code, 401) self.add_session() self.assertEqual(self.client.get(instructor_path).status_code, 403) with patch.object(api, "get_retry_request", return_value=None) as lookup: response = self.client.get(student_path) self.assertEqual(response.json(), {"status": "none"}) self.assertEqual(response.headers["cache-control"], "no-store") self.assertEqual(lookup.call_args.args[1]["user_id"], "test-user") with patch.object(api, "create_retry_request", return_value={"status": "pending"}) as create: response = self.client.post(student_path, json={"reason": " Please retry "}) self.assertEqual(response.json()["status"], "pending") self.assertEqual(create.call_args.args[3], "Please retry") with patch.object(api, "create_retry_request", return_value=None): self.assertEqual(self.client.post(student_path, json={}).status_code, 404) with patch.object(api, "_is_course_instructor", return_value=True), patch.object(api, "get_round_retry_requests", return_value=None): self.assertEqual(self.client.get(instructor_path).status_code, 404) def test_frontend_document_is_not_cached(self): if not hasattr(api, "spa_fallback"): self.skipTest("Frontend build is not present") with tempfile.TemporaryDirectory() as root: Path(root, "index.html").write_text("new version", encoding="utf-8") with patch.object(api, "_FRONTEND_DIST", Path(root)): for path in ("/", "/index.html", "/some-page"): with self.subTest(path=path): response = self.client.get(path) self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["cache-control"], "no-store") self.assertIn("new version", response.text) def test_round_export_raw_histories_and_submission_snapshots(self): self.add_session() round_id = str(uuid4()) path = f"/api/instructor/rounds/{round_id}/export.csv" chat = [{"question": '=SUM(1,2), "hello"\nnext', "response": "+Reply, with quotes \"yes\"", "gave_hint": True, "hint_summary": "Look here", "secret_tests": "PRIVATE CHAT FIELD"}] runs = [{"ran_at": "today", "passed": 1, "total": 2, "secret_tests": "PRIVATE RUN FIELD"}, {"ran_at": "later", "passed": 2, "total": 2}] data = { "attempts": [ {"workspace_id": "a", "auth_provider": "hf", "provider_user_id": "one", "attempt_chat_history": chat, "attempt_hint_history": chat, "public_test_runs": runs, "last_public_test_result": {"passed": 2, "total": 2, "output": "public, output\nline", "per_test": [{"num": 1, "status": "PASS", "expected": "yes", "secret_tests": "PRIVATE TEST FIELD"}], "secret_tests": "PRIVATE RESULT"}}, {"workspace_id": "b", "attempt_chat_history": [{"question": "unfinished", "response": "reply"}]}, ], "submissions": [ {"workspace_id": "a", "auth_provider": "hf", "provider_user_id": "one", "submission_id": "first", "submission_chat_history": chat, "submission_hint_history": chat, "confidence": "4", "known_limitations": '= "edge",\ncase', "self_assessment": {"confidence": 4, "known_limitations": '= "edge",\ncase', "secret_tests": "PRIVATE ASSESSMENT"}}, {"workspace_id": "a", "auth_provider": "hf", "provider_user_id": "one", "submission_id": "second"}, {"workspace_id": "a", "auth_provider": "hf", "provider_user_id": "other", "submission_id": "other"}, ], "feedback": [], } with patch.object(api, "_is_course_instructor", return_value=True), patch.object(api, "get_round_export", return_value=data): response = self.client.get(path) self.assertEqual(response.status_code, 200) rows = list(csv.DictReader(io.StringIO(response.text, newline=""))) self.assertEqual(len(rows), 4) first, second, other, unfinished = rows clean_chat = [{key: value for key, value in chat[0].items() if key != "secret_tests"}] for column in ("attempt_chat_history", "attempt_hint_history", "submission_chat_history", "submission_hint_history"): self.assertEqual(json.loads(first[column]), clean_chat) self.assertEqual(json.loads(first["public_test_runs"]), [{key: value for key, value in run.items() if key != "secret_tests"} for run in runs]) self.assertEqual(json.loads(first["last_public_test_result"])["per_test"], [{"num": 1, "status": "PASS", "expected": "yes"}]) self.assertEqual(json.loads(first["last_public_test_result"])["output"], "public, output\nline") self.assertEqual(json.loads(first["self_assessment"]), {"confidence": 4, "known_limitations": '= "edge",\ncase'}) self.assertEqual(first["known_limitations"], '\'= "edge",\ncase') self.assertEqual(json.loads(second["attempt_chat_history"]), clean_chat) self.assertEqual(json.loads(second["submission_chat_history"]), []) self.assertEqual(json.loads(other["attempt_chat_history"]), []) self.assertEqual(json.loads(unfinished["attempt_chat_history"])[0]["question"], "unfinished") for column in ("attempt_hint_history", "submission_chat_history", "submission_hint_history", "public_test_runs"): self.assertEqual(json.loads(unfinished[column]), []) self.assertNotIn("PRIVATE", response.text) def test_feedback_and_round_export_enforce_roles_and_csv_safety(self): self.add_session() submission_id, round_id = "20261202_120000_123456", str(uuid4()) student_path = f"/api/submissions/{submission_id}/feedback" instructor_path = f"/api/instructor/submissions/{submission_id}/feedback" export_path = f"/api/instructor/rounds/{round_id}/export.csv" with patch.object(api, "get_feedback", return_value={"feedback": "Helpful", "updated_at": "today"}) as lookup: self.assertEqual(self.client.get(student_path).json()["feedback"], "Helpful") self.assertEqual(lookup.call_args.args[1]["user_id"], "test-user") self.assertEqual(self.client.put(instructor_path, json={"feedback": "Hi"}).status_code, 403) self.assertEqual(self.client.get(export_path).status_code, 403) with patch.object(api, "_is_course_instructor", return_value=True), patch.object(api, "save_feedback", return_value=None): self.assertEqual(self.client.put(instructor_path, json={"feedback": "Hi"}).status_code, 404) self.assertEqual(self.client.put(instructor_path, json={"feedback": " "}).status_code, 422) data = {"attempts": [{"workspace_id": "a", "student_name": "=CMD()", "status": "submitted"}, {"workspace_id": "b", "student_name": "No submission"}], "submissions": [{"workspace_id": "a", "submission_id": submission_id, "is_late": True, "comprehension_grade": 0, "student_diff": "+formula", "secret_tests": "NEVER"}], "feedback": [{"submission_id": submission_id, "feedback": "\t=unsafe", "updated_at": "today"}]} with patch.object(api, "_is_course_instructor", return_value=True), patch.object(api, "get_round_export", return_value=data): response = self.client.get(export_path) self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["cache-control"], "no-store") rows = list(csv.DictReader(io.StringIO(response.text))) self.assertEqual(len(rows), 2) self.assertEqual(rows[0]["student_name"], "'=CMD()") self.assertEqual(rows[0]["student_diff"], "'+formula") self.assertEqual(rows[0]["feedback"], "'\t=unsafe") self.assertEqual(rows[0]["comprehension_grade"], "0") self.assertEqual(rows[0]["is_late"], "True") self.assertNotIn("NEVER", response.text) with patch.object(api, "_is_course_instructor", return_value=True), patch.object(api, "get_round_export", return_value=None): self.assertEqual(self.client.get(export_path).status_code, 404) def test_comprehension_grading_is_private_redacted_and_retryable(self): self.add_session() pending = {"status": "pending", "question": "Why?", "model_answer": "Private model answer", "grade": None, "answer": None} model = MagicMock() model.invoke.return_value.content = '{"grade": 2}' with patch.object(api, "get_submission_comprehension", return_value=pending) as lookup, patch.object( api, "save_comprehension_grade", return_value=True ) as save, patch.object(api, "save_comprehension_answer", return_value=True), patch.object(api, "get_llm", return_value=model): question = self.client.get("/api/submissions/20261202_120000_123456/comprehension") graded = self.client.post("/api/submissions/20261202_120000_123456/comprehension", json={"answer": "Test User: private@example.com"}) self.assertEqual(question.json()["question"], "Why?") self.assertNotIn("Private model answer", question.text) self.assertEqual(question.headers["cache-control"], "no-store") self.assertEqual(graded.json()["grade"], 2) self.assertNotIn("Private model answer", graded.text) self.assertNotIn("private@example.com", str(model.invoke.call_args)) self.assertNotIn("Test User", str(model.invoke.call_args)) self.assertEqual(save.call_args.args[-1], 2) self.assertEqual(lookup.call_args.args[1]["user_id"], "test-user") for invalid in ('{"grade": true}', '{"grade": 3}', '{"grade": "2"}', '{"grade": 0, "extra": 1}', 'not json'): model.invoke.return_value.content = invalid with self.subTest(invalid=invalid), patch.object(api, "get_submission_comprehension", return_value=pending), patch.object( api, "save_comprehension_grade" ) as save, patch.object(api, "save_comprehension_answer", return_value=True), patch.object(api, "get_llm", return_value=model): response = self.client.post("/api/submissions/20261202_120000_123456/comprehension", json={"answer": "answer"}) self.assertEqual(response.status_code, 503) save.assert_not_called() with patch.object(api, "get_submission_comprehension", return_value=None), patch.object(api, "save_comprehension_answer") as save_answer, patch.object(api, "get_llm") as get_model: self.assertEqual(self.client.get("/api/submissions/20261202_120000_123456/comprehension").status_code, 404) self.assertEqual(self.client.post("/api/submissions/20261202_120000_123456/comprehension", json={"answer": "answer"}).status_code, 404) save_answer.assert_not_called() get_model.assert_not_called() with patch.object(api, "get_submission_comprehension", return_value={"status": "legacy"}): self.assertEqual(self.client.get("/api/submissions/20261202_120000_123456/comprehension").json(), {"status": "legacy"}) self.assertEqual(self.client.post("/api/submissions/20261202_120000_123456/comprehension", json={"answer": "answer"}).status_code, 409) model.invoke.return_value.content = '{"grade": 0}' with patch.object(api, "get_submission_comprehension", return_value=pending), patch.object( api, "save_comprehension_grade", side_effect=api.ComprehensionStoreError("unavailable") ), patch.object(api, "save_comprehension_answer", return_value=True), patch.object(api, "get_llm", return_value=model): response = self.client.post("/api/submissions/20261202_120000_123456/comprehension", json={"answer": "answer"}) self.assertEqual(response.status_code, 503) self.assertNotIn('"grade":0', response.text) def test_comprehension_persists_before_failure_and_retries_with_owner(self): self.add_session() path = "/api/submissions/20261202_120000_123456/comprehension" state = {"status": "pending", "question": "Why?", "model_answer": "Secret", "answer": None, "grade": None} model = MagicMock() model.invoke.side_effect = [RuntimeError("outage"), MagicMock(content='{"grade": 2}')] def save_answer(submission_id, identity, course_id, answer): self.assertEqual(identity["user_id"], "test-user") state["answer"] = answer return True def save_grade(submission_id, identity, course_id, answer, grade): self.assertEqual(state["answer"], answer) state.update(status="completed", grade=grade) return True with patch.object(api, "get_submission_comprehension", side_effect=lambda *args: dict(state)), patch.object( api, "save_comprehension_answer", side_effect=save_answer ), patch.object(api, "save_comprehension_grade", side_effect=save_grade), patch.object(api, "get_llm", return_value=model): self.assertEqual(self.client.post(path, json={"answer": "My answer"}).status_code, 503) self.assertEqual(self.client.get(path).json(), {"status": "pending", "question": "Why?", "answer": "My answer", "grade": None}) self.assertEqual(self.client.post(path, json={"answer": "My answer"}).json()["grade"], 2) self.assertEqual(self.client.post(path, json={"answer": "Replacement"}).json()["answer"], "My answer") self.assertEqual(model.invoke.call_count, 2) def test_comprehension_conflicts_when_answer_changes_during_grading(self): self.add_session() path = "/api/submissions/20261202_120000_123456/comprehension" pending = {"status": "pending", "question": "Why?", "model_answer": "Secret", "answer": None, "grade": None} changed = {**pending, "answer": "Other answer"} model = MagicMock() model.invoke.return_value.content = '{"grade": 2}' with patch.object(api, "get_submission_comprehension", side_effect=[pending, changed]), patch.object( api, "save_comprehension_answer", return_value=True ), patch.object(api, "save_comprehension_grade", return_value=False) as save, patch.object(api, "get_llm", return_value=model): response = self.client.post(path, json={"answer": "Original answer"}) self.assertEqual(response.status_code, 409) self.assertEqual(save.call_args.args[-2:], ("Original answer", 2)) with patch.object(api, "get_submission_comprehension", side_effect=[pending, {**changed, "status": "completed", "grade": 1}]), patch.object( api, "save_comprehension_answer", return_value=False ), patch.object(api, "get_llm") as get_model: response = self.client.post(path, json={"answer": "Original answer"}) self.assertEqual(response.status_code, 409) get_model.assert_not_called() def test_round_requires_comprehension_authoring_before_publication(self): session = self.add_session(workspace_path="unused-workspace") manifest = {"round_id": str(uuid4()), "timer_minutes": 0} generated = ("Which input exposes the bug?", "An input containing repeated underscores.") workspace = object() with patch.object(api, "_is_course_instructor", return_value=True), patch.object( api, "_workspace", return_value=workspace ), patch.object(api, "_generate_comprehension_content", return_value=generated) as generate, patch.object( api, "create_challenge_round", return_value=manifest ), patch.object(api, "create_challenge_round_archive", return_value=b"bundle"), patch.object( api, "save_challenge_round" ) as save, patch.object(api, "_persist_challenge_progress"): response = self.client.post("/api/challenge-rounds", json={"hints_per_student": 2}) self.assertEqual(response.status_code, 200, response.text) generate.assert_called_once_with(session, workspace) save.assert_called_once_with( manifest, b"bundle", "development:test-user", "local", comprehension_question=generated[0], comprehension_model_answer=generated[1], ) self.assertNotIn(generated[1], response.text) legacy_payload = self.client.post("/api/challenge-rounds", json={ "comprehension_question": "client supplied question", "comprehension_model_answer": "client supplied answer", }) self.assertEqual(legacy_payload.status_code, 422) def test_comprehension_authoring_uses_redacted_bug_context_and_validates_json(self): session = self.add_session(api_key="session-model-key") workspace = SimpleNamespace( target_file="src/names.py", bug_description="The branch accepts a repeated underscore from Test User at private@example.com.", challenge_summary="A normalization bug.", bug_func_names=["normalize"], original_bug_func_sources_list=["def normalize(value):\n return value.replace('__', '_')\n"], bug_func_sources_list=["def normalize(value):\n return value.replace('_', '')\n"], original_bug_func_source="", bug_func_source="", ) model = MagicMock() model.invoke.return_value.content = json.dumps({ "question": "Which input reveals the bug?", "model_answer": "A string containing two underscores in a row.", }) from contextlib import nullcontext with patch.object(api, "_require_model_key"), patch.object( api, "get_llm", return_value=model ) as get_model, patch.object(api, "llm_api_key_context", return_value=nullcontext()): question, answer = self.generate_comprehension_content(session, workspace) self.assertEqual(question, "Which input reveals the bug?") self.assertEqual(answer, "A string containing two underscores in a row.") get_model.assert_called_once_with(temperature=0, request_timeout=60, max_tokens=500) llm_messages = model.invoke.call_args.args[0] self.assertIn("buggy", llm_messages[1].content) self.assertIn("original", llm_messages[1].content) self.assertNotIn("Test User", llm_messages[1].content) self.assertNotIn("private@example.com", llm_messages[1].content) self.assertIn("[REDACTED EMAIL]", llm_messages[1].content) model.invoke.return_value.content = '{"question":"Why?","model_answer":""}' with patch.object(api, "_require_model_key"), patch.object( api, "get_llm", return_value=model ), patch.object(api, "llm_api_key_context", return_value=nullcontext()): with self.assertRaises(api.HTTPException) as error: self.generate_comprehension_content(session, workspace) self.assertEqual(error.exception.status_code, 503) def test_value_error_job_message_exposes_safe_generation_detail(self): self.assertEqual( api._challenge_job_error_message(ValueError("Generated challenge target file is unavailable")), "Challenge generation failed: Generated challenge target file is unavailable", ) message = api._challenge_job_error_message(RuntimeError("Failed to inject 1 bugs (only got 0) in 4 candidate files")) self.assertIn("enough valid tests", message) self.assertNotIn("RuntimeError", message) def setUp(self): self.progress_upload = self.enterContext(patch.object(api, "upload_challenge_progress_to_supabase", return_value=(True, ""))) self.mentoring_chat = self.enterContext(patch.object(api, "get_mentoring_chat", return_value={"kind": "hint", "response": ""})) self.course_role_lookup = self.enterContext(patch.object(api, "get_course_role", return_value=None)) self.generate_comprehension_content = api._generate_comprehension_content self.auto_comprehension = self.enterContext(patch.object( api, "_generate_comprehension_content", return_value=(COMPREHENSION["comprehension_question"], COMPREHENSION["comprehension_model_answer"]), )) self.client_context = TestClient(api.app, base_url="https://testserver") self.client = self.client_context.__enter__() def tearDown(self): self.client_context.__exit__(None, None, None) def add_session(self, *, api_key="test-key", workspace_path=None): session_id = str(uuid4()) session = api.UserSession( session_id=session_id, identity={ "provider": "development", "user_id": "test-user", "username": "test-user", "display_name": "Test User", "profile_url": "", "email": "", }, expires_at=api.time.time() + api.SESSION_TTL_SECONDS, api_key=api_key, identity_verified=True, workspace_path=workspace_path, workspace_id=Path(workspace_path).name if workspace_path else None, ) api.app.state.sessions[session_id] = session self.client.cookies.set(api.SESSION_COOKIE, session_id) return session def test_async_llm_grade_cannot_credit_an_untouched_bug_function(self): record = { "submission": { "bug_function_names": ["result"], "changed_function_names": [], "touched_bug_function": False, }, "scoring": {"test_score": 100, "hint_penalty": 0, "scope_penalty": 0}, } result = dict(record["scoring"]) api._apply_llm_grade(record, result, {"score": 100, "explanation": "Perfect."}) self.assertEqual(result["total_score"], 0) self.assertEqual(record["scoring"]["total_score"], 0) class ImmediateExecutor: def submit(self, function, *args): function(*args) def shutdown(self, wait=False, cancel_futures=False): return None class QueuedExecutor: def __init__(self): self.pending = [] def submit(self, function, *args): self.pending.append((function, args)) def shutdown(self, wait=False, cancel_futures=False): return None def test_health_and_unauthenticated_session(self): self.assertEqual(self.client.get("/health").status_code, 200) favicon = self.client.get("/favicon.svg") self.assertEqual(favicon.status_code, 200) self.assertIn("image/svg+xml", favicon.headers.get("content-type", "")) self.assertEqual(self.client.get("/api/session").json(), {"authenticated": False}) self.assertEqual(self.client.get("/api/challenge").status_code, 401) def test_job_poll_includes_progress_percentage_and_message(self): session = self.add_session() job_id = str(uuid4()) api.app.state.jobs[job_id] = api.ChallengeJob( job_id=job_id, owner_session_id=session.session_id, status="running", progress=50, message="Generating bugs and test cases", ) response = self.client.get(f"/api/jobs/{job_id}") self.assertEqual(response.status_code, 200) self.assertEqual(response.json()["progress"], 50) self.assertEqual(response.json()["message"], "Generating bugs and test cases") def test_expired_session_is_rejected(self): session = self.add_session() session.expires_at = 0 self.assertEqual(self.client.get("/api/challenge").status_code, 401) self.assertFalse(self.client.get("/api/session").json()["authenticated"]) def test_runtime_cleanup_removes_expired_state_but_keeps_active_sessions(self): now = api.time.time() expired_session = self.add_session() expired_session.expires_at = now - 1 active_session_id = str(uuid4()) active_session = api.UserSession( session_id=active_session_id, identity={"provider": "development", "user_id": "active"}, expires_at=now - 1, active_job_id="job-running", ) api.app.state.sessions[active_session_id] = active_session api.app.state.oauth_states.update({ "expired": {"expires_at": now - 1}, "valid": {"expires_at": now + 60}, }) old_job = api.ChallengeJob(job_id="old", owner_session_id="expired", status="completed", created_at=now - api.JOB_RETENTION_SECONDS - 1) running_job = api.ChallengeJob(job_id="running", owner_session_id="active", status="running", created_at=now - api.JOB_RETENTION_SECONDS - 1) api.app.state.jobs.update({"old": old_job, "running": running_job}) removed = api._cleanup_runtime_state_once(api.app, now) self.assertEqual(removed, {"oauth_states": 1, "sessions": 1, "jobs": 1}) self.assertNotIn(expired_session.session_id, api.app.state.sessions) self.assertIn(active_session_id, api.app.state.sessions) self.assertNotIn("expired", api.app.state.oauth_states) self.assertIn("valid", api.app.state.oauth_states) self.assertNotIn("old", api.app.state.jobs) self.assertIn("running", api.app.state.jobs) def test_unverified_identity_session_is_rejected_in_space(self): session = self.add_session() session.identity_verified = False with patch.dict(os.environ, {"SPACE_ID": "owner/course-space"}): response = self.client.get("/api/challenge") self.assertEqual(response.status_code, 403) self.assertEqual(response.json()["detail"], "A verified sign-in is required") def test_mutation_rejects_foreign_origin(self): self.add_session() with patch.dict(os.environ, {"SPACE_ID": "owner/space", "SPACE_HOST": "owner-space.hf.space"}): response = self.client.post("/api/logout", headers={"Origin": "https://evil.example"}) self.assertEqual(response.status_code, 403) self.assertTrue(self.client.get("/api/session").json()["authenticated"]) def test_invalid_repo_url_is_rejected_before_enqueue(self): self.add_session() with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}): response = self.client.post("/api/challenges", json={"github_url": "http://example.com/a/b"}) self.assertEqual(response.status_code, 422) self.assertEqual(api.app.state.jobs, {}) def test_generation_runtime_error_persists_a_safe_failure_category(self): session = self.add_session() job_id = str(uuid4()) job = api.ChallengeJob(job_id=job_id, owner_session_id=session.session_id) api.app.state.jobs[job_id] = job payload = api.ChallengeStartRequest(github_url="https://github.com/acme/demo") with patch.object(api, "create_challenge", side_effect=RuntimeError("Failed to inject 1 bugs (only got 0) in 4 candidate files")), patch.object( api, "record_generation_run" ), patch.object(api, "record_generation_event"), patch.object(api, "record_generation_failures") as record_failures: api._run_challenge_job(job_id, session.session_id, payload, "test-key") self.assertEqual(job.status, "failed") record_failures.assert_called_once_with(job_id, [{ "stage": "challenge_generation", "failure_code": "requested_bug_count_not_met", "prompt_key": "bug_injection", "attempt_number": 1, }]) def test_failed_retry_workspace_releases_reservation(self): session = self.add_session() job_id, request_id = str(uuid4()), str(uuid4()) job = api.ChallengeJob(job_id=job_id, owner_session_id=session.session_id) api.app.state.jobs[job_id] = job payload = api.ChallengeStartRequest(round_id=str(uuid4()), retry_request_id=request_id) with patch.object(api, "create_challenge_from_round", side_effect=RuntimeError("snapshot unavailable")), patch.object(api, "release_approved_retry") as release, patch.object(api, "record_generation_run"), patch.object(api, "record_generation_event"), patch.object(api, "record_generation_failures"): api._run_challenge_job(job_id, session.session_id, payload, "test-key") self.assertEqual(job.status, "failed") release.assert_called_once_with(request_id, "local", session.identity, job_id) def test_github_repository_urls_are_canonicalized_and_spoofing_is_rejected(self): self.assertEqual(api._check_github_url("https://github.com/acme/demo.git/"), "https://github.com/acme/demo") for value in ( "https://github.com@evil.example/acme/demo", "https://github.com.evil.example/acme/demo", "https://github.com/acme/demo/tree/main", "https://github.com/acme/demo?redirect=evil", "https://github.com:bad/acme/demo", ): with self.subTest(value=value), self.assertRaises(api.HTTPException): api._check_github_url(value) def test_course_instructor_can_create_personal_challenge_from_unapproved_repository(self): session = self.add_session() api.app.state.executor = MagicMock() with patch.dict(os.environ, { "SPACE_ID": "owner/course-space", "COURSE_INSTRUCTOR_IDENTITIES": "development:test-user", "COURSE_APPROVED_REPOSITORIES": "https://github.com/acme/approved", }, clear=False), patch.object( api, "reserve_personal_challenge_generation", return_value={"reserved": True} ) as reserve: response = self.client.post("/api/challenges", json={"github_url": "https://github.com/acme/unapproved"}) self.assertEqual(response.status_code, 202) reserve.assert_called_once_with(response.json()["job_id"], session.identity, "owner/course-space", 3) def test_fastapi_serves_built_react_page_and_bundle(self): page = self.client.get("/") self.assertEqual(page.status_code, 200) self.assertIn('
', page.text) match = re.search(r'