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