import * as plugins from './plugins.js'; import { expect, tap } from '@git.zone/tstest/tapbundle'; import * as smartmetrics from '../ts/index.js'; let testSmartMetrics: smartmetrics.SmartMetrics; tap.test('should create a smartmetrics instance', async () => { const logger = new plugins.smartlog.Smartlog({ logContext: null, minimumLogLevel: 'silly', }); logger.enableConsole(); testSmartMetrics = new smartmetrics.SmartMetrics(logger, 'testContainer'); expect(testSmartMetrics).toBeInstanceOf(smartmetrics.SmartMetrics); }); tap.test('should start smartmetrics', async () => { testSmartMetrics.start(); }); tap.test('should produce valid metrics', async (tools) => { console.log('calling .getMetrics from Testfile:'); console.log(await testSmartMetrics.getMetrics()); }); tap.test('should return Prometheus formatted metrics', async () => { const prometheusMetrics = await testSmartMetrics.getPrometheusFormattedMetrics(); expect(prometheusMetrics).toBeTypeofString(); expect(prometheusMetrics).toContain('smartmetrics_cpu_percentage'); expect(prometheusMetrics).toContain('smartmetrics_memory_percentage'); expect(prometheusMetrics).toContain('smartmetrics_memory_usage_bytes'); expect(prometheusMetrics).toContain('# HELP'); expect(prometheusMetrics).toContain('# TYPE'); }); tap.test('should enable Prometheus endpoint', async (tools) => { const testPort = 19090; testSmartMetrics.enablePrometheusEndpoint(testPort); // Give the server time to start await tools.delayFor(1000); // Test the endpoint const response = await fetch(`http://localhost:${testPort}/metrics`); expect(response.status).toEqual(200); expect(response.headers.get('content-type')).toEqual('text/plain; version=0.0.4'); const metricsText = await response.text(); expect(metricsText).toContain('smartmetrics_cpu_percentage'); expect(metricsText).toContain('smartmetrics_memory_percentage'); expect(metricsText).toContain('smartmetrics_memory_usage_bytes'); }); tap.test('should handle 404 for non-metrics endpoints', async () => { const response = await fetch('http://localhost:19090/notfound'); expect(response.status).toEqual(404); const text = await response.text(); expect(text).toEqual('Not Found'); }); tap.test('should disable Prometheus endpoint', async () => { testSmartMetrics.disablePrometheusEndpoint(); // Give the server time to shut down await new Promise(resolve => setTimeout(resolve, 1000)); // Verify the endpoint is no longer accessible try { await fetch('http://localhost:19090/metrics'); throw new Error('Should have failed to connect'); } catch (error) { // Expected to fail expect(error.message).toContain('fetch failed'); } }); tap.start();