Skip to content

Commit

Permalink
MET-5960 add unit tests to the controller
Browse files Browse the repository at this point in the history
  • Loading branch information
jeortizquan committed Aug 27, 2024
1 parent 167a0c6 commit a54d1f1
Show file tree
Hide file tree
Showing 9 changed files with 355 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
* The type DeBias client.
*/
@Service
public class DebiasClient implements DetectService {

private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
Expand All @@ -44,8 +46,8 @@ public DebiasClient(String apiURL, Integer connectTimeOut, Integer readTimeOut)
/**
* Method to detect biased terms according to the input values provided
*
* @param detectionParameter language and values
* @return DetectionResult containing metadata and values of the detection
* @param detectionParameter {@link DetectionParameter} language and values
* @return {@link DetectionResult} containing metadata and values of the detection
*/
@Override
public DetectionResult detect(DetectionParameter detectionParameter) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import eu.europeana.metis.utils.RestEndpoints;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
Expand All @@ -23,11 +24,16 @@ public class DetectionController {
*/
DetectService detectService;

@Autowired
public DetectionController(DetectService detectService) {
this.detectService = detectService;
}

/**
* DeBias detection result.
*
* @param detectionParameter the detection parameter
* @return the detection result
* @param detectionParameter {@link DetectionParameter} the detection parameter
* @return {@link DetectionResult} the detection result
*/
@PostMapping(value = RestEndpoints.DEBIAS_DETECTION, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {
MediaType.APPLICATION_JSON_VALUE})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package eu.europeana.metis.debias.detect.rest.exceptions;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.net.URISyntaxException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ExceptionResponseHandler {

@ResponseBody
@ExceptionHandler({Exception.class})
public ServerError handleResponse(HttpServletResponse response, HttpServletRequest request,
Exception exception) {
final ResponseStatus annotationResponseStatus = AnnotationUtils
.findAnnotation(exception.getClass(), ResponseStatus.class);
HttpStatus status = annotationResponseStatus == null ? HttpStatus.INTERNAL_SERVER_ERROR
: annotationResponseStatus.value();
response.setStatus(status.value());
return new ServerError(exception.getMessage());
}

@ResponseBody
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ServerError handleResponse(HttpServletResponse response, HttpServletRequest request, HttpMediaTypeNotSupportedException exception) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
return new ServerError(exception.getMessage());
}

@ResponseBody
@ExceptionHandler(HttpMessageNotReadableException.class)
public ServerError handleResponse(HttpServletResponse response, HttpServletRequest request, HttpMessageNotReadableException exception) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
return new ServerError(exception.getMessage());
}

@ResponseBody
@ExceptionHandler({URISyntaxException.class})
public ServerError handleResponseURISystax(HttpServletResponse response, HttpServletRequest req,
Exception exception) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
return new ServerError(exception.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package eu.europeana.metis.debias.detect.rest.exceptions;

/**
* The type Server error.
*/
public class ServerError {

private String errorMessage;

/**
* Instantiates a new Server error.
*/
public ServerError() {
// Required for serialization and deserialization
}

/**
* Instantiates a new Server error.
*
* @param errorMessage the error message
*/
public ServerError(String errorMessage) {
this.errorMessage = errorMessage;
}

/**
* Gets error message.
*
* @return the error message
*/
public String getErrorMessage() {
return errorMessage;
}

/**
* Sets error message.
*
* @param errorMessage the error message
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package eu.europeana.metis.debias.detect.rest.controller;

import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.fasterxml.jackson.databind.ObjectMapper;
import eu.europeana.metis.debias.detect.model.DetectionParameter;
import eu.europeana.metis.debias.detect.model.DetectionResult;
import eu.europeana.metis.debias.detect.model.Metadata;
import eu.europeana.metis.debias.detect.model.Tag;
import eu.europeana.metis.debias.detect.model.ValueDetection;
import eu.europeana.metis.debias.detect.rest.client.DebiasClient;
import eu.europeana.metis.debias.detect.rest.exceptions.ExceptionResponseHandler;
import eu.europeana.metis.debias.detect.service.DetectService;
import eu.europeana.metis.utils.RestEndpoints;
import java.util.List;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.core.StringContains;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

class DetectionControllerTest {

private MockMvc mockMvc;
private DetectService detectService;

@BeforeEach
void setUp() {
detectService = mock(DebiasClient.class);
DetectionController detectionController = new DetectionController(detectService);
mockMvc = MockMvcBuilders.standaloneSetup(detectionController)
.setControllerAdvice(new ExceptionResponseHandler())
.alwaysDo(MockMvcResultHandlers.print())
.build();
}

@Test
void debias_detect_completeRequest_expectSuccess() throws Exception {
DetectionResult detectionResult = new DetectionResult();
ValueDetection valueDetection1 = new ValueDetection();
valueDetection1.setLanguage("en");
valueDetection1.setLiteral("sample title of aboriginal and addict");
Tag tag1 = new Tag();
tag1.setLength(10);
tag1.setStart(16);
tag1.setEnd(26);
tag1.setUri("http://www.example.org/debias#t_2_en");
Tag tag2 = new Tag();
tag2.setStart(31);
tag2.setEnd(37);
tag2.setUri("http://www.example.org/debias#t_3_en");
tag2.setLength(6);
valueDetection1.setTags(List.of(tag1, tag2));

detectionResult.setDetections(List.of(valueDetection1));
Metadata metadata = new Metadata();
detectionResult.setMetadata(metadata);
DetectionParameter detectionParameter = new DetectionParameter();
detectionParameter.setValues(List.of(
"sample title of aboriginal and addict",
"a second addict sample title",
"this is a demo of master and slave branch"));
detectionParameter.setLanguage("en");
ObjectMapper mapper = new ObjectMapper();
String detectionParameterJson = mapper.writeValueAsString(detectionParameter);
String expectedJson = mapper.writeValueAsString(detectionResult);
when(detectService.detect(any(DetectionParameter.class))).thenReturn(detectionResult);

mockMvc.perform(MockMvcRequestBuilders.post(RestEndpoints.DEBIAS_DETECTION)
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("utf-8")
.content(detectionParameterJson))
.andExpect(status().is(200))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string(expectedJson));
}

@Test
void debias_detect_NoLanguageRequest_expectSuccess() throws Exception {
DetectionResult detectionResult = new DetectionResult();
detectionResult.setDetections(List.of());
Metadata metadata = new Metadata();
detectionResult.setMetadata(metadata);
DetectionParameter detectionParameter = new DetectionParameter();
detectionParameter.setValues(List.of(
"sample title of aboriginal and addict",
"a second addict sample title",
"this is a demo of master and slave branch"));
detectionParameter.setLanguage("en");
ObjectMapper mapper = new ObjectMapper();
String detectionParameterJson = mapper.writeValueAsString(detectionParameter);
String expectedJson = mapper.writeValueAsString(detectionResult);
when(detectService.detect(any(DetectionParameter.class))).thenReturn(detectionResult);

mockMvc.perform(MockMvcRequestBuilders.post(RestEndpoints.DEBIAS_DETECTION)
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("utf-8")
.content(detectionParameterJson))
.andExpect(status().is(200))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string(expectedJson));
}

@Test
void debias_detect_emptyContentTypeRequest_expectContentTypeNotSupported() throws Exception {
DetectionResult detectionResult = new DetectionResult();
detectionResult.setDetections(List.of());
Metadata metadata = new Metadata();
detectionResult.setMetadata(metadata);

when(detectService.detect(any(DetectionParameter.class))).thenReturn(detectionResult);

mockMvc.perform(MockMvcRequestBuilders.post(RestEndpoints.DEBIAS_DETECTION)
.characterEncoding("utf-8"))
.andExpect(status().is(400))
.andExpect(jsonPath("$.errorMessage", containsString("Content-Type is not supported")));
}

@Test
void debias_detect_noBodyRequest_expectBadRequest() throws Exception {
DetectionResult detectionResult = new DetectionResult();
detectionResult.setDetections(List.of());
Metadata metadata = new Metadata();
detectionResult.setMetadata(metadata);

when(detectService.detect(any(DetectionParameter.class))).thenReturn(detectionResult);

mockMvc.perform(MockMvcRequestBuilders.post(RestEndpoints.DEBIAS_DETECTION)
.contentType(MediaType.APPLICATION_JSON)
.content("")
.characterEncoding("utf-8"))
.andExpect(status().is(400))
.andExpect(jsonPath("$.errorMessage", containsString("Required request body is missing")));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"detail": [
{
"type": "missing",
"loc": [
"body",
"language"
],
"msg": "Field required",
"input": {
"values": [
"sample title of aboriginal and addict",
"a second addict sample title",
"this is a demo of master and slave branch"
]
},
"url": "https://errors.pydantic.dev/2.5/v/missing"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"metadata": {
"annotator": "de-bias",
"thesaurus": null,
"date": "2024-08-27T12:04:17"
},
"results": [
{
"language": "en",
"literal": "sample title of aboriginal and addict",
"tags": [
{
"uri": "http://www.example.org/debias#t_2_en",
"start": 16,
"end": 26,
"length": 10
},
{
"uri": "http://www.example.org/debias#t_3_en",
"start": 31,
"end": 37,
"length": 6
}
]
},
{
"language": "en",
"literal": "a second addict sample title",
"tags": [
{
"uri": "http://www.example.org/debias#t_3_en",
"start": 9,
"end": 15,
"length": 6
}
]
},
{
"language": "en",
"literal": "this is a demo of master and slave branch",
"tags": [
{
"uri": "http://www.example.org/debias#t_198_en",
"start": 29,
"end": 34,
"length": 5
}
]
}
]
}
Loading

0 comments on commit a54d1f1

Please sign in to comment.