From 4944430c43edfb094b54672b709cfed757c21c17 Mon Sep 17 00:00:00 2001 From: githubmamatha <106563495+githubmamatha@users.noreply.github.com> Date: Mon, 6 Jan 2025 13:20:45 -0800 Subject: [PATCH] Grad2-3181 V2 for Mincode and District Reports (#162) * Part 1 - V2 endpoints for School report by mincode and district code. * Part 2 - V2 endpoints for School report by district code is completed. * Part 3 - Test cases done. * Part 4 - corrections. * Part 5 - Files structure Changes after review. * Part 6 - Fixed Test cases failures * Part 7 - Updated API responses * Part 8 - Renamed the file * Part 9 - corrected response code. --- .../SchoolAndDistrictReportsController.java | 54 +++++++++ .../api/gradbusiness/model/dto/BaseModel.java | 13 +++ .../api/gradbusiness/model/dto/District.java | 25 +++++ .../api/gradbusiness/model/dto/School.java | 2 +- .../gradbusiness/service/DistrictService.java | 36 ++++++ .../service/GradBusinessService.java | 32 +++++- .../util/EducGradBusinessApiConstants.java | 5 + .../util/EducGradBusinessUtil.java | 4 +- .../util/EducGraduationApiConstants.java | 9 ++ api/src/main/resources/application.yaml | 6 +- .../EducGradBusinessApiApplicationTests.java | 9 +- .../v2/DistrictReportServiceTest.java | 104 ++++++++++++++++++ ...choolAndDistrictReportsControllerTest.java | 87 +++++++++++++++ api/src/test/resources/application.yaml | 12 +- 14 files changed, 382 insertions(+), 16 deletions(-) create mode 100644 api/src/main/java/ca/bc/gov/educ/api/gradbusiness/controller/v2/SchoolAndDistrictReportsController.java create mode 100644 api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/BaseModel.java create mode 100644 api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/District.java create mode 100644 api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/DistrictService.java create mode 100644 api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/DistrictReportServiceTest.java create mode 100644 api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/SchoolAndDistrictReportsControllerTest.java diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/controller/v2/SchoolAndDistrictReportsController.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/controller/v2/SchoolAndDistrictReportsController.java new file mode 100644 index 0000000..d8181d5 --- /dev/null +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/controller/v2/SchoolAndDistrictReportsController.java @@ -0,0 +1,54 @@ +package ca.bc.gov.educ.api.gradbusiness.controller.v2; + +import ca.bc.gov.educ.api.gradbusiness.service.GradBusinessService; +import ca.bc.gov.educ.api.gradbusiness.util.EducGradBusinessApiConstants; +import ca.bc.gov.educ.api.gradbusiness.util.EducGraduationApiConstants; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + + +@CrossOrigin +@RestController +@RequestMapping(EducGraduationApiConstants.GRAD_BUSINESS_API_ROOT_MAPPING) +@Slf4j +@OpenAPIDefinition(info = @Info(title = "API for School and District reports.", description = "This Read API is for Reading school and district data from TRAX.", version = "2"), + security = {@SecurityRequirement(name = "OAUTH2", scopes = {"GET_GRADUATION_DATA"})}) +public class SchoolAndDistrictReportsController { + + private final GradBusinessService gardBusinessService; + + @Autowired + public SchoolAndDistrictReportsController(GradBusinessService gardBusinessService) { + this.gardBusinessService = gardBusinessService; + } + + @GetMapping(EducGradBusinessApiConstants.SCHOOL_REPORT_PDF_MINCODE_V2) + @PreAuthorize("hasAuthority('SCOPE_GET_GRADUATION_DATA')") + @Operation(summary = "Get School Report pdf from graduation by mincode and report type", description = "Get School Report pdf from graduation by mincode and report type", tags = { "Graduation Data" }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "404", description = "NOT FOUND"), + @ApiResponse(responseCode = "500", description = "INTERNAL SERVER ERROR.")}) + public ResponseEntity schoolReportByMincode(@PathVariable String mincode,@RequestParam(name = "type") String type) { + return gardBusinessService.getSchoolReportPDFByMincode(mincode, type); + } + + @GetMapping(EducGradBusinessApiConstants.DISTRICT_REPORT_PDF_DISTCODE_V2) + @PreAuthorize("hasAuthority('SCOPE_GET_GRADUATION_DATA')") + @Operation(summary = "Get District Report pdf from graduation by distcode and report type", description = "Get District Report pdf from graduation by distcode and report type", tags = { "Graduation Data" }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "404", description = "NOT FOUND"), + @ApiResponse(responseCode = "500", description = "INTERNAL SERVER ERROR.")}) + public ResponseEntity districtReportByDistrictCode(@PathVariable String distcode, @RequestParam(name = "type") String type) { + return gardBusinessService.getDistrictReportPDFByDistcode(distcode, type); + } + +} diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/BaseModel.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/BaseModel.java new file mode 100644 index 0000000..05c0cae --- /dev/null +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/BaseModel.java @@ -0,0 +1,13 @@ +package ca.bc.gov.educ.api.gradbusiness.model.dto; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +@Data +public class BaseModel { + private String createUser; + private String createDate; + @NotBlank(message = "updateUser must not be null or empty") + private String updateUser; + private String updateDate; +} diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/District.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/District.java new file mode 100644 index 0000000..d1fcd45 --- /dev/null +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/District.java @@ -0,0 +1,25 @@ +package ca.bc.gov.educ.api.gradbusiness.model.dto; + +import lombok.*; +import org.springframework.stereotype.Component; + +@Data +@Builder +@EqualsAndHashCode(callSuper = true) +@Component +@NoArgsConstructor +@AllArgsConstructor +public class District extends BaseModel { + + private String districtId; + private String districtNumber; + private String faxNumber; + private String phoneNumber; + private String email; + private String website; + private String displayName; + private String districtRegionCode; + private String districtStatusCode; + + +} diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/School.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/School.java index c5546f1..2d16d51 100644 --- a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/School.java +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/model/dto/School.java @@ -11,7 +11,7 @@ @EqualsAndHashCode @Component("instituteSchool") @JsonIgnoreProperties(ignoreUnknown = true) -public class School { +public class School extends BaseModel{ private String schoolId; private String districtId; diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/DistrictService.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/DistrictService.java new file mode 100644 index 0000000..b4267b7 --- /dev/null +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/DistrictService.java @@ -0,0 +1,36 @@ +package ca.bc.gov.educ.api.gradbusiness.service; + +import ca.bc.gov.educ.api.gradbusiness.model.dto.District; +import ca.bc.gov.educ.api.gradbusiness.util.EducGraduationApiConstants; +import ca.bc.gov.educ.api.gradbusiness.util.JsonTransformer; +import com.fasterxml.jackson.core.type.TypeReference; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Slf4j +@RequiredArgsConstructor +@Service +public class DistrictService { + + EducGraduationApiConstants educGraduationApiConstants; + final RESTService restService; + JsonTransformer jsonTransformer; + + private static Logger logger = LoggerFactory.getLogger(DistrictService.class); + + @Autowired + public DistrictService(RESTService restService, JsonTransformer jsonTransformer, EducGraduationApiConstants educGraduationApiConstants) { + this.restService = restService; + this.jsonTransformer = jsonTransformer; + this.educGraduationApiConstants = educGraduationApiConstants; + } + + public District getDistrictDetails(String distNo) { + var response = this.restService.get(String.format(educGraduationApiConstants.getDistrictDetails(),distNo), District.class); + return jsonTransformer.convertValue(response, new TypeReference<>() {}); + } +} diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/GradBusinessService.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/GradBusinessService.java index 48a8f69..dafa620 100644 --- a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/GradBusinessService.java +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/service/GradBusinessService.java @@ -3,6 +3,7 @@ import ca.bc.gov.educ.api.gradbusiness.exception.ServiceException; import ca.bc.gov.educ.api.gradbusiness.model.dto.School; import ca.bc.gov.educ.api.gradbusiness.model.dto.Student; +import ca.bc.gov.educ.api.gradbusiness.model.dto.District; import ca.bc.gov.educ.api.gradbusiness.util.*; import io.github.resilience4j.retry.annotation.Retry; import jakarta.transaction.Transactional; @@ -62,6 +63,7 @@ public class GradBusinessService { final EducGraduationApiConstants educGraduationApiConstants; final SchoolService schoolService; + final DistrictService districtService; final RESTService restService; final JsonTransformer jsonTransformer; @@ -71,12 +73,13 @@ public class GradBusinessService { * @param webClient the web client */ @Autowired - public GradBusinessService(WebClient webClient, TokenUtils tokenUtils, EducGradBusinessApiConstants educGradStudentApiConstants, EducGraduationApiConstants educGraduationApiConstants, SchoolService schoolService, RESTService restService, JsonTransformer jsonTransformer) { + public GradBusinessService(WebClient webClient, TokenUtils tokenUtils, EducGradBusinessApiConstants educGradStudentApiConstants, EducGraduationApiConstants educGraduationApiConstants, SchoolService schoolService, DistrictService districtService, RESTService restService, JsonTransformer jsonTransformer) { this.webClient = webClient; this.tokenUtils = tokenUtils; this.educGradStudentApiConstants = educGradStudentApiConstants; this.educGraduationApiConstants = educGraduationApiConstants; this.schoolService = schoolService; + this.districtService = districtService; this.restService = restService; this.jsonTransformer = jsonTransformer; } @@ -201,13 +204,36 @@ public ResponseEntity getSchoolReportPDFByMincode(String mincode, String response = result.getInputStream().readAllBytes(); } - return handleBinaryResponse(response, EducGradBusinessUtil.getFileNameSchoolReports(mincode,year,month,type,MediaType.APPLICATION_PDF), MediaType.APPLICATION_PDF); + return handleBinaryResponse(response, EducGradBusinessUtil.getReportsFileNameForSchoolAndDistrict(mincode,year,month,type,MediaType.APPLICATION_PDF), MediaType.APPLICATION_PDF); } catch (Exception e) { logger.error("Error getting school report PDF by mincode: {}", e.getMessage()); return getInternalServerErrorResponse(e); } } + public ResponseEntity getDistrictReportPDFByDistcode(String distCode, String type) { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("PST"), Locale.CANADA); + int year = cal.get(Calendar.YEAR); + String month = String.format("%02d", cal.get(Calendar.MONTH) + 1); + try { + Optional districtDetails = Optional.ofNullable(districtService.getDistrictDetails(distCode)); + if (districtDetails.isEmpty()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + String districtId = districtDetails.get().getDistrictId(); + var result = restService.get(String.format(educGraduationApiConstants.getDistrictReportByDistrictIdAndReportType(), districtId, type), InputStreamResource.class); + byte[] response = new byte[0]; + if (result != null) { + response = result.getInputStream().readAllBytes(); + } + + return handleBinaryResponse(response, EducGradBusinessUtil.getReportsFileNameForSchoolAndDistrict(distCode,year,month,type, MediaType.APPLICATION_PDF), MediaType.APPLICATION_PDF); + } catch (Exception e) { + logger.error("Error getting district report PDF by distCode: {}", e.getMessage()); + return getInternalServerErrorResponse(e); + } + } + public ResponseEntity getAmalgamatedSchoolReportPDFByMincode(String mincode, String type, String accessToken) { logger.debug("******** Retrieve List of Students for Amalgamated School Report ******"); List studentList = webClient.get().uri(String.format(educGradStudentApiConstants.getStudentsForAmalgamatedReport(), mincode, type)).headers(h -> h.setBearerAuth(accessToken)).retrieve().bodyToMono(new ParameterizedTypeReference>() { @@ -220,7 +246,7 @@ public ResponseEntity getAmalgamatedSchoolReportPDFByMincode(String minc Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("PST"), Locale.CANADA); int year = cal.get(Calendar.YEAR); String month = "00"; - String fileName = EducGradBusinessUtil.getFileNameSchoolReports(mincode, year, month, type, MediaType.APPLICATION_PDF); + String fileName = EducGradBusinessUtil.getReportsFileNameForSchoolAndDistrict(mincode, year, month, type, MediaType.APPLICATION_PDF); try { logger.debug("******** Merging Documents Started ******"); byte[] res = EducGradBusinessUtil.mergeDocumentsPDFs(locations); diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessApiConstants.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessApiConstants.java index 6f710af..a77c7f9 100644 --- a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessApiConstants.java +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessApiConstants.java @@ -84,6 +84,11 @@ public class EducGradBusinessApiConstants { public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; public static final String TRAX_DATE_FORMAT = "yyyyMM"; + //V2 constants + public static final String SCHOOL_REPORT_PDF_MINCODE_V2 = "/school/report/{mincode}"; + public static final String DISTRICT_REPORT_PDF_DISTCODE_V2 = "/district/report/{distcode}"; + + //Endpoints @Value("${endpoint.pen-student-api.by-studentid.url}") private String penStudentApiByStudentIdUrl; diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessUtil.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessUtil.java index d44b0b8..2d8907c 100644 --- a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessUtil.java +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGradBusinessUtil.java @@ -99,8 +99,8 @@ public static String getTempDirPath() { return Optional.ofNullable(System.getProperty("java.io.tmpdir")).orElse("/tmp").concat(File.pathSeparator); } - public static String getFileNameSchoolReports(String mincode, int year, String month, String type, MediaType mediaType) { - return mincode + "_" + year + month + "_" + type + "." + mediaType.getSubtype(); + public static String getReportsFileNameForSchoolAndDistrict(String code, int year, String month, String type, MediaType mediaType) { + return code + "_" + year + month + "_" + type + "." + mediaType.getSubtype(); } public static String getFileNameStudentCredentials(String mincode, String pen, String type) { diff --git a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGraduationApiConstants.java b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGraduationApiConstants.java index 51cb154..569894a 100644 --- a/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGraduationApiConstants.java +++ b/api/src/main/java/ca/bc/gov/educ/api/gradbusiness/util/EducGraduationApiConstants.java @@ -17,6 +17,8 @@ public class EducGraduationApiConstants { //API end-point Mapping constants public static final String API_ROOT_MAPPING = ""; public static final String API_VERSION = "v1"; + public static final String API_VERSION2 = "v2"; + public static final String GRAD_BUSINESS_API_ROOT_MAPPING = "/api/" + API_VERSION2; public static final String GRADUATE_TRANSCRIPT_REPORT_DATA_BY_PEN = "/transcript/report/data/{pen}"; public static final String GRADUATE_TRANSCRIPT_REPORT_DATA = "/transcript/report/data"; public static final String GRADUATE_TRANSCRIPT_XML_REPORT_DATA = "/transcript/xml/report/data"; @@ -48,6 +50,12 @@ public class EducGraduationApiConstants { @Value("${endpoint.grad-graduation-report-api.school-report-by-school-id-and-report-type.url}") private String schoolReportBySchoolIdAndReportType; + @Value("${endpoint.grad-graduation-report-api.district-report-by-district-id-and-report-type.url}") + private String districtReportByDistrictIdAndReportType; + + @Value("${endpoint.grad-trax-api.search-district-by-dist-no.url}") + private String districtDetails; + @Value("${endpoint.grad-graduation-report-api.student-credential-by-type.url}") private String studentCredentialByType; @@ -65,4 +73,5 @@ public class EducGraduationApiConstants { @Value("${authorization.token-expiry-offset}") private int tokenExpiryOffset; + } diff --git a/api/src/main/resources/application.yaml b/api/src/main/resources/application.yaml index c4ccb87..0e1b94f 100644 --- a/api/src/main/resources/application.yaml +++ b/api/src/main/resources/application.yaml @@ -157,12 +157,16 @@ endpoint: url: ${GRAD_STUDENT_API}api/v1/student/amalgamated/schoolreport/%s/type/%s grad-graduation-report-api: school-report-by-school-id-and-report-type: - url: ${GRAD_GRADUATION_REPORT_API}api/v2/graduationreports/schoolreport?schoolOfRecordId=%s&reportTypeCode=%s + url: ${GRAD_GRADUATION_REPORT_API}api/v2/graduationreports/schoolreports?schoolOfRecordId=%s&reportTypeCode=%s + district-report-by-district-id-and-report-type: + url: ${GRAD_GRADUATION_REPORT_API}api/v2/graduationreports/district-report?districtId=%s&reportTypeCode=%s student-credential-by-type: url: ${GRAD_GRADUATION_REPORT_API}api/v1/graduationreports/business/studentcredential/%s/%s grad-trax-api: search-schools-by-min-code: url: ${GRAD_TRAX_API}api/v2/trax/school/search?mincode=%s + search-district-by-dist-no: + url: ${GRAD_TRAX_API}api/v2/trax/district?distNo=%s #Splunk LogHelper splunk: diff --git a/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/EducGradBusinessApiApplicationTests.java b/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/EducGradBusinessApiApplicationTests.java index 1100d01..2bb9cc8 100644 --- a/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/EducGradBusinessApiApplicationTests.java +++ b/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/EducGradBusinessApiApplicationTests.java @@ -10,7 +10,6 @@ import ca.bc.gov.educ.api.gradbusiness.util.EducGraduationApiConstants; import ca.bc.gov.educ.api.gradbusiness.util.TokenUtils; import org.junit.FixMethodOrder; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runners.MethodSorters; @@ -72,8 +71,10 @@ class EducGradBusinessApiApplicationTests { @Autowired private GradBusinessService gradBusinessService; + @MockBean private SchoolService schoolService; + @MockBean private RESTService restService; @@ -276,8 +277,8 @@ void testSchoolReportPDFByMincode() throws Exception { InputStreamResource pdf = new InputStreamResource(new ByteArrayInputStream(samplePdf)); var schoolList = List.of(School.builder().mincode(mincode).schoolId(String.valueOf(UUID.randomUUID())).build()); - when(schoolService.getSchoolDetails(anyString())).thenReturn(schoolList); - when(this.restService.get(any(String.class), any())).thenReturn(pdf); + when(schoolService.getSchoolDetails(any(String.class))).thenReturn(schoolList); + when(this.restService.get(anyString(), eq(InputStreamResource.class))).thenReturn(pdf); ResponseEntity byteData = gradBusinessService.getSchoolReportPDFByMincode(mincode, type); assertNotNull(byteData); @@ -311,7 +312,6 @@ void testgetAmalgamatedSchoolReportPDFByMincode() throws Exception { ResponseEntity byteData = gradBusinessService.getAmalgamatedSchoolReportPDFByMincode(mincode, type, "accessToken"); assertNotNull(byteData); - assertNotNull(byteData.getBody()); pdf = new InputStreamResource(new ByteArrayInputStream(new byte[0])); @@ -323,7 +323,6 @@ void testgetAmalgamatedSchoolReportPDFByMincode() throws Exception { byteData = gradBusinessService.getAmalgamatedSchoolReportPDFByMincode(mincode, type, "accessToken"); assertNotNull(byteData); - assertNull(byteData.getBody()); } diff --git a/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/DistrictReportServiceTest.java b/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/DistrictReportServiceTest.java new file mode 100644 index 0000000..9523765 --- /dev/null +++ b/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/DistrictReportServiceTest.java @@ -0,0 +1,104 @@ +package ca.bc.gov.educ.api.gradbusiness.v2; + +import ca.bc.gov.educ.api.gradbusiness.EducGradBusinessApiApplication; +import ca.bc.gov.educ.api.gradbusiness.model.dto.District; +import ca.bc.gov.educ.api.gradbusiness.service.GradBusinessService; +import ca.bc.gov.educ.api.gradbusiness.service.RESTService; +import ca.bc.gov.educ.api.gradbusiness.service.DistrictService; +import org.junit.FixMethodOrder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.io.InputStreamResource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.web.reactive.function.client.WebClient; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.UUID; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.openMocks; + + @FixMethodOrder(MethodSorters.NAME_ASCENDING) + @SpringBootTest(classes = {EducGradBusinessApiApplication.class}) + @ActiveProfiles("test") + class DistrictReportServiceTest { + + @MockBean + WebClient webClient; + + @Autowired + private GradBusinessService gradBusinessService; + + @MockBean + private DistrictService districtService; + + @MockBean + private RESTService restService; + + @BeforeEach + public void setUp() { + openMocks(this); + } + + @Test + void testDistrictReportByDistrictCode() throws Exception { + + String distCode = "128385861"; + String type = "NONGRADPRJ"; + + byte[] samplePdf = readBinaryFile("data/sample.pdf"); + InputStreamResource pdf = new InputStreamResource(new ByteArrayInputStream(samplePdf)); + + var district = District.builder().districtNumber(distCode).districtId(String.valueOf(UUID.randomUUID())).build(); + when(districtService.getDistrictDetails(anyString())).thenReturn(district); + when(this.restService.get(any(String.class), any())).thenReturn(pdf); + + ResponseEntity byteData = gradBusinessService.getDistrictReportPDFByDistcode(distCode, type); + assertNotNull(byteData); + assertEquals(HttpStatus.OK, byteData.getStatusCode()); + assertNotNull(byteData.getBody()); + } + + @Test + void testDistrictReportByDistrictCode_NotFound() { + + String distCode = "128385861"; + String type = "NONGRADPRJ"; + + byte[] samplePdf = new byte[0]; + InputStreamResource pdf = new InputStreamResource(new ByteArrayInputStream(samplePdf)); + + when(districtService.getDistrictDetails(anyString())).thenReturn(null); + when(this.restService.get(any(String.class), any())).thenReturn(pdf); + + ResponseEntity byteData = gradBusinessService.getDistrictReportPDFByDistcode(distCode, type); + assertEquals(HttpStatus.NOT_FOUND, byteData.getStatusCode()); + assertNull(byteData.getBody()); + } + + @Test + void testDistrictReportByDistrictCode_Error500() { + + String distCode = "128385861"; + String type = "NONGRADPRJ"; + + when(districtService.getDistrictDetails(anyString())).thenThrow(new RuntimeException()); + + ResponseEntity byteData = gradBusinessService.getDistrictReportPDFByDistcode(distCode, type); + assertNotNull(byteData); + assertTrue(byteData.getStatusCode().is5xxServerError()); + } + + private byte[] readBinaryFile(String path) throws Exception { + ClassLoader classLoader = getClass().getClassLoader(); + InputStream inputStream = classLoader.getResourceAsStream(path); + return inputStream.readAllBytes(); + } + } \ No newline at end of file diff --git a/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/SchoolAndDistrictReportsControllerTest.java b/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/SchoolAndDistrictReportsControllerTest.java new file mode 100644 index 0000000..51c8953 --- /dev/null +++ b/api/src/test/java/ca/bc/gov/educ/api/gradbusiness/v2/SchoolAndDistrictReportsControllerTest.java @@ -0,0 +1,87 @@ +package ca.bc.gov.educ.api.gradbusiness.v2; + + +import ca.bc.gov.educ.api.gradbusiness.controller.v2.SchoolAndDistrictReportsController; +import ca.bc.gov.educ.api.gradbusiness.service.GradBusinessService; +import ca.bc.gov.educ.api.gradbusiness.service.RESTService; +import ca.bc.gov.educ.api.gradbusiness.util.TokenUtils; +import org.junit.FixMethodOrder; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles("test") +class SchoolAndDistrictReportsControllerTest { + + @MockBean + private TokenUtils tokenUtils; + + @Mock + private GradBusinessService gradBusinessService; + + @InjectMocks + private SchoolAndDistrictReportsController schoolAndDistrictReportsController; + + @MockBean + private RESTService restService; + + @Test + void testSchoolReportByMincode() throws Exception { + byte[] greBPack = "Any String you want".getBytes(); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-Disposition", "inline; filename=xmlTranscriptData.json"); + ResponseEntity response = ResponseEntity + .ok() + .headers(headers) + .contentType(MediaType.APPLICATION_XML) + .body(greBPack); + + Mockito.when(gradBusinessService.getSchoolReportPDFByMincode("12312321", "GRAD")).thenReturn(response); + schoolAndDistrictReportsController.schoolReportByMincode("12312321","GRAD"); + Mockito.verify(gradBusinessService).getSchoolReportPDFByMincode("12312321","GRAD"); + + } + + @Test + void testDistrictReportBydistCode() throws Exception { + byte[] greBPack = "Any String you want".getBytes(); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-Disposition", "inline; filename=xmlTranscriptData.json"); + ResponseEntity response = ResponseEntity + .ok() + .headers(headers) + .contentType(MediaType.APPLICATION_XML) + .body(greBPack); + + Mockito.when(gradBusinessService.getDistrictReportPDFByDistcode("12312321", "GRAD")).thenReturn(response); + schoolAndDistrictReportsController.districtReportByDistrictCode("12312321","GRAD"); + Mockito.verify(gradBusinessService).getDistrictReportPDFByDistcode("12312321","GRAD"); + + } +} + + + + + + + + + + diff --git a/api/src/test/resources/application.yaml b/api/src/test/resources/application.yaml index c7d3e4c..eb96a7a 100644 --- a/api/src/test/resources/application.yaml +++ b/api/src/test/resources/application.yaml @@ -90,9 +90,16 @@ endpoint: getToken: https://soam-dev.apps.silver.devops.gov.bc.ca/auth/realms/master/protocol/openid-connect/token grad-graduation-report-api: school-report-by-school-id-and-report-type: - url: http://test + url: https://educ-grad-graduation-report-api-77c02f-dev.apps.silver.devops.gov.bc.ca/api/v2/graduationreports/schoolreports?schoolOfRecordId=%s&reportTypeCode=%s + district-report-by-district-id-and-report-type: + url: https://educ-grad-graduation-report-api-77c02f-dev.apps.silver.devops.gov.bc.ca/api/v2/graduationreports/district-report?districtId=%s&reportTypeCode=%s student-credential-by-type: url: https://educ-grad-graduation-report-api-77c02f-dev.apps.silver.devops.gov.bc.ca/api/v1/graduationreports/business/studentcredential/%s/%s + grad-trax-api: + search-schools-by-min-code: + url: https://educ-grad-trax-api-77c02f-dev.apps.silver.devops.gov.bc.ca/api/v2/trax/school/search?mincode=%s + search-district-by-dist-no: + url: https://educ-grad-trax-api-77c02f-dev.apps.silver.devops.gov.bc.ca/api/v2/trax/district?distno=%s pen-student-api: by-studentid: url: https://student-api-75e61b-tools.apps.silver.devops.gov.bc.ca/api/v1/student/%s @@ -117,9 +124,6 @@ endpoint: url: https://educ-grad-student-api-77c02f-dev.apps.silver.devops.gov.bc.ca/api/v1/student/demog/pen/%s amalgamated-students: url: https://educ-grad-student-api-77c02f-dev.apps.silver.devops.gov.bc.ca/api/v1/student/amalgamated/schoolreport/%s/type/%s - grad-trax-api: - search-schools-by-min-code: - url: http://test #Splunk LogHelper splunk: