Skip to content

Commit

Permalink
fix(docs): ajout de tests unitaires
Browse files Browse the repository at this point in the history
  • Loading branch information
pYassine committed Jul 5, 2023
1 parent 195855b commit ca0f785
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 8 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { pathExists } from "fs-extra";
import { InteractionsModule } from "../../../interactions/interactions.module";
import { AppLogsService } from "../../../modules/app-logs/app-logs.service";
import { StructuresModule } from "../../../structures/structure.module";
import { UsersModule } from "../../../users/users.module";
import { AppTestContext, AppTestHelper } from "../../../util/test";
import {
AppTestContext,
AppTestHelper,
AppTestHttpClient,
} from "../../../util/test";
import { UsagerDocsController } from "../usager-docs.controller";
import { resolve } from "path";
import { TESTS_USERS_STRUCTURE } from "../../../_tests";
import { UsagerDoc } from "../../../_common/model";
import { HttpStatus } from "@nestjs/common";

describe("Document Controller", () => {
let controller: UsagerDocsController;

let context: AppTestContext;
let doc: UsagerDoc;

beforeAll(async () => {
context = await AppTestHelper.bootstrapTestApp({
Expand All @@ -17,12 +27,54 @@ describe("Document Controller", () => {
providers: [AppLogsService],
});
controller = context.module.get<UsagerDocsController>(UsagerDocsController);

const authInfo = TESTS_USERS_STRUCTURE.BY_EMAIL["[email protected]"];

await AppTestHelper.authenticateStructure(authInfo, { context });
});

afterAll(async () => {
await AppTestHelper.tearDownTestApp(context);
});

it("should be defined", () => {
expect(controller).toBeDefined();
});

it(`✅ Ajout d'un fichier`, async () => {
const importFilePath = resolve(
__dirname,
"../../../_static/usager-docs-test/logo-beta.jpeg"
);

expect(await pathExists(importFilePath)).toBeTruthy();

const headers: { [name: string]: string } = {};
headers["Content-Type"] = "multipart/form-data";

const response = await AppTestHttpClient.post("/docs/1", {
headers,
attachments: { file: importFilePath },
fields: {
label: "Logo beta-gouv",
},
context,
});

expect(response.status).toBe(HttpStatus.OK);

expect(response.body.length).toEqual(2);
expect(response.body[1].createdBy).toEqual("Patrick Roméro");
expect(response.body[1].filetype).toEqual("image/jpeg");
expect(response.body[1].label).toEqual("Logo beta-gouv");

doc = response.body[1];
});
it(`✅ Suppression d'un fichier`, async () => {
const response = await AppTestHttpClient.delete(`/docs/1/${doc.uuid}`, {
context,
});

expect(response.status).toBe(HttpStatus.OK);
});
});
22 changes: 15 additions & 7 deletions packages/backend/src/usagers/controllers/usager-docs.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ export class UsagerDocsController {
}

let filePath = "";

if (doc.encryptionContext) {
filePath = await getFilePath(
user.structure.uuid,
Expand Down Expand Up @@ -216,8 +217,6 @@ export class UsagerDocsController {
@CurrentUser() user: UserStructureAuthenticated,
@CurrentUsager() currentUsager: Usager
) {
const mainSecret = domifaConfig().security.files.mainSecret;

const doc = await usagerDocsRepository.findOneBy({
uuid: docUuid,
usagerRef,
Expand All @@ -231,27 +230,36 @@ export class UsagerDocsController {
}

if (doc.encryptionContext) {
const mainSecret = domifaConfig().security.files.mainSecret;

const encryptedFilePath = await getFilePath(
user.structure.uuid,
doc.usagerUUID,
doc.path + ".sfe"
);

if (doc.encryptionVersion !== 0) {
throw new Error("Implement main secret rotation logic");
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "CANNOT_UPLOAD_FILE_MAIN" });
}

try {
return await pipeline(
return pipeline(
// note: encryptedFilePath should end with .sfe, not .encrypted, to prepare for phase 3.
createReadStream(encryptedFilePath),
decryptFile(mainSecret, doc.encryptionContext),
res
);
} catch (e) {
appLogger.error("Erreur");
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "CANNOT_UPLOAD_FILE" });
}
} else {
}

// @deprecated
else {
// @deprecated: delete this after migration
const sourceFileDir = getFileDir(
currentUsager.structureId,
Expand Down Expand Up @@ -343,7 +351,7 @@ export class UsagerDocsController {
);
}
} catch (e) {
console.error(e);
appLogger.error(e);
return new Error(
`Erreur de chiffrement : ${sourceFilePath} ${e.message}`
);
Expand Down
7 changes: 7 additions & 0 deletions packages/backend/src/util/test/AppTestHttpClient.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ function query(method: "post" | "put" | "patch" | "delete") {
authenticate = true,
body,
headers,
fields,
context,
attachments,
}: {
authenticate?: boolean;
body?: string | object;
headers?: { [name: string]: string };
fields?: { [name: string]: string };
context: AppTestContext;
attachments?: { [name: string]: string };
}
Expand All @@ -62,6 +64,11 @@ function query(method: "post" | "put" | "patch" | "delete") {
req = req.set(key, headers[key]);
});
}
if (fields) {
Object.keys(fields).forEach((key) => {
req = req.field(key, fields[key]);
});
}
if (attachments) {
Object.keys(attachments).forEach((key) => {
req = req.attach(key, attachments[key]);
Expand Down

0 comments on commit ca0f785

Please sign in to comment.