Merge "create unit test for shouldShowUpgrade function"
[vid.git] / vid-app-common / src / test / java / org / onap / vid / roles / RoleProviderTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.roles;
22
23
24 import static java.util.Collections.emptyMap;
25 import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.when;
29 import static org.mockito.MockitoAnnotations.initMocks;
30
31 import com.fasterxml.jackson.core.JsonProcessingException;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import com.google.common.collect.ImmutableMap;
34 import java.util.List;
35 import java.util.Map;
36 import javax.servlet.http.HttpServletRequest;
37 import org.assertj.core.util.Lists;
38 import org.mockito.Mock;
39 import org.onap.vid.aai.AaiResponse;
40 import org.onap.vid.aai.exceptions.RoleParsingException;
41 import org.onap.vid.category.CategoryParametersResponse;
42 import org.onap.vid.model.CategoryParameter.Family;
43 import org.onap.vid.model.Subscriber;
44 import org.onap.vid.model.SubscriberList;
45 import org.onap.vid.services.AaiService;
46 import org.onap.vid.services.CategoryParameterService;
47 import org.testng.Assert;
48 import org.testng.annotations.BeforeMethod;
49 import org.testng.annotations.DataProvider;
50 import org.testng.annotations.Test;
51
52 public class RoleProviderTest {
53
54     private static final String SAMPLE_SUBSCRIBER = "sampleSubscriber";
55     private static final String SAMPLE_SUBSCRIBER_ID = "subscriberId";
56     private static final String SERVICE_TYPE_LOGS = "LOGS";
57     private static final String TENANT_PERMITTED = "PERMITTED";
58     private static final String SAMPLE_SERVICE = "sampleService";
59     private static final String SAMPLE_TENANT = "sampleTenant";
60     private static final String SAMPLE_ROLE_PREFIX = "prefix";
61     private static final String EXISTING_OWNING_ENTITY_NAME = "WayneHolland";
62     private static final String EXISTING_OWNING_ENTITY_ID = "d61e6f2d-12fa-4cc2-91df-7c244011d6fc";
63     private static final String NOT_EXISTING_OWNING_ENTITY_NAME = "notExistingOwningEntity";
64
65     @Mock
66     private AaiService aaiService;
67
68     @Mock
69     private HttpServletRequest request;
70
71     @Mock
72     private AaiResponse<SubscriberList> subscriberListResponse;
73
74     @Mock
75     private RoleValidatorFactory roleValidatorFactory;
76
77     @Mock
78     private CategoryParameterService categoryParameterService;
79
80     private RoleProvider roleProvider;
81
82
83     @BeforeMethod
84     public void setUp() {
85         initMocks(this);
86         roleProvider = new RoleProvider(aaiService, roleValidatorFactory, httpServletRequest -> 5,
87             httpServletRequest -> createRoles(),
88             categoryParameterService);
89
90         when(categoryParameterService.getCategoryParameters(any()))
91             .thenReturn(new CategoryParametersResponse(emptyMap()));
92     }
93
94     @Test
95     public void shouldSplitRolesWhenDelimiterIsPresent() {
96         String roles = "role_a___role_b";
97
98         assertThat(roleProvider.splitRole(roles, "")).isEqualTo(new String[]{"role_a", "role_b"});
99     }
100
101
102     @Test
103     public void shouldProperlyCreateRoleFromCorrectArray() throws RoleParsingException {
104         setSubscribers();
105         String[] roleParts = {SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT};
106
107         Role role = roleProvider.createRoleFromStringArr(roleParts, SAMPLE_ROLE_PREFIX, emptyMap());
108
109         assertThat(role.getEcompRole()).isEqualTo(EcompRole.READ);
110         assertThat(role.getSubscriberId()).isEqualTo(SAMPLE_SUBSCRIBER_ID);
111         assertThat(role.getTenant()).isEqualTo(SAMPLE_TENANT);
112         assertThat(role.getServiceType()).isEqualTo(SAMPLE_SERVICE);
113     }
114
115     @Test
116     public void shouldProperlyCreateRoleWhenTenantIsNotProvided() throws RoleParsingException {
117         setSubscribers();
118
119         String[] roleParts = {SAMPLE_SUBSCRIBER, SAMPLE_SERVICE};
120
121         Role role = roleProvider.createRoleFromStringArr(roleParts, SAMPLE_ROLE_PREFIX, emptyMap());
122
123         assertThat(role.getEcompRole()).isEqualTo(EcompRole.READ);
124         assertThat(role.getSubscriberId()).isEqualTo(SAMPLE_SUBSCRIBER_ID);
125         assertThat(role.getServiceType()).isEqualTo(SAMPLE_SERVICE);
126         assertThat(role.getTenant()).isNullOrEmpty();
127     }
128
129     @Test(expectedExceptions = RoleParsingException.class)
130     public void shouldRaiseExceptionWhenRolePartsAreIncomplete() throws RoleParsingException {
131         setSubscribers();
132
133         roleProvider.createRoleFromStringArr(new String[]{SAMPLE_SUBSCRIBER}, SAMPLE_ROLE_PREFIX, emptyMap());
134     }
135
136     @Test
137     public void shouldProperlyRetrieveUserRolesWhenPermissionIsDifferentThanRead() {
138         Role expectedRole = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER_ID, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId());
139         setSubscribers();
140
141         List<Role> userRoles = roleProvider.getUserRoles(request);
142
143
144         assertThat(userRoles.size()).isEqualTo(1);
145         Role actualRole = userRoles.get(0);
146
147         assertThat(actualRole.getTenant()).isEqualTo(expectedRole.getTenant());
148         assertThat(actualRole.getSubscriberId()).isEqualTo(expectedRole.getSubscriberId());
149         assertThat(actualRole.getServiceType()).isEqualTo(expectedRole.getServiceType());
150     }
151
152     @Test
153     public void shouldReturnReadOnlyPermissionWhenRolesAreEmpty() {
154         assertThat(roleProvider.userPermissionIsReadOnly(Lists.emptyList())).isTrue();
155     }
156
157     @Test
158     public void shouldReturnNotReadOnlyPermissionWhenRolesArePresent() {
159         assertThat(roleProvider.userPermissionIsReadOnly(Lists.list(new Role(
160             EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId())))).isFalse();
161     }
162
163     @Test
164     public void userShouldHavePermissionToReadLogsWhenServiceAndTenantAreCorrect() {
165         Role withoutPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId());
166         Role withPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SERVICE_TYPE_LOGS, TENANT_PERMITTED, owningEntityId());
167
168         assertThat(roleProvider.userPermissionIsReadLogs(Lists.list(withoutPermission, withPermission))).isTrue();
169     }
170
171     @Test
172     public void getUserRolesValidator_shouldReturnValidatorFromFactory() {
173         RoleValidator expectedRoleValidator = new AlwaysValidRoleValidator();
174         when(roleValidatorFactory.by(any())).thenReturn(expectedRoleValidator);
175
176         RoleValidator result = roleProvider.getUserRolesValidator(request);
177
178         assertThat(result).isEqualTo(expectedRoleValidator);
179     }
180
181     @DataProvider
182     public static Object[][] owningEntityNameAndId() {
183         return new Object[][] {
184             {"owning entity name exist on the response, id is returned ", EXISTING_OWNING_ENTITY_NAME, EXISTING_OWNING_ENTITY_ID},
185             {"owning entity name dont exist on the response, name is returned", NOT_EXISTING_OWNING_ENTITY_NAME, NOT_EXISTING_OWNING_ENTITY_NAME},
186         };
187     }
188
189     @Test(dataProvider = "owningEntityNameAndId")
190     public void translateOwningEntityNameToOwningEntityId_shouldTranslateNameToId(String description,
191         String owningEntityName, String expectedId) {
192         String owningEntityId = roleProvider.translateOwningEntityNameToOwningEntityId(owningEntityName,
193             ImmutableMap.of(
194                 EXISTING_OWNING_ENTITY_NAME, EXISTING_OWNING_ENTITY_ID,
195                 "anyName", "anyId"
196             ));
197
198         Assert.assertEquals(owningEntityId, expectedId);
199     }
200
201
202
203     private String owningEntityId() {
204         // while translateOwningEntityNameToOwningEntityId does nothing, no translation happens.
205         // this will be changed later.
206         return SAMPLE_SUBSCRIBER;
207     }
208
209     private void setSubscribers() {
210         Subscriber subscriber = new Subscriber();
211         subscriber.subscriberName = SAMPLE_SUBSCRIBER;
212         subscriber.globalCustomerId = SAMPLE_SUBSCRIBER_ID;
213         SubscriberList subscriberList = new SubscriberList(Lists.list(subscriber));
214         when(aaiService.getFullSubscriberList()).thenReturn(subscriberListResponse);
215         when(subscriberListResponse.getT()).thenReturn(subscriberList);
216     }
217
218     private Map<Long, org.onap.portalsdk.core.domain.Role> createRoles() {
219         org.onap.portalsdk.core.domain.Role role1 = new org.onap.portalsdk.core.domain.Role();
220         role1.setName("read___role2");
221         org.onap.portalsdk.core.domain.Role role2 = new org.onap.portalsdk.core.domain.Role();
222         role2.setName("sampleSubscriber___sampleService___sampleTenant");
223         return ImmutableMap.of(1L, role1, 2L, role2);
224     }
225
226     @Test
227     public void owningEntityNameToOwningEntityIdMapper_readsOwningEntityCorrectly() throws JsonProcessingException {
228
229         final String categoryParametersResponse = ""
230             + "{ "
231             + " \"categoryParameters\": { "
232             + " \"lineOfBusiness\": [ "
233             + "      { \"id\": \"ONAP\", \"name\": \"ONAP\" }, "
234             + "      { \"id\": \"zzz1\", \"name\": \"zzz1\" } "
235             + "    ], "
236             + " \"owningEntity\": [ "
237             + "      { \"id\": \"aaa1\", \"name\": \"aaa1\" }, "
238             + "      { \"id\": \"" + EXISTING_OWNING_ENTITY_ID + "\", \"name\": \"" + EXISTING_OWNING_ENTITY_NAME + "\" }, "
239             + "      { \"id\": \"Melissa\", \"name\": \"Melissa\" }     ], "
240             + " \"project\": [ "
241             + "      { \"id\": \"WATKINS\", \"name\": \"WATKINS\" }, "
242             + "      { \"id\": \"x1\", \"name\": \"x1\" }, "
243             + "      { \"id\": \"yyy1\", \"name\": \"yyy1\" } "
244             + "    ], "
245             + " \"platform\": [ "
246             + "      { \"id\": \"platform\", \"name\": \"platform\" }, "
247             + "      { \"id\": \"xxx1\", \"name\": \"xxx1\" } "
248             + "    ] "
249             + "  } "
250             + "}";
251
252         CategoryParametersResponse categoryParameterResponse =
253             new ObjectMapper().readValue(categoryParametersResponse, CategoryParametersResponse.class);
254
255         when(categoryParameterService.getCategoryParameters(Family.PARAMETER_STANDARDIZATION))
256             .thenReturn(categoryParameterResponse);
257
258         org.hamcrest.MatcherAssert.assertThat(roleProvider.owningEntityNameToOwningEntityIdMapper(),
259             jsonEquals(ImmutableMap.of(
260                 "aaa1", "aaa1",
261                 "Melissa", "Melissa",
262                 EXISTING_OWNING_ENTITY_NAME, EXISTING_OWNING_ENTITY_ID
263             )));
264     }
265 }