Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#142 testing framework #145

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"dev": "nodemon ./src/index.ts",
"start": "tsc && node dist/index.js",
"test": "jest --runInBand --watchAll"
"test": "jest --runInBand --watchAll --testTimeout=10000"
},
"dependencies": {
"@seitz/shared": "workspace:*",
Expand All @@ -31,6 +31,7 @@
"@types/passport-local": "^1.0.36",
"@types/supertest": "^2.0.15",
"jest": "^29.7.0",
"mongodb-memory-server": "^8.16.1",
"nodemon": "^3.0.1",
"supertest": "^6.3.3",
"ts-jest": "^29.1.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ app.use(passport.initialize());
app.use(passport.session());

// Routes
app.use("/admin/", adminRoutes);
app.use("/admin", adminRoutes);
app.use("/example/", exampleRoutes);
app.use("/studies/", studiesRoutes);
app.use("/tasks/", tasksRoutes);
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/models/battery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export const customizedBatterySchema = new Schema<ICustomizedBattery>({
battery: { type: Schema.Types.ObjectId, ref: "Battery", required: true },
name: { type: String, required: true },
values: [optionValueSchema],
isVisibleToNonAdmins: { type: Boolean, default: true },
});

export const CustomizedBattery = model<ICustomizedBattery>(
Expand Down
8 changes: 8 additions & 0 deletions packages/api/src/routes/admin.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,12 @@ router.delete(
route((req) => adminService.removeUserAsAdmin(req.params.id))
);

router.put(
"/battery/:id/visibility/:status",
isAdmin,
route((req) =>
adminService.updateAdminVisibility(req.params.id, req.params.status)
)
);

export default router;
23 changes: 22 additions & 1 deletion packages/api/src/services/admin.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import mongoose, { UpdateWriteOpResult } from "mongoose";
import { User, Battery } from "../models";
import { User, Battery, CustomizedBattery } from "../models";
import HttpError from "../types/errors";
import { APIResponse } from "../util/handlers";
import * as crypto from "crypto";
Expand All @@ -8,8 +8,10 @@ import type {
CreateBatteryStage,
CreateOption,
IBattery,
ICustomizedBattery,
IUser,
} from "@seitz/shared";
import { parseVisibility } from "@/util/validation.utils";

/* eslint-disable @typescript-eslint/no-explicit-any */

Expand Down Expand Up @@ -123,3 +125,22 @@ function parseOptions(s: any): CreateOption[] {
return acc;
}, []);
}

export const updateAdminVisibility = async (
batteryId: string,
visibility: string
): APIResponse<ICustomizedBattery> => {
const isVisibleToNonAdmins = parseVisibility(visibility);

const battery = await CustomizedBattery.findOneAndUpdate(
{ _id: batteryId },
{ isVisibleToNonAdmins: isVisibleToNonAdmins },
{ new: true }
);

if (!battery) {
throw new HttpError(404, `Battery not found with ID: ${batteryId}`);
}

return [200, battery];
};
6 changes: 6 additions & 0 deletions packages/api/src/types/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@ export default class HttpError extends Error {
this.status = status;
}
}

export class VisibilityError extends HttpError {
constructor(message: string) {
super(403, message);
}
}
23 changes: 23 additions & 0 deletions packages/api/src/util/validation.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { VisibilityError } from "@/types/errors";

export enum Visibility {
ON = "on",
OFF = "off",
}

export const parseVisibility = (visibility: string): boolean => {
try {
if (!Object.values(Visibility).includes(visibility as Visibility)) {
throw new VisibilityError(
`Invalid visibility value: '${visibility}'. Must be either '${Visibility.ON}' or '${Visibility.OFF}'`
);
}
return visibility === Visibility.ON;
} catch (e) {
// Log the error for monitoring but default to OFF for safety - debugging statement :/
console.warn(
`Invalid visibility value received: ${visibility}. Defaulting to OFF`
);
return false;
}
};
22 changes: 22 additions & 0 deletions packages/api/test/config/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";

let mongoServer: MongoMemoryServer;

export const connectDB = async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
await mongoose.connect(mongoUri);
};

export const closeDB = async () => {
await mongoose.disconnect();
await mongoServer.stop();
};

export const clearDB = async () => {
const collections = mongoose.connection.collections;
for (const key in collections) {
await collections[key].deleteMany({});
}
};
110 changes: 0 additions & 110 deletions packages/api/test/e2e/example.test.ts

This file was deleted.

43 changes: 43 additions & 0 deletions packages/api/test/seed/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import mongoose from "mongoose";
import { Battery, CustomizedBattery, User } from "../../src/models";
import type { CreateBattery, CreateUser } from "@seitz/shared";

export const seedUsers = [
{
_id: new mongoose.Types.ObjectId(),
email: "[email protected]",
password: "password123",
isAdmin: true,
},
{
_id: new mongoose.Types.ObjectId(),
email: "[email protected]",
password: "password123",
isAdmin: false,
},
] as CreateUser[];

export const seedBatteries = [
{
_id: new mongoose.Types.ObjectId(),
name: "Test Battery",
description: "A test battery",
imageUrl: "https://test.com/image.jpg",
stages: [],
deleted: false,
},
] as CreateBattery[];

export const seedCustomizedBatteries = [
{
_id: new mongoose.Types.ObjectId(),
battery: seedBatteries[0]._id,
isVisibleToNonAdmins: false,
},
];

export const seedDatabase = async () => {
await User.create(seedUsers);
await Battery.create(seedBatteries);
await CustomizedBattery.create(seedCustomizedBatteries);
};
85 changes: 85 additions & 0 deletions packages/api/test/unit/admin.service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { connectDB, closeDB, clearDB } from "../config/database";
import { seedDatabase, seedCustomizedBatteries } from "../seed";
import * as adminService from "../../src/services/admin.service";
import HttpError from "../../src/types/errors";

describe("Admin Service", () => {
beforeAll(async () => {
await connectDB();
});

beforeEach(async () => {
await clearDB();
await seedDatabase();
});

afterAll(async () => {
await closeDB();
});

describe("updateAdminVisibility", () => {
const batteryId = seedCustomizedBatteries[0]._id.toString();

it('should update visibility to true when setting to "on"', async () => {
const [status, battery] = await adminService.updateAdminVisibility(
batteryId,
"on"
);

expect(status).toBe(200);
expect(battery?.isVisibleToNonAdmins).toBe(true);
});

it('should update visibility to false when setting to "off"', async () => {
const [status, battery] = await adminService.updateAdminVisibility(
batteryId,
"off"
);

expect(status).toBe(200);
expect(battery?.isVisibleToNonAdmins).toBe(false);
});

it("should default to false for invalid visibility value", async () => {
const [status, battery] = await adminService.updateAdminVisibility(
batteryId,
"invalid"
);

expect(status).toBe(200);
expect(battery?.isVisibleToNonAdmins).toBe(false);
});

describe("edge cases should default to false", () => {
const testCases = [
{ desc: "undefined", value: undefined },
{ desc: "null", value: null },
{ desc: "empty string", value: "" },
{ desc: "number", value: 123 },
{ desc: "object", value: {} },
];

testCases.forEach(({ desc, value }) => {
it(`should handle ${desc} input`, async () => {
const [status, battery] = await adminService.updateAdminVisibility(
batteryId,
value as unknown as string // have to do this to avoid type error :/
);

expect(status).toBe(200);
expect(battery?.isVisibleToNonAdmins).toBe(false);
});
});
});

it("should throw 404 error for non-existent battery", async () => {
const nonExistentId = "507f1f77bcf86cd799439011";

await expect(
adminService.updateAdminVisibility(nonExistentId, "on")
).rejects.toThrow(
new HttpError(404, `Battery not found with ID: ${nonExistentId}`)
);
});
});
});
1 change: 1 addition & 0 deletions packages/shared/types/models/battery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export interface CreateCustomizedBattery {
battery: Types.ObjectId;
name: string;
values: CreateOptionValue[];
isVisibleToNonAdmins: boolean;
}

export interface ICustomizedBattery extends Required<CreateCustomizedBattery> {
Expand Down
Loading