HONEYCOMB-58 - Routing Api
[honeycomb.git] / vpp-common / vpp-translate-test / src / main / java / io / fd / honeycomb / vpp / test / util / FutureProducer.java
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package io.fd.honeycomb.vpp.test.util;
18
19 import java.util.concurrent.CompletableFuture;
20 import javax.annotation.Nonnull;
21 import io.fd.vpp.jvpp.VppCallbackException;
22 import io.fd.vpp.jvpp.core.future.FutureJVppCore;
23
24 /**
25  * <p>VPP translation test helper, that produces instances of {@link CompletableFuture} with desired results.</p>
26  * <p>Useful when stubbing {@link FutureJVppCore} methods: <br>{@code when(api.showVersion(any())).thenReturn(future(new
27  * ShowVersionReply()));}</p>
28  */
29 public interface FutureProducer {
30
31     /**
32      * Returns {@link CompletableFuture} with desired result.
33      *
34      * @param result returned when {@link CompletableFuture#get()} is invoked
35      * @param <T>    the result type of returned future
36      */
37     default <T> CompletableFuture<T> future(@Nonnull final T result) {
38         final CompletableFuture<T> future = new CompletableFuture<>();
39         future.complete(result);
40         return future;
41     }
42
43     /**
44      * Returns {@link CompletableFuture} with provided {@link Exception} as a result.
45      *
46      * @param exception to be thrown when {@link CompletableFuture#get()} is invoked
47      * @param <T>       the result type of returned future
48      */
49     default <T> CompletableFuture<T> failedFuture(@Nonnull final Exception exception) {
50         final CompletableFuture<T> future = new CompletableFuture<>();
51         future.completeExceptionally(exception);
52         return future;
53     }
54
55     /**
56      * Returns {@link CompletableFuture} with VppCallbackException(retval = -1) as a cause.
57      *
58      * @param <T> the result type of returned future
59      */
60     default <T> CompletableFuture<T> failedFuture() {
61         return failedFuture(new VppCallbackException("test-call", 1 /* ctxId */, -1 /* retval */));
62     }
63 }