From d010bae080c4bd754e26795ec120c6091ac2cb87 Mon Sep 17 00:00:00 2001 From: zarkinzz Date: Sat, 24 Oct 2026 14:38:49 +0500 Subject: [PATCH 1/3] test: cover Excel import, reports and staff directory Refs: DIP-39 --- backend/tests/test_directory.py | 62 +++++++++++++++++++++++ backend/tests/test_import_reports.py | 73 ++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 backend/tests/test_directory.py create mode 100644 backend/tests/test_import_reports.py diff --git a/backend/tests/test_directory.py b/backend/tests/test_directory.py new file mode 100644 index 0000000..3d9cff2 --- /dev/null +++ b/backend/tests/test_directory.py @@ -0,0 +1,62 @@ +import json + +from conftest import World +from sqlalchemy import select + +from app.models import Department, School, User + +RECORDS = [ + {"id": 1, "userId": 501, "fullName": "Тестов Тест Тестович", "surname": "Тестов", "name": "Тест", "patronymic": "Тестович", + "departmentId": 2, "departmentRu": "Школа программной инженерии", "departmentKz": "Бағдарламалық инженерия мектебі", + "departmentEn": "School of Software Engineering"}, + {"id": 2, "userId": 502, "fullName": "Example Person", "surname": "Example", "name": "Person", "patronymic": "", + "departmentId": None, "departmentRu": "Не указан", "departmentKz": "Көрсетілмеген", "departmentEn": "Not specified"}, +] + +CSV = ( + "ID;User ID;ФИО;Фамилия;Имя;Отчество;Департамент (RU);Департамент (KZ);Департамент (EN)\n" + '1;501;"Тестов Тест Тестович";"Тестов";"Тест";"Тестович";"Школа программной инженерии";"x";"School of Software Engineering"\n' + '3;503;"Новая Персона";"Новая";"Персона";"";"Школа кибербезопасности";"y";"School of Cybersecurity"\n' +) + + +def test_import_json_then_csv_is_idempotent(client, db, world): + admin = World.auth(world.admin) + r = client.post("/api/users/import", headers=admin, + files={"file": ("teachers.json", json.dumps(RECORDS, ensure_ascii=False).encode(), "application/json")}) + assert r.status_code == 200, r.text + assert r.json()["created"] == 2 and r.json()["without_school"] == 1 + + person = db.scalar(select(User).where(User.external_id == "501")) + assert person.email is None and person.is_faculty and person.roles == ["teacher"] + school = db.scalar(select(School).where(School.name == "Школа программной инженерии")) + assert school.name_en == "School of Software Engineering" + assert person.department.school_id == school.id + + # re-upload as CSV: 501 is updated, 503 is new, nobody is duplicated + person.roles = ["teacher", "dean"] + db.commit() + r = client.post("/api/users/import", headers=admin, files={"file": ("teachers.csv", CSV.encode("utf-8"), "text/csv")}) + assert r.status_code == 200, r.text + assert (r.json()["created"], r.json()["updated"]) == (1, 1) + db.expire_all() + assert len(db.scalars(select(User).where(User.external_id == "501")).all()) == 1 + assert "dean" in db.scalar(select(User).where(User.external_id == "501")).roles # roles are preserved + assert db.scalar(select(Department).where(Department.name == "Школа кибербезопасности")) is not None + + +def test_dev_login_by_id_for_directory_user_without_email(client, db, world): + db.add(User(external_id="777", full_name="Без Почты Человек", roles=["teacher"])) + db.commit() + user = db.scalar(select(User).where(User.external_id == "777")) + found = client.get("/api/auth/dev-users", params={"q": "без почты"}).json() + assert [u["id"] for u in found] == [user.id] + r = client.post("/api/auth/dev-login", json={"user_id": user.id}) + assert r.status_code == 200 and r.json()["email"] is None + assert client.get("/api/auth/me").json()["id"] == user.id + + +def test_bad_directory_file(client, world): + r = client.post("/api/users/import", headers=World.auth(world.admin), + files={"file": ("teachers.json", b'[{"foo": 1}]', "application/json")}) + assert r.status_code == 400 diff --git a/backend/tests/test_import_reports.py b/backend/tests/test_import_reports.py new file mode 100644 index 0000000..06676e2 --- /dev/null +++ b/backend/tests/test_import_reports.py @@ -0,0 +1,73 @@ +import io +from datetime import timedelta + +from conftest import World +from openpyxl import Workbook + +from app import clock +from app.models import Location + + +def _schedule_xlsx(rows): + wb = Workbook() + ws = wb.active + ws.append(["Учебный год", "Триместр", "ФИО преподавателя", "Должность", "Кафедра", + "Тема открытого занятия", "Дисциплина", "Дата", "Время", "Место", "Email"]) + for r in rows: + ws.append(r) + buf = io.BytesIO() + wb.save(buf) + return buf.getvalue() + + +def test_schedule_import_and_approval(client, db, world): + db.add(Location(code="C1.2.243K", map_key="C1.2.243K", block="C1.2", floor=2, room="243K", kind="computer")) + db.commit() + d = (clock.now() + timedelta(days=30)).strftime("%d.%m.%Y") + content = _schedule_xlsx([ + ["2026–2027", "I", world.teacher.full_name, "Старший преподаватель", "Программная инженерия", + "Интерактивные методы обучения", "Педагогика", d, "10:00–10:50", "Корпус C1, C1.2.243K", ""], + ["2026–2027", "I", "Новый Преподаватель Иванович", "Преподаватель", "Новая кафедра", + "Тема 2", "Дисциплина 2", d, "14:00-14:50", "Аудитория 101", "new.teacher@astanait.edu.kz"], + ["2026–2027", "I", "Неизвестный Без Почты", "Преподаватель", "", "Тема 3", "Дисц 3", d, "9:00-8:00", "", ""], + ["2026–2027", "II", world.teacher.full_name, "", "", "Тема 4", "Дисц 4", d, "10:00–10:50", "", ""], + ]) + admin = World.auth(world.admin) + r = client.post(f"/api/trimesters/{world.trimester.id}/import", headers=admin, + files={"file": ("schedule.xlsx", content, "application/octet-stream")}) + assert r.status_code == 200, r.text + body = r.json() + assert body["created"] == 2 + assert [e["row"] for e in body["errors"]] == [4, 5] + + lessons = client.get("/api/lessons", headers=admin, params={"trimester_id": world.trimester.id}).json() + assert {l["status"] for l in lessons} == {"draft"} + assert any(l["location"] and l["location"]["code"] == "C1.2.243K" for l in lessons) + # teachers don't see the unapproved schedule + assert client.get("/api/lessons", headers=World.auth(world.teacher)).json() == [] + + r = client.post(f"/api/trimesters/{world.trimester.id}/approve", headers=admin) + assert r.status_code == 200 and r.json()["approved"] == 2 + statuses = {l["status"] for l in client.get("/api/lessons", headers=World.auth(world.teacher)).json()} + assert statuses == {"scheduled"} + + +def test_template_and_reports(client, world): + admin = World.auth(world.admin) + r = client.get("/api/schedule/template", headers=admin) + assert r.status_code == 200 and r.content[:2] == b"PK" + world.lesson(days_ahead=10) + data = client.get("/api/analytics", headers=admin).json() + assert data["summary"]["total"] == 1 + r = client.get("/api/reports/export", headers=admin, params={"format": "xlsx"}) + assert r.status_code == 200 and r.content[:2] == b"PK" + r = client.get("/api/reports/export", headers=admin, params={"format": "pdf"}) + assert r.status_code == 200 and r.content.startswith(b"%PDF") + + +def test_dev_login_and_me(client, world): + r = client.post("/api/auth/dev-login", json={"email": world.teacher.email}) + assert r.status_code == 200 + me = client.get("/api/auth/me") + assert me.status_code == 200 and me.json()["email"] == world.teacher.email + assert client.get("/api/auth/config").json()["oidc_enabled"] is False From 838c14740304e53b90ac797b46a2276ce58c641d Mon Sep 17 00:00:00 2001 From: zarkinzz Date: Sat, 24 Oct 2026 14:38:49 +0500 Subject: [PATCH 2/3] test(ai): check the LLM client with a mocked transport Refs: DIP-39 --- backend/tests/test_ai_llm.py | 57 ++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 backend/tests/test_ai_llm.py diff --git a/backend/tests/test_ai_llm.py b/backend/tests/test_ai_llm.py new file mode 100644 index 0000000..795e18f --- /dev/null +++ b/backend/tests/test_ai_llm.py @@ -0,0 +1,57 @@ +"""AI Assistant client: OpenAI-compatible API (OpenAI / local LLM), structured answers, fallbacks.""" + +import json + +import httpx + +from app.config import settings +from app.services import ai + + +def _mock_client(monkeypatch, handler): + real = httpx.Client + monkeypatch.setattr(ai.httpx, "Client", lambda **kw: real(transport=httpx.MockTransport(handler), **kw)) + + +def test_local_llm_falls_back_to_json_mode(monkeypatch): + formats = [] + + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + formats.append(body["response_format"]["type"]) + assert request.url.path.endswith("/chat/completions") and body["model"] == "qwen2.5:7b" + if body["response_format"]["type"] == "json_schema": # an older local server without structured outputs + return httpx.Response(400, json={"error": "response_format json_schema is not supported"}) + content = json.dumps({"invitation_text": "Welcome to the open lesson!", "short_description": "Demo"}) + return httpx.Response(200, json={"choices": [{"message": {"content": content}, "finish_reason": "stop"}]}) + + _mock_client(monkeypatch, handler) + monkeypatch.setattr(settings, "ai_enabled", True) + monkeypatch.setattr(settings, "ai_provider", "local") + assert ai.provider() == "local_llm" and ai.model_name() == "qwen2.5:7b" + out = ai._ask_llm("Write an invitation", ai.Invitation) + assert out.invitation_text == "Welcome to the open lesson!" + assert formats == ["json_schema", "json_object"] + + +def test_openai_needs_a_key_and_rejects_bad_answers(monkeypatch): + monkeypatch.setattr(settings, "ai_enabled", True) + monkeypatch.setattr(settings, "ai_provider", "openai") + monkeypatch.setattr(settings, "ai_api_key", "") + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + assert ai.provider() == "local" # no key → rule-based analyser + + monkeypatch.setattr(settings, "ai_api_key", "sk-test") + + def handler(request: httpx.Request) -> httpx.Response: + assert request.headers["Authorization"] == "Bearer sk-test" + return httpx.Response(200, json={"choices": [{"message": {"content": '{"unexpected": true}'}, "finish_reason": "stop"}]}) + + _mock_client(monkeypatch, handler) + assert ai.provider() == "openai" and ai.model_name() == "gpt-4o-mini" + try: + ai._ask_llm("Write an invitation", ai.Invitation) + except ai.LLMError: + pass + else: + raise AssertionError("an answer that does not match the schema must be rejected") From 7c8c264d0d15d43f7c495b9aaa826dc522496d77 Mon Sep 17 00:00:00 2001 From: Dana Shokobalinova <121392270+zarkinzz@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:43:51 +0500 Subject: [PATCH 3/3] ci: run backend tests and frontend build on pull requests Refs: DIP-39 --- .github/workflows/ci.yml | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6a7b1bd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,39 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +jobs: + backend: + name: Backend tests + runs-on: ubuntu-latest + defaults: + run: + working-directory: backend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + cache: pip + cache-dependency-path: backend/requirements.txt + - run: pip install -r requirements.txt + - run: python -m pytest -q + + frontend: + name: Frontend build + runs-on: ubuntu-latest + defaults: + run: + working-directory: frontend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: frontend/package-lock.json + - run: npm ci + - run: npm run build