Clean autotest folder
[nonrtric.git] / test / common / compare_json.py
1 #  ============LICENSE_START===============================================
2 #  Copyright (C) 2020 Nordix Foundation. All rights reserved.
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 #  ============LICENSE_END=================================================
16 #
17
18 import os
19 import json
20 import sys
21
22 # Deep compare of two json obects
23 # If a parameter value in the target json is set to '????' then the result json value is not checked for the that parameter
24 # Any included json array will be sorted before comparison
25 # An optional array key can be given to sort array of objects containing that key
26
27 def comparejson(jsonTarget,jsonResult,arrayKey):
28
29     if isinstance(jsonTarget, dict):
30         if (len(jsonTarget) != len(jsonResult)):
31             return 1
32         for key in jsonTarget.keys():
33             if (jsonResult.get(key) is None):
34                 return 1
35             if (comparejson(jsonTarget.get(key), jsonResult.get(key), arrayKey) != 0):
36                 return 1
37     elif isinstance(jsonTarget, list):
38         if (len(jsonTarget) != len(jsonResult)):
39             return 1
40         if (arrayKey is None):
41             jsonTarget.sort()
42             jsonResult.sort()
43         else:
44             jsonTarget.sort(key=lambda k: k[arrayKey])
45             jsonResult.sort(key=lambda k: k[arrayKey])
46
47         for i in range(len(jsonTarget)):
48             if (comparejson(jsonTarget[i], jsonResult[i], arrayKey) != 0):
49                 return 1
50     else:
51         if (jsonTarget != "????") and (jsonTarget != jsonResult):
52             return 1
53     return 0
54
55 try:
56     jsonTarget = json.loads(sys.argv[1])
57     jsonResult = json.loads(sys.argv[2])
58     arrayKey = None
59     if (len(sys.argv) > 3):
60         arrayKey = sys.argv[3]
61     print(comparejson(jsonTarget,jsonResult,arrayKey))
62
63 except Exception as e:
64     print (1)
65 sys.exit()