Merge pull request 'BIT-15752: Add unit tests — 87 new tests, 95%+ coverage on writer-pipeline' (#7) from test/BIT-15752-add-unit-tests into main
Tests / writer-pipeline tests (push) Successful in 19s
Tests / bridge tests (push) Successful in 23s
Tests / frontend lib tests (push) Successful in 30s

This commit was merged in pull request #7.
This commit is contained in:
spark committed 2026-05-06 12:17:29 +01:00
commit 463184485f
13 files changed
+758 -6

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
name: Tests
on:
push:
branches: ["**"]
pull_request:
branches: [main]
jobs:
writer-pipeline:
name: writer-pipeline tests
runs-on: ubuntu-latest
defaults:
run:
working-directory: writer-pipeline
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
cache-dependency-path: writer-pipeline/package-lock.json
- run: npm ci
- name: Run tests with coverage
run: npm run test:coverage
bridge:
name: bridge tests
runs-on: ubuntu-latest
defaults:
run:
working-directory: bridge
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
cache-dependency-path: bridge/package-lock.json
- run: npm ci
- name: Run tests with coverage
run: npm run test:coverage
frontend-lib:
name: frontend lib tests
runs-on: ubuntu-latest
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- run: npm install
- name: Run lib tests with coverage
run: npm run test:coverage
+3 -1
View File
@@ -8,7 +8,9 @@
"dev": "tsx watch src/server.ts",
"build": "tsc",
"start": "node dist/server.js",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "npm run build && node --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js",
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js"
},
"dependencies": {
"@fastify/cors": "^9.0.1",
@@ -0,0 +1,77 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { aggregator_item_to_article_list_item } from './aggregator-mapper.js';
import type { AggregatorApiItem } from './aggregator-mapper.js';
function baseApiItem(overrides: Partial<AggregatorApiItem> = {}): AggregatorApiItem {
return {
id: 'abc123def456',
site: 'andebol.net',
sourceFeedId: 'feed-handball',
url: 'https://andebol.pt/article/1',
title: 'Handball match result',
summary: 'Team A beat Team B 3-1 in a thrilling match.',
publishedAt: '2026-04-29T10:00:00Z',
ingestedAt: '2026-04-29T10:05:00Z',
...overrides,
};
}
test('maps id to deterministic numeric id from hex', () => {
const item = aggregator_item_to_article_list_item(baseApiItem());
assert.ok(typeof item.id === 'number');
assert.ok(item.id >= 0);
});
test('maps slug to agg-{original-id}', () => {
const item = aggregator_item_to_article_list_item(baseApiItem({ id: 'xyz99' }));
assert.equal(item.slug, 'agg-xyz99');
});
test('preserves title', () => {
const item = aggregator_item_to_article_list_item(baseApiItem());
assert.equal(item.title, 'Handball match result');
});
test('truncates excerpt at 500 chars with ellipsis', () => {
const longSummary = 'x'.repeat(600);
const item = aggregator_item_to_article_list_item(baseApiItem({ summary: longSummary }));
assert.equal(item.excerpt.length, 500);
assert.ok(item.excerpt.endsWith('...'));
});
test('does not truncate excerpt under 500 chars', () => {
const item = aggregator_item_to_article_list_item(baseApiItem({ summary: 'Short summary.' }));
assert.equal(item.excerpt, 'Short summary.');
});
test('author.name is sourceFeedId', () => {
const item = aggregator_item_to_article_list_item(baseApiItem({ sourceFeedId: 'rss-feed-1' }));
assert.equal(item.author.name, 'rss-feed-1');
});
test('author.slug is slug-safe version of sourceFeedId', () => {
const item = aggregator_item_to_article_list_item(baseApiItem({ sourceFeedId: 'Feed Name/Special' }));
assert.match(item.author.slug, /^[a-z0-9-]+$/);
});
test('maps source_url from item url', () => {
const item = aggregator_item_to_article_list_item(baseApiItem());
assert.equal(item.source_url, 'https://andebol.pt/article/1');
});
test('sets is_featured and is_trending to false', () => {
const item = aggregator_item_to_article_list_item(baseApiItem());
assert.equal(item.is_featured, false);
assert.equal(item.is_trending, false);
});
test('category slug is aggregated', () => {
const item = aggregator_item_to_article_list_item(baseApiItem());
assert.equal(item.category.slug, 'aggregated');
});
test('reading_time is at least 1', () => {
const item = aggregator_item_to_article_list_item(baseApiItem({ summary: 'Hi.' }));
assert.ok(item.reading_time >= 1);
});
+140
View File
@@ -0,0 +1,140 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
calculate_freshness_score,
calculate_relevance_score,
rank_articles,
filter_by_score,
take_top_n,
} from './ranking.js';
import type { ArticleListItem } from '../types.js';
import type { WriterConfig } from './writer-config.js';
// ── calculate_freshness_score ──────────────────────────────────────────────
test('freshness score is 1 for a brand-new article', () => {
const now = new Date().toISOString();
assert.equal(calculate_freshness_score(now), 1.0);
});
test('freshness score is 0 for article at or beyond maxAgeHours', () => {
const old = new Date(Date.now() - 200 * 3600 * 1000).toISOString();
assert.equal(calculate_freshness_score(old, 168), 0.0);
});
test('freshness score is 1 for future date', () => {
const future = new Date(Date.now() + 3600_000).toISOString();
assert.equal(calculate_freshness_score(future), 1.0);
});
test('freshness score decays between 0 and 1 for mid-range article', () => {
const halfAge = new Date(Date.now() - 84 * 3600 * 1000).toISOString();
const score = calculate_freshness_score(halfAge, 168);
assert.ok(score > 0 && score < 1, `expected between 0 and 1, got ${score}`);
});
// ── calculate_relevance_score ──────────────────────────────────────────────
function makeConfig(topics: string[] = [], sourceUrls: string[] = []): WriterConfig {
return {
agent_id: 'ag1',
agent_name: 'Test',
role: 'writer',
domain: 'andebol.net',
topics,
sources: sourceUrls.map((url, i) => ({ id: `s${i}`, name: `Source ${i}`, url, type: 'rss', language: 'pt' })),
ranking_preferences: { freshness_weight: 0.6, relevance_weight: 0.4, min_score: 0.3 },
updated_at: new Date().toISOString(),
created_at: new Date().toISOString(),
};
}
function makeArticle(overrides: Partial<ArticleListItem> = {}): ArticleListItem {
return {
id: 1,
slug: 'test-article',
title: 'Handball match results',
excerpt: 'A handball game took place.',
featured_image: null,
featured_image_alt: '',
author: { id: 0, name: 'Source', slug: 'source', avatar: null },
category: { id: 0, slug: 'aggregated', name: 'Aggregated', description: '', count: 0 },
published_at: new Date().toISOString(),
reading_time: 2,
is_featured: false,
is_trending: false,
source_url: 'https://andebol.pt/article/1',
...overrides,
};
}
test('relevance score defaults to 0.2 with no topics/sources match', () => {
const { score } = calculate_relevance_score(makeArticle(), makeConfig(['football']));
assert.equal(score, 0.2);
});
test('relevance score increases when title matches a topic', () => {
const { score, matched_topics } = calculate_relevance_score(
makeArticle({ title: 'Handball final tonight' }),
makeConfig(['handball']),
);
assert.ok(score > 0.2);
assert.ok(matched_topics.includes('handball'));
});
test('relevance score includes source match bonus', () => {
const article = makeArticle({ source_url: 'https://andebol.pt/article/1' });
const config = makeConfig(['handball'], ['https://andebol.pt']);
const { score: baseScore } = calculate_relevance_score(makeArticle({ title: 'Handball win' }), makeConfig(['handball']));
const { score: withSource } = calculate_relevance_score(article, { ...config, topics: ['handball'] });
assert.ok(withSource >= baseScore);
});
// ── rank_articles ──────────────────────────────────────────────────────────
test('rank_articles returns sorted list by combined score (highest first)', () => {
const now = Date.now();
const articles = [
makeArticle({ id: 1, published_at: new Date(now - 24 * 3600_000).toISOString(), title: 'Old article' }),
makeArticle({ id: 2, published_at: new Date(now).toISOString(), title: 'Handball fresh news' }),
];
const config = makeConfig(['handball']);
const ranked = rank_articles(articles, config);
assert.equal(ranked.length, 2);
assert.ok(ranked[0].combined_score >= ranked[1].combined_score);
});
test('rank_articles returns empty list for no articles', () => {
const ranked = rank_articles([], makeConfig());
assert.equal(ranked.length, 0);
});
// ── filter_by_score ────────────────────────────────────────────────────────
test('filter_by_score removes articles below min_score', () => {
const articles = [makeArticle({ id: 1 }), makeArticle({ id: 2 })];
const scored = rank_articles(articles, makeConfig());
const filtered = filter_by_score(scored, 1.0); // impossibly high threshold
assert.equal(filtered.length, 0);
});
test('filter_by_score keeps articles above threshold', () => {
const articles = [makeArticle()];
const scored = rank_articles(articles, makeConfig());
const filtered = filter_by_score(scored, 0.0);
assert.equal(filtered.length, 1);
});
// ── take_top_n ─────────────────────────────────────────────────────────────
test('take_top_n returns at most n articles', () => {
const articles = Array.from({ length: 5 }, (_, i) => makeArticle({ id: i + 1 }));
const scored = rank_articles(articles, makeConfig());
assert.equal(take_top_n(scored, 3).length, 3);
});
test('take_top_n returns all when n exceeds length', () => {
const articles = [makeArticle()];
const scored = rank_articles(articles, makeConfig());
assert.equal(take_top_n(scored, 10).length, 1);
});
+68 -4
View File
@@ -1,16 +1,20 @@
{
"name": "frontend",
"version": "0.0.1",
"name": "news-platform-frontend",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frontend",
"version": "0.0.1",
"name": "news-platform-frontend",
"version": "0.1.0",
"dependencies": {
"@astrojs/node": "^10.0.3",
"astro": "^6.0.8"
},
"devDependencies": {
"@types/node": "^20.19.39",
"tsx": "^4.21.0"
},
"engines": {
"node": ">=22.12.0"
}
@@ -1578,6 +1582,16 @@
"@types/unist": "*"
}
},
"node_modules/@types/node": {
"version": "20.19.39",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.39.tgz",
"integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -2321,6 +2335,19 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/get-tsconfig": {
"version": "4.14.0",
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.0.tgz",
"integrity": "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"resolve-pkg-maps": "^1.0.0"
},
"funding": {
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/github-slugger": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/github-slugger/-/github-slugger-2.0.0.tgz",
@@ -4006,6 +4033,16 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/resolve-pkg-maps": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
"integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
"devOptional": true,
"license": "MIT",
"funding": {
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
}
},
"node_modules/retext": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/retext/-/retext-9.0.0.tgz",
@@ -4415,6 +4452,26 @@
"license": "0BSD",
"optional": true
},
"node_modules/tsx": {
"version": "4.21.0",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.27.0",
"get-tsconfig": "^4.7.5"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/ufo": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz",
@@ -4433,6 +4490,13 @@
"integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==",
"license": "MIT"
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"devOptional": true,
"license": "MIT"
},
"node_modules/unified": {
"version": "11.0.5",
"resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
+7 -1
View File
@@ -10,10 +10,16 @@
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
"astro": "astro",
"test": "node --import tsx/esm --test src/lib/*.test.ts",
"test:coverage": "node --experimental-test-coverage --import tsx/esm --test src/lib/*.test.ts"
},
"dependencies": {
"@astrojs/node": "^10.0.3",
"astro": "^6.0.8"
},
"devDependencies": {
"@types/node": "^20.19.39",
"tsx": "^4.21.0"
}
}
+74
View File
@@ -0,0 +1,74 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { formatDate, formatDateShort, relativeTime, truncate, slugToTitle } from './format.js';
// ── formatDate ─────────────────────────────────────────────────────────────
test('formatDate returns formatted long date', () => {
const result = formatDate('2026-04-29T10:00:00Z', 'en-US');
assert.ok(result.includes('2026'), `expected year 2026 in "${result}"`);
});
test('formatDate returns raw string for invalid date', () => {
assert.equal(formatDate('not-a-date'), 'not-a-date');
});
// ── formatDateShort ────────────────────────────────────────────────────────
test('formatDateShort returns short date (month + day)', () => {
const result = formatDateShort('2026-04-29T10:00:00Z', 'en-US');
assert.ok(result.length > 0);
assert.ok(!result.includes('2026'), `should not include year: "${result}"`);
});
test('formatDateShort returns raw string for invalid date', () => {
assert.equal(formatDateShort('bad'), 'bad');
});
// ── relativeTime ───────────────────────────────────────────────────────────
test('relativeTime returns relative string for recent date', () => {
const recent = new Date(Date.now() - 30_000).toISOString();
const result = relativeTime(recent, 'en-US');
assert.ok(result.length > 0);
});
test('relativeTime returns raw string for invalid date', () => {
assert.equal(relativeTime('garbage'), 'garbage');
});
test('relativeTime returns short date for old content (>1 week)', () => {
const old = new Date(Date.now() - 10 * 86400_000).toISOString();
const result = relativeTime(old, 'en-US');
assert.ok(result.length > 0);
});
// ── truncate ───────────────────────────────────────────────────────────────
test('truncate returns string unchanged when within max', () => {
assert.equal(truncate('hello', 10), 'hello');
});
test('truncate cuts and appends ellipsis when over max', () => {
const result = truncate('hello world', 5);
assert.ok(result.endsWith('…'));
assert.ok(result.length <= 6); // 5 chars + ellipsis
});
test('truncate returns string unchanged when exactly max length', () => {
assert.equal(truncate('hello', 5), 'hello');
});
// ── slugToTitle ────────────────────────────────────────────────────────────
test('slugToTitle converts hyphens to spaces and capitalizes', () => {
assert.equal(slugToTitle('handball-match-result'), 'Handball Match Result');
});
test('slugToTitle handles single word', () => {
assert.equal(slugToTitle('handball'), 'Handball');
});
test('slugToTitle handles empty string', () => {
assert.equal(slugToTitle(''), '');
});
+48
View File
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getPublicOrigin } from './public-origin.js';
function makeRequest(url: string, headers: Record<string, string> = {}): Request {
return new Request(url, { headers });
}
test('returns origin as-is when no host header', () => {
const req = makeRequest('http://localhost:4321/page');
const origin = getPublicOrigin(req);
assert.equal(origin, 'http://localhost:4321');
});
test('returns loopback origin unchanged even with host header', () => {
const req = makeRequest('http://127.0.0.1:3000/', { host: '127.0.0.1:3000' });
const origin = getPublicOrigin(req);
assert.equal(origin, 'http://127.0.0.1:3000');
});
test('returns https origin when x-forwarded-proto is https', () => {
const req = makeRequest('http://andebol.net/', {
host: 'andebol.net',
'x-forwarded-proto': 'https',
});
assert.equal(getPublicOrigin(req), 'https://andebol.net');
});
test('returns http origin when x-forwarded-proto is http', () => {
const req = makeRequest('https://andebol.net/', {
host: 'andebol.net',
'x-forwarded-proto': 'http',
});
assert.equal(getPublicOrigin(req), 'http://andebol.net');
});
test('uses request protocol when x-forwarded-proto is absent', () => {
const req = makeRequest('https://andebol.net/', { host: 'andebol.net' });
assert.equal(getPublicOrigin(req), 'https://andebol.net');
});
test('uses first value when x-forwarded-proto has multiple values', () => {
const req = makeRequest('http://andebol.net/', {
host: 'andebol.net',
'x-forwarded-proto': 'https, http',
});
assert.equal(getPublicOrigin(req), 'https://andebol.net');
});
+50
View File
@@ -0,0 +1,50 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getUiStrings } from './ui-i18n.js';
test('getUiStrings returns portuguese strings for pt locale', () => {
const s = getUiStrings('pt-PT');
assert.equal(s.nav_home, 'Início');
assert.equal(s.latest_news, 'Últimas notícias');
});
test('getUiStrings returns english strings for en locale', () => {
const s = getUiStrings('en-US');
assert.equal(s.nav_home, 'Home');
assert.equal(s.latest_news, 'Latest news');
});
test('getUiStrings falls back to english for unknown locale', () => {
const s = getUiStrings('fr-FR');
assert.equal(s.nav_home, 'Home');
});
test('getUiStrings pt pageOf returns formatted string', () => {
const s = getUiStrings('pt');
assert.equal(s.pageOf(2, 5), 'Página 2 de 5');
});
test('getUiStrings en pageOf returns formatted string', () => {
const s = getUiStrings('en');
assert.equal(s.pageOf(1, 3), 'Page 1 of 3');
});
test('getUiStrings pt search_results_count singular', () => {
const s = getUiStrings('pt');
assert.equal(s.search_results_count(1), '1 resultado');
});
test('getUiStrings pt search_results_count plural', () => {
const s = getUiStrings('pt');
assert.equal(s.search_results_count(5), '5 resultados');
});
test('getUiStrings en search_results_count', () => {
const s = getUiStrings('en');
assert.equal(s.search_results_count(3), '3 results');
});
test('getUiStrings category_meta_latest interpolates name', () => {
const s = getUiStrings('en');
assert.equal(s.category_meta_latest('Handball'), 'Latest Handball news');
});
+1
View File
@@ -8,6 +8,7 @@
"build": "tsc",
"typecheck": "tsc --noEmit",
"test": "npm run build && node --test dist/*.test.js",
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/*.test.js",
"aggregator": "node dist/aggregator-server.js",
"aggregator:dev": "tsx src/aggregator-server.ts",
"cycle": "node dist/run-cycle.js",
+43
View File
@@ -0,0 +1,43 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { readSourcesConfig } from './config-load.js';
async function writeTmp(name: string, content: string): Promise<string> {
const dir = join(tmpdir(), `bit-15752-${process.pid}`);
await mkdir(dir, { recursive: true });
const p = join(dir, name);
await writeFile(p, content, 'utf8');
return p;
}
test('readSourcesConfig loads valid config with sources', async () => {
const cfg = { site: 'andebol.net', sources: [{ id: 's1', url: 'https://ex.com' }] };
const p = await writeTmp('valid-sources.json', JSON.stringify(cfg));
const result = await readSourcesConfig(p);
assert.equal(result.site, 'andebol.net');
});
test('readSourcesConfig loads valid config with feeds', async () => {
const cfg = { site: 'andebol.net', feeds: ['https://ex.com/rss'] };
const p = await writeTmp('valid-feeds.json', JSON.stringify(cfg));
const result = await readSourcesConfig(p);
assert.equal(result.site, 'andebol.net');
});
test('readSourcesConfig throws when site is missing', async () => {
const p = await writeTmp('no-site.json', JSON.stringify({ sources: [{ id: 's1', url: 'x' }] }));
await assert.rejects(() => readSourcesConfig(p), /missing site/);
});
test('readSourcesConfig throws when sources and feeds are both empty', async () => {
const cfg = { site: 'andebol.net', sources: [] };
const p = await writeTmp('empty-sources.json', JSON.stringify(cfg));
await assert.rejects(() => readSourcesConfig(p), /need non-empty sources or feeds/);
});
test('readSourcesConfig throws for missing file', async () => {
await assert.rejects(() => readSourcesConfig('/does/not/exist.json'));
});
+154
View File
@@ -0,0 +1,154 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { canonicalUrl, itemId, upsertItem, shortlist } from './store.js';
import type { StoreFile, AggregatedItem } from './types.js';
// ── canonicalUrl ───────────────────────────────────────────────────────────
test('canonicalUrl strips utm_ params', () => {
const r = canonicalUrl('https://ex.com/a?utm_source=newsletter&utm_medium=email');
assert.equal(r, 'https://ex.com/a');
});
test('canonicalUrl strips tracking params (fbclid, gclid)', () => {
const r = canonicalUrl('https://ex.com/p?fbclid=abc&gclid=xyz&ref=ok');
assert.equal(r, 'https://ex.com/p?ref=ok');
});
test('canonicalUrl strips hash', () => {
const r = canonicalUrl('https://ex.com/p#section');
assert.equal(r, 'https://ex.com/p');
});
test('canonicalUrl preserves non-tracking params', () => {
const r = canonicalUrl('https://ex.com/a?page=2&sort=desc');
assert.equal(r, 'https://ex.com/a?page=2&sort=desc');
});
test('canonicalUrl returns trimmed raw string for invalid url', () => {
const r = canonicalUrl(' not a url ');
assert.equal(r, 'not a url');
});
// ── itemId ─────────────────────────────────────────────────────────────────
test('itemId returns 20-char hex string', () => {
const id = itemId('https://ex.com/a');
assert.match(id, /^[0-9a-f]{20}$/);
});
test('itemId is deterministic', () => {
assert.equal(itemId('https://ex.com/x'), itemId('https://ex.com/x'));
});
test('itemId differs for different urls', () => {
assert.notEqual(itemId('https://ex.com/a'), itemId('https://ex.com/b'));
});
// ── upsertItem ─────────────────────────────────────────────────────────────
function baseItem(overrides: Partial<AggregatedItem> = {}): AggregatedItem {
return {
id: 'abc123',
site: 'andebol.net',
sourceFeedId: 'feed1',
sourceKind: 'rss',
url: 'https://ex.com/a',
title: 'Test item',
summary: 'Summary.',
publishedAt: new Date().toISOString(),
ingestedAt: new Date().toISOString(),
...overrides,
};
}
function emptyStore(): StoreFile {
return { version: 1, items: [] };
}
test('upsertItem inserts new item and marks isNew=true', () => {
const store = emptyStore();
const { store: next, isNew } = upsertItem(store, baseItem());
assert.equal(isNew, true);
assert.equal(next.items.length, 1);
});
test('upsertItem updates existing item and marks isNew=false', () => {
const store = emptyStore();
const item = baseItem();
const { store: s1 } = upsertItem(store, item);
const updated = { ...item, title: 'Updated title' };
const { store: s2, isNew } = upsertItem(s1, updated);
assert.equal(isNew, false);
assert.equal(s2.items.length, 1);
assert.equal(s2.items[0].title, 'Updated title');
});
test('upsertItem preserves wpDraftId and skippedReason on update', () => {
const store = emptyStore();
const item = baseItem();
const { store: s1 } = upsertItem(store, item);
s1.items[0].wpDraftId = 42;
s1.items[0].skippedReason = 'dup';
const { store: s2 } = upsertItem(s1, { ...item, title: 'New title' });
assert.equal(s2.items[0].wpDraftId, 42);
assert.equal(s2.items[0].skippedReason, 'dup');
});
// ── shortlist ──────────────────────────────────────────────────────────────
test('shortlist returns newest first, limited to n', () => {
const now = Date.now();
const store: StoreFile = {
version: 1,
items: [
baseItem({ id: 'old', publishedAt: new Date(now - 3600_000).toISOString() }),
baseItem({ id: 'new', publishedAt: new Date(now).toISOString() }),
baseItem({ id: 'mid', publishedAt: new Date(now - 1800_000).toISOString() }),
],
};
const result = shortlist(store, 'andebol.net', 2);
assert.equal(result.length, 2);
assert.equal(result[0].id, 'new');
assert.equal(result[1].id, 'mid');
});
test('shortlist excludes items with wpDraftId or skippedReason', () => {
const store: StoreFile = {
version: 1,
items: [
baseItem({ id: 'ok' }),
baseItem({ id: 'draft', wpDraftId: 7 }),
baseItem({ id: 'skip', skippedReason: 'dup' }),
],
};
const result = shortlist(store, 'andebol.net', 10);
assert.equal(result.length, 1);
assert.equal(result[0].id, 'ok');
});
test('shortlist filters by topic when provided', () => {
const store: StoreFile = {
version: 1,
items: [
baseItem({ id: 'with-topic', topics: ['handball'] }),
baseItem({ id: 'no-topic', topics: [] }),
],
};
const result = shortlist(store, 'andebol.net', 10, 'handball');
assert.equal(result.length, 1);
assert.equal(result[0].id, 'with-topic');
});
test('shortlist excludes items from other sites', () => {
const store: StoreFile = {
version: 1,
items: [
baseItem({ id: 'mine', site: 'andebol.net' }),
baseItem({ id: 'other', site: 'other.com' }),
],
};
const result = shortlist(store, 'andebol.net', 10);
assert.equal(result.length, 1);
assert.equal(result[0].id, 'mine');
});
+34
View File
@@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { estimateTokens, estimatedInputCostUsd, aggregatorReadContext, REF_INPUT_USD_PER_1M } from './token-metrics.js';
test('estimateTokens returns 0 for empty string', () => {
assert.equal(estimateTokens(''), 0);
});
test('estimateTokens returns ceil(length/4)', () => {
assert.equal(estimateTokens('abcd'), 1);
assert.equal(estimateTokens('abcde'), 2);
assert.equal(estimateTokens('a'.repeat(100)), 25);
});
test('estimatedInputCostUsd returns 0 for 0 tokens', () => {
assert.equal(estimatedInputCostUsd(0), 0);
});
test('estimatedInputCostUsd applies REF_INPUT_USD_PER_1M rate', () => {
const expected = (1_000_000 / 1_000_000) * REF_INPUT_USD_PER_1M;
assert.equal(estimatedInputCostUsd(1_000_000), expected);
});
test('aggregatorReadContext includes title, summary, and url', () => {
const ctx = aggregatorReadContext({ title: 'Match report', summary: 'Team won 3-1.', url: 'https://ex.com/a' });
assert.ok(ctx.includes('Match report'));
assert.ok(ctx.includes('Team won 3-1.'));
assert.ok(ctx.includes('https://ex.com/a'));
});
test('aggregatorReadContext includes aggregator-first policy instruction', () => {
const ctx = aggregatorReadContext({ title: 'T', summary: 'S', url: 'https://ex.com' });
assert.ok(ctx.includes('structured source material'));
});