|
|
|
|
@@ -1,38 +1,23 @@
|
|
|
|
|
// src/routes/system.routes.test.ts
|
|
|
|
|
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
|
|
|
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
|
|
|
import supertest from 'supertest';
|
|
|
|
|
import { exec, type ExecException, type ExecOptions } from 'child_process'; // Keep this for mocking
|
|
|
|
|
import systemRouter from './system.routes'; // This was a duplicate, fixed.
|
|
|
|
|
import { exec, type ExecException, type ExecOptions } from 'child_process';
|
|
|
|
|
import { geocodingService } from '../services/geocodingService.server';
|
|
|
|
|
import { createTestApp } from '../tests/utils/createTestApp';
|
|
|
|
|
import { mockLogger } from '../tests/utils/mockLogger';
|
|
|
|
|
|
|
|
|
|
// =============================================================================
|
|
|
|
|
// MOCKS CONFIGURATION
|
|
|
|
|
// =============================================================================
|
|
|
|
|
|
|
|
|
|
// 1. Mock child_process
|
|
|
|
|
// FIX: Use the simple factory pattern for child_process to avoid default export issues.
|
|
|
|
|
// We also add logging here to catch any un-mocked usages immediately.
|
|
|
|
|
// FIX: Use the simple factory pattern for child_process to avoid default export issues
|
|
|
|
|
vi.mock('child_process', () => {
|
|
|
|
|
const defaultMockExec = (command: string, ...args: any[]) => {
|
|
|
|
|
console.log(`[MOCK:child_process] Global exec hit for command: "${command}"`);
|
|
|
|
|
const callback = args.find((arg) => typeof arg === 'function');
|
|
|
|
|
if (callback) {
|
|
|
|
|
// Defensive: Run callback async to prevent Zalgo and stack overflows
|
|
|
|
|
process.nextTick(() => {
|
|
|
|
|
callback(null, 'PM2 OK', '');
|
|
|
|
|
});
|
|
|
|
|
const mockExec = vi.fn((command, callback) => {
|
|
|
|
|
if (typeof callback === 'function') {
|
|
|
|
|
callback(null, 'PM2 OK', '');
|
|
|
|
|
}
|
|
|
|
|
return {
|
|
|
|
|
unref: () => {
|
|
|
|
|
/* no-op */
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
return { unref: () => {} };
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
default: { exec: defaultMockExec },
|
|
|
|
|
exec: defaultMockExec,
|
|
|
|
|
default: { exec: mockExec },
|
|
|
|
|
exec: mockExec,
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
@@ -45,162 +30,205 @@ vi.mock('../services/geocodingService.server', () => ({
|
|
|
|
|
|
|
|
|
|
// 3. Mock Logger
|
|
|
|
|
vi.mock('../services/logger.server', () => ({
|
|
|
|
|
logger: mockLogger,
|
|
|
|
|
logger: {
|
|
|
|
|
info: vi.fn(),
|
|
|
|
|
debug: vi.fn(),
|
|
|
|
|
error: vi.fn(),
|
|
|
|
|
warn: vi.fn(),
|
|
|
|
|
child: vi.fn().mockReturnThis(),
|
|
|
|
|
},
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
// Import the router AFTER all mocks are defined.
|
|
|
|
|
import systemRouter from './system.routes';
|
|
|
|
|
|
|
|
|
|
// =============================================================================
|
|
|
|
|
// TEST SUITE
|
|
|
|
|
// =============================================================================
|
|
|
|
|
|
|
|
|
|
describe('System Routes (/api/system)', () => {
|
|
|
|
|
console.log('[TEST SUITE] initializing System Routes tests...');
|
|
|
|
|
|
|
|
|
|
const app = createTestApp({ router: systemRouter, basePath: '/api/system' });
|
|
|
|
|
|
|
|
|
|
// Add a basic error handler to capture errors passed to next(err) and return JSON.
|
|
|
|
|
app.use((err: any, req: any, res: any, next: any) => {
|
|
|
|
|
console.error('[TEST SUITE] Error caught in test app error handler:', err.message);
|
|
|
|
|
res.status(err.status || 500).json({ message: err.message, errors: err.errors });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
beforeEach(() => {
|
|
|
|
|
// We cast here to get type-safe access to mock functions like .mockImplementation
|
|
|
|
|
vi.clearAllMocks();
|
|
|
|
|
console.log('[TEST SUITE] Mocks cleared.');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
afterAll(() => {
|
|
|
|
|
vi.restoreAllMocks();
|
|
|
|
|
console.log('[TEST SUITE] Mocks restored. Suite finished.');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
describe('GET /pm2-status', () => {
|
|
|
|
|
// Helper function to set up the mock for `child_process.exec` for each test case.
|
|
|
|
|
// This avoids repeating the complex mock implementation in every test.
|
|
|
|
|
const setupExecMock = (error: ExecException | null, stdout: string, stderr: string) => {
|
|
|
|
|
console.log('[TEST SETUP] Configuring exec mock implementation');
|
|
|
|
|
it('should return success: true when pm2 process is online', async () => {
|
|
|
|
|
// Arrange: Simulate a successful `pm2 describe` output for an online process.
|
|
|
|
|
const pm2OnlineOutput = `
|
|
|
|
|
┌─ PM2 info ────────────────┐
|
|
|
|
|
│ status │ online │
|
|
|
|
|
└───────────┴───────────┘
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
type ExecCallback = (error: ExecException | null, stdout: string, stderr: string) => void;
|
|
|
|
|
|
|
|
|
|
// A robust mock for `exec` that handles its multiple overloads.
|
|
|
|
|
// This avoids the complex and error-prone `...args` signature.
|
|
|
|
|
vi.mocked(exec).mockImplementation(
|
|
|
|
|
(
|
|
|
|
|
command: string,
|
|
|
|
|
options?: ExecOptions | ExecCallback | null,
|
|
|
|
|
callback?: ExecCallback | null,
|
|
|
|
|
) => {
|
|
|
|
|
// The actual callback can be the second or third argument.
|
|
|
|
|
const actualCallback = (
|
|
|
|
|
typeof options === 'function' ? options : callback
|
|
|
|
|
) as ExecCallback;
|
|
|
|
|
if (actualCallback) {
|
|
|
|
|
actualCallback(null, pm2OnlineOutput, '');
|
|
|
|
|
}
|
|
|
|
|
// Return a minimal object that satisfies the ChildProcess type for .unref()
|
|
|
|
|
return { unref: () => {} } as ReturnType<typeof exec>;
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Act
|
|
|
|
|
const response = await supertest(app).get('/api/system/pm2-status');
|
|
|
|
|
|
|
|
|
|
// Assert
|
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
|
expect(response.body).toEqual({
|
|
|
|
|
success: true,
|
|
|
|
|
message: 'Application is online and running under PM2.',
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return success: false when pm2 process is stopped or errored', async () => {
|
|
|
|
|
const pm2StoppedOutput = `│ status │ stopped │`;
|
|
|
|
|
|
|
|
|
|
vi.mocked(exec).mockImplementation(
|
|
|
|
|
(
|
|
|
|
|
command: string,
|
|
|
|
|
optionsOrCb?:
|
|
|
|
|
options?:
|
|
|
|
|
| ExecOptions
|
|
|
|
|
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
|
|
|
|
| null,
|
|
|
|
|
cb?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
|
|
|
|
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
|
|
|
|
) => {
|
|
|
|
|
console.log(`[MOCK EXEC] Command received: "${command}"`);
|
|
|
|
|
|
|
|
|
|
// Normalize arguments: options is optional
|
|
|
|
|
let callback:
|
|
|
|
|
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
|
|
|
|
| undefined;
|
|
|
|
|
|
|
|
|
|
if (typeof optionsOrCb === 'function') {
|
|
|
|
|
callback = optionsOrCb;
|
|
|
|
|
} else if (typeof cb === 'function') {
|
|
|
|
|
callback = cb;
|
|
|
|
|
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
|
|
|
|
error: ExecException | null,
|
|
|
|
|
stdout: string,
|
|
|
|
|
stderr: string,
|
|
|
|
|
) => void;
|
|
|
|
|
if (actualCallback) {
|
|
|
|
|
actualCallback(null, pm2StoppedOutput, '');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (callback) {
|
|
|
|
|
const safeCallback = callback;
|
|
|
|
|
// Defensive: Execute callback asynchronously (nextTick) to simulate real I/O
|
|
|
|
|
// This prevents the "synchronous callback" issue which can confuse test runners and async/await
|
|
|
|
|
process.nextTick(() => {
|
|
|
|
|
console.log(
|
|
|
|
|
`[MOCK EXEC] Invoking callback for "${command}" | Error: ${!!error} | Stdout len: ${stdout.length}`,
|
|
|
|
|
);
|
|
|
|
|
try {
|
|
|
|
|
safeCallback(error, stdout, stderr);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('[MOCK EXEC] CRITICAL: Error inside exec callback:', err);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
console.warn(`[MOCK EXEC] No callback provided for "${command}"`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
unref: () => {
|
|
|
|
|
/* no-op */
|
|
|
|
|
},
|
|
|
|
|
} as ReturnType<typeof exec>;
|
|
|
|
|
return { unref: () => {} } as ReturnType<typeof exec>;
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const testCases = [
|
|
|
|
|
{
|
|
|
|
|
description: 'should return success: true when pm2 process is online',
|
|
|
|
|
mock: {
|
|
|
|
|
error: null,
|
|
|
|
|
stdout: `
|
|
|
|
|
┌─ PM2 info ────────────────┐
|
|
|
|
|
│ status │ online │
|
|
|
|
|
└───────────┴───────────┘
|
|
|
|
|
`,
|
|
|
|
|
stderr: '',
|
|
|
|
|
const response = await supertest(app).get('/api/system/pm2-status');
|
|
|
|
|
|
|
|
|
|
// Assert
|
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
|
expect(response.body.success).toBe(false);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return success: false when pm2 process does not exist', async () => {
|
|
|
|
|
// Arrange: Simulate `pm2 describe` failing because the process isn't found.
|
|
|
|
|
const processNotFoundOutput =
|
|
|
|
|
"[PM2][ERROR] Process or Namespace flyer-crawler-api doesn't exist";
|
|
|
|
|
const processNotFoundError = new Error(
|
|
|
|
|
'Command failed: pm2 describe flyer-crawler-api',
|
|
|
|
|
) as ExecException;
|
|
|
|
|
processNotFoundError.code = 1;
|
|
|
|
|
|
|
|
|
|
vi.mocked(exec).mockImplementation(
|
|
|
|
|
(
|
|
|
|
|
command: string,
|
|
|
|
|
options?:
|
|
|
|
|
| ExecOptions
|
|
|
|
|
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
|
|
|
|
| null,
|
|
|
|
|
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
|
|
|
|
) => {
|
|
|
|
|
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
|
|
|
|
error: ExecException | null,
|
|
|
|
|
stdout: string,
|
|
|
|
|
stderr: string,
|
|
|
|
|
) => void;
|
|
|
|
|
if (actualCallback) {
|
|
|
|
|
actualCallback(processNotFoundError, processNotFoundOutput, '');
|
|
|
|
|
}
|
|
|
|
|
return { unref: () => {} } as ReturnType<typeof exec>;
|
|
|
|
|
},
|
|
|
|
|
expectedStatus: 200,
|
|
|
|
|
expectedBody: { success: true, message: 'Application is online and running under PM2.' },
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
description: 'should return success: false when pm2 process is stopped',
|
|
|
|
|
mock: { error: null, stdout: '│ status │ stopped │', stderr: '' },
|
|
|
|
|
expectedStatus: 200,
|
|
|
|
|
expectedBody: { success: false, message: 'Application process exists but is not online.' },
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
description: 'should return success: false when pm2 process does not exist',
|
|
|
|
|
mock: {
|
|
|
|
|
error: Object.assign(new Error('Command failed'), { code: 1 }),
|
|
|
|
|
stdout: "[PM2][ERROR] Process or Namespace flyer-crawler-api doesn't exist",
|
|
|
|
|
stderr: '',
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Act
|
|
|
|
|
const response = await supertest(app).get('/api/system/pm2-status');
|
|
|
|
|
|
|
|
|
|
// Assert
|
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
|
expect(response.body).toEqual({
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Application process is not running under PM2.',
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return 500 if pm2 command produces stderr output', async () => {
|
|
|
|
|
// Arrange: Simulate a successful exit code but with content in stderr.
|
|
|
|
|
const stderrOutput = 'A non-fatal warning occurred.';
|
|
|
|
|
|
|
|
|
|
vi.mocked(exec).mockImplementation(
|
|
|
|
|
(
|
|
|
|
|
command: string,
|
|
|
|
|
options?:
|
|
|
|
|
| ExecOptions
|
|
|
|
|
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
|
|
|
|
| null,
|
|
|
|
|
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
|
|
|
|
) => {
|
|
|
|
|
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
|
|
|
|
error: ExecException | null,
|
|
|
|
|
stdout: string,
|
|
|
|
|
stderr: string,
|
|
|
|
|
) => void;
|
|
|
|
|
if (actualCallback) {
|
|
|
|
|
actualCallback(null, 'Some stdout', stderrOutput);
|
|
|
|
|
}
|
|
|
|
|
return { unref: () => {} } as ReturnType<typeof exec>;
|
|
|
|
|
},
|
|
|
|
|
expectedStatus: 200,
|
|
|
|
|
expectedBody: { success: false, message: 'Application process is not running under PM2.' },
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
description: 'should return 500 if pm2 command produces stderr output',
|
|
|
|
|
mock: { error: null, stdout: 'Some stdout', stderr: 'A non-fatal warning occurred.' },
|
|
|
|
|
expectedStatus: 500,
|
|
|
|
|
expectedBody: { message: 'PM2 command produced an error: A non-fatal warning occurred.' },
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
description: 'should return 500 on a generic exec error',
|
|
|
|
|
mock: { error: new Error('System error'), stdout: '', stderr: 'stderr output' },
|
|
|
|
|
expectedStatus: 500,
|
|
|
|
|
expectedBody: { message: 'System error' },
|
|
|
|
|
},
|
|
|
|
|
];
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
it.each(testCases)(
|
|
|
|
|
'$description',
|
|
|
|
|
async ({ mock, expectedStatus, expectedBody, description }) => {
|
|
|
|
|
console.log(`[TEST CASE] Starting: ${description}`);
|
|
|
|
|
const response = await supertest(app).get('/api/system/pm2-status');
|
|
|
|
|
expect(response.status).toBe(500);
|
|
|
|
|
expect(response.body.message).toBe(`PM2 command produced an error: ${stderrOutput}`);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Arrange
|
|
|
|
|
setupExecMock(mock.error as ExecException | null, mock.stdout, mock.stderr);
|
|
|
|
|
it('should return 500 on a generic exec error', async () => {
|
|
|
|
|
vi.mocked(exec).mockImplementation(
|
|
|
|
|
(
|
|
|
|
|
command: string,
|
|
|
|
|
options?:
|
|
|
|
|
| ExecOptions
|
|
|
|
|
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
|
|
|
|
| null,
|
|
|
|
|
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
|
|
|
|
) => {
|
|
|
|
|
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
|
|
|
|
error: ExecException | null,
|
|
|
|
|
stdout: string,
|
|
|
|
|
stderr: string,
|
|
|
|
|
) => void;
|
|
|
|
|
if (actualCallback) {
|
|
|
|
|
actualCallback(new Error('System error') as ExecException, '', 'stderr output');
|
|
|
|
|
}
|
|
|
|
|
return { unref: () => {} } as ReturnType<typeof exec>;
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Act
|
|
|
|
|
console.log('[TEST CASE] Sending request...');
|
|
|
|
|
const response = await supertest(app).get('/api/system/pm2-status');
|
|
|
|
|
console.log(`[TEST CASE] Response received: status=${response.status}`);
|
|
|
|
|
// Act
|
|
|
|
|
const response = await supertest(app).get('/api/system/pm2-status');
|
|
|
|
|
|
|
|
|
|
// Assert
|
|
|
|
|
expect(response.status).toBe(expectedStatus);
|
|
|
|
|
expect(response.body).toEqual(expectedBody);
|
|
|
|
|
console.log(`[TEST CASE] Completed: ${description}`);
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
// Assert
|
|
|
|
|
expect(response.status).toBe(500);
|
|
|
|
|
expect(response.body.message).toBe('System error');
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
describe('POST /geocode', () => {
|
|
|
|
|
it('should return geocoded coordinates for a valid address', async () => {
|
|
|
|
|
console.log('[TEST CASE] POST /geocode - valid address');
|
|
|
|
|
// Arrange
|
|
|
|
|
const mockCoordinates = { lat: 48.4284, lng: -123.3656 };
|
|
|
|
|
vi.mocked(geocodingService.geocodeAddress).mockResolvedValue(mockCoordinates);
|
|
|
|
|
@@ -216,7 +244,6 @@ describe('System Routes (/api/system)', () => {
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return 404 if the address cannot be geocoded', async () => {
|
|
|
|
|
console.log('[TEST CASE] POST /geocode - address not found');
|
|
|
|
|
vi.mocked(geocodingService.geocodeAddress).mockResolvedValue(null);
|
|
|
|
|
const response = await supertest(app)
|
|
|
|
|
.post('/api/system/geocode')
|
|
|
|
|
@@ -226,7 +253,6 @@ describe('System Routes (/api/system)', () => {
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return 500 if the geocoding service throws an error', async () => {
|
|
|
|
|
console.log('[TEST CASE] POST /geocode - service error');
|
|
|
|
|
const geocodeError = new Error('Geocoding service unavailable');
|
|
|
|
|
vi.mocked(geocodingService.geocodeAddress).mockRejectedValue(geocodeError);
|
|
|
|
|
const response = await supertest(app)
|
|
|
|
|
@@ -236,7 +262,6 @@ describe('System Routes (/api/system)', () => {
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return 400 if the address is missing from the body', async () => {
|
|
|
|
|
console.log('[TEST CASE] POST /geocode - validation error');
|
|
|
|
|
const response = await supertest(app)
|
|
|
|
|
.post('/api/system/geocode')
|
|
|
|
|
.send({ not_address: 'Victoria, BC' });
|
|
|
|
|
|