Compare commits

..

21 Commits

Author SHA1 Message Date
djalim 3ac514a33d style: fix deno fmt and lint
Check Deno code / Check Deno code (pull_request) Successful in 6s
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Successful in 58s
2026-04-26 13:04:44 +00:00
djalim a791b8813d test(users): add integration and e2e tests for /users (#111)
- integration: list, filter by role, create, get, update, delete, not-found
- e2e: handler calls with mock context + real DB, covers 400/409/404 cases
  (unit tests already present from teammates)
2026-04-26 13:04:44 +00:00
djalim 3d6b7e28f3 test(users): add unit tests for users API 2026-04-26 13:04:44 +00:00
djalim e2f5bf7b95 ci: remove Run tests step from lint workflow
Check Deno code / Check Deno code (push) Successful in 6s
Tests / Unit tests (push) Successful in 12s
Tests / Integration tests (push) Successful in 57s
Check Deno code / Check Deno code (pull_request) Successful in 6s
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Successful in 1m3s
2026-04-26 14:30:40 +02:00
djalim cd5c524ff0 style: fix deno fmt on students tests and drizzle.config
Check Deno code / Check Deno code (pull_request) Failing after 8s
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Successful in 58s
2026-04-26 14:18:09 +02:00
djalim e5c6c389ea test(students): add unit, integration and e2e tests for /students (#109)
Check Deno code / Check Deno code (pull_request) Failing after 5s
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Successful in 58s
- unit: fixture shapes, mock API (GET/POST/PUT/DELETE), mock DB operations
- integration: real DB CRUD via testDb (list, filter, create, get, update, delete)
- e2e: handler calls directly with mock FreshContext + real DB
  covers auth (employee vs non-employee), 400/403/404 cases
- adds test:e2e deno task and CI step
- adds tests/helpers/handler.ts with makeEmployeeContext, makeContextWithAffiliation,
  makeGetRequest, makeJsonRequest utilities

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 14:00:38 +02:00
djalim daa7f4951f fix(ci): fix postgres TCP setup and truncateAll superuser error
Check Deno code / Check Deno code (push) Failing after 5s
Tests / Unit tests (push) Successful in 11s
Tests / Integration tests (push) Successful in 55s
- Use apt-get install + configure listen_addresses + md5 auth in pg_hba
  so psql can connect via 127.0.0.1 (not just Unix socket)
- Use pg_ctlcluster restart after config changes + wait for pg_isready
- Replace session_replication_role (requires superuser) with a single
  TRUNCATE ... CASCADE which handles FK deps without elevated privileges
- All 3 integration tests now pass in CI (act + Gitea Actions)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 11:30:33 +00:00
djalim a95818e3bf fix(ci): use connection URL with ssl:false in drizzle config 2026-04-26 11:30:33 +00:00
djalim 26eedcc4f2 debug(ci): add connection diagnostics before migrate 2026-04-26 11:30:33 +00:00
djalim ce4782580d fix(ci): remove unsupported --verbose from drizzle-kit migrate 2026-04-26 11:30:33 +00:00
djalim 91248370da fix(ci): add GRANT on public schema and verbose migrate output 2026-04-26 11:30:33 +00:00
djalim 6b8b5e6aa3 fix(ci): start postgres with pg_ctlcluster instead of systemctl 2026-04-26 11:30:33 +00:00
djalim d1c3b93755 fix(ci): install postgres via apt-get instead of docker 2026-04-26 11:30:33 +00:00
djalim f42df29f06 fix(ci): use docker run instead of services for postgres 2026-04-26 11:30:33 +00:00
djalim c8b808f509 fix(ci): use bash /dev/tcp for postgres readiness check 2026-04-26 11:30:33 +00:00
djalim fdfdd74894 fix(ci): replace pg_isready with nc for postgres readiness check 2026-04-26 11:30:33 +00:00
djalim 60dde4675c fix(ci): use deno install for unit tests, add postgres readiness check 2026-04-26 11:30:33 +00:00
djalim fef9457795 fix(ci): install npm deps before running unit tests 2026-04-26 11:30:33 +00:00
djalim 6db04045f4 fix(lint): add version to drizzle-orm imports and prefix unused NOT_FOUND 2026-04-26 11:30:33 +00:00
djalim cdd9c0bf06 chore(test): set up integration test framework with postgres
- Generate Drizzle migrations (databases/migrations/)
- Add databases/schema.kit.ts for drizzle-kit (Node-compatible imports)
- Update drizzle.config.ts to use schema.kit.ts
- Add deno tasks: test:unit, test:integration, migrate
- Add tests/helpers/db_integration.ts: testDb, truncateAll, seed helpers
- Add .gitea/workflows/test.yml: CI with postgres service container
- Update lint.yml: run test:unit only (no DB needed)
- Update deploy.yml: add check-code job, gate deploy on it
2026-04-26 11:30:33 +00:00
djalim 980efcfbc3 ci: add Deno code check job and enable lint on develop
Check Deno code / Check Deno code (pull_request) Failing after 9s
Check Deno code / Check Deno code (push) Failing after 6s
2026-04-23 14:29:08 +02:00
13 changed files with 1482 additions and 4 deletions
+17
View File
@@ -6,9 +6,26 @@ on:
- main
jobs:
check-code:
name: "Check Deno code"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- name: Check formatting
run: deno fmt --check
- name: Check linting
run: deno lint
deploy:
name: "Build Docker image"
runs-on: ubuntu-latest
needs: check-code
steps:
- name: Login to Docker Hub
uses: docker/login-action@v3
+4 -3
View File
@@ -4,6 +4,10 @@ on:
pull_request:
branches:
- main
- develop
push:
branches:
- develop
permissions:
contents: read
@@ -24,6 +28,3 @@ jobs:
- name: Check linting
run: deno lint
- name: Run tests
run: deno test -A --no-check tests/
+9
View File
@@ -68,3 +68,12 @@ jobs:
POSTGRES_PASS: test
POSTGRES_DB: polympr_test
run: deno task test:integration
- name: Run e2e tests
env:
POSTGRES_HOST: 127.0.0.1
POSTGRES_PORT: 5432
POSTGRES_USER: test
POSTGRES_PASS: test
POSTGRES_DB: polympr_test
run: deno task test:e2e
+79
View File
@@ -0,0 +1,79 @@
name: "Tests"
on:
pull_request:
branches:
- main
- develop
push:
branches:
- develop
jobs:
unit:
name: "Unit tests"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- name: Install dependencies
run: deno install
- name: Run unit tests
run: deno task test:unit
integration:
name: "Integration tests"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- name: Start postgres
run: |
sudo apt-get update -qq && sudo apt-get install -y -qq postgresql > /dev/null
PG_VER=$(ls /etc/postgresql/)
sudo sed -i "s/^#*listen_addresses\s*=.*/listen_addresses = '127.0.0.1'/" /etc/postgresql/$PG_VER/main/postgresql.conf
echo "host all all 127.0.0.1/32 md5" | sudo tee -a /etc/postgresql/$PG_VER/main/pg_hba.conf
sudo pg_ctlcluster $PG_VER main restart
until sudo -u postgres pg_isready -h 127.0.0.1; do sleep 1; done
sudo -u postgres psql -c "CREATE USER test WITH PASSWORD 'test';"
sudo -u postgres psql -c "CREATE DATABASE polympr_test OWNER test;"
sudo -u postgres psql -d polympr_test -c "GRANT ALL ON SCHEMA public TO test;"
- name: Apply migrations
run: |
sed 's/--> statement-breakpoint/;/g' databases/migrations/0000_square_jetstream.sql | \
PGPASSWORD=test psql -h 127.0.0.1 -U test -d polympr_test
- name: Install dependencies
run: npm install --ignore-scripts && deno install
- name: Run integration tests
env:
POSTGRES_HOST: 127.0.0.1
POSTGRES_PORT: 5432
POSTGRES_USER: test
POSTGRES_PASS: test
POSTGRES_DB: polympr_test
run: deno task test:integration
- name: Run e2e tests
env:
POSTGRES_HOST: 127.0.0.1
POSTGRES_PORT: 5432
POSTGRES_USER: test
POSTGRES_PASS: test
POSTGRES_DB: polympr_test
run: deno task test:e2e
+1
View File
@@ -13,6 +13,7 @@
"test": "deno test -A --no-check tests/",
"test:unit": "deno test -A --no-check tests/unit/",
"test:integration": "deno test -A --no-check tests/integration/",
"test:e2e": "deno test -A --no-check tests/e2e/",
"migrate": "node_modules/.bin/drizzle-kit migrate"
},
"lint": {
+3 -1
View File
@@ -2,7 +2,9 @@ import { defineConfig } from "drizzle-kit";
import process from "node:process";
const url = process.env.DATABASE_URL ??
`postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASS}@${process.env.POSTGRES_HOST ?? "localhost"}:${process.env.POSTGRES_PORT ?? 5432}/${process.env.POSTGRES_DB}`;
`postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASS}@${
process.env.POSTGRES_HOST ?? "localhost"
}:${process.env.POSTGRES_PORT ?? 5432}/${process.env.POSTGRES_DB}`;
export default defineConfig({
dialect: "postgresql",
+288
View File
@@ -0,0 +1,288 @@
// #109 - E2E tests for /students endpoints
// Appelle les handlers Fresh directement avec un vrai contexte + vraie DB
import { assertEquals, assertExists } from "@std/assert";
import {
makeContextWithAffiliation,
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedPromotions,
seedStudents,
truncateAll,
} from "../helpers/db_integration.ts";
import { handler as studentsHandler } from "$apps/students/api/students.ts";
import { handler as studentHandler } from "$apps/students/api/students/[numEtud].ts";
// --- GET /students ---
Deno.test({
name: "e2e students: GET /students returns all students as employee",
async fn() {
await truncateAll();
await seedPromotions([{ id: "PEIP1-2024" }]);
await seedStudents([
{ nom: "Dupont", prenom: "Jean", idPromo: "PEIP1-2024" },
{ nom: "Martin", prenom: "Alice", idPromo: "PEIP1-2024" },
]);
const req = makeGetRequest("/students");
const ctx = makeEmployeeContext();
const res = await studentsHandler.GET!(req, ctx);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
assertExists(body.find((s: { nom: string }) => s.nom === "Dupont"));
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: GET /students returns empty array for non-employee",
async fn() {
await truncateAll();
await seedPromotions([{ id: "PEIP1-2024" }]);
await seedStudents([
{ nom: "Dupont", prenom: "Jean", idPromo: "PEIP1-2024" },
]);
const req = makeGetRequest("/students");
const ctx = makeContextWithAffiliation("student");
const res = await studentsHandler.GET!(req, ctx);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: GET /students?idPromo filters by promotion",
async fn() {
await truncateAll();
await seedPromotions([{ id: "PEIP1-2024" }, { id: "PEIP2-2024" }]);
await seedStudents([
{ nom: "Dupont", prenom: "Jean", idPromo: "PEIP1-2024" },
{ nom: "Martin", prenom: "Alice", idPromo: "PEIP1-2024" },
{ nom: "Durand", prenom: "Claire", idPromo: "PEIP2-2024" },
]);
const req = makeGetRequest("/students", { idPromo: "PEIP1-2024" });
const ctx = makeEmployeeContext();
const res = await studentsHandler.GET!(req, ctx);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
assertEquals(
body.every((s: { idPromo: string }) => s.idPromo === "PEIP1-2024"),
true,
);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /students ---
Deno.test({
name: "e2e students: POST /students creates a student (201)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }]);
const req = makeJsonRequest("/students", "POST", {
nom: "Leroy",
prenom: "Paul",
idPromo: "INFO3-2024",
});
const ctx = makeEmployeeContext();
const res = await studentsHandler.POST!(req, ctx);
assertEquals(res.status, 201);
const body = await res.json();
assertExists(body.numEtud);
assertEquals(body.nom, "Leroy");
assertEquals(body.idPromo, "INFO3-2024");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: POST /students 403 for non-employee",
async fn() {
await truncateAll();
const req = makeJsonRequest("/students", "POST", {
nom: "Test",
prenom: "User",
idPromo: "PEIP1-2024",
});
const ctx = makeContextWithAffiliation("student");
const res = await studentsHandler.POST!(req, ctx);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: POST /students 400 when missing required fields",
async fn() {
await truncateAll();
const req = makeJsonRequest("/students", "POST", { nom: "Leroy" });
const ctx = makeEmployeeContext();
const res = await studentsHandler.POST!(req, ctx);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /students/:numEtud ---
Deno.test({
name: "e2e students: GET /students/:numEtud returns student",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }]);
const [s] = await seedStudents([
{ nom: "Bernard", prenom: "Lucie", idPromo: "INFO3-2024" },
]);
const req = makeGetRequest(`/students/${s.numEtud}`);
const ctx = makeEmployeeContext({ numEtud: String(s.numEtud) });
const res = await studentHandler.GET!(req, ctx);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.numEtud, s.numEtud);
assertEquals(body.nom, "Bernard");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: GET /students/:numEtud 404 when not found",
async fn() {
await truncateAll();
const req = makeGetRequest("/students/999999");
const ctx = makeEmployeeContext({ numEtud: "999999" });
const res = await studentHandler.GET!(req, ctx);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: GET /students/:numEtud 403 for non-employee",
async fn() {
await truncateAll();
const req = makeGetRequest("/students/12345");
const ctx = makeContextWithAffiliation("student", { numEtud: "12345" });
const res = await studentHandler.GET!(req, ctx);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /students/:numEtud ---
Deno.test({
name: "e2e students: PUT /students/:numEtud updates student",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }, { id: "INFO4-2024" }]);
const [s] = await seedStudents([
{ nom: "Petit", prenom: "Hugo", idPromo: "INFO3-2024" },
]);
const req = makeJsonRequest(`/students/${s.numEtud}`, "PUT", {
nom: "Grand",
prenom: "Hugo",
idPromo: "INFO4-2024",
});
const ctx = makeEmployeeContext({ numEtud: String(s.numEtud) });
const res = await studentHandler.PUT!(req, ctx);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.nom, "Grand");
assertEquals(body.idPromo, "INFO4-2024");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: PUT /students/:numEtud 404 when not found",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }]);
const req = makeJsonRequest("/students/999999", "PUT", {
nom: "Ghost",
prenom: "Ghost",
idPromo: "INFO3-2024",
});
const ctx = makeEmployeeContext({ numEtud: "999999" });
const res = await studentHandler.PUT!(req, ctx);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /students/:numEtud ---
Deno.test({
name: "e2e students: DELETE /students/:numEtud returns 204",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }]);
const [s] = await seedStudents([
{ nom: "Thomas", prenom: "Eva", idPromo: "INFO3-2024" },
]);
const req = makeGetRequest(`/students/${s.numEtud}`);
const ctx = makeEmployeeContext({ numEtud: String(s.numEtud) });
const res = await studentHandler.DELETE!(req, ctx);
assertEquals(res.status, 204);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e students: DELETE /students/:numEtud 404 when not found",
async fn() {
await truncateAll();
const req = makeGetRequest("/students/999999");
const ctx = makeEmployeeContext({ numEtud: "999999" });
const res = await studentHandler.DELETE!(req, ctx);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+250
View File
@@ -0,0 +1,250 @@
// #111 - E2E tests for /users endpoints
import { assertEquals, assertExists } from "@std/assert";
import {
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedRoles,
seedUsers,
truncateAll,
} from "../helpers/db_integration.ts";
import { handler as usersHandler } from "$apps/admin/api/users.ts";
import { handler as userHandler } from "$apps/admin/api/users/[id].ts";
// --- GET /users ---
Deno.test({
name: "e2e users: GET /users returns all users",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([
{ id: "dupont.jean", nom: "Dupont", prenom: "Jean", idRole: role.id },
{ id: "martin.alice", nom: "Martin", prenom: "Alice", idRole: role.id },
]);
const res = await usersHandler.GET!(
makeGetRequest("/users"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
assertExists(body.find((u: { id: string }) => u.id === "dupont.jean"));
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: GET /users?idRole filters by role",
async fn() {
await truncateAll();
const [role1] = await seedRoles([{ nom: "admin" }]);
const [role2] = await seedRoles([{ nom: "employee" }]);
await seedUsers([
{ id: "u1", nom: "A", prenom: "A", idRole: role1.id },
{ id: "u2", nom: "B", prenom: "B", idRole: role2.id },
]);
const res = await usersHandler.GET!(
makeGetRequest("/users", { idRole: String(role1.id) }),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 1);
assertEquals(body[0].id, "u1");
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /users ---
Deno.test({
name: "e2e users: POST /users creates user (201)",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
const res = await usersHandler.POST!(
makeJsonRequest("/users", "POST", {
id: "nouveau.user",
nom: "Nouveau",
prenom: "User",
idRole: role.id,
}),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertEquals(body.id, "nouveau.user");
assertExists(body.nom);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: POST /users 409 on duplicate id",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([{
id: "dup.user",
nom: "A",
prenom: "A",
idRole: role.id,
}]);
const res = await usersHandler.POST!(
makeJsonRequest("/users", "POST", {
id: "dup.user",
nom: "B",
prenom: "B",
idRole: role.id,
}),
makeEmployeeContext(),
);
assertEquals(res.status, 409);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: POST /users 400 on missing fields",
async fn() {
await truncateAll();
const res = await usersHandler.POST!(
makeJsonRequest("/users", "POST", { id: "x" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /users/:id ---
Deno.test({
name: "e2e users: GET /users/:id returns user",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([{
id: "test.user",
nom: "Test",
prenom: "User",
idRole: role.id,
}]);
const res = await userHandler.GET!(
makeGetRequest("/users/test.user"),
makeEmployeeContext({ id: "test.user" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.id, "test.user");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: GET /users/:id 404 when not found",
async fn() {
await truncateAll();
const res = await userHandler.GET!(
makeGetRequest("/users/ghost"),
makeEmployeeContext({ id: "ghost" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /users/:id ---
Deno.test({
name: "e2e users: PUT /users/:id updates user",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([{
id: "upd.user",
nom: "Old",
prenom: "Name",
idRole: role.id,
}]);
const res = await userHandler.PUT!(
makeJsonRequest("/users/upd.user", "PUT", {
nom: "New",
prenom: "Name",
idRole: role.id,
}),
makeEmployeeContext({ id: "upd.user" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.nom, "New");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: PUT /users/:id 404 when not found",
async fn() {
await truncateAll();
const res = await userHandler.PUT!(
makeJsonRequest("/users/ghost", "PUT", {
nom: "X",
prenom: "Y",
idRole: 1,
}),
makeEmployeeContext({ id: "ghost" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /users/:id ---
Deno.test({
name: "e2e users: DELETE /users/:id returns 204",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([{
id: "del.user",
nom: "Del",
prenom: "Me",
idRole: role.id,
}]);
const res = await userHandler.DELETE!(
makeGetRequest("/users/del.user"),
makeEmployeeContext({ id: "del.user" }),
);
assertEquals(res.status, 204);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: DELETE /users/:id 404 when not found",
async fn() {
await truncateAll();
const res = await userHandler.DELETE!(
makeGetRequest("/users/ghost"),
makeEmployeeContext({ id: "ghost" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+88
View File
@@ -0,0 +1,88 @@
// Helper pour les tests E2E — appel direct des handlers Fresh
// sans lancer de serveur HTTP
import { FreshContext } from "$fresh/server.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { CasContent } from "$root/defaults/interfaces.ts";
const BASE_EMPLOYEE_SESSION: CasContent = {
amuCampus: "",
amuComposante: "",
amuDateValidation: "",
coGroup: "",
eduPersonPrimaryAffiliation: "employee",
eduPersonPrincipalName: "test.user@polytech.fr",
mail: "test.user@polytech.fr",
displayName: "Test User",
givenName: "Test",
memberOf: [],
sn: "User",
supannCivilite: "M.",
supannEntiteAffectation: "",
supannEtuAnneeInscription: "",
supannEtuEtape: "",
uid: "test.user",
};
/**
* Crée un FreshContext mock authentifié en tant qu'employee.
*/
export function makeEmployeeContext(
params: Record<string, string> = {},
): FreshContext<AuthenticatedState> {
return {
params,
state: {
isAuthenticated: true,
session: { ...BASE_EMPLOYEE_SESSION },
availablePages: {},
},
render: () => Promise.resolve(new Response()),
renderNotFound: () => Promise.resolve(new Response(null, { status: 404 })),
next: () => Promise.resolve(new Response()),
} as unknown as FreshContext<AuthenticatedState>;
}
/**
* Crée un FreshContext mock avec un affiliation personnalisée.
*/
export function makeContextWithAffiliation(
affiliation: string,
params: Record<string, string> = {},
): FreshContext<AuthenticatedState> {
const ctx = makeEmployeeContext(params);
(ctx.state as AuthenticatedState).session.eduPersonPrimaryAffiliation =
affiliation;
return ctx;
}
/**
* Crée une Request GET simple.
*/
export function makeGetRequest(
path: string,
searchParams?: Record<string, string>,
): Request {
const url = new URL(`http://localhost${path}`);
if (searchParams) {
for (const [k, v] of Object.entries(searchParams)) {
url.searchParams.set(k, v);
}
}
return new Request(url.toString());
}
/**
* Crée une Request POST/PUT avec un corps JSON.
*/
export function makeJsonRequest(
path: string,
method: string,
body: unknown,
): Request {
return new Request(`http://localhost${path}`, {
method,
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
+173
View File
@@ -0,0 +1,173 @@
// #109 - Integration tests for /students endpoints
// Teste les opérations DB directement avec une vraie base de données
import { assertEquals, assertExists } from "@std/assert";
import {
seedPromotions,
seedStudents,
testDb,
truncateAll,
} from "../helpers/db_integration.ts";
import { students } from "$root/databases/schema.ts";
import { eq } from "npm:drizzle-orm@0.45.2";
Deno.test({
name: "integration students: list all students",
async fn() {
await truncateAll();
await seedPromotions([{ id: "PEIP1-2024" }]);
await seedStudents([
{ nom: "Dupont", prenom: "Jean", idPromo: "PEIP1-2024" },
{ nom: "Martin", prenom: "Alice", idPromo: "PEIP1-2024" },
]);
const rows = await testDb.select().from(students);
assertEquals(rows.length, 2);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration students: filter by idPromo",
async fn() {
await truncateAll();
await seedPromotions([{ id: "PEIP1-2024" }, { id: "PEIP2-2024" }]);
await seedStudents([
{ nom: "Dupont", prenom: "Jean", idPromo: "PEIP1-2024" },
{ nom: "Martin", prenom: "Alice", idPromo: "PEIP1-2024" },
{ nom: "Durand", prenom: "Claire", idPromo: "PEIP2-2024" },
]);
const rows = await testDb
.select()
.from(students)
.where(eq(students.idPromo, "PEIP1-2024"));
assertEquals(rows.length, 2);
assertEquals(rows.every((s) => s.idPromo === "PEIP1-2024"), true);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration students: create and retrieve by numEtud",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }]);
const [created] = await testDb
.insert(students)
.values({ nom: "Leroy", prenom: "Paul", idPromo: "INFO3-2024" })
.returning();
assertExists(created.numEtud);
const row = await testDb
.select()
.from(students)
.where(eq(students.numEtud, created.numEtud))
.then((r) => r[0] ?? null);
assertExists(row);
assertEquals(row.nom, "Leroy");
assertEquals(row.idPromo, "INFO3-2024");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration students: get by numEtud returns null when not found",
async fn() {
await truncateAll();
const row = await testDb
.select()
.from(students)
.where(eq(students.numEtud, 999999))
.then((r) => r[0] ?? null);
assertEquals(row, null);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration students: update student fields",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }, { id: "INFO4-2024" }]);
const [s] = await seedStudents([
{ nom: "Petit", prenom: "Hugo", idPromo: "INFO3-2024" },
]);
const [updated] = await testDb
.update(students)
.set({ nom: "Grand", idPromo: "INFO4-2024" })
.where(eq(students.numEtud, s.numEtud))
.returning();
assertEquals(updated.nom, "Grand");
assertEquals(updated.idPromo, "INFO4-2024");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration students: delete student",
async fn() {
await truncateAll();
await seedPromotions([{ id: "INFO3-2024" }]);
const [s] = await seedStudents([
{ nom: "Thomas", prenom: "Eva", idPromo: "INFO3-2024" },
]);
await testDb.delete(students).where(eq(students.numEtud, s.numEtud));
const row = await testDb
.select()
.from(students)
.where(eq(students.numEtud, s.numEtud))
.then((r) => r[0] ?? null);
assertEquals(row, null);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration students: update non-existent student returns empty",
async fn() {
await truncateAll();
const result = await testDb
.update(students)
.set({ nom: "Ghost" })
.where(eq(students.numEtud, 999999))
.returning();
assertEquals(result.length, 0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration students: delete non-existent student returns empty",
async fn() {
await truncateAll();
const result = await testDb
.delete(students)
.where(eq(students.numEtud, 999999))
.returning();
assertEquals(result.length, 0);
},
sanitizeResources: false,
sanitizeOps: false,
});
+138
View File
@@ -0,0 +1,138 @@
// #111 - Integration tests for /users endpoints
import { assertEquals, assertExists } from "@std/assert";
import {
seedRoles,
seedUsers,
testDb,
truncateAll,
} from "../helpers/db_integration.ts";
import { users } from "$root/databases/schema.ts";
import { eq } from "npm:drizzle-orm@0.45.2";
Deno.test({
name: "integration users: list all users",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([
{ id: "dupont.jean", nom: "Dupont", prenom: "Jean", idRole: role.id },
{ id: "martin.alice", nom: "Martin", prenom: "Alice", idRole: role.id },
]);
const rows = await testDb.select().from(users);
assertEquals(rows.length, 2);
assertExists(rows.find((u) => u.id === "dupont.jean"));
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration users: filter by idRole",
async fn() {
await truncateAll();
const [role1] = await seedRoles([{ nom: "admin" }]);
const [role2] = await seedRoles([{ nom: "employee" }]);
await seedUsers([
{ id: "u1", nom: "A", prenom: "A", idRole: role1.id },
{ id: "u2", nom: "B", prenom: "B", idRole: role2.id },
]);
const rows = await testDb
.select()
.from(users)
.where(eq(users.idRole, role1.id));
assertEquals(rows.length, 1);
assertEquals(rows[0].id, "u1");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration users: create and retrieve by id",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "admin" }]);
const [created] = await testDb
.insert(users)
.values({
id: "durand.claire",
nom: "Durand",
prenom: "Claire",
idRole: role.id,
})
.returning();
assertExists(created);
assertEquals(created.id, "durand.claire");
const row = await testDb
.select()
.from(users)
.where(eq(users.id, "durand.claire"))
.then((r) => r[0] ?? null);
assertExists(row);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration users: get by id returns null when not found",
async fn() {
await truncateAll();
const row = await testDb
.select()
.from(users)
.where(eq(users.id, "nonexistent"))
.then((r) => r[0] ?? null);
assertEquals(row, null);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration users: update user fields",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([{
id: "test.user",
nom: "Test",
prenom: "User",
idRole: role.id,
}]);
const [updated] = await testDb
.update(users)
.set({ nom: "Updated", prenom: "Name" })
.where(eq(users.id, "test.user"))
.returning();
assertExists(updated);
assertEquals(updated.nom, "Updated");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration users: delete user",
async fn() {
await truncateAll();
const [role] = await seedRoles([{ nom: "employee" }]);
await seedUsers([{
id: "to.delete",
nom: "Del",
prenom: "Me",
idRole: role.id,
}]);
await testDb.delete(users).where(eq(users.id, "to.delete"));
const row = await testDb
.select()
.from(users)
.where(eq(users.id, "to.delete"))
.then((r) => r[0] ?? null);
assertEquals(row, null);
},
sanitizeResources: false,
sanitizeOps: false,
});
+216
View File
@@ -0,0 +1,216 @@
// #109 - Unit tests for /students endpoints
// Tests purs : fixtures, mock API, mock DB — aucun appel réseau réel
import { assertEquals, assertExists } from "@std/assert";
import { getFetchCalls, mockFetch, restoreFetch } from "../helpers/api_mock.ts";
import { createMockDb } from "../helpers/db_mock.ts";
import { type Student, students } from "../helpers/fixtures.ts";
// --- Fixtures ---
Deno.test("students: fixtures have correct shape", () => {
assertEquals(students.length, 3);
assertEquals(typeof students[0].numEtud, "number");
assertEquals(typeof students[0].nom, "string");
assertEquals(typeof students[0].prenom, "string");
assertEquals(typeof students[0].idPromo, "string");
});
Deno.test("students: two students belong to the same promo", () => {
const promo4 = students.filter((s) => s.idPromo === "4AFISE25/26");
assertEquals(promo4.length, 2);
});
// --- Mock API - GET /students ---
Deno.test("mock API: GET /students returns list", async () => {
mockFetch({ "/students": students });
try {
const res = await fetch("http://localhost/api/students");
assertEquals(res.status, 200);
const data: Student[] = await res.json();
assertEquals(data.length, 3);
assertExists(data.find((s) => s.nom === "Dupont"));
} finally {
restoreFetch();
}
});
Deno.test("mock API: GET /students?idPromo filters by promo", async () => {
const filtered = students.filter((s) => s.idPromo === "4AFISE25/26");
mockFetch({ "/students": filtered });
try {
const res = await fetch(
"http://localhost/api/students?idPromo=4AFISE25/26",
);
const data: Student[] = await res.json();
assertEquals(data.length, 2);
assertEquals(data.every((s) => s.idPromo === "4AFISE25/26"), true);
} finally {
restoreFetch();
}
});
Deno.test("mock API: GET /students/:numEtud returns one student", async () => {
mockFetch({ "/students/21212006": students[0] });
try {
const res = await fetch("http://localhost/api/students/21212006");
assertEquals(res.status, 200);
const data: Student = await res.json();
assertEquals(data.numEtud, 21212006);
assertEquals(data.nom, "Dupont");
} finally {
restoreFetch();
}
});
Deno.test("mock API: GET /students/:numEtud 404 when not found", async () => {
mockFetch({
"/students/99999": {
status: 404,
body: { error: "Ressource introuvable" },
},
});
try {
const res = await fetch("http://localhost/api/students/99999");
assertEquals(res.status, 404);
} finally {
restoreFetch();
}
});
Deno.test("mock API: POST /students creates student", async () => {
const newStudent = students[0];
mockFetch({ "/students": { method: "POST", status: 201, body: newStudent } });
try {
const res = await fetch("http://localhost/api/students", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
nom: "Dupont",
prenom: "Jean",
idPromo: "4AFISE25/26",
}),
});
assertEquals(res.status, 201);
const data: Student = await res.json();
assertEquals(data.nom, "Dupont");
} finally {
restoreFetch();
}
});
Deno.test("mock API: PUT /students/:numEtud updates student", async () => {
const updated = { ...students[0], nom: "Dupont-Modifié" };
mockFetch({
"/students/21212006": { method: "PUT", status: 200, body: updated },
});
try {
const res = await fetch("http://localhost/api/students/21212006", {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
nom: "Dupont-Modifié",
prenom: "Jean",
idPromo: "4AFISE25/26",
}),
});
assertEquals(res.status, 200);
const data: Student = await res.json();
assertEquals(data.nom, "Dupont-Modifié");
} finally {
restoreFetch();
}
});
Deno.test("mock API: DELETE /students/:numEtud returns 204", async () => {
mockFetch({ "/students/21212006": { method: "DELETE", status: 204 } });
try {
const res = await fetch("http://localhost/api/students/21212006", {
method: "DELETE",
});
assertEquals(res.status, 204);
} finally {
restoreFetch();
}
});
Deno.test("mock API: POST /students 400 on missing fields", async () => {
mockFetch({ "/students": { method: "POST", status: 400 } });
try {
const res = await fetch("http://localhost/api/students", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: "Test" }),
});
assertEquals(res.status, 400);
} finally {
restoreFetch();
}
});
// --- Mock DB ---
Deno.test("mock DB: find student by numEtud", () => {
const db = createMockDb({ tables: { students: [...students] } });
const s = db.findOne<Student>("students", (r) => r.numEtud === 21212006);
assertExists(s);
assertEquals(s.nom, "Dupont");
});
Deno.test("mock DB: filter students by idPromo", () => {
const db = createMockDb({ tables: { students: [...students] } });
const rows = db.findMany<Student>(
"students",
(s) => s.idPromo === "4AFISE25/26",
);
assertEquals(rows.length, 2);
});
Deno.test("mock DB: insert student increments count", () => {
const db = createMockDb({ tables: { students: [...students] } });
db.insert<Student>("students", {
numEtud: 21212099,
nom: "Test",
prenom: "Ing",
idPromo: "4AFISE25/26",
});
assertEquals(db.getTable("students").length, 4);
});
Deno.test("mock DB: update student nom", () => {
const db = createMockDb({ tables: { students: [...students] } });
const count = db.updateWhere<Student>(
"students",
(s) => s.numEtud === 21212006,
{ nom: "Nouveau" },
);
assertEquals(count, 1);
assertEquals(
db.findOne<Student>("students", (s) => s.numEtud === 21212006)?.nom,
"Nouveau",
);
});
Deno.test("mock DB: delete student removes exactly one", () => {
const db = createMockDb({ tables: { students: [...students] } });
const count = db.deleteWhere<Student>(
"students",
(s) => s.numEtud === 21212006,
);
assertEquals(count, 1);
assertEquals(db.getTable("students").length, 2);
});
Deno.test("mock API: getFetchCalls tracks student requests", async () => {
mockFetch({ "/students": students });
try {
await fetch("http://localhost/api/students");
await fetch("http://localhost/api/students?idPromo=4AFISE25/26");
const calls = getFetchCalls();
assertEquals(calls.length, 2);
assertEquals(calls[0].method, "GET");
} finally {
restoreFetch();
}
});
+216
View File
@@ -0,0 +1,216 @@
import { assertEquals } from "@std/assert";
import { getFetchCalls, mockFetch, restoreFetch } from "../helpers/api_mock.ts";
const BASE = "http://localhost/apps/admin/api/users";
const users = [
{ id: "dupont.jean", nom: "Dupont", prenom: "Jean", idRole: 1 },
{ id: "martin.alice", nom: "Martin", prenom: "Alice", idRole: 2 },
];
// --- GET /users ---
Deno.test("GET /users - returns all users", async () => {
mockFetch({ [BASE]: users });
try {
const res = await fetch(BASE);
assertEquals(res.status, 200);
const data = await res.json();
assertEquals(data.length, 2);
assertEquals(data[0].id, "dupont.jean");
} finally {
restoreFetch();
}
});
Deno.test("GET /users - filters by idRole", async () => {
const filtered = users.filter((u) => u.idRole === 1);
mockFetch({ [`${BASE}?idRole=1`]: filtered });
try {
const res = await fetch(`${BASE}?idRole=1`);
assertEquals(res.status, 200);
const data = await res.json();
assertEquals(data.length, 1);
assertEquals(data[0].idRole, 1);
} finally {
restoreFetch();
}
});
// --- POST /users ---
Deno.test("POST /users - creates a user and returns 201", async () => {
const newUser = {
id: "durand.claire",
nom: "Durand",
prenom: "Claire",
idRole: 1,
};
mockFetch({ [BASE]: { method: "POST", status: 201, body: newUser } });
try {
const res = await fetch(BASE, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(newUser),
});
assertEquals(res.status, 201);
const data = await res.json();
assertEquals(data.id, "durand.claire");
assertEquals(data.nom, "Durand");
} finally {
restoreFetch();
}
});
Deno.test("POST /users - returns 409 on duplicate id", async () => {
mockFetch({
[BASE]: {
method: "POST",
status: 409,
body: { error: "Un utilisateur avec cet identifiant existe déjà" },
},
});
try {
const res = await fetch(BASE, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(users[0]),
});
assertEquals(res.status, 409);
const data = await res.json();
assertEquals(typeof data.error, "string");
} finally {
restoreFetch();
}
});
Deno.test("POST /users - returns 400 on missing fields", async () => {
mockFetch({ [BASE]: { method: "POST", status: 400 } });
try {
const res = await fetch(BASE, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ id: "x" }),
});
assertEquals(res.status, 400);
} finally {
restoreFetch();
}
});
// --- GET /users/{id} ---
Deno.test("GET /users/{id} - returns a user by id", async () => {
mockFetch({ [`${BASE}/dupont.jean`]: users[0] });
try {
const res = await fetch(`${BASE}/dupont.jean`);
assertEquals(res.status, 200);
const data = await res.json();
assertEquals(data.id, "dupont.jean");
assertEquals(data.prenom, "Jean");
} finally {
restoreFetch();
}
});
Deno.test("GET /users/{id} - returns 404 for unknown id", async () => {
mockFetch({
[`${BASE}/inconnu`]: {
status: 404,
body: { error: "Ressource introuvable" },
},
});
try {
const res = await fetch(`${BASE}/inconnu`);
assertEquals(res.status, 404);
const data = await res.json();
assertEquals(typeof data.error, "string");
} finally {
restoreFetch();
}
});
// --- PUT /users/{id} ---
Deno.test("PUT /users/{id} - updates a user", async () => {
const updated = { ...users[0], prenom: "Jean-Pierre" };
mockFetch({
[`${BASE}/dupont.jean`]: { method: "PUT", status: 200, body: updated },
});
try {
const res = await fetch(`${BASE}/dupont.jean`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: "Dupont", prenom: "Jean-Pierre", idRole: 1 }),
});
assertEquals(res.status, 200);
const data = await res.json();
assertEquals(data.prenom, "Jean-Pierre");
} finally {
restoreFetch();
}
});
Deno.test("PUT /users/{id} - returns 404 for unknown id", async () => {
mockFetch({
[`${BASE}/inconnu`]: {
method: "PUT",
status: 404,
body: { error: "Ressource introuvable" },
},
});
try {
const res = await fetch(`${BASE}/inconnu`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: "X", prenom: "Y", idRole: 1 }),
});
assertEquals(res.status, 404);
} finally {
restoreFetch();
}
});
// --- DELETE /users/{id} ---
Deno.test("DELETE /users/{id} - deletes a user and returns 204", async () => {
mockFetch({
[`${BASE}/dupont.jean`]: { method: "DELETE", status: 204 },
});
try {
const res = await fetch(`${BASE}/dupont.jean`, { method: "DELETE" });
assertEquals(res.status, 204);
} finally {
restoreFetch();
}
});
Deno.test("DELETE /users/{id} - returns 404 for unknown id", async () => {
mockFetch({
[`${BASE}/inconnu`]: {
method: "DELETE",
status: 404,
body: { error: "Ressource introuvable" },
},
});
try {
const res = await fetch(`${BASE}/inconnu`, { method: "DELETE" });
assertEquals(res.status, 404);
} finally {
restoreFetch();
}
});
// --- getFetchCalls ---
Deno.test("GET /users - call is tracked", async () => {
mockFetch({ [BASE]: users });
try {
await fetch(BASE);
const calls = getFetchCalls();
assertEquals(calls.length, 1);
assertEquals(calls[0].method, "GET");
} finally {
restoreFetch();
}
});