Skip to content

Commit e93a6b0

Browse files
Added unit tests (#34)
1 parent 73377d3 commit e93a6b0

15 files changed

+933
-46
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@ before_install:
1111
- chmod +x pom.xml
1212

1313
script:
14-
- mvn -DskipTests
14+
- mvn test

pom.xml

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,17 @@
4848
<groupId>org.apache.httpcomponents</groupId>
4949
<artifactId>httpclient</artifactId>
5050
<version>4.5.3</version>
51-
</dependency>
52-
<dependency>
53-
<groupId>org.springframework.boot</groupId>
54-
<artifactId>spring-boot-starter-tomcat</artifactId>
55-
<scope>compile</scope>
56-
</dependency>
51+
</dependency>
52+
<dependency>
53+
<groupId>org.springframework.boot</groupId>
54+
<artifactId>spring-boot-starter-tomcat</artifactId>
55+
<scope>compile</scope>
56+
</dependency>
57+
<dependency>
58+
<groupId>org.springframework.boot</groupId>
59+
<artifactId>spring-boot-starter-test</artifactId>
60+
<scope>test</scope>
61+
</dependency>
5762
<dependency>
5863
<groupId>org.projectlombok</groupId>
5964
<artifactId>lombok</artifactId>
@@ -65,8 +70,33 @@
6570
<artifactId>gson</artifactId>
6671
<version>2.8.4</version>
6772
</dependency>
68-
73+
<!-- https://mvnrepository.com/artifact/junit/junit -->
74+
<dependency>
75+
<groupId>junit</groupId>
76+
<artifactId>junit</artifactId>
77+
<version>4.12</version>
78+
</dependency>
79+
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
80+
<dependency>
81+
<groupId>org.mockito</groupId>
82+
<artifactId>mockito-all</artifactId>
83+
<version>1.10.19</version>
84+
</dependency>
85+
<!-- https://mvnrepository.com/artifact/org.mock-server/mockserver-netty -->
86+
<dependency>
87+
<groupId>org.mock-server</groupId>
88+
<artifactId>mockserver-netty</artifactId>
89+
<version>5.3.0</version>
90+
<scope>test</scope>
91+
</dependency>
92+
<!-- https://mvnrepository.com/artifact/org.mock-server/mockserver-client-java -->
93+
<dependency>
94+
<groupId>org.mock-server</groupId>
95+
<artifactId>mockserver-client-java</artifactId>
96+
<version>5.3.0</version>
97+
</dependency>
6998
</dependencies>
99+
70100
<build>
71101
<plugins>
72102
<plugin>

src/main/java/com/ericsson/ei/frontend/EIRequestsController.java

Lines changed: 20 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@
1414
package com.ericsson.ei.frontend;
1515

1616
import com.ericsson.ei.frontend.model.BackEndInformation;
17+
import org.apache.commons.lang3.StringUtils;
1718
import org.apache.http.HttpEntity;
1819
import org.apache.http.client.methods.*;
1920
import org.apache.http.entity.ByteArrayEntity;
2021
import org.apache.http.impl.client.CloseableHttpClient;
2122
import org.apache.http.impl.client.HttpClientBuilder;
23+
import org.apache.http.util.EntityUtils;
2224
import org.slf4j.Logger;
2325
import org.slf4j.LoggerFactory;
2426
import org.springframework.beans.factory.annotation.Autowired;
@@ -33,20 +35,18 @@
3335
import org.springframework.web.bind.annotation.RestController;
3436

3537
import javax.servlet.http.HttpServletRequest;
36-
import java.io.BufferedReader;
3738
import java.io.IOException;
38-
import java.io.InputStream;
39-
import java.io.InputStreamReader;
4039
import java.util.ArrayList;
4140
import java.util.Arrays;
4241
import java.util.List;
42+
import java.util.stream.Collectors;
4343

4444
@RestController
4545
public class EIRequestsController {
4646

4747
private static final Logger LOG = LoggerFactory.getLogger(EIRequestsController.class);
4848

49-
private static final List<String> REQUSETS_WITH_QUERY_PARAM = new ArrayList<>(Arrays.asList("/queryAggregatedObject", "/queryMissedNotifications", "/query"));
49+
private static final List<String> REQUESTS_WITH_QUERY_PARAM = new ArrayList<>(Arrays.asList("/queryAggregatedObject", "/queryMissedNotifications", "/query"));
5050

5151
private CloseableHttpClient client = HttpClientBuilder.create().build();
5252

@@ -101,19 +101,16 @@ public ResponseEntity<String> getRequests(Model model, HttpServletRequest reques
101101
public ResponseEntity<String> postRequests(Model model, HttpServletRequest request) {
102102
String eiRequestUrl = getEIRequestURL(request);
103103

104-
String inputReqJsonContent = "";
104+
String requestBody = "";
105105
try {
106-
BufferedReader inputBufReader = new BufferedReader(request.getReader());
107-
for (String line = inputBufReader.readLine(); line != null; line = inputBufReader.readLine()) {
108-
inputReqJsonContent += line;
109-
}
110-
inputBufReader.close();
106+
requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
111107
} catch (IOException e) {
112108
LOG.error("Forward Request Errors: " + e);
113109
}
114110

115-
LOG.debug("Input Request JSON Content to be forwarded:\n" + inputReqJsonContent);
116-
HttpEntity inputReqJsonEntity = new ByteArrayEntity(inputReqJsonContent.getBytes());
111+
LOG.debug("Input Request JSON Content to be forwarded:\n" + requestBody);
112+
113+
HttpEntity inputReqJsonEntity = new ByteArrayEntity(requestBody.getBytes());
117114

118115
HttpPost eiRequest = new HttpPost(eiRequestUrl);
119116
eiRequest.setEntity(inputReqJsonEntity);
@@ -131,19 +128,16 @@ public ResponseEntity<String> postRequests(Model model, HttpServletRequest reque
131128
public ResponseEntity<String> putRequests(Model model, HttpServletRequest request) {
132129
String eiRequestUrl = getEIRequestURL(request);
133130

134-
String inputReqJsonContent = "";
131+
String requestBody = "";
135132
try {
136-
BufferedReader inputBufReader = new BufferedReader(request.getReader());
137-
for (String line = inputBufReader.readLine(); line != null; line = inputBufReader.readLine()) {
138-
inputReqJsonContent += line;
139-
}
140-
inputBufReader.close();
133+
requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
141134
} catch (IOException e) {
142135
LOG.error("Forward Request Errors: " + e);
143136
}
144137

145-
LOG.debug("Input Request JSON Content to be forwarded:\n" + inputReqJsonContent);
146-
HttpEntity inputReqJsonEntity = new ByteArrayEntity(inputReqJsonContent.getBytes());
138+
LOG.debug("Input Request JSON Content to be forwarded:\n" + requestBody);
139+
140+
HttpEntity inputReqJsonEntity = new ByteArrayEntity(requestBody.getBytes());
147141

148142
HttpPut eiRequest = new HttpPut(eiRequestUrl);
149143
eiRequest.setEntity(inputReqJsonEntity);
@@ -182,7 +176,7 @@ private String getEIBackendSubscriptionAddress() {
182176
private String getEIRequestURL(HttpServletRequest request) {
183177
String eiBackendAddressSuffix = request.getServletPath();
184178
String requestUrl;
185-
if(REQUSETS_WITH_QUERY_PARAM.contains(eiBackendAddressSuffix)) {
179+
if(REQUESTS_WITH_QUERY_PARAM.contains(eiBackendAddressSuffix)) {
186180
String requestQuery = request.getQueryString();
187181
String query = (requestQuery != null && !requestQuery.isEmpty()) ? "?" + requestQuery : "";
188182
requestUrl = getEIBackendSubscriptionAddress() + eiBackendAddressSuffix + query;
@@ -196,23 +190,14 @@ private String getEIRequestURL(HttpServletRequest request) {
196190
}
197191

198192
private ResponseEntity<String> getResponse(HttpRequestBase request) {
199-
String jsonContent = "";
193+
String responseBody = "";
200194
int statusCode = HttpStatus.PROCESSING.value();
201195
try (CloseableHttpResponse eiResponse = client.execute(request)) {
202-
InputStream inStream = eiResponse.getEntity().getContent();
203-
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
204-
for (String line = bufReader.readLine(); line != null; line = bufReader.readLine()) {
205-
jsonContent += line;
206-
}
207-
if (jsonContent.isEmpty()) {
208-
jsonContent = "[]";
209-
}
196+
responseBody = StringUtils.defaultIfBlank(EntityUtils.toString(eiResponse.getEntity(), "utf-8"), "[]");
210197
statusCode = eiResponse.getStatusLine().getStatusCode();
211-
LOG.info("EI Http Reponse Status Code: " + eiResponse.getStatusLine().getStatusCode()
212-
+ "\nEI Recevied jsonContent:\n" + jsonContent
198+
LOG.info("EI Http response status code: " + eiResponse.getStatusLine().getStatusCode()
199+
+ "\nEI Received response body:\n" + responseBody
213200
+ "\nForwarding response back to EI Frontend WebUI.");
214-
bufReader.close();
215-
inStream.close();
216201
} catch (IOException e) {
217202
statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
218203
LOG.error("Forward Request Errors: " + e);
@@ -221,7 +206,7 @@ private ResponseEntity<String> getResponse(HttpRequestBase request) {
221206
HttpHeaders headers = new HttpHeaders();
222207
headers.setContentType(MediaType.APPLICATION_JSON);
223208

224-
return new ResponseEntity<>(jsonContent, headers, HttpStatus.valueOf(statusCode));
209+
return new ResponseEntity<>(responseBody, headers, HttpStatus.valueOf(statusCode));
225210
}
226211

227212
}

src/main/java/com/ericsson/ei/frontend/utils/BackEndInstancesUtils.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import java.io.FileWriter;
3333
import java.io.IOException;
3434
import java.nio.file.Files;
35+
import java.nio.file.Path;
3536
import java.nio.file.Paths;
3637
import java.util.ArrayList;
3738
import java.util.List;
@@ -123,9 +124,7 @@ public boolean checkIfInstanceAlreadyExist(JsonObject instance) {
123124

124125
public void writeIntoFile() {
125126
try {
126-
FileWriter fileWriter = new FileWriter(eiInstancesPath);
127-
fileWriter.append(instances.toString());
128-
fileWriter.flush();
127+
Files.write(Paths.get(eiInstancesPath), instances.toString().getBytes());
129128
} catch (IOException e) {
130129
LOG.error("Couldn't add instance to file " + e.getMessage());
131130
}
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
/*
2+
Copyright 2017 Ericsson AB.
3+
For a full list of individual contributors, please see the commit history.
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+
http://www.apache.org/licenses/LICENSE-2.0
8+
Unless required by applicable law or agreed to in writing, software
9+
distributed under the License is distributed on an "AS IS" BASIS,
10+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
See the License for the specific language governing permissions and
12+
limitations under the License.
13+
*/
14+
package com.ericsson.ei.frontend;
15+
16+
import com.ericsson.ei.frontend.model.BackEndInformation;
17+
import com.ericsson.ei.frontend.utils.BackEndInstancesUtils;
18+
import com.fasterxml.jackson.databind.ObjectMapper;
19+
import com.google.gson.JsonArray;
20+
import com.google.gson.JsonElement;
21+
import com.google.gson.JsonObject;
22+
import com.google.gson.JsonParser;
23+
import org.junit.Before;
24+
import org.junit.Test;
25+
import org.junit.runner.RunWith;
26+
import org.springframework.beans.factory.annotation.Autowired;
27+
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
28+
import org.springframework.boot.test.context.SpringBootTest;
29+
import org.springframework.boot.test.mock.mockito.MockBean;
30+
import org.springframework.http.MediaType;
31+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
32+
import org.springframework.test.web.servlet.MockMvc;
33+
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
34+
35+
import java.io.FileReader;
36+
import java.util.ArrayList;
37+
import java.util.List;
38+
39+
import static org.mockito.ArgumentMatchers.any;
40+
import static org.mockito.Mockito.when;
41+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
42+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
43+
44+
@RunWith(SpringJUnit4ClassRunner.class)
45+
@SpringBootTest
46+
@AutoConfigureMockMvc
47+
public class BackendInformationControllerTest {
48+
49+
private static final String BACKEND_INSTANCE_FILE_PATH = "src/test/resources/backendInstances/backendInstance.json";
50+
private static final String BACKEND_INSTANCES_FILE_PATH = "src/test/resources/backendInstances/backendInstances.json";
51+
52+
@Autowired
53+
private MockMvc mockMvc;
54+
55+
@MockBean
56+
private BackEndInstancesUtils utils;
57+
58+
private JsonObject instance;
59+
private JsonArray instances;
60+
private List<BackEndInformation> information;
61+
62+
@Before
63+
public void before() throws Exception {
64+
instance = new JsonParser().parse(new FileReader(BACKEND_INSTANCE_FILE_PATH)).getAsJsonObject();
65+
instances = new JsonParser().parse(new FileReader(BACKEND_INSTANCES_FILE_PATH)).getAsJsonArray();
66+
information = new ArrayList<>();
67+
for(JsonElement element : instances) {
68+
information.add(new ObjectMapper().readValue(element.toString(), BackEndInformation.class));
69+
}
70+
}
71+
72+
@Test
73+
public void testGetInstances() throws Exception {
74+
when(utils.getInstances()).thenReturn(instances);
75+
mockMvc.perform(MockMvcRequestBuilders.get("/get-instances")
76+
.accept(MediaType.APPLICATION_JSON_VALUE))
77+
.andExpect(status().isOk())
78+
.andExpect(content().string(instances.toString()))
79+
.andReturn();
80+
}
81+
82+
@Test
83+
public void testAddInstance() throws Exception {
84+
when(utils.checkIfInstanceAlreadyExist(any())).thenReturn(false);
85+
when(utils.getInstances()).thenReturn(new JsonArray());
86+
mockMvc.perform(MockMvcRequestBuilders.post("/add-instances")
87+
.accept(MediaType.APPLICATION_JSON_VALUE)
88+
.content(instance.toString()))
89+
.andExpect(status().isOk())
90+
.andReturn();
91+
}
92+
93+
@Test
94+
public void testAddInstanceIfAlreadyExists() throws Exception {
95+
when(utils.checkIfInstanceAlreadyExist(any())).thenReturn(true);
96+
mockMvc.perform(MockMvcRequestBuilders.post("/add-instances")
97+
.accept(MediaType.APPLICATION_JSON_VALUE)
98+
.content(instance.toString()))
99+
.andExpect(status().isBadRequest())
100+
.andExpect(content().string("Instance already exist"))
101+
.andReturn();
102+
}
103+
104+
@Test
105+
public void testSwitchInstance() throws Exception {
106+
when(utils.getInformation()).thenReturn(information);
107+
mockMvc.perform(MockMvcRequestBuilders.post("/switch-backend")
108+
.accept(MediaType.APPLICATION_JSON_VALUE)
109+
.content(instances.toString()))
110+
.andExpect(status().isOk())
111+
.andReturn();
112+
}
113+
114+
@Test
115+
public void testDeleteInstance() throws Exception {
116+
mockMvc.perform(MockMvcRequestBuilders.delete("/switch-backend")
117+
.accept(MediaType.APPLICATION_JSON_VALUE)
118+
.content(instances.toString()))
119+
.andExpect(status().isOk())
120+
.andReturn();
121+
}
122+
123+
@Test
124+
public void testSwitchBackEndInstanceByMainPage() throws Exception {
125+
when(utils.getInformation()).thenReturn(information);
126+
mockMvc.perform(MockMvcRequestBuilders.post("/switch-backendByMainPage")
127+
.accept(MediaType.APPLICATION_JSON_VALUE)
128+
.content("otherName"))
129+
.andExpect(status().isOk())
130+
.andReturn();
131+
}
132+
133+
134+
135+
}

0 commit comments

Comments
 (0)