verae-uptime/test/watch.test.js

45 lines
1.4 KiB
JavaScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
test('once mode fails when a required target is down', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'uptime-'));
const srv = await new Promise((resolve) => {
const s = http.createServer((req, res) => {
res.writeHead(req.url === '/ok' ? 200 : 500);
res.end('x');
});
s.listen(0, '127.0.0.1', () => resolve(s));
});
const port = srv.address().port;
const cfg = path.join(tmp, 'probes.json');
fs.writeFileSync(
cfg,
JSON.stringify({
failAfter: 1,
timeoutMs: 2000,
stateDir: tmp,
targets: [
{ id: 'ok', url: `http://127.0.0.1:${port}/ok` },
{ id: 'bad', url: `http://127.0.0.1:${port}/bad` },
],
}),
);
const code = await new Promise((resolve) => {
const p = spawn(process.execPath, [path.join(root, 'src/watch.js'), '--once'], {
env: { ...process.env, UPTIME_PROBES: cfg, UPTIME_STATE: tmp },
});
p.on('close', resolve);
});
srv.close();
assert.equal(code, 2);
const snap = JSON.parse(fs.readFileSync(path.join(tmp, 'status.json'), 'utf8'));
assert.equal(snap.failed, 1);
});