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

Develop #75

Merged
merged 20 commits into from
Dec 6, 2023
Merged
Changes from 1 commit
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
Prev Previous commit
Next Next commit
[REFACTOR] /get/me API 테스트.
dongseoki committed Nov 19, 2023
commit bdaa87fbf6b4dc2d4f3e02cc9caff9939bc4623d
7 changes: 3 additions & 4 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -269,15 +269,14 @@ gradle-app.setting

src/main/generated/**

src/main/resources/application-prd.yml
src/main/resources/application.properties
application-prd.yml
application-swagger.yml
application.properties


## logs ##
logs/

### security information
application.yml

### operation log
replay_pid.*.log
Copy link

Choose a reason for hiding this comment

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

위 코드 패치의 간단한 코드 리뷰를 도와드리겠습니다. 버그 위험 및 개선 제안은 환영합니다.

개선 제안:

  • gradle-app.setting 파일은 삭제되었습니다.
  • 경로가 src/main/generated/**인 모든 파일이 제외됩니다.
  • src/main/resources 디렉토리 내의 application-prd.ymlapplication.properties 파일이 경로 없이 나열됩니다.
  • application-swagger.yml 파일이 추가되었습니다.
  • logs/ 디렉토리 내의 모든 로그 파일도 제외됩니다.
  • application.yml 파일도 제거되었습니다.
  • replay_pid.*.log와 같은 형태의 파일도 제외됩니다.

이상입니다.

2 changes: 0 additions & 2 deletions server/build.gradle
Original file line number Diff line number Diff line change
@@ -69,8 +69,6 @@ dependencies {
// }
runtimeOnly 'com.mysql:mysql-connector-j'

runtimeOnly 'com.mysql:mysql-connector-j'

annotationProcessor 'org.projectlombok:lombok'

// spring boot 3.0 query dsl setting.
60 changes: 60 additions & 0 deletions server/scripts/deploy-swagger.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#!/bin/bash

# prd
REPOSITORY=/home/bside/311TEN003

# local
#REPOSITORY=/Users/dongseoklee/github/311TEN003

# common
PROJECT_LOCATION_FOLDER_NAME=server
PROJECT_NAME=bside_311

cd $REPOSITORY/$PROJECT_LOCATION_FOLDER_NAME/

echo "> Git reset --hard"
git reset --hard

echo "> Git Pull"

git pull

echo "Release Version Updated"
#grep "^Release" ./releasenote.txt | tail -1 > ./src/main/frontend/public/latestReleaseVer.txt


echo "> gradlew, deploy.sh 권한 변경 "
chmod 777 gradlew
chmod 774 scripts/deploy.sh

echo "> 프로젝트 Build 시작"
./gradlew build --exclude-task test

echo "> Build 파일 복사"

cp ./build/libs/*.jar $REPOSITORY/

echo "> 현재 구동중인 애플리케이션 pid 확인"

#CURRENT_PID=$(pgrep -f ${PROJECT_NAME}.*.jar)
CURRENT_PID=$(pgrep -f "active=swagger")

echo "$CURRENT_PID"

if [ -z "$CURRENT_PID" ]; then
echo "> 현재 구동중인 애플리케이션이 없으므로 종료하지 않습니다."
else
echo "> kill -2 $CURRENT_PID"
kill -9 "$CURRENT_PID"
sleep 10
fi

echo "> 새 어플리케이션 배포"

# JAR_NAME=$(ls $REPOSITORY/ |grep jar | tail -n 1)
JAR_NAME=$(ls $REPOSITORY/ |grep ${PROJECT_NAME}.*.jar | tail -n 1)

echo "> JAR Name: $JAR_NAME"

nohup java -jar $REPOSITORY/"$JAR_NAME" --spring.profiles.active=swagger &

Copy link

Choose a reason for hiding this comment

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

이 코드 패치는 다음과 같은 작업을 수행합니다:

  1. 지정된 저장소 경로에서 git reset --hard 명령어를 실행하여 이전 변경 내용을 모두 삭제합니다.
  2. git pull 명령어를 실행하여 최신 변경 내용을 가져옵니다.
  3. gradlew build 명령어를 사용하여 프로젝트를 빌드합니다.
  4. 빌드된 파일을 지정된 저장소로 복사합니다.
  5. 현재 구동 중인 애플리케이션의 PID(Process ID)를 확인합니다.
  6. 현재 구동 중인 애플리케이션이 없으면 아무 작업도 수행하지 않고, 있으면 해당 애플리케이션을 종료합니다.
  7. 새로운 애플리케이션을 배포하고 실행합니다.

이 코드에서 주의해야 할 몇 가지 사항이 있습니다:

  1. 현재 코드에서는 JAR 파일의 이름에 "bside_311" 문자열을 포함하는 파일을 배포하고 실행하고 있습니다. 이 부분을 프로젝트의 요구 사항에 맞게 수정해야 합니다.
  2. kill -9 명령어를 사용하여 애플리케이션을 강제로 종료하고 있습니다. 이는 예상치 못한 문제가 발생할 수 있으므로 조심해야 합니다. 가능한 경우, 더 안전한 방법을 사용하는 것이 좋습니다.
  3. 현재 코드에서는 nohup 명령어를 사용하여 백그라운드에서 애플리케이션을 실행하고 있습니다. 이 경우 애플리케이션의 로그 출력이나 오류 메시지를 확인하기 어렵습니다. 필요에 따라 로그 기능을 추가하거나 실행 방식을 변경할 수 있습니다.

개선 제안:

  1. 실행가능한 스크립트 파일(.sh)을 작성하여 각 단계를 별도의 함수로 모듈화하고, 잠재적인 오류 상황을 처리하도록 구성할 수 있습니다.
  2. 애플리케이션의 실행과 관련된 환경 변수를 구성 파일로 분리하여 유연성을 높일 수 있습니다.
  3. 롤백 기능을 추가하여 배포 과정 중 예상치 못한 문제가 발생했을 때 이전 버전으로 되돌릴 수 있는 기능을 제공할 수 있습니다.
  4. 작업을 자동화하여 CI/CD 파이프라인에 통합할 수 있습니다.

이러한 개선 사항은 코드의 가독성, 유지 보수성 및 안정성을 개선하는 데 도움이 될 수 있습니다.

3 changes: 2 additions & 1 deletion server/scripts/deploy.sh
Original file line number Diff line number Diff line change
@@ -36,7 +36,8 @@ cp ./build/libs/*.jar $REPOSITORY/

echo "> 현재 구동중인 애플리케이션 pid 확인"

CURRENT_PID=$(pgrep -f ${PROJECT_NAME}.*.jar)
#CURRENT_PID=$(pgrep -f ${PROJECT_NAME}.*.jar)
CURRENT_PID=$(pgrep -f "active=prd")

echo "$CURRENT_PID"

Copy link

Choose a reason for hiding this comment

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

제가 주어진 코드의 간단한 코드 리뷰를 도와드리겠습니다. 버그 위험이나 개선 제안에 대해서도 적절한 응답을 드리겠습니다.

@@ -36,7 +36,8 @@ cp ./build/libs/*.jar $REPOSITORY/
echo "> 현재 구동중인 애플리케이션 pid 확인"

-CURRENT_PID=$(pgrep -f ${PROJECT_NAME}..jar)
+#CURRENT_PID=$(pgrep -f ${PROJECT_NAME}.
.jar)
+CURRENT_PID=$(pgrep -f "active=prd")

echo "$CURRENT_PID"

  1. 이 코드 패치는 빌드된 JAR 파일을 지정된 리포지토리로 복사하는 명령어입니다. 이 부분은 문제가 없어 보입니다.

  2. 주석 처리된 줄을 봤을 때, pgrep 명령을 사용하여 프로젝트 이름과 .jar 파일 확장자를 기준으로 현재 실행 중인 애플리케이션의 프로세스 ID(PID)를 찾고 있습니다. 그러나 현재 코드에서는 이 부분이 주석 처리되어 있으므로 실제로는 PID를 얻을 수 없을 것입니다.

  3. 대신에 주석 처리된 아래의 줄은 pgrep 명령을 사용하여 "active=prd"라는 문자열을 포함하는 프로세스 ID를 찾습니다. 개발 환경에 따라서는 이 방식이 정확한 PID를 얻을 수 있습니다.

  4. echo "$CURRENT_PID"는 현재 실행 중인 애플리케이션의 PID를 출력하는 부분입니다.

버그 위험:

  • 현재 코드에서는 주석 처리된 부분을 사용하고 있으므로 실제로는 현재 실행 중인 애플리케이션의 PID를 얻을 수 없습니다.

개선 제안:

  • PID를 찾는 방식과 관련된 문제가 있는지 확인해야 합니다. 프로젝트의 특정 버전을 기준으로 PID를 찾아야 한다면, 해당 조건을 제대로 지정하여 PID를 찾을 수 있는지 확인하세요.
  • PID를 찾는 대체 방법을 고려할 수 있습니다. 예를 들어, 일련의 프로세스 관리 도구 (예: ps, pgrep 등)를 사용하여 PID를 가져오는 대신에 애플리케이션 자체가 PID 파일을 작성하는 등의 방법을 사용할 수도 있습니다.

28 changes: 13 additions & 15 deletions server/src/main/java/com/bside/bside_311/Bside311Application.java
Original file line number Diff line number Diff line change
@@ -5,27 +5,25 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import java.util.Optional;

@EnableJpaAuditing
@SpringBootApplication
public class Bside311Application {

public static void main(String[] args) {
SpringApplication.run(Bside311Application.class, args);
}
public static void main(String[] args) {
SpringApplication.run(Bside311Application.class, args);
}

@Bean
public AuditorAware<Long> auditorProvider() {
return () -> {
Long userNoFromAuthentication = AuthUtil.getUserNoFromAuthentication();
if (userNoFromAuthentication == null) {
return Optional.empty();
}
return Optional.of(userNoFromAuthentication);
};
}
@Bean
public AuditorAware<Long> auditorProvider() {
return () -> {
Long userNoFromAuthentication = AuthUtil.getUserNoFromAuthentication();
if (userNoFromAuthentication == null) {
return Optional.empty();
}
return Optional.of(userNoFromAuthentication);
};
}

}
Copy link

Choose a reason for hiding this comment

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

이 코드 패치에서 주목해야 할 부분은 다음과 같습니다:

  1. @EnableJpaAuditing 어노테이션의 삭제: 이 어노테이션은 JPA 감사(Auditing)를 사용하도록 설정하는 역할을 합니다. 만약 해당 기능을 사용하려면, 어노테이션이 필요합니다. 코드에서는 이 어노테이션이 삭제되었으므로 JPA 감사 기능이 비활성화된 것으로 보입니다. 이것이 의도한 동작인지 확인해야 합니다.

  2. main 메소드의 들여쓰기 변경: main 메소드의 내용이 들여쓰기에 의해 변경되었습니다. 이는 가독성 관점에서 큰 문제가 되지 않지만, 코드 스타일 일관성을 유지하기 위해서 들여쓰기 스타일을 통일하는 것이 좋습니다.

  3. auditorProvider() 메소드: auditorProvider() 메소드는 @Bean 어노테이션이 지정된 메소드로, AuditorAware 인터페이스의 구현체를 반환합니다. 이 메소드는 현재 인증된 사용자의 ID 값을 Optional로 반환합니다. 이 부분은 보안 측면에서 주의해야 합니다. AuthUtil.getUserNoFromAuthentication()에서 반환된 값이 신뢰할 수 있는지 확인하고, 인증되지 않은 사용자에게는 Optional.empty()를 반환하는 것이 좋습니다.

코드 패치의 개선점:

  1. @EnableJpaAuditing 어노테이션 삭제에 대한 이유를 명확하게 설명하거나, JPA 감사 기능을 포함하도록 복구해야 합니다.
  2. 들여쓰기 스타일을 일관성 있게 유지합니다.
  3. auditorProvider() 메소드에서 보안 검사와 관련된 부분을 검토하고 개선합니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.bside.bside_311.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@Profile("!test")
@Configuration
@EnableJpaAuditing
public class JpaConfiguration {
}
Copy link

Choose a reason for hiding this comment

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

이 코드 패치는 com.bside.bside_311.config 패키지 내에서 JpaConfiguration 클래스를 선언하고 구성합니다. 이 클래스는 JPA 감사(auditing) 기능을 활성화하는 데 사용됩니다.

이 코드에는 버그나 위험이 없어 보입니다. 하지만 몇 가지 개선 제안사항이 있습니다:

  1. 주석(comment): 코드의 의도와 동작에 대해 설명하는 주석을 추가하는 것이 도움이 될 수 있습니다.
  2. 패키지 이름: com.bside.bside_311.config 패키지가 적절한지 확인해야 합니다. 프로젝트의 컨벤션과 구조에 맞도록 패키지 이름을 조정할 수 있습니다.
  3. @EnableJpaAuditing 사용 영역 조정: @EnableJpaAuditing 어노테이션을 필요한 곳에만 적용할 수 있도록, @Configuration 어노테이션 바로 위로 이동시킬 수 있습니다.

이러한 개선 사항은 코드의 가독성과 유지 보수성을 향상시킬 수 있습니다.

Original file line number Diff line number Diff line change
@@ -12,7 +12,6 @@
import com.bside.bside_311.dto.UserUpdateRequestDto;
import com.bside.bside_311.entity.Role;
import com.bside.bside_311.entity.User;
import com.bside.bside_311.repository.UserMybatisRepository;
import com.bside.bside_311.service.UserService;
import com.bside.bside_311.util.AuthUtil;
import io.swagger.v3.oas.annotations.Operation;
@@ -39,7 +38,6 @@
@Tag(name = "유저", description = "유저 API")
public class UserController {
private final UserService userService;
private final UserMybatisRepository userMybatisRepository;

@Operation(summary = "[o]일반 유저 등록", description = "일반 유저 등록 API")
@PostMapping("/signup")
Original file line number Diff line number Diff line change
@@ -2,40 +2,75 @@

import com.bside.bside_311.Bside311Application;
import com.bside.bside_311.config.security.WebSecurityConfig;
import com.bside.bside_311.entity.Role;
import com.bside.bside_311.entity.User;
import com.bside.bside_311.util.JwtUtil;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.test.context.ContextConfiguration;

import static com.bside.bside_311.util.JwtUtil.NORMAL_TOKEN;
import static com.bside.bside_311.util.JwtUtil.normalValidity;

@ContextConfiguration(classes = {
Bside311Application.class,
WebSecurityConfig.class,
})
public abstract class ControllerTest {
protected static final String USER_ID = "UserId";
protected static final String ADMIN_ID = "AdminId";
// @SpyBean
// @SpyBean
// protected AccessTokenGenerator accessTokenGenerator;
// @MockBean
// protected AuthUserDao authUserDao;
public User normalUser;
@SpyBean
protected JwtUtil jwtUtil;
protected String userAccessToken;
protected String adminAccessToken;
// @SpyBean


// @SpyBean
// private AccessTokenService accessTokenService;
//
// @BeforeEach
// void setUpAccessTokenAndUserDetailsDaoForAuthentication() {
// userAccessToken = accessTokenGenerator.generate(USER_ID);
// adminAccessToken = accessTokenGenerator.generate(ADMIN_ID);
//
// AuthUser user = AuthUser.authenticated(
// USER_ID, "ROLE_USER", userAccessToken);
//
// given(authUserDao.findByAccessToken(userAccessToken))
// .willReturn(Optional.of(user));
//
// AuthUser admin = AuthUser.authenticated(
// ADMIN_ID, "ROLE_ADMIN", adminAccessToken);
//
// given(authUserDao.findByAccessToken(adminAccessToken))
// .willReturn(Optional.of(admin));
// }
@BeforeEach
void setUpAccessTokenAndUserDetailsDaoForAuthentication() {
normalUser = User.builder()
.id(1L)
.userId("normalUser")
.password("normalUserPassword")
.email("normalUser@example.com")
.nickname("normalUserNickname")
.role(Role.ROLE_USER)
.introduction("normalUserIntroduction")
.build();
Authentication normalUserAuthentication
= new UsernamePasswordAuthenticationToken(normalUser.getId(),
null,
AuthorityUtils.createAuthorityList(normalUser.getRole().toString()));

userAccessToken = jwtUtil.createLocalToken(normalUser, NORMAL_TOKEN, normalValidity,
normalUserAuthentication);


User adminUser = User.builder()
.id(2L)
.userId("adminUser")
.password("adminUserPassword")
.email("adminUser@example.com")
.nickname("adminUserNickname")
.role(Role.ROLE_USER)
.introduction("adminUserIntroduction")
.build();
Authentication adminUserAuthentication
= new UsernamePasswordAuthenticationToken(adminUser.getId(),
null,
AuthorityUtils.createAuthorityList(adminUser.getRole().toString()));

adminAccessToken =
jwtUtil.createLocalToken(adminUser, NORMAL_TOKEN, normalValidity, adminUserAuthentication);
}
}
Copy link

Choose a reason for hiding this comment

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

이 코드는 ControllerTest라는 추상 클래스에 대한 코드 패치입니다. 아래는 이 코드의 간단한 코드 리뷰와 버그 위험 및 개선 제안입니다:

  1. 변수명 변경: adminAccessToken, userAccessToken, normalUserAuthentication, adminUserAuthentication과 같은 변수명은 좀 더 명확하게 변경하는 것이 좋습니다.
  2. 주석 처리된 코드 정리: 주석 처리된 코드들이 많이 남아있는데, 필요 없는 코드는 정리하는 것이 좋습니다.
  3. 테스트 케이스 추가: 현재로서는 테스트 메소드가 없어서 어떤 기능을 테스트하는지 파악하기 어렵습니다. 테스트 케이스를 추가하여 코드의 기능을 명확히 할 수 있습니다.
  4. 상수 활용: com.bside.bside_311.util.JwtUtil.NORMAL_TOKENcom.bside.bside_311.util.JwtUtil.normalValidity은 둘 다 사용되지 않으므로 제거하는 것이 좋습니다.

위의 사항들을 고려하여 코드를 개선할 수 있습니다.

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.bside.bside_311.controller;

import com.bside.bside_311.dto.MyInfoResponseDto;
import com.bside.bside_311.service.UserService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -9,14 +10,16 @@
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;

import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(UserController.class)
class UserControllerTest extends ControllerTest{
class UserControllerTest extends ControllerTest {

@Autowired
private MockMvc mockMvc;
@@ -33,7 +36,7 @@ void signupSuccess() throws Exception {
String name = "Newbie";

String json = String.format(
"""
"""
{
"email": "%s",
"password": "%s",
@@ -45,8 +48,8 @@ void signupSuccess() throws Exception {
);

MvcResult mvcResult = mockMvc.perform(post("/user/signup")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isCreated())
.andReturn();
String responseBody = mvcResult.getResponse().getContentAsString();
@@ -63,21 +66,34 @@ void signupFail_emptynickname() throws Exception {

String json = String.format(
"""
{
"email": "%s",
"password": "%s",
"id": "%s"
}
""",
{
"email": "%s",
"password": "%s",
"id": "%s"
}
""",
email, password, id, name
);

MvcResult mvcResult = mockMvc.perform(post("/user/signup")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().is4xxClientError())
.andReturn();
String responseBody = mvcResult.getResponse().getContentAsString();
System.out.println(responseBody);
}

@Test
@DisplayName("GET /me success")
void me() throws Exception {
given(userService.getMyInfo(normalUser.getId()))
.willReturn(MyInfoResponseDto.of(normalUser, null, 0L,
0L));

mockMvc.perform(get("/user/me")
.header("Authorization", "Bearer " + userAccessToken))
.andExpect(status().isOk())
.andExpect(content().string(containsString("userNo")));
}
}
Copy link

Choose a reason for hiding this comment

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

이 코드 패치에는 몇 가지 수정 사항이 필요합니다:

  1. com.fasterxml.jackson.databind.ObjectMapper를 추가하는 부분은 필요하지 않습니다. 이미 사용되고 있기 때문입니다.

  2. mockMvc.perform 함수의 각 줄을 들여쓰기해야 합니다.

  3. user_follow_success 테스트 메서드에서 MvcResult 객체가 반환되어 응답 본문을 얻더라도 결과를 확인하는 구문이 없습니다. 적절한 단언문을 추가하여 응답을 확인하십시오.

  4. getUsersOfFollowingMePage_success 테스트 메서드에서 역시 결과를 확인하기 위한 단언문이 필요합니다.

  5. 파일 끝에 개행 문자를 추가해주는 것이 좋습니다.

30 changes: 16 additions & 14 deletions server/src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
spring:
datasource:
url: jdbc:h2:tcp://localhost/~/bside_311
username: sa
password:
driver-class-name: org.h2.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/bside_test?serverTimezone=UTC&characterEncoding=UTF-8
username: root
password: root
minimum-idle: 10
maximum-pool-size: 10
idle-timeout: 30000
connection-timeout: 10000
validation-timeout: 10000
max-lifetime: 30000
connection-test-query: SELECT 1

jpa:
database: mysql
database-platform: org.hibernate.dialect.MySQLDialect
hibernate:
ddl-auto: create
ddl-auto: 'create-drop'
properties:
hibernate:
# show_sql: true
format_sql: true
use_sql_comments: true
default_batch_fetch_size: 1000

logging.level:
org.hibernate.SQL: debug
# org.hibernate.orm.jdbc.bind: trace

p6spy:
detail: false

decorator:
datasource:
p6spy:
enable-logging: true
# org.hibernate.orm.jdbc.bind: trace
27 changes: 27 additions & 0 deletions server/src/test/resources/application-testbackup.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
spring:
datasource:
url: jdbc:h2:tcp://localhost/~/bside_311
username: sa
password:
driver-class-name: org.h2.Driver

jpa:
hibernate:
ddl-auto: create
properties:
hibernate:
# show_sql: true
format_sql: true
use_sql_comments: true

logging.level:
org.hibernate.SQL: debug
# org.hibernate.orm.jdbc.bind: trace

p6spy:
detail: false

decorator:
datasource:
p6spy:
enable-logging: true
Copy link

Choose a reason for hiding this comment

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

이 코드 패치는 스프링 프레임워크와 H2 데이터베이스를 사용하는 애플리케이션 환경 설정을 포함하고 있습니다. 몇 가지 개선 사항과 버그 위험이 있습니다:

  1. 비밀번호 없음: 현재 코드에서는 H2 데이터베이스에 연결할 때 비밀번호가 비어 있습니다. 보안상의 이유로 기본 값으로 두지 않는 것이 좋습니다. 비밀번호를 설정하여 데이터베이스 연결을 보호하는 것이 좋습니다.

  2. ddl-auto 속성: hibernate.ddl-auto 속성을 "create"로 설정하면 매번 애플리케이션 시작 시마다 테이블이 다시 생성됩니다. 개발 환경에서는 문제가 되지 않지만, 운영 환경에서는 유의해야 합니다. 안전한 선택은 "none"이며, 수동으로 마이그레이션 스크립트를 작성하여 데이터베이스 스키마를 관리하는 것입니다.

  3. show_sql 속성: 주석 처리된 show_sql 속성을 활성화하여 Hibernate가 실행하는 SQL 쿼리를 볼 수 있습니다. 개발 및 디버깅 중에 유용합니다.

  4. logging.level: logging.level 설정이 부분적으로 주석 처리되어 있습니다. 필요한 로깅 수준을 설정하여 Hibernate가 SQL 쿼리에 대한 디버그 로그를 기록하도록 할 수 있습니다.

  5. p6spy: P6Spy 라이브러리를 사용하는 것으로 보입니다. 현재 detail 속성이 비활성화되어 있습니다. 필요한 경우 자세한 SQL 로깅을 위해 해당 속성을 활성화할 수 있습니다.

위와 같은 개선 사항과 함께, 코드의 끝에 새 줄을 추가하는 것이 좋습니다.

35 changes: 35 additions & 0 deletions server/src/test/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
spring:
profiles:
active: test

mybatis:
type-aliases-package: com.bside.bside_311.entity;com.bside.bside_311.dto;java.lang;
mapper-locations: mybatis/mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true

p6spy:
detail: false

decorator:
datasource:
p6spy:
enable-logging: true

springdoc:
version: '0.0.1'
api-docs:
groups:
enabled: true
default-consumes-media-type: application/json
default-produces-media-type: application/json
swagger-ui:
path: /
disable-swagger-default-url: true
display-request-duration: true
operations-sorter: method
tags-sorter: alpha
displayRequestDuration: true
# doc-expansion: none
groups-order: DESC
persistAuthorization: true
Copy link

Choose a reason for hiding this comment

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

이 코드 패치는 YAML 형식으로 된 Spring 애플리케이션 설정 파일인 것 같습니다. 여기서 버그 리스크는 명확하지 않습니다. 다만 개선 제안은 있습니다:

  1. mybatis 섹션: type-aliases-packagemapper-locations 값을 확인하십시오. 필요한 패키지 및 XML 매퍼의 경로가 올바르게 지정되어 있는지 확인하여야 합니다.

  2. p6spy 섹션: enable-logging 값을 true로 설정하였지만, 실제로 수집된 로그를 어떻게 처리할지 확인해야 합니다. 즉, 로깅 설정에 대한 추가 작업이 필요할 수 있습니다.

  3. springdoc 섹션: 문서 생성과 관련된 설정입니다. 이 부분은 주로 API 문서화에 사용되는 SpringDoc OpenAPI 라이브러리와 관련된 것으로 보입니다. 주석 처리된 부분들을 해제하고 필요에 따라 해당 값을 조정하는 것이 좋습니다.

  4. 파일 끝에 \n이 없으므로 한 줄이 누락되었습니다. Yaml 파일은 마지막에 개행 문자가 포함되어야 합니다.

참고로, 이 코드 패치는 단독으로 실행하기보다는 프로젝트의 전체 구조와 의존성 설정 등을 고려해야 정확한 리뷰를 제공할 수 있습니다.