Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
test(backend:sync): improve coverage
johaven72327988741e
diff --git a/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts b/backend/src/applications/sync/services/sync-clients-manager.service.spec.tsindex a1df84ee..ced1f9dc 100644--- a/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts+++ b/backend/src/applications/sync/services/sync-clients-manager.service.spec.ts@@ -5,37 +5,409 @@*/import { HttpService } from '@nestjs/axios'+import { HttpStatus } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'+import { FastifyReply } from 'fastify'+import crypto from 'node:crypto'+import fs from 'node:fs/promises'import { AuthMethod } from '../../../authentication/models/auth-method'import { AuthManager } from '../../../authentication/services/auth-manager.service'+import * as commonFunctions from '../../../common/functions'+import * as commonShared from '../../../common/shared'+import { configuration } from '../../../configuration/config.environment'import { Cache } from '../../../infrastructure/cache/services/cache.service'+import { isPathExists } from '../../files/utils/files'import { UsersQueries } from '../../users/services/users-queries.service'+import { CLIENT_AUTH_TYPE, CLIENT_TOKEN_EXPIRED_ERROR } from '../constants/auth'+import { APP_STORE_DIRNAME, APP_STORE_REPOSITORY } from '../constants/store'+import { SYNC_CLIENT_TYPE } from '../constants/sync'import { SyncClientsManager } from './sync-clients-manager.service'import { SyncQueries } from './sync-queries.service'+// Pilotage permission via UserModel+let mockHavePermission = true+jest.mock('../../users/models/user.model', () => ({+ UserModel: jest.fn().mockImplementation((props: any) => ({+ ...props,+ havePermission: () => mockHavePermission+ }))+}))++// Mock ciblé de convertHumanTimeToSeconds+jest.mock('../../../common/functions', () => {+ const actual = jest.requireActual('../../../common/functions')+ return { ...actual, convertHumanTimeToSeconds: jest.fn() }+})++// Mock currentTimeStamp+jest.mock('../../../common/shared', () => ({ currentTimeStamp: jest.fn() }))++// Mock FS et helper d'existence+jest.mock('node:fs/promises', () => ({ readFile: jest.fn() }))+jest.mock('../../files/utils/files', () => ({ isPathExists: jest.fn() }))+describe(SyncClientsManager.name, () => {let service: SyncClientsManager+ // Mocks+ let http: { axiosRef: jest.Mock }+ let authManager: { setCookies: jest.Mock; getTokens: jest.Mock }+ let authMethod: { validateUser: jest.Mock }+ let usersQueries: { from: jest.Mock; updateUserOrGuest: jest.Mock }+ let syncQueries: {+ getOrCreateClient: jest.Mock+ deleteClient: jest.Mock+ getClient: jest.Mock+ updateClientInfo: jest.Mock+ renewClientTokenAndExpiration: jest.Mock+ getClients: jest.Mock+ }+ let cacheMock: { genSlugKey: jest.Mock; get: jest.Mock; set: jest.Mock; del: jest.Mock }++ // Helpers+ const setRepo = (repo: APP_STORE_REPOSITORY) => {+ ;(configuration as any).applications.appStore.repository = repo+ }+ const makeClient = (overrides: any = {}) => ({+ id: 'cid',+ ownerId: 1,+ tokenExpiration: 2000,+ enabled: true,+ info: { type: 'desktop' },+ ...overrides+ })+ const makeUser = (overrides: any = {}) => ({+ id: 1,+ isActive: true,+ login: 'u',+ email: 'u@x',+ firstName: 'U',+ lastName: 'X',+ role: 1,+ permissions: 'desktop',+ ...overrides+ })+beforeAll(async () => {+ http = { axiosRef: jest.fn() }+ authManager = { setCookies: jest.fn(), getTokens: jest.fn() }+ authMethod = { validateUser: jest.fn() }+ usersQueries = { from: jest.fn(), updateUserOrGuest: jest.fn() }+ syncQueries = {+ getOrCreateClient: jest.fn(),+ deleteClient: jest.fn(),+ getClient: jest.fn(),+ updateClientInfo: jest.fn(),+ renewClientTokenAndExpiration: jest.fn(),+ getClients: jest.fn()+ }+ cacheMock = {+ genSlugKey: jest.fn().mockReturnValue('syncclientsmanager:checkappstore'),+ get: jest.fn().mockResolvedValue(undefined),+ set: jest.fn().mockResolvedValue(undefined),+ del: jest.fn().mockResolvedValue(undefined)+ }+const module: TestingModule = await Test.createTestingModule({providers: [SyncClientsManager,- { provide: Cache, useValue: {} },- { provide: HttpService, useValue: {} },- { provide: SyncQueries, useValue: {} },- { provide: UsersQueries, useValue: {} },- { provide: AuthManager, useValue: {} },- {- provide: AuthMethod,- useValue: {}- }+ { provide: Cache, useValue: cacheMock },+ { provide: HttpService, useValue: http },+ { provide: SyncQueries, useValue: syncQueries },+ { provide: UsersQueries, useValue: usersQueries },+ { provide: AuthManager, useValue: authManager },+ { provide: AuthMethod, useValue: authMethod }]}).compile()+ module.useLogger(['fatal'])service = module.get<SyncClientsManager>(SyncClientsManager)+ ;(service as any).cache = cacheMock+ })++ beforeEach(() => {+ jest.restoreAllMocks()+ jest.clearAllMocks()+ mockHavePermission = true+ ;(commonShared.currentTimeStamp as jest.Mock).mockReturnValue(1_000)+ ;(commonFunctions.convertHumanTimeToSeconds as jest.Mock).mockImplementation((v: string | number) => {+ if (v === '90d') return 90 * 24 * 3600+ if (v === '180d') return 180 * 24 * 3600+ if (typeof v === 'number') return v+ return 0+ })+ ;(isPathExists as jest.Mock).mockReset()+ ;(fs.readFile as jest.Mock).mockReset()+ ;(syncQueries.updateClientInfo as jest.Mock).mockResolvedValue(undefined)+ ;(usersQueries.updateUserOrGuest as jest.Mock).mockResolvedValue(undefined)+ ;(service as any).cache = cacheMock+ cacheMock.get.mockResolvedValue(undefined)+ cacheMock.get.mockClear()+ cacheMock.set.mockClear()+ cacheMock.del.mockClear()+ cacheMock.genSlugKey.mockClear()+ setRepo(APP_STORE_REPOSITORY.PUBLIC)+ })++ it('should be defined', () => expect(service).toBeDefined())++ describe('register', () => {+ const baseDto = { login: 'john', password: 'secret', clientId: 'client-1', info: { type: 'desktop', version: '1.0.0' } }++ test.each([+ ['Unauthorized when credentials are invalid', null, HttpStatus.UNAUTHORIZED],+ ['Forbidden when user lacks DESKTOP_APP permission', { id: 10, login: 'john', havePermission: () => false }, HttpStatus.FORBIDDEN]+ ])('should throw %s', async (_label, user, status) => {+ authMethod.validateUser.mockResolvedValue(user)+ await expect(service.register(baseDto as any, '1.2.3.4')).rejects.toMatchObject({ status })+ })++ it('should return client token when registration succeeds', async () => {+ authMethod.validateUser.mockResolvedValue({ id: 10, login: 'john', havePermission: () => true })+ syncQueries.getOrCreateClient.mockResolvedValue('token-abc')++ const r = await service.register(baseDto as any, '1.2.3.4')+ expect(r).toEqual({ clientToken: 'token-abc' })+ expect(syncQueries.getOrCreateClient).toHaveBeenCalledWith(10, 'client-1', baseDto.info, '1.2.3.4')+ })++ it('should throw Internal Server Error when persistence fails', async () => {+ authMethod.validateUser.mockResolvedValue({ id: 10, login: 'john', havePermission: () => true })+ syncQueries.getOrCreateClient.mockRejectedValue(new Error('db error'))+ await expect(service.register(baseDto as any, '1.2.3.4')).rejects.toMatchObject({ status: HttpStatus.INTERNAL_SERVER_ERROR })+ })+ })++ describe('unregister', () => {+ it('should delete client without error', async () => {+ syncQueries.deleteClient.mockResolvedValue(undefined)+ await expect(service.unregister({ id: 1, clientId: 'c1' } as any)).resolves.toBeUndefined()+ expect(syncQueries.deleteClient).toHaveBeenCalledWith(1, 'c1')+ })+ it('should throw Internal Server Error when deletion fails', async () => {+ syncQueries.deleteClient.mockRejectedValue(new Error('db error'))+ await expect(service.unregister({ id: 1, clientId: 'c1' } as any)).rejects.toMatchObject({ status: HttpStatus.INTERNAL_SERVER_ERROR })+ })+ })++ describe('authenticate', () => {+ const ip = '9.9.9.9'+ const dto = { clientId: 'cid', token: 'ctok' }++ it('should forbid when client is unknown', async () => {+ syncQueries.getClient.mockResolvedValue(undefined)+ await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ response: 'Client is unknown'+ })+ })++ it('should forbid when client is disabled', async () => {+ syncQueries.getClient.mockResolvedValue(makeClient({ enabled: false, tokenExpiration: 5000 }))+ await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ response: 'Client is disabled'+ })+ })++ it('should forbid when client token is expired', async () => {+ ;(commonShared.currentTimeStamp as jest.Mock).mockReturnValue(1000)+ syncQueries.getClient.mockResolvedValue(makeClient({ tokenExpiration: 1000 }))+ await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ response: CLIENT_TOKEN_EXPIRED_ERROR+ })+ })++ it('should forbid when owner user does not exist', async () => {+ syncQueries.getClient.mockResolvedValue(makeClient())+ syncQueries.updateClientInfo.mockRejectedValueOnce(new Error('update-fails')) // silence expected+ usersQueries.from.mockResolvedValue(null)+ await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ response: 'User does not exist'+ })+ })++ it('should forbid when owner account is inactive', async () => {+ syncQueries.getClient.mockResolvedValue(makeClient())+ usersQueries.from.mockResolvedValue(makeUser({ isActive: false }))+ await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ response: 'Account suspended or not authorized'+ })+ })++ it('should forbid when owner lacks DESKTOP_APP permission', async () => {+ mockHavePermission = false+ syncQueries.getClient.mockResolvedValue(makeClient())+ usersQueries.from.mockResolvedValue(makeUser({ permissions: '', role: 999 }))+ await expect(service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ response: 'Missing permission'+ })+ })++ it('should perform COOKIE authentication and renew client token when needed', async () => {+ syncQueries.getClient.mockResolvedValue(makeClient({ ownerId: 7 }))+ usersQueries.from.mockResolvedValue(makeUser({ id: 7, login: 'john', email: 'john@doe', firstName: 'John', lastName: 'Doe' }))+ usersQueries.updateUserOrGuest.mockRejectedValueOnce(new Error('update-access-fail')) // silence expected+ authManager.setCookies.mockResolvedValue({ access_token: 'a', refresh_token: 'b' })+ jest.spyOn(service, 'renewTokenAndExpiration').mockResolvedValue('new-client-token')++ const reply = {} as unknown as FastifyReply+ const r: any = await service.authenticate(CLIENT_AUTH_TYPE.COOKIE, dto as any, ip, reply)++ expect(authManager.setCookies).toHaveBeenCalledTimes(1)+ expect(service.renewTokenAndExpiration).toHaveBeenCalledTimes(1)+ expect(r.client_token_update).toBe('new-client-token')+ })++ it('should perform TOKEN authentication and not renew when not needed', async () => {+ syncQueries.getClient.mockResolvedValue(makeClient({ ownerId: 8 }))+ usersQueries.from.mockResolvedValue(makeUser({ id: 8, login: 'alice', email: 'alice@doe', firstName: 'Alice' }))+ authManager.getTokens.mockResolvedValue({ access_token: 'x', refresh_token: 'y' })+ jest.spyOn(service, 'renewTokenAndExpiration').mockResolvedValue(undefined)++ const r: any = await service.authenticate(CLIENT_AUTH_TYPE.TOKEN, dto as any, ip, {} as FastifyReply)+ expect(authManager.getTokens).toHaveBeenCalledTimes(1)+ expect(r.client_token_update).toBeUndefined()+ })++ it('should throw when auth type is unknown (else branch)', async () => {+ syncQueries.getClient.mockResolvedValue(makeClient({ ownerId: 9 }))+ usersQueries.from.mockResolvedValue(makeUser({ id: 9, login: 'bob', email: 'bob@doe', firstName: 'Bob' }))+ jest.spyOn(service, 'renewTokenAndExpiration').mockResolvedValue(undefined)+ await expect(service.authenticate('unknown' as any, { clientId: 'cid', token: 'ctok' } as any, ip, {} as FastifyReply)).rejects.toBeInstanceOf(+ TypeError+ )+ })+ })++ describe('getClients', () => {+ it('should proxy to SyncQueries.getClients', async () => {+ const fake = [{ id: 'c1', paths: [] }]+ syncQueries.getClients.mockResolvedValue(fake)+ const r = await service.getClients({ id: 1, clientId: 'c1' } as any)+ expect(r).toBe(fake)+ expect(syncQueries.getClients).toHaveBeenCalledWith({ id: 1, clientId: 'c1' })+ })+ })++ describe('renewTokenAndExpiration', () => {+ const owner = { id: 1, login: 'bob' } as any++ it('should return undefined when token expiration is far enough', async () => {+ ;(commonShared.currentTimeStamp as jest.Mock).mockReturnValue(1_000)+ ;(commonFunctions.convertHumanTimeToSeconds as jest.Mock).mockImplementation((v: string) => (v === '90d' ? 90 * 24 * 3600 : 0))+ const client = { id: 'cid', tokenExpiration: 1_000 + 90 * 24 * 3600 + 1 } as any+ expect(await service.renewTokenAndExpiration(client, owner)).toBeUndefined()+ })++ it('should renew token and return new value when close to expiration', async () => {+ ;(commonShared.currentTimeStamp as jest.Mock).mockReturnValue(1_000)+ ;(commonFunctions.convertHumanTimeToSeconds as jest.Mock).mockImplementation((v: string) =>+ v === '90d' ? 90 * 24 * 3600 : v === '180d' ? 180 * 24 * 3600 : 0+ )+ const client = { id: 'cid', tokenExpiration: 1_000 + 90 * 24 * 3600 - 1 } as any+ syncQueries.renewClientTokenAndExpiration.mockResolvedValue(undefined)++ const r = await service.renewTokenAndExpiration(client, owner)+ expect(typeof r).toBe('string')+ expect(r).toBeTruthy()+ expect(syncQueries.renewClientTokenAndExpiration).toHaveBeenCalledWith('cid', r, expect.any(Number))+ })++ it('should throw Bad Request when renewal persistence fails', async () => {+ ;(commonShared.currentTimeStamp as jest.Mock).mockReturnValue(1_000)+ const client = { id: 'cid', tokenExpiration: 1_000 } as any+ jest.spyOn(crypto, 'randomUUID').mockReturnValue('uuid-err' as any)+ syncQueries.renewClientTokenAndExpiration.mockRejectedValue(new Error('db fail'))+ await expect(service.renewTokenAndExpiration(client, owner)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })+ })+ })++ describe('deleteClient', () => {+ it('should delete client successfully', async () => {+ syncQueries.deleteClient.mockResolvedValue(undefined)+ await expect(service.deleteClient({ id: 5 } as any, 'cid')).resolves.toBeUndefined()+ expect(syncQueries.deleteClient).toHaveBeenCalledWith(5, 'cid')+ })+ it('should throw Internal Server Error when deletion fails', async () => {+ syncQueries.deleteClient.mockRejectedValue(new Error('db error'))+ await expect(service.deleteClient({ id: 5 } as any, 'cid')).rejects.toMatchObject({ status: HttpStatus.INTERNAL_SERVER_ERROR })+ })})- it('should be defined', () => {- expect(service).toBeDefined()+ describe('checkAppStore', () => {+ it('should return PUBLIC manifest when HTTP fetch succeeds', async () => {+ setRepo(APP_STORE_REPOSITORY.PUBLIC)+ http.axiosRef.mockResolvedValue({ data: { platform: { win: [] } } })++ const manifest: any = await service.checkAppStore()+ expect(manifest).toBeTruthy()+ expect(manifest.repository).toBe(APP_STORE_REPOSITORY.PUBLIC)+ expect(http.axiosRef).toHaveBeenCalled()+ })++ it('should return null when PUBLIC manifest fetch fails', async () => {+ setRepo(APP_STORE_REPOSITORY.PUBLIC)+ http.axiosRef.mockRejectedValue(new Error('network'))+ expect(await service.checkAppStore()).toBeNull()+ })++ it('should return null when LOCAL manifest file does not exist', async () => {+ setRepo(APP_STORE_REPOSITORY.LOCAL)+ ;(isPathExists as jest.Mock).mockResolvedValue(false)+ expect(await service.checkAppStore()).toBeNull()+ })++ it('should return LOCAL manifest with rewritten URLs when file is valid', async () => {+ setRepo(APP_STORE_REPOSITORY.LOCAL)+ ;(isPathExists as jest.Mock).mockResolvedValue(true)+ const raw = {+ platform: {+ win: [{ package: 'desktop-win.exe' }, { package: 'cli-win.zip' }],+ linux: [{ package: 'desktop-linux.AppImage' }]+ }+ }+ ;(fs.readFile as jest.Mock).mockResolvedValue(JSON.stringify(raw))++ const manifest: any = await service.checkAppStore()+ expect(manifest.repository).toBe(APP_STORE_REPOSITORY.LOCAL)+ expect(manifest.platform.win[0].url.startsWith(APP_STORE_DIRNAME)).toBe(true)+ expect(manifest.platform.win[0].url.endsWith('desktop-win.exe')).toBe(true)+ expect(manifest.platform.win[1].url.startsWith(APP_STORE_DIRNAME)).toBe(true)+ expect(manifest.platform.win[1].url.endsWith('cli-win.zip')).toBe(true)+ expect(manifest.platform.linux[0].url.startsWith(APP_STORE_DIRNAME)).toBe(true)+ expect(manifest.platform.linux[0].url.endsWith('desktop-linux.AppImage')).toBe(true)+ })++ it('should return null when LOCAL manifest cannot be parsed', async () => {+ setRepo(APP_STORE_REPOSITORY.LOCAL)+ ;(isPathExists as jest.Mock).mockResolvedValue(true)+ ;(fs.readFile as jest.Mock).mockRejectedValue(new Error('fs error'))+ expect(await service.checkAppStore()).toBeNull()+ })++ it('should rewrite desktop packages under desktop/os when package starts with "desktop"', async () => {+ setRepo(APP_STORE_REPOSITORY.LOCAL)+ ;(isPathExists as jest.Mock).mockResolvedValue(true)+ const raw = {+ platform: {+ win: [{ package: `${SYNC_CLIENT_TYPE.DESKTOP}-win.exe` }],+ mac: [{ package: `${SYNC_CLIENT_TYPE.DESKTOP}-mac.dmg` }],+ linux: [{ package: `${SYNC_CLIENT_TYPE.DESKTOP}-linux.AppImage` }]+ }+ }+ ;(fs.readFile as jest.Mock).mockResolvedValue(JSON.stringify(raw))++ const manifest: any = await service.checkAppStore()+ expect(manifest).toBeTruthy()+ expect(manifest.repository).toBe(APP_STORE_REPOSITORY.LOCAL)+ expect(manifest.platform.win[0].url).toBe(`${APP_STORE_DIRNAME}/${SYNC_CLIENT_TYPE.DESKTOP}/win/${SYNC_CLIENT_TYPE.DESKTOP}-win.exe`)+ expect(manifest.platform.mac[0].url).toBe(`${APP_STORE_DIRNAME}/${SYNC_CLIENT_TYPE.DESKTOP}/mac/${SYNC_CLIENT_TYPE.DESKTOP}-mac.dmg`)+ expect(manifest.platform.linux[0].url).toBe(`${APP_STORE_DIRNAME}/${SYNC_CLIENT_TYPE.DESKTOP}/linux/${SYNC_CLIENT_TYPE.DESKTOP}-linux.AppImage`)+ })})})diff --git a/backend/src/applications/sync/services/sync-manager.service.spec.ts b/backend/src/applications/sync/services/sync-manager.service.spec.tsindex 8ad339ca..2b84dd94 100644--- a/backend/src/applications/sync/services/sync-manager.service.spec.ts+++ b/backend/src/applications/sync/services/sync-manager.service.spec.ts@@ -4,32 +4,591 @@* See the LICENSE file for licensing details*/+import { HttpException, HttpStatus, StreamableFile } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'+// Helpers to access mocked fs/promises+import fsPromisesModule from 'fs/promises'+import path from 'node:path'+import { FILE_OPERATION } from '../../files/constants/operations'+import { FileError } from '../../files/models/file-error'+import { LockConflict } from '../../files/models/file-lock-error'import { FilesManager } from '../../files/services/files-manager.service'+import { checksumFile, isPathExists, isPathIsDir, removeFiles, touchFile } from '../../files/utils/files'import { SpacesManager } from '../../spaces/services/spaces-manager.service'+import { F_SPECIAL_STAT, F_STAT, SYNC_CHECKSUM_ALG, SYNC_DIFF_DONE } from '../constants/sync'import { SyncManager } from './sync-manager.service'import { SyncQueries } from './sync-queries.service'+// Mock fs/promises used internally by the service+jest.mock('fs/promises', () => ({+ __esModule: true,+ default: {+ stat: jest.fn(),+ readdir: jest.fn()+ }+}))++// Mock helper functions used in service+jest.mock('../../files/utils/files', () => ({+ __esModule: true,+ checksumFile: jest.fn(),+ isPathExists: jest.fn(),+ isPathIsDir: jest.fn(),+ removeFiles: jest.fn(),+ touchFile: jest.fn(),+ sanitizePath: jest.fn((p: string) => p)+}))++// Mock regExpPathPattern to a simple, predictable behavior+jest.mock('../../../common/functions', () => ({+ __esModule: true,+ regExpPathPattern: (base: string) => new RegExp('^' + base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))+}))++// Mock routes helper used by copyMove to bypass repo validation+jest.mock('../utils/routes', () => ({+ __esModule: true,+ SYNC_PATH_TO_SPACE_SEGMENTS: jest.fn((dst: string) => dst)+}))++// Mock heavy providers to avoid configuration side-effects on import+jest.mock('../../files/services/files-manager.service', () => ({+ __esModule: true,+ FilesManager: class FilesManager {}+}))+jest.mock('../../spaces/services/spaces-manager.service', () => ({+ __esModule: true,+ SpacesManager: class SpacesManager {}+}))+jest.mock('./sync-queries.service', () => ({+ __esModule: true,+ SyncQueries: class SyncQueries {}+}))++const fsPromises = fsPromisesModule as unknown as { stat: jest.Mock; readdir: jest.Mock }++// small helper to collect async generators+const collect = async <T>(iter: AsyncIterable<T>): Promise<T[]> => {+ const out: T[] = []+ for await (const i of iter) out.push(i)+ return out+}+describe(SyncManager.name, () => {let service: SyncManager+ let filesManager: {+ sendFileFromSpace: jest.Mock+ saveStream: jest.Mock+ delete: jest.Mock+ touch: jest.Mock+ mkDir: jest.Mock+ mkFile: jest.Mock+ copyMove: jest.Mock+ }+ let spacesManager: { spaceEnv: jest.Mock }+ let syncQueries: { getPathSettings: jest.Mock }beforeAll(async () => {+ filesManager = {+ sendFileFromSpace: jest.fn(),+ saveStream: jest.fn(),+ delete: jest.fn(),+ touch: jest.fn(),+ mkDir: jest.fn(),+ mkFile: jest.fn(),+ copyMove: jest.fn()+ }+ spacesManager = { spaceEnv: jest.fn() }+ syncQueries = { getPathSettings: jest.fn() }+const module: TestingModule = await Test.createTestingModule({providers: [SyncManager,- { provide: SpacesManager, useValue: {} },- { provide: FilesManager, useValue: {} },- {- provide: SyncQueries,- useValue: {}- }+ { provide: SpacesManager, useValue: spacesManager },+ { provide: FilesManager, useValue: filesManager },+ { provide: SyncQueries, useValue: syncQueries }]}).compile()+ module.useLogger(['fatal'])service = module.get<SyncManager>(SyncManager)})- it('should be defined', () => {- expect(service).toBeDefined()+ beforeEach(() => jest.clearAllMocks())++ const makeReq = (over?: Partial<any>) => ({+ method: 'PUT',+ user: { id: 1, clientId: 42 },+ space: { realPath: '/base/file.txt', url: '/space/file.txt' },+ ...over+ })++ const makeReply = () => {+ const raw = { writeHead: jest.fn(), write: jest.fn(), end: jest.fn() }+ return { raw, status: jest.fn().mockReturnThis() }+ }++ describe('download', () => {+ it('should stream file successfully', async () => {+ const req = makeReq()+ const res = makeReply()+ const checks = jest.fn().mockResolvedValue(undefined)+ const stream = jest.fn().mockResolvedValue(new StreamableFile(Buffer.from('abc')))+ filesManager.sendFileFromSpace.mockReturnValue({ checks, stream })++ const result = await service.download(req as any, res as any)++ expect(filesManager.sendFileFromSpace).toHaveBeenCalledWith(req.space)+ expect(checks).toHaveBeenCalled()+ expect(stream).toHaveBeenCalledWith(req, res)+ expect(result).toBeInstanceOf(StreamableFile)+ })++ it.each([+ ['LockConflict maps to 423', new LockConflict(null, 'locked'), HttpStatus.LOCKED],+ ['FileError maps to its http code', new FileError(HttpStatus.BAD_REQUEST, 'bad'), HttpStatus.BAD_REQUEST],+ ['generic Error maps to 500', new Error('oops'), HttpStatus.INTERNAL_SERVER_ERROR]+ ])('should map errors (%s)', async (_title, thrown, expectedStatus) => {+ const req = makeReq()+ const res = makeReply()+ const checks = jest.fn().mockRejectedValue(thrown)+ const stream = jest.fn()+ filesManager.sendFileFromSpace.mockReturnValue({ checks, stream })++ await expect(service.download(req as any, res as any)).rejects.toMatchObject({ status: expectedStatus })+ })+ })++ describe('upload', () => {+ it('should upload with checksum OK and return ino', async () => {+ const req = makeReq({ space: { realPath: '/tmp/up.bin', url: '/space/up.bin' } })+ const dto = { checksum: 'abc', size: 10, mtime: 1710000000 }+ filesManager.saveStream.mockResolvedValue('abc')+ fsPromises.stat.mockResolvedValue({ size: 10, ino: 123, mtime: new Date(1710000000 * 1000) })+ ;(touchFile as jest.Mock).mockResolvedValue(undefined)++ const r = await service.upload(req as any, dto as any)+ expect(filesManager.saveStream).toHaveBeenCalledWith(req.user, req.space, req, { tmpPath: expect.any(String), checksumAlg: SYNC_CHECKSUM_ALG })+ expect(touchFile).toHaveBeenCalledWith('/tmp/up.bin', 1710000000)+ expect(r).toEqual({ ino: 123 })+ expect(removeFiles).not.toHaveBeenCalled()+ })++ it('should reject when checksum mismatches and remove tmp', async () => {+ const req = makeReq()+ const dto = { checksum: 'abc', size: 10, mtime: 1710000000 }+ filesManager.saveStream.mockResolvedValue('bad')+ fsPromises.stat.mockResolvedValue({ size: 10, ino: 123, mtime: new Date(1710000000 * 1000) })++ await expect(service.upload(req as any, dto as any)).rejects.toBeInstanceOf(HttpException)+ expect(removeFiles).toHaveBeenCalledWith(expect.any(String))+ })++ it('should upload without checksum', async () => {+ const req = makeReq({ space: { realPath: '/tmp/up2.bin', url: '/space/up2.bin' } })+ const dto = { size: 5, mtime: 1710000100 }+ filesManager.saveStream.mockResolvedValue(undefined)+ fsPromises.stat.mockResolvedValue({ size: 5, ino: 321, mtime: new Date(1710000100 * 1000) })++ const r = await service.upload(req as any, dto as any)+ expect(filesManager.saveStream).toHaveBeenCalledWith(req.user, req.space, req, { tmpPath: expect.any(String) })+ expect(touchFile).toHaveBeenCalledWith('/tmp/up2.bin', 1710000100)+ expect(r).toEqual({ ino: 321 })+ })++ it('should reject when size mismatches and remove tmp', async () => {+ const req = makeReq()+ const dto = { size: 10, mtime: 1710000100 }+ filesManager.saveStream.mockResolvedValue(undefined)+ fsPromises.stat.mockResolvedValue({ size: 99, ino: 321, mtime: new Date(1710000100 * 1000) })++ await expect(service.upload(req as any, dto as any)).rejects.toBeInstanceOf(HttpException)+ expect(removeFiles).toHaveBeenCalledWith(expect.any(String))+ })+ })++ describe('delete', () => {+ it('should delete successfully', async () => {+ const req = makeReq()+ filesManager.delete.mockResolvedValue(undefined)++ await expect(service.delete(req as any)).resolves.toBeUndefined()+ expect(filesManager.delete).toHaveBeenCalledWith(req.user, req.space)+ })++ it('should map errors via handleError', async () => {+ const req = makeReq()+ filesManager.delete.mockRejectedValue(new LockConflict(null, 'locked'))++ await expect(service.delete(req as any)).rejects.toMatchObject({ status: HttpStatus.LOCKED })+ })+ })++ describe('props', () => {+ it('should touch successfully', async () => {+ const req = makeReq()+ filesManager.touch.mockResolvedValue(undefined)++ await expect(service.props(req as any, { mtime: 1710000200 } as any)).resolves.toBeUndefined()+ expect(filesManager.touch).toHaveBeenCalledWith(req.user, req.space, 1710000200, false)+ })++ it('should map errors via handleError', async () => {+ const req = makeReq()+ filesManager.touch.mockRejectedValue(new FileError(HttpStatus.BAD_REQUEST, 'bad'))++ await expect(service.props(req as any, { mtime: 123 } as any)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })+ })+ })++ describe('make', () => {+ it('should create directory and return ino', async () => {+ const req = makeReq({ space: { realPath: '/tmp/newdir', url: '/space/newdir' } })+ filesManager.mkDir.mockResolvedValue(undefined)+ fsPromises.stat.mockResolvedValue({ ino: 555 })+ ;(touchFile as jest.Mock).mockResolvedValue(undefined)++ const r = await service.make(req as any, { type: 'directory', mtime: 1710000300 } as any)+ expect(filesManager.mkDir).toHaveBeenCalledWith(req.user, req.space, true)+ expect(touchFile).toHaveBeenCalledWith('/tmp/newdir', 1710000300)+ expect(r).toEqual({ ino: 555 })+ })++ it('should create file and return ino', async () => {+ const req = makeReq({ space: { realPath: '/tmp/newfile', url: '/space/newfile' } })+ filesManager.mkFile.mockResolvedValue(undefined)+ fsPromises.stat.mockResolvedValue({ ino: 777 })++ const r = await service.make(req as any, { type: 'file', mtime: 1710000400 } as any)+ expect(filesManager.mkFile).toHaveBeenCalledWith(req.user, req.space, true)+ expect(touchFile).toHaveBeenCalledWith('/tmp/newfile', 1710000400)+ expect(r).toEqual({ ino: 777 })+ })++ it('should map errors via handleError', async () => {+ const req = makeReq()+ filesManager.mkDir.mockRejectedValue(new LockConflict(null, 'locked'))++ await expect(service.make(req as any, { type: 'directory', mtime: 0 } as any)).rejects.toMatchObject({ status: HttpStatus.LOCKED })+ })+ })++ describe('copyMove', () => {+ it('should move (no return) and not touch mtime', async () => {+ const req = makeReq()+ const dstSpace = { realPath: '/dst/moved', url: '/space/dst/moved' }+ spacesManager.spaceEnv.mockResolvedValue(dstSpace)+ filesManager.copyMove.mockResolvedValue(undefined)++ const r = await service.copyMove(req as any, { destination: '/dst/moved' } as any, true)+ expect(spacesManager.spaceEnv).toHaveBeenCalled()+ expect(filesManager.copyMove).toHaveBeenCalledWith(req.user, req.space, dstSpace, true, true, true)+ expect(touchFile).not.toHaveBeenCalled()+ expect(r).toBeUndefined()+ })++ it('should copy, touch mtime when provided, and return ino/mtime', async () => {+ const req = makeReq()+ const dstSpace = { realPath: '/dst/copied', url: '/space/dst/copied' }+ spacesManager.spaceEnv.mockResolvedValue(dstSpace)+ filesManager.copyMove.mockResolvedValue(undefined)+ fsPromises.stat.mockResolvedValue({ ino: 999, mtime: new Date(1710000500 * 1000) })++ const r = await service.copyMove(req as any, { destination: '/dst/copied', mtime: 1710000500 } as any, false)+ expect(filesManager.copyMove).toHaveBeenCalledWith(req.user, req.space, dstSpace, false, true, true)+ expect(touchFile).toHaveBeenCalledWith('/dst/copied', 1710000500)+ expect(r).toEqual({ ino: 999, mtime: 1710000500 })+ })++ it('should copy without mtime and still return ino/mtime', async () => {+ const req = makeReq()+ const dstSpace = { realPath: '/dst/copied2', url: '/space/dst/copied2' }+ spacesManager.spaceEnv.mockResolvedValue(dstSpace)+ filesManager.copyMove.mockResolvedValue(undefined)+ fsPromises.stat.mockResolvedValue({ ino: 1001, mtime: new Date(1710000600 * 1000) })++ const r = await service.copyMove(req as any, { destination: '/dst/copied2' } as any, false)+ expect(touchFile).not.toHaveBeenCalled()+ expect(r).toEqual({ ino: 1001, mtime: 1710000600 })+ })++ it('should map errors via handleError', async () => {+ const req = makeReq()+ const dstSpace = { realPath: '/dst/err', url: '/space/dst/err' }+ spacesManager.spaceEnv.mockResolvedValue(dstSpace)+ filesManager.copyMove.mockRejectedValue(new FileError(HttpStatus.BAD_REQUEST, 'bad'))++ await expect(service.copyMove(req as any, { destination: '/dst/err' } as any, false)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })+ })++ it('should map errors via handleError for move (isMove=true)', async () => {+ const req = makeReq()+ const dstSpace = { realPath: '/dst/err-move', url: '/space/dst/err-move' }+ spacesManager.spaceEnv.mockResolvedValue(dstSpace)+ filesManager.copyMove.mockRejectedValue(new LockConflict(null, 'locked'))++ const spy = jest.spyOn(service as any, 'handleError')++ await expect(service.copyMove(req as any, { destination: '/dst/err-move' } as any, true)).rejects.toMatchObject({+ status: HttpStatus.LOCKED+ })++ expect(spy).toHaveBeenCalledWith(req.space, FILE_OPERATION.MOVE, expect.anything(), dstSpace)+ })+ })++ describe('parseSyncPath', () => {+ it('should delegate to parseFiles and yield file stats from the base directory', async () => {+ const base = '/base-sync'+ const space = { realPath: base, url: '/space-sync', quotaIsExceeded: false }+ const dirent = { name: 'afile', parentPath: base, isDirectory: () => false, isFile: () => true }+ fsPromises.readdir.mockResolvedValue([dirent])+ fsPromises.stat.mockResolvedValue({ isDirectory: () => false, isFile: () => true, size: 42, ino: 7, mtime: new Date(1234 * 1000) })++ const syncDiff: any = { defaultFilters: new Set(), secureDiff: false, firstSync: true, snapshot: new Map() }++ const out = await collect<Record<string, any>>((service as any).parseSyncPath(space, syncDiff))++ expect(out.length).toBe(1)+ expect(out[0]).toHaveProperty('/afile')+ const stats = out[0]['/afile']+ expect(Array.isArray(stats)).toBe(true)+ expect(stats[F_STAT.IS_DIR]).toBe(false)+ expect(stats[F_STAT.SIZE]).toBe(42)+ expect(stats[F_STAT.MTIME]).toBe(1234)+ expect(stats[F_STAT.INO]).toBe(7)+ expect(stats[F_STAT.CHECKSUM]).toBeNull()+ })+ })++ describe('diff', () => {+ it('should fail when clientId is missing', async () => {+ const res = makeReply()+ await expect(service.diff({ id: 1 } as any, 1, {} as any, res as any)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })+ })++ it('should fail when path settings not found', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue(undefined)+ await expect(service.diff(user, 1, {} as any, res as any)).rejects.toMatchObject({ status: HttpStatus.NOT_FOUND })+ })++ it('should map spaceEnv thrown error to BAD_REQUEST', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue({ remotePath: '/base' })+ spacesManager.spaceEnv.mockRejectedValue(new Error('boom'))++ await expect(service.diff(user, 1, {} as any, res as any)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST, message: 'boom' })+ })++ it('should fail when space not found', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue({ remotePath: '/base' })+ spacesManager.spaceEnv.mockResolvedValue(undefined)++ await expect(service.diff(user, 1, {} as any, res as any)).rejects.toMatchObject({ status: HttpStatus.NOT_FOUND })+ })++ it('should fail when space quota exceeded', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue({ remotePath: '/base' })+ spacesManager.spaceEnv.mockResolvedValue({ realPath: '/base', url: '/space', quotaIsExceeded: true })++ await expect(service.diff(user, 1, {} as any, res as any)).rejects.toMatchObject({ status: HttpStatus.INSUFFICIENT_STORAGE })+ })++ it('should fail when remote path does not exist', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue({ remotePath: '/base' })+ spacesManager.spaceEnv.mockResolvedValue({ realPath: '/base', url: '/space', quotaIsExceeded: false })+ ;(isPathExists as jest.Mock).mockResolvedValue(false)++ await expect(service.diff(user, 1, {} as any, res as any)).rejects.toMatchObject({+ status: HttpStatus.NOT_FOUND,+ message: 'Remote path not found : /base'+ })+ })++ it('should fail when remote path is not a directory', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue({ remotePath: '/base' })+ spacesManager.spaceEnv.mockResolvedValue({ realPath: '/base', url: '/space', quotaIsExceeded: false })+ ;(isPathExists as jest.Mock).mockResolvedValue(true)+ ;(isPathIsDir as jest.Mock).mockResolvedValue(false)++ await expect(service.diff(user, 1, {} as any, res as any)).rejects.toMatchObject({+ status: HttpStatus.BAD_REQUEST,+ message: 'Remote path must be a directory'+ })+ })++ it('should stream diff results successfully', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue({ remotePath: '/base' })+ const space = { realPath: '/base', url: '/space', quotaIsExceeded: false }+ spacesManager.spaceEnv.mockResolvedValue(space)+ ;(isPathExists as jest.Mock).mockResolvedValue(true)+ ;(isPathIsDir as jest.Mock).mockResolvedValue(true)++ const gen = async function* () {+ yield { '/file1': [false, 1, 2, 3, 'x'] }+ yield { '/file2': [true, 0, 2, 4, null] }+ }+ jest.spyOn(service as any, 'parseSyncPath').mockImplementation(() => gen())++ await service.diff(user, 1, { secureDiff: false } as any, res as any)++ expect(res.raw.writeHead).toHaveBeenCalledWith(200, {+ 'Content-Type': 'text/plain; charset=utf-8',+ 'Transfer-Encoding': 'chunked'+ })+ expect(res.raw.write).toHaveBeenCalledWith(`${JSON.stringify({ '/file1': [false, 1, 2, 3, 'x'] })}\n`)+ expect(res.raw.write).toHaveBeenCalledWith(`${JSON.stringify({ '/file2': [true, 0, 2, 4, null] })}\n`)+ expect(res.raw.write).toHaveBeenCalledWith(SYNC_DIFF_DONE)+ expect(res.raw.end).toHaveBeenCalled()+ })++ it('should handle error during streaming and set status 500', async () => {+ const res = makeReply()+ const user = { id: 1, clientId: 9 } as any+ syncQueries.getPathSettings.mockResolvedValue({ remotePath: '/base' })+ const space = { realPath: '/base', url: '/space', quotaIsExceeded: false }+ spacesManager.spaceEnv.mockResolvedValue(space)+ ;(isPathExists as jest.Mock).mockResolvedValue(true)+ ;(isPathIsDir as jest.Mock).mockResolvedValue(true)++ jest.spyOn(service as any, 'parseSyncPath').mockImplementation(() => {+ throw new Error('parse error')+ })++ await service.diff(user, 1, {} as any, res as any)++ expect(res.raw.write).toHaveBeenCalledWith('parse error\n')+ expect(res.status).toHaveBeenCalledWith(HttpStatus.INTERNAL_SERVER_ERROR)+ expect(res.raw.end).toHaveBeenCalled()+ })+ })++ describe('internal parseFiles/analyzeFile coverage', () => {+ const makeDirent = (name: string, parentPath: string, kind: 'dir' | 'file' | 'other') => ({+ name,+ parentPath,+ isDirectory: () => kind === 'dir',+ isFile: () => kind === 'file'+ })++ it('should walk directory, ignore special files, filter by name/path, reuse snapshot checksum, and compute checksum when needed', async () => {+ const base = '/base'+ const ctx: any = {+ regexBasePath: new RegExp('^/base'),+ syncDiff: {+ defaultFilters: new Set<string>(['ignoredName']),+ pathFilters: /file2/,+ secureDiff: true,+ firstSync: false,+ snapshot: new Map<string, any>([['/file3', [false, 100, 1000, 33, 'snaphash']]])+ }+ }++ fsPromises.readdir.mockImplementation(async (dir: string) => {+ if (dir === base) {+ return [+ makeDirent('special', base, 'other'),+ makeDirent('dir1', base, 'dir'),+ makeDirent('ignoredName', base, 'file'),+ makeDirent('fileStatError', base, 'file'),+ makeDirent('file2', base, 'file'),+ makeDirent('file3', base, 'file'),+ makeDirent('file4', base, 'file')+ ]+ }+ if (dir === path.join(base, 'dir1')) return []+ return []+ })++ const mtimeDate = new Date(1000 * 1000)+ fsPromises.stat.mockImplementation(async (p: string) => {+ switch (p) {+ case path.join(base, 'dir1'):+ return { isDirectory: () => true, isFile: () => false, size: 0, ino: 11, mtime: mtimeDate }+ case path.join(base, 'fileStatError'):+ throw new Error('stat fail')+ case path.join(base, 'file2'):+ return { isDirectory: () => false, isFile: () => true, size: 10, ino: 22, mtime: mtimeDate }+ case path.join(base, 'file3'):+ return { isDirectory: () => false, isFile: () => true, size: 100, ino: 33, mtime: new Date(1000 * 1000) }+ case path.join(base, 'file4'):+ return { isDirectory: () => false, isFile: () => true, size: 200, ino: 44, mtime: new Date(2000 * 1000) }+ default:+ return { isDirectory: () => false, isFile: () => false, size: 0, ino: 0, mtime: new Date() }+ }+ })+ ;(checksumFile as jest.Mock).mockResolvedValue('computed-hash')++ const results = await collect<Record<string, any>>((service as any).parseFiles(base, ctx))++ const keys = results.map((o) => Object.keys(o)[0]).sort()+ expect(keys).toEqual(['/dir1', '/file2', '/file3', '/file4', '/fileStatError'])++ const fileStatError = results.find((o) => o['/fileStatError'])+ expect(fileStatError?.['/fileStatError'][0]).toBe(F_SPECIAL_STAT.ERROR)+ expect(fileStatError?.['/fileStatError'][1]).toContain('stat fail')++ const filtered = results.find((o) => o['/file2'])+ expect(filtered?.['/file2'][0]).toBe(F_SPECIAL_STAT.FILTERED)++ const reused = results.find((o) => o['/file3'])?.['/file3']+ expect(reused[F_STAT.CHECKSUM]).toBe('snaphash')+ expect(checksumFile).toHaveBeenCalledTimes(1)++ const computed = results.find((o) => o['/file4'])?.['/file4']+ expect(computed[F_STAT.CHECKSUM]).toBe('computed-hash')+ })++ it('should throw a generic error when readdir fails', async () => {+ fsPromises.readdir.mockRejectedValue(new Error('readdir fail'))++ const ctx: any = { regexBasePath: /./, syncDiff: { defaultFilters: new Set(), secureDiff: false } }+ const iter = (service as any).parseFiles('/any', ctx)++ await expect(+ (async () => {+ for await (const _ of iter) {+ /* consume */+ }+ })()+ ).rejects.toThrow('Unable to parse path')+ })++ it('should return ERROR when checkSumFile throws during analyzeFile', async () => {+ const base = '/base'+ const dirent = { name: 'badfile', parentPath: base, isDirectory: () => false, isFile: () => true }++ fsPromises.readdir.mockImplementation(async (dir: string) => (dir === base ? [dirent] : []))+ fsPromises.stat.mockResolvedValue({ isDirectory: () => false, isFile: () => true, size: 10, ino: 42, mtime: new Date(1234 * 1000) })++ jest.spyOn(service as any, 'checkSumFile').mockRejectedValue(new Error('checksum fail'))++ const ctx: any = {+ regexBasePath: new RegExp('^/base'),+ syncDiff: { defaultFilters: new Set<string>(), pathFilters: undefined, secureDiff: true, firstSync: false, snapshot: new Map<string, any>() }+ }++ const results = await collect<Record<string, any>>((service as any).parseFiles(base, ctx))++ expect(results).toHaveLength(1)+ expect(results[0]).toHaveProperty('/badfile')+ const out = results[0]['/badfile']+ expect(Array.isArray(out)).toBe(true)+ expect(out[0]).toBe(F_SPECIAL_STAT.ERROR)+ expect(String(out[1])).toContain('checksum fail')+ })})})diff --git a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts b/backend/src/applications/sync/services/sync-paths-manager.service.spec.tsindex 534663fe..fab6d1e0 100644--- a/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts+++ b/backend/src/applications/sync/services/sync-paths-manager.service.spec.ts@@ -4,38 +4,588 @@* See the LICENSE file for licensing details*/+import { HttpStatus } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'+import { currentTimeStamp } from '../../../common/shared'import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'import { FilesQueries } from '../../files/services/files-queries.service'+import { getProps, isPathExists, isPathIsDir } from '../../files/utils/files'import { NotificationsManager } from '../../notifications/services/notifications-manager.service'import { SpacesManager } from '../../spaces/services/spaces-manager.service'+import { getEnvPermissions } from '../../spaces/utils/permissions'import { UsersQueries } from '../../users/services/users-queries.service'import { SyncPathsManager } from './sync-paths-manager.service'import { SyncQueries } from './sync-queries.service'+// Mock modules used directly inside SyncPathsManager+jest.mock('../../../common/shared', () => ({+ currentTimeStamp: jest.fn(() => 1000)+}))+jest.mock('../../files/utils/files', () => ({+ isPathExists: jest.fn(),+ isPathIsDir: jest.fn(),+ getProps: jest.fn(),+ sanitizePath: jest.fn((p: string) => p)+}))+jest.mock('../../spaces/utils/permissions', () => ({+ getEnvPermissions: jest.fn(() => 'server-perms')+}))+jest.mock('../constants/sync', () => ({+ SYNC_PATH_REPOSITORY: {+ SPACES: ['spaces'],+ PERSONAL: ['personal'],+ SHARES: ['shares']+ }+}))+jest.mock('../../notifications/constants/notifications', () => ({+ NOTIFICATION_APP: { SYNC: 'SYNC' },+ NOTIFICATION_APP_EVENT: { SYNC: { DELETE: 'DELETE', CREATE: 'CREATE', UPDATE: 'UPDATE' } }+}))+describe(SyncPathsManager.name, () => {let service: SyncPathsManager+ let contextManager: { get: jest.Mock }+ let spacesManager: { spaceEnv: jest.Mock }+ let usersQueries: Record<string, jest.Mock>+ let filesQueries: { getSpaceFileId: jest.Mock; getOrCreateSpaceFile: jest.Mock }+ let notificationsManager: { create: jest.Mock }+ let syncQueries: {+ getClient: jest.Mock+ clientExistsForOwner: jest.Mock+ createPath: jest.Mock+ deletePath: jest.Mock+ getPaths: jest.Mock+ getPathSettings: jest.Mock+ updatePathSettings: jest.Mock+ clearCachePathSettings: jest.Mock+ }++ const userWith = (clientId?: string) => ({ id: 1, clientId })+ const flush = () => new Promise((r) => setImmediate(r))++ beforeEach(async () => {+ contextManager = { get: jest.fn(() => 'http://origin.local') }+ spacesManager = { spaceEnv: jest.fn() }+ usersQueries = {}+ filesQueries = {+ getSpaceFileId: jest.fn(),+ getOrCreateSpaceFile: jest.fn()+ }+ notificationsManager = {+ create: jest.fn().mockResolvedValue(undefined)+ }+ syncQueries = {+ getClient: jest.fn(),+ clientExistsForOwner: jest.fn(),+ createPath: jest.fn(),+ deletePath: jest.fn(),+ getPaths: jest.fn(),+ getPathSettings: jest.fn(),+ updatePathSettings: jest.fn().mockResolvedValue(undefined),+ clearCachePathSettings: jest.fn()+ }+ ;(isPathExists as jest.Mock).mockReset()+ ;(isPathIsDir as jest.Mock).mockReset()+ ;(getProps as jest.Mock).mockReset()+ ;(getEnvPermissions as jest.Mock).mockReset().mockReturnValue('server-perms')+ ;(currentTimeStamp as jest.Mock).mockReset().mockReturnValue(1000)- beforeAll(async () => {const module: TestingModule = await Test.createTestingModule({providers: [SyncPathsManager,- { provide: ContextManager, useValue: {} },- { provide: SpacesManager, useValue: {} },- { provide: UsersQueries, useValue: {} },- { provide: FilesQueries, useValue: {} },- { provide: NotificationsManager, useValue: {} },- {- provide: SyncQueries,- useValue: {}- }+ { provide: ContextManager, useValue: contextManager },+ { provide: SpacesManager, useValue: spacesManager },+ { provide: UsersQueries, useValue: usersQueries },+ { provide: FilesQueries, useValue: filesQueries },+ { provide: NotificationsManager, useValue: notificationsManager },+ { provide: SyncQueries, useValue: syncQueries }]}).compile()+ module.useLogger(['fatal'])service = module.get<SyncPathsManager>(SyncPathsManager)})it('should be defined', () => {expect(service).toBeDefined()})++ describe('createPath', () => {+ const baseReq = () =>+ ({+ user: { id: 1, clientId: 'client-1' },+ params: { '*': 'SPACES/alias/sub' },+ space: {+ realPath: '/real/path',+ quotaIsExceeded: false,+ root: { id: 1, alias: 'alias' },+ inFilesRepository: true,+ paths: ['sub'],+ dbFile: { ownerId: 1, path: '.' },+ id: 10+ }+ }) as any++ it('should throw BAD_REQUEST when client id is missing', async () => {+ const req = baseReq()+ req.user.clientId = undefined+ await expect(service.createPath(req, { remotePath: 'x' } as any)).rejects.toMatchObject({+ status: HttpStatus.BAD_REQUEST,+ message: 'Client id is missing'+ })+ })++ it('should throw INSUFFICIENT_STORAGE when space quota is exceeded', async () => {+ const req = baseReq()+ req.space.quotaIsExceeded = true+ await expect(service.createPath(req, { remotePath: 'x' } as any)).rejects.toMatchObject({+ status: HttpStatus.INSUFFICIENT_STORAGE+ })+ })++ it.each([+ {+ title: 'NOT_FOUND when remote path does not exist',+ setup: () => (isPathExists as jest.Mock).mockResolvedValue(false),+ expected: { status: HttpStatus.NOT_FOUND, message: 'Remote path not found : client/remote' }+ },+ {+ title: 'BAD_REQUEST when remote path is not a directory',+ setup: () => ((isPathExists as jest.Mock).mockResolvedValue(true), (isPathIsDir as jest.Mock).mockResolvedValue(false)),+ expected: { status: HttpStatus.BAD_REQUEST, message: 'Remote path must be a directory' }+ },+ {+ title: 'NOT_FOUND when client is not found',+ setup: () => (+ (isPathExists as jest.Mock).mockResolvedValue(true),+ (isPathIsDir as jest.Mock).mockResolvedValue(true),+ syncQueries.getClient.mockResolvedValue(null)+ ),+ expected: { status: HttpStatus.NOT_FOUND, message: 'Client not found' }+ }+ ])('should throw $title', async ({ setup, expected }) => {+ const req = baseReq()+ setup()+ await expect(service.createPath(req, { remotePath: 'client/remote' } as any)).rejects.toMatchObject(expected)+ })++ it('should create path and return id and permissions, overriding remotePath and permissions', async () => {+ const req = baseReq()+ ;(isPathExists as jest.Mock).mockResolvedValue(true)+ ;(isPathIsDir as jest.Mock).mockResolvedValue(true)+ ;(getEnvPermissions as jest.Mock).mockReturnValue('env-perms')+ syncQueries.getClient.mockResolvedValue({ id: 'client-1' })+ // Spy on private getDBProps to simplify+ const getDBPropsSpy = jest.spyOn<any, any>(service as any, 'getDBProps').mockResolvedValue({ ownerId: 1 })+ syncQueries.createPath.mockResolvedValue(123)++ const res = await service.createPath(req, { remotePath: 'client/remote', permissions: 'client-perms' } as any)+ expect(res).toEqual({ id: 123, permissions: 'env-perms' })+ expect(syncQueries.createPath).toHaveBeenCalledWith(+ 'client-1',+ { ownerId: 1 },+ expect.objectContaining({ remotePath: 'SPACES/alias/sub', permissions: 'env-perms' })+ )++ getDBPropsSpy.mockRestore()+ })+ })++ describe('deletePath', () => {+ it.each([+ { user: { id: 1, clientId: undefined } as any, id: 10, status: HttpStatus.BAD_REQUEST, msg: 'Client id is missing' },+ { user: { id: 1, clientId: 'c1' } as any, id: 10, status: HttpStatus.FORBIDDEN }+ ])('should handle errors (status=$status)', async ({ user, id, status, msg }) => {+ if (status === HttpStatus.FORBIDDEN) syncQueries.clientExistsForOwner.mockResolvedValue(false)+ await expect(service.deletePath(user, id)).rejects.toMatchObject(msg ? { status, message: msg } : { status })+ })++ it('should catch errors from deletePath and throw BAD_REQUEST', async () => {+ const user: any = { id: 1, clientId: 'c1' }+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.deletePath.mockRejectedValue(new Error('db'))+ await expect(service.deletePath(user, 10)).rejects.toMatchObject({+ status: HttpStatus.BAD_REQUEST,+ message: 'Unable to remove path'+ })+ expect(syncQueries.deletePath).toHaveBeenCalledWith('c1', 10)+ })++ it('should delete path successfully when allowed', async () => {+ const user: any = { id: 1, clientId: undefined }+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.deletePath.mockResolvedValue(undefined)+ await expect(service.deletePath(user, 10, 'cX')).resolves.toBeUndefined()+ expect(syncQueries.deletePath).toHaveBeenCalledWith('cX', 10)+ })+ })++ describe('updatePath', () => {+ it('should throw FORBIDDEN when client does not belong to owner', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(false)+ await expect(service.updatePath({ id: 1 } as any, 'c1', 5, {} as any)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN+ })+ })++ it('should throw NOT_FOUND when path settings do not exist', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPathSettings.mockResolvedValue(null)+ await expect(service.updatePath({ id: 1 } as any, 'c1', 5, {} as any)).rejects.toMatchObject({+ status: HttpStatus.NOT_FOUND,+ message: 'Sync path not found'+ })+ })++ it('should update path settings, set new timestamp, clear cache and return updated settings', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPathSettings.mockResolvedValue({ id: 5, timestamp: 500, lastSync: 1, remotePath: '/a', permissions: 'p' })+ syncQueries.updatePathSettings.mockResolvedValue(undefined)+ ;(currentTimeStamp as jest.Mock).mockReturnValue(4242)++ const out = await service.updatePath({ id: 1 } as any, 'c1', 5, { id: 666, lastSync: 3, permissions: 'new' } as any)+ expect(syncQueries.updatePathSettings).toHaveBeenCalledWith(+ 'c1',+ 5,+ expect.objectContaining({ id: 5, lastSync: 3, timestamp: 4242, permissions: 'new' })+ )+ expect(syncQueries.clearCachePathSettings).toHaveBeenCalledWith('c1', 5)+ expect(out).toEqual(expect.objectContaining({ id: 5, lastSync: 3, timestamp: 4242, permissions: 'new' }))+ })++ it('should clear cache and throw INTERNAL_SERVER_ERROR when update fails', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPathSettings.mockResolvedValue({ id: 5, timestamp: 500, lastSync: 1 })+ syncQueries.updatePathSettings.mockRejectedValue(new Error('db'))+ await expect(service.updatePath({ id: 1 } as any, 'c1', 5, {} as any)).rejects.toMatchObject({+ status: HttpStatus.INTERNAL_SERVER_ERROR,+ message: 'Unable to update path'+ })+ expect(syncQueries.clearCachePathSettings).toHaveBeenCalledWith('c1', 5)+ })+ })++ describe('updatePaths', () => {+ beforeEach(() => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'p' })+ })++ it('should throw when client id is missing', async () => {+ await expect(service.updatePaths(userWith(undefined) as any, [])).rejects.toMatchObject({+ status: HttpStatus.BAD_REQUEST,+ message: 'Client id is missing'+ })+ })++ it('should throw FORBIDDEN when client does not belong to owner', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(false)+ await expect(service.updatePaths(userWith('c1') as any, [])).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN+ })+ })++ it('should mark client paths as deleted and notify when no corresponding server paths (server remotePath undefined)', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 2, settings: { timestamp: 1, lastSync: 1 }, remotePath: undefined }])+ const clientPaths = [{ id: 1, remotePath: 'SPACES/a', timestamp: 1, lastSync: 1, permissions: 'p' } as any]++ const res = await service.updatePaths(userWith('c1') as any, clientPaths)+ expect(res.delete).toEqual([1])+ expect(notificationsManager.create).toHaveBeenCalledTimes(1)+ })++ it('should propagate spaceEnv errors as BAD_REQUEST', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 1, settings: { timestamp: 1, lastSync: 1 }, remotePath: 'SPACES/x' }])+ spacesManager.spaceEnv.mockRejectedValue(new Error('boom'))+ await expect(+ service.updatePaths(userWith('c1') as any, [{ id: 1, remotePath: 'SPACES/x', timestamp: 1, lastSync: 1, permissions: 'p' } as any])+ ).rejects.toMatchObject({+ status: HttpStatus.BAD_REQUEST,+ message: 'boom'+ })+ })++ it('should skip server path when space is null and mark client item as deleted', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 2, settings: { timestamp: 1, lastSync: 1 }, remotePath: 'SPACES/x' }])+ spacesManager.spaceEnv.mockResolvedValue(null)+ const res = await service.updatePaths(userWith('c1') as any, [+ { id: 2, remotePath: 'SPACES/x', timestamp: 1, lastSync: 1, permissions: 'p' } as any+ ])+ expect(res.delete).toEqual([2])+ expect(notificationsManager.create).toHaveBeenCalledTimes(1)+ })++ it('should add server-only path to client with server permissions', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 3, settings: { timestamp: 1, lastSync: 1 }, remotePath: 'SPACES/x' }])+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'perm-xyz' })+ const res = await service.updatePaths(userWith('c1') as any, [])+ expect(res.add).toHaveLength(1)+ expect(res.add[0]).toEqual(expect.objectContaining({ id: 3, remotePath: 'SPACES/x', permissions: 'perm-xyz' }))+ })++ it('should update server settings from client when client is newer (no hasUpdates)', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 5, settings: { timestamp: 1, lastSync: 1, foo: 'server' }, remotePath: 'SPACES/x' }])+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'p' })++ const client = [{ id: 5, timestamp: 10, lastSync: 2, remotePath: 'SPACES/x', permissions: 'p', foo: 'client' } as any]+ await service.updatePaths(userWith('c1') as any, client)++ expect(syncQueries.updatePathSettings).toHaveBeenCalledWith('c1', 5, expect.objectContaining({ foo: 'client', lastSync: 2 }))+ // No client update instructions because hasUpdates=false and serverNewer=false+ })++ it('should push server-newer updates to client and also remotePath/permissions corrections', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 7, settings: { timestamp: 20, lastSync: 5, srv: true }, remotePath: 'SPACES/correct' }])+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'permX' })++ const client = [{ id: 7, timestamp: 10, lastSync: 5, remotePath: 'SPACES/wrong', permissions: 'old' } as any]+ const res = await service.updatePaths(userWith('c1') as any, client)++ // Should have two client updates: one full server settings + corrections, and one corrections-only+ expect(res.update).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: 7, srv: true, remotePath: 'SPACES/correct', permissions: 'permX' }),+ expect.objectContaining({ id: 7, remotePath: 'SPACES/correct', permissions: 'permX' })+ ])+ )+ expect(syncQueries.updatePathSettings).toHaveBeenCalledWith('c1', 7, expect.objectContaining({ lastSync: 5 }))+ // clear cache called for each update instruction+ expect(syncQueries.clearCachePathSettings).toHaveBeenCalledTimes(res.update.length)+ for (const u of res.update) {+ expect(syncQueries.clearCachePathSettings).toHaveBeenCalledWith('c1', u.id)+ }+ })++ it('should trigger update when lastSync differs even if timestamps and settings match', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 9, settings: { timestamp: 10, lastSync: 1, flag: 'S' }, remotePath: 'SPACES/x' }])+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'p' })++ const client = [{ id: 9, timestamp: 10, lastSync: 2, remotePath: 'SPACES/x', permissions: 'p', flag: 'S' } as any]+ await service.updatePaths(userWith('c1') as any, client)+ expect(syncQueries.updatePathSettings).toHaveBeenCalledWith('c1', 9, expect.objectContaining({ lastSync: 2 }))+ })++ it('should perform no changes when client and server are identical (no-op branch)', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 12, settings: { timestamp: 5, lastSync: 7, flag: 'A' }, remotePath: 'SPACES/x' }])+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'p' })++ const client = [{ id: 12, timestamp: 5, lastSync: 7, remotePath: 'SPACES/x', permissions: 'p', flag: 'A' } as any]+ const res = await service.updatePaths(userWith('c1') as any, client)++ expect(res).toEqual({ add: [], update: [], delete: [] })+ expect(syncQueries.updatePathSettings).not.toHaveBeenCalled()+ })++ it('should correct client info while keeping server settings when timestamps are equal (hasUpdates=true)', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ // Server has srv='S', client has wrong remotePath/permissions and extra clientOnly flag+ syncQueries.getPaths.mockResolvedValue([{ id: 13, settings: { timestamp: 5, lastSync: 1, srv: 'S' }, remotePath: 'SPACES/correct' }])+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'permX' })++ const client = [{ id: 13, timestamp: 5, lastSync: 1, remotePath: 'SPACES/wrong', permissions: 'old', clientOnly: 'C' } as any]+ const res = await service.updatePaths(userWith('c1') as any, client)++ // Server uses its own settings base (srv: 'S') with corrections applied+ expect(syncQueries.updatePathSettings).toHaveBeenCalledWith(+ 'c1',+ 13,+ expect.objectContaining({ srv: 'S', lastSync: 1, remotePath: 'SPACES/correct', permissions: 'permX' })+ )+ // Client should receive corrections for remotePath and permissions+ expect(res.update).toEqual(expect.arrayContaining([expect.objectContaining({ id: 13, remotePath: 'SPACES/correct', permissions: 'permX' })]))+ })++ it('should log error when updatePathSettings rejects inside updatePaths', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([{ id: 11, settings: { timestamp: 1, lastSync: 1 }, remotePath: 'SPACES/x' }])+ spacesManager.spaceEnv.mockResolvedValue({ envPermissions: 'p' })+ // Force client newer to trigger updatePathSettings+ const client = [{ id: 11, timestamp: 10, lastSync: 2, remotePath: 'SPACES/x', permissions: 'p' } as any]+ syncQueries.updatePathSettings.mockRejectedValueOnce(new Error('db-fail'))+ const loggerSpy = jest.spyOn((service as any).logger, 'error').mockImplementation(() => undefined)++ await service.updatePaths(userWith('c1') as any, client)+ // wait for microtasks to ensure .catch executed+ await flush()++ expect(loggerSpy).toHaveBeenCalled()+ expect(loggerSpy.mock.calls.some(([msg]) => String(msg).includes('updatePaths'))).toBe(true)+ })++ it('should catch notify failure at updatePaths level when building notification fails', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ // No server paths: will mark client path as deleted and call notify+ syncQueries.getPaths.mockResolvedValue([])+ const loggerSpy = jest.spyOn((service as any).logger, 'error').mockImplementation(() => undefined)+ // BAD first segment to make notify fail while building URL (before notificationsManager.create)+ const client = [{ id: 1, remotePath: 'BAD/a/b', timestamp: 1, lastSync: 1, permissions: 'p' } as any]++ const res = await service.updatePaths(userWith('c1') as any, client)+ await flush()++ expect(res.delete).toEqual([1])+ expect(loggerSpy).toHaveBeenCalled()+ expect(loggerSpy.mock.calls.some(([msg]) => String(msg).includes('updatePaths'))).toBe(true)+ // create not called because we failed before reaching it+ expect(notificationsManager.create).not.toHaveBeenCalled()+ })++ it('should catch error inside notify when notifications creation fails', async () => {+ syncQueries.clientExistsForOwner.mockResolvedValue(true)+ syncQueries.getPaths.mockResolvedValue([])+ // Valid remotePath to build URL correctly+ const client = [{ id: 2, remotePath: 'SPACES/a', timestamp: 1, lastSync: 1, permissions: 'p' } as any]+ const loggerSpy = jest.spyOn((service as any).logger, 'error').mockImplementation(() => undefined)+ notificationsManager.create.mockRejectedValueOnce(new Error('notify-fail'))++ const res = await service.updatePaths(userWith('c1') as any, client)+ await flush()++ expect(res.delete).toEqual([2])+ expect(loggerSpy).toHaveBeenCalled()+ // error comes from notify() catch+ expect(loggerSpy.mock.calls.some(([msg]) => String(msg).includes('notify'))).toBe(true)+ })+ })++ describe('getDBProps (private) branches', () => {+ it('should throw BAD_REQUEST for shares list selection', async () => {+ await expect((service as any).getDBProps({ inSharesList: true } as any)).rejects.toMatchObject({+ status: HttpStatus.BAD_REQUEST,+ message: 'Sync all shares is not supported, you must select a sub-directory'+ })+ })++ it('should return ownerId only for personal space at root', async () => {+ const res = await (service as any).getDBProps({+ inSharesList: false,+ inPersonalSpace: true,+ paths: [],+ dbFile: { ownerId: 42 }+ } as any)+ expect(res).toEqual({ ownerId: 42 })+ })++ it('should return ownerId and fileId for personal space subdir', async () => {+ const getOrCreateFileIdSpy = jest.spyOn<any, any>(service as any, 'getOrCreateFileId').mockResolvedValue(77)+ const res = await (service as any).getDBProps({+ inPersonalSpace: true,+ paths: ['sub'],+ dbFile: { ownerId: 42 }+ } as any)+ expect(res).toEqual({ ownerId: 42, fileId: 77 })+ getOrCreateFileIdSpy.mockRestore()+ })++ it('should throw BAD_REQUEST for whole files repository without alias', async () => {+ await expect((service as any).getDBProps({ inFilesRepository: true, root: { alias: null }, paths: [] } as any)).rejects.toMatchObject({+ status: HttpStatus.BAD_REQUEST,+ message: 'Sync all space is not yet supported, you must select a sub-directory'+ })+ })++ it('should return spaceId and rootId for files repository root selection', async () => {+ const res = await (service as any).getDBProps({+ inFilesRepository: true,+ id: 5,+ root: { id: 3, alias: 'x' },+ paths: []+ } as any)+ expect(res).toEqual({ spaceId: 5, spaceRootId: 3 })+ })++ it('should return spaceId, rootId and fileId for files repository subdir or null root', async () => {+ const getOrCreateFileIdSpy = jest.spyOn<any, any>(service as any, 'getOrCreateFileId').mockResolvedValue(88)+ const res = await (service as any).getDBProps({+ inFilesRepository: true,+ id: 5,+ root: { id: 3, alias: 'x' },+ paths: ['sub']+ } as any)+ expect(res).toEqual({ spaceId: 5, spaceRootId: 3, fileId: 88 })+ getOrCreateFileIdSpy.mockRestore()+ })++ it('should return spaceId and null spaceRootId plus fileId when files repository root has no id', async () => {+ const getOrCreateFileIdSpy = jest.spyOn<any, any>(service as any, 'getOrCreateFileId').mockResolvedValue(90)+ const res = await (service as any).getDBProps({+ inFilesRepository: true,+ id: 6,+ root: { id: undefined, alias: 'x' },+ paths: []+ } as any)+ expect(res).toEqual({ spaceId: 6, spaceRootId: null, fileId: 90 })+ getOrCreateFileIdSpy.mockRestore()+ })++ it('should return shareId only for shares repository root', async () => {+ const res = await (service as any).getDBProps({+ inSharesList: false,+ inPersonalSpace: false,+ inFilesRepository: false,+ inSharesRepository: true,+ id: 9,+ paths: []+ } as any)+ expect(res).toEqual({ shareId: 9 })+ })++ it('should return shareId and fileId for shares repository subdir', async () => {+ const getOrCreateFileIdSpy = jest.spyOn<any, any>(service as any, 'getOrCreateFileId').mockResolvedValue(55)+ const res = await (service as any).getDBProps({+ inSharesList: false,+ inPersonalSpace: false,+ inFilesRepository: false,+ inSharesRepository: true,+ id: 9,+ paths: ['sub']+ } as any)+ expect(res).toEqual({ shareId: 9, fileId: 55 })+ getOrCreateFileIdSpy.mockRestore()+ })++ it('should return undefined when no space flags match (no branch taken)', async () => {+ const res = await (service as any).getDBProps({+ inSharesList: false,+ inPersonalSpace: false,+ inFilesRepository: false,+ inSharesRepository: false,+ paths: []+ } as any)+ expect(res).toBeUndefined()+ })+ })++ describe('getOrCreateFileId (private) branches', () => {+ it('should return existing file id without creation', async () => {+ ;(getProps as jest.Mock).mockResolvedValue({ name: 'file' })+ filesQueries.getSpaceFileId.mockResolvedValue(101)+ const id = await (service as any).getOrCreateFileId({+ realPath: '/rp',+ dbFile: { path: '.' }+ })+ expect(id).toBe(101)+ expect(filesQueries.getOrCreateSpaceFile).not.toHaveBeenCalled()+ })++ it('should create file when not exists and return its id', async () => {+ ;(getProps as jest.Mock).mockResolvedValue({ id: 999, name: 'file' })+ filesQueries.getSpaceFileId.mockResolvedValue(0)+ filesQueries.getOrCreateSpaceFile.mockResolvedValue(202)+ const id = await (service as any).getOrCreateFileId({+ realPath: '/rp',+ dbFile: { path: '.' }+ })+ expect(id).toBe(202)+ expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(0, expect.objectContaining({ id: undefined }), { path: '.' })+ })+ })})