Added support for using oauth token for Kafka
[nonrtric/plt/ranpm.git] / datafilecollector / src / test / java / org / oran / datafile / http / DfcHttpClientTest.java
1 /*-
2  * ============LICENSE_START======================================================================
3  *  Copyright (C) 2020-2023 Nordix Foundation. All rights reserved.
4  * Copyright (C) 2020-2021 Nokia. All rights reserved.
5  * ===============================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7  * in compliance with the License. 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 distributed under the License
12  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13  * or implied. See the License for the specific language governing permissions and limitations under
14  * the License.
15  * ============LICENSE_END========================================================================
16  */
17 package org.oran.datafile.http;
18
19 import static org.assertj.core.api.Assertions.assertThatThrownBy;
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertFalse;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23 import static org.mockito.ArgumentMatchers.any;
24 import static org.mockito.Mockito.doReturn;
25 import static org.mockito.Mockito.spy;
26 import static org.mockito.Mockito.times;
27 import static org.mockito.Mockito.verify;
28 import static org.mockito.Mockito.when;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.InputStream;
32 import java.net.URISyntaxException;
33 import java.nio.file.Path;
34
35 import org.apache.hc.core5.net.URIBuilder;
36 import org.junit.jupiter.api.BeforeEach;
37 import org.junit.jupiter.api.Test;
38 import org.junit.jupiter.api.extension.ExtendWith;
39 import org.mockito.ArgumentMatchers;
40 import org.mockito.Mock;
41 import org.mockito.junit.jupiter.MockitoExtension;
42 import org.oran.datafile.commons.FileServerData;
43 import org.oran.datafile.exceptions.DatafileTaskException;
44 import org.oran.datafile.service.HttpUtils;
45
46 import reactor.core.publisher.Flux;
47 import reactor.netty.http.client.HttpClientConfig;
48
49 @ExtendWith(MockitoExtension.class)
50 class DfcHttpClientTest {
51
52     private static final String USERNAME = "bob";
53     private static final String PASSWORD = "123";
54     private static final String XNF_ADDRESS = "127.0.0.1";
55     private static final int PORT = 80;
56     private static final String JWT_PASSWORD = "thisIsThePassword";
57     private static String ACCESS_TOKEN = "access_token";
58
59     @Mock
60     private Path pathMock;
61
62     DfcHttpClient dfcHttpClientSpy;
63
64     @BeforeEach
65     public void setup() {
66         dfcHttpClientSpy = spy(new DfcHttpClient(createFileServerData()));
67     }
68
69     @Test
70     void openConnection_successBasicAuthSetup() throws DatafileTaskException {
71         dfcHttpClientSpy.open();
72         HttpClientConfig config = dfcHttpClientSpy.client.configuration();
73         assertEquals(HttpUtils.basicAuthContent(USERNAME, PASSWORD), config.headers().get("Authorization"));
74     }
75
76     @Test
77     void openConnection_failedBasicAuthSetupThrowException() {
78         FileServerData serverData =
79             FileServerData.builder().serverAddress(XNF_ADDRESS).userId(USERNAME).password("").port(PORT).build();
80
81         DfcHttpClient dfcHttpClientSpy = spy(new DfcHttpClient(serverData));
82
83         assertThatThrownBy(() -> dfcHttpClientSpy.open())
84             .hasMessageContaining("Not sufficient basic auth data for file.");
85     }
86
87     @Test
88     void collectFile_AllOk() throws Exception {
89         String REMOTE_FILE = "any";
90         Flux<InputStream> fis = Flux.just(new ByteArrayInputStream("ReturnedString".getBytes()));
91
92         dfcHttpClientSpy.open();
93
94         when(dfcHttpClientSpy.getServerResponse(any())).thenReturn(fis);
95         doReturn(false).when(dfcHttpClientSpy).isDownloadFailed(any());
96
97         dfcHttpClientSpy.collectFile(REMOTE_FILE, pathMock);
98         dfcHttpClientSpy.close();
99
100         verify(dfcHttpClientSpy, times(1)).getServerResponse(REMOTE_FILE);
101         verify(dfcHttpClientSpy, times(1)).processDataFromServer(any(), any(), any());
102         verify(dfcHttpClientSpy, times(1)).isDownloadFailed(any());
103     }
104
105     @Test
106     void collectFile_AllOkWithJWTToken() throws Exception {
107         dfcHttpClientSpy = spy(new DfcHttpClient(fileServerDataWithJWTToken()));
108         String REMOTE_FILE = "any";
109         Flux<InputStream> fis = Flux.just(new ByteArrayInputStream("ReturnedString".getBytes()));
110
111         dfcHttpClientSpy.open();
112         HttpClientConfig config = dfcHttpClientSpy.client.configuration();
113         assertEquals(HttpUtils.jwtAuthContent(JWT_PASSWORD), config.headers().get("Authorization"));
114
115         when(dfcHttpClientSpy.getServerResponse(any())).thenReturn(fis);
116         doReturn(false).when(dfcHttpClientSpy).isDownloadFailed(any());
117
118         dfcHttpClientSpy.collectFile(REMOTE_FILE, pathMock);
119         dfcHttpClientSpy.close();
120
121         verify(dfcHttpClientSpy, times(1)).getServerResponse(ArgumentMatchers.eq(REMOTE_FILE));
122         verify(dfcHttpClientSpy, times(1)).processDataFromServer(any(), any(), any());
123         verify(dfcHttpClientSpy, times(1)).isDownloadFailed(any());
124     }
125
126     @Test
127     void collectFile_No200ResponseWriteToErrorMessage() throws DatafileTaskException {
128         String ERROR_RESPONSE = "This is unexpected message";
129         String REMOTE_FILE = "any";
130         Flux<Throwable> fis = Flux.error(new Throwable(ERROR_RESPONSE));
131
132         dfcHttpClientSpy.open();
133
134         doReturn(fis).when(dfcHttpClientSpy).getServerResponse(any());
135
136         assertThatThrownBy(() -> dfcHttpClientSpy.collectFile(REMOTE_FILE, pathMock))
137             .hasMessageContaining(ERROR_RESPONSE);
138         verify(dfcHttpClientSpy, times(1)).getServerResponse(REMOTE_FILE);
139         verify(dfcHttpClientSpy, times(1)).processFailedConnectionWithServer(any(), any());
140         dfcHttpClientSpy.close();
141     }
142
143     @Test
144     void isResponseOk_validateResponse() {
145         assertTrue(dfcHttpClientSpy.isResponseOk(HttpClientResponseHelper.NETTY_RESPONSE_OK));
146         assertFalse(dfcHttpClientSpy.isResponseOk(HttpClientResponseHelper.RESPONSE_ANY_NO_OK));
147     }
148
149     private FileServerData createFileServerData() {
150         return FileServerData.builder().serverAddress(XNF_ADDRESS).userId(USERNAME).password(PASSWORD).port(PORT)
151             .build();
152     }
153
154     private FileServerData fileServerDataWithJWTToken() throws URISyntaxException {
155         String query = "?" + ACCESS_TOKEN + "=" + JWT_PASSWORD;
156
157         return FileServerData.builder().serverAddress(XNF_ADDRESS).userId("").password("").port(PORT)
158             .queryParameters(new URIBuilder(query).getQueryParams()).build();
159     }
160 }