|
| 1 | +package com.amazonaws.serverless.proxy.spark; |
| 2 | + |
| 3 | + |
| 4 | +import com.amazonaws.serverless.exceptions.ContainerInitializationException; |
| 5 | +import com.amazonaws.serverless.proxy.internal.model.AwsProxyRequest; |
| 6 | +import com.amazonaws.serverless.proxy.internal.model.AwsProxyResponse; |
| 7 | +import com.amazonaws.serverless.proxy.internal.testutils.AwsProxyRequestBuilder; |
| 8 | +import com.amazonaws.serverless.proxy.internal.testutils.MockLambdaContext; |
| 9 | +import com.amazonaws.serverless.proxy.spark.filter.CustomHeaderFilter; |
| 10 | + |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +import javax.servlet.DispatcherType; |
| 14 | +import javax.servlet.FilterRegistration; |
| 15 | + |
| 16 | +import java.util.EnumSet; |
| 17 | + |
| 18 | +import static org.junit.Assert.*; |
| 19 | +import static spark.Spark.get; |
| 20 | + |
| 21 | + |
| 22 | +public class SparkLambdaContainerHandlerTest { |
| 23 | + private static final String RESPONSE_BODY_TEXT = "hello"; |
| 24 | + |
| 25 | + @Test |
| 26 | + public void filters_onStartupMethod_executeFilters() { |
| 27 | + |
| 28 | + SparkLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler = null; |
| 29 | + try { |
| 30 | + handler = SparkLambdaContainerHandler.getAwsProxyHandler(); |
| 31 | + } catch (ContainerInitializationException e) { |
| 32 | + e.printStackTrace(); |
| 33 | + fail(); |
| 34 | + } |
| 35 | + |
| 36 | + handler.onStartup(c -> { |
| 37 | + if (c == null) { |
| 38 | + System.out.println("Null servlet context"); |
| 39 | + fail(); |
| 40 | + } |
| 41 | + FilterRegistration.Dynamic registration = c.addFilter("CustomHeaderFilter", CustomHeaderFilter.class); |
| 42 | + // update the registration to map to a path |
| 43 | + registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); |
| 44 | + // servlet name mappings are disabled and will throw an exception |
| 45 | + }); |
| 46 | + |
| 47 | + configureRoutes(); |
| 48 | + |
| 49 | + AwsProxyRequest req = new AwsProxyRequestBuilder().method("GET").path("/header-filter").build(); |
| 50 | + AwsProxyResponse response = handler.proxy(req, new MockLambdaContext()); |
| 51 | + |
| 52 | + assertNotNull(response); |
| 53 | + assertEquals(200, response.getStatusCode()); |
| 54 | + assertTrue(response.getHeaders().containsKey(CustomHeaderFilter.HEADER_NAME)); |
| 55 | + assertEquals(CustomHeaderFilter.HEADER_VALUE, response.getHeaders().get(CustomHeaderFilter.HEADER_NAME)); |
| 56 | + assertEquals(RESPONSE_BODY_TEXT, response.getBody()); |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + private void configureRoutes() { |
| 61 | + get("/header-filter", (req, res) -> { |
| 62 | + res.status(200); |
| 63 | + return RESPONSE_BODY_TEXT; |
| 64 | + }); |
| 65 | + } |
| 66 | +} |
0 commit comments