Merge "Fixed SO request creation"
[policy/models.git] / models-interactions / model-impl / cds / src / test / java / org / onap / policy / cds / client / BasicAuthClientHeaderInterceptorTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 Bell Canada.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.policy.cds.client;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.mockito.AdditionalAnswers.delegatesTo;
23 import static org.mockito.Mockito.mock;
24 import static org.mockito.Mockito.verify;
25
26 import io.grpc.ClientInterceptors;
27 import io.grpc.ManagedChannel;
28 import io.grpc.Metadata;
29 import io.grpc.Metadata.Key;
30 import io.grpc.ServerCall;
31 import io.grpc.ServerCall.Listener;
32 import io.grpc.ServerCallHandler;
33 import io.grpc.ServerInterceptor;
34 import io.grpc.ServerInterceptors;
35 import io.grpc.inprocess.InProcessChannelBuilder;
36 import io.grpc.inprocess.InProcessServerBuilder;
37 import io.grpc.stub.StreamObserver;
38 import io.grpc.testing.GrpcCleanupRule;
39 import java.io.IOException;
40 import java.nio.charset.StandardCharsets;
41 import java.util.Base64;
42 import org.junit.Before;
43 import org.junit.Rule;
44 import org.junit.Test;
45 import org.mockito.ArgumentCaptor;
46 import org.mockito.ArgumentMatchers;
47 import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc;
48 import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase;
49 import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceStub;
50 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
51 import org.onap.policy.cds.properties.CdsServerProperties;
52
53 public class BasicAuthClientHeaderInterceptorTest {
54
55     // Generate a unique in-process server name.
56     private static final String SERVER_NAME = InProcessServerBuilder.generateName();
57     private static final String CREDS = "test";
58
59     // Manages automatic graceful shutdown for the registered server and client channels at the end of test.
60     @Rule
61     public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
62
63     private final ServerInterceptor mockCdsGrpcServerInterceptor = mock(ServerInterceptor.class,
64         delegatesTo(new TestServerInterceptor()));
65
66     private final CdsServerProperties props = new CdsServerProperties();
67
68     private ManagedChannel channel;
69
70     /**
71      * Setup the test.
72      *
73      * @throws IOException on failure to register the test grpc server for graceful shutdown
74      */
75     @Before
76     public void setUp() throws IOException {
77         // Setup the CDS properties
78         props.setHost(SERVER_NAME);
79         props.setPort(2000);
80         props.setUsername(CREDS);
81         props.setPassword(CREDS);
82         props.setTimeout(60);
83
84         // Implement the test gRPC server
85         BluePrintProcessingServiceImplBase testCdsBlueprintServerImpl = new BluePrintProcessingServiceImplBase() {};
86
87         // Create a server, add service, start, and register for automatic graceful shutdown.
88         grpcCleanup.register(InProcessServerBuilder.forName(SERVER_NAME).directExecutor()
89             .addService(ServerInterceptors.intercept(testCdsBlueprintServerImpl, mockCdsGrpcServerInterceptor)).build()
90             .start());
91
92         // Create a client channel and register for automatic graceful shutdown
93         channel = grpcCleanup.register(InProcessChannelBuilder.forName(SERVER_NAME).directExecutor().build());
94     }
95
96     @Test
97     public void testIfBasicAuthHeaderIsDeliveredToCdsServer() {
98         BluePrintProcessingServiceStub bpProcessingSvcStub = BluePrintProcessingServiceGrpc
99             .newStub(ClientInterceptors.intercept(channel, new BasicAuthClientHeaderInterceptor(props)));
100         ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
101         bpProcessingSvcStub.process(new StreamObserver<ExecutionServiceOutput>() {
102             @Override
103             public void onNext(final ExecutionServiceOutput executionServiceOutput) {
104                 // Test purpose only
105             }
106
107             @Override
108             public void onError(final Throwable throwable) {
109                 // Test purpose only
110             }
111
112             @Override
113             public void onCompleted() {
114                 // Test purpose only
115             }
116         });
117         verify(mockCdsGrpcServerInterceptor).interceptCall(ArgumentMatchers.any(), metadataCaptor.capture(),
118             ArgumentMatchers.any());
119
120         Key<String> authHeader = Key
121             .of(BasicAuthClientHeaderInterceptor.BASIC_AUTH_HEADER_KEY, Metadata.ASCII_STRING_MARSHALLER);
122         String expectedBaseAuth = Base64.getEncoder().encodeToString(String.format("%s:%s", CREDS, CREDS)
123             .getBytes(StandardCharsets.UTF_8));
124         assertEquals(expectedBaseAuth, metadataCaptor.getValue().get(authHeader));
125     }
126
127     private static class TestServerInterceptor implements ServerInterceptor {
128
129         @Override
130         public <ReqT, RespT> Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
131             final Metadata metadata,
132             final ServerCallHandler<ReqT, RespT> serverCallHandler) {
133             return serverCallHandler.startCall(serverCall, metadata);
134         }
135     }
136 }
137
138