diff --git a/scripts/start.sh b/scripts/start.sh index b3c6adcb..66a353d0 100644 --- a/scripts/start.sh +++ b/scripts/start.sh @@ -18,7 +18,7 @@ cp $PROJECT_ROOT/build/libs/*.jar $JAR_FILE # jar 파일 실행 chmod 755 $JAR_FILE echo "$TIME_NOW > $JAR_FILE 파일 실행" >> $DEPLOY_LOG -nohup java -jar $JAR_FILE > $APP_LOG 2> $ERROR_LOG & +nohup java -jar -Dspring.profiles.active=prod -Xmx128 -Xmx128m $JAR_FILE > $APP_LOG 2> $ERROR_LOG & CURRENT_PID=$(pgrep -f $JAR_FILE) -echo "$TIME_NOW > 실행된 프로세스 아이디 $CURRENT_PID 입니다." >> $DEPLOY_LOG \ No newline at end of file +echo "$TIME_NOW > 실행된 프로세스 아이디 $CURRENT_PID 입니다." >> $DEPLOY_LOG diff --git a/src/main/java/com/kustacks/kuring/config/CustomConfig.java b/src/main/java/com/kustacks/kuring/config/CustomConfig.java deleted file mode 100644 index 21a0d9e4..00000000 --- a/src/main/java/com/kustacks/kuring/config/CustomConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.kustacks.kuring.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -@Configuration -@PropertySource(value = "classpath:constants.properties", ignoreResourceNotFound = true) -public class CustomConfig { -} diff --git a/src/main/java/com/kustacks/kuring/worker/scrap/client/notice/KuisNoticeApiClient.java b/src/main/java/com/kustacks/kuring/worker/scrap/client/notice/KuisNoticeApiClient.java index 6f60ad8d..b86ae001 100644 --- a/src/main/java/com/kustacks/kuring/worker/scrap/client/notice/KuisNoticeApiClient.java +++ b/src/main/java/com/kustacks/kuring/worker/scrap/client/notice/KuisNoticeApiClient.java @@ -38,7 +38,6 @@ public class KuisNoticeApiClient implements NoticeApiClient request(KuisNoticeInfo kuisNoticeRequestBody) throws InternalLogicException { - // sessionId 획득 String sessionId = parsingKuisAuthManager.getSessionId(); @@ -64,9 +63,14 @@ private HttpEntity kuisNoticeRequests(KuisNoticeInfo kuisNoticeRequestBo return new HttpEntity<>(encodedNoticeRequestBody, noticeRequestHeader); } - private ResponseEntity sendKuisNoticesRequestAndResponse(HttpEntity noticeRequestEntity) { + private ResponseEntity sendKuisNoticesRequestAndResponse( + HttpEntity noticeRequestEntity + ) throws InternalLogicException { try { - return restTemplate.postForEntity(kuisNoticeProperties.getRequestUrl(), noticeRequestEntity, KuisNoticeResponseDto.class); + return restTemplate.postForEntity( + kuisNoticeProperties.getRequestUrl(), + noticeRequestEntity, + KuisNoticeResponseDto.class); } catch (RestClientException e) { log.warn("세션 갱신이 필요합니다."); parsingKuisAuthManager.forceRenewing(); diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 00000000..d862f778 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,110 @@ +server: + deploy: + environment: ${DEPLOY_ENV} + port: ${PORT:8080} + tomcat: + mbeanregistry: + enabled: true + +spring: + jpa: + generate-ddl: false + hibernate: + ddl-auto: none + properties: + hibernate: + jdbc: + batch_size: 100 + format_sql: true + dialect: com.kustacks.kuring.config.CustomMariaDbDialect + defer-datasource-initialization: false + show-sql: false + open-in-view: false + datasource: + hikari: + connectionTimeout: '30000' + maximum-pool-size: '8' + max-lifetime: '1800000' + password: ${DB_PASSWORD} + username: ${DB_USER} + url: jdbc:${DB_URL} + driver-class-name: org.mariadb.jdbc.Driver + flyway: + enabled: true + baseline-on-migrate: true + url: jdbc:${DB_URL} + user: ${DB_USER} + password: ${DB_PASSWORD} + thymeleaf: + cache: true + prefix: classpath:/templates/ + suffix: .html + enabled: true + jackson: + serialization: + FAIL_ON_EMPTY_BEANS: false + +logging: + level: + org: + apache: + coyote: + http11: info + file: + name: classpath:/kuring.log + +management: + endpoint: + health: + show-details: always + endpoints: + web: + exposure: + include: "*" + +security: + jwt: + token: + secret-key: ${JWT_SECRET_KEY} + expire-length: ${JWT_EXPIRE_LENGTH} + + +notice: + kuis: + request-url: https://kuis.konkuk.ac.kr/CmmnOneStop/find.do + referer-url: https://kuis.konkuk.ac.kr/index.do + real-estate: + list-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice + view-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice + recent: + list-url: https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/artclList.do + view-url: https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/{noticeId}/artclView.do + normal-base-url: https://old.konkuk.ac.kr/do/MessageBoard/ArticleRead.do + library: + request-url: https://library.konkuk.ac.kr/pyxis-api/1/bulletin-boards/1/bulletins + library-base-url: https://library.konkuk.ac.kr/library-guide/bulletins/notice + +auth: + api-skeleton-producer-url: https://kuis.konkuk.ac.kr/ui/cpr-lib/user-modules.js?p=0.9460032500983822 + password: ${KU_PASSWORD} + user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38 + id: ${KU_ID} + session: JSESSIONID=00015GJS2T_gl7M-TqGjYvyHAuJ:-103KQM + referer: https://kuis.konkuk.ac.kr/index.do + login-url: https://kuis.konkuk.ac.kr/Login/login.do + +firebase: + file-path: third/ku-stack-firebase-adminsdk-87nwq-5ba04dfc12.json + +admin: + password: ${ADMIN_PASSWORD} + id: ${ADMIN_ID} + +ip: + proxy-list: 14.63.228.239:80, 101.79.15.198:80, 222.104.128.205:8678, 106.244.154.91:8080, 103.51.205.42:8181 + +staff: + real-estate-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=faculty + communication-design-url: http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_01_tab01.jsp + living-design-url: http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_05_tab01.jsp + each-dept-url: http://home.konkuk.ac.kr/cms/Common/Professor/ProfessorList.do diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 00000000..d862f778 --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,110 @@ +server: + deploy: + environment: ${DEPLOY_ENV} + port: ${PORT:8080} + tomcat: + mbeanregistry: + enabled: true + +spring: + jpa: + generate-ddl: false + hibernate: + ddl-auto: none + properties: + hibernate: + jdbc: + batch_size: 100 + format_sql: true + dialect: com.kustacks.kuring.config.CustomMariaDbDialect + defer-datasource-initialization: false + show-sql: false + open-in-view: false + datasource: + hikari: + connectionTimeout: '30000' + maximum-pool-size: '8' + max-lifetime: '1800000' + password: ${DB_PASSWORD} + username: ${DB_USER} + url: jdbc:${DB_URL} + driver-class-name: org.mariadb.jdbc.Driver + flyway: + enabled: true + baseline-on-migrate: true + url: jdbc:${DB_URL} + user: ${DB_USER} + password: ${DB_PASSWORD} + thymeleaf: + cache: true + prefix: classpath:/templates/ + suffix: .html + enabled: true + jackson: + serialization: + FAIL_ON_EMPTY_BEANS: false + +logging: + level: + org: + apache: + coyote: + http11: info + file: + name: classpath:/kuring.log + +management: + endpoint: + health: + show-details: always + endpoints: + web: + exposure: + include: "*" + +security: + jwt: + token: + secret-key: ${JWT_SECRET_KEY} + expire-length: ${JWT_EXPIRE_LENGTH} + + +notice: + kuis: + request-url: https://kuis.konkuk.ac.kr/CmmnOneStop/find.do + referer-url: https://kuis.konkuk.ac.kr/index.do + real-estate: + list-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice + view-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice + recent: + list-url: https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/artclList.do + view-url: https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/{noticeId}/artclView.do + normal-base-url: https://old.konkuk.ac.kr/do/MessageBoard/ArticleRead.do + library: + request-url: https://library.konkuk.ac.kr/pyxis-api/1/bulletin-boards/1/bulletins + library-base-url: https://library.konkuk.ac.kr/library-guide/bulletins/notice + +auth: + api-skeleton-producer-url: https://kuis.konkuk.ac.kr/ui/cpr-lib/user-modules.js?p=0.9460032500983822 + password: ${KU_PASSWORD} + user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38 + id: ${KU_ID} + session: JSESSIONID=00015GJS2T_gl7M-TqGjYvyHAuJ:-103KQM + referer: https://kuis.konkuk.ac.kr/index.do + login-url: https://kuis.konkuk.ac.kr/Login/login.do + +firebase: + file-path: third/ku-stack-firebase-adminsdk-87nwq-5ba04dfc12.json + +admin: + password: ${ADMIN_PASSWORD} + id: ${ADMIN_ID} + +ip: + proxy-list: 14.63.228.239:80, 101.79.15.198:80, 222.104.128.205:8678, 106.244.154.91:8080, 103.51.205.42:8181 + +staff: + real-estate-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=faculty + communication-design-url: http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_01_tab01.jsp + living-design-url: http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_05_tab01.jsp + each-dept-url: http://home.konkuk.ac.kr/cms/Common/Professor/ProfessorList.do diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d266318d..3d7808a0 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,67 +1,3 @@ -server: - port: ${PORT:8080} - tomcat: - mbeanregistry: - enabled: true - spring: - jpa: - generate-ddl: false - hibernate: - ddl-auto: none - properties: - hibernate: - jdbc: - batch_size: 100 - format_sql: true - dialect: com.kustacks.kuring.config.CustomMariaDbDialect - defer-datasource-initialization: false - show-sql: false - open-in-view: false - datasource: - hikari: - connectionTimeout: '30000' - maximum-pool-size: '8' - max-lifetime: '1800000' - password: ${DB_PASSWORD} - username: ${DB_USER} - url: jdbc:${DB_URL} - driver-class-name: org.mariadb.jdbc.Driver - flyway: - enabled: true - baseline-on-migrate: true - url: jdbc:${DB_URL} - user: ${DB_USER} - password: ${DB_PASSWORD} - thymeleaf: - cache: true - prefix: classpath:/templates/ - suffix: .html - enabled: true - jackson: - serialization: - FAIL_ON_EMPTY_BEANS: false - -logging: - level: - org: - apache: - coyote: - http11: info - file: - name: classpath:/kuring.log - -management: - endpoint: - health: - show-details: always - endpoints: - web: - exposure: - include: "*" - -security: - jwt: - token: - secret-key: ${JWT_SECRET_KEY} - expire-length: ${JWT_EXPIRE_LENGTH} + profiles: + active: dev diff --git a/src/main/resources/constants.properties b/src/main/resources/constants.properties deleted file mode 100644 index ca026383..00000000 --- a/src/main/resources/constants.properties +++ /dev/null @@ -1,31 +0,0 @@ -notice.kuis.request-url=https://kuis.konkuk.ac.kr/CmmnOneStop/find.do -notice.kuis.referer-url=https://kuis.konkuk.ac.kr/index.do -notice.normal-base-url=https://old.konkuk.ac.kr/do/MessageBoard/ArticleRead.do -notice.library-base-url=https://library.konkuk.ac.kr/library-guide/bulletins/notice -notice.recent.list-url=https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/artclList.do -notice.recent.view-url=https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/{noticeId}/artclView.do -notice.real-estate.list-url=http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice -notice.real-estate.view-url=http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice -notice.library.request-url=https://library.konkuk.ac.kr/pyxis-api/1/bulletin-boards/1/bulletins - -staff.communication-design-url=http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_01_tab01.jsp -staff.living-design-url=http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_05_tab01.jsp -staff.each-dept-url=http://home.konkuk.ac.kr/cms/Common/Professor/ProfessorList.do -staff.real-estate-url=http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=faculty - -auth.api-skeleton-producer-url=https://kuis.konkuk.ac.kr/ui/cpr-lib/user-modules.js?p=0.9460032500983822 -auth.session=JSESSIONID=00015GJS2T_gl7M-TqGjYvyHAuJ:-103KQM -auth.referer=https://kuis.konkuk.ac.kr/index.do -auth.login-url=https://kuis.konkuk.ac.kr/Login/login.do -auth.user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38 -auth.id=${KU_ID} -auth.password=${KU_PASSWORD} - -admin.id=${ADMIN_ID} -admin.password=${ADMIN_PASSWORD} - -firebase.file-path=third/ku-stack-firebase-adminsdk-87nwq-5ba04dfc12.json - -server.deploy.environment=${DEPLOY_ENV} - -ip.proxy-list=14.63.228.239:80, 101.79.15.198:80, 222.104.128.205:8678, 106.244.154.91:8080, 103.51.205.42:8181 diff --git a/src/test/java/com/kustacks/kuring/ApiDocumentUtils.java b/src/test/java/com/kustacks/kuring/ApiDocumentUtils.java deleted file mode 100644 index 4b90095b..00000000 --- a/src/test/java/com/kustacks/kuring/ApiDocumentUtils.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.kustacks.kuring; - -import org.springframework.restdocs.operation.preprocess.OperationRequestPreprocessor; -import org.springframework.restdocs.operation.preprocess.OperationResponsePreprocessor; - -import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; - -public interface ApiDocumentUtils { - static OperationRequestPreprocessor getDocumentRequest() { - return preprocessRequest( - modifyUris() - .scheme("https") - .host("kuring.herokuapp.com") - .removePort(), - prettyPrint()); - } - - static OperationResponsePreprocessor getDocumentResponse() { - return preprocessResponse(prettyPrint()); - } -} diff --git a/src/test/java/com/kustacks/kuring/notice/adapter/out/persistence/NoticeRepositoryTest.java b/src/test/java/com/kustacks/kuring/notice/adapter/out/persistence/NoticeRepositoryTest.java index f86db1ff..2966a37a 100644 --- a/src/test/java/com/kustacks/kuring/notice/adapter/out/persistence/NoticeRepositoryTest.java +++ b/src/test/java/com/kustacks/kuring/notice/adapter/out/persistence/NoticeRepositoryTest.java @@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; +@DisplayName("리포지토리 : Notice") class NoticeRepositoryTest extends IntegrationTestSupport { @Autowired diff --git a/src/test/java/com/kustacks/kuring/notice/domain/CategoryNameTest.java b/src/test/java/com/kustacks/kuring/notice/domain/CategoryNameTest.java index 592fb0e2..cc520f1a 100644 --- a/src/test/java/com/kustacks/kuring/notice/domain/CategoryNameTest.java +++ b/src/test/java/com/kustacks/kuring/notice/domain/CategoryNameTest.java @@ -10,6 +10,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +@DisplayName("도메인 : CategoryName") class CategoryNameTest { @DisplayName("name을 String으로 받아 해당 CategoryName enum으로 변환한다") diff --git a/src/test/java/com/kustacks/kuring/support/IntegrationTestSupport.java b/src/test/java/com/kustacks/kuring/support/IntegrationTestSupport.java index 8d700593..b8a0e40c 100644 --- a/src/test/java/com/kustacks/kuring/support/IntegrationTestSupport.java +++ b/src/test/java/com/kustacks/kuring/support/IntegrationTestSupport.java @@ -9,9 +9,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.TestPropertySource; -@TestPropertySource(locations = "classpath:test-constants.properties") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class IntegrationTestSupport { public static final String ADMIN_LOGIN_ID = "admin@email.com"; diff --git a/src/test/java/com/kustacks/kuring/user/adapter/out/persistence/UserRepositoryTest.java b/src/test/java/com/kustacks/kuring/user/adapter/out/persistence/UserRepositoryTest.java index ed483724..8399bcfe 100644 --- a/src/test/java/com/kustacks/kuring/user/adapter/out/persistence/UserRepositoryTest.java +++ b/src/test/java/com/kustacks/kuring/user/adapter/out/persistence/UserRepositoryTest.java @@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; - +@DisplayName("리포지토리 : User") class UserRepositoryTest extends IntegrationTestSupport { @Autowired diff --git a/src/test/java/com/kustacks/kuring/user/domain/BookmarksTest.java b/src/test/java/com/kustacks/kuring/user/domain/BookmarksTest.java index f1aa3cdb..09229c22 100644 --- a/src/test/java/com/kustacks/kuring/user/domain/BookmarksTest.java +++ b/src/test/java/com/kustacks/kuring/user/domain/BookmarksTest.java @@ -8,6 +8,7 @@ import static org.assertj.core.api.Assertions.*; +@DisplayName("도메인 : Bookmarks") class BookmarksTest { @DisplayName("사용자는 원하는 공지를 북마크 할 수 있다") diff --git a/src/test/java/com/kustacks/kuring/worker/client/notice/KuisNoticeApiClientTest.java b/src/test/java/com/kustacks/kuring/worker/client/notice/KuisNoticeApiClientTest.java deleted file mode 100644 index a8904cca..00000000 --- a/src/test/java/com/kustacks/kuring/worker/client/notice/KuisNoticeApiClientTest.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.kustacks.kuring.worker.client.notice; - -import com.kustacks.kuring.common.exception.code.ErrorCode; -import com.kustacks.kuring.common.exception.InternalLogicException; -import com.kustacks.kuring.common.utils.converter.KuisNoticeDtoToCommonFormatDtoConverter; -import com.kustacks.kuring.config.JsonConfig; -import com.kustacks.kuring.worker.scrap.client.auth.ParsingKuisAuthManager; -import com.kustacks.kuring.worker.scrap.client.notice.KuisNoticeApiClient; -import com.kustacks.kuring.worker.scrap.client.notice.property.KuisNoticeProperties; -import com.kustacks.kuring.worker.update.notice.dto.request.BachelorKuisNoticeInfo; -import com.kustacks.kuring.worker.update.notice.dto.request.EmploymentKuisNoticeInfo; -import com.kustacks.kuring.worker.update.notice.dto.request.IndustryUnivKuisNoticeInfo; -import com.kustacks.kuring.worker.update.notice.dto.request.NationalKuisNoticeInfo; -import com.kustacks.kuring.worker.update.notice.dto.request.NormalKuisNoticeInfo; -import com.kustacks.kuring.worker.update.notice.dto.request.ScholarshipKuisNoticeInfo; -import com.kustacks.kuring.worker.update.notice.dto.request.StudentKuisNoticeInfo; -import com.kustacks.kuring.worker.update.notice.dto.response.CommonNoticeFormatDto; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.context.TestConstructor; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.web.client.RestClientException; -import org.springframework.web.client.RestTemplate; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.BDDMockito.given; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withUnauthorizedRequest; - -@SpringJUnitConfig({ - KuisNoticeApiClient.class, RestTemplate.class, KuisNoticeDtoToCommonFormatDtoConverter.class, - BachelorKuisNoticeInfo.class, - ScholarshipKuisNoticeInfo.class, - EmploymentKuisNoticeInfo.class, - NationalKuisNoticeInfo.class, - StudentKuisNoticeInfo.class, - IndustryUnivKuisNoticeInfo.class, - NormalKuisNoticeInfo.class, - JsonConfig.class}) -@EnableConfigurationProperties(value = KuisNoticeProperties.class) -@TestPropertySource("classpath:test-constants.properties") -@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) -class KuisNoticeApiClientTest { - - private final KuisNoticeProperties kuisNoticeProperties; - - @InjectMocks - private final KuisNoticeApiClient kuisNoticeAPIClient; - private final RestTemplate restTemplate; - - @MockBean - private ParsingKuisAuthManager kuisAuthManager; - private MockRestServiceServer server; - private String testSession; - - public KuisNoticeApiClientTest(KuisNoticeApiClient kuisNoticeAPIClient, RestTemplate restTemplate, KuisNoticeProperties kuisNoticeProperties) { - this.kuisNoticeAPIClient = kuisNoticeAPIClient; - this.restTemplate = restTemplate; - this.kuisNoticeProperties = kuisNoticeProperties; - } - - @BeforeEach - void setUp() { - server = MockRestServiceServer.createServer(restTemplate); - testSession = "JSESSIONID=SESSION_ID"; - } - - @Test - @DisplayName("성공") - void success() { - - // given - String notice1ArticleId = "5b49a79"; - String notice1PostedDate = "20211220"; - String notice1Subject = "2022학년도 다,부,연계,연합,융합전공 신청(포기) 안내 (2021. 12. 20. 수정)"; - - String notice2ArticleId = "5b49a74"; - String notice2PostedDate = "20211219"; - String notice2Subject = "2022학년도 전과 신청 안내 (2021. 12. 20. 수정)"; - - List expectedNotices = new ArrayList<>(2); - CommonNoticeFormatDto notice1 = CommonNoticeFormatDto.builder() - .articleId(notice1ArticleId) - .postedDate(notice1PostedDate) - .subject(notice1Subject) - .build(); - CommonNoticeFormatDto notice2 = CommonNoticeFormatDto.builder() - .articleId(notice2ArticleId) - .postedDate(notice2PostedDate) - .subject(notice2Subject) - .build(); - expectedNotices.add(notice1); - expectedNotices.add(notice2); - - String expectedResponseBody = "{\"DS_LIST\": [" + - "{\"POSTED_DT\":\"" + notice1PostedDate + "\",\"SUBJECT\":\"" + notice1Subject + "\",\"ARTICLE_ID\":\"" + notice1ArticleId + "\"}," + - "{\"POSTED_DT\":\"" + notice2PostedDate + "\",\"SUBJECT\":\"" + notice2Subject + "\",\"ARTICLE_ID\":\"" + notice2ArticleId + "\"}" + - "]}"; - - given(kuisAuthManager.getSessionId()).willReturn(testSession); - server.expect(requestTo(kuisNoticeProperties.getRequestUrl())).andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(expectedResponseBody)); - - // when - List notices = new BachelorKuisNoticeInfo(kuisNoticeAPIClient).scrapLatestPageHtml(); - - // then - for(int i=0; i<2 ;++i) { - assertEquals(expectedNotices.get(i).getArticleId(), notices.get(i).getArticleId()); - assertEquals(expectedNotices.get(i).getPostedDate(), notices.get(i).getPostedDate()); - assertEquals(expectedNotices.get(i).getSubject(), notices.get(i).getSubject()); - } - } - - - @Test - @DisplayName("실패 - 응답 오류") - void failByBadResponse() { - - // given - given(kuisAuthManager.getSessionId()).willReturn(testSession); - server.expect(requestTo(kuisNoticeProperties.getRequestUrl())).andRespond(withUnauthorizedRequest()); - BachelorKuisNoticeInfo bachelorKuisNoticeInfo = new BachelorKuisNoticeInfo(kuisNoticeAPIClient); - - // when, then - InternalLogicException e = assertThrows(InternalLogicException.class, bachelorKuisNoticeInfo::scrapLatestPageHtml); - assertEquals(ErrorCode.KU_LOGIN_BAD_RESPONSE, e.getErrorCode()); - } - - @Test - @DisplayName("실패 - 응답 body가 없거나 JSON 파싱이 잘못됨") - void failByNoResponseBody() { - - // given - given(kuisAuthManager.getSessionId()).willReturn(testSession); - server.expect(requestTo(kuisNoticeProperties.getRequestUrl())).andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)); - BachelorKuisNoticeInfo bachelorKuisNoticeInfo = new BachelorKuisNoticeInfo(kuisNoticeAPIClient); - - //when, then - InternalLogicException e = assertThrows(InternalLogicException.class, bachelorKuisNoticeInfo::scrapLatestPageHtml); - assertEquals(ErrorCode.KU_NOTICE_CANNOT_PARSE_JSON, e.getErrorCode()); - } - - @Test - @DisplayName("실패 - 응답 body에 DS_LIST 필드가 없음") - void failByNoDsListField() { - - // given - String badResponseBody = "{\"UNKNOWN\": []}"; - given(kuisAuthManager.getSessionId()).willReturn(testSession); - server.expect(requestTo(kuisNoticeProperties.getRequestUrl())).andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(badResponseBody)); - BachelorKuisNoticeInfo bachelorKuisNoticeInfo = new BachelorKuisNoticeInfo(kuisNoticeAPIClient); - - //when, then - InternalLogicException e = assertThrows(InternalLogicException.class, bachelorKuisNoticeInfo::scrapLatestPageHtml); - assertEquals(ErrorCode.KU_NOTICE_CANNOT_PARSE_JSON, e.getErrorCode()); - } - - @DisplayName("실패 - 로그인 세션 획득 3회 실패") - @Test - void failAfterRetry() { - // given - given(kuisAuthManager.getSessionId()).willThrow(new InternalLogicException(ErrorCode.KU_LOGIN_BAD_RESPONSE, new RestClientException("로그인 세션 획득 실패"))); - BachelorKuisNoticeInfo bachelorKuisNoticeInfo = new BachelorKuisNoticeInfo(kuisNoticeAPIClient); - - // when, then - InternalLogicException e = assertThrows(InternalLogicException.class, bachelorKuisNoticeInfo::scrapLatestPageHtml); - assertEquals(ErrorCode.KU_LOGIN_BAD_RESPONSE, e.getErrorCode()); - } -} diff --git a/src/test/java/com/kustacks/kuring/worker/notice/ParsingKuisAuthManagerTest.java b/src/test/java/com/kustacks/kuring/worker/notice/ParsingKuisAuthManagerTest.java deleted file mode 100644 index 9f156303..00000000 --- a/src/test/java/com/kustacks/kuring/worker/notice/ParsingKuisAuthManagerTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.kustacks.kuring.worker.notice; - -import com.kustacks.kuring.common.exception.InternalLogicException; -import com.kustacks.kuring.common.exception.code.ErrorCode; -import com.kustacks.kuring.common.utils.encoder.RequestBodyEncoder; -import com.kustacks.kuring.config.JsonConfig; -import com.kustacks.kuring.config.RestTemplateConfig; -import com.kustacks.kuring.worker.scrap.client.auth.KuisAuthManager; -import com.kustacks.kuring.worker.scrap.client.auth.ParsingKuisAuthManager; -import com.kustacks.kuring.worker.scrap.client.auth.property.ParsingKuisAuthProperties; -import com.kustacks.kuring.worker.update.notice.dto.request.KuisLoginInfo; -import org.junit.jupiter.api.*; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.core.io.ClassPathResource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.test.context.TestConstructor; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.util.FileCopyUtils; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.springframework.test.web.client.ExpectedCount.times; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; - -@SpringJUnitConfig({ - ParsingKuisAuthManager.class, KuisLoginInfo.class, RequestBodyEncoder.class, - RestTemplateConfig.class, JsonConfig.class, ParsingKuisAuthProperties.class -}) -@EnableConfigurationProperties(value = ParsingKuisAuthProperties.class) -@TestPropertySource(locations = "classpath:test-constants.properties") -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) -class ParsingKuisAuthManagerTest { - - private final KuisAuthManager kuisAuthManager; - private final String apiSkeleton; - private final String successResponseBody = "{\"_METADATA_\":{\"success\":true}}"; - private final String failResponseBody = "{\"ERRMSGINFO\":{\"ERRMSG\":\"건국대학교에 허가되지 않은 접근입니다. 반복시도시 내부규정에 따라 해당 계정정보를 차단하며 경우에 따라 민형사상의 책임을 질 수 있습니다.\",\"STATUSCODE\":-2000,\"ERRCODE\":\"건국대학교에 허가되지 않은 접근입니다. 반복시도시 내부규정에 따라 해당 계정정보를 차단하며 경우에 따라 민형사상의 책임을 질 수 있습니다.\"}}"; - - private MockRestServiceServer server; - private ParsingKuisAuthProperties parsingKuisAuthProperties; - private RestTemplate restTemplate; - - public ParsingKuisAuthManagerTest( - KuisAuthManager parsingKuisAuthManager, - RestTemplate restTemplate, - ParsingKuisAuthProperties parsingKuisAuthProperties, - @Value("${auth.api-skeleton-file-path}") String apiSkeletonFilePath) throws IOException { - - this.kuisAuthManager = parsingKuisAuthManager; - this.restTemplate = restTemplate; - this.parsingKuisAuthProperties = parsingKuisAuthProperties; - apiSkeleton = readApiSkeleton(apiSkeletonFilePath); - } - - @AfterEach - void setUpAfter() { - kuisAuthManager.forceRenewing(); - } - - @BeforeEach - void setUpBefore() { - server = MockRestServiceServer.createServer(restTemplate); - kuisAuthManager.forceRenewing(); - } - - @Test - @Order(1) - @DisplayName("성공 - 로그인 후 세션ID 권한 획득") - void success() { - - // given - server.expect(requestTo(parsingKuisAuthProperties.getApiSkeletonProducerUrl())).andRespond(withSuccess().body(apiSkeleton)); - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add("Set-Cookie", "JSESSIONID=test_session_id;"); - server.expect(requestTo(parsingKuisAuthProperties.getLoginUrl())).andExpect(method(HttpMethod.POST)).andRespond(withSuccess().headers(httpHeaders).body(successResponseBody)); - - // when - String sessionId = kuisAuthManager.getSessionId(); - - // then - server.verify(); - assertEquals(parsingKuisAuthProperties.getSession(), sessionId); - } - - @Test - @Order(2) - @DisplayName("성공 - 기존에 사용한 세션ID 반환") - void successWithSessionCache() { - - // given - server.expect(times(1), requestTo(parsingKuisAuthProperties.getApiSkeletonProducerUrl())).andRespond(withSuccess().body(apiSkeleton)); - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add("Set-Cookie", "JSESSIONID=test_session_id;"); - server.expect(times(1), requestTo(parsingKuisAuthProperties.getLoginUrl())).andExpect(method(HttpMethod.POST)).andRespond(withSuccess().headers(httpHeaders).body(successResponseBody)); - - // when - String sessionId = kuisAuthManager.getSessionId(); - String secondSessionId = kuisAuthManager.getSessionId(); - - // then - server.verify(); - assertEquals(parsingKuisAuthProperties.getSession(), sessionId); - assertEquals(parsingKuisAuthProperties.getSession(), secondSessionId); - } - - @Test - @Order(3) - @DisplayName("실패 - 응답 body가 없음") - void failByNoBody() { - - // given - server.expect(requestTo(parsingKuisAuthProperties.getApiSkeletonProducerUrl())).andRespond(withSuccess().body(apiSkeleton)); - server.expect(requestTo(parsingKuisAuthProperties.getLoginUrl())).andExpect(method(HttpMethod.POST)).andRespond(withSuccess()); - - // when - InternalLogicException e = assertThrows(InternalLogicException.class, kuisAuthManager::getSessionId); - - // then - assertEquals(ErrorCode.KU_LOGIN_NO_RESPONSE_BODY, e.getErrorCode()); - } - - @Test - @Order(4) - @DisplayName("실패 - 응답 body에 success 문자열이 없음 (kuis 로그인 방식이 바뀜 or api skeleton 최신화 안됨)") - void failByNoSuccessStringInBody() { - - // given - server.expect(requestTo(parsingKuisAuthProperties.getApiSkeletonProducerUrl())).andRespond(withSuccess().body(apiSkeleton)); - server.expect(requestTo(parsingKuisAuthProperties.getLoginUrl())).andExpect(method(HttpMethod.POST)).andRespond(withSuccess().body(failResponseBody)); - - // when - InternalLogicException e = assertThrows(InternalLogicException.class, kuisAuthManager::getSessionId); - - // then - assertEquals(ErrorCode.KU_LOGIN_BAD_RESPONSE, e.getErrorCode()); - } - - private String readApiSkeleton(String path) throws IOException { - ClassPathResource resource = new ClassPathResource(path); - return resourceToString(resource.getInputStream()); - } - - private String resourceToString(InputStream inputStream) throws IOException { - return FileCopyUtils.copyToString(new InputStreamReader(inputStream)); - } -} diff --git a/src/test/java/com/kustacks/kuring/worker/scrap/client/auth/ParsingKuisAuthManagerTest.java b/src/test/java/com/kustacks/kuring/worker/scrap/client/auth/ParsingKuisAuthManagerTest.java new file mode 100644 index 00000000..4254753e --- /dev/null +++ b/src/test/java/com/kustacks/kuring/worker/scrap/client/auth/ParsingKuisAuthManagerTest.java @@ -0,0 +1,131 @@ +package com.kustacks.kuring.worker.scrap.client.auth; + +import com.kustacks.kuring.common.exception.InternalLogicException; +import com.kustacks.kuring.support.IntegrationTestSupport; +import com.kustacks.kuring.worker.scrap.client.auth.property.ParsingKuisAuthProperties; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +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.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.util.FileCopyUtils; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.springframework.test.web.client.ExpectedCount.times; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + + +class ParsingKuisAuthManagerTest extends IntegrationTestSupport { + + @Autowired + private ParsingKuisAuthProperties parsingKuisAuthProperties; + + @Autowired + private ParsingKuisAuthManager kuisAuthManager; + + @Autowired + private RestTemplate restTemplate; + + @Value("${auth.api-skeleton-file-path}") + private String apiSkeletonFilePath; + + private MockRestServiceServer server; + + @BeforeEach + void setUpBefore() { + server = MockRestServiceServer.createServer(restTemplate); + kuisAuthManager.forceRenewing(); + } + + @Test + @DisplayName("로그인에 성공한 후 세션ID 권한을 획득한다") + void success() throws IOException { + // given + String apiSkeleton = readApiSkeleton(apiSkeletonFilePath); + String successResponseBody = "{\"_METADATA_\":{\"success\":true}}"; + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add("Set-Cookie", "JSESSIONID=test_session_id;"); + + server.expect(times(1), requestTo(parsingKuisAuthProperties.getApiSkeletonProducerUrl())) + .andRespond(withSuccess().body(apiSkeleton)); + + server.expect(times(1), requestTo(parsingKuisAuthProperties.getLoginUrl())) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().headers(httpHeaders).body(successResponseBody)); + + // when + String sessionId = kuisAuthManager.getSessionId(); + + // then + assertAll( + () -> server.verify(), + () -> assertThat(parsingKuisAuthProperties.getSession()).isEqualTo(sessionId) + ); + } + + @Test + @DisplayName("로그인 요청에 대한 서버의 응답 body가 없는경우 예외를 발생시킨다") + void failByNoBody() throws IOException { + // given + String apiSkeleton = readApiSkeleton(apiSkeletonFilePath); + + server.expect(times(1), requestTo(parsingKuisAuthProperties.getApiSkeletonProducerUrl())) + .andRespond(withSuccess().body(apiSkeleton)); + + server.expect(times(1), requestTo(parsingKuisAuthProperties.getLoginUrl())) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess()); + + // when + ThrowingCallable actual = kuisAuthManager::getSessionId; + + // then + assertThatThrownBy(actual) + .isInstanceOf(InternalLogicException.class); + } + + @Test + @DisplayName("로그인 요청에 대한 서버의 응답 body에 success 문자열이 없는경우 예외를 발생시킨다 (kuis 로그인 방식이 바뀜 or api skeleton 최신화 안됨)") + void failByNoSuccessStringInBody() throws IOException { + // given + String apiSkeleton = readApiSkeleton(apiSkeletonFilePath); + String failResponseBody = "{\"ERRMSGINFO\":{\"ERRMSG\":\"건국대학교에 허가되지 않은 접근입니다. 반복시도시 내부규정에 따라 해당 계정정보를 차단하며 경우에 따라 민형사상의 책임을 질 수 있습니다.\",\"STATUSCODE\":-2000,\"ERRCODE\":\"건국대학교에 허가되지 않은 접근입니다. 반복시도시 내부규정에 따라 해당 계정정보를 차단하며 경우에 따라 민형사상의 책임을 질 수 있습니다.\"}}"; + + server.expect(times(1), requestTo(parsingKuisAuthProperties.getApiSkeletonProducerUrl())) + .andRespond(withSuccess().body(apiSkeleton)); + + server.expect(times(1), requestTo(parsingKuisAuthProperties.getLoginUrl())) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().body(failResponseBody)); + + // when + ThrowingCallable actual = kuisAuthManager::getSessionId; + + // then + assertThatThrownBy(actual) + .isInstanceOf(InternalLogicException.class); + } + + private String readApiSkeleton(String path) throws IOException { + ClassPathResource resource = new ClassPathResource(path); + return resourceToString(resource.getInputStream()); + } + + private String resourceToString(InputStream inputStream) throws IOException { + return FileCopyUtils.copyToString(new InputStreamReader(inputStream)); + } +} diff --git a/src/test/java/com/kustacks/kuring/worker/scrap/client/notice/KuisNoticeApiClientTest.java b/src/test/java/com/kustacks/kuring/worker/scrap/client/notice/KuisNoticeApiClientTest.java new file mode 100644 index 00000000..a934f461 --- /dev/null +++ b/src/test/java/com/kustacks/kuring/worker/scrap/client/notice/KuisNoticeApiClientTest.java @@ -0,0 +1,155 @@ +package com.kustacks.kuring.worker.scrap.client.notice; + +import com.kustacks.kuring.common.exception.InternalLogicException; +import com.kustacks.kuring.support.IntegrationTestSupport; +import com.kustacks.kuring.worker.scrap.client.auth.ParsingKuisAuthManager; +import com.kustacks.kuring.worker.scrap.client.notice.property.KuisNoticeProperties; +import com.kustacks.kuring.worker.update.notice.dto.request.BachelorKuisNoticeInfo; +import com.kustacks.kuring.worker.update.notice.dto.response.CommonNoticeFormatDto; +import org.assertj.core.api.ThrowableAssert; +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.mock.mockito.MockBean; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.groups.Tuple.tuple; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.client.ExpectedCount.times; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +@DisplayName("클라이언트 : KUIS 공지") +class KuisNoticeApiClientTest extends IntegrationTestSupport { + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private KuisNoticeProperties kuisNoticeProperties; + + @Autowired + private KuisNoticeApiClient kuisNoticeAPIClient; + + @Autowired + private BachelorKuisNoticeInfo bachelorKuisNoticeInfo; + + @MockBean + private ParsingKuisAuthManager kuisAuthManager; + + private MockRestServiceServer server; + + @BeforeEach + void setUpBefore() { + server = MockRestServiceServer.createServer(restTemplate); + } + + @Test + @DisplayName("kuis 공지사항을 성공적으로 스크랩 해온다") + void success() { + // given + String notice1ArticleId = "5b49a79"; + String notice1PostedDate = "20211220"; + String notice1Subject = "2022학년도 다,부,연계,연합,융합전공 신청(포기) 안내 (2021. 12. 20. 수정)"; + + String notice2ArticleId = "5b49a74"; + String notice2PostedDate = "20211219"; + String notice2Subject = "2022학년도 전과 신청 안내 (2021. 12. 20. 수정)"; + + String expectedResponseBody = "{\"DS_LIST\": [" + + "{\"POSTED_DT\":\"" + notice1PostedDate + "\",\"SUBJECT\":\"" + notice1Subject + "\",\"ARTICLE_ID\":\"" + notice1ArticleId + "\"}," + + "{\"POSTED_DT\":\"" + notice2PostedDate + "\",\"SUBJECT\":\"" + notice2Subject + "\",\"ARTICLE_ID\":\"" + notice2ArticleId + "\"}" + + "]}"; + + server.expect(times(1), requestTo(kuisNoticeProperties.getRequestUrl())) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(expectedResponseBody)); + + // when + List notices = kuisNoticeAPIClient + .request(bachelorKuisNoticeInfo); + + // then + assertAll( + () -> server.verify(), + () -> assertThat(notices).hasSize(2) + .extracting("articleId", "postedDate", "subject") + .containsExactlyInAnyOrder( + tuple(notice1ArticleId, notice1PostedDate, notice1Subject), + tuple(notice2ArticleId, notice2PostedDate, notice2Subject) + ) + ); + } + + @Test + @DisplayName("kuis 공지서버에 문제가 있는 경우에는 서버 에러로 간주한다") + void fail_by_kuis_server_error() { + // given + String testSession = "JSESSIONID=SESSION_ID"; + given(kuisAuthManager.getSessionId()).willReturn(testSession); + + server.expect(times(3), requestTo(kuisNoticeProperties.getRequestUrl())) + .andExpect(method(HttpMethod.POST)) + .andRespond(withServerError()); + + // when + ThrowableAssert.ThrowingCallable actual = + () -> kuisNoticeAPIClient.request(bachelorKuisNoticeInfo); + + // then + assertThatThrownBy(actual) + .isInstanceOf(InternalLogicException.class); + } + + @Test + @DisplayName("kuis 서버의 응답에 body가 없거는경우 서버 에러로 간주한다") + void failByNoResponseBody() { + // given + String testSession = "JSESSIONID=SESSION_ID"; + given(kuisAuthManager.getSessionId()).willReturn(testSession); + + server.expect(times(3), requestTo(kuisNoticeProperties.getRequestUrl())) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)); + + // when + ThrowableAssert.ThrowingCallable actual = + () -> kuisNoticeAPIClient.request(bachelorKuisNoticeInfo); + + // then + assertThatThrownBy(actual) + .isInstanceOf(InternalLogicException.class); + } + + @Test + @DisplayName("kuis 서버의 응답 body에 DS_LIST 필드가 없는 경우 서버 에러로 간주한다") + void failByNoDsListField() { + // given + String badResponseBody = "{\"UNKNOWN\": []}"; + String testSession = "JSESSIONID=SESSION_ID"; + + given(kuisAuthManager.getSessionId()).willReturn(testSession); + server.expect(times(3), requestTo(kuisNoticeProperties.getRequestUrl())) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(badResponseBody)); + + // when + ThrowableAssert.ThrowingCallable actual = + () -> kuisNoticeAPIClient.request(bachelorKuisNoticeInfo); + + // then + assertThatThrownBy(actual) + .isInstanceOf(InternalLogicException.class); + } +} diff --git a/src/test/java/com/kustacks/kuring/worker/client/staff/StaffScraperTest.java b/src/test/java/com/kustacks/kuring/worker/scrap/parser/StaffScraperTest.java similarity index 97% rename from src/test/java/com/kustacks/kuring/worker/client/staff/StaffScraperTest.java rename to src/test/java/com/kustacks/kuring/worker/scrap/parser/StaffScraperTest.java index a7633b27..872073f3 100644 --- a/src/test/java/com/kustacks/kuring/worker/client/staff/StaffScraperTest.java +++ b/src/test/java/com/kustacks/kuring/worker/scrap/parser/StaffScraperTest.java @@ -1,31 +1,27 @@ -package com.kustacks.kuring.worker.client.staff; +package com.kustacks.kuring.worker.scrap.parser; import com.fasterxml.jackson.databind.ObjectMapper; -import com.kustacks.kuring.worker.update.staff.dto.StaffDto; -import com.kustacks.kuring.common.exception.code.ErrorCode; import com.kustacks.kuring.common.exception.InternalLogicException; +import com.kustacks.kuring.common.exception.code.ErrorCode; +import com.kustacks.kuring.worker.scrap.StaffScraper; +import com.kustacks.kuring.worker.scrap.client.NormalJsoupClient; import com.kustacks.kuring.worker.scrap.client.notice.LatestPageNoticeApiClient; import com.kustacks.kuring.worker.scrap.client.notice.property.LatestPageNoticeProperties; -import com.kustacks.kuring.worker.client.staff.dto.TestStaffDTO; -import com.kustacks.kuring.worker.scrap.StaffScraper; import com.kustacks.kuring.worker.scrap.client.staff.EachDeptStaffApiClient; import com.kustacks.kuring.worker.scrap.client.staff.LivingAndCommunicationDesignStaffApiClient; -import com.kustacks.kuring.worker.scrap.client.NormalJsoupClient; import com.kustacks.kuring.worker.scrap.client.staff.RealEstateStaffApiClient; import com.kustacks.kuring.worker.scrap.deptinfo.DeptInfo; import com.kustacks.kuring.worker.scrap.deptinfo.art_design.CommunicationDesignDept; import com.kustacks.kuring.worker.scrap.deptinfo.art_design.LivingDesignDept; import com.kustacks.kuring.worker.scrap.deptinfo.liberal_art.KoreanDept; import com.kustacks.kuring.worker.scrap.deptinfo.real_estate.RealEstateDept; +import com.kustacks.kuring.worker.scrap.parser.dto.TestStaffDTO; import com.kustacks.kuring.worker.scrap.parser.notice.LatestPageNoticeHtmlParser; -import com.kustacks.kuring.worker.scrap.parser.staff.RealEstateStaffHtmlParser; import com.kustacks.kuring.worker.scrap.parser.staff.EachDeptStaffHtmlParser; import com.kustacks.kuring.worker.scrap.parser.staff.LivingAndCommunicationDesignStaffHtmlParser; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; +import com.kustacks.kuring.worker.scrap.parser.staff.RealEstateStaffHtmlParser; +import com.kustacks.kuring.worker.update.staff.dto.StaffDto; +import org.junit.jupiter.api.*; import org.mockserver.client.MockServerClient; import org.mockserver.integration.ClientAndServer; import org.mockserver.model.HttpRequest; @@ -35,7 +31,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.core.io.ClassPathResource; import org.springframework.test.context.TestConstructor; -import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.FileCopyUtils; @@ -53,6 +48,7 @@ import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; +@Disabled @SpringJUnitConfig({ StaffScraper.class, LatestPageNoticeApiClient.class, LatestPageNoticeHtmlParser.class, @@ -62,7 +58,6 @@ KoreanDept.class, LivingDesignDept.class, CommunicationDesignDept.class, RealEstateDept.class, ObjectMapper.class}) @EnableConfigurationProperties(value = LatestPageNoticeProperties.class) -@TestPropertySource("classpath:test-constants.properties") @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) public class StaffScraperTest { diff --git a/src/test/java/com/kustacks/kuring/worker/client/staff/dto/TestStaffDTO.java b/src/test/java/com/kustacks/kuring/worker/scrap/parser/dto/TestStaffDTO.java similarity index 94% rename from src/test/java/com/kustacks/kuring/worker/client/staff/dto/TestStaffDTO.java rename to src/test/java/com/kustacks/kuring/worker/scrap/parser/dto/TestStaffDTO.java index eabdb14e..984fbbb9 100644 --- a/src/test/java/com/kustacks/kuring/worker/client/staff/dto/TestStaffDTO.java +++ b/src/test/java/com/kustacks/kuring/worker/scrap/parser/dto/TestStaffDTO.java @@ -1,4 +1,4 @@ -package com.kustacks.kuring.worker.client.staff.dto; +package com.kustacks.kuring.worker.scrap.parser.dto; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/test/java/com/kustacks/kuring/worker/update/CategoryNoticeUpdaterTest.java b/src/test/java/com/kustacks/kuring/worker/update/CategoryNoticeUpdaterTest.java index f6c52de4..6899f62e 100644 --- a/src/test/java/com/kustacks/kuring/worker/update/CategoryNoticeUpdaterTest.java +++ b/src/test/java/com/kustacks/kuring/worker/update/CategoryNoticeUpdaterTest.java @@ -28,8 +28,7 @@ @SpringBootTest @TestPropertySource(properties = "spring.config.location=" + "classpath:/application.yml" + - ",classpath:/application-test.yml" + - ",classpath:/test-constants.properties") + ",classpath:/application-test.yml") class CategoryNoticeUpdaterTest { @MockBean diff --git a/src/test/java/com/kustacks/kuring/worker/update/DepartmentNoticeUpdaterTest.java b/src/test/java/com/kustacks/kuring/worker/update/DepartmentNoticeUpdaterTest.java index fbc8eaab..8a5fc6b2 100644 --- a/src/test/java/com/kustacks/kuring/worker/update/DepartmentNoticeUpdaterTest.java +++ b/src/test/java/com/kustacks/kuring/worker/update/DepartmentNoticeUpdaterTest.java @@ -28,8 +28,7 @@ @SpringBootTest @TestPropertySource(properties = "spring.config.location=" + "classpath:/application.yml" + - ",classpath:/application-test.yml" + - ",classpath:/test-constants.properties") + ",classpath:/application-test.yml") class DepartmentNoticeUpdaterTest { @MockBean diff --git a/src/test/resources/application-test.yml b/src/test/resources/application-test.yml index 931b4122..311b6915 100644 --- a/src/test/resources/application-test.yml +++ b/src/test/resources/application-test.yml @@ -44,3 +44,49 @@ security: token: secret-key: test-secret-key-test-secret-key-test-secret-key-test-secret-key expire-length: 3600000 + + +notice: + kuis: + request-url: https://kuis.konkuk.ac.kr/CmmnOneStop/find.do + referer-url: https://kuis.konkuk.ac.kr/index.do + real-estate: + list-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice + view-url: http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice + recent: + list-url: https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/artclList.do + view-url: https://{department}.konkuk.ac.kr/bbs/{department}/{siteId}/{noticeId}/artclView.do + normal-base-url: https://old.konkuk.ac.kr/do/MessageBoard/ArticleRead.do + library: + request-url: https://library.konkuk.ac.kr/pyxis-api/1/bulletin-boards/1/bulletins + library-base-url: https://library.konkuk.ac.kr/library-guide/bulletins/notice + +auth: + session: JSESSIONID=TEST_SESSION + api-skeleton-producer-url: https://kuis.konkuk.ac.kr/ui/cpr-lib/user-modules.js?p=0.9460032500983822 + password: ku_test_password + api-skeleton-file-path: notice/api-skeleton.js + referer: https://kuis.konkuk.ac.kr/index.do + user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38 + id: ku_test_id + login-url: https://kuis.konkuk.ac.kr/Login/login.do + +server: + deploy: + environment: test + +firebase: + file-path: third/ku-stack-firebase-adminsdk-87nwq-5ba04dfc12.json + +admin: + id: admin@email.com + password: admin_password + +ip: + proxy-list: 14.63.228.239:80, 101.79.15.198:80, 222.104.128.205:8678, 106.244.154.91:8080, 103.51.205.42:8181 + +staff: + real-estate-url: "http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=faculty" + communication-design-url: "http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_01_tab01.jsp" + living-design-url: "http://www.konkuk.ac.kr/jsp/Coll/coll_01_13_01_05_tab01.jsp" + each-dept-url: "http://home.konkuk.ac.kr/cms/Common/Professor/ProfessorList.do" diff --git a/src/test/resources/test-constants.properties b/src/test/resources/test-constants.properties deleted file mode 100644 index e9333024..00000000 --- a/src/test/resources/test-constants.properties +++ /dev/null @@ -1,27 +0,0 @@ -notice.kuis.request-url=https://kuis.konkuk.ac.kr/CmmnOneStop/find.do -notice.kuis.referer-url=https://kuis.konkuk.ac.kr/index.do -notice.normal-base-url=https://www.konkuk.ac.kr/do/MessageBoard/ArticleRead.do -notice.library-base-url=https://library.konkuk.ac.kr/library-guide/bulletins/notice -notice.recent.list-url=http://{department}.konkuk.ac.kr/noticeList.do -notice.recent.view-url=http://{department}.konkuk.ac.kr/noticeView.do -notice.real-estate.list-url=http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice -notice.real-estate.view-url=http://www.realestate.ac.kr/gb/bbs/board.php?bo_table=notice -notice.library.request-url=https://library.konkuk.ac.kr/pyxis-api/1/bulletin-boards/1/bulletins - -staff.communication-design-url=http://localhost:9000/jsp/Coll/coll_01_13_01_01_tab01.jsp -staff.living-design-url=http://localhost:9000/jsp/Coll/coll_01_13_01_05_tab01.jsp -staff.each-dept-url=http://localhost:9000/cms/Common/Professor/ProfessorList.do -staff.real-estate-url=http://localhost:9000/gb/bbs/board.php?bo_table=faculty - -auth.api-skeleton-file-path=notice/api-skeleton.js -auth.api-skeleton-producer-url=https://kuis.konkuk.ac.kr/ui/cpr-lib/user-modules.js?p=0.9460032500983822 -auth.session=JSESSIONID=TEST_SESSION -auth.referer=https://kuis.konkuk.ac.kr/index.do -auth.login-url=https://kuis.konkuk.ac.kr/Login/login.do -auth.user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38 -auth.id=ku_test_id -auth.password=ku_test_password - -server.deploy.environment=test - -ip.proxy-list=14.63.228.239:80, 101.79.15.198:80, 222.104.128.205:8678, 106.244.154.91:8080, 103.51.205.42:8181