require("dotenv").config(); const assert = require("node:assert/strict"); const http = require("node:http"); const https = require("node:https"); const mariadb = require("mariadb"); function unique(values) { return [...new Set(values.filter(Boolean))]; } function getJson(targetUrl) { const url = new URL(targetUrl); const transport = url.protocol === "https:" ? https : http; return new Promise((resolve, reject) => { const request = transport.get(url, (response) => { let body = ""; response.on("data", (chunk) => { body += chunk; }); response.on("end", () => { try { resolve({ body: JSON.parse(body), statusCode: response.statusCode }); } catch (error) { reject(error); } }); }); request.on("error", reject); }); } async function testApp() { const appPort = Number(process.env.APP_PORT || 3000); const candidates = unique([ process.env.APP_URL, `http://localhost:${appPort}`, `http://app:${appPort}` ]); let lastError; for (const baseUrl of candidates) { try { const response = await getJson(`${baseUrl}/health`); assert.equal(response.statusCode, 200, `Unexpected status from ${baseUrl}`); assert.equal(response.body.status, "ok", "Application health endpoint is not healthy"); assert.equal(response.body.database, "reachable", "Application cannot reach MariaDB"); return { baseUrl, payload: response.body }; } catch (error) { lastError = error; } } throw lastError; } async function testDatabase() { const candidates = unique([ process.env.DB_HOST, "127.0.0.1", "localhost", "db" ]); let lastError; for (const host of candidates) { const pool = mariadb.createPool({ host, port: Number(process.env.DB_PORT || 3306), user: process.env.DB_USER || "app_user", password: process.env.DB_PASSWORD || "app_password", database: process.env.DB_NAME || "app_db", connectionLimit: 1 }); try { const connection = await pool.getConnection(); const rows = await connection.query( "SELECT name FROM environment_checks ORDER BY id" ); connection.release(); await pool.end(); assert.ok(rows.length >= 1, "Seed table is empty"); return { host, rows }; } catch (error) { lastError = error; await pool.end(); } } throw lastError; } async function main() { const appResult = await testApp(); const databaseResult = await testDatabase(); console.log("Environment test passed"); console.log(`App endpoint: ${appResult.baseUrl}`); console.log(`Database host: ${databaseResult.host}`); console.log(`Seed rows: ${databaseResult.rows.length}`); } main().catch((error) => { console.error("Environment test failed"); console.error(error.message); process.exit(1); });