Files
TREK/server/tests/e2e/places-library-rating.e2e.test.ts
T
Maurice 29ae0de1ef fix(places): the third CI run, no awaits in loops and an edit target that may be none
The rating order test pages through its cursor with a recursion and checks
the refused floors at once instead of awaiting in a loop, and the edit hook
types its first editable copy as possibly none, which the strict check reads
from a conditional rather than a narrowed assignment.
2026-11-30 00:16:23 +00:00

160 lines
7.2 KiB
TypeScript

/**
* The rating filter and the rating order of All places, end to end on the
* whole app (buildApp, the real guards and a migrated temp database; in the
* Postgres lane on Postgres too): `min_rating` keeps the entries whose
* average vote (every person once, over the copies the reader reaches)
* reaches it and leaves out the unrated ones, the tab counts follow it, the
* order `rating` puts the best rated first and the unrated last, page by
* page through its cursor, and list_all_places answers the same.
*/
import { buildApp } from '../../src/bootstrap';
import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity';
import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity';
import type { McpContext } from '../../src/nest-mcp';
import { withRequestContext } from '../../src/nest/database/request-context';
import { PlacesLibraryMcp } from '../../src/nest/places-library/places-library.mcp';
import { makeCollection, makeCollectionPlace } from '../helpers/factories/collections';
import { makePlace } from '../helpers/factories/places';
import { insertRow } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember, makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { resetRateLimits } from '../helpers/test-db';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
let app: INestApplication;
let server: Server;
let orm: MikroORM;
const LIBRARY = '/api/addons/collections/library/places';
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
interface Page {
entries: { key: string; name: string; rating?: { average: number | null } }[];
total: number;
counts: { all: number; trip: number; list: number };
next_cursor: string | null;
}
/**
* `me` has the trip Alps (with `friend` on it) holding Alpha (me 5, friend 3:
* 4 on average), Beta (me 5) and Gamma (no vote), and the list Food holding
* Delta (me 2). Each place stands alone, far from the others.
*/
async function seed() {
const { user: me } = await makeUser(orm);
const { user: friend } = await makeUser(orm);
const alps = await makeTrip(orm, me.id, { title: 'Alps' });
await addTripMember(orm, alps.id, friend.id);
const alpha = await makePlace(orm, alps.id, { name: 'Alpha', lat: 10, lng: 10 });
const beta = await makePlace(orm, alps.id, { name: 'Beta', lat: 20, lng: 20 });
await makePlace(orm, alps.id, { name: 'Gamma', lat: 30, lng: 30 });
const food = await makeCollection(orm, me.id, { name: 'Food' });
const delta = await makeCollectionPlace(orm, food.id, me.id, { name: 'Delta', lat: 40, lng: 40 });
await insertRow(orm, PlaceRatings, { place: alpha.id, user: me.id, rating: 5 });
await insertRow(orm, PlaceRatings, { place: alpha.id, user: friend.id, rating: 3 });
await insertRow(orm, PlaceRatings, { place: beta.id, user: me.id, rating: 5 });
await insertRow(orm, CollectionPlaceRatings, { collectionPlace: delta.id, user: me.id, rating: 2 });
return { me, friend, alps, food };
}
async function page(userId: number, query: Record<string, string | number>): Promise<Page> {
const res = await request(server).get(LIBRARY).query(query).set(as(userId));
expect(res.status).toBe(200);
return res.body as Page;
}
const names = (p: Page) => p.entries.map((entry) => entry.name);
beforeAll(async () => {
app = await buildApp();
server = app.getHttpServer() as Server;
orm = app.get(MikroORM);
await setAddonEnabled(orm, 'collections', true);
}, 60_000);
beforeEach(async () => {
await resetRateLimits(app);
});
afterAll(async () => {
await app?.close();
});
describe('the rating filter of All places', () => {
it('keeps the entries whose average reaches the floor, and the counts follow it', async () => {
const s = await seed();
const four = await page(s.me.id, { min_rating: 4 });
expect(names(four).sort()).toEqual(['Alpha', 'Beta']);
expect(four.total).toBe(2);
expect(four.counts).toEqual({ all: 2, trip: 2, list: 0 });
const two = await page(s.me.id, { min_rating: '2' });
expect(names(two).sort()).toEqual(['Alpha', 'Beta', 'Delta']);
expect(two.counts).toEqual({ all: 3, trip: 2, list: 1 });
// Without the filter the unrated place is there too.
expect((await page(s.me.id, {})).counts.all).toBe(4);
});
it('narrows a kind as well, and refuses a floor outside 1 to 5', async () => {
const s = await seed();
expect(names(await page(s.me.id, { min_rating: 2, kind: 'list' }))).toEqual(['Delta']);
const refused = await Promise.all(
['0', '6', '4.5', 'x'].map((bad) => request(server).get(LIBRARY).query({ min_rating: bad }).set(as(s.me.id))),
);
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]);
});
it('averages over the votes the reader can see: the friend reaches the trip only', async () => {
const s = await seed();
const theirs = await page(s.friend.id, { min_rating: 3 });
expect(names(theirs).sort()).toEqual(['Alpha', 'Beta']);
expect(theirs.entries.find((entry) => entry.name === 'Alpha')?.rating?.average).toBe(4);
});
});
describe('the rating order of All places', () => {
it('puts the best rated first, a tie by name, and the unrated last', async () => {
const s = await seed();
expect(names(await page(s.me.id, { sort: 'rating' }))).toEqual(['Beta', 'Alpha', 'Delta', 'Gamma']);
});
it('pages through its cursor without a gap or a double', async () => {
const s = await seed();
/** The pages from `cursor` on, one entry each, until the order ends. */
const rest = async (cursor: string | null, depth: number): Promise<string[]> => {
const query: Record<string, string | number> = { sort: 'rating', limit: 1 };
if (cursor) query.cursor = cursor;
const p = await page(s.me.id, query);
return p.next_cursor && depth < 5 ? [...names(p), ...(await rest(p.next_cursor, depth + 1))] : names(p);
};
const seen = await rest(null, 0);
expect(seen).toEqual(['Beta', 'Alpha', 'Delta', 'Gamma']);
// A cursor of the name order is no cursor of the rating order.
const byName = await page(s.me.id, { limit: 1 });
const res = await request(server)
.get(LIBRARY)
.query({ sort: 'rating', cursor: byName.next_cursor ?? '' })
.set(as(s.me.id));
expect(res.status).toBe(400);
});
it('combines with the floor, and list_all_places answers the same', async () => {
const s = await seed();
expect(names(await page(s.me.id, { sort: 'rating', min_rating: 3 }))).toEqual(['Beta', 'Alpha']);
const tools = app.get(PlacesLibraryMcp);
const ctx: McpContext = { userId: s.me.id, scopes: null, isStaticToken: false };
const answer = await withRequestContext(orm, () =>
tools.listAllPlaces({ sort: 'rating', min_rating: 3 } as never, ctx),
);
const text = (answer as unknown as { content: { text: string }[] }).content[0]?.text ?? '';
expect((JSON.parse(text) as Page).entries.map((entry) => entry.name)).toEqual(['Beta', 'Alpha']);
});
});