Skip to content

Commit

Permalink
[빙봉] 체스 - 스프링 실습 4단계 제출합니다. (#203)
Browse files Browse the repository at this point in the history
* [디디] 체스 스프링 실습 1단계 제출합니다. (#12)

* initial commit

* fix : build.gradle mysql 의존성 추가

* refactor : 왕이 죽었을 때 게임이 종료 안되는 버그 수정

* refactor : 버튼으로 방에 입장할 수 있도록 함

* refactor : 방을 삭제하고 나서 새로고침해야 적용되던 문제 수정

* feat : 방에 입장하자마자 게임을 바로 불러오도록 하고 못 불러왔을 시 게임을 초기화하는 기능 추가, refactor : 불러왔을 때 현재 Turn이 나오지 않는 문제 수정

* refactor, style : tab 공백을 space로 변경, 익명 객체 람다식으로 수정

* feat : Spring room Controller 구현
- 방 제목 empty 에 대한 validation 추가
- default 요청시 바로 방 목록을 불러오도록 수정

* feat, refactor : Dto 생성 방식 수정, 게임 컨트롤러 구현

- 게임 초기화 기능 구현

Co-authored-by: aegis <[email protected]>

* [디디] 체스 - 스프링 실습 2단계 제출합니다. (#73)

* refactor : 사용하지 않는 클래스 삭제

* refactor : 디폴트 생성자 접근제어자 수정

* refactor : 디폴트 생성자 접근제어자 수정

* refactor : 디폴트 생성자 접근제어자 수정

* refactor : Object 객체 타입 파라미터 반영하도록 수정

* refactor : 필드간 공백 추가

* refactor : 사용하지 않는 메서드 삭제

* refactor : 필드 접근제어자 추가

* style : 공백 추가

* feat : gameController init, movablePosition 구현

- todo : move시 에러

* feat : move 예외 처리 작업중

* refactor : spring MVC 구조에 맞게 refactor

- GameController 예외 알맞게 처리
- DAO 클래스 Repository로 설정
- Service의 DAO를 bean으로 주입

* docs : README.md 추가

* test : domain test 메서드 추가

* refactor : 사용하지 않은 메서드 삭제 및 공백 수정

* refactor, fix : Spark Application과 Spring Application 이 모두 동작하도록 수정, 점수가 제대로 나오지 않는 버그 수정

* style : 공백 삭제

* refactor : move 메서드가 Post방식의 Json으로 요청을 받도록 수정

- front의 request uri 수정
- MoveManagerDTO 클래스로 request 매핑

* refactor : 불필요한 attribute 삭제

* refactor : move 메서드 리턴 타입 수정, 클래스명 수정

* refactor : 서비스 메서드 불필요한 동작 수정

Co-authored-by: aegis <[email protected]>

* refactor : RoomDAO 를 spring data jdbc repository로 변경

* refactor : Spring data jdbc 에 맞도록 테이블, 엔티티, dto 설계

* refactor : 변경 사항에 맞게 Controller와 서비스 수정

* refactor : 공백 제거

* refactor : GameRequestDto 에 기본 생성자 추가

* refactor : HTTP 메서드에 맞게 Mapping 어노테이션 수정,@PathVariable 적용

* refactor : HTTP 메서드에 맞게 Mapping 어노테이션 수정,@PathVariable 적용

* refactor : getPath 이름을 path로 수정, del : GameRepository, PieceRepository

* refactor : JDBCConnectorTest 삭제 및 build.gradle 수정

* refactor : Status라는 네이밍을 Score로 변경

* refactor : banner 변경 및 addRoom에 리턴을 RoomEntity로 하도록 수정

* feat : SpringDefaultControllerTest 추가

* feat : SpringRoomControllerTest 추가

* feat : SpringGameControllerTest 추가

Co-authored-by: DD <[email protected]>
Co-authored-by: dd <[email protected]>
  • Loading branch information
3 people authored May 4, 2020
1 parent baa4ef1 commit ddf3b67
Show file tree
Hide file tree
Showing 10 changed files with 371 additions and 43 deletions.
3 changes: 0 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,10 @@ repositories {

dependencies {
compile('mysql:mysql-connector-java:8.0.16')
implementation 'com.sparkjava:spark-core:2.9.0'
implementation 'com.sparkjava:spark-template-handlebars:2.7.1'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
implementation 'net.rakugakibox.spring.boot:logback-access-spring-boot-starter:2.7.1'
implementation 'pl.allegro.tech.boot:handlebars-spring-boot-starter:0.3.1'
implementation 'com.google.code.gson:gson:2.8.6'
testImplementation 'io.rest-assured:rest-assured:3.3.0'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import wooteco.chess.dto.GameRequestDto;
import wooteco.chess.dto.GameResponseDto;
import wooteco.chess.dto.GameStatusDto;
import wooteco.chess.dto.GameScoreDto;
import wooteco.chess.dto.MoveRequestDto;
import wooteco.chess.service.SpringGameService;

Expand All @@ -30,14 +30,13 @@ public GameResponseDto init(@RequestBody GameRequestDto gameRequestDto) {
return gameService.initialize(gameRequestDto);
}

@PostMapping("/status")
public GameStatusDto showStatus(@RequestBody GameRequestDto gameRequestDto) {
return new GameStatusDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto));
@PostMapping("/score")
public GameScoreDto showStatus(@RequestBody GameRequestDto gameRequestDto) {
return new GameScoreDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto));
}

@PostMapping("/path")
public List<String> getMovablePositions(@RequestBody MoveRequestDto moveRequestDto) {
System.out.println(moveRequestDto);
return gameService.getMovablePositions(moveRequestDto);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package wooteco.chess.dto;

public class GameStatusDto {
public class GameScoreDto {
private final double whiteScore;
private final double blackScore;

public GameStatusDto(final double whiteScore, final double blackScore) {
public GameScoreDto(final double whiteScore, final double blackScore) {
this.whiteScore = whiteScore;
this.blackScore = blackScore;
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/wooteco/chess/service/SpringRoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ public class SpringRoomService {
@Autowired
private RoomRepository roomRepository;

public void addRoom(RoomRequestDto roomRequestDto) {
public RoomEntity addRoom(RoomRequestDto roomRequestDto) {
Set<PieceEntity> pieceEntities = convertPiecesToPieceEntity(Pieces.initPieces());
GameEntity gameEntity = new GameEntity(Color.WHITE, pieceEntities);
roomRepository.save(new RoomEntity(roomRequestDto.getName(), roomRequestDto.getPassword(), gameEntity));
return roomRepository.save(new RoomEntity(roomRequestDto.getName(), roomRequestDto.getPassword(), gameEntity));
}

public void removeRoom(Long id) {
Expand Down
17 changes: 8 additions & 9 deletions src/main/resources/banner.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
('-. .-. ('-. _ .-') _ _ .-') _
( OO ) / _( OO) ( ( OO) )( ( OO) )
,--. ,--.(,------.,--. ,--. .-'),-----. \ .'_ \ .'_
| | | | | .---'| |.-') | |.-') ( OO' .-. ' .-') ,`'--..._),`'--..._)
| .| | | | | | OO ) | | OO )/ | | | | _( OO) | | \ '| | \ '
| |(| '--. | |`-' | | |`-' |\_) | |\| | (,------. | | ' || | ' |
| .-. | | .--'(| '---.'(| '---.' \ | | | | '------' | | / :| | / :
| | | | | `---.| | | | `' '-' ' | '--' /| '--' /
`--' `--' `------'`------' `------' `-----' `-------' `-------'

██████╗ ██╗███╗ ██╗ ██████╗ ██████╗ ██████╗ ███╗ ██╗ ██████╗
██╔══██╗██║████╗ ██║██╔════╝ ██╔══██╗██╔═══██╗████╗ ██║██╔════╝
██████╔╝██║██╔██╗ ██║██║ ███╗██████╔╝██║ ██║██╔██╗ ██║██║ ███╗
██╔══██╗██║██║╚██╗██║██║ ██║██╔══██╗██║ ██║██║╚██╗██║██║ ██║
██████╔╝██║██║ ╚████║╚██████╔╝██████╔╝╚██████╔╝██║ ╚████║╚██████╔╝
╚═════╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝

10 changes: 5 additions & 5 deletions src/main/resources/templates/game.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

<div>현재 턴은 <span id="turn"></span>입니다.</div>

<button class="btn btn-primary" id="statusButton">점수보기</button>
<button class="btn btn-primary" id="scoreButton">점수보기</button>

<button class="btn btn-primary" id="initButton">체스판 초기화</button>

Expand Down Expand Up @@ -227,15 +227,15 @@
init();
});
document.getElementById("statusButton").addEventListener('click', function () {
document.getElementById("scoreButton").addEventListener('click', function () {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let statusResponse = JSON.parse(xhr.responseText);
showStatus(statusResponse.whiteScore, statusResponse.blackScore);
let scoreResponse = JSON.parse(xhr.responseText);
showStatus(scoreResponse.whiteScore, scoreResponse.blackScore);
}
};
xhr.open('POST', '/game/status', true);
xhr.open('POST', '/game/score', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package wooteco.chess.controller;

import static io.restassured.RestAssured.*;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.CoreMatchers.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringDefaultControllerTest {

@LocalServerPort
int port;

@BeforeEach
void setUp() {
RestAssured.port = port;
}

@Autowired
private SpringDefaultController springDefaultController;

@DisplayName("SpringDefaultController가 빈으로 등록됐는지 확인")
@Test
void testSpringDefaultControllerIsRegisteredBean() {
assertThat(springDefaultController).isNotNull();
}

@DisplayName("SpringDefaultController에 SpringRoomService가 주입됐는지 확인")
@Test
void testDIFromSpringDefaultControllerToSpringRoomService() {
assertThat(springDefaultController.index()).isNotNull();
}

@Test
void testIndexPage() {
indexRequest();
}

private void indexRequest() {
given().
log().all().
when().
get("/").
then().
log().all().
body(containsString("전체 방 목록")).
and().
statusCode(200).
and().
contentType(ContentType.HTML);
}
}

189 changes: 189 additions & 0 deletions src/test/java/wooteco/chess/controller/SpringGameControllerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package wooteco.chess.controller;

import static io.restassured.RestAssured.*;
import static org.assertj.core.api.Assertions.*;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import wooteco.chess.dto.GameRequestDto;
import wooteco.chess.dto.GameResponseDto;
import wooteco.chess.dto.GameScoreDto;
import wooteco.chess.dto.MoveRequestDto;
import wooteco.chess.dto.PieceResponseDto;
import wooteco.chess.dto.RoomRequestDto;
import wooteco.chess.repository.entity.RoomEntity;
import wooteco.chess.service.SpringRoomService;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringGameControllerTest {
@LocalServerPort
private int port;

@BeforeEach
public void setUp() {
RestAssured.port = port;
}

@Autowired
private SpringGameController springGameController;

@Autowired
private SpringRoomService springRoomService;

private final RoomRequestDto roomRequestDto = new RoomRequestDto("hello", "world");

@DisplayName("SpringRoomController가 빈으로 등록됐는지 확인")
@Test
void testSpringRoomControllerIsRegisteredBean() {
assertThat(springGameController).isNotNull();
}

@DisplayName("init 했을 때 Response에 값이 비지 않았는지")
@Test
void testInit() {
RoomEntity roomEntity = springRoomService.addRoom(roomRequestDto);
GameRequestDto gameRequestDto = new GameRequestDto(roomEntity.getId());

GameResponseDto gameResponseDto =
given().
contentType(ContentType.JSON).
body(gameRequestDto).
log().all().
when().
post("/game/init").
then().
log().all().
and().
statusCode(HttpStatus.SC_OK).
and().
contentType(ContentType.JSON).
and().
extract().
as(GameResponseDto.class);

assertThat(gameResponseDto.getPieces()).isNotEmpty();
}

@DisplayName("게임을 생성하고 난 뒤, 흑과 백의 score가 같은지 체크")
@Test
void testShowStatus() {
RoomEntity roomEntity = springRoomService.addRoom(roomRequestDto);
GameRequestDto gameRequestDto = new GameRequestDto(roomEntity.getId());

GameScoreDto gameScoreDto =
given().
contentType(ContentType.JSON).
body(gameRequestDto).
log().all().
when().
post("/game/score").
then().
log().all().
and().
statusCode(HttpStatus.SC_OK).
and().
contentType(ContentType.JSON).
and().
extract().
as(GameScoreDto.class);

assertThat(gameScoreDto.getBlackScore()).isEqualTo(gameScoreDto.getWhiteScore());
}

@DisplayName("a2(폰)의 갈 수 있는 위치가 null이 아닌지 확인")
@Test
void testGetMovablePositions() {
RoomEntity roomEntity = springRoomService.addRoom(roomRequestDto);
MoveRequestDto moveRequestDto = new MoveRequestDto(roomEntity.getId(), "a2", null);

List<String> movablePositions =
given().
contentType(ContentType.JSON).
body(moveRequestDto).
log().all().
when().
post("/game/path").
then().
log().all().
and().
statusCode(HttpStatus.SC_OK).
and().
contentType(ContentType.JSON).
and().
extract().
as(ArrayList.class);

assertThat(movablePositions).isNotNull();
}

@DisplayName("a2(폰)가 a4로 이동하고 그 결과가 맞는지 확인")
@Test
void testMove() {
RoomEntity roomEntity = springRoomService.addRoom(roomRequestDto);
MoveRequestDto moveRequestDto = new MoveRequestDto(roomEntity.getId(), "a2", "a4");

GameResponseDto gameResponseDto =
given().
contentType(ContentType.JSON).
body(moveRequestDto).
log().all().
when().
post("/game/move").
then().
log().all().
and().
statusCode(HttpStatus.SC_OK).
and().
contentType(ContentType.JSON).
and().
extract().
as(GameResponseDto.class);

PieceResponseDto piece = gameResponseDto.getPieces().stream()
.filter(pieceResponseDto -> "a4".equals(pieceResponseDto.getPosition()))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("제대로 이동하지 못 했습니다."));

assertThat(piece).isNotNull();
}

@DisplayName("load했을 때 값이 Null이 아닌지")
@Test
void testLoad() {
RoomEntity roomEntity = springRoomService.addRoom(roomRequestDto);
GameRequestDto gameRequestDto = new GameRequestDto(roomEntity.getId());

GameResponseDto gameResponseDto =
given().
contentType(ContentType.JSON).
body(gameRequestDto).
log().all().
when().
post("/game/load").
then().
log().all().
and().
statusCode(HttpStatus.SC_OK).
and().
contentType(ContentType.JSON).
and().
extract().
as(GameResponseDto.class);

assertThat(gameResponseDto.getPieces()).isNotNull();
}



}
Loading

0 comments on commit ddf3b67

Please sign in to comment.