dnd-character-deploy/tests/companions.test.ts

36 lines
2.4 KiB
TypeScript

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {newDb} from 'pg-mem';
import {Storage} from '../server/storage.mjs';
import {newCharacter,characterSchema,createCompanion,addCompanion,stableCompanion,retrieveCompanion,changeCompanionHP} from '../src/model.ts';
test('horse stats, stabling and retrieval preserve the last recorded stable',()=>{
const c=newCharacter(),entry=createCompanion('horse','riding-horse');entry.name='Biscuit';
const horse=addCompanion(c,entry);
assert.equal(horse.speed,60);assert.equal(horse.carryingCapacity,480);assert.equal(horse.abilities.str,16);
stableCompanion(horse,{name:'The Copper Horseshoe',settlement:'Neverwinter',date:'2026-10-08'});
assert.equal(horse.status,'stabled');assert.equal(horse.currentLocation,'The Copper Horseshoe, Neverwinter');
retrieveCompanion(horse);assert.equal(horse.status,'travelling');assert.equal(horse.lastStabled?.name,'The Copper Horseshoe');
changeCompanionHP(horse,-99);assert.equal(horse.hp.current,0);changeCompanionHP(horse,99);assert.equal(horse.hp.current,horse.hp.max);
assert.deepEqual(characterSchema.parse(c).companions,[horse]);
});
test('pets, mounts and legacy characters validate without losing old saves',()=>{
const c=newCharacter();delete c.companions;
assert.equal(characterSchema.parse(c).companions,undefined);
const mastiff=createCompanion('pet','mastiff');mastiff.name='Ruff';addCompanion(c,mastiff);
assert.throws(()=>addCompanion(c,mastiff));assert.throws(()=>stableCompanion(mastiff,{name:'',settlement:'',date:'2026-10-08'}));
assert.equal(characterSchema.safeParse({...c,companions:[mastiff,mastiff]}).success,false);
assert.equal(characterSchema.safeParse({...c,companions:[{...mastiff,hp:{current:10,max:5}}]}).success,false);
});
test('old clients cannot clear companions by omitting the field; an explicit empty list removes them',async()=>{
const pg=newDb().adapters.createPg(),storage=new Storage(new pg.Pool());await storage.init();
const c=newCharacter(),pony=createCompanion('mount','pony');pony.name='Apple';addCompanion(c,pony);
await storage.put('alice',c.id,c,0);
const old={...c,name:'Old client'};delete old.companions;
await storage.put('alice',c.id,old,1);
assert.equal((await storage.get('alice',c.id)).character.companions[0].name,'Apple');
await storage.put('alice',c.id,{...old,companions:[]},2);
assert.deepEqual((await storage.get('alice',c.id)).character.companions,[]);
});