Added unit tests fo MappingRulesValidator
[sdc/dcae-d/dt-be-main.git] / dcaedt_be / src / test / java / org / onap / sdc / dcae / rule / editor / validators / MappingRulesValidatorTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 Samsung. 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.sdc.dcae.rule.editor.validators;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertTrue;
26
27 import com.google.gson.GsonBuilder;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.junit.runner.RunWith;
40
41 import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ActionDeserializer;
42 import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction;
43 import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCondition;
44 import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ConditionDeserializer;
45 import org.onap.sdc.dcae.composition.restmodels.ruleeditor.MappingRules;
46 import org.onap.sdc.dcae.composition.restmodels.ruleeditor.Rule;
47 import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader;
48 import org.onap.sdc.dcae.errormng.ResponseFormat;
49 import org.onap.sdc.dcae.errormng.ServiceException;
50 import org.onap.sdc.dcae.ves.VesStructureLoader;
51
52 import org.powermock.api.mockito.PowerMockito;
53 import org.powermock.core.classloader.annotations.PrepareForTest;
54 import org.powermock.modules.junit4.PowerMockRunner;
55
56 @RunWith(PowerMockRunner.class)
57 public class MappingRulesValidatorTest {
58
59     private static final MappingRulesValidator validator = MappingRulesValidator.getInstance();
60     private List<ResponseFormat> errors;
61
62     private static final String FORMAT_ERROR_MESSAGE_ID = "SVC6035";
63     private static final String FORMAT_ERROR_TEXT = "Error - Rule format is invalid: %1.";
64     private static final String FORMAT_ERROR_VARIABLE_TEXT = "no rules found";
65
66     private static final String TRANSLATION_ERROR_MESSAGE_ID = "SVC6116";
67     private static final String TRANSLATION_ERROR_TEXT = "Translation failed. Reason: %1";
68     private static final String TRANSLATION_ERROR_ENTRY_VARIABLE_TEXT =
69         "entry phase name already exists";
70     private static final String TRANSLATION_ERROR_PUBLISH_VARIABLE_TEXT =
71         "publish phase name already exists";
72
73     private static final String BAD_RULE_VERSION = "1234";
74     private static final String RULE_VERSION = "4.1";
75     private static final String RULE_EVENT_TYPE = "syslogFields";
76     private static final String RULE_GROUP_ID = "4321";
77     private static final String RULE_PHASE = "test";
78
79     private static final String BASE_JSON =
80         String.format("{version:%s,eventType:%s,notifyId:.1.3.6.1.4.1.26878.200.2}", RULE_VERSION,
81             RULE_EVENT_TYPE);
82
83     private static final String RULE_OBJECT_TEMPLATE =
84         "{version:%s,eventType:%s,notifyId:.1.3.6.1.4.1.26878.200.2,description:newRule,"
85             + "actions:[{from:{state:closed,value:fromField,regex:\"\"},target:event.commonEventHeader.target,id:id,actionType:copy},"
86             + "{actionType:concat,id:id1,from:{state:closed,values:[{value:concat1},{value:_concat2}]},target:concatTargetField},"
87             + "{actionType:copy,id:id2,from:{state:open,value:extractFromHere,regex:\"([^:]*):.*\"},target:regexTargetField}],"
88             + "condition:{id:idc,level:0,name:elvis,left:\"${leftOperand}\",operator:contains,right:[rightOperand1,rightOperand2]},"
89             + "groupId: %s, phase:%s, entryPhase:%s, publishPhase:%s}";
90
91     private static final String RULE_JSON = createRuleJSON(null, null, null, null);
92
93     private static final String RULE_WITH_GROUP_JSON =
94         createRuleJSON(RULE_GROUP_ID, RULE_PHASE, null, null);
95
96     @BeforeClass
97     public static void setup() {
98         new ErrorConfigurationLoader(System.getProperty("user.dir") + "/src/main/webapp/WEB-INF");
99     }
100
101     @Before
102     public void prepare() {
103         errors = new ArrayList<>();
104     }
105
106     @Test
107     public void validateMappingRulesTest() {
108         // given
109         MappingRules mappingRules = createMappingRules();
110         // when - then
111         assertTrue(validator.validate(mappingRules, errors));
112     }
113
114     @Test
115     public void validateMappingRulesWithNoRulesTest() {
116         // given
117         MappingRules mappingRules = createMappingRulesWithoutRules();
118         // when
119         boolean result = validator.validate(mappingRules, errors);
120         ResponseFormat error = errors.get(0);
121         ServiceException exception = error.getRequestError().getServiceException();
122         // then
123         assertFalse(result);
124         assertEquals(400, error.getStatus().intValue());
125         assertEquals(FORMAT_ERROR_MESSAGE_ID, exception.getMessageId());
126         assertEquals(FORMAT_ERROR_TEXT, exception.getText());
127         assertEquals(FORMAT_ERROR_VARIABLE_TEXT, exception.getVariables()[0]);
128     }
129
130     @Test
131     @PrepareForTest(VesStructureLoader.class)
132     public void validateVersionAndTypeTest() {
133         // given
134         MappingRules mappingRules = createMappingRules();
135         // when
136         mockAvailableVersionsAndEventTypes(RULE_VERSION);
137         boolean shouldValidate = validator.validateVersionAndType(mappingRules);
138         mockAvailableVersionsAndEventTypes(BAD_RULE_VERSION);
139         boolean shouldNotValidate = validator.validateVersionAndType(mappingRules);
140         // then
141         assertTrue(shouldValidate);
142         assertFalse(shouldNotValidate);
143     }
144
145     @Test
146     public void validateGroupDefinitionsTest() {
147         // given
148         MappingRules mappingRules = createMappingRules();
149         MappingRules mappingRulesWithGroup = createMappingRulesWithGroup();
150         // then
151         assertFalse(validator.validateGroupDefinitions(mappingRules));
152         assertTrue(validator.validateGroupDefinitions(mappingRulesWithGroup));
153     }
154
155     @Test
156     public void validateTranslationPhaseNamesTest() {
157         // given
158         MappingRules mappingRules = createMappingRulesWithGroup();
159
160         Rule rule = createRule(createRuleJSON(RULE_GROUP_ID, RULE_PHASE, RULE_PHASE, null));
161         MappingRules mappingRulesWithEntryPhase = new MappingRules(rule);
162         rule = createRule(createRuleJSON(RULE_GROUP_ID, RULE_PHASE, null, RULE_PHASE));
163         MappingRules mappingRulesWithPublishPhase = new MappingRules(rule);
164
165         // when
166         boolean normalRulesValidation =
167             validator.validateTranslationPhaseNames(mappingRules, errors);
168
169         boolean rulesWithTheSameEntryPhase =
170             validator.validateTranslationPhaseNames(mappingRulesWithEntryPhase, errors);
171         ResponseFormat errorEntryPhase = errors.get(0);
172         ServiceException exceptionEntryPhase =
173             errorEntryPhase.getRequestError().getServiceException();
174
175         boolean rulesWithTheSamePublishPhase =
176             validator.validateTranslationPhaseNames(mappingRulesWithPublishPhase, errors);
177         ResponseFormat errorPublishPhase = errors.get(1);
178         ServiceException exceptionPublishPhase =
179             errorPublishPhase.getRequestError().getServiceException();
180         // then
181         assertTrue(normalRulesValidation);
182
183         assertFalse(rulesWithTheSameEntryPhase);
184         assertEquals(400, errorEntryPhase.getStatus().intValue());
185         assertEquals(TRANSLATION_ERROR_MESSAGE_ID, exceptionEntryPhase.getMessageId());
186         assertEquals(TRANSLATION_ERROR_TEXT, exceptionEntryPhase.getText());
187         assertEquals(TRANSLATION_ERROR_ENTRY_VARIABLE_TEXT, exceptionEntryPhase.getVariables()[0]);
188
189         assertFalse(rulesWithTheSamePublishPhase);
190         assertEquals(400, errorPublishPhase.getStatus().intValue());
191         assertEquals(TRANSLATION_ERROR_MESSAGE_ID, exceptionPublishPhase.getMessageId());
192         assertEquals(TRANSLATION_ERROR_TEXT, exceptionPublishPhase.getText());
193         assertEquals(TRANSLATION_ERROR_PUBLISH_VARIABLE_TEXT,
194             exceptionPublishPhase.getVariables()[0]);
195     }
196
197     private void mockAvailableVersionsAndEventTypes(String version) {
198         PowerMockito.mockStatic(VesStructureLoader.class);
199         Map<String, Set<String>> availableVersionsAndEventTypes = new HashMap<>();
200         Set<String> eventTypes = new HashSet<>();
201         eventTypes.add(RULE_EVENT_TYPE);
202         availableVersionsAndEventTypes.put(version, eventTypes);
203         PowerMockito.when(VesStructureLoader.getAvailableVersionsAndEventTypes())
204             .thenReturn(availableVersionsAndEventTypes);
205     }
206
207     private Rule createRule(String body) {
208         GsonBuilder gsonBuilder = new GsonBuilder();
209         gsonBuilder.registerTypeAdapter(BaseAction.class, new ActionDeserializer());
210         gsonBuilder.registerTypeAdapter(BaseCondition.class, new ConditionDeserializer());
211         return gsonBuilder.create().fromJson(body, Rule.class);
212     }
213
214     private MappingRules createMappingRulesWithoutRules() {
215         GsonBuilder gsonBuilder = new GsonBuilder();
216         gsonBuilder.registerTypeAdapter(BaseAction.class, new ActionDeserializer());
217         gsonBuilder.registerTypeAdapter(BaseCondition.class, new ConditionDeserializer());
218         return gsonBuilder.create().fromJson(BASE_JSON, MappingRules.class);
219     }
220
221     private MappingRules createMappingRules() {
222         Rule rule = createRule(RULE_JSON);
223         return new MappingRules(rule);
224     }
225
226     private MappingRules createMappingRulesWithGroup() {
227         Rule rule = createRule(RULE_WITH_GROUP_JSON);
228         return new MappingRules(rule);
229     }
230
231     private static String createRuleJSON(String ruleGroupId, String rulePhase,
232         String ruleEntryPhase, String rulePublishPhase) {
233         return String.format(RULE_OBJECT_TEMPLATE, RULE_VERSION, RULE_EVENT_TYPE, ruleGroupId,
234             rulePhase, ruleEntryPhase, rulePublishPhase);
235     }
236 }