[SDC-29] rebase continue work to align source
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / externalApis / SearchFilterCategoryExternalAPI.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.openecomp.sdc.externalApis;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Random;
29
30 import org.json.simple.parser.JSONParser;
31 import org.junit.Rule;
32 import org.junit.rules.TestName;
33 import org.openecomp.sdc.be.dao.api.ActionStatus;
34 import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
35 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
36 import org.openecomp.sdc.be.model.Resource;
37 import org.openecomp.sdc.be.model.category.CategoryDefinition;
38 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
39 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
40 import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
41 import org.openecomp.sdc.ci.tests.config.Config;
42 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
43 import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
44 import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
45 import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
46 import org.openecomp.sdc.ci.tests.datatypes.enums.SearchCriteriaEnum;
47 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
48 import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
49 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
50 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
51 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
52 import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
53 import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
54 import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
55 import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
56 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.testng.Assert;
60 import org.testng.annotations.DataProvider;
61 import org.testng.annotations.Test;
62
63 import com.google.gson.Gson;
64 import com.google.gson.JsonArray;
65 import com.google.gson.JsonElement;
66 import com.google.gson.JsonParser;
67
68 public class SearchFilterCategoryExternalAPI extends ComponentBaseTest {
69
70         private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName());
71
72         protected Config config = Config.instance();
73         protected String contentTypeHeaderData = "application/json";
74         protected String acceptHeaderDate = "application/json";
75
76         protected Gson gson = new Gson();
77         protected JSONParser jsonParser = new JSONParser();
78
79 //      @BeforeMethod
80 //      public void init() throws Exception{
81 //              AtomicOperationUtils.createDefaultConsumer(true);
82 //      }
83         
84         ;
85         @Rule 
86         public static TestName name = new TestName();
87
88         public SearchFilterCategoryExternalAPI() {
89                 super(name, SearchFilterCategoryExternalAPI.class.getName());
90
91         }
92         
93         // Search for invalid resourceType
94         @Test
95         public void searchWithInvalidFilter() throws Exception {
96                 RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "invalid", ResourceTypeEnum.VFC.toString());
97                 
98                 Integer expectedResponseCode = 400;
99                 Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode);
100                 
101                 List<String> variables = Arrays.asList("resourceTypeinvalid", "[resourceType, subCategory, category]");
102                 ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FILTER_KEY.name(), variables, restResponse.getResponse());
103
104                 ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "invalid=" + ResourceTypeEnum.VFC.toString());
105                 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FILTER_KEY.name());
106                 expectedExternalAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
107                 expectedExternalAudit.setSTATUS("400");
108                 Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
109                 body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
110                 AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
111         }
112         
113         @DataProvider(name="searchForResourceTypeNegativeTest", parallel=true) 
114         public static Object[][] dataProviderSearchForResourceTypeNegativeTest() {
115                 return new Object[][] {
116                         {"invalidResourceType"},
117                         {""}
118                         };
119         }
120         
121         // Search for invalid resourceType
122         @Test(dataProvider="searchForResourceTypeNegativeTest")
123         public void searchForResourceTypeNegativeTest(String resourceType) throws Exception {
124                 RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), resourceType);
125                 
126                 Integer expectedResponseCode = 400;
127                 Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode);
128                 
129                 List<String> variables = Arrays.asList();
130                 ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, restResponse.getResponse());
131
132                 ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceType);
133                 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
134                 expectedExternalAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
135                 expectedExternalAudit.setSTATUS("400");
136                 Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
137                 body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
138                 AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
139         }
140         
141         // Searching for resource filter incorrect resource type using external API
142         @Test
143         public void searchingForResouceFilterIncorrectResouceTypeUsingExternalAPI() throws Exception {
144                 Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value();
145                 List<String> createdResoucesName = new ArrayList<String>();
146                 createdResoucesName.add(resource.getName());
147                 
148                 for(ResourceTypeEnum resourceTypeEnum: ResourceTypeEnum.values()) {
149                         // Create resource for each type so it will not return 404
150                         AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(resourceTypeEnum, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value();
151
152                         RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), resourceTypeEnum.toString());
153                         
154                         Integer expectedResponseCode = 200;
155                         Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode);
156                         if(resourceTypeEnum == ResourceTypeEnum.VF) {
157                                 validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true);
158                         } else {
159                                 validateJsonContainResource(restResponse.getResponse(), createdResoucesName, false);
160                         }
161                         
162                         
163                         ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceTypeEnum.toString());
164                         Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
165                         body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
166                         AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
167                 }
168         }
169         
170         // Searching for several resource types using external API
171         @Test
172         public void searchingForSeveralResouceTypesUsingExternalAPI() throws Exception {
173                 performClean();
174                 for(ResourceTypeEnum resourceTypeEnum: ResourceTypeEnum.values()) {
175                         List<String> createdResoucesName = new ArrayList<String>();
176                         Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(resourceTypeEnum, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value();
177                         createdResoucesName.add(resource.getName());
178                         
179                         RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), resourceTypeEnum.toString());
180                         
181                         Integer expectedResponseCode = 200;
182                         Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode);
183                         validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true);
184                         
185                         ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceTypeEnum.toString());
186                         Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
187                         body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
188                         AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
189                 }
190         }
191         
192         // Searching for several resources of type VFCMT using external API
193         @Test
194         public void searchingForSeveralResourcesOfTypeVFCMTUsingExternalAPI() throws Exception {
195                 performClean();
196                 Random random = new Random();
197                 int numberOfResouceToCreate = random.nextInt(5) + 1;    
198                 List<String> createdResoucesName = new ArrayList<String>();
199                 
200                 for(int i=0; i<numberOfResouceToCreate; i++) {
201                         
202                         Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFCMT, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value();
203                         createdResoucesName.add(resource.getName());
204                 }
205                 
206                 RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), ResourceTypeEnum.VFCMT.toString());
207                 
208                 Integer expectedResponseCode = 200;
209                 Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode);
210                 validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true);
211                 
212                 ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + ResourceTypeEnum.VFCMT.toString());
213                 AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
214         }
215         
216         
217         
218         @DataProvider(name="normativeResourceCategory", parallel=true) 
219         public static Object[][] dataProviderNormativeResourceCategory() {
220                 return new Object[][] {
221                         {ResourceCategoryEnum.ALLOTTED_RESOURCE},
222                         {ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE},
223                         };
224         }
225         
226         // Verify exist of normative resource category from data provider
227         @Test(dataProvider="normativeResourceCategory")
228         public void normativeResourceCategory(ResourceCategoryEnum resourceCategoryEnum) throws Exception {
229                 RestResponse restResponse = CategoryRestUtils.getAllCategories(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "resources");
230                 validateJsonContainResourceCategory(restResponse.getResponse(), resourceCategoryEnum);
231                 
232                 Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, resourceCategoryEnum, UserRoleEnum.DESIGNER, true).left().value();
233                 List<String> createdResoucesName = new ArrayList<String>();
234                 createdResoucesName.add(resource.getName());
235                 
236                 restResponse = ResourceRestUtils.getResourceListFilterByCategory(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), resourceCategoryEnum.getCategory());
237                 
238                 Integer expectedResponseCode = 200;
239                 Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode);
240                 validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true);
241         }
242         
243         // Verify search filter by sub-category
244         @Test
245         public void validateFilterBySubcategory() throws Exception {
246                 ResourceCategoryEnum resourceCategoryEnum = getRandomCategoryFromResourceCategoryEnum();
247                 
248                 Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, resourceCategoryEnum, UserRoleEnum.DESIGNER, true).left().value();
249                 List<String> createdResoucesName = new ArrayList<String>();
250                 createdResoucesName.add(resource.getName());
251                 
252                 RestResponse restResponse = ResourceRestUtils.getResourceListFilterBySubCategory(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), resourceCategoryEnum.getSubCategory());
253                 
254                 Integer expectedResponseCode = 200;
255                 Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode);
256                 validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true);
257         }
258         
259         
260         protected ResourceCategoryEnum getRandomCategoryFromResourceCategoryEnum() throws Exception {
261                 Random random = new Random();
262                 int randint = random.nextInt(ResourceCategoryEnum.values().length);
263                 int i = 0;
264                 for(ResourceCategoryEnum resourceTypeEnum: ResourceCategoryEnum.values()) {
265                         if(randint == i) {
266                                 return resourceTypeEnum;
267                         }
268                         i++;
269                 }
270                 return null;
271         }
272         
273         protected CategoryDefinition getRandomCategory() throws Exception {
274                 Random random = new Random();
275                 
276                 RestResponse restResponse = CategoryRestUtils.getAllCategories(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "resources");
277                 Gson gson = new Gson();
278                 JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
279                 JsonArray jsonArray = jelement.getAsJsonArray();
280                 
281                 CategoryDefinition categoryDefinition = gson.fromJson(jsonArray.get(random.nextInt(jsonArray.size())), CategoryDefinition.class);
282                 
283                 return categoryDefinition;
284         }
285         
286         protected void validateJsonContainResource(String json, List<String> resourceNameList, Boolean willBeFound) {
287                 int lenResourceNameList = resourceNameList.size();
288                 Gson gson = new Gson();
289                 JsonElement jsonElement = new JsonParser().parse(json);
290                 JsonArray jsonArray = jsonElement.getAsJsonArray();
291                 for(JsonElement jElement: jsonArray) {
292                         ResourceReqDetails jResource = gson.fromJson(jElement, ResourceReqDetails.class);
293                         
294                         if(resourceNameList.contains(jResource.getName())) {
295                                 resourceNameList.remove(jResource.getName());
296                         }
297                 }
298                 
299                 if(resourceNameList.size() != 0 && willBeFound) {                       
300                         Assert.assertTrue(false, "Created resource not found on search filtered by category.");
301                 } else if (lenResourceNameList != resourceNameList.size() & !willBeFound) {
302                         Assert.assertTrue(false, "Some of the resources found when expect that no resource will be found.");
303                 }
304         }
305         
306         
307         
308         protected void validateJsonContainResourceCategory(String json, ResourceCategoryEnum resourceCategoryEnum) {
309                 Gson gson = new Gson();
310                 JsonElement jelement = new JsonParser().parse(json);
311                 JsonArray jsonArray = jelement.getAsJsonArray();
312                 for(JsonElement jsonElement : jsonArray){
313                         CategoryDefinition categoryDefinition = gson.fromJson(jsonElement, CategoryDefinition.class);
314                         
315                         if(categoryDefinition.getName().equals(resourceCategoryEnum.getCategory())) { 
316                                 for(SubCategoryDefinition subcategory: categoryDefinition.getSubcategories()) {
317                                         if(subcategory.getName().equals(resourceCategoryEnum.getSubCategory())) {
318                                                 return;
319                                         }
320                                 }
321                         }
322                         
323                 }
324                 
325                 Assert.assertTrue(false, "Category and subcategory not found in categories list.");
326         }
327
328         
329 }