Files
Online-Topup-V1/application/tests/observability.test.js
T
2026-11-24 23:14:30 +07:00

106 lines
4.1 KiB
JavaScript

const express = require('express');
const request = require('supertest');
const responseTime = require('response-time');
const knex = require('../../infrastructure/database/knex');
const responseAudit = require('../helpers/response-audit');
const { correlation, response: responseTelemetry } = require('../middlewares/response-telemetry.middleware');
const histograms = Object.values(require('../helpers/prometheusmetrics'));
jest.mock('../../infrastructure/database/knex', () => jest.fn());
jest.mock('../helpers/response-audit', () => ({ record: jest.fn() }));
const app = express();
app.use(express.json(), responseTime(), correlation, responseTelemetry);
app.post('/api/topup1', (req, res) => {
req._startTime = Date.now() - req.body.duration;
res.json({ code: '00', data: { trxID: req.body.trxID } });
});
app.post('/api/topup2', (req, res) => {
req.partner_id_token = 'fixture';
res.json({ code: '5001', data: {} });
});
app.post('/api/topup3', (req, res) => {
req.partner_id_token = '9917';
res.json({ code: '00', data: {} });
});
beforeEach(() => {
jest.clearAllMocks();
for (const histogram of histograms) histogram.reset();
});
test('distinct transaction IDs and latencies share one histogram series per bucket', async () => {
const transactionIds = ['0001', '0002', '0100', '01a0'];
const responses = await Promise.all(transactionIds.map((trxID, index) =>
request(app).post('/api/topup1?fixture=1').send({ trxID, duration: 200 + index * 100 })
));
for (const histogram of histograms) {
const metric = await histogram.get();
const counts = metric.values.filter((value) => value.metricName.endsWith('_count'));
expect(counts).toEqual([{
metricName: `${metric.name}_count`,
labels: { route: '/api/topup1', status_code: '00', issuer_name: 'UNDEFINED' },
value: transactionIds.length,
}]);
expect(metric.values.some((entry) => entry.labels.le === 1000)).toBe(true);
}
const logs = responseAudit.record.mock.calls.map(([info]) => info);
const requestIds = responses.map(({ headers }) => headers['x-request-id']);
expect(new Set(requestIds).size).toBe(transactionIds.length);
responses.forEach(({ headers, body }, index) => {
const record = logs.find((entry) => entry.request_id === headers['x-request-id']);
expect(headers['x-response-time']).toMatch(/ms$/);
expect(body.data.trxID).toBe(transactionIds[index]);
expect(record).toMatchObject({
event: 'http_response',
http_status: 200,
trx_id: transactionIds[index],
});
expect(record.response_time_ms).toBeGreaterThanOrEqual(200 + index * 100);
expect(record).not.toHaveProperty('labels');
});
});
test('logs the valid request transaction ID on HSM failure even if issuer lookup fails', async () => {
knex.mockReturnValue({
where: jest.fn().mockReturnValue({
first: jest.fn().mockReturnValue({ timeout: jest.fn().mockRejectedValue(new Error('DB unavailable')) }),
}),
});
const response = await request(app).post('/api/topup2').send({ trxID: 'ABCD', card_number: 'fixture-card' });
expect(response.status).toBe(200);
const [info] = responseAudit.record.mock.calls[0];
expect(info).toMatchObject({
level: 'error',
status_code: '5001',
request_id: response.headers['x-request-id'],
trx_id: 'abcd',
issuer_name: 'UNDEFINED',
});
expect(info).not.toHaveProperty('card_number');
});
test('a slow issuer lookup is shared and audit records are emitted while it is pending', async () => {
let finishLookup;
const pending = new Promise((resolve) => { finishLookup = resolve; });
const timeout = jest.fn().mockReturnValue(pending);
knex.mockReturnValue({
where: jest.fn().mockReturnValue({ first: jest.fn().mockReturnValue({ timeout }) }),
});
try {
await Promise.all(Array.from({ length: 12 }, () => request(app).post('/api/topup3')));
expect(timeout).toHaveBeenCalledTimes(1);
expect(responseAudit.record).toHaveBeenCalledTimes(12);
expect(responseAudit.record).toHaveBeenCalledWith(expect.objectContaining({
issuer_name: 'UNDEFINED',
partner_id: '9917',
}));
} finally {
finishLookup({ c_name: 'Fixture' });
}
});