Skip to content

Commit

Permalink
WIP restructure test setup
Browse files Browse the repository at this point in the history
  • Loading branch information
CeEv committed Jul 24, 2024
1 parent 9ff1e42 commit ffe98a4
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 89 deletions.
116 changes: 73 additions & 43 deletions apps/server/src/modules/files/uc/delete-files.uc.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { S3Client } from '@aws-sdk/client-s3';
import { AwsClientStub, mockClient } from 'aws-sdk-client-mock';
import { createMock, DeepMocked } from '@golevelup/ts-jest';
import { Test, TestingModule } from '@nestjs/testing';
import { ObjectId } from '@mikro-orm/mongodb';
Expand All @@ -11,36 +9,14 @@ import { FilesRepo } from '../repo';
import { fileEntityFactory, filePermissionEntityFactory } from '../entity/testing';

describe(DeleteFilesUc.name, () => {
let module: TestingModule;
let service: DeleteFilesUc;
let filesRepo: DeepMocked<FilesRepo>;
let storageProviderRepo: DeepMocked<StorageProviderRepo>;
let s3Mock: AwsClientStub<S3Client>;
let logger: DeepMocked<LegacyLogger>;

const userId = new ObjectId().toHexString();

const storageProvider = storageProviderFactory.build();

const exampleFiles = [
fileEntityFactory.build({
storageProvider,
ownerId: userId,
creatorId: userId,
permissions: [filePermissionEntityFactory.build({ refId: userId })],
}),
fileEntityFactory.build({
storageProvider,
ownerId: userId,
creatorId: userId,
permissions: [filePermissionEntityFactory.build({ refId: userId })],
}),
];

beforeAll(async () => {
exampleFiles[0].id = '123';
exampleFiles[1].id = '456';

const module: TestingModule = await Test.createTestingModule({
module = await Test.createTestingModule({
providers: [
DeleteFilesUc,
{
Expand All @@ -65,11 +41,11 @@ describe(DeleteFilesUc.name, () => {
});

beforeEach(() => {
s3Mock = mockClient(S3Client);
jest.resetAllMocks();
});

afterEach(() => {
jest.resetAllMocks();
afterAll(async () => {
await module.close();
});

it('should be defined', () => {
Expand All @@ -81,24 +57,62 @@ describe(DeleteFilesUc.name, () => {
const setup = () => {
const thresholdDate = new Date();
const batchSize = 3;
filesRepo.findForCleanup.mockResolvedValueOnce(exampleFiles);
filesRepo.findForCleanup.mockResolvedValueOnce([]);

const userId = new ObjectId().toHexString();
const storageProvider = storageProviderFactory.build();

const exampleFiles = [
fileEntityFactory.buildWithId({
storageProvider,
ownerId: userId,
creatorId: userId,
permissions: [filePermissionEntityFactory.build({ refId: userId })],
isDirectory: false,
}),
fileEntityFactory.buildWithId({
storageProvider,
ownerId: userId,
creatorId: userId,
permissions: [filePermissionEntityFactory.build({ refId: userId })],
isDirectory: false,
}),
];

const s3ClientMock = {
send: jest.fn(),
};

// Please note the second try, that found no more files that needs to be deleted.
filesRepo.findForCleanup.mockResolvedValueOnce(exampleFiles).mockResolvedValueOnce([]);
filesRepo.delete.mockResolvedValueOnce();
storageProviderRepo.findAll.mockResolvedValueOnce([storageProvider]);
const spy = jest
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.spyOn(DeleteFilesUc.prototype as any, 'getClientForFile')
.mockImplementation(() => s3ClientMock);

return { thresholdDate, batchSize };
return { thresholdDate, batchSize, exampleFiles, spy };
};

it('should delete all marked files in storage', async () => {
it('should create correct log result', async () => {
const { thresholdDate, batchSize } = setup();

await service.deleteMarkedFiles(thresholdDate, batchSize);

expect(s3Mock.send.callCount).toEqual(2);
expect(logger.log).toBeCalledTimes(4);
expect(logger.error).toBeCalledTimes(0);
});

it('should delete all marked files in S3', async () => {
const { thresholdDate, batchSize, spy } = setup();

await service.deleteMarkedFiles(thresholdDate, batchSize);

expect(spy).toHaveBeenCalledTimes(2);
});

it('should delete all marked files in database', async () => {
const { thresholdDate, batchSize } = setup();
const { thresholdDate, batchSize, exampleFiles } = setup();

await service.deleteMarkedFiles(thresholdDate, batchSize);

Expand All @@ -114,13 +128,29 @@ describe(DeleteFilesUc.name, () => {
const batchSize = 3;
const error = new Error();

filesRepo.findForCleanup.mockResolvedValueOnce(exampleFiles);
filesRepo.findForCleanup.mockResolvedValueOnce([]);

const userId = new ObjectId().toHexString();
const storageProvider = storageProviderFactory.build();

const exampleFiles = [
fileEntityFactory.buildWithId({
storageProvider,
ownerId: userId,
creatorId: userId,
permissions: [filePermissionEntityFactory.build({ refId: userId })],
}),
fileEntityFactory.buildWithId({
storageProvider,
ownerId: userId,
creatorId: userId,
permissions: [filePermissionEntityFactory.build({ refId: userId })],
}),
];

// Please note the second try, that found no more files that needs to be deleted.
filesRepo.findForCleanup.mockResolvedValueOnce(exampleFiles).mockResolvedValueOnce([]);
storageProviderRepo.findAll.mockResolvedValueOnce([storageProvider]);

const spy = jest.spyOn(DeleteFilesUc.prototype as any, 'deleteFileInStorage');
spy.mockRejectedValueOnce(error);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const spy = jest.spyOn(DeleteFilesUc.prototype as any, 'deleteFileInStorage').mockImplementation(() => error);

return { thresholdDate, batchSize, error, spy };
};
Expand All @@ -138,15 +168,15 @@ describe(DeleteFilesUc.name, () => {

await service.deleteMarkedFiles(thresholdDate, batchSize);

expect(filesRepo.delete).toBeCalledTimes(exampleFiles.length - 1);
expect(filesRepo.delete).toBeCalledTimes(2);
});

it('should continue with other files', async () => {
const { thresholdDate, batchSize, spy } = setup();

await service.deleteMarkedFiles(thresholdDate, batchSize);

expect(spy).toBeCalledTimes(exampleFiles.length);
expect(spy).toBeCalledTimes(2);
});
});
});
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/modules/files/uc/delete-files.uc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class DeleteFilesUc {
}
}

private getProviderForFile(file: FileEntity): S3Client {
private getClientForFile(file: FileEntity): S3Client {
const storageProvider = TypeGuard.checkNotNullOrUndefined(
file.storageProvider,
new Error(`File ${file.id} has no provider.`)
Expand All @@ -120,7 +120,7 @@ export class DeleteFilesUc {
const { bucket, storageFileName } = file;
const deletionCommand = new DeleteObjectCommand({ Bucket: bucket, Key: storageFileName });

const client = this.getProviderForFile(file);
const client = this.getClientForFile(file);

await client.send(deletionCommand);
}
Expand Down
77 changes: 34 additions & 43 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,6 @@
"@typescript-eslint/eslint-plugin": "^5.47.1",
"@typescript-eslint/parser": "^5.47.1",
"@typescript-eslint/typescript-estree": "^5.47.1",
"aws-sdk-client-mock": "^0.5.5",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"chai-http": "^4.2.0",
Expand Down

0 comments on commit ffe98a4

Please sign in to comment.