2 # Copyright 2016 RIFT.io Inc
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
24 from deepdiff
import DeepDiff
26 from rift
.mano
.yang_translator
.common
.utils
import _
31 class CompareDescShell(object):
33 SUPPORTED_TYPES
= ['yaml', 'json']
46 'iterable_item_added',
47 'iterable_item_removed',
53 REMOVED_ITEMS
: 'Items removed',
54 ADDED_ITEMS
: 'Items added',
55 ITER_ITEM_ADDED
: 'Items added to list',
56 ITER_ITEM_REM
: 'Items removed from list',
57 TYPE_CHANGES
: 'Change in types',
58 VALUES_CHANGED
: 'Change in values',
61 # Changes in following items are error
62 ERROR_ITEMS
= [REMOVED_ITEMS
, ADDED_ITEMS
, ITER_ITEM_ADDED
,
63 ITER_ITEM_REM
, TYPE_CHANGES
, ]
66 def compare_dicts(cls
, generated
, expected
, log
=None):
67 """Compare two dictionaries and generate error if required"""
69 log
.debug(_("Generated: {0}").format(generated
))
70 log
.debug(_("Expected: {0}").format(expected
))
72 diff
= DeepDiff(expected
, generated
)
74 log
.debug(_("Keys in diff: {0}").format(diff
.keys()))
75 log
.info(_("Differences:\n"))
78 d
= pprint
.pformat(diff
, indent
=cls
.INDENT
)
79 log
.info("Differences:\n{0}".format(d
))
81 if len(set(cls
.ERROR_ITEMS
).intersection(diff
.keys())):
82 diff_str
= pprint
.pformat(diff
)
83 msg
= _("Found item changes: {0}").format(diff_str
)
88 def main(self
, log
, args
):
90 self
.log
.debug(_("Args: {0}").format(args
))
91 if args
.type not in self
.SUPPORTED_TYPES
:
92 self
.log
.error(_("Unsupported file type {0}").
96 with
open(args
.generated
) as g
:
98 if args
.type == 'yaml':
99 y_gen
= yaml
.load(gen_data
)
101 y_gen
= json
.loads(gen_data
)
103 with
open(args
.expected
) as e
:
105 if args
.type == 'yaml':
106 y_exp
= yaml
.load(exp_data
)
108 y_exp
= json
.loads(exp_data
)
110 self
.compare_dicts(y_gen
, y_exp
, log
=self
.log
)
113 def main(args
=None, log
=None):
114 parser
= argparse
.ArgumentParser(
115 description
='Validate descriptors by comparing')
120 help="Generated descriptor file")
125 help="Descriptor file to compare")
130 help="File type. Default yaml")
133 help="Enable debug logging",
137 args
= parser
.parse_args(args
)
139 args
= parser
.parse_args()
143 logging
.basicConfig(level
=logging
.DEBUG
)
145 logging
.basicConfig(level
=logging
.ERROR
)
146 log
= logging
.getLogger("rwmano-translator")
148 CompareDescShell().main(log
, args
)
151 if __name__
== '__main__':