Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
57 changes: 57 additions & 0 deletions backend/tests/test_ai_llm.py
Original file line number Diff line number Diff line change
@@ -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")
62 changes: 62 additions & 0 deletions backend/tests/test_directory.py
Original file line number Diff line number Diff line change
@@ -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
73 changes: 73 additions & 0 deletions backend/tests/test_import_reports.py
Original file line number Diff line number Diff line change
@@ -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", "[email protected]"],
["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
Loading