blob: 34db051aa2841b9744cdc6120b70ecf588c8a75b (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.filter.security.base;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
/**
* @author bjorncs
*/
public class JsonSecurityRequestFilterBaseTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void filter_renders_errors_as_json() throws IOException {
int statusCode = 403;
String message = "Forbidden";
DiscFilterRequest request = mock(DiscFilterRequest.class);
SimpleSecurityRequestFilter filter =
new SimpleSecurityRequestFilter(new JsonSecurityRequestFilterBase.ErrorResponse(statusCode, message));
RequestHandlerTestDriver.MockResponseHandler responseHandler = new RequestHandlerTestDriver.MockResponseHandler();
filter.filter(request, responseHandler);
Response response = responseHandler.getResponse();
assertNotNull(response);
assertEquals(statusCode, response.getStatus());
JsonNode jsonNode = mapper.readTree(responseHandler.readAll());
assertEquals(message, jsonNode.get("message").asText());
assertEquals(statusCode, jsonNode.get("code").asInt());
}
private static class SimpleSecurityRequestFilter extends JsonSecurityRequestFilterBase {
private final ErrorResponse errorResponse;
SimpleSecurityRequestFilter(ErrorResponse errorResponse) {
this.errorResponse = errorResponse;
}
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
return Optional.ofNullable(this.errorResponse);
}
}
}
|