Trim register tests and redundant input checks #85

Merged
eleith merged 2 commits from refactor/register-test-and-input-cleanup into main 2026-12-04 22:43:40 +00:00
3 changed files with 111 additions and 130 deletions

No files matched your search

@@ -9,7 +9,6 @@ import {
type AccountActivityPage
} from '@hledger-reports/snapshots';
import type { ApplicationContext } from '#lib/server/application.js';
import { projectActivityPage } from '#lib/server/registers/cash/projection.js';
import { savedReportFixture } from '#lib/server/reports.fixture.js';
import { load } from './+page.server.js';
@@ -19,14 +18,11 @@ vi.mock('@hledger-reports/snapshots', () => ({
readFocusedAccountPage: vi.fn(),
readAccountTransaction: vi.fn()
}));
vi.mock('#lib/server/registers/cash/projection.js', () => ({
projectActivityPage: vi.fn()
}));
vi.mock('@hledger-reports/hledger', () => {
throw new Error('Browsing must not load the native runtime.');
});
const id = 'abcd1234';
const name = 'custom:銀行';
const name = 'assets:cash';
const publication = savedReportFixture({
journal: testConfig.journal,
accounts: [{ id, name, access: 'ready', rowCount: 51, summary: { status: 'undated' } }]
@@ -41,10 +37,6 @@ const accountPage: AccountActivityPage = {
unclassifiedEndingCash: []
}
};
const projection: ReturnType<typeof projectActivityPage> = {
rows: [],
endingBalance: [{ commodity: 'USD', quantity: '1.0001' }]
};
function event(query = '', accounts: AccountConfig[] = [{ account: name, register: 'cash' }]) {
const application: ApplicationContext = {
config: { ...testConfig, accounts },
@@ -76,22 +68,11 @@ beforeEach(() => {
vi.resetAllMocks();
vi.mocked(readReportPublication).mockResolvedValue(publication);
vi.mocked(readAccountPage).mockResolvedValue(accountPage);
vi.mocked(projectActivityPage).mockReturnValue(projection);
});
it('loads a member from one pinned publication and delegates its requested page', async () => {
vi.mocked(readAccountPage).mockImplementation(async (pinned) => {
expect(pinned).toBe(publication);
vi.mocked(readReportPublication).mockResolvedValue(
savedReportFixture({
...publication,
overview: { preparedAt: '2026-05-02T12:00:00Z' }
})
);
return accountPage;
});
it('loads the requested Cash page from the selected publication', async () => {
const request = event('order=desc&page=2');
const result = await load(request);
expect(result).toEqual({
expect(result).toMatchObject({
readFailed: false,
accountId: id,
accountName: name,
@@ -101,15 +82,15 @@ it('loads a member from one pinned publication and delegates its requested page'
pageCount: 2,
page: 2,
order: 'desc',
...projection
rows: [{ transactionIndex: 1 }],
endingBalance: [{ commodity: 'USD', quantity: '1.0001' }]
});
expect(JSON.stringify(result)).not.toContain('PRIVATE');
expect(readReportPublication).toHaveBeenCalledOnce();
expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'desc',
offset: 50
});
expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(accountPage);
expect(request.parent).toHaveBeenCalledOnce();
expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' });
});
it('marks only the target on the saved Cash page in the requested order', async () => {
@@ -120,10 +101,6 @@ it('marks only the target on the saved Cash page in the requested order', async
indexOnPage: 1
};
const [other, target] = focusedPage.rows.map((row) => row.transaction.index);
const actual = await vi.importActual<typeof import('#lib/server/registers/cash/projection.js')>(
'#lib/server/registers/cash/projection.js'
);
vi.mocked(projectActivityPage).mockImplementationOnce(actual.projectActivityPage);
vi.mocked(readFocusedAccountPage).mockResolvedValue(focusedPage);
const result = await load(event(`focus=${target}&order=asc`));
expect(result).toMatchObject({ page: 1, order: 'asc', readFailed: false });
@@ -143,7 +120,7 @@ it('returns the ordinary Cash page in the requested order when the target is abs
page: 2,
order: 'asc',
missingFocusTransactionIndex: 99,
...projection
rows: [{ transactionIndex: 1 }]
});
});
@@ -170,17 +147,12 @@ it('requires an application without reading reports or parent data', async () =>
expect(readReportPublication).not.toHaveBeenCalled();
expect(readAccountPage).not.toHaveBeenCalled();
});
it.each(['missing', 'unreadable', 'journal-changed'] as const)(
'requires a usable publication (%s) before reading activity',
async (status) => {
const request = event();
request.locals.savedReports = Promise.resolve({ status });
await expect(load(request)).rejects.toMatchObject({ status: 503 });
expect(readReportPublication).not.toHaveBeenCalled();
expect(readAccountPage).not.toHaveBeenCalled();
expect(projectActivityPage).not.toHaveBeenCalled();
}
);
it('requires a usable publication before reading activity', async () => {
const request = event();
request.locals.savedReports = Promise.resolve({ status: 'unreadable' });
await expect(load(request)).rejects.toMatchObject({ status: 503 });
expect(readAccountPage).not.toHaveBeenCalled();
});
it('returns a safe read failure when the fallback page cannot be read after a focus miss', async () => {
vi.mocked(readFocusedAccountPage).mockResolvedValue(null);
vi.mocked(readAccountPage).mockRejectedValue(
@@ -206,7 +178,6 @@ it('returns a safe read failure when the fallback page cannot be read after a fo
order: 'desc',
offset: 0
});
expect(projectActivityPage).not.toHaveBeenCalled();
expect(queue).not.toHaveBeenCalled();
});
it('opens the newest recorded activity on the first descending page by default', async () => {
@@ -217,7 +188,6 @@ it('opens the newest recorded activity on the first descending page by default',
order: 'desc',
offset: 0
});
expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(firstPage);
});
it('opens the last page when ascending order is requested', async () => {
await load(event('order=asc'));
@@ -225,7 +195,6 @@ it('opens the last page when ascending order is requested', async () => {
order: 'asc',
offset: 50
});
expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(accountPage);
});
it('rejects a disabled register before IO', async () => {
await expect(load(event('', []))).rejects.toMatchObject({ status: 404 });
@@ -246,7 +215,6 @@ it('does not read or project activity for an ambiguous account', async () => {
});
expect(readAccountPage).not.toHaveBeenCalled();
expect(readFocusedAccountPage).not.toHaveBeenCalled();
expect(projectActivityPage).not.toHaveBeenCalled();
});
it('reports unreadable activity even if the catalog says the account is empty', async () => {
@@ -1,5 +1,8 @@
import type { AccountConfig } from '@hledger-reports/config';
import { preparedAccountRows } from '../../../../../../../../packages/db/src/reports/data.fixture.js';
import {
amount,
preparedAccountRows
} from '../../../../../../../../packages/db/src/reports/data.fixture.js';
import { testConfig } from '#lib/server/application.fixture.js';
import { beforeEach, expect, it, vi } from 'vitest';
import {
@@ -9,9 +12,7 @@ import {
readFocusedInvestmentActivityPage,
type AccountInvestmentActivityPage
} from '@hledger-reports/snapshots';
import { investmentRegisterFixture } from '#lib/registers/investment/investment-register.fixture.js';
import type { ApplicationContext } from '#lib/server/application.js';
import { projectInvestmentActivityPage } from '#lib/server/registers/investment/projection.js';
import { savedReportFixture } from '#lib/server/reports.fixture.js';
import { load } from './+page.server.js';
@@ -21,27 +22,40 @@ vi.mock('@hledger-reports/snapshots', () => ({
readInvestmentActivityPage: vi.fn(),
readFocusedInvestmentActivityPage: vi.fn()
}));
vi.mock('#lib/server/registers/investment/projection.js', () => ({
projectInvestmentActivityPage: vi.fn()
}));
vi.mock('@hledger-reports/hledger', () => {
throw new Error('Browsing must not load the native runtime.');
});
const id = 'abcd1234';
const name = 'custom:銀行';
const name = 'assets:cash';
const publication = savedReportFixture({
journal: testConfig.journal,
accounts: [{ id, name, access: 'ready', rowCount: 1, summary: { status: 'undated' } }]
accounts: [{ id, name, access: 'ready', rowCount: 50, summary: { status: 'undated' } }]
});
const [neighbor, focusedEntry] = preparedAccountRows(2, 'Saved activity', 6);
const [cashPosting, ...counterpartPostings] = focusedEntry.transaction.postings;
const [firstCashPosting, siblingCashPosting] = ['-60.00', '-40.00'].map((quantity) => ({
...cashPosting,
amounts: [amount(quantity)],
transactedAmounts: [{ commodity: '$', quantity }]
}));
const focusedPostings = [firstCashPosting, ...counterpartPostings, siblingCashPosting];
const siblingPostingIndex = focusedPostings.indexOf(siblingCashPosting);
focusedEntry.transaction.postings = focusedPostings;
focusedEntry.accountPostingIndexes = [0, siblingPostingIndex];
focusedEntry.investment.cashPostingIndexes = [0, siblingPostingIndex];
const focusedTransactionIndex = focusedEntry.transaction.index;
const activityPage: AccountInvestmentActivityPage = {
activityCount: 51,
rows: preparedAccountRows().map((row) => ({
row,
postingIndex: 0,
displayDate: row.transaction.postings[0].date ?? row.transaction.date,
entryActivityPosition: 1,
entryActivityCount: 1
})),
activityCount: 53,
rows: [neighbor, focusedEntry].flatMap((row) =>
row.accountPostingIndexes.map((postingIndex, position, postingIndexes) => ({
row,
postingIndex,
displayDate: row.transaction.postings[postingIndex].date ?? row.transaction.date,
entryActivityPosition: position + 1,
entryActivityCount: postingIndexes.length
}))
),
summary: {
hasMultipleAmounts: false,
hasMultipleCommodities: false,
@@ -50,11 +64,6 @@ const activityPage: AccountInvestmentActivityPage = {
unclassifiedEndingCash: []
}
};
const projection: ReturnType<typeof projectInvestmentActivityPage> = {
activities: [],
endingCash: [{ commodity: 'USD', quantity: '1.0001' }],
unclassifiedEndingCash: []
};
function event(
query = '',
accounts: AccountConfig[] = [{ account: name, register: 'investment' }],
@@ -89,20 +98,14 @@ function event(
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(readReportPublication).mockResolvedValue(publication);
vi.mocked(readInvestmentActivityCount).mockResolvedValue(51);
vi.mocked(readInvestmentActivityCount).mockResolvedValue(activityPage.activityCount);
vi.mocked(readInvestmentActivityPage).mockResolvedValue(activityPage);
vi.mocked(projectInvestmentActivityPage).mockReturnValue(projection);
});
it('pages by the saved posting count in one publication, not the enclosing entry count', async () => {
vi.mocked(readInvestmentActivityCount).mockImplementation(async (pinned) => {
expect(pinned).toBe(publication);
vi.mocked(readReportPublication).mockResolvedValue(null);
return 51;
});
it('pages by the saved posting count, not the enclosing entry count', async () => {
const request = event('order=desc&page=2');
const result = await load(request);
expect(result).toEqual({
expect(result).toMatchObject({
readFailed: false,
accountName: name,
access: 'ready',
@@ -110,47 +113,54 @@ it('pages by the saved posting count in one publication, not the enclosing entry
register: {
accountId: id,
accountName: name,
activityCount: 51,
activityCount: 53,
pageCount: 2,
page: 2,
order: 'desc',
...projection
endingCash: [{ commodity: 'USD', quantity: '1.0001' }]
}
});
expect(JSON.stringify(result)).not.toContain('PRIVATE');
expect(readReportPublication).toHaveBeenCalledOnce();
expect(readInvestmentActivityCount).toHaveBeenCalledExactlyOnceWith(publication, id);
expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'desc',
offset: 50
});
expect(projectInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(activityPage, name);
expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' });
});
it('marks only the located posting on the saved containing page', async () => {
const [firstBuy, secondBuy, otherActivity] = investmentRegisterFixture().activities;
const focusedPage = { ...activityPage, activityCount: 53, pageNumber: 2, indexOnPage: 1 };
vi.mocked(readFocusedInvestmentActivityPage).mockResolvedValue(focusedPage);
vi.mocked(projectInvestmentActivityPage).mockReturnValue({
...projection,
activities: [otherActivity, firstBuy, secondBuy]
vi.mocked(readFocusedInvestmentActivityPage).mockResolvedValue({
...activityPage,
pageNumber: 2,
indexOnPage: 1
});
const result = await load(event('order=desc&focus=1'));
const result = await load(event(`order=desc&focus=${focusedTransactionIndex}`));
expect(readFocusedInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(
publication,
id,
1,
focusedTransactionIndex,
'desc'
);
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
expect(result.register).toMatchObject({
page: 2,
pageCount: 2,
activityCount: 53,
order: 'desc'
});
expect(result.register?.activities.filter((activity) => activity.isFocusTarget)).toEqual([
{ ...firstBuy, isFocusTarget: true }
expect(
result.register?.activities.map(({ transactionIndex, postingIndex, isFocusTarget }) => [
transactionIndex,
postingIndex,
isFocusTarget
])
).toEqual([
[neighbor.transaction.index, 0, undefined],
[focusedTransactionIndex, 0, true],
[focusedTransactionIndex, siblingPostingIndex, undefined]
]);
});
@@ -164,7 +174,11 @@ it('returns the ordinary Investment page and missing index when the target is ab
expect(result).toMatchObject({
readFailed: false,
missingFocusTransactionIndex: 99,
register: { page: 2, order: 'asc', ...projection }
register: {
page: 2,
order: 'asc',
activities: [{ transactionIndex: 6 }, { transactionIndex: 7 }, { transactionIndex: 7 }]
}
});
});
@@ -195,7 +209,6 @@ it.each(['count', 'fallback page', 'focus'] as const)(
});
expect(result).not.toHaveProperty('missingFocusTransactionIndex');
expect(JSON.stringify(result)).not.toContain('PRIVATE');
expect(projectInvestmentActivityPage).not.toHaveBeenCalled();
expect(queue).not.toHaveBeenCalled();
}
);
@@ -259,7 +272,6 @@ it('uses the saved posting count for a readable empty account', async () => {
});
expect(readInvestmentActivityCount).toHaveBeenCalledOnce();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
expect(projectInvestmentActivityPage).not.toHaveBeenCalled();
});
it('rejects unknown accounts before activity IO', async () => {
@@ -315,14 +327,10 @@ it('requires an application without reading reports or parent data', async () =>
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it.each(['missing', 'unreadable', 'journal-changed'] as const)(
'requires a usable publication (%s) before reading activity',
async (status) => {
const request = event();
request.locals.savedReports = Promise.resolve({ status });
await expect(load(request)).rejects.toMatchObject({ status: 503 });
expect(readReportPublication).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
}
);
it('requires a usable publication before reading activity', async () => {
const request = event();
request.locals.savedReports = Promise.resolve({ status: 'unreadable' });
await expect(load(request)).rejects.toMatchObject({ status: 503 });
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
@@ -22,6 +22,7 @@ import {
readReportPublication
} from '../index.js';
import type { ReportPublication, ReportStage } from '../index.js';
import { decodeInvestmentOverview } from './investment-overview.js';
import {
ambiguous,
accountTransactionExportsFixture,
@@ -524,35 +525,46 @@ it('stores bounded portfolio values without extra native position data', async (
expect(await readInvestmentOverview(await selected())).toEqual(unavailable);
});
it('rejects a corrupt investment payload without affecting core reports', async () => {
it('rejects malformed Investment values at decode', () => {
const investment = investmentFixture();
await publish(older, fixture(), investment);
const publication = await selected();
for (const bytes of [
'not JSON: private contents',
'null',
JSON.stringify({ ...investment, state: 'not a state' }),
JSON.stringify({ ...investment, asOf: '2025-01-01' }),
JSON.stringify({ ...investment, investmentAccountNames: [1] }),
JSON.stringify({ ...investment, securityCount: -1 }),
JSON.stringify({ ...investment, portfolioValue: { commodity: '$', quantity: 1 } }),
JSON.stringify({
for (const value of [
null,
{ ...investment, state: 'not a state' },
{ ...investment, asOf: '2025-01-01' },
{ ...investment, investmentAccountNames: [1] },
{ ...investment, securityCount: -1 },
{ ...investment, portfolioValue: { commodity: '$', quantity: 1 } },
{
...investment,
history: [...investment.history!.slice(0, -1), { date: investment.asOf, total: null }]
})
}
]) {
withReportFile((db) =>
db.prepare('UPDATE publication SET investment_overview_json = ?').run(bytes)
);
await expect(readInvestmentOverview(publication)).rejects.toSatisfy(
safeError('Unable to read investment overview')
expect(() => decodeInvestmentOverview(value, investment.asOf)).toThrow(
'Invalid saved investment overview'
);
}
expect(await selected()).toEqual(publication);
expect(await readOverview(snapshots)).toEqual(fixture());
});
it('keeps other saved reports readable until preparation replaces the old investment format', async () => {
it('rejects corrupt saved Investment JSON without affecting core reports', async () => {
await publish(older, fixture(), investmentFixture());
const publication = await selected();
withReportFile((db) =>
db
.prepare('UPDATE publication SET investment_overview_json = ?')
.run('not JSON: private contents')
);
await expect(readInvestmentOverview(publication)).rejects.toSatisfy(
safeError('Unable to read investment overview')
);
expect(await selected()).toEqual(publication);
const cashPage = await readAccountPage(publication, publication.accounts[0].id, {
order: 'desc',
offset: 0
});
expect(cashPage?.rows).toEqual(rows());
});
it('replaces an unreadable old Investment format on explicit preparation', async () => {
const investment = investmentFixture();
const { investmentAccountNames, ...otherFields } = investment;
const oldInvestment = { ...otherFields, members: investmentAccountNames };
@@ -567,13 +579,6 @@ it('keeps other saved reports readable until preparation replaces the old invest
await expect(readInvestmentOverview(publication)).rejects.toSatisfy(
safeError('Unable to read investment overview')
);
expect(publication.overview).toEqual(fixture());
const page = await readAccountPage(publication, publication.accounts[0].id, {
order: 'desc',
offset: 0
});
expect(page?.rows).toEqual(rows());
await publish(newer, fixture(), investment);
expect(await readInvestmentOverview(await selected())).toEqual(investment);
});