This function is used to recursively compare two dictionaries and return the difference. The difference is from source to target :param source_dict: source dict :param target_dict: target dict :param ignore_keys: ignore keys to compare :param difference:
(source_dict, target_dict, ignore_keys=[], difference=None)
| 638 | |
| 639 | |
| 640 | def directory_diff(source_dict, target_dict, ignore_keys=[], difference=None): |
| 641 | """ |
| 642 | This function is used to recursively compare two dictionaries and |
| 643 | return the difference. |
| 644 | The difference is from source to target |
| 645 | :param source_dict: source dict |
| 646 | :param target_dict: target dict |
| 647 | :param ignore_keys: ignore keys to compare |
| 648 | :param difference: |
| 649 | """ |
| 650 | |
| 651 | difference = {} if difference is None else difference |
| 652 | src_keys = set(source_dict.keys()) |
| 653 | tar_keys = set(target_dict.keys()) |
| 654 | igr_keys = set(ignore_keys) |
| 655 | |
| 656 | # Keys that are available in source and missing in target. |
| 657 | src_only = (src_keys - igr_keys) - tar_keys |
| 658 | # Keys that are available in target and missing in source. |
| 659 | tar_only = (tar_keys - igr_keys) - src_keys |
| 660 | |
| 661 | for key in source_dict.keys(): |
| 662 | added = [] |
| 663 | deleted = [] |
| 664 | updated = [] |
| 665 | source = None |
| 666 | |
| 667 | # ignore the keys if available. |
| 668 | if key in ignore_keys: |
| 669 | continue |
| 670 | elif key in tar_only: |
| 671 | if isinstance(target_dict[key], list): |
| 672 | difference[key] = {} |
| 673 | difference[key]['deleted'] = target_dict[key] |
| 674 | elif key in src_only: |
| 675 | # Source only values in the newly added list |
| 676 | if isinstance(source_dict[key], list): |
| 677 | difference[key] = {} |
| 678 | difference[key]['added'] = source_dict[key] |
| 679 | elif isinstance(source_dict[key], dict): |
| 680 | directory_diff(source_dict[key], target_dict[key], |
| 681 | ignore_keys, difference) |
| 682 | elif isinstance(source_dict[key], list): |
| 683 | tmp_target = None |
| 684 | tmp_list = [x for x in source_dict[key] |
| 685 | if isinstance(x, (list, dict))] |
| 686 | |
| 687 | if tmp_list: |
| 688 | tmp_target = copy.deepcopy(target_dict[key]) |
| 689 | for index in range(len(source_dict[key])): |
| 690 | source = copy.deepcopy(source_dict[key][index]) |
| 691 | if isinstance(source, list): |
| 692 | # This block is empty will figure out some scenario |
| 693 | pass |
| 694 | elif isinstance(source, dict): |
| 695 | # Check the above keys are exist in the dictionary |
| 696 | tmp_key = is_key_exists(list_keys_array, source) |
| 697 | if tmp_key is not None: |
no test coverage detected