summaryrefslogtreecommitdiffstats
path: root/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java
blob: 742382155ab29856fe14d4f8e54e1c35dad1327d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.be.servlets;

import com.fasterxml.jackson.databind.DeserializationFeature;
import fj.data.Either;
import org.assertj.core.api.AssertionsForClassTypes;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.openecomp.sdc.be.components.impl.GroupBusinessLogicNew;
import org.openecomp.sdc.be.components.validation.AccessValidations;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
import org.openecomp.sdc.be.model.operations.StorageException;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.anyList;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.openecomp.sdc.be.model.operations.api.StorageOperationStatus.NOT_FOUND;

public class GroupEndpointTest extends JerseySpringBaseTest {

    private static final String VALID_USER = "ab001";
    private static final String INVALID_USER = "ab002";
    private static final String VALID_COMPONENT_ID = "12345";
    private static final String INVALID_COMPONENT_ID = "9999";
    private static final String VALID_GROUP_ID = "1";
    private static final String INVALID_GROUP_ID = "2";
    public static final String A = "a";
    private static final String VL1 = "VL1";
    private static final String OLD_VALUE = "old value";
    private static AccessValidations accessValidations;
    private static ComponentValidations componentValidations;
    private static GroupsOperation groupsOperation;
    private static GroupOperation groupOperation;
    private Resource cr;
    private GroupDefinition g1;
    private ComponentInstance ci;
    private GroupProperty gp1;

    @Configuration
    @Import(BaseTestConfig.class)
    static class GroupEndpointTestConfig {

        @Bean
        GroupEndpoint groupEndpoint() {
            UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class);
            ComponentsUtils componentsUtils = mock(ComponentsUtils.class);

            return new GroupEndpoint(userBusinessLogic, componentsUtils, groupBusinessLogic());
        }

        @Bean
        GroupBusinessLogicNew groupBusinessLogic() {
            return new GroupBusinessLogicNew(accessValidations, componentValidations, groupsOperation, groupOperation);
        }
    }

    @BeforeClass
    public static void initClass() {
        ExternalConfiguration.setAppName("catalog-be");
        String appConfigDir = "src/test/resources/config/catalog-be";
        ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
        ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
        //ComponentsUtils needs configuration singleton to be set
        componentValidations = mock(ComponentValidations.class);
        accessValidations = mock(AccessValidations.class);
        groupsOperation = mock(GroupsOperation.class);
        groupOperation = mock(GroupOperation.class);

    }

    @Override
    protected void configureClient(ClientConfig config) {
        final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        config.register(jacksonJsonProvider);
    }

    @Override
    protected ResourceConfig configure() {
        return super.configure(GroupEndpointTestConfig.class)
                .register(GroupEndpoint.class)
                .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, "WARNING");
    }

    @Before
    public void init() {
        cr = new Resource();
        cr.setSystemName("CR1");
        g1 = new GroupDefinition();
        g1.setUniqueId(VALID_GROUP_ID);
        gp1 = new GroupProperty();
        gp1.setUniqueId("1");
        gp1.setName("p1");
        gp1.setValue(OLD_VALUE);
        g1.setProperties(Arrays.asList(gp1));
        cr.setGroups(Arrays.asList(g1));
        ci = new ComponentInstance();
        ci.setUniqueId(A);
        ci.setName(VL1);
        happyScenarioSetup();
        unhappyScenarioSetup();
    }

    private void unhappyScenarioSetup() {
        when(accessValidations.validateUserCanWorkOnComponent(eq(INVALID_COMPONENT_ID), eq(ComponentTypeEnum.RESOURCE), eq(VALID_USER), anyString())).thenThrow(new StorageException(NOT_FOUND, INVALID_COMPONENT_ID));
        when(componentValidations.getComponentInstance(cr, A)).thenReturn(Optional.of(ci));
    }


    private void happyScenarioSetup() {
        when(accessValidations.validateUserCanWorkOnComponent(eq(VALID_COMPONENT_ID), any(ComponentTypeEnum.class), eq(VALID_USER), anyString())).thenReturn(cr);
        when(accessValidations.validateUserCanRetrieveComponentData(eq(VALID_COMPONENT_ID), eq("resources"), eq(VALID_USER), anyString()))
                .thenReturn(cr);
        when(componentValidations.getComponentInstance(cr, A)).thenReturn(Optional.of(ci));
        doNothing().when(groupsOperation).updateGroupOnComponent(eq(VALID_COMPONENT_ID), isA(GroupDefinition.class), any(PromoteVersionEnum.class));
        when(groupOperation.validateAndUpdatePropertyValue(isA(GroupProperty.class))).thenReturn(StorageOperationStatus.OK);
        when(groupsOperation.updateGroupPropertiesOnComponent(eq(VALID_COMPONENT_ID), isA(GroupDefinition.class), anyList(), any(PromoteVersionEnum.class))).thenAnswer(new Answer<Either>() {
            @Override
            public Either answer(InvocationOnMock invocationOnMock) throws Throwable {
                Object[] args = invocationOnMock.getArguments();
                return Either.left(Arrays.asList(args[2]));
            }
        });
    }

    @Test
    public void updateGroupMembers_success() {
        List<String> ids = Arrays.asList(A);
        List<String> updatedIds = buildUpdateGroupMembersCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
                .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
                });
        assertThat(updatedIds.size()).isEqualTo(ids.size());
        assertThat(updatedIds).containsExactlyInAnyOrder(ids.toArray(new String[ids.size()]));
    }

    @Test
    public void updateGroupMembersWith2IdenticalMembers_success() {
        List<String> ids = Arrays.asList(A, A);
        List<String> updatedIds = buildUpdateGroupMembersCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
                .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
                });
        assertThat(updatedIds.size()).isEqualTo(1);
        assertThat(updatedIds).containsExactlyInAnyOrder(String.valueOf(A));
    }

    @Test
    public void updateGroupMembersWithEmptyList_success() {
        List<String> ids = new ArrayList<>();
        List<String> updatedIds = buildUpdateGroupMembersCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
                .post(Entity.entity(ids, MediaType.APPLICATION_JSON), new GenericType<List<String>>() {
                });
        assertThat(updatedIds.size()).isEqualTo(0);
    }

    @Test
    public void updateGroupMember_InvalidComponentId_failure() {
        List<String> ids = new ArrayList<>();
        Response response = buildUpdateGroupMembersCall(INVALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
                .post(Entity.entity(ids, MediaType.APPLICATION_JSON), Response.class);
        AssertionsForClassTypes.assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
    }

    @Test
    public void updateGroupProperty_success() {
        GroupProperty property = new GroupProperty();
        property.setValue("value1");
        property.setName("prop");
        String propertyStr = "[{\"uniqueId\":\"1\",\"type\":null,\"required\":false,\"definition\":false,\"defaultValue\":null,\"description\":null,\"schema\":null,\"password\":false,\"name\":\"p1\",\"value\":\"new value\",\"label\":null,\"hidden\":false,\"immutable\":false,\"inputPath\":null,\"status\":null,\"inputId\":null,\"instanceUniqueId\":null,\"propertyId\":null,\"parentUniqueId\":null,\"getInputValues\":null,\"constraints\":null,\"valueUniqueUid\":null,\"ownerId\":null}]";
        List<GroupProperty> properties = Arrays.asList(property);
        //TODO define GroupPropertyDTO (after finding other usage in UI code) and improve test coverage
//        List<GroupProperty> updatedProperties = buildUpdateGroupPropertiesCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
//                .put(Entity.entity(propertyStr, MediaType.APPLICATION_JSON), new GenericType<List<GroupProperty>>() {
//                });
//        assertThat(updatedProperties.size()).isEqualTo(1);
        Response response = buildUpdateGroupPropertiesCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
                .put(Entity.entity(propertyStr, MediaType.APPLICATION_JSON));
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    }

    @Test
    public void getGroupProperties_success() {
        List<PropertyDataDefinition> properties = buildUpdateGroupPropertiesCall(VALID_COMPONENT_ID, VALID_GROUP_ID, VALID_USER)
                .get(new GenericType<List<PropertyDataDefinition>>(){});
        assertThat(properties.size()).isEqualTo(1);
        assertThat(properties.get(0).getValue()).isEqualTo(OLD_VALUE);
    }

    private Invocation.Builder buildUpdateGroupMembersCall(String componentId, String groupId, String userId) {
        return target("/v1/catalog/resources/" + componentId + "/groups/" + groupId + "/members")
                .request(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header(Constants.USER_ID_HEADER, userId);
    }

    private Invocation.Builder buildUpdateGroupPropertiesCall(String componentId, String groupId, String userId) {
        return target("/v1/catalog/resources/" + componentId + "/groups/" + groupId + "/properties")
                .request(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header(Constants.USER_ID_HEADER, userId);
    }
	

}