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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ npm test --prefix backend
npm test --prefix frontend
```

The complete clean-install, MongoDB and Playwright commands are documented in [Automated local testing](docs/testing.md). Automated tests run locally; browser tests use the production frontend, real API and an isolated database. Automatic execution on pull requests is optional future work requiring runner access from the course staff who administer the repository. GitHub Actions is not required by the assignment.

`npm run test:integration --prefix backend` also runs the API against a temporary MongoDB database (`MONGODB_TEST_URI`). The tests never change the deployed catalog. What is tested is described in [docs/backend.md](docs/backend.md#tests) and [frontend/README.md](frontend/README.md#tests).

Linting, formatting and the production builds are checked with:
Expand Down
24 changes: 12 additions & 12 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"db:explain": "npm run build && node --env-file-if-exists=.env dist/cli.js explain",
"db:verify": "npm run build && node --env-file-if-exists=.env dist/cli.js verify",
"test": "npm run build && node --test tests/validation.test.js tests/graphql.test.js tests/lineups.test.js tests/ratings.test.js",
"test:integration": "npm run build && node --env-file-if-exists=.env --test tests/integration.test.js tests/graphql.integration.test.js tests/lineups.integration.test.js tests/ratings.integration.test.js"
"test:integration": "npm run build && node --env-file-if-exists=.env --test tests/integration.test.js tests/graphql.integration.test.js tests/lineups.integration.test.js tests/ratings.integration.test.js tests/user-data.integration.test.js"
},
"dependencies": {
"@apollo/server": "^5.5.1",
Expand Down
54 changes: 54 additions & 0 deletions backend/tests/e2e-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Dedicated Playwright API. Never loads .env or uses MONGODB_URI/MONGODB_DB.
import { randomUUID } from "node:crypto";
import { MongoClient } from "mongodb";
import { importDataset, loadDataset } from "../dist/database.js";
import { createMongoCatalog } from "../dist/catalog.js";
import { createMongoLineupStore } from "../dist/lineups.js";
import { createMongoRatingStore } from "../dist/ratings.js";
import { startServer } from "../dist/server.js";

const uri = process.env.MONGODB_TEST_URI || "mongodb://127.0.0.1:27028";
// Tests are deliberately limited to a local, separately configured test service.
if (!/^mongodb:\/\/(127\.0\.0\.1|localhost):\d+(\/[^?]*)?(\?.*)?$/.test(uri)) {
throw new Error(
"E2E requires a loopback MONGODB_TEST_URI with an explicit port.",
);
}
const name = `vm26_e2e_${randomUUID().replaceAll("-", "")}`;
const client = new MongoClient(uri, { serverSelectionTimeoutMS: 5000 });
const db = client.db(name);
let server;
let stopping = false;
async function stop() {
if (stopping) return;
stopping = true;
try {
await server?.stop();
// The database name is generated here, never supplied by environment/config.
await db.dropDatabase();
} finally {
await client.close();
}
}
try {
await client.connect();
await importDataset(db, await loadDataset());
server = await startServer({
port: 3101,
catalog: createMongoCatalog(db),
lineups: createMongoLineupStore(db),
ratings: createMongoRatingStore(db),
});
console.log(`E2E API ready: ${server.url}; isolated database ${name}`);
for (const signal of ["SIGINT", "SIGTERM"]) {
process.once(signal, () => {
stop().catch((error) => {
console.error(error);
process.exitCode = 1;
});
});
}
} catch (error) {
await stop();
throw error;
}
4 changes: 4 additions & 0 deletions backend/tests/graphql.integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,10 @@ test("real MongoDB: GraphQL queries, pagination, squads and indexes", async (t)
)
).body.singleResult;
for (const [sort, expected] of Object.entries({
GOALS_DESC: ["1", "2", "3", "7"],
ASSISTS_DESC: ["1", "2", "3", "7"],
MATCHES_DESC: ["1", "2", "3", "7"],
RATING_DESC: ["1", "2", "3", "7"],
NAME_ASC: ["1", "2", "3", "7"],
NAME_DESC: ["7", "2", "3", "1"],
HEIGHT_DESC: ["1", "2", "3", "7"],
Expand Down
235 changes: 235 additions & 0 deletions backend/tests/user-data.integration.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
import test from "node:test";
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { MongoClient } from "mongodb";
import { importDataset, loadDataset } from "../dist/database.js";
import { createMongoCatalog } from "../dist/catalog.js";
import { createMongoLineupStore } from "../dist/lineups.js";
import { createMongoRatingStore } from "../dist/ratings.js";
import { createApolloServer } from "../dist/server.js";

test("real MongoDB: saved-data GraphQL mutations, validation and tied pagination", async (t) => {
assert.ok(
process.env.MONGODB_TEST_URI,
"Set MONGODB_TEST_URI to run integration tests",
);
const client = await new MongoClient(process.env.MONGODB_TEST_URI, {
serverSelectionTimeoutMS: 5000,
}).connect();
const db = client.db(`vm26_test_${randomUUID().replaceAll("-", "")}`);
const server = createApolloServer();
await server.start();
try {
const dataset = await loadDataset();
await importDataset(db, dataset);
const ratings = createMongoRatingStore(db);
const contextValue = {
catalog: createMongoCatalog(db),
lineups: createMongoLineupStore(db),
ratings,
};
const execute = async (query, variables = {}) => {
const response = await server.executeOperation(
{ query, variables },
{ contextValue },
);
assert.equal(response.body.kind, "single");
return response.body.singleResult;
};
const ownerId = randomUUID();
const otherOwner = randomUUID();
const input = {
ownerId,
playerId: "737066",
stars: 4,
comment: " Persist me ",
};
const rate = `mutation($input: RatingInput!) { ratePlayer(input: $input) { playerId stars comment createdAt updatedAt player { id name } } }`;
const find = `query($ownerId: ID!) { myRating(ownerId: $ownerId, playerId: "737066") { stars comment } myRatings(ownerId: $ownerId, limit: 1) { totalCount items { playerId } hasNextPage } }`;
await t.test(
"rating mutations round-trip through MongoDB, isolate owners and preserve creation time",
async () => {
const first = await execute(rate, { input });
assert.equal(first.errors, undefined);
assert.equal(first.data.ratePlayer.comment, "Persist me");
assert.equal(first.data.ratePlayer.player.name, "Erling Haaland");
const updated = await execute(rate, {
input: { ...input, stars: 2, comment: "Updated" },
});
assert.equal(updated.errors, undefined);
assert.equal(
updated.data.ratePlayer.createdAt,
first.data.ratePlayer.createdAt,
);
assert.equal(
await db.collection("ratings").countDocuments({ ownerId }),
1,
);
const read = await execute(find, { ownerId });
assert.equal(read.data.myRating.stars, 2);
assert.equal(read.data.myRating.comment, "Updated");
assert.equal(read.data.myRatings.totalCount, 1);
const other = await execute(find, { ownerId: otherOwner });
assert.equal(other.data.myRating, null);
assert.equal(other.data.myRatings.totalCount, 0);
},
);
await t.test(
"invalid rating mutations and pagination leave stored data untouched",
async () => {
for (const change of [
{ stars: 0 },
{ stars: 6 },
{ comment: "x".repeat(301) },
{ ownerId: "bad" },
{ playerId: "999999999" },
]) {
const result = await execute(rate, {
input: { ...input, ...change },
});
assert.equal(result.errors[0].extensions.code, "BAD_USER_INPUT");
}
for (const args of [
"limit: 0",
"limit: 51",
"offset: -1",
"offset: 10001",
]) {
const result = await execute(
`{ myRatings(ownerId: "${ownerId}", ${args}) { totalCount } }`,
);
assert.equal(result.errors[0].extensions.code, "BAD_USER_INPUT");
}
assert.equal(
(await ratings.find(ownerId, "737066")).comment,
"Updated",
);
assert.equal(await db.collection("ratings").countDocuments(), 1);
},
);
await t.test(
"all rating sort orders page deterministically across tied names, stars and timestamps",
async () => {
const ids = ["737066", "534670", "73409"];
const tiedOwner = randomUUID();
// Insert in reverse order so MongoDB natural insertion order cannot satisfy the expected order.
for (const playerId of ids.slice().reverse()) {
await ratings.save(
{ ownerId: tiedOwner, playerId, stars: 4, comment: "Tie" },
"2026-10-01T00:00:00.000Z",
);
}
await db
.collection("players")
.updateMany({ id: { $in: ids } }, { $set: { name: "Same name" } });
const query = `query($ownerId: ID!, $sort: RatingSort!, $offset: Int!) { myRatings(ownerId: $ownerId, sort: $sort, limit: 1, offset: $offset) { items { playerId } totalCount hasNextPage } }`;
for (const sort of ["NAME_ASC", "STARS_DESC", "UPDATED_DESC"]) {
const walk = async () => {
const seen = [];
for (let offset = 0; offset < 4; offset++) {
const result = await execute(query, {
ownerId: tiedOwner,
sort,
offset,
});
assert.equal(result.errors, undefined);
assert.equal(result.data.myRatings.totalCount, 3);
assert.equal(result.data.myRatings.hasNextPage, offset < 2);
seen.push(
...result.data.myRatings.items.map((item) => item.playerId),
);
}
return seen;
};
assert.deepEqual(await walk(), ids.slice().sort(), sort);
assert.deepEqual(
await walk(),
ids.slice().sort(),
`${sort} repeated`,
);
}
await importDataset(db, dataset);
},
);
await t.test(
"lineup mutation replaces slots, validates input and reads back via GraphQL",
async () => {
const save = `mutation($input: LineupInput!) { saveLineup(input: $input) { id name formation slots { slot playerId player { name } } } }`;
const lineup = {
ownerId,
name: " API XI ",
formation: "4-3-3",
slots: [{ slot: "FWD-2", playerId: "737066" }],
};
const result = await execute(save, { input: lineup });
assert.equal(result.errors, undefined);
assert.equal(result.data.saveLineup.name, "API XI");
const query = `query($ownerId: ID!) { myLineup(ownerId: $ownerId) { name slots { playerId player { name } } } }`;
assert.equal(
(await execute(query, { ownerId })).data.myLineup.slots[0].player
.name,
"Erling Haaland",
);
assert.equal(
(await execute(query, { ownerId: otherOwner })).data.myLineup,
null,
);
for (const change of [
{ name: " " },
{ formation: "2-2-6" },
{ slots: [...lineup.slots, ...lineup.slots] },
{ slots: [{ slot: "FWD-2", playerId: "999999999" }] },
]) {
const invalid = await execute(save, {
input: { ...lineup, ...change },
});
assert.equal(invalid.errors[0].extensions.code, "BAD_USER_INPUT");
}
assert.equal(
(await execute(query, { ownerId })).data.myLineup.slots.length,
1,
);
const cleared = await execute(save, {
input: { ...lineup, slots: [] },
});
assert.equal(cleared.errors, undefined);
assert.deepEqual(cleared.data.saveLineup.slots, []);
assert.equal(await db.collection("lineups").countDocuments(), 1);
const remove = `mutation($ownerId: ID!) { deleteLineup(ownerId: $ownerId) }`;
assert.equal(
(await execute(remove, { ownerId })).data.deleteLineup,
true,
);
assert.equal(
(await execute(remove, { ownerId })).data.deleteLineup,
false,
);
assert.equal((await execute(query, { ownerId })).data.myLineup, null);
},
);
await t.test(
"delete mutation is idempotent and the next query is empty",
async () => {
const remove = `mutation($ownerId: ID!) { removeRating(ownerId: $ownerId, playerId: "737066") }`;
assert.equal(
(await execute(remove, { ownerId })).data.removeRating,
true,
);
assert.equal(
(await execute(remove, { ownerId })).data.removeRating,
false,
);
const read = await execute(find, { ownerId });
assert.equal(read.data.myRating, null);
assert.equal(read.data.myRatings.totalCount, 0);
},
);
} finally {
await server.stop();
try {
await db.dropDatabase();
} finally {
await client.close();
}
}
});
20 changes: 20 additions & 0 deletions database/compose.test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Disposable test service, separate from compose.yaml and its persistent volume.
services:
mongodb-test:
image: mongo:8.0
ports:
- "127.0.0.1:27028:27017"
tmpfs:
- /data/db
healthcheck:
test:
[
"CMD",
"mongosh",
"--quiet",
"--eval",
"db.adminCommand({ ping: 1 }).ok",
]
interval: 2s
timeout: 5s
retries: 30
Loading