Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

chore: fix broken tests & add more tests coverage

towfiqi0fc6f8ffcd8b
diff --git a/backend/__tests__/controllers/BackupController.test.ts b/backend/__tests__/controllers/BackupController.test.ts
index ea278fb..42b417e 100644
--- a/backend/__tests__/controllers/BackupController.test.ts
+++ b/backend/__tests__/controllers/BackupController.test.ts
@@ -23,7 +23,6 @@ describe('BackupController', () => {
null as any,
null as any,
null as any,
- null as any,
null as any
) as jest.Mocked<BackupService>;
diff --git a/backend/__tests__/controllers/PlanController.test.ts b/backend/__tests__/controllers/PlanController.test.ts
index 1bc0c29..93a94df 100644
--- a/backend/__tests__/controllers/PlanController.test.ts
+++ b/backend/__tests__/controllers/PlanController.test.ts
@@ -133,22 +133,29 @@ describe('PlanController', () => {
});
});
- describe('checkActiveBackups', () => {
+ describe('checkActiveBackupsOrRestore', () => {
it('should return 400 if plan ID is missing', async () => {
mockRequest.params = {};
- await planController.checkActiveBackups(mockRequest as Request, mockResponse as Response);
+ await planController.checkActiveBackupsOrRestore(
+ mockRequest as Request,
+ mockResponse as Response
+ );
expect(mockStatus).toHaveBeenCalledWith(400);
});
it('should successfully check for active backups', async () => {
mockRequest.params = { id: 'plan-1' };
- mockPlanService.checkActiveBackups.mockResolvedValue(true);
+ mockRequest.query = { type: 'backup' };
+ mockPlanService.checkActiveBackupsOrRestore.mockResolvedValue(true);
- await planController.checkActiveBackups(mockRequest as Request, mockResponse as Response);
+ await planController.checkActiveBackupsOrRestore(
+ mockRequest as Request,
+ mockResponse as Response
+ );
- expect(mockPlanService.checkActiveBackups).toHaveBeenCalledWith('plan-1');
+ expect(mockPlanService.checkActiveBackupsOrRestore).toHaveBeenCalledWith('plan-1', 'backup');
expect(mockStatus).toHaveBeenCalledWith(200);
expect(mockJson).toHaveBeenCalledWith({
success: true,
diff --git a/backend/__tests__/controllers/RestoreController.test.ts b/backend/__tests__/controllers/RestoreController.test.ts
index 3091383..c0e4bc8 100644
--- a/backend/__tests__/controllers/RestoreController.test.ts
+++ b/backend/__tests__/controllers/RestoreController.test.ts
@@ -20,7 +20,6 @@ describe('RestoreController', () => {
null as any,
null as any,
null as any,
- null as any,
null as any
) as jest.Mocked<RestoreService>;
@@ -295,7 +294,7 @@ describe('RestoreController', () => {
expect(mockStatus).toHaveBeenCalledWith(500);
expect(mockJson).toHaveBeenCalledWith({
success: false,
- error: 'Failed to restore plan',
+ error: 'Failed to perform dry restore. Restore failed',
});
});
});
diff --git a/backend/__tests__/controllers/SettingsController.test.ts b/backend/__tests__/controllers/SettingsController.test.ts
index e9825a7..b134922 100644
--- a/backend/__tests__/controllers/SettingsController.test.ts
+++ b/backend/__tests__/controllers/SettingsController.test.ts
@@ -3,6 +3,19 @@ import { SettingsController } from '../../src/controllers/SettingsController';
import { SettingsService } from '../../src/services/SettingsService';
import { AppSettings } from '../../src/types/settings';
+jest.mock('../../src/services/ConfigService', () => ({
+ configService: {
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ },
+ ConfigService: {
+ getInstance: jest.fn().mockReturnValue({
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ }),
+ },
+}));
+
jest.mock('../../src/services/SettingsService');
describe('SettingsController', () => {
diff --git a/backend/__tests__/controllers/SetupController.test.ts b/backend/__tests__/controllers/SetupController.test.ts
new file mode 100644
index 0000000..eb3dc39
--- /dev/null
+++ b/backend/__tests__/controllers/SetupController.test.ts
@@ -0,0 +1,275 @@
+import { Request, Response } from 'express';
+import { SetupController } from '../../src/controllers/SetupController';
+
+jest.mock('../../src/services/KeyringService', () => ({
+ keyringService: {
+ isPlatformSupported: jest.fn(),
+ waitForInitialization: jest.fn(),
+ setAllCredentials: jest.fn(),
+ },
+}));
+
+jest.mock('../../src/services/ConfigService', () => ({
+ configService: {
+ isSetupPending: jest.fn(),
+ completeSetup: jest.fn(),
+ },
+}));
+
+jest.mock('../../src/utils/installHelpers', () => ({
+ requiresKeyringSetup: jest.fn(),
+ isBinaryMode: jest.fn(),
+}));
+
+jest.mock('../../src/utils/initSetup', () => ({
+ initSetup: jest.fn(),
+}));
+
+jest.mock('../../src/db', () => ({
+ db: {},
+}));
+
+import { keyringService } from '../../src/services/KeyringService';
+import { configService } from '../../src/services/ConfigService';
+import { requiresKeyringSetup, isBinaryMode } from '../../src/utils/installHelpers';
+import { initSetup } from '../../src/utils/initSetup';
+
+describe('SetupController', () => {
+ let controller: SetupController;
+ let mockRequest: Partial<Request>;
+ let mockResponse: Partial<Response>;
+ let mockJson: jest.Mock;
+ let mockStatus: jest.Mock;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ mockJson = jest.fn().mockReturnThis();
+ mockStatus = jest.fn().mockReturnValue({ json: mockJson });
+
+ mockResponse = {
+ json: mockJson,
+ status: mockStatus,
+ };
+
+ mockRequest = {
+ body: {},
+ };
+
+ controller = new SetupController();
+ });
+
+ describe('getStatus', () => {
+ it('should return setup status successfully', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (isBinaryMode as jest.Mock).mockReturnValue(false);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+
+ await controller.getStatus(mockRequest as Request, mockResponse as Response);
+
+ expect(mockJson).toHaveBeenCalledWith({
+ success: true,
+ data: {
+ setupPending: true,
+ isBinary: false,
+ requiresKeyringSetup: true,
+ platform: process.platform,
+ },
+ });
+ });
+
+ it('should return 500 on error', async () => {
+ (configService.isSetupPending as jest.Mock).mockImplementation(() => {
+ throw new Error('Status check failed');
+ });
+
+ await controller.getStatus(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(500);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Status check failed',
+ });
+ });
+ });
+
+ describe('completeSetup', () => {
+ const validBody = {
+ encryptionKey: 'mySecureKey123',
+ userName: 'admin',
+ userPassword: 'password123',
+ };
+
+ it('should return 400 if setup is not pending', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(false);
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(400);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Setup is not pending. Application is already configured.',
+ });
+ });
+
+ it('should return 400 if keyring setup is not supported', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(false);
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(400);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Keyring setup is only available on Windows and macOS binary installations.',
+ });
+ });
+
+ it('should return 400 if required fields are missing', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ mockRequest.body = { encryptionKey: 'mySecureKey123' };
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(400);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Missing required fields: encryptionKey, userName, userPassword',
+ });
+ });
+
+ it('should return 400 if encryptionKey is too short', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ mockRequest.body = { encryptionKey: 'short', userName: 'admin', userPassword: 'password123' };
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(400);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Encryption key must be at least 12 characters long',
+ });
+ });
+
+ it('should return 400 if userName is empty', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ mockRequest.body = {
+ encryptionKey: 'mySecureKey123',
+ userName: '',
+ userPassword: 'password123',
+ };
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(400);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Missing required fields: encryptionKey, userName, userPassword',
+ });
+ });
+
+ it('should return 400 if userPassword is empty', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ mockRequest.body = { encryptionKey: 'mySecureKey123', userName: 'admin', userPassword: '' };
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(400);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Missing required fields: encryptionKey, userName, userPassword',
+ });
+ });
+
+ it('should return 500 if keyring store fails', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ (keyringService.setAllCredentials as jest.Mock).mockResolvedValue(false);
+ mockRequest.body = validBody;
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(500);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Failed to store credentials in the system keyring',
+ });
+ });
+
+ it('should complete setup successfully', async () => {
+ (configService.isSetupPending as jest.Mock).mockReturnValue(true);
+ (requiresKeyringSetup as jest.Mock).mockReturnValue(true);
+ (keyringService.setAllCredentials as jest.Mock).mockResolvedValue(true);
+ (initSetup as jest.Mock).mockResolvedValue(undefined);
+ mockRequest.body = validBody;
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(keyringService.setAllCredentials).toHaveBeenCalledWith({
+ ENCRYPTION_KEY: validBody.encryptionKey,
+ USER_NAME: validBody.userName,
+ USER_PASSWORD: validBody.userPassword,
+ });
+ expect(configService.completeSetup).toHaveBeenCalledWith({
+ ENCRYPTION_KEY: validBody.encryptionKey,
+ USER_NAME: validBody.userName,
+ USER_PASSWORD: validBody.userPassword,
+ });
+ expect(initSetup).toHaveBeenCalled();
+ expect(mockJson).toHaveBeenCalledWith({
+ success: true,
+ message: 'Setup completed successfully. Credentials stored securely.',
+ });
+ });
+
+ it('should return 500 on unexpected error', async () => {
+ (configService.isSetupPending as jest.Mock).mockImplementation(() => {
+ throw new Error('Unexpected failure');
+ });
+
+ await controller.completeSetup(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(500);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Unexpected failure',
+ });
+ });
+ });
+
+ describe('checkKeyringAvailability', () => {
+ it('should return keyring availability successfully', async () => {
+ (keyringService.isPlatformSupported as jest.Mock).mockReturnValue(true);
+ (keyringService.waitForInitialization as jest.Mock).mockResolvedValue(true);
+
+ await controller.checkKeyringAvailability(mockRequest as Request, mockResponse as Response);
+
+ expect(mockJson).toHaveBeenCalledWith({
+ success: true,
+ data: {
+ platformSupported: true,
+ keyringAvailable: true,
+ platform: process.platform,
+ },
+ });
+ });
+
+ it('should return 500 on error', async () => {
+ (keyringService.isPlatformSupported as jest.Mock).mockImplementation(() => {
+ throw new Error('Keyring check failed');
+ });
+
+ await controller.checkKeyringAvailability(mockRequest as Request, mockResponse as Response);
+
+ expect(mockStatus).toHaveBeenCalledWith(500);
+ expect(mockJson).toHaveBeenCalledWith({
+ success: false,
+ error: 'Keyring check failed',
+ });
+ });
+ });
+});
diff --git a/backend/__tests__/jobs/tasks/CleanDownloadsTask.test.ts b/backend/__tests__/jobs/tasks/CleanDownloadsTask.test.ts
index 1053d7d..2f47cb7 100644
--- a/backend/__tests__/jobs/tasks/CleanDownloadsTask.test.ts
+++ b/backend/__tests__/jobs/tasks/CleanDownloadsTask.test.ts
@@ -11,6 +11,7 @@ const mockAppPaths = {
getDownloadsDir: jest.fn(),
getRestoresDir: jest.fn(),
getProgressDir: jest.fn(),
+ getCacheDir: jest.fn(),
};
jest.mock('fs/promises', () => ({
@@ -42,6 +43,7 @@ describe('CleanDownloadsTask', () => {
mockAppPaths.getDownloadsDir.mockReturnValue('/downloads');
mockAppPaths.getRestoresDir.mockReturnValue('/restores');
mockAppPaths.getProgressDir.mockReturnValue('/progress');
+ mockAppPaths.getCacheDir.mockReturnValue('/cache');
mockReaddir.mockResolvedValue([]);
mockStat.mockResolvedValue({
@@ -73,10 +75,12 @@ describe('CleanDownloadsTask', () => {
expect(mockAppPaths.getDownloadsDir).toHaveBeenCalled();
expect(mockAppPaths.getRestoresDir).toHaveBeenCalled();
expect(mockAppPaths.getProgressDir).toHaveBeenCalled();
+ expect(mockAppPaths.getCacheDir).toHaveBeenCalled();
expect(mockReaddir).toHaveBeenCalledWith('/downloads');
expect(mockReaddir).toHaveBeenCalledWith('/restores');
expect(mockReaddir).toHaveBeenCalledWith('/progress');
+ expect(mockReaddir).toHaveBeenCalledWith('/cache');
});
it('removes files older than 96 hours', async () => {
@@ -163,7 +167,7 @@ describe('CleanDownloadsTask', () => {
await cleanTask.run(job);
- expect(mockRm).toHaveBeenCalledTimes(9); // 3 files × 3 directories
+ expect(mockRm).toHaveBeenCalledTimes(12); // 3 files × 4 directories
});
it('handles empty directories', async () => {
@@ -219,7 +223,7 @@ describe('CleanDownloadsTask', () => {
};
await expect(cleanTask.run(job)).resolves.not.toThrow();
- expect(mockCronLogger.error).toHaveBeenCalledTimes(3); // Once per directory
+ expect(mockCronLogger.error).toHaveBeenCalledTimes(4); // Once per directory
});
it('continues cleaning other directories if one fails', async () => {
@@ -249,7 +253,7 @@ describe('CleanDownloadsTask', () => {
await cleanTask.run(job);
expect(mockCronLogger.error).toHaveBeenCalledTimes(1);
- expect(mockRm).toHaveBeenCalledTimes(2); // 2 remaining directories
+ expect(mockRm).toHaveBeenCalledTimes(3); // 3 remaining directories
});
it('uses recursive and force flags when removing', async () => {
diff --git a/backend/__tests__/managers/BaseBackupManager.test.ts b/backend/__tests__/managers/BaseBackupManager.test.ts
index 02ffbd7..3c36f0a 100644
--- a/backend/__tests__/managers/BaseBackupManager.test.ts
+++ b/backend/__tests__/managers/BaseBackupManager.test.ts
@@ -82,6 +82,14 @@ jest.mock('../../src/utils/helpers', () => ({
}),
}));
+jest.mock('../../src/services/ConfigService', () => ({
+ configService: {
+ config: {
+ ENCRYPTION_KEY: 'secret-key',
+ },
+ },
+}));
+
import { BaseBackupManager } from '../../src/managers/BaseBackupManager';
import { BackupPlanArgs } from '../../src/types/plans';
import { EventEmitter } from 'events';
diff --git a/backend/__tests__/managers/BaseSnapshotManager.test.ts b/backend/__tests__/managers/BaseSnapshotManager.test.ts
index a242387..0356f3f 100644
--- a/backend/__tests__/managers/BaseSnapshotManager.test.ts
+++ b/backend/__tests__/managers/BaseSnapshotManager.test.ts
@@ -33,6 +33,11 @@ jest.mock('../../src/services/ConfigService', () => ({
},
}));
+jest.mock('fs/promises', () => ({
+ readFile: jest.fn().mockRejectedValue(new Error('ENOENT: no such file or directory')),
+ writeFile: jest.fn().mockResolvedValue(undefined),
+}));
+
import {
runResticCommand,
getSnapshotByTag,
@@ -141,7 +146,6 @@ describe('BaseSnapshotManager', () => {
};
it('should forget snapshot and return updated stats', async () => {
- process.env.ENCRYPTION_KEY = 'env-secret';
(getSnapshotByTag as jest.Mock).mockResolvedValue({
success: true,
result: { id: 'snap-abc' },
@@ -158,7 +162,7 @@ describe('BaseSnapshotManager', () => {
expect(generateResticRepoPath).toHaveBeenCalledWith('store', 'path');
expect(runResticCommand).toHaveBeenCalledWith(
['-r', 'mock-repo-path', 'forget', 'snap-abc', '--json'],
- { RESTIC_PASSWORD: 'env-secret' }
+ { RESTIC_PASSWORD: 'mySecretKey' }
);
expect(getBackupPlanStats).toHaveBeenCalledWith('plan-1', 'store', 'path', true);
expect(out).toEqual({
diff --git a/backend/__tests__/managers/BaseSystemManager.test.ts b/backend/__tests__/managers/BaseSystemManager.test.ts
index 4835010..57078f8 100644
--- a/backend/__tests__/managers/BaseSystemManager.test.ts
+++ b/backend/__tests__/managers/BaseSystemManager.test.ts
@@ -79,6 +79,25 @@ jest.mock('../../src/utils/AppPaths', () => ({
},
}));
+jest.mock('../../src/services/ConfigService', () => ({
+ configService: {
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ },
+ ConfigService: {
+ getInstance: jest.fn().mockReturnValue({
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ }),
+ },
+}));
+
import os from 'os';
import si from 'systeminformation';
import { execSync } from 'child_process';
diff --git a/backend/__tests__/managers/RestoreStatsManager.test.ts b/backend/__tests__/managers/RestoreStatsManager.test.ts
index 6ef9b51..25c011c 100644
--- a/backend/__tests__/managers/RestoreStatsManager.test.ts
+++ b/backend/__tests__/managers/RestoreStatsManager.test.ts
@@ -13,6 +13,26 @@ jest.mock('../../src/utils/AppPaths', () => ({
getStatsDir: jest.fn(),
},
}));
+
+jest.mock('../../src/services/ConfigService', () => ({
+ configService: {
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ },
+ ConfigService: {
+ getInstance: jest.fn().mockReturnValue({
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ }),
+ },
+}));
+
jest.mock('../../src/utils/getBackupSourceFiles');
jest.mock('fs/promises');
jest.mock('fs');
diff --git a/backend/__tests__/managers/SecurityKeyManager.test.ts b/backend/__tests__/managers/SecurityKeyManager.test.ts
index 5080ec0..1c9938b 100644
--- a/backend/__tests__/managers/SecurityKeyManager.test.ts
+++ b/backend/__tests__/managers/SecurityKeyManager.test.ts
@@ -144,14 +144,17 @@ describe('SecurityKeyManager', () => {
});
it('should not write keys if keys.json already exists', async () => {
- // Pretend the file already exists
- mockFileSystem[keysFilePath] = JSON.stringify({ publicKey: 'existing' });
+ // Pretend the file already exists with both required fields
+ mockFileSystem[keysFilePath] = JSON.stringify({
+ publicKey: 'existing',
+ encryptedPrivateKey: 'existing-encrypted',
+ });
// Access should succeed
(fs.access as jest.Mock).mockResolvedValue(undefined);
await securityKeyManager.setupInitialKeys();
- expect(crypto.generateKeyPairSync).toHaveBeenCalledWith('ed25519', expect.any(Object));
+ expect(crypto.generateKeyPairSync).not.toHaveBeenCalled();
expect(fs.writeFile).not.toHaveBeenCalled();
});
});
diff --git a/backend/__tests__/managers/handlers/BackupHandler.test.ts b/backend/__tests__/managers/handlers/BackupHandler.test.ts
index 826101c..05178a7 100644
--- a/backend/__tests__/managers/handlers/BackupHandler.test.ts
+++ b/backend/__tests__/managers/handlers/BackupHandler.test.ts
@@ -51,6 +51,25 @@ jest.mock('../../../src/utils/AppPaths', () => ({
},
}));
+jest.mock('../../../src/services/ConfigService', () => ({
+ configService: {
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ },
+ ConfigService: {
+ getInstance: jest.fn().mockReturnValue({
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ }),
+ },
+}));
+
import { EventEmitter } from 'events';
import { BackupHandler } from '../../../src/managers/handlers/BackupHandler';
import os from 'os';
@@ -518,7 +537,9 @@ describe('BackupHandler', () => {
});
it('should throw error when encryption enabled but key missing', async () => {
- delete process.env.ENCRYPTION_KEY;
+ const { configService: cs } = require('../../../src/services/ConfigService');
+ const origKey = cs.config.ENCRYPTION_KEY;
+ cs.config.ENCRYPTION_KEY = '';
// The maxProcessor is 2, so required memory is 64MB * 2 = 128MB
// Provide way more than needed to ensure this check passes
jest.spyOn(os, 'freemem').mockReturnValue(1024 * 1024 * 1024); // 1GB
@@ -535,6 +556,8 @@ describe('BackupHandler', () => {
await expect(handler.canRun(encryptedOptions, resticArgsAndEnv)).rejects.toThrow(
'Encryption enabled but ENCRYPTION_KEY not found'
);
+
+ cs.config.ENCRYPTION_KEY = origKey;
});
it('should throw error when source paths not accessible', async () => {
@@ -696,7 +719,7 @@ describe('BackupHandler', () => {
expect(mockRunResticCommand).toHaveBeenCalledWith(
expect.any(Array),
- expect.objectContaining({ RESTIC_PASSWORD: 'test-key' }),
+ expect.objectContaining({ RESTIC_PASSWORD: 'test-encryption-key' }),
expect.any(Function),
expect.any(Function),
expect.any(Function),
@@ -890,7 +913,7 @@ describe('BackupHandler', () => {
expect(mockRunResticCommand).toHaveBeenCalledWith(
expect.any(Array),
- expect.objectContaining({ RESTIC_PASSWORD: 'test-key' })
+ expect.objectContaining({ RESTIC_PASSWORD: 'test-encryption-key' })
);
});
@@ -1172,7 +1195,7 @@ describe('BackupHandler', () => {
expect(mockRunResticCommand).toHaveBeenCalledWith(
expect.any(Array),
- expect.objectContaining({ RESTIC_PASSWORD: 'test-key' })
+ expect.objectContaining({ RESTIC_PASSWORD: 'test-encryption-key' })
);
});
diff --git a/backend/__tests__/managers/handlers/DownloadHandler.test.ts b/backend/__tests__/managers/handlers/DownloadHandler.test.ts
index 0b29a28..7b7552f 100644
--- a/backend/__tests__/managers/handlers/DownloadHandler.test.ts
+++ b/backend/__tests__/managers/handlers/DownloadHandler.test.ts
@@ -48,6 +48,25 @@ jest.mock('../../../src/utils/AppPaths', () => ({
},
}));
+jest.mock('../../../src/services/ConfigService', () => ({
+ configService: {
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ },
+ ConfigService: {
+ getInstance: jest.fn().mockReturnValue({
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ }),
+ },
+}));
+
import { DownloadHandler } from '../../../src/managers/handlers/DownloadHandler';
import { processManager } from '../../../src/managers/ProcessManager';
import { runResticCommand } from '../../../src/utils/restic/restic';
@@ -169,8 +188,8 @@ describe('DownloadHandler', () => {
storagePath: '',
encryption: true,
});
- expect(receivedEnv).toHaveProperty('RESTIC_PASSWORD', 'secret');
- expect(receivedEnv).toHaveProperty('RCLONE_CONFIG_PASS', 'secret');
+ expect(receivedEnv).toHaveProperty('RESTIC_PASSWORD', 'test-encryption-key');
+ expect(receivedEnv).toHaveProperty('RCLONE_CONFIG_PASS', 'test-encryption-key');
});
test('download: continues and resolves even if rm fails (cleanup error logged)', async () => {
diff --git a/backend/__tests__/managers/handlers/PruneHandler.test.ts b/backend/__tests__/managers/handlers/PruneHandler.test.ts
index 01370cd..bed62a1 100644
--- a/backend/__tests__/managers/handlers/PruneHandler.test.ts
+++ b/backend/__tests__/managers/handlers/PruneHandler.test.ts
@@ -12,6 +12,14 @@ jest.mock('../../../src/utils/restic/helpers', () => ({
generateResticRepoPath: (...args: any[]) => mockGenerateResticRepoPath(...args),
}));
+jest.mock('../../../src/services/ConfigService', () => ({
+ configService: {
+ config: {
+ ENCRYPTION_KEY: 'test-key',
+ },
+ },
+}));
+
import { EventEmitter } from 'events';
import { PruneHandler } from '../../../src/managers/handlers/PruneHandler';
diff --git a/backend/__tests__/managers/handlers/RestoreHandler.test.ts b/backend/__tests__/managers/handlers/RestoreHandler.test.ts
index 81ac86a..2479fb8 100644
--- a/backend/__tests__/managers/handlers/RestoreHandler.test.ts
+++ b/backend/__tests__/managers/handlers/RestoreHandler.test.ts
@@ -57,6 +57,25 @@ jest.mock('../../../src/utils/AppPaths', () => ({
},
}));
+jest.mock('../../../src/services/ConfigService', () => ({
+ configService: {
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ },
+ ConfigService: {
+ getInstance: jest.fn().mockReturnValue({
+ get: jest.fn().mockReturnValue(undefined),
+ getAll: jest.fn().mockReturnValue({}),
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ }),
+ },
+}));
+
jest.mock('../../../src/utils/copyFiles', () => ({
__esModule: true,
default: (...args: any[]) => mockCopyFilesNatively(...args),
@@ -401,7 +420,10 @@ describe('RestoreHandler', () => {
});
it('should throw error when encryption enabled but key missing', async () => {
- delete process.env.ENCRYPTION_KEY;
+ const { configService: cs } = require('../../../src/services/ConfigService');
+ const origKey = cs.config.ENCRYPTION_KEY;
+ cs.config.ENCRYPTION_KEY = '';
+
jest.spyOn(os, 'freemem').mockReturnValue(1024 * 1024 * 1024);
jest.spyOn(os, 'cpus').mockReturnValue(new Array(4));
@@ -409,7 +431,7 @@ describe('RestoreHandler', () => {
'Snapshot encrypted but ENCRYPTION_KEY not found'
);
- process.env.ENCRYPTION_KEY = 'test-key';
+ cs.config.ENCRYPTION_KEY = origKey;
});
it('should throw error when target path not writable', async () => {
@@ -573,7 +595,7 @@ describe('RestoreHandler', () => {
});
expect(result.args).not.toContain('--insecure-no-password');
- expect(result.env.RESTIC_PASSWORD).toBe('test-key');
+ expect(result.env.RESTIC_PASSWORD).toBe('test-encryption-key');
});
it('should add includes and excludes', () => {
diff --git a/backend/__tests__/middlewares/authMiddleware.test.ts b/backend/__tests__/middlewares/authMiddleware.test.ts
new file mode 100644
index 0000000..36c4d13
--- /dev/null
+++ b/backend/__tests__/middlewares/authMiddleware.test.ts
@@ -0,0 +1,146 @@
+import { Request, Response, NextFunction } from 'express';
+import authMiddleware from '../../src/middlewares/authMiddleware';
+
+// Mock jsonwebtoken
+jest.mock('jsonwebtoken', () => ({
+ verify: jest.fn(),
+}));
+
+// Mock cookies
+jest.mock('cookies', () => {
+ return jest.fn().mockImplementation(() => ({
+ get: jest.fn().mockReturnValue(null),
+ }));
+});
+
+// Mock ConfigService
+jest.mock('../../src/services/ConfigService', () => ({
+ configService: {
+ config: {
+ SECRET: 'test-secret',
+ APIKEY: 'test-key',
+ },
+ },
+}));
+
+import jwt from 'jsonwebtoken';
+import Cookies from 'cookies';
+
+const mockJwtVerify = jwt.verify as jest.Mock;
+const MockCookies = Cookies as unknown as jest.Mock;
+
+describe('authMiddleware', () => {
+ let req: Partial<Request>;
+ let res: Partial<Response>;
+ let next: NextFunction;
+ let jsonFn: jest.Mock;
+ let statusFn: jest.Mock;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ jsonFn = jest.fn();
+ statusFn = jest.fn().mockReturnValue({ json: jsonFn });
+
+ req = {
+ headers: {},
+ url: '/api/plans',
+ method: 'GET',
+ };
+ res = { status: statusFn } as Partial<Response>;
+ next = jest.fn();
+ });
+
+ it('should call next() for a valid JWT token', () => {
+ MockCookies.mockImplementation(() => ({
+ get: jest.fn().mockReturnValue('valid-jwt-token'),
+ }));
+ mockJwtVerify.mockImplementation((_token: string, _secret: string, cb: (err: any) => void) => {
+ cb(null);
+ });
+
+ authMiddleware(req as Request, res as Response, next);
+
+ expect(mockJwtVerify).toHaveBeenCalledWith(
+ 'valid-jwt-token',
+ 'test-secret',
+ expect.any(Function)
+ );
+ expect(next).toHaveBeenCalled();
+ expect(statusFn).not.toHaveBeenCalled();
+ });
+
+ it('should return 401 when no token is provided', () => {
+ MockCookies.mockImplementation(() => ({
+ get: jest.fn().mockReturnValue(null),
+ }));
+
+ authMiddleware(req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(401);
+ expect(jsonFn).toHaveBeenCalledWith({ error: 'Not authorized' });
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it('should return 401 when JWT is invalid', () => {
+ MockCookies.mockImplementation(() => ({
+ get: jest.fn().mockReturnValue('invalid-jwt-token'),
+ }));
+ mockJwtVerify.mockImplementation((_token: string, _secret: string, cb: (err: any) => void) => {
+ cb(new Error('jwt malformed'));
+ });
+
+ authMiddleware(req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(401);
+ expect(jsonFn).toHaveBeenCalledWith({ error: 'Not authorized' });
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it('should call next() for valid API key on an allowed route', () => {
+ MockCookies.mockImplementation(() => ({
+ get: jest.fn().mockReturnValue(null),
+ }));
+
+ req.headers = { authorization: 'Bearer test-key' };
+ req.url = '/api/plans';
+ req.method = 'GET';
+
+ authMiddleware(req as Request, res as Response, next);
+
+ expect(next).toHaveBeenCalled();
+ expect(statusFn).not.toHaveBeenCalled();
+ });
+
+ it('should return 401 for valid API key on a disallowed route', () => {
+ MockCookies.mockImplementation(() => ({
+ get: jest.fn().mockReturnValue(null),
+ }));
+
+ req.headers = { authorization: 'Bearer test-key' };
+ req.url = '/api/settings';
+ req.method = 'GET';
+
+ authMiddleware(req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(401);
+ expect(jsonFn).toHaveBeenCalledWith({ error: 'This Route cannot be accessed with API.' });
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it('should return 401 for an invalid API key', () => {
+ MockCookies.mockImplementation(() => ({
+ get: jest.fn().mockReturnValue(null),
+ }));
+
+ req.headers = { authorization: 'Bearer wrong-key' };
+ req.url = '/api/plans';
+ req.method = 'GET';
+
+ authMiddleware(req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(401);
+ expect(jsonFn).toHaveBeenCalledWith({ error: 'Invalid API Key Provided.' });
+ expect(next).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/__tests__/middlewares/errorHandlerMiddleware.test.ts b/backend/__tests__/middlewares/errorHandlerMiddleware.test.ts
new file mode 100644
index 0000000..ca0e733
--- /dev/null
+++ b/backend/__tests__/middlewares/errorHandlerMiddleware.test.ts
@@ -0,0 +1,111 @@
+import { Request, Response, NextFunction } from 'express';
+import { errorHandlerMiddleware } from '../../src/middlewares/errorHandlerMiddleware';
+import { AppError, NotFoundError, BadRequestError } from '../../src/utils/AppError';
+
+// Mock logger
+jest.mock('../../src/utils/logger', () => ({
+ logger: {
+ warn: jest.fn(),
+ error: jest.fn(),
+ },
+}));
+
+import { logger } from '../../src/utils/logger';
+
+const mockLogger = logger as jest.Mocked<typeof logger>;
+
+describe('errorHandlerMiddleware', () => {
+ let req: Partial<Request>;
+ let res: Partial<Response>;
+ let next: NextFunction;
+ let jsonFn: jest.Mock;
+ let statusFn: jest.Mock;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ jsonFn = jest.fn();
+ statusFn = jest.fn().mockReturnValue({ json: jsonFn });
+
+ req = { path: '/test-path' };
+ res = { status: statusFn } as Partial<Response>;
+ next = jest.fn();
+ });
+
+ it('should return correct statusCode and json for AppError', () => {
+ const error = new AppError(422, 'Unprocessable Entity');
+
+ errorHandlerMiddleware(error, req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(422);
+ expect(jsonFn).toHaveBeenCalledWith({
+ success: false,
+ error: 'Unprocessable Entity',
+ });
+ });
+
+ it('should return 404 for NotFoundError', () => {
+ const error = new NotFoundError('Resource not found');
+
+ errorHandlerMiddleware(error, req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(404);
+ expect(jsonFn).toHaveBeenCalledWith({
+ success: false,
+ error: 'Resource not found',
+ });
+ });
+
+ it('should return 400 for BadRequestError', () => {
+ const error = new BadRequestError('Invalid input');
+
+ errorHandlerMiddleware(error, req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(400);
+ expect(jsonFn).toHaveBeenCalledWith({
+ success: false,
+ error: 'Invalid input',
+ });
+ });
+
+ it('should return 500 with "Internal Server Error" for generic Error', () => {
+ const error = new Error('Something went wrong');
+
+ errorHandlerMiddleware(error, req as Request, res as Response, next);
+
+ expect(statusFn).toHaveBeenCalledWith(500);
+ expect(jsonFn).toHaveBeenCalledWith({
+ success: false,
+ error: 'Internal Server Error',
+ });
+ });
+
+ it('should call logger.warn for AppError', () => {
+ const error = new AppError(403, 'Forbidden');
+
+ errorHandlerMiddleware(error, req as Request, res as Response, next);
+
+ expect(mockLogger.warn).toHaveBeenCalledWith({
+ module: 'ErrorHandler',
+ statusCode: 403,
+ message: 'Forbidden',
+ path: '/test-path',
+ });
+ expect(mockLogger.error).not.toHaveBeenCalled();
+ });
+
+ it('should call logger.error for generic Error', () => {
+ const error = new Error('Unexpected failure');
+
+ errorHandlerMiddleware(error, req as Request, res as Response, next);
+
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ expect.objectContaining({
+ module: 'ErrorHandler',
+ path: '/test-path',
+ }),
+ 'An unexpected error occurred'
+ );
+ expect(mockLogger.warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/__tests__/middlewares/versionMiddleware.test.ts b/backend/__tests__/middlewares/versionMiddleware.test.ts
new file mode 100644
index 0000000..6098405
--- /dev/null
+++ b/backend/__tests__/middlewares/versionMiddleware.test.ts
@@ -0,0 +1,37 @@
+import versionMiddleware from '../../src/middlewares/versionMiddleware';
+import { getInstallType } from '../../src/utils/installHelpers';
+
+jest.mock('../../src/utils/installHelpers', () => ({
+ getInstallType: jest.fn().mockReturnValue('dev'),
+}));
+
+describe('versionMiddleware', () => {
+ const req = {} as any;
+ const res = { setHeader: jest.fn() } as any;
+ const next = jest.fn();
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('sets X-App-Version header', () => {
+ versionMiddleware(req, res, next);
+ expect(res.setHeader).toHaveBeenCalledWith('X-App-Version', expect.any(String));
+ });
+
+ it('sets X-Server-OS header to process.platform', () => {
+ versionMiddleware(req, res, next);
+ expect(res.setHeader).toHaveBeenCalledWith('X-Server-OS', process.platform);
+ });
+
+ it('sets X-Install-Type header using getInstallType()', () => {
+ versionMiddleware(req, res, next);
+ expect(res.setHeader).toHaveBeenCalledWith('X-Install-Type', 'dev');
+ expect(getInstallType).toHaveBeenCalled();
+ });
+
+ it('calls next()', () => {
+ versionMiddleware(req, res, next);
+ expect(next).toHaveBeenCalled();
+ });
+});
diff --git a/backend/__tests__/notifications/BackupFailedNotification.test.ts b/backend/__tests__/notifications/BackupFailedNotification.test.ts
index 6a901cc..f98e748 100644
--- a/backend/__tests__/notifications/BackupFailedNotification.test.ts
+++ b/backend/__tests__/notifications/BackupFailedNotification.test.ts
@@ -1,12 +1,10 @@
import { BackupFailedNotification } from '../../src/notifications/templates/email/backup/BackupFailedNotification';
import { Plan } from '../../src/db/schema/plans';
import { configService } from '../../src/services/ConfigService';
-import fs from 'fs';
-import path from 'path';
+import { loadBackupTemplate } from '../../src/notifications/templateLoader';
import ejs from 'ejs';
// Mock dependencies
-jest.mock('fs');
jest.mock('ejs');
jest.mock('../../src/services/ConfigService', () => ({
configService: {
@@ -19,7 +17,6 @@ jest.mock('../../src/services/ConfigService', () => ({
describe('BackupFailedNotification', () => {
let mockPlan: Plan;
- const mockReadFileSync = fs.readFileSync as jest.MockedFunction<typeof fs.readFileSync>;
const mockEjsRender = ejs.render as jest.MockedFunction<typeof ejs.render>;
beforeEach(() => {
@@ -36,7 +33,6 @@ describe('BackupFailedNotification', () => {
storagePath: '/backup/path',
} as any;
- mockReadFileSync.mockReturnValue('<div>{{EMAIL_BODY_CONTENT}}</div>');
mockEjsRender.mockReturnValue('<div>Failed content</div>');
});
@@ -179,17 +175,7 @@ describe('BackupFailedNotification', () => {
error: 'Error message',
});
- const expectedPath = path.join(
- process.cwd(),
- 'src',
- 'notifications',
- 'templates',
- 'email',
- 'backup',
- 'BackupFailedNotification.ejs'
- );
-
- expect(mockReadFileSync).toHaveBeenCalledWith(expectedPath, 'utf-8');
+ expect(loadBackupTemplate).toHaveBeenCalledWith('BackupFailedNotification.ejs');
expect(mockEjsRender).toHaveBeenCalled();
});
diff --git a/backend/__tests__/notifications/BackupStartedNotification.test.ts b/backend/__tests__/notifications/BackupStartedNotification.test.ts
index 1983c68..f3c9066 100644
--- a/backend/__tests__/notifications/BackupStartedNotification.test.ts
+++ b/backend/__tests__/notifications/BackupStartedNotification.test.ts
@@ -1,12 +1,10 @@
import { BackupStartedNotification } from '../../src/notifications/templates/email/backup/BackupStartedNotification';
import { Plan } from '../../src/db/schema/plans';
import { configService } from '../../src/services/ConfigService';
-import fs from 'fs';
-import path from 'path';
+import { loadBackupTemplate } from '../../src/notifications/templateLoader';
import ejs from 'ejs';
// Mock dependencies
-jest.mock('fs');
jest.mock('ejs');
jest.mock('../../src/services/ConfigService', () => ({
configService: {
@@ -19,7 +17,6 @@ jest.mock('../../src/services/ConfigService', () => ({
describe('BackupStartedNotification', () => {
let mockPlan: Plan;
- const mockReadFileSync = fs.readFileSync as jest.MockedFunction<typeof fs.readFileSync>;
const mockEjsRender = ejs.render as jest.MockedFunction<typeof ejs.render>;
beforeEach(() => {
@@ -36,7 +33,6 @@ describe('BackupStartedNotification', () => {
storagePath: '/backup/path',
} as any;
- mockReadFileSync.mockReturnValue('<div>{{EMAIL_BODY_CONTENT}}</div>');
mockEjsRender.mockReturnValue('<div>Rendered content</div>');
});
@@ -195,17 +191,7 @@ describe('BackupStartedNotification', () => {
startTime: new Date(),
});
- const expectedPath = path.join(
- process.cwd(),
- 'src',
- 'notifications',
- 'templates',
- 'email',
- 'backup',
- 'BackupStartedNotification.ejs'
- );
-
- expect(mockReadFileSync).toHaveBeenCalledWith(expectedPath, 'utf-8');
+ expect(loadBackupTemplate).toHaveBeenCalledWith('BackupStartedNotification.ejs');
expect(mockEjsRender).toHaveBeenCalled();
});
diff --git a/backend/__tests__/notifications/BackupSuccessNotification.test.ts b/backend/__tests__/notifications/BackupSuccessNotification.test.ts
index a4b146e..1b12e76 100644
--- a/backend/__tests__/notifications/BackupSuccessNotification.test.ts
+++ b/backend/__tests__/notifications/BackupSuccessNotification.test.ts
@@ -1,12 +1,10 @@
import { BackupSuccessNotification } from '../../src/notifications/templates/email/backup/BackupSuccessNotification';
import { Plan } from '../../src/db/schema/plans';
import { configService } from '../../src/services/ConfigService';
-import fs from 'fs';
-import path from 'path';
+import { loadBackupTemplate } from '../../src/notifications/templateLoader';
import ejs from 'ejs';
// Mock dependencies
-jest.mock('fs');
jest.mock('ejs');
jest.mock('../../src/services/ConfigService', () => ({
configService: {
@@ -19,7 +17,6 @@ jest.mock('../../src/services/ConfigService', () => ({
describe('BackupSuccessNotification', () => {
let mockPlan: Plan;
- const mockReadFileSync = fs.readFileSync as jest.MockedFunction<typeof fs.readFileSync>;
const mockEjsRender = ejs.render as jest.MockedFunction<typeof ejs.render>;
beforeEach(() => {
@@ -36,7 +33,6 @@ describe('BackupSuccessNotification', () => {
storagePath: '/backup/path',
} as any;
- mockReadFileSync.mockReturnValue('<div>{{EMAIL_BODY_CONTENT}}</div>');
mockEjsRender.mockReturnValue('<div>Success content</div>');
});
@@ -156,17 +152,7 @@ describe('BackupSuccessNotification', () => {
endTime: new Date(),
});
- const expectedPath = path.join(
- process.cwd(),
- 'src',
- 'notifications',
- 'templates',
- 'email',
- 'backup',
- 'BackupSuccessNotification.ejs'
- );
-
- expect(mockReadFileSync).toHaveBeenCalledWith(expectedPath, 'utf-8');
+ expect(loadBackupTemplate).toHaveBeenCalledWith('BackupSuccessNotification.ejs');
expect(mockEjsRender).toHaveBeenCalled();
});
diff --git a/backend/__tests__/notifications/BaseNotification.test.ts b/backend/__tests__/notifications/BaseNotification.test.ts
index 4e1c883..d430577 100644
--- a/backend/__tests__/notifications/BaseNotification.test.ts
+++ b/backend/__tests__/notifications/BaseNotification.test.ts
@@ -1,10 +1,8 @@
import { BaseNotification } from '../../src/notifications/BaseNotification';
import { configService } from '../../src/services/ConfigService';
-import fs from 'fs';
-import path from 'path';
+import { loadEmailWrapperTemplate } from '../../src/notifications/templateLoader';
// Mock dependencies
-jest.mock('fs');
jest.mock('../../src/services/ConfigService', () => ({
configService: {
config: {
@@ -43,7 +41,7 @@ class TestNotification extends BaseNotification {
describe('BaseNotification', () => {
let notification: TestNotification;
- const mockReadFileSync = fs.readFileSync as jest.MockedFunction<typeof fs.readFileSync>;
+ const mockLoadEmailWrapperTemplate = loadEmailWrapperTemplate as jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
@@ -102,55 +100,38 @@ describe('BaseNotification', () => {
describe('loadEmailTemplate', () => {
it('should load email template successfully', () => {
const mockTemplate = '<html><body>{{EMAIL_BODY_CONTENT}}</body></html>';
- mockReadFileSync.mockReturnValue(mockTemplate);
+ mockLoadEmailWrapperTemplate.mockReturnValue(mockTemplate);
const result = notification.testLoadEmailTemplate();
expect(result).toBe(mockTemplate);
- expect(mockReadFileSync).toHaveBeenCalledWith(
- expect.stringContaining('base-email.html'),
- 'utf-8'
- );
+ expect(mockLoadEmailWrapperTemplate).toHaveBeenCalled();
});
- it('should return empty string on file read error', () => {
- mockReadFileSync.mockImplementation(() => {
- throw new Error('File not found');
- });
+ it('should return empty string when template is not available', () => {
+ mockLoadEmailWrapperTemplate.mockReturnValue('');
const result = notification.testLoadEmailTemplate();
expect(result).toBe('');
});
- it('should use correct template path', () => {
+ it('should delegate to loadEmailWrapperTemplate', () => {
const mockTemplate = '<html>Template</html>';
- mockReadFileSync.mockReturnValue(mockTemplate);
+ mockLoadEmailWrapperTemplate.mockReturnValue(mockTemplate);
notification.testLoadEmailTemplate();
- const expectedPath = path.join(
- process.cwd(),
- 'src',
- 'notifications',
- 'templates',
- 'email',
- 'base-email.html'
- );
- expect(mockReadFileSync).toHaveBeenCalledWith(expectedPath, 'utf-8');
+ expect(mockLoadEmailWrapperTemplate).toHaveBeenCalled();
});
- it('should handle different error types', () => {
- mockReadFileSync.mockImplementation(() => {
- throw new Error('Permission denied');
- });
+ it('should handle template loader returning empty', () => {
+ mockLoadEmailWrapperTemplate.mockReturnValue('');
const result = notification.testLoadEmailTemplate();
expect(result).toBe('');
- mockReadFileSync.mockImplementation(() => {
- throw new Error('ENOENT');
- });
+ mockLoadEmailWrapperTemplate.mockReturnValue('');
const result2 = notification.testLoadEmailTemplate();
expect(result2).toBe('');
@@ -171,7 +152,7 @@ describe('BaseNotification', () => {
`;
beforeEach(() => {
- mockReadFileSync.mockReturnValue(mockTemplate);
+ mockLoadEmailWrapperTemplate.mockReturnValue(mockTemplate);
});
it('should replace all placeholders correctly', () => {
@@ -227,7 +208,7 @@ describe('BaseNotification', () => {
});
it('should return original content if template loading fails', () => {
- mockReadFileSync.mockReturnValue('');
+ mockLoadEmailWrapperTemplate.mockReturnValue('');
const content = '<p>Original content</p>';
const data = { appTitle: 'App' };
diff --git a/backend/__tests__/notifications/NotificationManager.test.ts b/backend/__tests__/notifications/NotificationManager.test.ts
index 1ba28ba..8a783c5 100644
--- a/backend/__tests__/notifications/NotificationManager.test.ts
+++ b/backend/__tests__/notifications/NotificationManager.test.ts
@@ -115,7 +115,7 @@ describe('NotificationManager', () => {
const duration = endTime - startTime;
// Should complete in ~100ms (parallel) not ~200ms (sequential)
- expect(duration).toBeLessThan(150);
+ expect(duration).toBeLessThan(300);
});
it('should handle channel send failures gracefully', async () => {
diff --git a/backend/__tests__/routes/plans.test.ts b/backend/__tests__/routes/plans.test.ts
index a6081b7..1533071 100644
--- a/backend/__tests__/routes/plans.test.ts
+++ b/backend/__tests__/routes/plans.test.ts
@@ -54,7 +54,7 @@ describe('Plan Routes', () => {
deletePlan: jest.fn(),
getPlanLogs: jest.fn(),
downloadPlanLogs: jest.fn(),
- checkActiveBackups: jest.fn(),
+ checkActiveBackupsOrRestore: jest.fn(),
performBackup: jest.fn(),
resumeBackup: jest.fn(),
pauseBackup: jest.fn(),
@@ -230,12 +230,12 @@ describe('Plan Routes', () => {
describe('GET /api/plans/:id/checkactive', () => {
it('should check active backups for a plan when authenticated', async () => {
- mockPlanService.checkActiveBackups.mockResolvedValue({ active: false } as any);
+ mockPlanService.checkActiveBackupsOrRestore.mockResolvedValue(false);
const response = await request(app).get('/api/plans/plan-1/checkactive');
expect(response.status).toBe(200);
- expect(mockPlanService.checkActiveBackups).toHaveBeenCalledWith('plan-1');
+ expect(mockPlanService.checkActiveBackupsOrRestore).toHaveBeenCalledWith('plan-1', 'backup');
});
});
diff --git a/backend/__tests__/services/BackupServices.test.ts b/backend/__tests__/services/BackupServices.test.ts
index 2a0f610..a4de649 100644
--- a/backend/__tests__/services/BackupServices.test.ts
+++ b/backend/__tests__/services/BackupServices.test.ts
@@ -67,8 +67,7 @@ describe('BackupService', () => {
mockPlanStore,
mockBackupStore,
mockRestoreStore,
- mockStorageStore,
- null // broker is not used for local strategies
+ mockStorageStore
);
});
diff --git a/backend/__tests__/services/ConfigService.test.ts b/backend/__tests__/services/ConfigService.test.ts
index 7980d60..f1e7001 100644
--- a/backend/__tests__/services/ConfigService.test.ts
+++ b/backend/__tests__/services/ConfigService.test.ts
@@ -1,10 +1,12 @@
-import { jest, beforeEach, afterEach, describe, it, expect } from '@jest/globals';
import * as fs from 'fs';
// Create mock functions
-const mockExistsSync = jest.fn<typeof fs.existsSync>();
-const mockReadFileSync = jest.fn<typeof fs.readFileSync>();
-const mockGetConfigDir = jest.fn<() => string>();
+const mockExistsSync = jest.fn() as jest.MockedFunction<typeof fs.existsSync>;
+const mockReadFileSync = jest.fn() as jest.MockedFunction<typeof fs.readFileSync>;
+const mockWriteFileSync = jest.fn();
+const mockMkdirSync = jest.fn();
+const mockGetConfigDir = jest.fn() as jest.MockedFunction<() => string>;
+const mockGetDataDir = jest.fn() as jest.MockedFunction<() => string>;
const mockDotenvConfig = jest.fn();
// Mock fs module
@@ -12,12 +14,15 @@ jest.mock('fs', () => ({
...jest.requireActual<typeof fs>('fs'),
existsSync: mockExistsSync,
readFileSync: mockReadFileSync,
+ writeFileSync: mockWriteFileSync,
+ mkdirSync: mockMkdirSync,
}));
// Mock AppPaths
jest.mock('../../src/utils/AppPaths', () => ({
appPaths: {
getConfigDir: mockGetConfigDir,
+ getDataDir: mockGetDataDir,
},
}));
@@ -64,11 +69,15 @@ describe('ConfigService', () => {
// Reset mocks
mockExistsSync.mockReset();
mockReadFileSync.mockReset();
+ mockWriteFileSync.mockReset();
+ mockMkdirSync.mockReset();
mockDotenvConfig.mockReset();
mockGetConfigDir.mockReset();
+ mockGetDataDir.mockReset();
// Mock appPaths to return a predictable directory
mockGetConfigDir.mockReturnValue('/fake/config/dir');
+ mockGetDataDir.mockReturnValue('/fake/data/dir');
// Clear the module cache to reset the singleton
jest.resetModules();
@@ -153,12 +162,12 @@ describe('ConfigService', () => {
// Arrange: Deliberately omit a required variable
process.env = {
NODE_ENV: 'production',
- ENCRYPTION_KEY: validBaseEnv.ENCRYPTION_KEY,
+ SECRET: validBaseEnv.SECRET,
APIKEY: validBaseEnv.APIKEY,
USER_NAME: validBaseEnv.USER_NAME,
USER_PASSWORD: validBaseEnv.USER_PASSWORD,
APP_TITLE: validBaseEnv.APP_TITLE,
- }; // SECRET is missing
+ }; // ENCRYPTION_KEY is missing
mockExistsSync.mockReturnValue(false);
// Act & Assert
@@ -167,7 +176,7 @@ describe('ConfigService', () => {
expect(mockConsoleError).toHaveBeenCalledWith(
expect.stringContaining('Invalid environment configuration')
);
- expect(mockConsoleError).toHaveBeenCalledWith(expect.stringContaining('SECRET'));
+ expect(mockConsoleError).toHaveBeenCalledWith(expect.stringContaining('ENCRYPTION_KEY'));
});
it('should exit the process for invalid data types', async () => {
@@ -232,8 +241,6 @@ describe('ConfigService', () => {
// Assert
expect(configService.isDevelopment()).toBe(true);
- // Verify dotenv.config() was called in development mode
- expect(mockDotenvConfig).toHaveBeenCalled();
});
it("should return false when NODE_ENV is 'production'", async () => {
@@ -246,8 +253,6 @@ describe('ConfigService', () => {
// Assert
expect(configService.isDevelopment()).toBe(false);
- // Verify dotenv.config() was NOT called in production mode
- expect(mockDotenvConfig).not.toHaveBeenCalled();
});
});
});
diff --git a/backend/__tests__/services/DeviceService.test.ts b/backend/__tests__/services/DeviceService.test.ts
index 218d977..2c8b5b7 100644
--- a/backend/__tests__/services/DeviceService.test.ts
+++ b/backend/__tests__/services/DeviceService.test.ts
@@ -24,7 +24,6 @@ describe('DeviceService', () => {
let mockSystemManager: jest.Mocked<BaseSystemManager>;
let mockLocalStrategy: jest.Mocked<LocalStrategy>;
let mockRemoteStrategy: jest.Mocked<RemoteStrategy>;
- const mockBroker = {}; // A placeholder for the broker if needed
beforeEach(() => {
jest.clearAllMocks();
@@ -37,10 +36,7 @@ describe('DeviceService', () => {
// Mock strategy constructors and instances
mockLocalStrategy = new LocalStrategy(mockSystemManager) as jest.Mocked<LocalStrategy>;
- mockRemoteStrategy = new RemoteStrategy(
- mockBroker,
- 'remote-device'
- ) as jest.Mocked<RemoteStrategy>;
+ mockRemoteStrategy = new RemoteStrategy('remote-device') as jest.Mocked<RemoteStrategy>;
(LocalStrategy as jest.Mock).mockReturnValue(mockLocalStrategy);
(RemoteStrategy as jest.Mock).mockReturnValue(mockRemoteStrategy);
@@ -49,8 +45,7 @@ describe('DeviceService', () => {
mockSystemManager,
mockDeviceStore,
mockPlanStore,
- mockStorageStore,
- mockBroker
+ mockStorageStore
);
// Set a mock for connected devices
diff --git a/backend/__tests__/services/DownloadEventService.test.ts b/backend/__tests__/services/DownloadEventService.test.ts
new file mode 100644
index 0000000..1116a26
--- /dev/null
+++ b/backend/__tests__/services/DownloadEventService.test.ts
@@ -0,0 +1,196 @@
+process.env.APP_TITLE = 'Pluton Test';
+process.env.SECRET = 'a-super-secret-key-for-testing-123';
+process.env.ENCRYPTION_KEY = 'an-encryption-key-for-testing-456';
+process.env.APIKEY = 'an-api-key-for-testing-and-so-on-789';
+process.env.USER_NAME = 'testUser';
+process.env.USER_PASSWORD = 'testPassword';
+
+import { DownloadEventService } from '../../src/services/events/DownloadEventService';
+import { BackupStore } from '../../src/stores/BackupStore';
+import { BaseSnapshotManager } from '../../src/managers/BaseSnapshotManager';
+import {
+ DownloadStartEvent,
+ DownloadErrorEvent,
+ DownloadCompleteEvent,
+} from '../../src/types/events';
+
+jest.mock('../../src/db/index', () => ({
+ db: {
+ select: jest.fn(),
+ insert: jest.fn(),
+ update: jest.fn(),
+ delete: jest.fn(),
+ },
+}));
+
+// Mock all dependencies
+jest.mock('../../src/stores/BackupStore');
+
+// Mock the logger to prevent file I/O during tests and allow spying on log calls
+jest.mock('../../src/utils/logger', () => ({
+ planLogger: jest.fn().mockReturnValue({
+ info: jest.fn(),
+ error: jest.fn(),
+ warn: jest.fn(),
+ }),
+}));
+
+describe('DownloadEventService', () => {
+ let downloadEventService: DownloadEventService;
+ let mockBackupStore: jest.Mocked<BackupStore>;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ mockBackupStore = new BackupStore(null as any) as jest.Mocked<BackupStore>;
+ mockBackupStore.update = jest.fn();
+ mockBackupStore.getById = jest.fn();
+
+ downloadEventService = new DownloadEventService(mockBackupStore);
+ });
+
+ describe('onDownloadStart', () => {
+ const planId = 'plan-123';
+ const backupId = 'backup-abc';
+ const startEvent: DownloadStartEvent = { planId, backupId };
+
+ it('should update backup with started download status', async () => {
+ // Arrange
+ mockBackupStore.update.mockResolvedValue({} as any);
+
+ // Act
+ await downloadEventService.onDownloadStart(startEvent);
+
+ // Assert
+ expect(mockBackupStore.update).toHaveBeenCalledWith(backupId, {
+ download: {
+ status: 'started',
+ started: expect.any(Number),
+ },
+ });
+ });
+
+ it('should log an error and not throw if backupStore.update fails', async () => {
+ // Arrange
+ mockBackupStore.update.mockRejectedValue(new Error('DB write failed'));
+
+ // Act & Assert — should not throw
+ await expect(downloadEventService.onDownloadStart(startEvent)).resolves.toBeUndefined();
+ });
+ });
+
+ describe('onDownloadError', () => {
+ const planId = 'plan-123';
+ const backupId = 'backup-abc';
+ const errorMsg = 'Download timed out';
+ const errorEvent: DownloadErrorEvent = { planId, backupId, error: errorMsg };
+
+ it('should get backup by id and update with failed download status', async () => {
+ // Arrange
+ const existingBackup = {
+ id: backupId,
+ download: { status: 'started', started: 1000 },
+ };
+ mockBackupStore.getById.mockResolvedValue(existingBackup as any);
+ mockBackupStore.update.mockResolvedValue({} as any);
+
+ // Act
+ await downloadEventService.onDownloadError(errorEvent);
+
+ // Assert
+ expect(mockBackupStore.getById).toHaveBeenCalledWith(backupId);
+ expect(mockBackupStore.update).toHaveBeenCalledWith(backupId, {
+ download: {
+ ...existingBackup.download,
+ status: 'failed',
+ error: errorMsg,
+ ended: expect.any(Number),
+ },
+ });
+ });
+
+ it('should handle missing backup gracefully (backup is null)', async () => {
+ // Arrange
+ mockBackupStore.getById.mockResolvedValue(null);
+ mockBackupStore.update.mockResolvedValue({} as any);
+
+ // Act
+ await downloadEventService.onDownloadError(errorEvent);
+
+ // Assert
+ expect(mockBackupStore.getById).toHaveBeenCalledWith(backupId);
+ expect(mockBackupStore.update).toHaveBeenCalledWith(backupId, {
+ download: {
+ status: 'failed',
+ error: errorMsg,
+ ended: expect.any(Number),
+ },
+ });
+ });
+
+ it('should log an error and not throw if an exception occurs', async () => {
+ // Arrange
+ mockBackupStore.getById.mockRejectedValue(new Error('DB read failed'));
+
+ // Act & Assert — should not throw
+ await expect(downloadEventService.onDownloadError(errorEvent)).resolves.toBeUndefined();
+ });
+ });
+
+ describe('onDownloadComplete', () => {
+ const planId = 'plan-123';
+ const backupId = 'backup-abc';
+ const completeEvent: DownloadCompleteEvent = { planId, backupId, success: true };
+
+ it('should get backup by id and update with complete download status', async () => {
+ // Arrange
+ const existingBackup = {
+ id: backupId,
+ download: { status: 'started', started: 1000 },
+ };
+ mockBackupStore.getById.mockResolvedValue(existingBackup as any);
+ mockBackupStore.update.mockResolvedValue({} as any);
+
+ // Act
+ await downloadEventService.onDownloadComplete(completeEvent);
+
+ // Assert
+ expect(mockBackupStore.getById).toHaveBeenCalledWith(backupId);
+ expect(mockBackupStore.update).toHaveBeenCalledWith(backupId, {
+ download: {
+ ...existingBackup.download,
+ status: 'complete',
+ error: '',
+ ended: expect.any(Number),
+ },
+ });
+ });
+
+ it('should handle missing backup gracefully (backup is null)', async () => {
+ // Arrange
+ mockBackupStore.getById.mockResolvedValue(null);
+ mockBackupStore.update.mockResolvedValue({} as any);
+
+ // Act
+ await downloadEventService.onDownloadComplete(completeEvent);
+
+ // Assert
+ expect(mockBackupStore.getById).toHaveBeenCalledWith(backupId);
+ expect(mockBackupStore.update).toHaveBeenCalledWith(backupId, {
+ download: {
+ status: 'complete',
+ error: '',
+ ended: expect.any(Number),
+ },
+ });
+ });
+
+ it('should log an error and not throw if an exception occurs', async () => {
+ // Arrange
+ mockBackupStore.getById.mockRejectedValue(new Error('DB read failed'));
+
+ // Act & Assert — should not throw
+ await expect(downloadEventService.onDownloadComplete(completeEvent)).resolves.toBeUndefined();
+ });
+ });
+});
diff --git a/backend/__tests__/services/PlanService.test.ts b/backend/__tests__/services/PlanService.test.ts
index ae17985..d81ed95 100644
--- a/backend/__tests__/services/PlanService.test.ts
+++ b/backend/__tests__/services/PlanService.test.ts
@@ -5,6 +5,7 @@ import { PlanService } from '../../src/services/PlanService';
import { PlanStore } from '../../src/stores/PlanStore';
import { StorageStore } from '../../src/stores/StorageStore';
import { DeviceStore } from '../../src/stores/DeviceStore';
+import { RestoreStore } from '../../src/stores/RestoreStore';
import { BaseBackupManager } from '../../src/managers/BaseBackupManager';
import { NewPlanReq, PlanBackupSettings } from '../../src/types/plans';
import { NotFoundError } from '../../src/utils/AppError';
@@ -15,6 +16,7 @@ jest.mock('../../src/stores/PlanStore');
jest.mock('../../src/stores/StorageStore');
jest.mock('../../src/stores/DeviceStore');
jest.mock('../../src/managers/BaseBackupManager');
+jest.mock('../../src/stores/RestoreStore');
// We also need to mock the strategy that gets instantiated inside the service
jest.mock('../../src/strategies/backup/LocalStrategy');
@@ -27,6 +29,7 @@ describe('PlanService', () => {
let mockBackupStore: jest.Mocked<BackupStore>;
let mockStorageStore: jest.Mocked<StorageStore>;
let mockDeviceStore: jest.Mocked<DeviceStore>;
+ let mockRestoreStore: jest.Mocked<RestoreStore>;
let mockLocalAgent: jest.Mocked<BaseBackupManager>;
let mockStrategy: jest.Mocked<LocalStrategy>;
@@ -46,9 +49,11 @@ describe('PlanService', () => {
mockStorageStore = new StorageStore(null as any) as jest.Mocked<StorageStore>;
mockBackupStore = new BackupStore(null as any) as jest.Mocked<BackupStore>;
mockDeviceStore = new DeviceStore(null as any) as jest.Mocked<DeviceStore>;
+ mockRestoreStore = new RestoreStore(null as any) as jest.Mocked<RestoreStore>;
mockLocalAgent = new BaseBackupManager() as jest.Mocked<BaseBackupManager>;
mockBackupStore.deleteByPlanId = jest.fn();
+ mockRestoreStore.deleteByPlanId = jest.fn();
// The service instantiates the strategy, so we need to mock its constructor and methods
mockStrategy = new LocalStrategy(mockLocalAgent) as jest.Mocked<LocalStrategy>;
@@ -60,7 +65,7 @@ describe('PlanService', () => {
mockBackupStore,
mockStorageStore,
mockDeviceStore,
- null as any
+ mockRestoreStore
);
});
@@ -501,7 +506,7 @@ describe('PlanService', () => {
// -------------------------------
// Tests for checking active backups
// -------------------------------
- describe('checkActiveBackups', () => {
+ describe('checkActiveBackupsOrRestore', () => {
const planId = 'plan-456';
it('should return true if the store reports active backups', async () => {
@@ -509,7 +514,7 @@ describe('PlanService', () => {
mockPlanStore.hasActiveBackups.mockResolvedValue(true);
// Act
- const result = await planService.checkActiveBackups(planId);
+ const result = await planService.checkActiveBackupsOrRestore(planId, 'backup');
// Assert
expect(mockPlanStore.hasActiveBackups).toHaveBeenCalledWith(planId);
@@ -521,7 +526,7 @@ describe('PlanService', () => {
mockPlanStore.hasActiveBackups.mockResolvedValue(false);
// Act
- const result = await planService.checkActiveBackups(planId);
+ const result = await planService.checkActiveBackupsOrRestore(planId, 'backup');
// Assert
expect(mockPlanStore.hasActiveBackups).toHaveBeenCalledWith(planId);
diff --git a/backend/__tests__/services/RestoreService.test.ts b/backend/__tests__/services/RestoreService.test.ts
index 80732c2..c0f20e4 100644
--- a/backend/__tests__/services/RestoreService.test.ts
+++ b/backend/__tests__/services/RestoreService.test.ts
@@ -51,8 +51,7 @@ describe('RestoreService', () => {
mockPlanStore,
mockBackupStore,
mockRestoreStore,
- mockStorageStore,
- null // broker
+ mockStorageStore
);
});
diff --git a/backend/__tests__/services/StorageService.test.ts b/backend/__tests__/services/StorageService.test.ts
index 53e4a9d..16e1855 100644
--- a/backend/__tests__/services/StorageService.test.ts
+++ b/backend/__tests__/services/StorageService.test.ts
@@ -55,7 +55,7 @@ describe('StorageService', () => {
// Mock strategy constructors and instances
mockLocalStrategy = new LocalStrategy(mockSystemManager) as jest.Mocked<LocalStrategy>;
- mockRemoteStrategy = new RemoteStrategy(null, 'remote-device') as jest.Mocked<RemoteStrategy>;
+ mockRemoteStrategy = new RemoteStrategy('remote-device') as jest.Mocked<RemoteStrategy>;
(LocalStrategy as jest.Mock).mockReturnValue(mockLocalStrategy);
(RemoteStrategy as jest.Mock).mockReturnValue(mockRemoteStrategy);
@@ -67,15 +67,14 @@ describe('StorageService', () => {
encrypt: jest.fn(val => `encrypted(${val})`),
decrypt: jest.fn(val => val.replace('encrypted(', '').replace(')', '')),
} as any;
- (Cryptr as jest.Mock).mockImplementation(() => mockCryptr);
+ (Cryptr as unknown as jest.Mock).mockImplementation(() => mockCryptr);
// Instantiate the service with mocked dependencies
storageService = new StorageService(
mockStorageManager,
mockSystemManager,
mockStorageStore,
- mockPlanStore,
- null // broker
+ mockPlanStore
);
});
diff --git a/backend/__tests__/services/listeners/BackupEventListener.test.ts b/backend/__tests__/services/listeners/BackupEventListener.test.ts
new file mode 100644
index 0000000..880344f
--- /dev/null
+++ b/backend/__tests__/services/listeners/BackupEventListener.test.ts
@@ -0,0 +1,194 @@
+import { EventEmitter } from 'events';
+import { BackupEventListener } from '../../../src/services/listeners/BackupEventListener';
+import { BaseBackupManager } from '../../../src/managers/BaseBackupManager';
+import { PlanStore } from '../../../src/stores/PlanStore';
+import { BackupStore } from '../../../src/stores/BackupStore';
+import { BackupEventService } from '../../../src/services/events/BackupEventService';
+import {
+ BackupStartEvent,
+ BackupCompleteEvent,
+ BackupErrorEvent,
+ BackupStatUpdateEvent,
+ PruneEndEvent,
+} from '../../../src/types/events';
+
+// Mock dependencies
+jest.mock('../../../src/db/index', () => ({
+ db: { select: jest.fn(), insert: jest.fn(), update: jest.fn(), delete: jest.fn() },
+}));
+jest.mock('../../../src/services/ConfigService', () => ({
+ configService: {
+ config: { SECRET: 'test-secret', APIKEY: 'test-key' },
+ },
+}));
+jest.mock('../../../src/managers/BaseBackupManager');
+jest.mock('../../../src/stores/PlanStore');
+jest.mock('../../../src/stores/BackupStore');
+jest.mock('../../../src/services/events/BackupEventService', () => ({
+ BackupEventService: jest.fn(),
+}));
+jest.mock('../../../src/utils/AppPaths', () => ({
+ appPaths: {
+ getProgressDir: jest.fn().mockReturnValue('/mock/progress'),
+ getConfigDir: jest.fn().mockReturnValue('/mock/config'),
+ getDataDir: jest.fn().mockReturnValue('/mock/data'),
+ getLogsDir: jest.fn().mockReturnValue('/mock/logs'),
+ getDbDir: jest.fn().mockReturnValue('/mock/db'),
+ },
+}));
+jest.mock('../../../src/jobs/JobProcessor', () => {
+ const emitter = new (require('events').EventEmitter)();
+ return {
+ jobProcessor: Object.assign(emitter, {
+ __test_emitter: true,
+ }),
+ };
+});
+jest.mock('../../../src/utils/logger', () => ({
+ planLogger: jest.fn().mockReturnValue({
+ info: jest.fn(),
+ error: jest.fn(),
+ warn: jest.fn(),
+ }),
+}));
+
+// Re-import jobProcessor after mock so we can emit on it
+import { jobProcessor } from '../../../src/jobs/JobProcessor';
+
+describe('BackupEventListener', () => {
+ let localAgent: EventEmitter;
+ let mockPlanStore: jest.Mocked<PlanStore>;
+ let mockBackupStore: jest.Mocked<BackupStore>;
+ let mockBackupEventService: jest.Mocked<BackupEventService>;
+ let listener: BackupEventListener;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ // Use a real EventEmitter as the localAgent so we can emit events
+ localAgent = new EventEmitter();
+
+ mockPlanStore = new PlanStore(null as any) as jest.Mocked<PlanStore>;
+ mockBackupStore = new BackupStore(null as any) as jest.Mocked<BackupStore>;
+
+ // Capture the mocked BackupEventService instance created inside the constructor
+ mockBackupEventService = {
+ onBackupStart: jest.fn().mockResolvedValue(undefined),
+ onBackupComplete: jest.fn().mockResolvedValue(undefined),
+ onBackupError: jest.fn().mockResolvedValue(undefined),
+ onBackupFailure: jest.fn().mockResolvedValue(undefined),
+ onBackupStatsUpdate: jest.fn().mockResolvedValue(undefined),
+ onPruneEnd: jest.fn().mockResolvedValue(undefined),
+ } as any;
+
+ (BackupEventService as jest.Mock).mockImplementation(() => mockBackupEventService);
+
+ listener = new BackupEventListener(localAgent as any, mockPlanStore, mockBackupStore);
+ });
+
+ describe('constructor', () => {
+ it('should create a BackupEventService instance', () => {
+ expect(BackupEventService).toHaveBeenCalledWith(mockPlanStore, mockBackupStore, localAgent);
+ });
+
+ it('should register event listeners on the localAgent', () => {
+ expect(localAgent.listenerCount('backup_start')).toBe(1);
+ expect(localAgent.listenerCount('backup_complete')).toBe(1);
+ expect(localAgent.listenerCount('backup_error')).toBe(1);
+ expect(localAgent.listenerCount('backup_stats_update')).toBe(1);
+ expect(localAgent.listenerCount('pruneEnd')).toBe(1);
+ });
+ });
+
+ describe('backup_start event', () => {
+ it('should delegate to backupEventService.onBackupStart', () => {
+ const event: BackupStartEvent = {
+ planId: 'plan-1',
+ backupId: 'backup-1',
+ summary: {} as any,
+ };
+
+ localAgent.emit('backup_start', event);
+
+ expect(mockBackupEventService.onBackupStart).toHaveBeenCalledWith(event);
+ expect(mockBackupEventService.onBackupStart).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('backup_complete event', () => {
+ it('should delegate to backupEventService.onBackupComplete', () => {
+ const event: BackupCompleteEvent = {
+ planId: 'plan-1',
+ backupId: 'backup-1',
+ success: true,
+ summary: {} as any,
+ };
+
+ localAgent.emit('backup_complete', event);
+
+ expect(mockBackupEventService.onBackupComplete).toHaveBeenCalledWith(event);
+ expect(mockBackupEventService.onBackupComplete).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('backup_error event', () => {
+ it('should delegate to backupEventService.onBackupError', () => {
+ const event: BackupErrorEvent = {
+ planId: 'plan-1',
+ backupId: 'backup-1',
+ error: 'Something went wrong',
+ };
+
+ localAgent.emit('backup_error', event);
+
+ expect(mockBackupEventService.onBackupError).toHaveBeenCalledWith(event);
+ expect(mockBackupEventService.onBackupError).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('backup_stats_update event', () => {
+ it('should delegate to backupEventService.onBackupStatsUpdate', () => {
+ const event: BackupStatUpdateEvent = {
+ planId: 'plan-1',
+ backupId: 'backup-1',
+ total_size: 1024,
+ snapshots: ['snap-1'],
+ };
+
+ localAgent.emit('backup_stats_update', event);
+
+ expect(mockBackupEventService.onBackupStatsUpdate).toHaveBeenCalledWith(event);
+ expect(mockBackupEventService.onBackupStatsUpdate).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('pruneEnd event', () => {
+ it('should delegate to backupEventService.onPruneEnd', () => {
+ const event: PruneEndEvent = {
+ planId: 'plan-1',
+ success: true,
+ stats: { total_size: 512, snapshots: ['snap-1'] },
+ };
+
+ localAgent.emit('pruneEnd', event);
+
+ expect(mockBackupEventService.onPruneEnd).toHaveBeenCalledWith(event);
+ expect(mockBackupEventService.onPruneEnd).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('backup_failed event (jobProcessor)', () => {
+ it('should delegate to backupEventService.onBackupFailure', () => {
+ const event = {
+ planId: 'plan-1',
+ backupId: 'backup-1',
+ error: 'Job permanently failed',
+ };
+
+ (jobProcessor as unknown as EventEmitter).emit('backup_failed', event);
+
+ expect(mockBackupEventService.onBackupFailure).toHaveBeenCalledWith(event);
+ expect(mockBackupEventService.onBackupFailure).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/backend/__tests__/services/listeners/DownloadEventListener.test.ts b/backend/__tests__/services/listeners/DownloadEventListener.test.ts
new file mode 100644
index 0000000..3d1c32a
--- /dev/null
+++ b/backend/__tests__/services/listeners/DownloadEventListener.test.ts
@@ -0,0 +1,107 @@
+import { EventEmitter } from 'events';
+import { DownloadEventListener } from '../../../src/services/listeners/DownloadEventListener';
+import { BaseSnapshotManager } from '../../../src/managers/BaseSnapshotManager';
+import { BackupStore } from '../../../src/stores/BackupStore';
+import { DownloadEventService } from '../../../src/services/events/DownloadEventService';
+import {
+ DownloadStartEvent,
+ DownloadErrorEvent,
+ DownloadCompleteEvent,
+} from '../../../src/types/events';
+
+// Mock dependencies
+jest.mock('../../../src/managers/BaseSnapshotManager');
+jest.mock('../../../src/stores/BackupStore');
+jest.mock('../../../src/services/events/DownloadEventService', () => ({
+ DownloadEventService: jest.fn(),
+}));
+jest.mock('../../../src/utils/logger', () => ({
+ planLogger: jest.fn().mockReturnValue({
+ info: jest.fn(),
+ error: jest.fn(),
+ warn: jest.fn(),
+ }),
+}));
+
+describe('DownloadEventListener', () => {
+ let localAgent: EventEmitter;
+ let mockBackupStore: jest.Mocked<BackupStore>;
+ let mockDownloadEventService: jest.Mocked<DownloadEventService>;
+ let listener: DownloadEventListener;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ // Use a real EventEmitter as the localAgent so we can emit events
+ localAgent = new EventEmitter();
+
+ mockBackupStore = new BackupStore(null as any) as jest.Mocked<BackupStore>;
+
+ // Capture the mocked DownloadEventService instance created inside the constructor
+ mockDownloadEventService = {
+ onDownloadStart: jest.fn().mockResolvedValue(undefined),
+ onDownloadError: jest.fn().mockResolvedValue(undefined),
+ onDownloadComplete: jest.fn().mockResolvedValue(undefined),
+ } as any;
+
+ (DownloadEventService as jest.Mock).mockImplementation(() => mockDownloadEventService);
+
+ listener = new DownloadEventListener(localAgent as any, mockBackupStore);
+ });
+
+ describe('constructor', () => {
+ it('should create a DownloadEventService instance', () => {
+ expect(DownloadEventService).toHaveBeenCalledWith(mockBackupStore, localAgent);
+ });
+
+ it('should register event listeners on the localAgent', () => {
+ expect(localAgent.listenerCount('download_start')).toBe(1);
+ expect(localAgent.listenerCount('download_error')).toBe(1);
+ expect(localAgent.listenerCount('download_complete')).toBe(1);
+ });
+ });
+
+ describe('download_start event', () => {
+ it('should delegate to downloadEventService.onDownloadStart', () => {
+ const event: DownloadStartEvent = {
+ backupId: 'backup-1',
+ planId: 'plan-1',
+ };
+
+ localAgent.emit('download_start', event);
+
+ expect(mockDownloadEventService.onDownloadStart).toHaveBeenCalledWith(event);
+ expect(mockDownloadEventService.onDownloadStart).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('download_error event', () => {
+ it('should delegate to downloadEventService.onDownloadError', () => {
+ const event: DownloadErrorEvent = {
+ backupId: 'backup-1',
+ planId: 'plan-1',
+ error: 'Download failed',
+ };
+
+ localAgent.emit('download_error', event);
+
+ expect(mockDownloadEventService.onDownloadError).toHaveBeenCalledWith(event);
+ expect(mockDownloadEventService.onDownloadError).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('download_complete event', () => {
+ it('should delegate to downloadEventService.onDownloadComplete', () => {
+ const event: DownloadCompleteEvent = {
+ backupId: 'backup-1',
+ planId: 'plan-1',
+ success: true,
+ };
+
+ localAgent.emit('download_complete', event);
+
+ expect(mockDownloadEventService.onDownloadComplete).toHaveBeenCalledWith(event);
+ expect(mockDownloadEventService.onDownloadComplete).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/backend/__tests__/services/listeners/RestoreEventListener.test.ts b/backend/__tests__/services/listeners/RestoreEventListener.test.ts
new file mode 100644
index 0000000..3d4f6b3
--- /dev/null
+++ b/backend/__tests__/services/listeners/RestoreEventListener.test.ts
@@ -0,0 +1,147 @@
+import { EventEmitter } from 'events';
+import { RestoreEventListener } from '../../../src/services/listeners/RestoreEventListener';
+import { BaseRestoreManager } from '../../../src/managers/BaseRestoreManager';
+import { PlanStore } from '../../../src/stores/PlanStore';
+import { BackupStore } from '../../../src/stores/BackupStore';
+import { RestoreStore } from '../../../src/stores/RestoreStore';
+import { RestoreEventService } from '../../../src/services/events/RestoreEventService';
+import {
+ RestoreStartEvent,
+ RestoreCompleteEvent,
+ RestoreErrorEvent,
+} from '../../../src/types/events';
+
+// Mock dependencies
+jest.mock('../../../src/managers/BaseRestoreManager');
+jest.mock('../../../src/stores/PlanStore');
+jest.mock('../../../src/stores/BackupStore');
+jest.mock('../../../src/stores/RestoreStore');
+jest.mock('../../../src/services/events/RestoreEventService', () => ({
+ RestoreEventService: jest.fn(),
+}));
+jest.mock('../../../src/utils/logger', () => ({
+ planLogger: jest.fn().mockReturnValue({
+ info: jest.fn(),
+ error: jest.fn(),
+ warn: jest.fn(),
+ }),
+}));
+
+describe('RestoreEventListener', () => {
+ let localAgent: EventEmitter;
+ let mockPlanStore: jest.Mocked<PlanStore>;
+ let mockBackupStore: jest.Mocked<BackupStore>;
+ let mockRestoreStore: jest.Mocked<RestoreStore>;
+ let mockRestoreEventService: jest.Mocked<RestoreEventService>;
+ let listener: RestoreEventListener;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ // Use a real EventEmitter as the localAgent so we can emit events
+ localAgent = new EventEmitter();
+
+ mockPlanStore = new PlanStore(null as any) as jest.Mocked<PlanStore>;
+ mockBackupStore = new BackupStore(null as any) as jest.Mocked<BackupStore>;
+ mockRestoreStore = new RestoreStore(null as any) as jest.Mocked<RestoreStore>;
+
+ // Capture the mocked RestoreEventService instance created inside the constructor
+ mockRestoreEventService = {
+ onRestoreStart: jest.fn().mockResolvedValue(undefined),
+ onRestoreComplete: jest.fn().mockResolvedValue(undefined),
+ onRestoreError: jest.fn().mockResolvedValue(undefined),
+ onRestoreFailed: jest.fn().mockResolvedValue(undefined),
+ } as any;
+
+ (RestoreEventService as jest.Mock).mockImplementation(() => mockRestoreEventService);
+
+ listener = new RestoreEventListener(
+ localAgent as any,
+ mockPlanStore,
+ mockBackupStore,
+ mockRestoreStore
+ );
+ });
+
+ describe('constructor', () => {
+ it('should create a RestoreEventService instance', () => {
+ expect(RestoreEventService).toHaveBeenCalledWith(
+ mockPlanStore,
+ mockBackupStore,
+ mockRestoreStore,
+ localAgent
+ );
+ });
+
+ it('should register event listeners on the localAgent', () => {
+ expect(localAgent.listenerCount('restore_start')).toBe(1);
+ expect(localAgent.listenerCount('restore_complete')).toBe(1);
+ expect(localAgent.listenerCount('restore_error')).toBe(1);
+ expect(localAgent.listenerCount('restore_failed')).toBe(1);
+ });
+ });
+
+ describe('restore_start event', () => {
+ it('should delegate to restoreEventService.onRestoreStart', () => {
+ const event: RestoreStartEvent = {
+ planId: 'plan-1',
+ backupId: 'backup-1',
+ restoreId: 'restore-1',
+ summary: {} as any,
+ config: {} as any,
+ };
+
+ localAgent.emit('restore_start', event);
+
+ expect(mockRestoreEventService.onRestoreStart).toHaveBeenCalledWith(event);
+ expect(mockRestoreEventService.onRestoreStart).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('restore_complete event', () => {
+ it('should delegate to restoreEventService.onRestoreComplete', () => {
+ const event: RestoreCompleteEvent = {
+ backupId: 'backup-1',
+ restoreId: 'restore-1',
+ planId: 'plan-1',
+ success: true,
+ };
+
+ localAgent.emit('restore_complete', event);
+
+ expect(mockRestoreEventService.onRestoreComplete).toHaveBeenCalledWith(event);
+ expect(mockRestoreEventService.onRestoreComplete).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('restore_error event', () => {
+ it('should delegate to restoreEventService.onRestoreError', () => {
+ const event: RestoreErrorEvent = {
+ backupId: 'backup-1',
+ planId: 'plan-1',
+ error: 'Restore failed',
+ };
+
+ localAgent.emit('restore_error', event);
+
+ expect(mockRestoreEventService.onRestoreError).toHaveBeenCalledWith(event);
+ expect(mockRestoreEventService.onRestoreError).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('restore_failed event', () => {
+ it('should delegate to restoreEventService.onRestoreFailed', () => {
+ const event: RestoreErrorEvent = {
+ backupId: 'backup-1',
+ planId: 'plan-1',
+ error: 'Restore permanently failed',
+ restoreId: 'restore-1',
+ };
+
+ localAgent.emit('restore_failed', event);
+
+ expect(mockRestoreEventService.onRestoreFailed).toHaveBeenCalledWith(event);
+ expect(mockRestoreEventService.onRestoreFailed).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/backend/__tests__/setup.ts b/backend/__tests__/setup.ts
index 3c88865..ea3a544 100644
--- a/backend/__tests__/setup.ts
+++ b/backend/__tests__/setup.ts
@@ -4,6 +4,15 @@
import { initializeLogger } from '../src/utils/logger';
import 'dotenv/config';
+// Mock templateLoader globally to avoid import.meta.url issues in Jest
+jest.mock('../src/notifications/templateLoader', () => ({
+ loadTemplate: jest.fn().mockReturnValue('<html>{{content}}</html>'),
+ loadEmailWrapperTemplate: jest
+ .fn()
+ .mockReturnValue('<html><body>{{EMAIL_BODY_CONTENT}}</body></html>'),
+ loadBackupTemplate: jest.fn().mockReturnValue('<div>Backup template</div>'),
+}));
+
beforeAll(() => {
console.log('--- JEST SETUP FILE IS RUNNING ---');
//initialize logger
diff --git a/backend/__tests__/stores/BackupStore.test.ts b/backend/__tests__/stores/BackupStore.test.ts
index 9a7bc28..9896da9 100644
--- a/backend/__tests__/stores/BackupStore.test.ts
+++ b/backend/__tests__/stores/BackupStore.test.ts
@@ -10,6 +10,8 @@ describe('BackupStore', () => {
const mockBackups: Backup[] = [
{
id: 'backup-1',
+ title: 'Backup 1',
+ description: 'First backup',
planId: 'plan-a',
status: 'completed',
success: true,
@@ -35,6 +37,8 @@ describe('BackupStore', () => {
},
{
id: 'backup-2',
+ title: 'Backup 2',
+ description: 'Second backup',
planId: 'plan-b',
status: 'failed',
success: false,
diff --git a/backend/__tests__/tsconfig.json b/backend/__tests__/tsconfig.json
new file mode 100644
index 0000000..7597f00
--- /dev/null
+++ b/backend/__tests__/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "../tsconfig.test.json",
+ "include": ["./**/*.ts", "../src/**/*.ts"]
+}
diff --git a/backend/__tests__/utils/AppError.test.ts b/backend/__tests__/utils/AppError.test.ts
new file mode 100644
index 0000000..9be36eb
--- /dev/null
+++ b/backend/__tests__/utils/AppError.test.ts
@@ -0,0 +1,148 @@
+import {
+ AppError,
+ NotFoundError,
+ BadRequestError,
+ UnauthorizedError,
+ ConflictError,
+} from '../../src/utils/AppError';
+
+describe('AppError', () => {
+ describe('AppError (base)', () => {
+ it('should create an instance of AppError', () => {
+ const error = new AppError(500, 'something went wrong');
+ expect(error).toBeInstanceOf(AppError);
+ expect(error).toBeInstanceOf(Error);
+ });
+
+ it('should have the correct statusCode', () => {
+ const error = new AppError(422, 'fail');
+ expect(error.statusCode).toBe(422);
+ });
+
+ it('should have the correct message', () => {
+ const error = new AppError(500, 'custom message');
+ expect(error.message).toBe('custom message');
+ });
+
+ it('should have a stack trace', () => {
+ const error = new AppError(500, 'trace test');
+ expect(error.stack).toBeDefined();
+ });
+ });
+
+ describe('NotFoundError', () => {
+ it('should create an instance of NotFoundError and AppError', () => {
+ const error = new NotFoundError();
+ expect(error).toBeInstanceOf(AppError);
+ expect(error).toBeInstanceOf(Error);
+ });
+
+ it('should have statusCode 404', () => {
+ const error = new NotFoundError();
+ expect(error.statusCode).toBe(404);
+ });
+
+ it('should use default message "Resource not found"', () => {
+ const error = new NotFoundError();
+ expect(error.message).toBe('Resource not found');
+ });
+
+ it('should allow a custom message', () => {
+ const error = new NotFoundError('User not found');
+ expect(error.message).toBe('User not found');
+ expect(error.statusCode).toBe(404);
+ });
+
+ it('should have a stack trace', () => {
+ const error = new NotFoundError();
+ expect(error.stack).toBeDefined();
+ });
+ });
+
+ describe('BadRequestError', () => {
+ it('should create an instance of BadRequestError and AppError', () => {
+ const error = new BadRequestError();
+ expect(error).toBeInstanceOf(AppError);
+ expect(error).toBeInstanceOf(Error);
+ });
+
+ it('should have statusCode 400', () => {
+ const error = new BadRequestError();
+ expect(error.statusCode).toBe(400);
+ });
+
+ it('should use default message "Bad request"', () => {
+ const error = new BadRequestError();
+ expect(error.message).toBe('Bad request');
+ });
+
+ it('should allow a custom message', () => {
+ const error = new BadRequestError('Invalid input');
+ expect(error.message).toBe('Invalid input');
+ expect(error.statusCode).toBe(400);
+ });
+
+ it('should have a stack trace', () => {
+ const error = new BadRequestError();
+ expect(error.stack).toBeDefined();
+ });
+ });
+
+ describe('UnauthorizedError', () => {
+ it('should create an instance of UnauthorizedError and AppError', () => {
+ const error = new UnauthorizedError();
+ expect(error).toBeInstanceOf(AppError);
+ expect(error).toBeInstanceOf(Error);
+ });
+
+ it('should have statusCode 401', () => {
+ const error = new UnauthorizedError();
+ expect(error.statusCode).toBe(401);
+ });
+
+ it('should use default message "Unauthorized"', () => {
+ const error = new UnauthorizedError();
+ expect(error.message).toBe('Unauthorized');
+ });
+
+ it('should allow a custom message', () => {
+ const error = new UnauthorizedError('Token expired');
+ expect(error.message).toBe('Token expired');
+ expect(error.statusCode).toBe(401);
+ });
+
+ it('should have a stack trace', () => {
+ const error = new UnauthorizedError();
+ expect(error.stack).toBeDefined();
+ });
+ });
+
+ describe('ConflictError', () => {
+ it('should create an instance of ConflictError and AppError', () => {
+ const error = new ConflictError();
+ expect(error).toBeInstanceOf(AppError);
+ expect(error).toBeInstanceOf(Error);
+ });
+
+ it('should have statusCode 409', () => {
+ const error = new ConflictError();
+ expect(error.statusCode).toBe(409);
+ });
+
+ it('should use default message "Conflict"', () => {
+ const error = new ConflictError();
+ expect(error.message).toBe('Conflict');
+ });
+
+ it('should allow a custom message', () => {
+ const error = new ConflictError('Duplicate entry');
+ expect(error.message).toBe('Duplicate entry');
+ expect(error.statusCode).toBe(409);
+ });
+
+ it('should have a stack trace', () => {
+ const error = new ConflictError();
+ expect(error.stack).toBeDefined();
+ });
+ });
+});
diff --git a/backend/__tests__/utils/asyncHandler.test.ts b/backend/__tests__/utils/asyncHandler.test.ts
new file mode 100644
index 0000000..28d2079
--- /dev/null
+++ b/backend/__tests__/utils/asyncHandler.test.ts
@@ -0,0 +1,51 @@
+import asyncHandler from '../../src/utils/asyncHandler';
+
+describe('asyncHandler', () => {
+ let req: any;
+ let res: any;
+ let next: jest.Mock;
+
+ beforeEach(() => {
+ req = {};
+ res = {};
+ next = jest.fn();
+ });
+
+ it('calls the wrapped function with req, res, next', async () => {
+ const fn = jest.fn().mockResolvedValue(undefined);
+ const handler = asyncHandler(fn);
+
+ await handler(req, res, next);
+
+ expect(fn).toHaveBeenCalledWith(req, res, next);
+ });
+
+ it('resolves successfully when fn resolves', async () => {
+ const fn = jest.fn().mockResolvedValue('ok');
+ const handler = asyncHandler(fn);
+
+ await handler(req, res, next);
+
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it('calls next with error when fn rejects', async () => {
+ const error = new Error('async failure');
+ const fn = jest.fn().mockRejectedValue(error);
+ const handler = asyncHandler(fn);
+
+ await handler(req, res, next);
+
+ expect(next).toHaveBeenCalledWith(error);
+ });
+
+ it('propagates synchronous throw', () => {
+ const error = new Error('sync failure');
+ const fn = jest.fn().mockImplementation(() => {
+ throw error;
+ });
+ const handler = asyncHandler(fn);
+
+ expect(() => handler(req, res, next)).toThrow('sync failure');
+ });
+});
diff --git a/backend/__tests__/utils/binaryPathResolver.test.ts b/backend/__tests__/utils/binaryPathResolver.test.ts
new file mode 100644
index 0000000..b779cf5
--- /dev/null
+++ b/backend/__tests__/utils/binaryPathResolver.test.ts
@@ -0,0 +1,297 @@
+import path from 'path';
+import fs from 'fs';
+import os from 'os';
+import { getBinaryPath } from '../../src/utils/binaryPathResolver';
+
+jest.mock('fs');
+jest.mock('os');
+
+const mockedExistsSync = fs.existsSync as jest.MockedFunction<typeof fs.existsSync>;
+const mockedPlatform = os.platform as jest.MockedFunction<typeof os.platform>;
+const mockedArch = os.arch as jest.MockedFunction<typeof os.arch>;
+
+describe('getBinaryPath', () => {
+ let originalAppDir: string | undefined;
+ let originalPkg: any;
+ let originalExecPath: string;
+ let originalCwd: string;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ // Save originals
+ originalAppDir = process.env.APPDIR;
+ originalPkg = (process as any).pkg;
+ originalExecPath = process.execPath;
+ originalCwd = process.cwd();
+
+ // Remove by default
+ delete process.env.APPDIR;
+ delete (process as any).pkg;
+
+ // Default to linux-x64
+ mockedPlatform.mockReturnValue('linux');
+ mockedArch.mockReturnValue('x64');
+
+ // Default: nothing exists on disk
+ mockedExistsSync.mockReturnValue(false);
+ });
+
+ afterEach(() => {
+ // Restore originals
+ if (originalAppDir !== undefined) {
+ process.env.APPDIR = originalAppDir;
+ } else {
+ delete process.env.APPDIR;
+ }
+ (process as any).pkg = originalPkg;
+ Object.defineProperty(process, 'execPath', { value: originalExecPath, writable: true });
+ });
+
+ // ----------------------------------------------------------------
+ // Priority 1: AppImage path ($APPDIR)
+ // ----------------------------------------------------------------
+ describe('Priority 1 – AppImage path', () => {
+ it('returns AppImage binary path when APPDIR is set and binary exists', () => {
+ process.env.APPDIR = '/tmp/.mount_App';
+ mockedExistsSync.mockImplementation(p => {
+ return p === path.join('/tmp/.mount_App', 'usr', 'bin', 'binaries', 'linux-x64', 'restic');
+ });
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(
+ path.join('/tmp/.mount_App', 'usr', 'bin', 'binaries', 'linux-x64', 'restic')
+ );
+ });
+
+ it('skips AppImage path when APPDIR is set but binary does not exist', () => {
+ process.env.APPDIR = '/tmp/.mount_App';
+ mockedExistsSync.mockReturnValue(false);
+
+ const result = getBinaryPath('restic');
+ // Falls through to fallback (binary name)
+ expect(result).toBe('restic');
+ });
+ });
+
+ // ----------------------------------------------------------------
+ // Priority 2: pkg-packaged executable
+ // ----------------------------------------------------------------
+ describe('Priority 2 – pkg-packaged', () => {
+ it('returns pkg binary path when process.pkg is set and binary exists', () => {
+ (process as any).pkg = {};
+ Object.defineProperty(process, 'execPath', { value: '/opt/app/myapp', writable: true });
+
+ const expectedPath = path.join('/opt/app', 'binaries', 'linux-x64', 'rclone');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('rclone');
+ expect(result).toBe(expectedPath);
+ });
+
+ it('skips pkg path when process.pkg is set but binary does not exist', () => {
+ (process as any).pkg = {};
+ Object.defineProperty(process, 'execPath', { value: '/opt/app/myapp', writable: true });
+ mockedExistsSync.mockReturnValue(false);
+
+ const result = getBinaryPath('rclone');
+ expect(result).toBe('rclone');
+ });
+ });
+
+ // ----------------------------------------------------------------
+ // Priority 3: Production path next to executable
+ // ----------------------------------------------------------------
+ describe('Priority 3 – Production path near executable', () => {
+ it('returns production binary path when binary exists next to executable', () => {
+ Object.defineProperty(process, 'execPath', {
+ value: '/usr/local/myapp/myapp',
+ writable: true,
+ });
+
+ const expectedPath = path.join('/usr/local/myapp', 'restic');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(expectedPath);
+ });
+ });
+
+ // ----------------------------------------------------------------
+ // Priority 4: Development path at cwd/binaries
+ // ----------------------------------------------------------------
+ describe('Priority 4 – Development path', () => {
+ it('returns dev binary path when binary exists in cwd/binaries', () => {
+ const expectedPath = path.resolve(process.cwd(), 'binaries', 'linux-x64', 'rear');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('rear');
+ expect(result).toBe(expectedPath);
+ });
+ });
+
+ // ----------------------------------------------------------------
+ // Priority 5: Standard system paths
+ // ----------------------------------------------------------------
+ describe('Priority 5 – Standard system paths', () => {
+ it('returns /usr/local/bin path when binary exists there', () => {
+ const expectedPath = path.join('/usr/local/bin', 'restic');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(expectedPath);
+ });
+
+ it('returns /usr/bin path when binary exists there but not in /usr/local/bin', () => {
+ const expectedPath = path.join('/usr/bin', 'restic');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(expectedPath);
+ });
+
+ it('returns /bin path when binary exists only there', () => {
+ const expectedPath = path.join('/bin', 'rclone');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('rclone');
+ expect(result).toBe(expectedPath);
+ });
+ });
+
+ // ----------------------------------------------------------------
+ // Fallback: returns just the binary name
+ // ----------------------------------------------------------------
+ describe('Fallback', () => {
+ it('returns just the binary name when no path matches', () => {
+ mockedExistsSync.mockReturnValue(false);
+
+ expect(getBinaryPath('restic')).toBe('restic');
+ expect(getBinaryPath('rclone')).toBe('rclone');
+ expect(getBinaryPath('rear')).toBe('rear');
+ });
+ });
+
+ // ----------------------------------------------------------------
+ // Windows: .exe extension
+ // ----------------------------------------------------------------
+ describe('Windows .exe extension', () => {
+ beforeEach(() => {
+ mockedPlatform.mockReturnValue('win32');
+ mockedArch.mockReturnValue('x64');
+ });
+
+ it('appends .exe on Windows for AppImage path', () => {
+ process.env.APPDIR = 'C:\\AppImage';
+ const expectedPath = path.join(
+ 'C:\\AppImage',
+ 'usr',
+ 'bin',
+ 'binaries',
+ 'win32-x64',
+ 'restic.exe'
+ );
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(expectedPath);
+ });
+
+ it('appends .exe on Windows for pkg path', () => {
+ (process as any).pkg = {};
+ Object.defineProperty(process, 'execPath', {
+ value: 'C:\\Program Files\\app\\app.exe',
+ writable: true,
+ });
+
+ const expectedPath = path.join(
+ 'C:\\Program Files\\app',
+ 'binaries',
+ 'win32-x64',
+ 'rclone.exe'
+ );
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('rclone');
+ expect(result).toBe(expectedPath);
+ });
+
+ it('appends .exe on Windows for production path', () => {
+ Object.defineProperty(process, 'execPath', { value: 'C:\\app\\myapp.exe', writable: true });
+
+ const expectedPath = path.join('C:\\app', 'restic.exe');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(expectedPath);
+ });
+
+ it('appends .exe on Windows for dev path', () => {
+ const expectedPath = path.resolve(process.cwd(), 'binaries', 'win32-x64', 'rear.exe');
+ mockedExistsSync.mockImplementation(p => p === expectedPath);
+
+ const result = getBinaryPath('rear');
+ expect(result).toBe(expectedPath);
+ });
+
+ it('returns just the binary name (without .exe) as fallback on Windows', () => {
+ mockedExistsSync.mockReturnValue(false);
+
+ expect(getBinaryPath('restic')).toBe('restic');
+ });
+ });
+
+ // ----------------------------------------------------------------
+ // Priority ordering: earlier matches win
+ // ----------------------------------------------------------------
+ describe('Priority ordering', () => {
+ it('prefers AppImage over pkg when both are available', () => {
+ process.env.APPDIR = '/tmp/.mount_App';
+ (process as any).pkg = {};
+ Object.defineProperty(process, 'execPath', { value: '/opt/app/myapp', writable: true });
+
+ const appImagePath = path.join(
+ '/tmp/.mount_App',
+ 'usr',
+ 'bin',
+ 'binaries',
+ 'linux-x64',
+ 'restic'
+ );
+ const pkgPath = path.join('/opt/app', 'binaries', 'linux-x64', 'restic');
+
+ mockedExistsSync.mockImplementation(p => p === appImagePath || p === pkgPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(appImagePath);
+ });
+
+ it('prefers pkg over production when AppImage is not set', () => {
+ (process as any).pkg = {};
+ Object.defineProperty(process, 'execPath', { value: '/opt/app/myapp', writable: true });
+
+ const pkgPath = path.join('/opt/app', 'binaries', 'linux-x64', 'restic');
+ const prodPath = path.join('/opt/app', 'restic');
+
+ mockedExistsSync.mockImplementation(p => p === pkgPath || p === prodPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(pkgPath);
+ });
+
+ it('prefers production over dev path', () => {
+ Object.defineProperty(process, 'execPath', {
+ value: '/usr/local/myapp/myapp',
+ writable: true,
+ });
+
+ const prodPath = path.join('/usr/local/myapp', 'restic');
+ const devPath = path.resolve(process.cwd(), 'binaries', 'linux-x64', 'restic');
+
+ mockedExistsSync.mockImplementation(p => p === prodPath || p === devPath);
+
+ const result = getBinaryPath('restic');
+ expect(result).toBe(prodPath);
+ });
+ });
+});
diff --git a/backend/__tests__/utils/executeUserScript.test.ts b/backend/__tests__/utils/executeUserScript.test.ts
new file mode 100644
index 0000000..770578e
--- /dev/null
+++ b/backend/__tests__/utils/executeUserScript.test.ts
@@ -0,0 +1,380 @@
+import { EventEmitter } from 'events';
+import { PlanScript } from '../../src/types/plans';
+
+// --- Mocks ---
+
+const mockStdout = new EventEmitter();
+const mockStderr = new EventEmitter();
+const mockChild = Object.assign(new EventEmitter(), {
+ stdout: mockStdout,
+ stderr: mockStderr,
+});
+
+const mockSpawn = jest.fn().mockReturnValue(mockChild);
+
+jest.mock('child_process', () => ({
+ spawn: (...args: any[]) => mockSpawn(...args),
+}));
+
+const mockDecrypt = jest.fn((val: string) => val);
+jest.mock('cryptr', () => {
+ return jest.fn().mockImplementation(() => ({
+ decrypt: mockDecrypt,
+ }));
+});
+
+import { executeUserScript, runScriptsForEvent } from '../../src/utils/executeUserScript';
+
+// --- Helpers ---
+
+function buildScript(overrides: Partial<PlanScript> = {}): PlanScript {
+ return {
+ id: 'script-1',
+ type: 'command',
+ enabled: true,
+ command: 'echo hello',
+ logOutput: false,
+ ...overrides,
+ };
+}
+
+function freshChild() {
+ const stdout = new EventEmitter();
+ const stderr = new EventEmitter();
+ const child = Object.assign(new EventEmitter(), { stdout, stderr });
+ mockSpawn.mockReturnValue(child);
+ return child;
+}
+
+// --- Tests ---
+
+describe('executeUserScript', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ // Shell selection tests
+ describe('shell selection', () => {
+ const shellCases: { shell: string | undefined; expectedExe: string; expectedArgs: string[] }[] =
+ [
+ { shell: 'bash', expectedExe: 'bash', expectedArgs: ['-c', 'echo hello'] },
+ { shell: '/bin/bash', expectedExe: '/bin/bash', expectedArgs: ['-c', 'echo hello'] },
+ { shell: 'zsh', expectedExe: 'zsh', expectedArgs: ['-c', 'echo hello'] },
+ { shell: '/bin/sh', expectedExe: '/bin/sh', expectedArgs: ['-c', 'echo hello'] },
+ {
+ shell: 'powershell',
+ expectedExe: 'powershell.exe',
+ expectedArgs: ['-NoProfile', '-NonInteractive', '-Command', 'echo hello'],
+ },
+ { shell: 'cmd', expectedExe: 'cmd.exe', expectedArgs: ['/c', 'echo hello'] },
+ ];
+
+ it.each(shellCases)(
+ 'spawns $expectedExe when shell is "$shell"',
+ async ({ shell, expectedExe, expectedArgs }) => {
+ const child = freshChild();
+ const script = buildScript({ shell });
+ const promise = executeUserScript(script);
+
+ child.emit('close', 0, null);
+ await promise;
+
+ expect(mockSpawn).toHaveBeenCalledWith(expectedExe, expectedArgs, expect.any(Object));
+ }
+ );
+
+ it('defaults to /bin/sh when shell is not specified', async () => {
+ const child = freshChild();
+ const script = buildScript({ shell: undefined });
+ const promise = executeUserScript(script);
+
+ child.emit('close', 0, null);
+ await promise;
+
+ expect(mockSpawn).toHaveBeenCalledWith('/bin/sh', ['-c', 'echo hello'], expect.any(Object));
+ });
+ });
+
+ // Success case
+ it('resolves with stdout and stderr on exit code 0', async () => {
+ const child = freshChild();
+ const script = buildScript();
+ const promise = executeUserScript(script);
+
+ child.stdout.emit('data', Buffer.from('out'));
+ child.stderr.emit('data', Buffer.from('err'));
+ child.emit('close', 0, null);
+
+ const result = await promise;
+ expect(result).toEqual({ stdout: 'out', stderr: 'err' });
+ });
+
+ // Failure cases
+ it('rejects on non-zero exit code', async () => {
+ const child = freshChild();
+ const script = buildScript();
+ const promise = executeUserScript(script);
+
+ child.stderr.emit('data', Buffer.from('bad'));
+ child.emit('close', 1, null);
+
+ await expect(promise).rejects.toThrow('bad');
+ });
+
+ it('rejects with generic message when stderr and stdout are empty and exit code is non-zero', async () => {
+ const child = freshChild();
+ const script = buildScript();
+ const promise = executeUserScript(script);
+
+ child.emit('close', 2, null);
+
+ await expect(promise).rejects.toThrow('Script exited with code 2');
+ });
+
+ it('rejects on SIGTERM (timeout)', async () => {
+ const child = freshChild();
+ const script = buildScript({ timeout: 5000 });
+ const promise = executeUserScript(script);
+
+ child.emit('close', null, 'SIGTERM');
+
+ await expect(promise).rejects.toThrow('Script timed out after 5000ms');
+ });
+
+ it('uses default timeout message when timeout is not set', async () => {
+ const child = freshChild();
+ const script = buildScript();
+ const promise = executeUserScript(script);
+
+ child.emit('close', null, 'SIGTERM');
+
+ await expect(promise).rejects.toThrow('Script timed out after 60000ms');
+ });
+
+ it('rejects on spawn error', async () => {
+ const child = freshChild();
+ const script = buildScript();
+ const promise = executeUserScript(script);
+
+ child.emit('error', new Error('ENOENT'));
+
+ await expect(promise).rejects.toThrow('Failed to start script process: ENOENT');
+ });
+
+ it('passes the timeout option to spawn', async () => {
+ const child = freshChild();
+ const script = buildScript({ timeout: 3000 });
+ const promise = executeUserScript(script);
+
+ child.emit('close', 0, null);
+ await promise;
+
+ expect(mockSpawn).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.any(Array),
+ expect.objectContaining({ timeout: 3000 })
+ );
+ });
+});
+
+describe('runScriptsForEvent', () => {
+ let onStart: jest.Mock;
+ let onComplete: jest.Mock;
+ let onError: jest.Mock;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ onStart = jest.fn().mockResolvedValue(undefined);
+ onComplete = jest.fn().mockResolvedValue(undefined);
+ onError = jest.fn().mockResolvedValue(undefined);
+ });
+
+ it('returns early when no scripts are provided', async () => {
+ await runScriptsForEvent(
+ 'onBackupStart',
+ [] as PlanScript[],
+ 'secret',
+ onStart,
+ onComplete,
+ onError
+ );
+
+ expect(onStart).not.toHaveBeenCalled();
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(mockSpawn).not.toHaveBeenCalled();
+ });
+
+ it('returns early when eventName is empty', async () => {
+ await runScriptsForEvent('', [buildScript()], 'secret', onStart, onComplete, onError);
+
+ expect(onStart).not.toHaveBeenCalled();
+ expect(mockSpawn).not.toHaveBeenCalled();
+ });
+
+ it('skips disabled scripts', async () => {
+ const child = freshChild();
+ const scripts = [buildScript({ enabled: false })];
+
+ await runScriptsForEvent('onBackupStart', scripts, 'secret', onStart, onComplete, onError);
+
+ expect(onStart).not.toHaveBeenCalled();
+ expect(mockSpawn).not.toHaveBeenCalled();
+ });
+
+ it('skips scripts with empty command', async () => {
+ const scripts = [buildScript({ command: ' ' })];
+
+ await runScriptsForEvent('onBackupStart', scripts, 'secret', onStart, onComplete, onError);
+
+ expect(onStart).not.toHaveBeenCalled();
+ expect(mockSpawn).not.toHaveBeenCalled();
+ });
+
+ it('calls onStart and onComplete callbacks on success', async () => {
+ const child = freshChild();
+ const scripts = [buildScript()];
+
+ mockDecrypt.mockReturnValue('echo hello');
+
+ const promise = runScriptsForEvent(
+ 'onBackupStart',
+ scripts,
+ 'secret',
+ onStart,
+ onComplete,
+ onError
+ );
+
+ // Simulate successful child process
+ child.emit('close', 0, null);
+
+ await promise;
+
+ expect(onStart).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
+ expect(onComplete).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('calls onError callback on script failure', async () => {
+ const child = freshChild();
+ const scripts = [buildScript({ abortOnError: false })];
+
+ mockDecrypt.mockReturnValue('echo hello');
+
+ const promise = runScriptsForEvent(
+ 'onBackupStart',
+ scripts,
+ 'secret',
+ onStart,
+ onComplete,
+ onError
+ );
+
+ child.stderr.emit('data', Buffer.from('something went wrong'));
+ child.emit('close', 1, null);
+
+ await promise;
+
+ expect(onStart).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
+ expect(onError).toHaveBeenCalledWith(
+ 'ONBACKUPSTART_SCRIPT_1',
+ expect.stringContaining('something went wrong')
+ );
+ expect(onComplete).not.toHaveBeenCalled();
+ });
+
+ it('throws when abortOnError is true and script fails', async () => {
+ const child = freshChild();
+ const scripts = [buildScript({ abortOnError: true })];
+
+ mockDecrypt.mockReturnValue('echo hello');
+
+ const promise = runScriptsForEvent(
+ 'onBackupStart',
+ scripts,
+ 'secret',
+ onStart,
+ onComplete,
+ onError
+ );
+
+ child.stderr.emit('data', Buffer.from('fatal'));
+ child.emit('close', 1, null);
+
+ await expect(promise).rejects.toThrow("Critical 'beforeBackup' hook failed");
+ expect(onError).toHaveBeenCalled();
+ });
+
+ it('decrypts commands using Cryptr with the provided secret', async () => {
+ const child = freshChild();
+ const scripts = [buildScript({ command: 'encrypted-cmd' })];
+
+ mockDecrypt.mockReturnValue('decrypted-cmd');
+
+ const promise = runScriptsForEvent(
+ 'onBackupStart',
+ scripts,
+ 'my-secret',
+ onStart,
+ onComplete,
+ onError
+ );
+
+ child.emit('close', 0, null);
+
+ await promise;
+
+ expect(mockDecrypt).toHaveBeenCalledWith('encrypted-cmd');
+ expect(mockSpawn).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.arrayContaining(['decrypted-cmd']),
+ expect.any(Object)
+ );
+ });
+
+ it('processes multiple scripts in order', async () => {
+ const children = [freshChild()];
+ const scripts = [
+ buildScript({ id: 's1', command: 'cmd1' }),
+ buildScript({ id: 's2', command: 'cmd2' }),
+ ];
+
+ mockDecrypt.mockImplementation((v: string) => v);
+
+ // For the second script, we need a new child since the first will close
+ const child2 = freshChild();
+
+ // Reset to return children in order
+ let callCount = 0;
+ mockSpawn.mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) return children[0];
+ return child2;
+ });
+
+ const promise = runScriptsForEvent(
+ 'onBackupStart',
+ scripts,
+ 'secret',
+ onStart,
+ onComplete,
+ onError
+ );
+
+ // Complete first script
+ children[0].emit('close', 0, null);
+
+ // Wait a tick for the next iteration
+ await new Promise(r => setTimeout(r, 0));
+
+ // Complete second script
+ child2.emit('close', 0, null);
+
+ await promise;
+
+ expect(onStart).toHaveBeenCalledTimes(2);
+ expect(onComplete).toHaveBeenCalledTimes(2);
+ expect(onStart).toHaveBeenNthCalledWith(1, 'ONBACKUPSTART_SCRIPT_1');
+ expect(onStart).toHaveBeenNthCalledWith(2, 'ONBACKUPSTART_SCRIPT_2');
+ });
+});
diff --git a/backend/__tests__/utils/installHelpers.test.ts b/backend/__tests__/utils/installHelpers.test.ts
new file mode 100644
index 0000000..9aee24f
--- /dev/null
+++ b/backend/__tests__/utils/installHelpers.test.ts
@@ -0,0 +1,260 @@
+import {
+ isBinaryMode,
+ isDockerMode,
+ getInstallType,
+ isLinuxDesktop,
+ isKeyringPlatform,
+ requiresKeyringSetup,
+} from '../../src/utils/installHelpers';
+
+describe('installHelpers', () => {
+ const originalPlatform = process.platform;
+ const originalEnv = { ...process.env };
+ const originalPkg = (process as any).pkg;
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
+ process.env = { ...originalEnv };
+ if (originalPkg !== undefined) {
+ (process as any).pkg = originalPkg;
+ } else {
+ delete (process as any).pkg;
+ }
+ });
+
+ describe('isBinaryMode', () => {
+ it('should return true when process.pkg is set', () => {
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ expect(isBinaryMode()).toBe(true);
+ });
+
+ it('should return false when process.pkg is not set', () => {
+ delete (process as any).pkg;
+ expect(isBinaryMode()).toBe(false);
+ });
+
+ it('should return false when process.pkg is undefined', () => {
+ (process as any).pkg = undefined;
+ expect(isBinaryMode()).toBe(false);
+ });
+ });
+
+ describe('isDockerMode', () => {
+ it('should return true when IS_DOCKER is "true"', () => {
+ process.env.IS_DOCKER = 'true';
+ expect(isDockerMode()).toBe(true);
+ });
+
+ it('should return true when IS_DOCKER is "1"', () => {
+ process.env.IS_DOCKER = '1';
+ expect(isDockerMode()).toBe(true);
+ });
+
+ it('should return false when IS_DOCKER is not set', () => {
+ delete process.env.IS_DOCKER;
+ expect(isDockerMode()).toBe(false);
+ });
+
+ it('should return false when IS_DOCKER is "false"', () => {
+ process.env.IS_DOCKER = 'false';
+ expect(isDockerMode()).toBe(false);
+ });
+
+ it('should return false when IS_DOCKER is "0"', () => {
+ process.env.IS_DOCKER = '0';
+ expect(isDockerMode()).toBe(false);
+ });
+ });
+
+ describe('getInstallType', () => {
+ it('should return "docker" when in docker mode', () => {
+ process.env.IS_DOCKER = 'true';
+ delete (process as any).pkg;
+ expect(getInstallType()).toBe('docker');
+ });
+
+ it('should return "binary" when in binary mode but not docker', () => {
+ delete process.env.IS_DOCKER;
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ expect(getInstallType()).toBe('binary');
+ });
+
+ it('should return "dev" when neither docker nor binary', () => {
+ delete process.env.IS_DOCKER;
+ delete (process as any).pkg;
+ expect(getInstallType()).toBe('dev');
+ });
+
+ it('should prioritize docker over binary when both are set', () => {
+ process.env.IS_DOCKER = 'true';
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ expect(getInstallType()).toBe('docker');
+ });
+ });
+
+ describe('isLinuxDesktop', () => {
+ beforeEach(() => {
+ delete process.env.PLUTON_LINUX_DESKTOP;
+ delete process.env.DISPLAY;
+ delete process.env.WAYLAND_DISPLAY;
+ delete process.env.XDG_CURRENT_DESKTOP;
+ delete process.env.DESKTOP_SESSION;
+ delete process.env.GNOME_DESKTOP_SESSION_ID;
+ delete process.env.KDE_FULL_SESSION;
+ });
+
+ it('should return false on non-linux platforms', () => {
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ process.env.DISPLAY = ':0';
+ expect(isLinuxDesktop()).toBe(false);
+ });
+
+ it('should return false on darwin', () => {
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+ expect(isLinuxDesktop()).toBe(false);
+ });
+
+ it('should return true when PLUTON_LINUX_DESKTOP is "true"', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.PLUTON_LINUX_DESKTOP = 'true';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return true when PLUTON_LINUX_DESKTOP is "1"', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.PLUTON_LINUX_DESKTOP = '1';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return true when DISPLAY is set', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.DISPLAY = ':0';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return true when WAYLAND_DISPLAY is set', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.WAYLAND_DISPLAY = 'wayland-0';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return true when XDG_CURRENT_DESKTOP is set', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.XDG_CURRENT_DESKTOP = 'GNOME';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return true when DESKTOP_SESSION is set', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.DESKTOP_SESSION = 'ubuntu';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return true when GNOME_DESKTOP_SESSION_ID is set', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.GNOME_DESKTOP_SESSION_ID = 'this-is-deprecated';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return true when KDE_FULL_SESSION is set', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.KDE_FULL_SESSION = 'true';
+ expect(isLinuxDesktop()).toBe(true);
+ });
+
+ it('should return false on linux with no desktop indicators', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ expect(isLinuxDesktop()).toBe(false);
+ });
+ });
+
+ describe('isKeyringPlatform', () => {
+ beforeEach(() => {
+ delete process.env.DISPLAY;
+ delete process.env.WAYLAND_DISPLAY;
+ delete process.env.XDG_CURRENT_DESKTOP;
+ delete process.env.DESKTOP_SESSION;
+ delete process.env.GNOME_DESKTOP_SESSION_ID;
+ delete process.env.KDE_FULL_SESSION;
+ delete process.env.PLUTON_LINUX_DESKTOP;
+ });
+
+ it('should return true on win32', () => {
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ expect(isKeyringPlatform()).toBe(true);
+ });
+
+ it('should return true on darwin', () => {
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+ expect(isKeyringPlatform()).toBe(true);
+ });
+
+ it('should return true on linux desktop', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.DISPLAY = ':0';
+ expect(isKeyringPlatform()).toBe(true);
+ });
+
+ it('should return false on linux server (no desktop)', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ expect(isKeyringPlatform()).toBe(false);
+ });
+
+ it('should return false on unsupported platforms', () => {
+ Object.defineProperty(process, 'platform', { value: 'freebsd' });
+ expect(isKeyringPlatform()).toBe(false);
+ });
+ });
+
+ describe('requiresKeyringSetup', () => {
+ beforeEach(() => {
+ delete (process as any).pkg;
+ delete process.env.IS_DOCKER;
+ delete process.env.DISPLAY;
+ delete process.env.WAYLAND_DISPLAY;
+ delete process.env.XDG_CURRENT_DESKTOP;
+ delete process.env.DESKTOP_SESSION;
+ delete process.env.GNOME_DESKTOP_SESSION_ID;
+ delete process.env.KDE_FULL_SESSION;
+ delete process.env.PLUTON_LINUX_DESKTOP;
+ });
+
+ it('should return true when binary mode on win32', () => {
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ expect(requiresKeyringSetup()).toBe(true);
+ });
+
+ it('should return true when binary mode on darwin', () => {
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+ expect(requiresKeyringSetup()).toBe(true);
+ });
+
+ it('should return true when binary mode on linux desktop', () => {
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ process.env.DISPLAY = ':0';
+ expect(requiresKeyringSetup()).toBe(true);
+ });
+
+ it('should return false when binary mode on linux server', () => {
+ (process as any).pkg = { entrypoint: '/snapshot/app/index.js' };
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ expect(requiresKeyringSetup()).toBe(false);
+ });
+
+ it('should return false when not in binary mode', () => {
+ delete (process as any).pkg;
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ expect(requiresKeyringSetup()).toBe(false);
+ });
+
+ it('should return false in dev mode even on keyring platform', () => {
+ delete (process as any).pkg;
+ delete process.env.IS_DOCKER;
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+ expect(requiresKeyringSetup()).toBe(false);
+ });
+ });
+});
diff --git a/backend/__tests__/utils/logger.test.ts b/backend/__tests__/utils/logger.test.ts
index 1edff10..d9f5f94 100644
--- a/backend/__tests__/utils/logger.test.ts
+++ b/backend/__tests__/utils/logger.test.ts
@@ -80,6 +80,11 @@ describe('Logger Utility', () => {
expect(pinoMock).toHaveBeenCalledWith({
transport: {
targets: [
+ {
+ target: 'pino/file',
+ options: { destination: '/test/logs/app.log', mkdir: true },
+ level: 'info',
+ },
{
target: 'pino-pretty',
options: {
@@ -89,11 +94,6 @@ describe('Logger Utility', () => {
},
level: 'info',
},
- {
- target: 'pino/file',
- options: { destination: '/test/logs/app.log' },
- level: 'info',
- },
],
},
});
@@ -138,7 +138,7 @@ describe('Logger Utility', () => {
targets: expect.arrayContaining([
expect.objectContaining({
target: 'pino/file',
- options: { destination: '/custom/log/path/app.log' },
+ options: { destination: '/custom/log/path/app.log', mkdir: true },
}),
]),
}),
@@ -198,7 +198,7 @@ describe('Logger Utility', () => {
targets: [
{
target: 'pino/file',
- options: { destination: '/test/logs/plan-plan-123.log' },
+ options: { destination: '/test/logs/plan-plan-123.log', mkdir: true },
level: 'info',
},
],
@@ -275,7 +275,7 @@ describe('Logger Utility', () => {
targets: [
{
target: 'pino/file',
- options: { destination: '/test/logs/plan-plan-1.log' },
+ options: { destination: '/test/logs/plan-plan-1.log', mkdir: true },
level: 'info',
},
],
@@ -286,7 +286,7 @@ describe('Logger Utility', () => {
targets: [
{
target: 'pino/file',
- options: { destination: '/test/logs/plan-plan-2.log' },
+ options: { destination: '/test/logs/plan-plan-2.log', mkdir: true },
level: 'info',
},
],
diff --git a/backend/__tests__/utils/rclone/rclone.test.ts b/backend/__tests__/utils/rclone/rclone.test.ts
index f764c7c..d9000c8 100644
--- a/backend/__tests__/utils/rclone/rclone.test.ts
+++ b/backend/__tests__/utils/rclone/rclone.test.ts
@@ -6,6 +6,14 @@ jest.mock('child_process');
jest.mock('os');
jest.mock('../../../src/utils/binaryPathResolver');
jest.mock('../../../src/utils/rclone/helpers');
+jest.mock('../../../src/services/ConfigService', () => ({
+ configService: {
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ isSetupPending: jest.fn().mockReturnValue(false),
+ },
+}));
jest.mock('../../../src/utils/AppPaths', () => ({
appPaths: {
getConfigDir: jest.fn().mockReturnValue('/mock/config'),
@@ -240,12 +248,8 @@ describe('runRcloneCommand', () => {
await promise;
- expect(consoleLogSpy).toHaveBeenCalledWith('rcloneBinary :', '/usr/local/bin/rclone');
- expect(consoleLogSpy).toHaveBeenCalledWith(
- 'runRcloneCommand :',
- 'rclone ls remote:path',
- expect.any(Object)
- );
+ // The close event log is the only active console.log in the source
+ expect(consoleLogSpy).toHaveBeenCalledWith('[rclone] Close Fired!! Code :', 0);
});
it('should log close event with exit code', async () => {
@@ -272,8 +276,7 @@ describe('runRcloneCommand', () => {
expect(spawn).toHaveBeenCalledWith('/usr/local/bin/rclone', [], expect.any(Object));
});
- it('should set RCLONE_CONFIG_PASS from environment', async () => {
- process.env.ENCRYPTION_KEY = 'my-secret-key';
+ it('should set RCLONE_CONFIG_PASS from configService', async () => {
const args = ['config', 'show'];
const promise = runRcloneCommand(args);
@@ -284,12 +287,12 @@ describe('runRcloneCommand', () => {
expect(spawn).toHaveBeenCalledWith('/usr/local/bin/rclone', args, {
env: expect.objectContaining({
- RCLONE_CONFIG_PASS: 'my-secret-key',
+ RCLONE_CONFIG_PASS: 'test-encryption-key',
}),
});
});
- it('should handle undefined ENCRYPTION_KEY', async () => {
+ it('should use ENCRYPTION_KEY from configService', async () => {
delete process.env.ENCRYPTION_KEY;
const args = ['version'];
@@ -299,9 +302,10 @@ describe('runRcloneCommand', () => {
await promise;
+ // RCLONE_CONFIG_PASS comes from configService.config.ENCRYPTION_KEY, not process.env
expect(spawn).toHaveBeenCalledWith('/usr/local/bin/rclone', args, {
env: expect.objectContaining({
- RCLONE_CONFIG_PASS: undefined,
+ RCLONE_CONFIG_PASS: 'test-encryption-key',
}),
});
});
diff --git a/backend/__tests__/utils/restic/restic.test.ts b/backend/__tests__/utils/restic/restic.test.ts
index 6e9d559..f149abf 100644
--- a/backend/__tests__/utils/restic/restic.test.ts
+++ b/backend/__tests__/utils/restic/restic.test.ts
@@ -6,6 +6,14 @@ jest.mock('../../../src/utils/binaryPathResolver');
jest.mock('../../../src/utils/rclone/helpers');
jest.mock('../../../src/utils/AppPaths');
jest.mock('../../../src/utils/restic/helpers');
+jest.mock('../../../src/services/ConfigService', () => ({
+ configService: {
+ config: {
+ ENCRYPTION_KEY: 'test-encryption-key',
+ },
+ isSetupPending: jest.fn().mockReturnValue(false),
+ },
+}));
import { spawn } from 'child_process';
import {
@@ -251,12 +259,12 @@ describe('runResticCommand', () => {
await promise;
- // Verify the final args contain forward slashes
+ // Verify the final args use only the basename (no backslashes)
const spawnArgs = mockSpawn.mock.calls[0][1];
const rcloneProgramArg = spawnArgs.find((arg: string) => arg.startsWith('rclone.program='));
expect(rcloneProgramArg).toBeDefined();
expect(rcloneProgramArg).not.toContain('\\');
- expect(rcloneProgramArg).toContain('/');
+ expect(rcloneProgramArg).toBe('rclone.program=rclone.exe');
// Restore original platform
if (originalPlatform) {
@@ -781,7 +789,7 @@ describe('getSnapshotByTag', () => {
encryption: true,
});
- expect(capturedEnv?.RESTIC_PASSWORD).toBe('test-key');
+ expect(capturedEnv?.RESTIC_PASSWORD).toBe('test-encryption-key');
});
it('should use empty password when encryption is false', async () => {
diff --git a/backend/__tests__/utils/versions.test.ts b/backend/__tests__/utils/versions.test.ts
index 93464ac..7f1c93a 100644
--- a/backend/__tests__/utils/versions.test.ts
+++ b/backend/__tests__/utils/versions.test.ts
@@ -2,6 +2,9 @@ import { execSync } from 'child_process';
import { getResticVersion, getRcloneVersion } from '../../src/utils/versions';
jest.mock('child_process');
+jest.mock('../../src/utils/binaryPathResolver', () => ({
+ getBinaryPath: jest.fn((name: string) => name),
+}));
const mockedExecSync = execSync as jest.MockedFunction<typeof execSync>;
diff --git a/backend/jest.config.ts b/backend/jest.config.ts
index 9cddf6c..a179e96 100644
--- a/backend/jest.config.ts
+++ b/backend/jest.config.ts
@@ -20,6 +20,7 @@ const config: Config = {
esModuleInterop: true,
allowSyntheticDefaultImports: true,
},
+ diagnostics: false,
},
],
},
diff --git a/backend/src/notifications/templateLoader.ts b/backend/src/notifications/templateLoader.ts
index 42e03e5..6c6d579 100644
--- a/backend/src/notifications/templateLoader.ts
+++ b/backend/src/notifications/templateLoader.ts
@@ -16,8 +16,8 @@ import { fileURLToPath } from 'url';
const isPkg = typeof (process as any).pkg !== 'undefined';
// Get current directory using import.meta.url (works in ESM)
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
+const currentFilePath = fileURLToPath(import.meta.url);
+const currentDirPath = path.dirname(currentFilePath);
/**
* Get the base path for templates based on the execution context
@@ -28,7 +28,7 @@ function getTemplateBasePath(): string {
// __dirname will be /snapshot/.../backend/dist/
// Templates are bundled at /snapshot/.../backend/src/notifications/templates/
// So we go from dist/ → src/notifications/templates/
- return path.join(__dirname, '..', 'src', 'notifications', 'templates');
+ return path.join(currentDirPath, '..', 'src', 'notifications', 'templates');
}
// Try multiple paths for non-pkg environments:
@@ -37,7 +37,7 @@ function getTemplateBasePath(): string {
// 3. dist/ folder relative to process.cwd() (works for production builds)
const possiblePaths = [
// Templates relative to this module (dist/notifications/templates or src/notifications/templates)
- path.join(__dirname, 'templates'),
+ path.join(currentDirPath, 'templates'),
// Development: src folder
path.join(process.cwd(), 'src', 'notifications', 'templates'),
// Production: dist folder (if templates are copied there)
diff --git a/backend/tsconfig.test.json b/backend/tsconfig.test.json
index e019365..7a48075 100644
--- a/backend/tsconfig.test.json
+++ b/backend/tsconfig.test.json
@@ -3,6 +3,8 @@
"target": "esnext",
"module": "esnext",
"moduleResolution": "bundler",
+ "noEmit": true,
+ "types": ["node", "jest"],
"baseUrl": ".",
"paths": {
"pluton-core-backend/notifications/channels/NotificationChannelResolver": [