Skip to content

Commit

Permalink
Test: Add auth, user module E2E test code and add coverage test
Browse files Browse the repository at this point in the history
  • Loading branch information
J-Hoplin committed Jan 6, 2024
1 parent 4221952 commit 9e0e660
Show file tree
Hide file tree
Showing 10 changed files with 353 additions and 56 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,8 @@ lerna-debug.log*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/extensions.json

# Unit, E2e coverage result
e2e-coverage/*
unit-coverage/*
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"ci:init": "dotenv -e .ci.env -- npx prisma generate",
"ci:init": "dotenv -e .ci.env -- npx prisma db push",
"ci:unit": "dotenv -e .ci.env -- jest --setupFiles jest --config ./test/jest-unit.json --runInBand",
"ci:e2e": "dotenv -e .ci.env -- jest --config ./test/jest-e2e.json --runInBand",
"test:init": "dotenv -e .test.env -- npx prisma db push",
"test:e2e": "dotenv -e .test.env -- jest --config ./test/jest-e2e.json --runInBand",
"test:unit": "dotenv -e .test.env -- jest --setupFiles jest --config ./test/jest-unit.json --runInBand"
"test:e2e:cov": "dotenv -e .test.env -- jest --config ./test/jest-e2e.json --runInBand --coverage",
"test:unit": "dotenv -e .test.env -- jest --config ./test/jest-unit.json --runInBand",
"test:unit:cov": "dotenv -e .test.env -- jest --config ./test/jest-unit.json --runInBand --coverage"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.465.0",
Expand Down
37 changes: 37 additions & 0 deletions src/admin-init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { INestApplication, LoggerService } from '@nestjs/common';
import { PrismaService } from './prisma/prisma.service';
import { SystemLoggerService } from './system-logger/system-logger.service';
import * as bcrypt from 'bcryptjs';

export async function InitializeAdmin(app: INestApplication) {
// Generate default admin account
const prisma = app.get<PrismaService>(PrismaService);
const logger = app.get<LoggerService>(SystemLoggerService);

if (!(process.env.ADMIN_EMAIL && process.env.ADMIN_PW)) {
logger.error(
'Admin Email and Admin Pw not found. Please configure `.env` file and reboot',
);
throw new Error('Fail to initialize server');
} else {
const findAdmin = await prisma.user.findUnique({
where: {
email: process.env.ADMIN_EMAIL,
},
});
if (!findAdmin) {
// Initialize root admin
await prisma.user.create({
data: {
nickname: 'admin',
password: bcrypt.hashSync(process.env.ADMIN_PW, 10),
email: process.env.ADMIN_EMAIL,
type: 'Admin',
},
});
logger.log('Admin initialized');
} else {
logger.log('Admin already initialized');
}
}
}
65 changes: 65 additions & 0 deletions src/auth/auth.controller.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { AppModule } from 'app/app.module';
import * as request from 'supertest';
import { userSignupGen } from 'test/mock-generator';

describe('/auth Auth Controller', () => {
let app: INestApplication;

// Mock user
const user1 = userSignupGen();

beforeAll(async () => {
const testModule: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();

app = testModule.createNestApplication();
await app.init();
});

afterAll(async () => {
await app.close();
});

// Signup test
describe('/singup POST', () => {
it('should sign up', () => {
return request(app.getHttpServer())
.post('/auth/signup')
.send(user1)
.expect(200);
});

it('should throw if credential already taken', () => {
return request(app.getHttpServer())
.post('/auth/signup')
.send(user1)
.expect(400);
});
});

//Signin test
describe('/signin POST', () => {
it('should singin', () => {
return request(app.getHttpServer())
.post('/auth/signin')
.send({
password: user1.password,
email: user1.email,
})
.expect(200);
});

it('should throw if credential is not correct', () => {
return request(app.getHttpServer())
.post('/auth/signin')
.send({
email: user1.email,
password: 'wrong-password',
})
.expect(401);
});
});
});
39 changes: 4 additions & 35 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Logger, LoggerService, ValidationPipe } from '@nestjs/common';
import { PrismaService } from './prisma/prisma.service';
import * as bcrypt from 'bcryptjs';
import { SystemLoggerService } from './system-logger/system-logger.service';
import { InitializeAdmin } from './admin-init';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
Expand All @@ -24,36 +22,7 @@ async function bootstrap() {
.addBearerAuth()
.build();

// Generate default admin account
const prisma = app.get<PrismaService>(PrismaService);
const logger = app.get<LoggerService>(SystemLoggerService);

if (!(process.env.ADMIN_EMAIL && process.env.ADMIN_PW)) {
logger.error(
'Admin Email and Admin Pw not found. Please configure `.env` file and reboot',
);
throw new Error('Fail to initialize server');
} else {
const findAdmin = await prisma.user.findUnique({
where: {
email: process.env.ADMIN_EMAIL,
},
});
if (!findAdmin) {
// Initialize root admin
await prisma.user.create({
data: {
nickname: 'admin',
password: bcrypt.hashSync(process.env.ADMIN_PW, 10),
email: process.env.ADMIN_EMAIL,
type: 'Admin',
},
});
logger.log('Admin initialized');
} else {
logger.log('Admin already initialized');
}
}
await InitializeAdmin(app);

// Initialize Swagger Document
const document = SwaggerModule.createDocument(app, config);
Expand Down
Loading

1 comment on commit 9e0e660

@J-Hoplin
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blue/Green Deployment

  • PATCH /user/admin/role -> /user/role
  • POST /judge/:pid/submit -> /judge/:pid/submission

Please sign in to comment.