treker-po-trenirovkam-i-pit.../tests/profile.test.mjs
Peppa 8abdffba01
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 1с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 7s
deploy / deploy (pull_request) Successful in 26s
TPTIP-4: приватный профиль и расчёт питания по введённым данным
2026-11-17 12:23:14 +05:00

70 lines
4.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {mkdtemp,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {createApp} from '../profile-server.mjs';
import {validateProfile,ProfileService,nutrition} from '../profile/service.mjs';
const profile = {height:182,weight:81,age:32,sex:'male',activity:1.375};
const account = {username:'anna',password:'a-long-private-password',...profile};
test('Пустое или неверное измерение; границы диапазонов',() => {
for (const [key,values] of Object.entries({height:['',null,'abc','1e2',[],true,99,251],weight:['',null,'abc',0,351],age:[17,101,20.5],sex:['','unknown'],activity:['',99]})) {
for (const value of values) assert.throws(()=>validateProfile({...profile,[key]:value}));
}
for (const p of [{height:100,weight:25,age:18},{height:250,weight:350,age:100}]) assert.doesNotThrow(()=>validateProfile({...profile,...p}));
assert.equal(validateProfile({...profile,weight:'81,5'}).weight,81.5);
assert.equal(nutrition(profile).calories,2465);
assert.equal(nutrition(profile).protein,130);
});
test('Регистрация с измерениями; два пользователя; пересчёт; ошибка редактирования; доступ без входа',async t => {
const server = createApp({database:':memory:'});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(()=>new Promise(r=>server.close(r)));
const origin = `http://127.0.0.1:${server.address().port}`;
const call = async(path,method='GET',body,cookie,headers={}) => {
const response = await fetch(origin+path,{method,headers:{origin,'Content-Type':'application/json',...(cookie?{cookie}:{}),...headers},body:body===undefined?undefined:JSON.stringify(body)});
return {status:response.status,body:await response.json(),cookie:response.headers.get('set-cookie'),headers:response.headers};
};
assert.equal((await call('/api/profile')).status,401);
assert.equal((await call('/api/register','POST',{...account,height:''})).status,400);
const anna = await call('/api/register','POST',account);
assert.equal(anna.status,200);assert.equal(anna.body.profile.height,182);
assert.match(anna.cookie,/HttpOnly/);assert.match(anna.cookie,/SameSite=Strict/);
assert.equal(anna.headers.get('cache-control'),'no-store');
assert.equal(JSON.stringify(anna.body).includes('password'),false);
const boris = await call('/api/register','POST',{...account,username:'boris',weight:92});
const own = await call('/api/profile?username=anna','GET',undefined,boris.cookie);
assert.equal(own.body.profile.weight,92);
const updated = await call('/api/profile','PUT',{...profile,weight:84,user_id:2},anna.cookie);
assert.equal(updated.body.profile.weight,84);
assert.notEqual(updated.body.nutrition.calories,anna.body.nutrition.calories);
assert.notEqual(updated.body.nutrition.protein,anna.body.nutrition.protein);
assert.notEqual(updated.body.nutrition.menu[0].grams,anna.body.nutrition.menu[0].grams);
assert.equal((await call('/api/profile','GET',undefined,anna.cookie)).body.profile.weight,84);
assert.equal((await call('/api/profile','PUT',{...profile,weight:0},anna.cookie)).status,400);
assert.equal((await call('/api/profile','GET',undefined,anna.cookie)).body.profile.weight,84);
assert.equal((await call('/api/profile','PUT',profile,anna.cookie,{origin:'https://attacker.example'})).status,403);
assert.equal((await call('/api/profile','PUT',profile,anna.cookie,{origin:''})).status,403);
assert.equal((await call('/api/login','POST',{...account,password:'wrong-password-long'})).status,401);
assert.equal((await call('/api/login','POST',{...account,weight:''})).status,400);
const login = await call('/api/login','POST',{...account,weight:86});
assert.equal(login.body.profile.weight,86);
assert.equal((await call('/api/logout','POST',{},login.cookie)).status,200);
assert.equal((await call('/api/profile','GET',undefined,login.cookie)).status,401);
for (let n=0;n<21;n++) await call('/api/login','POST',account);
assert.equal((await call('/api/login','POST',account)).status,429);
assert.equal((await fetch(origin+'/.peppa/project.json')).status,404);
assert.equal((await fetch(origin+'/healthz')).status,200);
});
test('Сохранение после перезапуска и истечение срока входа',async t=>{
const dir = await mkdtemp(join(tmpdir(),'tptip-test-'));
t.after(()=>rm(dir,{recursive:true,force:true}));
let now = Date.now();
let service = new ProfileService(join(dir,'profile.sqlite'),{now:()=>now});
const token = await service.authenticate(account,true);
service.close();service = new ProfileService(join(dir,'profile.sqlite'),{now:()=>now});
assert.equal(service.read(token).profile.weight,81);
now += 8*86400000;
assert.throws(()=>service.read(token));service.close();
});