Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions apps/web/src/app/api/backtest/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,14 @@ function makeReq(body: unknown) {
});
}

function makeRawReq(body: string) {
return new Request('http://test.local/api/backtest', {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: 'Bearer fake-token' },
body,
});
}

describe('POST /api/backtest', () => {
beforeEach(() => {
vi.clearAllMocks();
Expand Down Expand Up @@ -166,6 +174,22 @@ describe('POST /api/backtest', () => {
expect(body.error).toMatch(/invalid exchange/);
});

it('rejects a null JSON body with 400', async () => {
const { POST } = await importRoute();
const res = await POST(makeReq(null) as any);
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'invalid JSON body' });
expect(fetchHistoricalCandlesMock).not.toHaveBeenCalled();
});

it('rejects malformed JSON with 400', async () => {
const { POST } = await importRoute();
const res = await POST(makeRawReq('{') as any);
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'invalid JSON body' });
expect(getActivePairsMock).not.toHaveBeenCalled();
});

it('returns 400 when no pairs are available and none requested', async () => {
getActivePairsMock.mockResolvedValueOnce([]);
const { POST } = await importRoute();
Expand Down
6 changes: 5 additions & 1 deletion apps/web/src/app/api/backtest/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ export async function POST(req: NextRequest) {
const auth = await authenticate(req);
if (!auth) return unauthorized();

const body = (await req.json().catch(() => ({}))) as BacktestRequest;
const rawBody = await req.json().catch(() => null) as unknown;
if (!rawBody || typeof rawBody !== 'object' || Array.isArray(rawBody)) {
return Response.json({ error: 'invalid JSON body' }, { status: 400 });
}
const body = rawBody as BacktestRequest;
const timeframe = (body.timeframe ?? '5m') as AnalysisTimeframe;
if (!TIMEFRAMES.includes(timeframe)) {
return Response.json({ error: `invalid timeframe "${timeframe}"`, validTimeframes: TIMEFRAMES }, { status: 400 });
Expand Down
Loading