Upgrade sonar plugin
[vid.git] / vid-app-common / src / test / java / org / opencomp / vid / testUtils / TestUtils.java
1 package org.opencomp.vid.testUtils;
2
3 import org.json.JSONArray;
4 import org.json.JSONObject;
5 import org.junit.Assert;
6
7 import java.util.Iterator;
8
9 import static fj.parser.Parser.fail;
10
11 /**
12  * Created by Oren on 6/7/17.
13  */
14 public class TestUtils {
15
16     /**
17      * The method compares between two jsons. the function assert that the actual object does not reduce or change the functionallity/parsing of the expected json.
18      * This means that if the expected JSON has a key which is null or the JSON doesn't have a key which contained in the expected JSON the assert will succeed and the will pass.
19      * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
20      * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
21      *
22      * @param expected JSON
23      * @param actual JSON
24      */
25     public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
26         if (expected == null || expected == JSONObject.NULL) {return;}
27
28         JSONObject expectedJSON = new JSONObject(expected);
29         JSONObject actualJSON = new JSONObject(actual);
30         Iterator<?> keys = expectedJSON.keys();
31
32         while( keys.hasNext() ) {
33             String key = (String)keys.next();
34             Object expectedValue = expectedJSON.get(key);
35             if (expectedValue == JSONObject.NULL){
36                 continue;
37             }
38
39             Object actualValue = actualJSON.get(key);
40
41             if (expectedValue instanceof JSONObject) {
42                 String expectedVal = expectedValue.toString();
43                 String actualVal = actualValue.toString();
44                 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
45             }
46             else if (expectedValue instanceof JSONArray) {
47                 if (actualValue instanceof JSONArray) {
48                     JSONArray expectedJSONArray = (JSONArray)expectedValue;
49                     JSONArray actualJSONArray = (JSONArray)expectedValue;
50                     for (int i = 0; i < expectedJSONArray.length(); i++) {
51                         String expectedItem = expectedJSONArray.getJSONObject(i).toString();
52                         String actualItem = actualJSONArray.getJSONObject(i).toString();
53                         assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
54                     }
55                 }
56                 else {
57                     fail("expected: " + expectedValue + " got:" + actualValue);
58                 }
59             }
60             else {
61                 Assert.assertEquals(expectedValue, actualValue);
62             }
63         }
64     }
65 }