UI Exensibility config cleanup
[aai/sparky-be.git] / src / test / java / org / onap / aai / sparky / security / portal / TestUserManager.java
1 /**
2  * ============LICENSE_START===================================================
3  * SPARKY (AAI UI service)
4  * ============================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=====================================================
21  *
22  * ECOMP and OpenECOMP are trademarks
23  * and service marks of AT&T Intellectual Property.
24  */
25
26 package org.onap.aai.sparky.security.portal;
27
28 import static org.hamcrest.Matchers.empty;
29 import static org.hamcrest.Matchers.is;
30 import static org.junit.Assert.assertThat;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.nio.file.Files;
35 import java.nio.file.Paths;
36 import java.util.Arrays;
37 import java.util.List;
38 import java.util.concurrent.Callable;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.Executors;
41 import java.util.stream.Collectors;
42
43 import org.junit.After;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 import org.onap.aai.sparky.security.portal.UserManager;
50 import org.onap.aai.sparky.util.NodeUtils;
51 import org.openecomp.portalsdk.core.restful.domain.EcompUser;
52 import org.powermock.modules.junit4.PowerMockRunner;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 import com.google.gson.Gson;
57
58 @RunWith(PowerMockRunner.class)
59 // @PrepareForTest(RolesConfig.class)
60 public class TestUserManager {
61
62   private static final String LOGINID_3 = "3";
63   private static File noFile;
64   private static File concurrentUsers;
65   private static File concurrentEditUsers;
66
67   private static final Gson GSON = new Gson();
68   private static final String LOGINID_1 = "1";
69   private static final String LOGINID_2 = "2";
70
71   private static Logger logger = LoggerFactory.getLogger(TestUserManager.class);
72
73   enum TestData {
74     // @formatter:off
75     NO_FILE               ("src/test/resources/portal/no-users.config"),
76     CONCURRENT_USERS      ("src/test/resources/portal/concurrent-users.config"),
77     CONCURRENT_EDIT_USERS ("src/test/resources/portal/concurrent-edit-users.config");
78 //    ROLES_CONFIG_FILE     ("src/test/resources/portal/roles.config");
79
80     private String filename;
81     TestData(String filename) {this.filename = filename;}
82     public String getFilename() {return this.filename;}
83     // @formatter:on
84   }
85
86   @BeforeClass
87   public static void setUpBeforeClass() throws Exception {
88     noFile = Paths.get(TestData.NO_FILE.getFilename()).toFile();
89     concurrentUsers = Paths.get(TestData.CONCURRENT_USERS.getFilename()).toFile();
90     concurrentEditUsers = Paths.get(TestData.CONCURRENT_EDIT_USERS.getFilename()).toFile();
91   }
92
93   @AfterClass
94   public static void tearDownAfterClass() throws Exception {
95     Files.deleteIfExists(concurrentUsers.toPath());
96     Files.deleteIfExists(concurrentEditUsers.toPath());
97   }
98
99   @Before
100   public void setUp() throws Exception {
101     EcompUser user1 = new EcompUser();
102     user1.setLoginId(LOGINID_1);
103
104     EcompUser user2 = new EcompUser();
105     user2.setLoginId(LOGINID_2);
106
107     List<EcompUser> users = Arrays.asList(user1, user2);
108     Files.write(concurrentEditUsers.toPath(), GSON.toJson(users).getBytes());
109
110     // Whitebox.setInternalState(RolesConfig.class, "ROLES_CONFIG_FILE",
111     // TestData.ROLES_CONFIG_FILE.getFilename());
112   }
113
114   @After
115   public void tearDown() throws Exception {
116     Files.deleteIfExists(concurrentUsers.toPath());
117     Files.deleteIfExists(concurrentEditUsers.toPath());
118   }
119
120   @Test
121   public void testGetUsersNoFile() throws Exception {
122     UserManager userManager = new UserManager(noFile);
123     List<EcompUser> users = userManager.getUsers();
124
125     assertThat(users, empty());
126   }
127
128   @Test
129   public void testConcurrentPush() throws Exception {
130     Callable<EcompUser> pushTask = () -> {
131       return pushTask(concurrentUsers, String.valueOf(NodeUtils.getRandomTxnId()));
132     };
133
134     List<Callable<EcompUser>> callables = Arrays.asList(pushTask, pushTask, pushTask, pushTask,
135         pushTask);
136
137     ExecutorService executor = Executors.newWorkStealingPool();
138     executor.invokeAll(callables).stream().map(future -> {
139       try {
140         return future.get();
141       } catch (Exception e) {
142         throw new IllegalStateException(e);
143       }
144     });
145
146     UserManager userManager = new UserManager(concurrentUsers);
147     assertThat(userManager.getUsers().size(), is(5));
148   }
149
150   /**
151    * Concurrent push/edit with sequential retry on failure.
152    *
153    * @throws Exception
154    */
155   @Test
156   public void testConcurrentPushAndEdit() throws Exception {
157     Callable<EcompUser> pushTaskRandomId = () -> {
158       return pushTask(concurrentEditUsers, String.valueOf(NodeUtils.getRandomTxnId()));
159     };
160
161     Callable<EcompUser> pushTaskId3 = () -> {
162       return pushTask(concurrentEditUsers, LOGINID_3);
163     };
164
165     Callable<EcompUser> editTaskId1 = () -> {
166       return editTask(LOGINID_1, "Bob");
167     };
168
169     Callable<EcompUser> editTaskId2 = () -> {
170       return editTask(LOGINID_2, "Jen");
171     };
172
173     Callable<EcompUser> editTaskId3 = () -> {
174       return editTask(LOGINID_3, "Amy");
175     };
176
177     List<Callable<EcompUser>> callables = Arrays.asList(pushTaskRandomId, pushTaskRandomId,
178         pushTaskId3, editTaskId1, pushTaskRandomId, pushTaskRandomId, editTaskId3, editTaskId2,
179         pushTaskRandomId);
180
181     ExecutorService executor = Executors.newWorkStealingPool();
182     List<EcompUser> userTasks = executor.invokeAll(callables).stream().map(future -> {
183       try {
184         return future.get();
185       } catch (Exception e) {
186         throw new IllegalStateException(e);
187       }
188     }).collect(Collectors.toList());
189
190     assertThat(userTasks.size(), is(9));
191
192     assertUserPushEdit(concurrentEditUsers);
193   }
194
195   /**
196    * Retry push/edit if assert fails following concurrent attempt.
197    *
198    * @param userFile
199    * @throws Exception
200    */
201   private void assertUserPushEdit(File userFile) throws Exception {
202     UserManager userManager = new UserManager(userFile);
203     try {
204       assertThat(userManager.getUsers().size(), is(8));
205     } catch (Throwable t) {
206       int size = userManager.getUsers().size();
207       logger.error("Failed to push all users. Only created: " + size + " users. " + t.getMessage());
208       pushTask(concurrentEditUsers, String.valueOf(NodeUtils.getRandomTxnId()));
209       assertThat(userManager.getUsers().size(), is(size + 1));
210     }
211
212     try {
213       assertThat(userManager.getUser(LOGINID_1).get().getFirstName(), is("Bob"));
214     } catch (Throwable t) {
215       logger.error("Failed to edit user. " + t.getMessage());
216       retryEdit(userManager, LOGINID_1, "Bob");
217     }
218
219     try {
220       assertThat(userManager.getUser(LOGINID_2).get().getFirstName(), is("Jen"));
221     } catch (Throwable t) {
222       logger.error("Failed to edit user. " + t.getMessage());
223       retryEdit(userManager, LOGINID_2, "Jen");
224     }
225
226     try {
227       assertThat(userManager.getUser(LOGINID_3).isPresent(), is(true));
228     } catch (Throwable t) {
229       logger.error("Failed to push user. " + t.getMessage());
230       pushTask(concurrentEditUsers, LOGINID_3);
231       assertThat(userManager.getUser(LOGINID_3).isPresent(), is(true));
232     }
233
234     try {
235       assertThat(userManager.getUser(LOGINID_3).get().getFirstName(), is("Amy"));
236     } catch (Throwable t) {
237       logger.error("Failed to edit user. " + t.getMessage());
238       retryEdit(userManager, LOGINID_3, "Amy");
239     }
240   }
241
242   private void retryEdit(UserManager userManager, String loginId, String firstName)
243       throws IOException {
244     editTask(loginId, firstName);
245     assertThat(userManager.getUser(loginId).get().getFirstName(), is(firstName));
246   }
247
248   private EcompUser pushTask(File fileStore, String loginId) throws IOException {
249     UserManager userManager = new UserManager(fileStore);
250     EcompUser user = new EcompUser();
251     user.setLoginId(loginId);
252     userManager.pushUser(user);
253     return user;
254   }
255
256   private EcompUser editTask(String loginId, String firstName) throws IOException {
257     UserManager userManager = new UserManager(concurrentEditUsers);
258     EcompUser user = new EcompUser();
259     user.setLoginId(loginId);
260     user.setFirstName(firstName);
261     userManager.editUser(loginId, user);
262     return user;
263   }
264
265 }