Search in sources :

Example 1 with InMemoryRateLimiterComponent

use of io.apiman.gateway.engine.impl.InMemoryRateLimiterComponent in project apiman by apiman.

the class RateLimitingPolicyTest method testApply.

/**
 * Test method for {@link io.apiman.gateway.engine.policies.RateLimitingPolicy#parseConfiguration(java.lang.String)}.
 */
@Test
public void testApply() {
    RateLimitingPolicy policy = new RateLimitingPolicy();
    String json = "{\r\n" + "  \"limit\" : 10,\r\n" + "  \"granularity\" : \"User\",\r\n" + "  \"period\" : \"Minute\",\r\n" + "  \"userHeader\" : \"X-Identity\"\r\n" + "}";
    Object config = policy.parseConfiguration(json);
    ApiRequest request = new ApiRequest();
    request.setContract(createTestContract());
    request.setType("GET");
    request.setApiKey("12345");
    request.setRemoteAddr("1.2.3.4");
    request.setDestination("/");
    // $NON-NLS-2$
    request.getHeaders().put("X-Identity", "sclause");
    IPolicyContext context = Mockito.mock(IPolicyContext.class);
    final PolicyFailure failure = new PolicyFailure();
    Mockito.when(context.getComponent(IPolicyFailureFactoryComponent.class)).thenReturn(new IPolicyFailureFactoryComponent() {

        @Override
        public PolicyFailure createFailure(PolicyFailureType type, int failureCode, String message) {
            return failure;
        }
    });
    Mockito.when(context.getComponent(IRateLimiterComponent.class)).thenReturn(new InMemoryRateLimiterComponent());
    IPolicyChain<ApiRequest> chain;
    for (int count = 0; count < 10; count++) {
        chain = Mockito.mock(IPolicyChain.class);
        policy.apply(request, context, config, chain);
        Mockito.verify(chain).doApply(request);
    }
    // Failure - only allow 10 per minute!
    chain = Mockito.mock(IPolicyChain.class);
    policy.apply(request, context, config, chain);
    Mockito.verify(chain).doFailure(failure);
}
Also used : ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) IPolicyFailureFactoryComponent(io.apiman.gateway.engine.components.IPolicyFailureFactoryComponent) IPolicyChain(io.apiman.gateway.engine.policy.IPolicyChain) IPolicyContext(io.apiman.gateway.engine.policy.IPolicyContext) PolicyFailure(io.apiman.gateway.engine.beans.PolicyFailure) InMemoryRateLimiterComponent(io.apiman.gateway.engine.impl.InMemoryRateLimiterComponent) PolicyFailureType(io.apiman.gateway.engine.beans.PolicyFailureType) Test(org.junit.Test)

Aggregations

ApiRequest (io.apiman.gateway.engine.beans.ApiRequest)1 PolicyFailure (io.apiman.gateway.engine.beans.PolicyFailure)1 PolicyFailureType (io.apiman.gateway.engine.beans.PolicyFailureType)1 IPolicyFailureFactoryComponent (io.apiman.gateway.engine.components.IPolicyFailureFactoryComponent)1 InMemoryRateLimiterComponent (io.apiman.gateway.engine.impl.InMemoryRateLimiterComponent)1 IPolicyChain (io.apiman.gateway.engine.policy.IPolicyChain)1 IPolicyContext (io.apiman.gateway.engine.policy.IPolicyContext)1 Test (org.junit.Test)1