import { expect, tap } from '@push.rocks/tapbundle'; import { SmartlogDestinationFile } from '../ts_destination_file/index.js'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; let testLogDir: string; let testLogFile: string; let testDestination: SmartlogDestinationFile; // Setup and teardown helpers const createTempLogDir = () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartlog-test-')); return tempDir; }; const removeTempDir = (dirPath: string) => { if (fs.existsSync(dirPath)) { const files = fs.readdirSync(dirPath); for (const file of files) { fs.unlinkSync(path.join(dirPath, file)); } fs.rmdirSync(dirPath); } }; // Tests tap.test('should prepare test environment', async () => { testLogDir = createTempLogDir(); testLogFile = path.join(testLogDir, 'test.log'); expect(fs.existsSync(testLogDir)).toBeTrue(); }); tap.test('should create a file destination instance with a valid path', async () => { testDestination = new SmartlogDestinationFile(testLogFile); expect(testDestination).toBeTruthy(); expect(fs.existsSync(testLogFile)).toBeTrue(); }); tap.test('should throw error when file path is not absolute', async () => { let errorThrown = false; try { new SmartlogDestinationFile('relative/path/file.log'); } catch (error) { errorThrown = true; expect(error.message).toContain('filePath needs to be absolute'); } expect(errorThrown).toBeTrue(); }); tap.test('should write log messages to file', async () => { const testMessage = 'Test log message'; await testDestination.handleLog({ timestamp: Date.now(), type: 'log', level: 'info', message: testMessage, context: { environment: 'test', runtime: 'node' }, correlation: { id: '123', type: 'none' } }); // Give file system a moment to write await new Promise(resolve => setTimeout(resolve, 50)); const fileContent = fs.readFileSync(testLogFile, 'utf8'); expect(fileContent).toContain(testMessage); }); tap.test('should clean up test resources', async () => { // Close file handle before cleanup testDestination.fileWriteStream.end(); // Small delay to ensure file is properly closed await new Promise(resolve => setTimeout(resolve, 100)); removeTempDir(testLogDir); expect(fs.existsSync(testLogDir)).toBeFalse(); }); export default tap.start();