Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ·
6118488
1
Parent(s): a3925c9
deploy: backend from 37a7da1
Browse files- main.py +83 -9
- services/user_provisioning_service.py +8 -3
- tests/test_api.py +69 -12
- tests/test_quiz_cap.py +4 -4
- tests/test_user_provisioning_service.py +30 -0
main.py
CHANGED
|
@@ -4434,6 +4434,14 @@ def _normalize_class_records(
|
|
| 4434 |
}
|
| 4435 |
)
|
| 4436 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4437 |
|
| 4438 |
lrn_value = str(student.get("lrn", "")).strip()
|
| 4439 |
email_value = str(student.get("email", "")).strip().lower()
|
|
@@ -4455,12 +4463,23 @@ def _normalize_class_records(
|
|
| 4455 |
continue
|
| 4456 |
|
| 4457 |
defaulted_metrics: Set[str] = set()
|
|
|
|
| 4458 |
for field in ["engagementScore", "avgQuizScore", "attendance", "assignmentCompletion"]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4459 |
numeric_value, parse_warning = _safe_numeric(student.get(field))
|
|
|
|
|
|
|
|
|
|
| 4460 |
student[field] = numeric_value
|
| 4461 |
if parse_warning:
|
| 4462 |
warnings_for_row.append(f"{field}: {parse_warning}")
|
| 4463 |
defaulted_metrics.add(field)
|
|
|
|
|
|
|
|
|
|
| 4464 |
|
| 4465 |
student_id, term, assessment_name, dedup_key = _build_record_identity(student, unknown_fields)
|
| 4466 |
student["name"] = student_name
|
|
@@ -5401,10 +5420,10 @@ class AdminCreateUserRequest(BaseModel):
|
|
| 5401 |
role: str
|
| 5402 |
status: str
|
| 5403 |
grade: str
|
| 5404 |
-
section: str
|
| 5405 |
lrn: Optional[str] = None
|
| 5406 |
|
| 5407 |
-
@field_validator("name", "email", "password", "confirmPassword", "role", "status", "grade"
|
| 5408 |
@classmethod
|
| 5409 |
def _strip_required(cls, value: str) -> str:
|
| 5410 |
return str(value or "").strip()
|
|
@@ -6026,8 +6045,12 @@ async def preview_student_account_import(
|
|
| 6026 |
issues: List[str] = []
|
| 6027 |
if not first_name:
|
| 6028 |
issues.append(f"Row {row_number}: Missing firstName")
|
|
|
|
|
|
|
| 6029 |
if not last_name:
|
| 6030 |
issues.append(f"Row {row_number}: Missing lastName")
|
|
|
|
|
|
|
| 6031 |
if not student_id:
|
| 6032 |
issues.append(f"Row {row_number}: Missing studentId/lrn")
|
| 6033 |
elif not re.fullmatch(r"\d{12}", student_id):
|
|
@@ -6467,7 +6490,38 @@ async def commit_student_account_import(
|
|
| 6467 |
existing_profile_doc = docs[0]
|
| 6468 |
existing_uid = docs[0].id
|
| 6469 |
except Exception as duplicate_err:
|
| 6470 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6471 |
|
| 6472 |
try:
|
| 6473 |
roster_rows = list(
|
|
@@ -6493,7 +6547,21 @@ async def commit_student_account_import(
|
|
| 6493 |
)
|
| 6494 |
continue
|
| 6495 |
except Exception as roster_err:
|
| 6496 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6497 |
|
| 6498 |
auth_uid: Optional[str] = None
|
| 6499 |
temporary_password: Optional[str] = None
|
|
@@ -11444,6 +11512,7 @@ async def _regenerate_quiz_json_strict(
|
|
| 11444 |
def _validate_quiz_questions(
|
| 11445 |
questions: List[Dict[str, Any]],
|
| 11446 |
distribution: List[Dict[str, str]],
|
|
|
|
| 11447 |
topic_provenance_map: Optional[Dict[str, Dict[str, Optional[str]]]] = None,
|
| 11448 |
) -> List[QuizQuestion]:
|
| 11449 |
"""Validate and normalise each question from the LLM response."""
|
|
@@ -11514,7 +11583,7 @@ def _validate_quiz_questions(
|
|
| 11514 |
question_type = "identification"
|
| 11515 |
options = None
|
| 11516 |
|
| 11517 |
-
question_topic = str(q.get("topic", "General"))
|
| 11518 |
question_provenance = None
|
| 11519 |
if topic_provenance_map:
|
| 11520 |
question_provenance = topic_provenance_map.get(_topic_key(question_topic))
|
|
@@ -11545,9 +11614,9 @@ async def generate_quiz(http_request: Request, request: QuizGenerationRequest):
|
|
| 11545 |
Supports Bloom's Taxonomy integration, multiple question types,
|
| 11546 |
and graph-based identification questions.
|
| 11547 |
"""
|
| 11548 |
-
# Quiz item cap —
|
| 11549 |
-
if request.numQuestions >
|
| 11550 |
-
raise HTTPException(status_code=400, detail="capped at
|
| 11551 |
|
| 11552 |
try:
|
| 11553 |
|
|
@@ -11760,6 +11829,10 @@ Remember:
|
|
| 11760 |
f"LLM generated {len(parsed_questions)}/{request.numQuestions} questions "
|
| 11761 |
f"after {max_attempts} attempts (raw length={len(raw_content)} chars)."
|
| 11762 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11763 |
|
| 11764 |
topic_provenance_map: Dict[str, Dict[str, Optional[str]]] = {}
|
| 11765 |
for imported_topic in (imported_topics_payload.get("topics") or []):
|
|
@@ -11777,8 +11850,9 @@ Remember:
|
|
| 11777 |
}
|
| 11778 |
|
| 11779 |
validated = _validate_quiz_questions(
|
| 11780 |
-
parsed_questions,
|
| 11781 |
distribution,
|
|
|
|
| 11782 |
topic_provenance_map=topic_provenance_map,
|
| 11783 |
)
|
| 11784 |
total_points = sum(q.points for q in validated)
|
|
|
|
| 4434 |
}
|
| 4435 |
)
|
| 4436 |
continue
|
| 4437 |
+
if re.fullmatch(r"[A-Za-z]", student_name):
|
| 4438 |
+
rejected_rows.append(
|
| 4439 |
+
{
|
| 4440 |
+
"row": int(idx) + 2,
|
| 4441 |
+
"reason": f"Row {int(idx) + 2}: single-character learner name is invalid; row quarantined.",
|
| 4442 |
+
}
|
| 4443 |
+
)
|
| 4444 |
+
continue
|
| 4445 |
|
| 4446 |
lrn_value = str(student.get("lrn", "")).strip()
|
| 4447 |
email_value = str(student.get("email", "")).strip().lower()
|
|
|
|
| 4463 |
continue
|
| 4464 |
|
| 4465 |
defaulted_metrics: Set[str] = set()
|
| 4466 |
+
invalid_score_reason: Optional[str] = None
|
| 4467 |
for field in ["engagementScore", "avgQuizScore", "attendance", "assignmentCompletion"]:
|
| 4468 |
+
raw_score = str(student.get(field) or "").strip()
|
| 4469 |
+
if re.search(r"%\s*$", raw_score):
|
| 4470 |
+
invalid_score_reason = f"Row {int(idx) + 2}: {field} is a percentage-formatted score, expected a raw mark; row quarantined."
|
| 4471 |
+
break
|
| 4472 |
numeric_value, parse_warning = _safe_numeric(student.get(field))
|
| 4473 |
+
if (parse_warning and parse_warning.startswith("invalid numeric value")) or not math.isfinite(numeric_value) or not 0 <= numeric_value <= 100:
|
| 4474 |
+
invalid_score_reason = f"Row {int(idx) + 2}: {field} must be a numeric raw mark from 0 to 100; row quarantined."
|
| 4475 |
+
break
|
| 4476 |
student[field] = numeric_value
|
| 4477 |
if parse_warning:
|
| 4478 |
warnings_for_row.append(f"{field}: {parse_warning}")
|
| 4479 |
defaulted_metrics.add(field)
|
| 4480 |
+
if invalid_score_reason:
|
| 4481 |
+
rejected_rows.append({"row": int(idx) + 2, "reason": invalid_score_reason})
|
| 4482 |
+
continue
|
| 4483 |
|
| 4484 |
student_id, term, assessment_name, dedup_key = _build_record_identity(student, unknown_fields)
|
| 4485 |
student["name"] = student_name
|
|
|
|
| 5420 |
role: str
|
| 5421 |
status: str
|
| 5422 |
grade: str
|
| 5423 |
+
section: str = ""
|
| 5424 |
lrn: Optional[str] = None
|
| 5425 |
|
| 5426 |
+
@field_validator("name", "email", "password", "confirmPassword", "role", "status", "grade")
|
| 5427 |
@classmethod
|
| 5428 |
def _strip_required(cls, value: str) -> str:
|
| 5429 |
return str(value or "").strip()
|
|
|
|
| 6045 |
issues: List[str] = []
|
| 6046 |
if not first_name:
|
| 6047 |
issues.append(f"Row {row_number}: Missing firstName")
|
| 6048 |
+
elif len(first_name) < 2:
|
| 6049 |
+
issues.append(f"Row {row_number}: firstName must contain at least 2 characters")
|
| 6050 |
if not last_name:
|
| 6051 |
issues.append(f"Row {row_number}: Missing lastName")
|
| 6052 |
+
elif len(last_name) < 2:
|
| 6053 |
+
issues.append(f"Row {row_number}: lastName must contain at least 2 characters")
|
| 6054 |
if not student_id:
|
| 6055 |
issues.append(f"Row {row_number}: Missing studentId/lrn")
|
| 6056 |
elif not re.fullmatch(r"\d{12}", student_id):
|
|
|
|
| 6490 |
existing_profile_doc = docs[0]
|
| 6491 |
existing_uid = docs[0].id
|
| 6492 |
except Exception as duplicate_err:
|
| 6493 |
+
blocked_rows += 1
|
| 6494 |
+
result_rows.append(
|
| 6495 |
+
{
|
| 6496 |
+
"rowNumber": row_number,
|
| 6497 |
+
"studentId": student_id,
|
| 6498 |
+
"fullName": full_name,
|
| 6499 |
+
"email": email,
|
| 6500 |
+
"uid": None,
|
| 6501 |
+
"classSectionId": class_section_id,
|
| 6502 |
+
"status": "blocked",
|
| 6503 |
+
"message": f"Cannot import: duplicate check failed ({duplicate_err}).",
|
| 6504 |
+
"temporaryPassword": None,
|
| 6505 |
+
}
|
| 6506 |
+
)
|
| 6507 |
+
continue
|
| 6508 |
+
|
| 6509 |
+
if existing_profile_doc:
|
| 6510 |
+
blocked_rows += 1
|
| 6511 |
+
result_rows.append(
|
| 6512 |
+
{
|
| 6513 |
+
"rowNumber": row_number,
|
| 6514 |
+
"studentId": student_id,
|
| 6515 |
+
"fullName": full_name,
|
| 6516 |
+
"email": email,
|
| 6517 |
+
"uid": None,
|
| 6518 |
+
"classSectionId": class_section_id,
|
| 6519 |
+
"status": "blocked",
|
| 6520 |
+
"message": "Cannot import: an account with this LRN or email already exists.",
|
| 6521 |
+
"temporaryPassword": None,
|
| 6522 |
+
}
|
| 6523 |
+
)
|
| 6524 |
+
continue
|
| 6525 |
|
| 6526 |
try:
|
| 6527 |
roster_rows = list(
|
|
|
|
| 6547 |
)
|
| 6548 |
continue
|
| 6549 |
except Exception as roster_err:
|
| 6550 |
+
blocked_rows += 1
|
| 6551 |
+
result_rows.append(
|
| 6552 |
+
{
|
| 6553 |
+
"rowNumber": row_number,
|
| 6554 |
+
"studentId": student_id,
|
| 6555 |
+
"fullName": full_name,
|
| 6556 |
+
"email": email,
|
| 6557 |
+
"uid": None,
|
| 6558 |
+
"classSectionId": class_section_id,
|
| 6559 |
+
"status": "blocked",
|
| 6560 |
+
"message": f"Cannot import: roster duplicate check failed ({roster_err}).",
|
| 6561 |
+
"temporaryPassword": None,
|
| 6562 |
+
}
|
| 6563 |
+
)
|
| 6564 |
+
continue
|
| 6565 |
|
| 6566 |
auth_uid: Optional[str] = None
|
| 6567 |
temporary_password: Optional[str] = None
|
|
|
|
| 11512 |
def _validate_quiz_questions(
|
| 11513 |
questions: List[Dict[str, Any]],
|
| 11514 |
distribution: List[Dict[str, str]],
|
| 11515 |
+
topics: Optional[List[str]] = None,
|
| 11516 |
topic_provenance_map: Optional[Dict[str, Dict[str, Optional[str]]]] = None,
|
| 11517 |
) -> List[QuizQuestion]:
|
| 11518 |
"""Validate and normalise each question from the LLM response."""
|
|
|
|
| 11583 |
question_type = "identification"
|
| 11584 |
options = None
|
| 11585 |
|
| 11586 |
+
question_topic = topics[i % len(topics)] if topics else str(q.get("topic", "General"))
|
| 11587 |
question_provenance = None
|
| 11588 |
if topic_provenance_map:
|
| 11589 |
question_provenance = topic_provenance_map.get(_topic_key(question_topic))
|
|
|
|
| 11614 |
Supports Bloom's Taxonomy integration, multiple question types,
|
| 11615 |
and graph-based identification questions.
|
| 11616 |
"""
|
| 11617 |
+
# Quiz item cap — 12 classroom items maximum.
|
| 11618 |
+
if request.numQuestions > 12:
|
| 11619 |
+
raise HTTPException(status_code=400, detail="capped at 12 items")
|
| 11620 |
|
| 11621 |
try:
|
| 11622 |
|
|
|
|
| 11829 |
f"LLM generated {len(parsed_questions)}/{request.numQuestions} questions "
|
| 11830 |
f"after {max_attempts} attempts (raw length={len(raw_content)} chars)."
|
| 11831 |
)
|
| 11832 |
+
raise HTTPException(
|
| 11833 |
+
status_code=502,
|
| 11834 |
+
detail=f"Quiz generation returned {len(parsed_questions)} of {request.numQuestions} requested questions. Please try again.",
|
| 11835 |
+
)
|
| 11836 |
|
| 11837 |
topic_provenance_map: Dict[str, Dict[str, Optional[str]]] = {}
|
| 11838 |
for imported_topic in (imported_topics_payload.get("topics") or []):
|
|
|
|
| 11850 |
}
|
| 11851 |
|
| 11852 |
validated = _validate_quiz_questions(
|
| 11853 |
+
parsed_questions[:request.numQuestions],
|
| 11854 |
distribution,
|
| 11855 |
+
topics=effective_topics,
|
| 11856 |
topic_provenance_map=topic_provenance_map,
|
| 11857 |
)
|
| 11858 |
total_points = sum(q.points for q in validated)
|
services/user_provisioning_service.py
CHANGED
|
@@ -169,14 +169,17 @@ class UserProvisioningService:
|
|
| 169 |
"role": role_lower,
|
| 170 |
"status": normalized_status,
|
| 171 |
"grade": grade,
|
| 172 |
-
"section": section,
|
| 173 |
-
"classSectionId": class_section_id,
|
| 174 |
"forcePasswordChange": True,
|
| 175 |
"photo": self._build_default_avatar_url(display_name),
|
| 176 |
"updatedAt": self._firestore_server_timestamp,
|
| 177 |
}
|
| 178 |
|
| 179 |
if role_lower == "student":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
lrn = (user_input.lrn or "").strip()
|
| 181 |
if not lrn:
|
| 182 |
raise UserProvisioningError("missing_lrn", "LRN is required for student accounts.", 400)
|
|
@@ -195,7 +198,7 @@ class UserProvisioningService:
|
|
| 195 |
elif role_lower == "teacher":
|
| 196 |
payload.update(
|
| 197 |
{
|
| 198 |
-
"department":
|
| 199 |
"teacherId": f"TCH-{self._slugify(payload['email'])}",
|
| 200 |
"subject": "Mathematics",
|
| 201 |
"yearsOfExperience": "0",
|
|
@@ -204,6 +207,8 @@ class UserProvisioningService:
|
|
| 204 |
}
|
| 205 |
)
|
| 206 |
else:
|
|
|
|
|
|
|
| 207 |
payload.update(
|
| 208 |
{
|
| 209 |
"department": f"{grade} - {section}",
|
|
|
|
| 169 |
"role": role_lower,
|
| 170 |
"status": normalized_status,
|
| 171 |
"grade": grade,
|
|
|
|
|
|
|
| 172 |
"forcePasswordChange": True,
|
| 173 |
"photo": self._build_default_avatar_url(display_name),
|
| 174 |
"updatedAt": self._firestore_server_timestamp,
|
| 175 |
}
|
| 176 |
|
| 177 |
if role_lower == "student":
|
| 178 |
+
section = (user_input.section or "").strip()
|
| 179 |
+
if not section:
|
| 180 |
+
raise UserProvisioningError("missing_section", "Section is required for student accounts.", 400)
|
| 181 |
+
payload["section"] = section
|
| 182 |
+
payload["classSectionId"] = self._slugify(f"{grade}_{section}")
|
| 183 |
lrn = (user_input.lrn or "").strip()
|
| 184 |
if not lrn:
|
| 185 |
raise UserProvisioningError("missing_lrn", "LRN is required for student accounts.", 400)
|
|
|
|
| 198 |
elif role_lower == "teacher":
|
| 199 |
payload.update(
|
| 200 |
{
|
| 201 |
+
"department": "Mathematics",
|
| 202 |
"teacherId": f"TCH-{self._slugify(payload['email'])}",
|
| 203 |
"subject": "Mathematics",
|
| 204 |
"yearsOfExperience": "0",
|
|
|
|
| 207 |
}
|
| 208 |
)
|
| 209 |
else:
|
| 210 |
+
payload["section"] = section
|
| 211 |
+
payload["classSectionId"] = class_section_id
|
| 212 |
payload.update(
|
| 213 |
{
|
| 214 |
"department": f"{grade} - {section}",
|
tests/test_api.py
CHANGED
|
@@ -881,16 +881,19 @@ class TestClassRecordImportMapping:
|
|
| 881 |
|
| 882 |
@patch("main.call_hf_chat")
|
| 883 |
def test_preview_quiz(self, mock_chat):
|
| 884 |
-
quiz_json = json.dumps([
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
|
|
|
|
|
|
|
|
|
| 894 |
mock_chat.return_value = quiz_json
|
| 895 |
response = client.post("/api/quiz/preview", json={
|
| 896 |
"topics": ["Algebra"],
|
|
@@ -900,7 +903,7 @@ class TestClassRecordImportMapping:
|
|
| 900 |
|
| 901 |
@patch("main.call_hf_chat")
|
| 902 |
def test_generate_quiz_accepts_new_max_limits(self, mock_chat):
|
| 903 |
-
max_questions =
|
| 904 |
quiz_json = json.dumps([
|
| 905 |
{
|
| 906 |
"questionType": "identification",
|
|
@@ -930,7 +933,17 @@ class TestClassRecordImportMapping:
|
|
| 930 |
response = client.post("/api/quiz/generate", json={
|
| 931 |
"topics": ["Algebra"],
|
| 932 |
"gradeLevel": "Grade 11",
|
| 933 |
-
"numQuestions":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 934 |
})
|
| 935 |
|
| 936 |
assert response.status_code == 422
|
|
@@ -1115,6 +1128,35 @@ class TestUploadClassRecordsGuardrails:
|
|
| 1115 |
assert any("missing required identity value: lrn_or_email" in key for key in reasons.keys())
|
| 1116 |
assert len(payload.get("rejectedRowDetails") or []) == 2
|
| 1117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1118 |
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
|
| 1119 |
def test_upload_class_records_degrades_gracefully_when_firestore_adc_missing(self, _mock_chat):
|
| 1120 |
class _FailingFirestoreModule:
|
|
@@ -1819,6 +1861,21 @@ class TestStudentAccountProvisioningImport:
|
|
| 1819 |
assert payload["summary"]["duplicateRows"] >= 1
|
| 1820 |
assert payload["summary"]["invalidRows"] >= 1
|
| 1821 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1822 |
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
|
| 1823 |
def test_commit_student_account_import_provisions_profiles(self, _mock_chat):
|
| 1824 |
firestore = _ProvisionFirestoreModule({"users": {}, "managedStudents": {}, "classSectionOwnership": {}, "accessAuditLogs": {}})
|
|
|
|
| 881 |
|
| 882 |
@patch("main.call_hf_chat")
|
| 883 |
def test_preview_quiz(self, mock_chat):
|
| 884 |
+
quiz_json = json.dumps([
|
| 885 |
+
{
|
| 886 |
+
"questionType": "identification",
|
| 887 |
+
"question": f"Question {index + 1}",
|
| 888 |
+
"correctAnswer": "Rise over run",
|
| 889 |
+
"bloomLevel": "remember",
|
| 890 |
+
"difficulty": "easy",
|
| 891 |
+
"topic": "Algebra",
|
| 892 |
+
"points": 1,
|
| 893 |
+
"explanation": "Slope = rise/run.",
|
| 894 |
+
}
|
| 895 |
+
for index in range(3)
|
| 896 |
+
])
|
| 897 |
mock_chat.return_value = quiz_json
|
| 898 |
response = client.post("/api/quiz/preview", json={
|
| 899 |
"topics": ["Algebra"],
|
|
|
|
| 903 |
|
| 904 |
@patch("main.call_hf_chat")
|
| 905 |
def test_generate_quiz_accepts_new_max_limits(self, mock_chat):
|
| 906 |
+
max_questions = 12 # Classroom generation cap is 12 items.
|
| 907 |
quiz_json = json.dumps([
|
| 908 |
{
|
| 909 |
"questionType": "identification",
|
|
|
|
| 933 |
response = client.post("/api/quiz/generate", json={
|
| 934 |
"topics": ["Algebra"],
|
| 935 |
"gradeLevel": "Grade 11",
|
| 936 |
+
"numQuestions": 13,
|
| 937 |
+
})
|
| 938 |
+
|
| 939 |
+
assert response.status_code == 400
|
| 940 |
+
assert response.json()["detail"] == "capped at 12 items"
|
| 941 |
+
|
| 942 |
+
def test_generate_quiz_preserves_structural_ceiling_over_thirty(self):
|
| 943 |
+
response = client.post("/api/quiz/generate", json={
|
| 944 |
+
"topics": ["Algebra"],
|
| 945 |
+
"gradeLevel": "Grade 11",
|
| 946 |
+
"numQuestions": 31,
|
| 947 |
})
|
| 948 |
|
| 949 |
assert response.status_code == 422
|
|
|
|
| 1128 |
assert any("missing required identity value: lrn_or_email" in key for key in reasons.keys())
|
| 1129 |
assert len(payload.get("rejectedRowDetails") or []) == 2
|
| 1130 |
|
| 1131 |
+
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
|
| 1132 |
+
def test_upload_class_records_quarantines_short_names_and_percentage_score_corruption(self, _mock_chat):
|
| 1133 |
+
files = {
|
| 1134 |
+
"files": (
|
| 1135 |
+
"records.csv",
|
| 1136 |
+
(
|
| 1137 |
+
b"name,lrn,avgQuizScore,attendance,engagementScore\n"
|
| 1138 |
+
b"A,123456789001,81,92,88\n"
|
| 1139 |
+
b"Ana Cruz,123456789002,11%,92,88\n"
|
| 1140 |
+
b"Ben Dela,123456789003,81,90,85\n"
|
| 1141 |
+
),
|
| 1142 |
+
"text/csv",
|
| 1143 |
+
),
|
| 1144 |
+
}
|
| 1145 |
+
|
| 1146 |
+
response = client.post(
|
| 1147 |
+
"/api/upload/class-records",
|
| 1148 |
+
files=files,
|
| 1149 |
+
data={"datasetIntent": "synthetic_student_records"},
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
assert response.status_code == 200
|
| 1153 |
+
payload = response.json()
|
| 1154 |
+
assert payload["interpretedRows"] == 1
|
| 1155 |
+
assert payload["rejectedRows"] == 2
|
| 1156 |
+
reasons = payload.get("rejectedReasons") or {}
|
| 1157 |
+
assert any("single-character learner name" in reason for reason in reasons)
|
| 1158 |
+
assert any("percentage-formatted score" in reason for reason in reasons)
|
| 1159 |
+
|
| 1160 |
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
|
| 1161 |
def test_upload_class_records_degrades_gracefully_when_firestore_adc_missing(self, _mock_chat):
|
| 1162 |
class _FailingFirestoreModule:
|
|
|
|
| 1861 |
assert payload["summary"]["duplicateRows"] >= 1
|
| 1862 |
assert payload["summary"]["invalidRows"] >= 1
|
| 1863 |
|
| 1864 |
+
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
|
| 1865 |
+
def test_preview_quarantines_single_letter_and_duplicate_lrn_rows(self, _mock_chat):
|
| 1866 |
+
firestore = _ProvisionFirestoreModule({"users": {}, "managedStudents": {}})
|
| 1867 |
+
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")):
|
| 1868 |
+
response = client.post(
|
| 1869 |
+
"/api/import/student-accounts/preview",
|
| 1870 |
+
files={"file": ("accounts.csv", b"First Name,Last Name,Student ID,Email,Grade,Section\nA,Cruz,123456789001,a@example.com,Grade 11,STEM-A\nAna,Cruz,123456789001,b@example.com,Grade 11,STEM-A\n", "text/csv")},
|
| 1871 |
+
)
|
| 1872 |
+
|
| 1873 |
+
assert response.status_code == 200
|
| 1874 |
+
preview = response.json()
|
| 1875 |
+
assert [row["status"] for row in preview["rows"]] == ["invalid", "duplicate"]
|
| 1876 |
+
assert any("at least 2 characters" in issue for issue in preview["rows"][0]["issues"])
|
| 1877 |
+
assert preview["summary"]["validRows"] == 0
|
| 1878 |
+
|
| 1879 |
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
|
| 1880 |
def test_commit_student_account_import_provisions_profiles(self, _mock_chat):
|
| 1881 |
firestore = _ProvisionFirestoreModule({"users": {}, "managedStudents": {}, "classSectionOwnership": {}, "accessAuditLogs": {}})
|
tests/test_quiz_cap.py
CHANGED
|
@@ -37,17 +37,17 @@ client = TestClient(app, headers={"Authorization": "Bearer test-auth-token"})
|
|
| 37 |
|
| 38 |
|
| 39 |
def test_quiz_cap():
|
| 40 |
-
"""Test that quiz generation capped at
|
| 41 |
response = client.post("/api/quiz/generate", json={
|
| 42 |
"topics": ["Algebra"],
|
| 43 |
"subject": "Mathematics",
|
| 44 |
"gradeLevel": "Grade 11",
|
| 45 |
-
"numQuestions":
|
| 46 |
})
|
| 47 |
assert response.status_code == 400, f"Expected 400, got {response.status_code}: {response.text}"
|
| 48 |
-
assert
|
| 49 |
print("Test passed!")
|
| 50 |
|
| 51 |
|
| 52 |
if __name__ == "__main__":
|
| 53 |
-
test_quiz_cap()
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def test_quiz_cap():
|
| 40 |
+
"""Test that classroom quiz generation capped at 12 items returns 400."""
|
| 41 |
response = client.post("/api/quiz/generate", json={
|
| 42 |
"topics": ["Algebra"],
|
| 43 |
"subject": "Mathematics",
|
| 44 |
"gradeLevel": "Grade 11",
|
| 45 |
+
"numQuestions": 13,
|
| 46 |
})
|
| 47 |
assert response.status_code == 400, f"Expected 400, got {response.status_code}: {response.text}"
|
| 48 |
+
assert response.json()["detail"] == "capped at 12 items"
|
| 49 |
print("Test passed!")
|
| 50 |
|
| 51 |
|
| 52 |
if __name__ == "__main__":
|
| 53 |
+
test_quiz_cap()
|
tests/test_user_provisioning_service.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from services.user_provisioning_service import AdminCreateUserInput, UserProvisioningService
|
| 2 |
+
from unittest.mock import MagicMock
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_teacher_profile_does_not_require_or_assign_a_section():
|
| 6 |
+
provisioning = UserProvisioningService(
|
| 7 |
+
firebase_auth_module=None,
|
| 8 |
+
firestore_module=None,
|
| 9 |
+
firestore_server_timestamp=None,
|
| 10 |
+
email_service=MagicMock(),
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
profile = provisioning._build_profile_payload(
|
| 14 |
+
AdminCreateUserInput(
|
| 15 |
+
name="Taylor Teacher",
|
| 16 |
+
email="teacher@example.com",
|
| 17 |
+
password="Secure123!",
|
| 18 |
+
confirm_password="Secure123!",
|
| 19 |
+
role="Teacher",
|
| 20 |
+
status="Active",
|
| 21 |
+
grade="Grade 11",
|
| 22 |
+
section="",
|
| 23 |
+
),
|
| 24 |
+
"teacher",
|
| 25 |
+
"Active",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
assert profile["role"] == "teacher"
|
| 29 |
+
assert "section" not in profile
|
| 30 |
+
assert "classSectionId" not in profile
|