Add schema type for plugins like http
[cli.git] / framework / src / test / java / org / onap / cli / fw / utils / OnapCommandUtilsTest.java
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.cli.fw.utils;
18
19
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertTrue;
23 import static org.junit.Assert.fail;
24
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33
34 import org.junit.FixMethodOrder;
35 import org.junit.Ignore;
36 import org.junit.Test;
37 import org.junit.runners.MethodSorters;
38 import org.onap.cli.fw.OnapCommand;
39 import org.onap.cli.fw.OnapCommandSchema;
40 import org.onap.cli.fw.cmd.OnapHttpCommand;
41 import org.onap.cli.fw.cmd.OnapSwaggerCommand;
42 import org.onap.cli.fw.error.OnapCommandException;
43 import org.onap.cli.fw.error.OnapCommandHelpFailed;
44 import org.onap.cli.fw.error.OnapCommandHttpHeaderNotFound;
45 import org.onap.cli.fw.error.OnapCommandHttpInvalidResponseBody;
46 import org.onap.cli.fw.error.OnapCommandInvalidParameterType;
47 import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection;
48 import org.onap.cli.fw.error.OnapCommandInvalidResultAttributeScope;
49 import org.onap.cli.fw.error.OnapCommandInvalidSchema;
50 import org.onap.cli.fw.error.OnapCommandInvalidSchemaVersion;
51 import org.onap.cli.fw.error.OnapCommandParameterNameConflict;
52 import org.onap.cli.fw.error.OnapCommandParameterNotFound;
53 import org.onap.cli.fw.error.OnapCommandParameterOptionConflict;
54 import org.onap.cli.fw.error.OnapCommandSchemaNotFound;
55 import org.onap.cli.fw.http.HttpInput;
56 import org.onap.cli.fw.http.HttpResult;
57 import org.onap.cli.fw.info.OnapCommandInfo;
58 import org.onap.cli.fw.input.OnapCommandParameter;
59 import org.onap.cli.fw.input.ParameterType;
60 import org.onap.cli.fw.output.OnapCommandResult;
61 import org.onap.cli.fw.run.OnapCommandExecutor;
62 import org.springframework.core.io.Resource;
63
64 import mockit.Invocation;
65 import mockit.Mock;
66 import mockit.MockUp;
67
68 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
69 public class OnapCommandUtilsTest {
70
71     @Test(expected = OnapCommandInvalidSchema.class)
72     public void oclipCommandUtilsInputStreamNullTest() throws OnapCommandException {
73         OnapCommandUtils.validateSchemaVersion("sample-test1-schema-http1.yaml", "1.0");
74     }
75
76     @Test
77     public void oclipCommandUtilsInputStreamNotNullTest() throws OnapCommandException {
78         Map<String, ?> map = OnapCommandUtils.validateSchemaVersion("sample-test1-schema-http.yaml", "1.0");
79         assertTrue(map != null);
80     }
81
82     @Test
83     public void externalSchemaTest() {
84         SchemaInfo schema = new SchemaInfo();
85         schema.setCmdName("cmdName");
86         schema.setSchemaName("schemaName");
87         schema.setVersion("version");
88
89         assertTrue("cmdName".equals(schema.getCmdName()) && "schemaName".equals(schema.getSchemaName())
90                 && "version".equals(schema.getVersion()));
91     }
92
93     @Test
94     public void schemaFileNotFoundTest() throws OnapCommandException {
95
96         Map<String, ?> map = OnapCommandUtils.validateSchemaVersion("sample-test-schema.yaml", "1.0");
97         assertTrue(map.size() > 0);
98     }
99
100     @Test
101     @Ignore
102     public void invalidSchemaFileTest() throws OnapCommandException {
103         Map<String, ?> map = null;
104         try {
105             map = OnapCommandUtils.validateSchemaVersion("sample-test-schema1.yaml", "1.0");
106         } catch (OnapCommandInvalidSchemaVersion e) {
107             fail("Test should not have thrown this exception : " + e.getMessage());
108         } catch (OnapCommandInvalidSchema e) {
109             fail("Test should not have thrown this exception : " + e.getMessage());
110         } catch (OnapCommandSchemaNotFound e) {
111             assertEquals("0xb002::Command schema sample-test-schema1.yaml is not found", e.getMessage());
112         }
113     }
114
115     @Test
116     public void validateWrongSchemaVersionTest() throws OnapCommandException {
117         Map<String, ?> map = null;
118         try {
119             map = OnapCommandUtils.validateSchemaVersion("sample-test-invalid-schema.yaml", "1.0");
120         } catch (OnapCommandInvalidSchemaVersion e) {
121             fail("Test should not have thrown this exception : " + e.getMessage());
122         } catch (OnapCommandInvalidSchema e) {
123             assertTrue(e.getMessage().contains("0xb001::Command schema sample-test-invalid-schema.yaml is invalid"));
124         } catch (OnapCommandSchemaNotFound e) {
125             fail("Test should not have thrown this exception : " + e.getMessage());
126         }
127     }
128
129     @Test
130     public void validateSchemaVersionTest() throws OnapCommandException {
131         Map<String, ?> map = null;
132         try {
133             map = OnapCommandUtils.validateSchemaVersion("sample-test-schema.yaml", "1.1");
134         } catch (OnapCommandInvalidSchemaVersion e) {
135             assertEquals("0xb003::Command schema open_cli_schema_version 1.0 is invalid or missing", e.getMessage());
136         } catch (OnapCommandInvalidSchema e) {
137             fail("Test should not have thrown this exception : " + e.getMessage());
138         } catch (OnapCommandSchemaNotFound e) {
139             fail("Test should not have thrown this exception : " + e.getMessage());
140         }
141     }
142
143     @Test
144     public void loadOnapCommandSchemaWithOutDefaultTest() throws OnapCommandException {
145         OnapCommand cmd = new OnapCommandSample();
146         OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", false, false);
147         assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() == 9);
148     }
149
150     @Test(expected = OnapCommandParameterNameConflict.class)
151     public void loadOnapCommandSchemaWithDuplicateNameTest() throws OnapCommandException {
152         OnapCommand cmd = new OnapCommandSample();
153         OnapCommandUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-name.yaml", false, false);
154     }
155
156     @Test(expected = OnapCommandParameterOptionConflict.class)
157     public void loadOnapCommandSchemaWithDuplicateShortOptionTest() throws OnapCommandException {
158         OnapCommand cmd = new OnapCommandSample();
159         OnapCommandUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-shortoption.yaml", false, false);
160     }
161
162     @Test(expected = OnapCommandParameterOptionConflict.class)
163     public void loadOnapCommandSchemaWithDuplicateLongOptionTest() throws OnapCommandException {
164         OnapCommand cmd = new OnapCommandSample();
165         OnapCommandUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-longoption.yaml", false, false);
166     }
167
168     @Test
169     public void loadOnapCommandSchemaWithDefaultTest() throws OnapCommandException {
170         OnapCommand cmd = new OnapCommandSample();
171         OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", true, false);
172         assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() > 9);
173
174         for (OnapCommandParameter com : cmd.getParameters()) {
175             com.setValue("value");
176         }
177
178         Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters());
179         assertTrue(map.size() == 15);
180     }
181
182     @Test
183     public void loadOnapCommandSchemaAuthRequiredTest() throws OnapCommandException {
184         OnapCommand cmd = new OnapCommandSample();
185         OnapCommandUtils.loadSchema(cmd, "sample-test-schema-auth-required.yaml", true, false);
186         assertTrue("sample-test".equals(cmd.getName()));
187
188         Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters());
189         assertTrue(map.size() == 7);
190     }
191
192     @Test
193     public void loadSwaggerBasedSchemaExceptionTest() throws OnapCommandException {
194         OnapSwaggerCommand cmd = new OnapSwaggerBasedCommandSample();
195         try {
196             OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml");
197         } catch (OnapCommandInvalidSchema e) {
198             assertEquals("0xb001", e.getErrorCode());
199         }
200     }
201
202     @Test
203     public void loadSwaggerBasedSchemaTest() throws OnapCommandException {
204         OnapSwaggerCommand cmd = new OnapSwaggerBasedCommandSample();
205         try {
206             OnapCommandUtils.loadSchema(cmd, "sample-test-schema-swagger.yaml");
207             OnapCommandExecutor exe = cmd.getExecutor();
208             assertTrue(exe != null);
209         } catch (OnapCommandInvalidSchema e) {
210             assertTrue(e.getMessage().contains("0xb001::Command schema sample-test-schema.yaml is invalid"));
211         }
212     }
213
214     @Test
215     public void loadHttpBasedSchemaExceptionTest() throws OnapCommandException {
216         OnapHttpCommand cmd = new OnapHttpCommandSample();
217         cmd.setName("sample-test-http");
218         try {
219             OnapCommandUtils.loadHttpSchema(cmd, "sample-test-schema.yaml", true, false);
220         } catch (OnapCommandParameterNameConflict | OnapCommandParameterOptionConflict
221                 | OnapCommandInvalidParameterType | OnapCommandInvalidPrintDirection
222                 | OnapCommandInvalidResultAttributeScope | OnapCommandSchemaNotFound | OnapCommandInvalidSchema
223                 | OnapCommandInvalidSchemaVersion e) {
224             assertTrue(e.getMessage().contains("0xb001::Command schema sample-test-schema.yaml is invalid"));
225         }
226     }
227
228     @Test
229     public void loadHttpBasedSchemaTest() throws OnapCommandException {
230         OnapHttpCommand cmd = new OnapHttpCommandSample();
231         cmd.setName("sample-create-http");
232         try {
233             OnapCommandUtils.loadHttpSchema(cmd, "sample-test-schema-http.yaml", true, true);
234             assertTrue(cmd.getSuccessStatusCodes().size() == 2);
235         } catch (OnapCommandParameterNameConflict | OnapCommandParameterOptionConflict
236                 | OnapCommandInvalidParameterType | OnapCommandInvalidPrintDirection
237                 | OnapCommandInvalidResultAttributeScope | OnapCommandSchemaNotFound | OnapCommandInvalidSchema
238                 | OnapCommandInvalidSchemaVersion e) {
239             fail("Test should not have thrown this exception : " + e.getMessage());
240         }
241     }
242
243     @Test
244     public void helpCommandTest() throws IOException, OnapCommandException {
245         OnapCommand cmd = new OnapCommandSample();
246         OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", true, false);
247
248         String actualResult = OnapCommandUtils.help(cmd);
249
250         String expectedHelp = FileUtil.loadResource("sample-cmd-test-help.txt");
251
252         //mrkanag compare the result
253     }
254
255     @Test
256     public void findOnapCommandsTest() {
257         List<Class<OnapCommand>> cmds = OnapCommandUtils.discoverCommandPlugins();
258         assertTrue(cmds.size() == 7);
259     }
260
261     @Test
262     public void sortTest() {
263         Set<String> set = new HashSet<String>();
264         set.add("dbvc");
265         set.add("bbvcb");
266         set.add("aaa");
267         set.add("c");
268         set.add("z");
269         List<String> list = OnapCommandUtils.sort(set);
270         assertEquals("[aaa, bbvcb, c, dbvc, z]", list.toString());
271     }
272
273     @Test
274     public void jsonFlattenTest() {
275         List<String> list = Arrays.asList(new String[] { "{\"menu1\": {\"id\": \"file1\",\"value\": \"File1\"}}" });
276         List<String> list1 = OnapCommandUtils.jsonFlatten(list);
277         String expected = "[{\"menu1\":{\"id\":\"file1\",\"value\":\"File1\"}}]";
278         assertEquals(expected, list1.toString());
279
280     }
281
282     @Test
283     public void jsonFlattenExceptionTest() {
284         List<String> list = Arrays.asList(new String[] { "{\"menu1\"::{\"id\":\"file1\",\"value\":\"File1\"}}" });
285         List<String> list1 = OnapCommandUtils.jsonFlatten(list);
286         String expected = "[{\"menu1\"::{\"id\":\"file1\",\"value\":\"File1\"}}]";
287         assertEquals(expected, list1.toString());
288
289     }
290
291     @Test
292     public void formMethodNameFromAttributeTest() {
293
294         String str = "";
295         String name = OnapCommandUtils.formMethodNameFromAttributeName(str, "test");
296
297         assertEquals("", name);
298
299         str = null;
300         name = OnapCommandUtils.formMethodNameFromAttributeName(str, "test");
301
302         assertEquals(null, name);
303
304         str = "test-get";
305         name = OnapCommandUtils.formMethodNameFromAttributeName(str, "");
306         assertEquals("TestGet", name);
307
308     }
309
310     @Test
311     public void populateParametersTest() throws OnapCommandException {
312
313         HttpInput input = new HttpInput();
314         input.setBody("body");
315         input.setMethod("method");
316         Map<String, String> mapHead = new HashMap<>();
317         mapHead.put("key2", "${value2}");
318         input.setReqHeaders(mapHead);
319         Map<String, String> query = new HashMap<>();
320         query.put("key3", "{${value3}}");
321         input.setReqQueries(query);
322         input.setUri("uri");
323
324         Map<String, OnapCommandParameter> params = new HashMap<>();
325         OnapCommandParameter param = new OnapCommandParameter();
326         param.setDefaultValue("defaultValue2");
327         param.setParameterType(ParameterType.STRING);
328         params.put("value2", param);
329         OnapCommandParameter param1 = new OnapCommandParameter();
330         param1.setDefaultValue("{\"defaultValue3\"}");
331         param1.setParameterType(ParameterType.JSON);
332         params.put("value3", param1);
333
334         HttpInput input1 = OnapCommandUtils.populateParameters(params, input);
335         String expected = "\nURL: uri\nMethod: method\nRequest Queries: {key3={\"defaultValue3\"}}\n"
336                 + "Request Body: body\nRequest Headers: {key2=defaultValue2}\nRequest Cookies: {}\nbinaryData=false";
337         assertEquals(expected, input1.toString());
338
339         input.setBody("${body}");
340
341         HttpInput input2 = null;
342         try {
343             input2 = OnapCommandUtils.populateParameters(params, input);
344         } catch (OnapCommandParameterNotFound e) {
345             assertEquals("0x7005::Command input parameter body is not valid", e.getMessage());
346         }
347
348     }
349
350     @Test(expected = OnapCommandHttpHeaderNotFound.class)
351     public void populateOutputsTest() throws OnapCommandException {
352         HttpResult output = new HttpResult();
353         output.setBody(
354                 "{\"serviceName\":\"test\",\"version\":\"v1\",\"url\":\"/api/test/v1\",\"protocol\":\"REST\",\"visualRange\":\"1\",\"lb_policy\":\"hash\",\"nodes\":[{\"ip\":\"127.0.0.1\",\"port\":\"8012\",\"ttl\":0,\"nodeId\":\"test_127.0.0.1_8012\",\"expiration\":\"2017-02-10T05:33:25Z\",\"created_at\":\"2017-02-10T05:33:25Z\",\"updated_at\":\"2017-02-10T05:33:25Z\"}],\"status\":\"1\"}");
355         Map<String, String> mapHead = new HashMap<>();
356         mapHead.put("head1", "value1");
357         output.setRespHeaders(mapHead);
358         output.setStatus(0);
359
360         Map<String, String> params = new HashMap<>();
361         params.put("head", "$h{head1}");
362         params.put("body", "$b{$.serviceName}");
363         params.put("key", "value");
364
365         Map<String, ArrayList<String>> input1 = OnapCommandUtils.populateOutputs(params, output);
366         assertEquals("{head=[value1], body=[test], key=[value]}", input1.toString());
367
368         params.put("body", "$b{{$.serviceName}");
369         try {
370             input1 = OnapCommandUtils.populateOutputs(params, output);
371         } catch (OnapCommandHttpInvalidResponseBody e) {
372             assertEquals(
373                     "0x3004::Http response body does not have json entry {$.serviceName, Missing property in path $['{$']",
374                     e.getMessage());
375         }
376         output.setBody("{}");
377         input1 = OnapCommandUtils.populateOutputs(params, output);
378         params.put("head", "$h{head2}");
379         output.setBody("{\"test\"}");
380         input1 = OnapCommandUtils.populateOutputs(params, output);
381     }
382
383
384     @Test(expected = OnapCommandHelpFailed.class)
385     public void zendExceptionHelpTest1() throws OnapCommandException {
386
387         mockPrintMethodException();
388         OnapCommand cmd = new OnapCommandSample();
389         OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", true, false);
390
391         OnapCommandUtils.help(cmd);
392
393     }
394
395
396     @Test
397     public void test() throws OnapCommandException {
398         OnapCommandSampleInfo cmd = new OnapCommandSampleInfo();
399         OnapCommandUtils.loadSchema(cmd, "sample-test-info.yaml", true, false);
400         OnapCommandInfo info = cmd.getInfo();
401         assert info != null;
402     }
403
404     @OnapCommandSchema(schema = "sample-test-info.yaml")
405     class OnapCommandSampleInfo extends OnapCommand {
406         @Override
407         protected void run() throws OnapCommandException {
408         }
409     }
410
411     @OnapCommandSchema(schema = "sample-test-schema.yaml")
412     class OnapCommandSample extends OnapCommand {
413         @Override
414         protected void run() throws OnapCommandException {
415         }
416     }
417
418     @OnapCommandSchema(schema = "sample-test-schema-swagger.yaml")
419     class OnapSwaggerBasedCommandSample extends OnapSwaggerCommand {
420
421         @Override
422         protected void run() throws OnapCommandException {
423         }
424     }
425
426     @OnapCommandSchema(schema = "sample-test-schema-http.yaml")
427     class OnapHttpCommandSample extends OnapHttpCommand {
428
429         @Override
430         protected void run() throws OnapCommandException {
431         }
432     }
433
434     private void mockExternalResources() {
435         new MockUp<OnapCommandUtils>() {
436             boolean isMock = true;
437
438             @Mock
439             public Resource[] getExternalResources(Invocation inv, String pattern) throws IOException {
440                 if (isMock) {
441                     isMock = false;
442                     throw new IOException();
443                 } else {
444                     return inv.proceed(pattern);
445                 }
446             }
447         };
448     }
449
450     private void mockPrintMethodException() {
451         new MockUp<OnapCommandResult>() {
452             boolean isMock = true;
453
454             @Mock
455             public String print(Invocation inv) throws OnapCommandException {
456                 if (isMock) {
457                     isMock = false;
458                     throw new OnapCommandException("", "");
459                 } else {
460                     return inv.proceed();
461                 }
462             }
463         };
464     }
465 }