Skip to content

Commit

Permalink
Merge pull request #459 from boostcampwm-2022/test/#421-service-unit
Browse files Browse the repository at this point in the history
리뷰와 신고 서비스의 단위 테스트를 작성했습니다.
  • Loading branch information
shyuuuuni authored Dec 15, 2022
2 parents 4eaf971 + fac9558 commit 2da02fc
Show file tree
Hide file tree
Showing 4 changed files with 293 additions and 8 deletions.
14 changes: 7 additions & 7 deletions scheduler-server/src/ranking/ranking.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,28 +75,28 @@ export class RankingService {
return;
}

const timeWaste = this.calcTimeWaste(idx);
const timeWeight = this.calcTimeWeight(idx);
for (const tag in tagCounts) {
if (totalTagCounts[tag]) {
totalTagCounts[tag] += tagCounts[tag] * timeWaste;
totalTagCounts[tag] += tagCounts[tag] * timeWeight;
continue;
}

totalTagCounts[tag] = tagCounts[tag] * timeWaste;
totalTagCounts[tag] = tagCounts[tag] * timeWeight;
}
});

return totalTagCounts;
}

/**
/*
* 시간 가중치는 현재 큐의 인덱스와 배열의 크기에 따라 정해진다
*/
private calcTimeWaste(idx: number): number {
private calcTimeWeight(idx: number): number {
const offset = idx - this.index + ARRAY_SIZE - 1;
const timeWaste = ((offset % ARRAY_SIZE) + 1) / ARRAY_SIZE;
const timeWeight = ((offset % ARRAY_SIZE) + 1) / ARRAY_SIZE;

return timeWaste;
return timeWeight;
}

private addPrevInfo(newRanking: any[]) {
Expand Down
2 changes: 1 addition & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.service.(t|j)s"
"src/**/*.service.(t|j)s"
],
"coverageDirectory": "./coverage",
"testEnvironment": "node"
Expand Down
111 changes: 111 additions & 0 deletions server/src/domain/report/report.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PostAlreadyReportedException } from 'src/exception/post-already-reported.exception';
import { PostNotFoundException } from 'src/exception/post-not-found.exception';
import { UserNotFoundException } from 'src/exception/user-not-found.exception';
import { Post } from '../post/post.entity';
import { PostRepository } from '../post/post.repository';
import { User } from '../user/user.entity';
import { UserRepository } from '../user/user.repository';
import { ReportCreateRequestDto } from './dto/controller-request.dto';
import { Report } from './report.entity';
import { ReportRepository } from './report.repository';
import { ReportService } from './report.service';

describe('신고 서비스', () => {
let testingModule: TestingModule;
let reportService: ReportService;
let reportRepository: ReportRepository;
let userRepository: UserRepository;
let postRepository: PostRepository;

beforeAll(async () => {
testingModule = await Test.createTestingModule({
providers: [
ReportService,
{
provide: ReportRepository,
useValue: {},
},
{
provide: PostRepository,
useValue: {},
},
{
provide: UserRepository,
useValue: {},
},
],
}).compile();
});

beforeEach(() => {
reportService = testingModule.get<ReportService>(ReportService);
reportRepository = testingModule.get<ReportRepository>(ReportRepository);
postRepository = testingModule.get<PostRepository>(PostRepository);
userRepository = testingModule.get<UserRepository>(UserRepository);
});

describe('신고하기', () => {
it('존재하지 않는 유저가 신고를 하면 UserNotFoundException이 발생한다.', async () => {
// given
const userId = 1;
const postId = 1;
const requestDto = new ReportCreateRequestDto();

userRepository.findOneBy = jest.fn();
postRepository.findOneBy = jest.fn();

// when
try {
await reportService.report(userId, postId, requestDto);
throw new Error();
} catch (err) {
// then
expect(err).toBeInstanceOf(UserNotFoundException);
}
});

it('존재하지 않는 포스트에 신고를 하면 PostNotFoundException이 발생한다.', async () => {
// given
const userId = 1;
const postId = 1;
const requestDto = new ReportCreateRequestDto();

userRepository.findOneBy = jest.fn(async () => new User());
postRepository.findOneBy = jest.fn();

// when
try {
await reportService.report(userId, postId, requestDto);
throw new Error();
} catch (err) {
// then
expect(err).toBeInstanceOf(PostNotFoundException);
}
});

it('신고한 포스트를 다시 신고하면 PostAlreadyReportedException이 발생한다.', async () => {
// given
const userId = 1;
const postId = 1;
const requestDto = new ReportCreateRequestDto();

userRepository.findOneBy = jest.fn(async () => new User());
postRepository.findOneBy = jest.fn(async () => new Post());
reportRepository.findOneBy = jest.fn();
reportRepository.insert = jest.fn();

// when
try {
await reportService.report(userId, postId, requestDto);
reportRepository.findOneBy = jest.fn(async () => new Report());
await reportService.report(userId, postId, requestDto);
throw new Error();
} catch (err) {
// then
expect(err).toBeInstanceOf(PostAlreadyReportedException);
expect(reportRepository.insert).toHaveBeenCalledTimes(1);
}
});
});
});
174 changes: 174 additions & 0 deletions server/src/domain/review/review.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PostNotFoundException } from 'src/exception/post-not-found.exception';
import { UserNotFoundException } from 'src/exception/user-not-found.exception';
import { Post } from '../post/post.entity';
import { PostRepository } from '../post/post.repository';
import { User } from '../user/user.entity';
import { UserRepository } from '../user/user.repository';
import {
ReviewGetAllRequestDto,
ReviewWriteRequestDto,
} from './dto/controller-request.dto';
import { Review } from './review.entity';
import { ReviewRepository } from './review.repository';
import { ReviewService } from './review.service';

describe('리뷰 서비스', () => {
let testingModule: TestingModule;
let reviewService: ReviewService;
let reviewRepository: ReviewRepository;
let postRepository: PostRepository;
let userRepository: UserRepository;

beforeAll(async () => {
testingModule = await Test.createTestingModule({
providers: [
ReviewService,
{
provide: ReviewRepository,
useValue: {},
},
{
provide: PostRepository,
useValue: {},
},
{
provide: UserRepository,
useValue: {},
},
],
}).compile();
});

beforeEach(() => {
reviewService = testingModule.get<ReviewService>(ReviewService);
reviewRepository = testingModule.get<ReviewRepository>(ReviewRepository);
postRepository = testingModule.get<PostRepository>(PostRepository);
userRepository = testingModule.get<UserRepository>(UserRepository);
});

describe('리뷰 작성', () => {
it('존재하지 않는 유저가 리뷰를 작성하면 UserNotFoundException이 발생한다.', async () => {
// given
const dto: ReviewWriteRequestDto = {
postId: 1,
content: '내용',
};
const userId = 1;

userRepository.findOneBy = jest.fn(() => null);
postRepository.findOneBy = jest.fn();

// when
try {
await reviewService.write(userId, dto);
throw new Error();
} catch (err) {
// then
expect(userRepository.findOneBy).toHaveBeenCalledTimes(1);
expect(err).toBeInstanceOf(UserNotFoundException);
}
});

it('존재하지 않는 포스트에 리뷰를 작성하면 PostNotFoundException이 발생한다.', async () => {
// given
const dto: ReviewWriteRequestDto = {
postId: 1,
content: '내용',
};
const userId = 1;

userRepository.findOneBy = jest.fn(async () => new User());
postRepository.findOneBy = jest.fn(() => null);

// when
try {
await reviewService.write(userId, dto);
throw new Error();
} catch (err) {
expect(postRepository.findOneBy).toHaveBeenCalledTimes(1);
expect(err).toBeInstanceOf(PostNotFoundException);
}
});

it('유저 정보와 포스트 정보로 리뷰 작성에 성공한다.', async () => {
// given
const dto: ReviewWriteRequestDto = {
postId: 1,
content: '내용',
};
const userId = 1;

userRepository.findOneBy = jest.fn(async () => new User());
postRepository.findOneBy = jest.fn(async () => new Post());
postRepository.increaseReviewCount = jest.fn(async () => new Post());
reviewRepository.insert = jest.fn();

// when
await reviewService.write(userId, dto);

// then
expect(reviewRepository.insert).toHaveBeenCalledTimes(1);
});
});

describe('리뷰 목록 조회', () => {
const REQUEST_CNT = 3;
it('리뷰를 한 번에 최대 REQUEST_CNT개까지 반환한다.', async () => {
// given
const reviews = Array.from({ length: REQUEST_CNT + 1 }, (v, i) => {
const review = new Review();
review.id = i + 1;
review.user = new User();
return review;
});
const postId = 1;
const requestDto = new ReviewGetAllRequestDto();

reviewRepository.find = jest.fn(async () => reviews);

// when
const dtos = await reviewService.getReviewsOfPost(postId, requestDto);

// then
expect(dtos.reviews.length).toEqual(REQUEST_CNT);
expect(dtos.isLast).toEqual(false);
});

it('리뷰가 요청한 개수보다 적거나 같으면 isLast가 true다.', async () => {
// given
const reviews = Array.from({ length: REQUEST_CNT }, (v, i) => {
const review = new Review();
review.id = i + 1;
review.user = new User();
return review;
});
const postId = 1;
const requestDto = new ReviewGetAllRequestDto();

reviewRepository.find = jest.fn(async () => reviews);

// when
const dtos = await reviewService.getReviewsOfPost(postId, requestDto);

// then
expect(dtos.lastId).toEqual(dtos.reviews[dtos.reviews.length - 1].id);
expect(dtos.isLast).toEqual(true);
});

it('리뷰가 없으면 isLast가 true다.', async () => {
// given
const postId = 1;
const requestDto = new ReviewGetAllRequestDto();

reviewRepository.find = jest.fn();

// when
const dtos = await reviewService.getReviewsOfPost(postId, requestDto);

// then
expect(dtos.reviews.length).toEqual(0);
expect(dtos.isLast).toEqual(true);
});
});
});

0 comments on commit 2da02fc

Please sign in to comment.