mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
feat(tours): plan rides on horseback from signposted horse routes
A tour can now be a ride (HOR-01). The planner offers "Horse ride" as a tour type with its own horseshoe, and a Horse routes card beside the waypoints looks, when asked, for the route=horse relations OpenStreetMap knows in the map view. A route opens in a dialog that shows it on a map in the sections it is made of, split at forks, gaps and crossings, so nothing is ever joined across a gap. The rider picks a section and its direction, sees what the horse=* tags along it say (open, limited, closed, or unknown where untagged) and whether it is signposted the other way, and takes it as one undoable step. A section that does not start where the ride ends is only joined by a straight manual stretch once the rider switched that on. Nothing of a ride is routed: every leg follows a section or is drawn by hand, and the waypoint list and the map say which (a section as a solid line with its route, a manual stretch dashed and marked unchecked). A point at a section stays where the route has it, a ride works out no riding time, and distance, heights, day assignment, GPX import and export, the 3D view and the reversed ride keep working with each leg's origin saved and opened again. A failed lookup leaves the ride and the routes already found as they were. The server reads the routes through the shared Overpass client (GET /api/trips/:tripId/tours/horse-routes, Tours addon, trip access), keeps an answer twelve hours per grid-aligned view, and the tour contract refuses a routed leg, a via ferrata or a riding time on a ride and a horse route section on any other type. A migration enables the horse tour type.
This commit is contained in:
@@ -0,0 +1,351 @@
|
||||
/**
|
||||
* Tours e2e for rides on horseback (HOR-01): a horse tour saved, read, copied
|
||||
* and exported with the origin of each of its legs, and the horse routes
|
||||
* around a map view, through the real JwtAuthGuard, AddonGuard and
|
||||
* TripAccessGuard against a migrated and seeded temp SQLite db. Overpass is a
|
||||
* container stub, the permission check a container spy and the broadcast goes
|
||||
* to a FakeRealtimeService, as in tours-bike.e2e.test.ts.
|
||||
*
|
||||
* Fixtures: user 1 owns trip 5, user 2 is a member of it whom the permission
|
||||
* spy denies 'place_edit', user 3 has no access.
|
||||
*/
|
||||
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { Tours } from '../../src/db/entities/Tours.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
|
||||
import { MapsService } from '../../src/nest/maps/maps.service';
|
||||
import { OverpassElementsClient } from '../../src/nest/overpass/overpass-elements.service';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { HORSE_ROUTES_UNAVAILABLE_MESSAGE } from '../../src/nest/tours/tour-horse-routes.service';
|
||||
import { ToursModule } from '../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { addTripMember } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { FERRATA_BBOX_TOO_LARGE_MESSAGE, HORSE_ROUTES_ATTRIBUTION } from '@trek/shared';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
|
||||
|
||||
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const { journeyHooks } = vi.hoisted(() => ({
|
||||
journeyHooks: {
|
||||
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceUpdated: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceDeleted: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
// The horse routes come from OpenStreetMap through Overpass: no network in a test.
|
||||
const overpassQuery = vi.fn();
|
||||
const realtime = new FakeRealtimeService();
|
||||
|
||||
let orm: TestOrm;
|
||||
let checkPermission: MockInstance;
|
||||
|
||||
const OWNER = 1;
|
||||
const VIEWER = 2;
|
||||
const OUTSIDER = 3;
|
||||
|
||||
const GEOMETRY = [
|
||||
[47, 11, 600],
|
||||
[47.005, 11.005, 640],
|
||||
[47.01, 11.01, 700],
|
||||
[47.02, 11.02, 650],
|
||||
];
|
||||
const SECTION = {
|
||||
kind: 'horse_route',
|
||||
ref: 'relation/42',
|
||||
name: 'Reitweg Isartal',
|
||||
geometry: [
|
||||
[47, 11],
|
||||
[47.005, 11.005],
|
||||
[47.01, 11.01],
|
||||
],
|
||||
signposted: 'with',
|
||||
access: [
|
||||
{ value: 'designated', length_m: 900 },
|
||||
{ value: 'unknown', length_m: 450 },
|
||||
],
|
||||
};
|
||||
const DRAWN = {
|
||||
kind: 'free',
|
||||
geometry: [
|
||||
[47.01, 11.01],
|
||||
[47.02, 11.02],
|
||||
],
|
||||
};
|
||||
const rideBody = (overrides: Record<string, unknown> = {}) => ({
|
||||
name: 'Ausritt am Fluss',
|
||||
tour_type: 'horse',
|
||||
route_geometry: GEOMETRY,
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0, fixed_leg: SECTION },
|
||||
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, fixed_leg: DRAWN },
|
||||
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
const GPX = `<?xml version="1.0"?>
|
||||
<gpx version="1.1" creator="e2e"><trk><name>Recorded ride</name><trkseg>
|
||||
<trkpt lat="47" lon="11"><ele>600</ele></trkpt>
|
||||
<trkpt lat="47.01" lon="11.01"><ele>640</ele></trkpt>
|
||||
</trkseg></trk></gpx>`;
|
||||
const overpassAnswer = [
|
||||
{
|
||||
type: 'relation',
|
||||
id: 42,
|
||||
tags: { route: 'horse', name: 'Reitweg Isartal', ref: 'R1' },
|
||||
members: [
|
||||
{ type: 'way', ref: 1, role: '' },
|
||||
{ type: 'way', ref: 2, role: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'way',
|
||||
id: 1,
|
||||
tags: { horse: 'designated' },
|
||||
nodes: [1, 2],
|
||||
geometry: [
|
||||
{ lat: 47.15, lon: 11.25 },
|
||||
{ lat: 47.16, lon: 11.25 },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe('Horse tours e2e (real guards + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
RealtimeModule,
|
||||
ToursModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(realtime)
|
||||
.overrideProvider(JourneyDomainService)
|
||||
.useValue(journeyHooks)
|
||||
.overrideProvider(MapsService)
|
||||
.useValue({ pois: vi.fn() })
|
||||
.overrideProvider(OverpassElementsClient)
|
||||
.useValue({ query: overpassQuery })
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
// Pinned ids: the session cookies sign for exactly these users.
|
||||
await makeUser(orm, { id: 1, username: 'owner', email: 'owner@example.test', role: 'user', password_version: 0 });
|
||||
await makeUser(orm, { id: 2, username: 'viewer', email: 'viewer@example.test', role: 'user', password_version: 0 });
|
||||
await makeUser(orm, {
|
||||
id: 3,
|
||||
username: 'outsider',
|
||||
email: 'outsider@example.test',
|
||||
role: 'user',
|
||||
password_version: 0,
|
||||
});
|
||||
await insertRows(orm, Trips, [{ id: 5, user: 1, title: 'Isar' }]);
|
||||
await addTripMember(orm, 5, 2);
|
||||
app = await build();
|
||||
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
checkPermission.mockImplementation(
|
||||
(action: string, _role: string, _owner: number, userId: number) =>
|
||||
!(action === 'place_edit' && userId === VIEWER),
|
||||
);
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
realtime.broadcastMock.mockClear();
|
||||
overpassQuery.mockReset();
|
||||
await deleteRows(orm, DayAssignments);
|
||||
await deleteRows(orm, Places);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
const send = (method: 'post' | 'put', path: string, body: Record<string, unknown>, userId = OWNER) =>
|
||||
request(server)[method](`/api/trips/5/tours${path}`).set('Cookie', sessionCookie(userId)).send(body);
|
||||
const create = async (body: Record<string, unknown> = rideBody()) => {
|
||||
const res = await send('post', '', body);
|
||||
expect(res.status).toBe(201);
|
||||
return res.body.tour.place_id as number;
|
||||
};
|
||||
|
||||
describe('a ride and the origin of its legs', () => {
|
||||
it('saves a ride, lists it without a riding time and broadcasts the change', async () => {
|
||||
const placeId = await create();
|
||||
expect(await findRow(orm, Tours, { place: placeId })).toMatchObject({
|
||||
tour_type: 'horse',
|
||||
duration: null,
|
||||
max_hiking_difficulty: null,
|
||||
bike_profile: null,
|
||||
});
|
||||
const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(VIEWER));
|
||||
expect(list.status).toBe(200);
|
||||
const tour = list.body.tours.find((item: { place_id: number }) => item.place_id === placeId);
|
||||
expect(tour).toMatchObject({ tour_type: 'horse', duration: null });
|
||||
// The heights of its line are read like any other tour's; only a time is never worked out.
|
||||
expect(tour.elevation_gain).toBeGreaterThan(0);
|
||||
expect(realtime.broadcastMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens again with each leg as taken, a section with its direction and access', async () => {
|
||||
const placeId = await create();
|
||||
const res = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.tour.tour_type).toBe('horse');
|
||||
expect(res.body.waypoints.map((point: { fixed_leg?: unknown }) => point.fixed_leg ?? null)).toEqual([
|
||||
SECTION,
|
||||
DRAWN,
|
||||
null,
|
||||
]);
|
||||
});
|
||||
|
||||
it('refuses a routed leg, a via ferrata, a riding time worked out and a section on a hike', async () => {
|
||||
const ferrata = { kind: 'ferrata', ref: 'way/1', name: null, geometry: SECTION.geometry };
|
||||
const routed = rideBody({
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 47.01, lng: 11.01, role: 'end', sequence: 1 },
|
||||
],
|
||||
});
|
||||
const bodies = [
|
||||
routed,
|
||||
rideBody({
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0, fixed_leg: ferrata },
|
||||
{ lat: 47.01, lng: 11.01, role: 'end', sequence: 1 },
|
||||
],
|
||||
}),
|
||||
rideBody({ duration_seconds: 5400 }),
|
||||
rideBody({ tour_type: 'hike', max_hiking_difficulty: 2 }),
|
||||
];
|
||||
const statuses = await bodies.reduce<Promise<number[]>>(
|
||||
async (done, body) => [...(await done), (await send('post', '', body)).status],
|
||||
Promise.resolve([]),
|
||||
);
|
||||
expect(statuses).toEqual([400, 400, 400, 400]);
|
||||
expect(await countRows(orm, Tours)).toBe(0);
|
||||
});
|
||||
|
||||
it('a member who may only read cannot save one', async () => {
|
||||
expect((await send('post', '', rideBody(), VIEWER)).status).toBe(403);
|
||||
});
|
||||
|
||||
it('a copy keeps the type and the legs', async () => {
|
||||
const placeId = await create();
|
||||
const copy = await send('post', `/${placeId}/copy`, { name: 'Noch einmal' });
|
||||
expect(copy.status).toBe(201);
|
||||
expect(copy.body.tour).toMatchObject({ tour_type: 'horse' });
|
||||
expect(copy.body.waypoints[0].fixed_leg).toEqual(SECTION);
|
||||
});
|
||||
|
||||
it('exports a ride as horseback riding', async () => {
|
||||
const placeId = await create();
|
||||
const res = await request(server)
|
||||
.get(`/api/trips/5/tours/${placeId}/export.gpx`)
|
||||
.set('Cookie', sessionCookie(OWNER))
|
||||
.buffer(true)
|
||||
.parse((response, done) => {
|
||||
let text = '';
|
||||
response.setEncoding('utf8');
|
||||
response.on('data', (chunk: string) => (text += chunk));
|
||||
response.on('end', () => done(null, text));
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(String(res.body)).toContain('<type>horseback_riding</type>');
|
||||
});
|
||||
|
||||
it('imports a recorded ride as a ride, with nothing of another type', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/trips/5/tours/import/gpx')
|
||||
.set('Cookie', sessionCookie(OWNER))
|
||||
.field('tour_type', 'horse')
|
||||
.attach('file', Buffer.from(GPX), { filename: 'ride.gpx', contentType: 'application/gpx+xml' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.tours[0]).toMatchObject({ tour_type: 'horse', origin: 'gpx', duration: null, bike_profile: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET horse-routes', () => {
|
||||
const ask = (bbox: string | undefined, userId?: number) => {
|
||||
const req = request(server).get('/api/trips/5/tours/horse-routes');
|
||||
const withQuery = bbox === undefined ? req : req.query({ bbox });
|
||||
return userId ? withQuery.set('Cookie', sessionCookie(userId)) : withQuery;
|
||||
};
|
||||
|
||||
it('answers the routes in the view, cut into sections, to anyone who sees the trip', async () => {
|
||||
overpassQuery.mockResolvedValueOnce(overpassAnswer);
|
||||
const res = await ask('47.12,11.21,47.18,11.29', VIEWER);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({
|
||||
truncated: false,
|
||||
source: 'openstreetmap',
|
||||
attribution: HORSE_ROUTES_ATTRIBUTION,
|
||||
});
|
||||
expect(res.body.routes).toEqual([
|
||||
expect.objectContaining({ id: 'relation/42', name: 'Reitweg Isartal', ref: 'R1', continues: true }),
|
||||
]);
|
||||
expect(res.body.routes[0].sections[0]).toMatchObject({
|
||||
number: 1,
|
||||
signposted: null,
|
||||
access: [{ value: 'designated', length_m: 1112 }],
|
||||
});
|
||||
});
|
||||
|
||||
it('says when no mirror answered, and refuses a box too large, an outsider and no session', async () => {
|
||||
overpassQuery.mockRejectedValueOnce(new Error('all mirrors down'));
|
||||
const failed = await ask('48.12,11.21,48.18,11.29', OWNER);
|
||||
expect(failed.status).toBe(502);
|
||||
expect(failed.body).toEqual({ error: HORSE_ROUTES_UNAVAILABLE_MESSAGE, code: 'horse_routes_unavailable' });
|
||||
const wide = await ask('46,11,47,11.4', OWNER);
|
||||
expect(wide.status).toBe(400);
|
||||
expect(wide.body).toEqual({ error: FERRATA_BBOX_TOO_LARGE_MESSAGE });
|
||||
expect((await ask('47.12,11.21,47.18,11.29', OUTSIDER)).status).toBe(404);
|
||||
expect((await ask('47.12,11.21,47.18,11.29')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('is not there while the Tours addon is off', async () => {
|
||||
await setAddonEnabled(orm, 'tours', false);
|
||||
expect((await ask('47.12,11.21,47.18,11.29', OWNER)).status).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -69,6 +69,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101045500_a_hike_can_be_marked_as_a_winter_activity',
|
||||
'Migration20200101045510_a_tour_can_be_a_run',
|
||||
'Migration20200101045520_a_tour_can_be_a_ski_track',
|
||||
'Migration20200101045600_a_tour_can_be_ridden_on_horseback',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* `Migration20200101045600_a_tour_can_be_ridden_on_horseback` (HOR-01):
|
||||
* `tour_types` gains the enabled `horse` key with no routing profile, the
|
||||
* other types stay as they were, and an instance that already defined the key
|
||||
* keeps its own row.
|
||||
*/
|
||||
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
|
||||
import type { MikroORM } from '@mikro-orm/sqlite';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const TARGET = 'Migration20200101045600_a_tour_can_be_ridden_on_horseback';
|
||||
|
||||
async function ormBeforeTarget(): Promise<MikroORM> {
|
||||
const orm = await createMigrationOrm();
|
||||
const names = await pendingNames(orm);
|
||||
const index = names.indexOf(TARGET);
|
||||
expect(index).toBeGreaterThan(0);
|
||||
await migrateTo(orm, names[index - 1]);
|
||||
return orm;
|
||||
}
|
||||
|
||||
describe('Tour horse type migration', () => {
|
||||
it('TOURHORSEMIG-001: adds the enabled horse type without a routing profile and leaves the others alone', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
const before = await rawQuery(orm, "SELECT key, enabled FROM tour_types WHERE key <> 'horse' ORDER BY key");
|
||||
expect(await rawQuery(orm, "SELECT key FROM tour_types WHERE key = 'horse'")).toEqual([]);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(
|
||||
await rawQuery(
|
||||
orm,
|
||||
"SELECT key, label_key, routing_profile, is_sport, enabled, sort_order FROM tour_types WHERE key = 'horse'",
|
||||
),
|
||||
).toEqual([
|
||||
{
|
||||
key: 'horse',
|
||||
label_key: 'tourTypes.horse',
|
||||
routing_profile: null,
|
||||
is_sport: 1,
|
||||
enabled: 1,
|
||||
sort_order: 7,
|
||||
},
|
||||
]);
|
||||
expect(await rawQuery(orm, "SELECT key, enabled FROM tour_types WHERE key <> 'horse' ORDER BY key")).toEqual(
|
||||
before,
|
||||
);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('TOURHORSEMIG-002: a horse type an instance already defined keeps its own values', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await rawExec(
|
||||
orm,
|
||||
"INSERT INTO tour_types (key, label_key, icon, color, routing_profile, enabled, sort_order) VALUES ('horse', 'tourTypes.horse', 'Own', '#000000', NULL, 0, 9)",
|
||||
);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await rawQuery(orm, "SELECT icon, enabled, sort_order FROM tour_types WHERE key = 'horse'")).toEqual([
|
||||
{ icon: 'Own', enabled: 0, sort_order: 9 },
|
||||
]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
@@ -41,7 +41,8 @@ describe('Tour types migration', () => {
|
||||
orm,
|
||||
'SELECT key, enabled, label_key FROM tour_types ORDER BY sort_order',
|
||||
);
|
||||
expect(types.map((t) => t.key)).toEqual([...tourTypeKeySchema.options]);
|
||||
// The keys the contract named then; `horse` came later with a migration of its own (HOR-01).
|
||||
expect(types.map((t) => t.key)).toEqual(tourTypeKeySchema.options.filter((key) => key !== 'horse'));
|
||||
expect(types.filter((t) => t.enabled === 1).map((t) => t.key)).toEqual(['hike']);
|
||||
for (const t of types) expect(t.label_key).toBe(`tourTypes.${t.key}`);
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { routeSections, type RouteEdge } from '../../../src/nest/tours/horse-route-sections';
|
||||
import { HORSE_ROUTE_SECTION_MAX_POINTS, type HorseAccess } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// HORSE-SECT-001 to HORSE-SECT-007
|
||||
|
||||
/** Node n lies n thousandths of a degree north of 47° N, about 111 m apart. */
|
||||
const coords = (count: number) =>
|
||||
new Map<number, [number, number]>(Array.from({ length: count }, (_, n) => [n + 1, [47 + n * 0.001, 11]]));
|
||||
|
||||
/** The steps of a way along the nodes given, in that order. */
|
||||
function way(nodes: number[], order: number, extra: { access?: HorseAccess; signed?: 1 | -1 | 0 } = {}): RouteEdge[] {
|
||||
return nodes.slice(1).map((to, index) => ({
|
||||
from: nodes[index] as number,
|
||||
to,
|
||||
access: extra.access ?? 'unknown',
|
||||
signed: extra.signed ?? 0,
|
||||
order,
|
||||
}));
|
||||
}
|
||||
|
||||
const firstPoints = (sections: ReturnType<typeof routeSections>) =>
|
||||
sections.map((section) => [section.geometry[0], section.geometry[section.geometry.length - 1]]);
|
||||
|
||||
describe('routeSections (HOR-01)', () => {
|
||||
it('HORSE-SECT-001: ways that meet end to end are one section, with the access of each along it', () => {
|
||||
const sections = routeSections(
|
||||
[...way([1, 2, 3], 0, { access: 'designated' }), ...way([3, 4, 5], 1, { access: 'private' })],
|
||||
coords(5),
|
||||
);
|
||||
expect(sections).toHaveLength(1);
|
||||
expect(sections[0]?.geometry).toEqual([
|
||||
[47, 11],
|
||||
[47.001, 11],
|
||||
[47.002, 11],
|
||||
[47.003, 11],
|
||||
[47.004, 11],
|
||||
]);
|
||||
expect(sections[0]?.lengthM).toBeCloseTo(445, -1);
|
||||
expect(sections[0]?.access.map((share) => share.value).sort()).toEqual(['designated', 'private']);
|
||||
expect(sections[0]?.access.reduce((sum, share) => sum + share.length_m, 0)).toBeCloseTo(445, -1);
|
||||
expect(sections[0]?.signposted).toBeNull();
|
||||
});
|
||||
|
||||
it('HORSE-SECT-002: a fork ends a section, and each branch is one of its own', () => {
|
||||
const sections = routeSections([...way([1, 2, 3], 0), ...way([3, 4], 1), ...way([3, 5], 2)], coords(5));
|
||||
expect(sections).toHaveLength(3);
|
||||
for (const section of sections) {
|
||||
const ends = [section.geometry[0], section.geometry[section.geometry.length - 1]];
|
||||
expect(ends).toContainEqual([47.002, 11]);
|
||||
}
|
||||
});
|
||||
|
||||
it('HORSE-SECT-003: a gap stays a gap, never joined by a line of its own', () => {
|
||||
const sections = routeSections([...way([1, 2], 0), ...way([4, 5], 1)], coords(5));
|
||||
expect(firstPoints(sections)).toEqual([
|
||||
[
|
||||
[47, 11],
|
||||
[47.001, 11],
|
||||
],
|
||||
[
|
||||
[47.003, 11],
|
||||
[47.004, 11],
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it('HORSE-SECT-004: a ring without a fork is walked once round', () => {
|
||||
const ring = new Map<number, [number, number]>([
|
||||
[1, [47, 11]],
|
||||
[2, [47.001, 11]],
|
||||
[3, [47.001, 11.001]],
|
||||
]);
|
||||
const sections = routeSections(way([1, 2, 3, 1], 0), ring);
|
||||
expect(sections).toHaveLength(1);
|
||||
expect(sections[0]?.geometry).toHaveLength(4);
|
||||
expect(sections[0]?.geometry[0]).toEqual(sections[0]?.geometry[3]);
|
||||
});
|
||||
|
||||
it('HORSE-SECT-005: says the signposted direction only where all of the section is signposted one way', () => {
|
||||
expect(routeSections(way([1, 2, 3], 0, { signed: 1 }), coords(3))[0]?.signposted).toBe('with');
|
||||
expect(routeSections(way([1, 2, 3], 0, { signed: -1 }), coords(3))[0]?.signposted).toBe('against');
|
||||
const mixed = [...way([1, 2], 0, { signed: 1 }), ...way([2, 3], 1)];
|
||||
expect(routeSections(mixed, coords(3))[0]?.signposted).toBeNull();
|
||||
// A way listed against the walk still reads the right way round.
|
||||
const turned = [...way([1, 2], 0, { signed: 1 }), ...way([3, 2], 1, { signed: -1 })];
|
||||
expect(routeSections(turned, coords(3))[0]?.signposted).toBe('with');
|
||||
});
|
||||
|
||||
it('HORSE-SECT-006: a stretch longer than a fixed leg takes is cut into pieces that meet end to end', () => {
|
||||
const count = HORSE_ROUTE_SECTION_MAX_POINTS + 10;
|
||||
const nodes = Array.from({ length: count }, (_, n) => n + 1);
|
||||
const places = new Map<number, [number, number]>(nodes.map((n) => [n, [47 + n * 0.00001, 11]]));
|
||||
const sections = routeSections(way(nodes, 0), places);
|
||||
expect(sections.map((section) => section.geometry.length)).toEqual([HORSE_ROUTE_SECTION_MAX_POINTS, 11]);
|
||||
expect(sections[1]?.geometry[0]).toEqual(sections[0]?.geometry[HORSE_ROUTE_SECTION_MAX_POINTS - 1]);
|
||||
});
|
||||
|
||||
it('HORSE-SECT-007: sections follow the order the route lists its ways, and one of no length is left out', () => {
|
||||
const places = new Map<number, [number, number]>([
|
||||
[1, [47, 11]],
|
||||
[2, [47.001, 11]],
|
||||
[3, [47.1, 11]],
|
||||
[4, [47.101, 11]],
|
||||
[5, [47.2, 11]],
|
||||
[6, [47.2, 11]],
|
||||
]);
|
||||
const sections = routeSections([...way([3, 4], 0), ...way([1, 2], 1), ...way([5, 6], 2)], places);
|
||||
expect(sections.map((section) => section.order)).toEqual([0, 1]);
|
||||
expect(sections[0]?.geometry[0]).toEqual([47.1, 11]);
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,9 @@ import { gpxActivityOf } from '../../../src/nest/tours/tour-gpx-export.helpers';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// TOUR-GPX-ACTIVITY-001 to TOUR-GPX-ACTIVITY-005
|
||||
// TOUR-GPX-ACTIVITY-001 to TOUR-GPX-ACTIVITY-007
|
||||
|
||||
describe('gpxActivityOf (PR1-06A, BIK-01, HIK-01, RUN-01, SKI-02)', () => {
|
||||
describe('gpxActivityOf (PR1-06A, BIK-01, HIK-01, RUN-01, SKI-02, HOR-01)', () => {
|
||||
it('TOUR-GPX-ACTIVITY-001: a bike tour names its profile, and the plainest riding without a known one', () => {
|
||||
expect(gpxActivityOf({ tour_type: 'bike', bike_profile: 'mtb' })).toBe('mountain_biking');
|
||||
expect(gpxActivityOf({ tour_type: 'bike', bike_profile: null })).toBe('cycling');
|
||||
@@ -44,4 +44,8 @@ describe('gpxActivityOf (PR1-06A, BIK-01, HIK-01, RUN-01, SKI-02)', () => {
|
||||
expect(gpxActivityOf({ tour_type: 'ski', ski_discipline: null })).toBe('skiing');
|
||||
expect(gpxActivityOf({ tour_type: 'ski', ski_discipline: 'freeride' })).toBe('skiing');
|
||||
});
|
||||
|
||||
it('TOUR-GPX-ACTIVITY-007: a horse tour is horseback riding (HOR-01)', () => {
|
||||
expect(gpxActivityOf({ tour_type: 'horse' })).toBe('horseback_riding');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
|
||||
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
|
||||
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';
|
||||
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
|
||||
import {
|
||||
parseHorseRoutesQuery,
|
||||
TourHorseRoutesController,
|
||||
} from '../../../src/nest/tours/tour-horse-routes.controller';
|
||||
import type { TourHorseRoutesService } from '../../../src/nest/tours/tour-horse-routes.service';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
import {
|
||||
FERRATA_BBOX_INVALID_MESSAGE,
|
||||
FERRATA_BBOX_TOO_LARGE_MESSAGE,
|
||||
HORSE_ROUTES_ATTRIBUTION,
|
||||
horseRoutesResponseSchema,
|
||||
type HorseRoutesResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// HORSE-CTRL-001 to HORSE-CTRL-004
|
||||
|
||||
function thrown(fn: () => unknown): { status: number; body: unknown } {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(HttpException);
|
||||
const e = err as HttpException;
|
||||
return { status: e.getStatus(), body: e.getResponse() };
|
||||
}
|
||||
throw new Error('expected a throw');
|
||||
}
|
||||
|
||||
const answer: HorseRoutesResponse = {
|
||||
routes: [],
|
||||
truncated: false,
|
||||
source: 'openstreetmap',
|
||||
attribution: HORSE_ROUTES_ATTRIBUTION,
|
||||
};
|
||||
|
||||
describe('TourHorseRoutesController (HOR-01)', () => {
|
||||
it('HORSE-CTRL-001: reads the box of the map view', () => {
|
||||
expect(parseHorseRoutesQuery({ bbox: '47.1,11.2,47.4,11.6' }).bbox).toEqual({
|
||||
south: 47.1,
|
||||
west: 11.2,
|
||||
north: 47.4,
|
||||
east: 11.6,
|
||||
});
|
||||
});
|
||||
|
||||
it('HORSE-CTRL-002: answers a malformed box and one too large with their own messages', () => {
|
||||
for (const raw of [{}, { bbox: '1,2,3' }, { bbox: '47.4,11.2,47.1,11.6' }]) {
|
||||
expect(thrown(() => parseHorseRoutesQuery(raw))).toEqual({
|
||||
status: 400,
|
||||
body: { error: FERRATA_BBOX_INVALID_MESSAGE },
|
||||
});
|
||||
}
|
||||
expect(thrown(() => parseHorseRoutesQuery({ bbox: '46,11,47,11.4' }))).toEqual({
|
||||
status: 400,
|
||||
body: { error: FERRATA_BBOX_TOO_LARGE_MESSAGE },
|
||||
});
|
||||
});
|
||||
|
||||
it('HORSE-CTRL-003: hands the box to the service and returns its answer', async () => {
|
||||
const list = vi.fn(async () => answer);
|
||||
const controller = new TourHorseRoutesController({ list } as unknown as TourHorseRoutesService);
|
||||
await expect(controller.list({ bbox: '47.1,11.2,47.4,11.6' })).resolves.toBe(answer);
|
||||
expect(list).toHaveBeenCalledWith({ south: 47.1, west: 11.2, north: 47.4, east: 11.6 });
|
||||
});
|
||||
|
||||
it('HORSE-CTRL-004: sits behind the Tours addon, the session and the trip access, and declares its contract', () => {
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, TourHorseRoutesController)).toEqual([
|
||||
AddonGuard,
|
||||
JwtAuthGuard,
|
||||
TripAccessGuard,
|
||||
]);
|
||||
expect(Reflect.getMetadata(REQUIRE_ADDON, TourHorseRoutesController)).toEqual({
|
||||
addonId: ADDON_IDS.TOURS,
|
||||
label: 'Tours',
|
||||
});
|
||||
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, TourHorseRoutesController.prototype.list)).toBe(
|
||||
horseRoutesResponseSchema,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import {
|
||||
buildHorseRoutesQuery,
|
||||
HORSE_ROUTE_WAYS_CAP,
|
||||
horseAccessOf,
|
||||
horseRouteBboxKey,
|
||||
snapHorseRouteBbox,
|
||||
toHorseRoutes,
|
||||
} from '../../../src/nest/tours/tour-horse-routes.helpers';
|
||||
import { HORSE_ROUTE_SECTIONS_CAP, HORSE_ROUTES_RESULT_CAP, horseRouteSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// HORSE-HELP-001 to HORSE-HELP-008
|
||||
|
||||
const at = (lat: number, lon: number) => ({ lat, lon });
|
||||
const way = (
|
||||
id: number,
|
||||
nodes: number[],
|
||||
tags: Record<string, string> = {},
|
||||
geometry: Array<{ lat: number; lon: number } | null> = nodes.map((n) => at(47 + n * 0.001, 11)),
|
||||
) => ({ type: 'way', id, tags, nodes, geometry });
|
||||
const relation = (
|
||||
id: number,
|
||||
members: Array<{ type?: string; ref: number; role?: string }>,
|
||||
tags: Record<string, string> = { route: 'horse', name: 'Reitweg', ref: 'R1' },
|
||||
) => ({ type: 'relation', id, tags, members: members.map((member) => ({ type: 'way', role: '', ...member })) });
|
||||
|
||||
describe('horse route helpers (HOR-01)', () => {
|
||||
it('HORSE-HELP-001: asks for the routes in the box, their members and their ways in it with tags and nodes', () => {
|
||||
expect(buildHorseRoutesQuery({ south: 47.1, west: 11.2, north: 47.4, east: 11.6 })).toBe(
|
||||
[
|
||||
'[out:json][timeout:25];',
|
||||
'rel["route"="horse"](47.1,11.2,47.4,11.6)->.routes;',
|
||||
'way(r.routes)(47.1,11.2,47.4,11.6)->.ways;',
|
||||
`.routes out body qt ${HORSE_ROUTES_RESULT_CAP + 1};`,
|
||||
`.ways out body geom qt ${HORSE_ROUTE_WAYS_CAP + 1};`,
|
||||
].join('\n'),
|
||||
);
|
||||
});
|
||||
|
||||
it('HORSE-HELP-002: grows a box to the 0.05 degree grid, clamped to the globe, and keys it by its edges', () => {
|
||||
const box = snapHorseRouteBbox({ south: 47.12, west: 11.21, north: 47.18, east: 11.29 });
|
||||
expect(box).toEqual({ south: 47.1, west: 11.2, north: 47.2, east: 11.3 });
|
||||
expect(horseRouteBboxKey(box)).toBe('47.1,11.2,47.2,11.3');
|
||||
expect(snapHorseRouteBbox({ south: -89.99, west: -179.99, north: 89.99, east: 179.99 })).toEqual({
|
||||
south: -90,
|
||||
west: -180,
|
||||
north: 90,
|
||||
east: 180,
|
||||
});
|
||||
});
|
||||
|
||||
it('HORSE-HELP-003: reads horse=* as tagged, any other value as other and none as unknown', () => {
|
||||
const tagged = ['designated', ' Yes ', 'permissive', 'destination', 'discouraged', 'private', 'no'];
|
||||
expect(tagged.map((value) => horseAccessOf(value))).toEqual([
|
||||
'designated',
|
||||
'yes',
|
||||
'permissive',
|
||||
'destination',
|
||||
'discouraged',
|
||||
'private',
|
||||
'no',
|
||||
]);
|
||||
expect(horseAccessOf('customers')).toBe('other');
|
||||
expect(horseAccessOf('')).toBe('unknown');
|
||||
expect(horseAccessOf(undefined)).toBe('unknown');
|
||||
});
|
||||
|
||||
it('HORSE-HELP-004: a route with its sections, the access of its ways and its own name and ref', () => {
|
||||
const { routes, truncated } = toHorseRoutes([
|
||||
relation(7, [{ ref: 1 }, { ref: 2, role: 'forward' }]),
|
||||
way(1, [1, 2, 3], { horse: 'designated' }),
|
||||
way(2, [3, 4], { horse: 'no' }),
|
||||
]);
|
||||
expect(truncated).toBe(false);
|
||||
expect(routes).toHaveLength(1);
|
||||
const route = routes[0];
|
||||
expect(horseRouteSchema.parse(route)).toEqual(route);
|
||||
expect(route).toMatchObject({
|
||||
id: 'relation/7',
|
||||
name: 'Reitweg',
|
||||
ref: 'R1',
|
||||
osmUrl: 'https://www.openstreetmap.org/relation/7',
|
||||
continues: false,
|
||||
});
|
||||
expect(route?.sections).toHaveLength(1);
|
||||
expect(route?.sections[0]).toMatchObject({ number: 1, signposted: null });
|
||||
expect(route?.sections[0]?.access.map((share) => share.value)).toEqual(['designated', 'no']);
|
||||
});
|
||||
|
||||
it('HORSE-HELP-005: says a route goes on past the box, and leaves out one with no way in it', () => {
|
||||
const { routes } = toHorseRoutes([
|
||||
relation(7, [{ ref: 1 }, { ref: 99 }]),
|
||||
relation(8, [{ ref: 98 }]),
|
||||
way(1, [1, 2]),
|
||||
]);
|
||||
expect(routes.map((route) => [route.id, route.continues])).toEqual([['relation/7', true]]);
|
||||
});
|
||||
|
||||
it('HORSE-HELP-006: reads each way once, skips other members, unplaced points and elements of another shape', () => {
|
||||
const { routes } = toHorseRoutes([
|
||||
relation(7, [{ ref: 1 }, { ref: 1, role: 'backward' }, { type: 'node', ref: 5 }, { ref: 2 }], {
|
||||
route: 'horse',
|
||||
name: ' ',
|
||||
}),
|
||||
way(1, [1, 2, 3], {}, [at(47, 11), null, at(47.002, 11)]),
|
||||
way(2, [10, 11], { horse: 'yes' }),
|
||||
{ type: 'way', id: 3 },
|
||||
{ type: 'node', id: 4, lat: 47, lon: 11 },
|
||||
null,
|
||||
]);
|
||||
expect(routes).toHaveLength(1);
|
||||
expect(routes[0]).toMatchObject({ name: null, ref: null, continues: false });
|
||||
// The way with an unplaced middle point has no step left; only the second way gives a section.
|
||||
expect(routes[0]?.sections.map((section) => section.access[0]?.value)).toEqual(['yes']);
|
||||
});
|
||||
|
||||
it('HORSE-HELP-007: an answer past the caps says it was cut', () => {
|
||||
const many = Array.from({ length: HORSE_ROUTES_RESULT_CAP + 1 }, (_, index) => relation(index + 1, [{ ref: 1 }]));
|
||||
const cut = toHorseRoutes([...many, way(1, [1, 2])]);
|
||||
expect(cut.truncated).toBe(true);
|
||||
expect(cut.routes).toHaveLength(HORSE_ROUTES_RESULT_CAP);
|
||||
});
|
||||
|
||||
it('HORSE-HELP-008: a route with more sections than an answer carries is cut to the cap and said to be', () => {
|
||||
const count = HORSE_ROUTE_SECTIONS_CAP + 1;
|
||||
const members = Array.from({ length: count }, (_, index) => ({ ref: index + 1 }));
|
||||
// Each way two nodes of its own, apart from the others: as many sections as ways.
|
||||
const ways = members.map(({ ref }) => way(ref, [ref * 10, ref * 10 + 1]));
|
||||
const { routes, truncated } = toHorseRoutes([relation(7, members), ...ways]);
|
||||
expect(truncated).toBe(true);
|
||||
expect(routes[0]?.sections).toHaveLength(HORSE_ROUTE_SECTIONS_CAP);
|
||||
expect(routes[0]?.sections.map((section) => section.number).slice(0, 3)).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { OverpassElementsClient } from '../../../src/nest/overpass/overpass-elements.service';
|
||||
import {
|
||||
HORSE_ROUTES_KEPT_MS,
|
||||
HORSE_ROUTES_UNAVAILABLE_MESSAGE,
|
||||
TourHorseRoutesService,
|
||||
} from '../../../src/nest/tours/tour-horse-routes.service';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { HORSE_ROUTES_ATTRIBUTION, HORSE_ROUTES_UNAVAILABLE_CODE, horseRoutesResponseSchema } from '@trek/shared';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// HORSE-SVC-001 to HORSE-SVC-005
|
||||
|
||||
const query = vi.fn<(q: string, caller: string) => Promise<unknown[]>>();
|
||||
let service: TourHorseRoutesService;
|
||||
|
||||
const NOW = 1_800_000_000_000;
|
||||
const box = { south: 47.12, west: 11.21, north: 47.18, east: 11.29 };
|
||||
const elements = [
|
||||
{ type: 'relation', id: 7, tags: { route: 'horse', name: 'Reitweg' }, members: [{ type: 'way', ref: 1, role: '' }] },
|
||||
{
|
||||
type: 'way',
|
||||
id: 1,
|
||||
tags: { horse: 'designated' },
|
||||
nodes: [1, 2],
|
||||
geometry: [
|
||||
{ lat: 47.15, lon: 11.25 },
|
||||
{ lat: 47.16, lon: 11.25 },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(async () => {
|
||||
query.mockReset();
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [TourHorseRoutesService, { provide: OverpassElementsClient, useValue: { query } }],
|
||||
}).compile();
|
||||
service = moduleRef.get(TourHorseRoutesService);
|
||||
});
|
||||
|
||||
describe('TourHorseRoutesService (HOR-01)', () => {
|
||||
it('HORSE-SVC-001: asks Overpass for the box grown to the grid and answers the contract', async () => {
|
||||
query.mockResolvedValue(elements);
|
||||
const answer = await service.list(box, NOW);
|
||||
expect(horseRoutesResponseSchema.parse(answer)).toEqual(answer);
|
||||
expect(answer).toMatchObject({ truncated: false, source: 'openstreetmap', attribution: HORSE_ROUTES_ATTRIBUTION });
|
||||
expect(answer.routes.map((route) => route.id)).toEqual(['relation/7']);
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
expect(query.mock.calls[0]?.[0]).toContain('(47.1,11.2,47.2,11.3)');
|
||||
expect(query.mock.calls[0]?.[1]).toBe('HorseRoutes');
|
||||
});
|
||||
|
||||
it('HORSE-SVC-002: keeps an answer for nearby views, and asks again once it is old', async () => {
|
||||
query.mockResolvedValue(elements);
|
||||
await service.list(box, NOW);
|
||||
await service.list({ south: 47.11, west: 11.22, north: 47.19, east: 11.28 }, NOW + 1000);
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
await service.list(box, NOW + HORSE_ROUTES_KEPT_MS);
|
||||
expect(query).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('HORSE-SVC-003: two requests for the same box at once share one query', async () => {
|
||||
let answer: (value: unknown[]) => void = () => undefined;
|
||||
query.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
}),
|
||||
);
|
||||
const both = Promise.all([service.list(box, NOW), service.list(box, NOW)]);
|
||||
answer(elements);
|
||||
const [first, second] = await both;
|
||||
expect(first).toEqual(second);
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('HORSE-SVC-004: no mirror answering is a 502 the client can show, and the next request asks again', async () => {
|
||||
query.mockRejectedValueOnce(new Error('all mirrors down'));
|
||||
const failure = await service.list(box, NOW).catch((err: unknown) => err);
|
||||
expect(failure).toBeInstanceOf(DomainError);
|
||||
expect((failure as DomainError).getStatus()).toBe(502);
|
||||
expect((failure as DomainError).getResponse()).toEqual({
|
||||
error: HORSE_ROUTES_UNAVAILABLE_MESSAGE,
|
||||
code: HORSE_ROUTES_UNAVAILABLE_CODE,
|
||||
});
|
||||
query.mockResolvedValueOnce(elements);
|
||||
expect((await service.list(box, NOW)).routes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('HORSE-SVC-005: keeps at most two hundred answers, letting the one kept longest go', async () => {
|
||||
query.mockResolvedValue([]);
|
||||
const nth = (n: number) => ({ south: 40 + n * 0.1, west: 5, north: 40.05 + n * 0.1, east: 5.05 });
|
||||
for (let n = 0; n <= 200; n += 1) await service.list(nth(n), NOW);
|
||||
expect(query).toHaveBeenCalledTimes(201);
|
||||
await service.list(nth(200), NOW);
|
||||
expect(query).toHaveBeenCalledTimes(201);
|
||||
await service.list(nth(0), NOW);
|
||||
expect(query).toHaveBeenCalledTimes(202);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user