pax_global_header00006660000000000000000000000064140762704360014523gustar00rootroot0000000000000052 comment=36506e4046e07e4d43e0b5af6f76c75ff7b2b6a3 dictdiffer-0.9.0/000077500000000000000000000000001407627043600136345ustar00rootroot00000000000000dictdiffer-0.9.0/.coveragerc000066400000000000000000000003601407627043600157540ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2014 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. [run] source = dictdiffer dictdiffer-0.9.0/.github/000077500000000000000000000000001407627043600151745ustar00rootroot00000000000000dictdiffer-0.9.0/.github/workflows/000077500000000000000000000000001407627043600172315ustar00rootroot00000000000000dictdiffer-0.9.0/.github/workflows/pypi-release.yml000066400000000000000000000016651407627043600223630ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2020 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details name: Publish on: push: tags: - v* jobs: Publish: runs-on: ubuntu-20.04 steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel - name: Build package run: python setup.py sdist bdist_wheel - name: Publish on PyPI uses: pypa/gh-action-pypi-publish@v1.3.1 with: user: __token__ # The token is provided by the inveniosoftware organization password: ${{ secrets.pypi_token }} dictdiffer-0.9.0/.github/workflows/tests.yml000066400000000000000000000034371407627043600211250ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2020 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. name: CI on: push: branches: master pull_request: branches: master schedule: # * is a special character in YAML so you have to quote this string - cron: '0 3 * * 6' workflow_dispatch: inputs: reason: description: 'Reason' required: false default: 'Manual trigger' jobs: Tests: runs-on: ubuntu-20.04 strategy: matrix: python-version: [3.5, 3.6, 3.7, 3.8, 3.9] requirements-level: [min, pypi] steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Generate dependencies run: | sudo apt-get install libxml2-dev libxslt1-dev python -m pip install --upgrade pip setuptools py wheel requirements-builder requirements-builder -e all --level=${{ matrix.requirements-level }} setup.py > .${{ matrix.requirements-level }}-${{ matrix.python-version }}-requirements.txt - name: Cache pip uses: actions/cache@v2 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('.${{ matrix.requirements-level }}-${{ matrix.python-version }}-requirements.txt') }} - name: Install dependencies run: | pip install -r .${{ matrix.requirements-level }}-${{ matrix.python-version }}-requirements.txt pip install .[all] pip freeze - name: Run tests run: | ./run-tests.sh dictdiffer-0.9.0/.gitignore000066400000000000000000000005621407627043600156270ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2013 Fatih Erikli. # Copyright (C) 2014, 2016 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. .eggs/ *.egg *.egg-info *.pyc .DS_Store .cache .coverage .tox build/ dist/ docs/_build docs/db docs/static htmlcov dictdiffer-0.9.0/.lgtm000066400000000000000000000000741407627043600146010ustar00rootroot00000000000000approvals = 1 pattern = "(?i)LGTM" self_approval_off = true dictdiffer-0.9.0/AUTHORS000066400000000000000000000011311407627043600147000ustar00rootroot00000000000000Authors ======= Dictdiffer was originally developed by Fatih Erikli. It is now being developed and maintained by the Invenio collaboration. You can contact us at `info@inveniosoftware.org `_. Contributors: * Fatih Erikli * Brian Rue * Lars Holm Nielsen * Tibor Simko * Jiri Kuncar * Jason Peddle * Martin Vesper * Gilles DAVID * Alexander Mohr dictdiffer-0.9.0/CHANGES000066400000000000000000000073071407627043600146360ustar00rootroot00000000000000Changes ======= Version 0.9.0 (released 2021-07-22) - Adds absolute tolerance feature for floats (@adrien-berchet) (#152) - Drops support of Python<3.5 (@adrien-berchet) (#160) - Adds `assert_no_diff` helper to assist pytest users (@joesolly) (#153) - Migrates CI to gh-actions (@ParthS007 @diegodelemos) (#145) - Removes dependency on pkg_resources (@eldruin) Version 0.8.1 (released 2019-12-13) - Fix invalid diff output for sets. (@jirikuncar @danielduhh) (#133 #134) Version 0.8.0 (released 2019-03-17) - Respect `dot_notation` flag in ignore argument (@yoyonel) (#107) - Adds argument for toggling dot notation in diff. (@robinchew) Version 0.7.2 (released 2019-02-22) - Two NaN values are considered the same, hence they are not shown in `diff` output. (#114) (@t-b) - Refactors `diff` method to reduce recursive call stack size. (#112) (@yoyonel) - Python porting best practice use feature detection instead of version detection to save an import and pass both PyLint and Flake8 tests with neither 'pragma' nor 'noqa'. (@cclauss) Version 0.7.1 (released 2018-05-04) - Resolves issue with keys containing dots. (#101) Version 0.7.0 (released 2017-10-16) - Fixes problem with diff results that reference the original structure by introduction of `deepcopy` for all possibly unhashable items. Thus the diff does not change later when the diffed structures change. - Adds new option for patching and reverting patches in-place. - Adds Python 3.6 to test matrix. - Fixes the `ignore` argument when it contains a unicode value. Version 0.6.1 (released 2016-11-22) - Changes order of items for REMOVE section of generated patches when `swap` is called so the list items are removed from the end. (#85) - Improves API documentation for `ignore` argument in `diff` function. (#79) - Executes doctests during PyTest invocation. Version 0.6.0 (released 2016-06-22) - Adds support for comparing NumPy arrays. (#68) - Adds support for comparing mutable mappings, sequences and sets from `collections.abs` module. (#67) - Updates package structure, sorts imports and runs doctests. - Fixes order in which handled conflicts are unified so that the Merger's unified_patches can be always applied. Version 0.5.0 (released 2016-01-04) - Adds tolerance parameter used when user wants to treat closed values as equals - Adds support for comparing numerical values and NaN. (#54) (#55) Version 0.4.0 (released 2015-03-11) - Adds support for diffing and patching of sets. (#44) - New tests for diff on the same lists. (#48) - Fix for exception when dict has unicode keys and ignore parameter is provided. (#50) - PEP8 improvements. Version 0.3.0 (released 2014-11-05) - Adds ignore argument to `diff` function that allows skipping check on specified keys. (#34 #35) - Fix for diffing of dict or list subclasses. (#37) - Better instance checking of diffing objects. (#39) Version 0.2.0 (released 2014-09-29) - Fix for empty list instructions. (#30) - Regression test for empty list instructions. Version 0.1.0 (released 2014-09-01) - Fix for list removal issues during patching caused by wrong iteration. (#10) - Fix for issues with multiple value types for the same key. (#10) - Fix for issues with strings handled as iterables. (#6) - Fix for integer keys. (#12) - Regression test for complex dictionaries. (#4) - Better testing with Github actions, tox, pytest, code coverage. (#10) - Initial release of documentation on ReadTheDocs. (#21 #24) - Support for Python 3. (#15) Version 0.0.4 (released 2014-01-04) - List diff behavior treats lists as lists instead of sets. (#3) - Differed typed objects are flagged as `changed` now. - Swap function refactored. Version 0.0.3 (released 2013-05-26) - Initial public release on PyPI. dictdiffer-0.9.0/CONTRIBUTING.rst000066400000000000000000000016501407627043600162770ustar00rootroot00000000000000Contributing ============ Bug reports, feature requests, and other contributions are welcome. If you find a demonstrable problem that is caused by the code of this library, please: 1. Search for `already reported problems `_. 2. Check if the issue has been fixed or is still reproducible on the latest `master` branch. 3. Create an issue with **a test case**. If you create a feature branch, you can run the tests to ensure everything is operating correctly: .. code-block:: console $ ./run-tests.sh ... Name Stmts Miss Cover Missing --------------------------------------------------- dictdiffer/__init__ 88 0 100% dictdiffer/version 2 0 100% --------------------------------------------------- TOTAL 90 0 100% ... 52 passed, 2 skipped in 0.44 seconds dictdiffer-0.9.0/LICENSE000066400000000000000000000025661407627043600146520ustar00rootroot00000000000000Dictdiffer is free software; you can redistribute it and/or modify it under the terms of the MIT License quoted below. Copyright (C) 2013 Fatih Erikli. Copyright (C) 2013, 2014 CERN. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. dictdiffer-0.9.0/MAINTAINERS000066400000000000000000000001401407627043600153240ustar00rootroot00000000000000Jiri Kuncar (@jirikuncar) Tibor Simko (@tiborsimko) dictdiffer-0.9.0/MANIFEST.in000066400000000000000000000010171407627043600153710ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2014, 2016 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. include README.rst CHANGES CONTRIBUTING.rst AUTHORS LICENSE MANIFEST.in include RELEASE-NOTES.rst include .coveragerc pytest.ini include .lgtm MAINTAINERS include docs/*.rst docs/*.py docs/Makefile docs/requirements.txt include *.py *.sh include tox.ini tests/*.py recursive-include .github/workflows *.yml dictdiffer-0.9.0/README.rst000066400000000000000000000023161407627043600153250ustar00rootroot00000000000000============ Dictdiffer ============ .. image:: https://github.com/inveniosoftware/dictdiffer/workflows/CI/badge.svg :target: https://github.com/inveniosoftware/dictdiffer/actions .. image:: https://img.shields.io/coveralls/inveniosoftware/dictdiffer.svg :target: https://coveralls.io/r/inveniosoftware/dictdiffer .. image:: https://img.shields.io/github/tag/inveniosoftware/dictdiffer.svg :target: https://github.com/inveniosoftware/dictdiffer/releases .. image:: https://img.shields.io/pypi/dm/dictdiffer.svg :target: https://pypi.python.org/pypi/dictdiffer .. image:: https://img.shields.io/github/license/inveniosoftware/dictdiffer.svg :target: https://github.com/inveniosoftware/dictdiffer/blob/master/LICENSE About ===== Dictdiffer is a helper module that helps you to diff and patch dictionaries. Installation ============ Dictdiffer is on PyPI so all you need is: :: pip install dictdiffer Documentation ============= Documentation is readable at https://dictdiffer.readthedocs.io or can be built using Sphinx: :: pip install dictdiffer[docs] python setup.py build_sphinx Testing ======= Running the test suite is as simple as: :: ./run-tests.sh dictdiffer-0.9.0/dictdiffer/000077500000000000000000000000001407627043600157375ustar00rootroot00000000000000dictdiffer-0.9.0/dictdiffer/__init__.py000066400000000000000000000340641407627043600200570ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2013 Fatih Erikli. # Copyright (C) 2013, 2014, 2015, 2016 CERN. # Copyright (C) 2017-2019 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Dictdiffer is a helper module to diff and patch dictionaries.""" from collections.abc import (Iterable, MutableMapping, MutableSequence, MutableSet) from copy import deepcopy from .utils import EPSILON, PathLimit, are_different, dot_lookup from .version import __version__ (ADD, REMOVE, CHANGE) = ( 'add', 'remove', 'change') __all__ = ('diff', 'patch', 'swap', 'revert', 'dot_lookup', '__version__') DICT_TYPES = (MutableMapping, ) LIST_TYPES = (MutableSequence, ) SET_TYPES = (MutableSet, ) try: import numpy HAS_NUMPY = True LIST_TYPES += (numpy.ndarray, ) except ImportError: # pragma: no cover HAS_NUMPY = False def diff(first, second, node=None, ignore=None, path_limit=None, expand=False, tolerance=EPSILON, absolute_tolerance=None, dot_notation=True): """Compare two dictionary/list/set objects, and returns a diff result. Return an iterator with differences between two objects. The diff items represent addition/deletion/change and the item value is a *deep copy* from the corresponding source or destination objects. >>> from dictdiffer import diff >>> result = diff({'a': 'b'}, {'a': 'c'}) >>> list(result) [('change', 'a', ('b', 'c'))] The keys can be skipped from difference calculation when they are included in ``ignore`` argument of type :class:`collections.Container`. >>> list(diff({'a': 1, 'b': 2}, {'a': 3, 'b': 4}, ignore=set(['a']))) [('change', 'b', (2, 4))] >>> class IgnoreCase(set): ... def __contains__(self, key): ... return set.__contains__(self, str(key).lower()) >>> list(diff({'a': 1, 'b': 2}, {'A': 3, 'b': 4}, ignore=IgnoreCase('a'))) [('change', 'b', (2, 4))] The difference calculation can be limitted to certain path: >>> list(diff({}, {'a': {'b': 'c'}})) [('add', '', [('a', {'b': 'c'})])] >>> from dictdiffer.utils import PathLimit >>> list(diff({}, {'a': {'b': 'c'}}, path_limit=PathLimit())) [('add', '', [('a', {})]), ('add', 'a', [('b', 'c')])] >>> from dictdiffer.utils import PathLimit >>> list(diff({}, {'a': {'b': 'c'}}, path_limit=PathLimit([('a',)]))) [('add', '', [('a', {'b': 'c'})])] >>> from dictdiffer.utils import PathLimit >>> list(diff({}, {'a': {'b': 'c'}}, ... path_limit=PathLimit([('a', 'b')]))) [('add', '', [('a', {})]), ('add', 'a', [('b', 'c')])] The patch can be expanded to small units e.g. when adding multiple values: >>> list(diff({'fruits': []}, {'fruits': ['apple', 'mango']})) [('add', 'fruits', [(0, 'apple'), (1, 'mango')])] >>> list(diff({'fruits': []}, {'fruits': ['apple', 'mango']}, expand=True)) [('add', 'fruits', [(0, 'apple')]), ('add', 'fruits', [(1, 'mango')])] >>> list(diff({'a': {'x': 1}}, {'a': {'x': 2}})) [('change', 'a.x', (1, 2))] >>> list(diff({'a': {'x': 1}}, {'a': {'x': 2}}, ... dot_notation=False)) [('change', ['a', 'x'], (1, 2))] :param first: The original dictionary, ``list`` or ``set``. :param second: New dictionary, ``list`` or ``set``. :param node: Key for comparison that can be used in :func:`dot_lookup`. :param ignore: Set of keys that should not be checked. :param path_limit: List of path limit tuples or dictdiffer.utils.Pathlimit object to limit the diff recursion depth. :param expand: Expand the patches. :param tolerance: Threshold to consider when comparing two float numbers. :param absolute_tolerance: Absolute threshold to consider when comparing two float numbers. :param dot_notation: Boolean to toggle dot notation on and off. .. versionchanged:: 0.3 Added *ignore* parameter. .. versionchanged:: 0.4 Arguments ``first`` and ``second`` can now contain a ``set``. .. versionchanged:: 0.5 Added *path_limit* parameter. Added *expand* paramter. Added *tolerance* parameter. .. versionchanged:: 0.7 Diff items are deep copies from its corresponding objects. Argument *ignore* is always converted to a ``set``. .. versionchanged:: 0.8 Added *dot_notation* parameter. """ if path_limit is not None and not isinstance(path_limit, PathLimit): path_limit = PathLimit(path_limit) if isinstance(ignore, Iterable): def _process_ignore_value(value): if isinstance(value, int): return value, elif isinstance(value, list): return tuple(value) elif not dot_notation and isinstance(value, str): return value, return value ignore = type(ignore)(_process_ignore_value(value) for value in ignore) def dotted(node, default_type=list): """Return dotted notation.""" if dot_notation and \ all(map(lambda x: isinstance(x, str) and '.' not in x, node)): return '.'.join(node) else: return default_type(node) def _diff_recursive(_first, _second, _node=None): _node = _node or [] dotted_node = dotted(_node) differ = False if isinstance(_first, DICT_TYPES) and isinstance(_second, DICT_TYPES): # dictionaries are not hashable, we can't use sets def check(key): """Test if key in current node should be ignored.""" return ignore is None or ( dotted(_node + [key], default_type=tuple) not in ignore and tuple(_node + [key]) not in ignore ) intersection = [k for k in _first if k in _second and check(k)] addition = [k for k in _second if k not in _first and check(k)] deletion = [k for k in _first if k not in _second and check(k)] differ = True elif isinstance(_first, LIST_TYPES) and isinstance(_second, LIST_TYPES): len_first = len(_first) len_second = len(_second) intersection = list(range(0, min(len_first, len_second))) addition = list(range(min(len_first, len_second), len_second)) deletion = list( reversed(range(min(len_first, len_second), len_first))) differ = True elif isinstance(_first, SET_TYPES) and isinstance(_second, SET_TYPES): # Deep copy is not necessary for hashable items. addition = _second - _first if len(addition): yield ADD, dotted_node, [(0, addition)] deletion = _first - _second if len(deletion): yield REMOVE, dotted_node, [(0, deletion)] return # stop here for sets if differ: # Compare if object is a dictionary or list. # # NOTE variables: intersection, addition, deletion contain only # hashable types, hence they do not need to be deepcopied. # # Call again the parent function as recursive if dictionary have # child objects. Yields `add` and `remove` flags. for key in intersection: # if type is not changed, # callees again diff function to compare. # otherwise, the change will be handled as `change` flag. if path_limit and path_limit.path_is_limit(_node + [key]): yield CHANGE, _node + [key], ( deepcopy(_first[key]), deepcopy(_second[key]) ) else: recurred = _diff_recursive( _first[key], _second[key], _node=_node + [key], ) for diffed in recurred: yield diffed if addition: if path_limit: collect = [] collect_recurred = [] for key in addition: if not isinstance(_second[key], SET_TYPES + LIST_TYPES + DICT_TYPES): collect.append((key, deepcopy(_second[key]))) elif path_limit.path_is_limit(_node + [key]): collect.append((key, deepcopy(_second[key]))) else: collect.append((key, _second[key].__class__())) recurred = _diff_recursive( _second[key].__class__(), _second[key], _node=_node + [key], ) collect_recurred.append(recurred) if expand: for key, val in collect: yield ADD, dotted_node, [(key, val)] else: yield ADD, dotted_node, collect for recurred in collect_recurred: for diffed in recurred: yield diffed else: if expand: for key in addition: yield ADD, dotted_node, [ (key, deepcopy(_second[key]))] else: yield ADD, dotted_node, [ # for additions, return a list that consist with # two-pair tuples. (key, deepcopy(_second[key])) for key in addition] if deletion: if expand: for key in deletion: yield REMOVE, dotted_node, [ (key, deepcopy(_first[key]))] else: yield REMOVE, dotted_node, [ # for deletions, return the list of removed keys # and values. (key, deepcopy(_first[key])) for key in deletion] else: # Compare string and numerical types and yield `change` flag. if are_different(_first, _second, tolerance, absolute_tolerance): yield CHANGE, dotted_node, (deepcopy(_first), deepcopy(_second)) return _diff_recursive(first, second, node) def patch(diff_result, destination, in_place=False): """Patch the diff result to the destination dictionary. :param diff_result: Changes returned by ``diff``. :param destination: Structure to apply the changes to. :param in_place: By default, destination dictionary is deep copied before applying the patch, and the copy is returned. Setting ``in_place=True`` means that patch will apply the changes directly to and return the destination structure. """ if not in_place: destination = deepcopy(destination) def add(node, changes): for key, value in changes: dest = dot_lookup(destination, node) if isinstance(dest, LIST_TYPES): dest.insert(key, value) elif isinstance(dest, SET_TYPES): dest |= value else: dest[key] = value def change(node, changes): dest = dot_lookup(destination, node, parent=True) if isinstance(node, str): last_node = node.split('.')[-1] else: last_node = node[-1] if isinstance(dest, LIST_TYPES): last_node = int(last_node) _, value = changes dest[last_node] = value def remove(node, changes): for key, value in changes: dest = dot_lookup(destination, node) if isinstance(dest, SET_TYPES): dest -= value else: del dest[key] patchers = { REMOVE: remove, ADD: add, CHANGE: change } for action, node, changes in diff_result: patchers[action](node, changes) return destination def swap(diff_result): """Swap the diff result. It uses following mapping: - remove -> add - add -> remove In addition, swap the changed values for `change` flag. >>> from dictdiffer import swap >>> swapped = swap([('add', 'a.b.c', [('a', 'b'), ('c', 'd')])]) >>> next(swapped) ('remove', 'a.b.c', [('c', 'd'), ('a', 'b')]) >>> swapped = swap([('change', 'a.b.c', ('a', 'b'))]) >>> next(swapped) ('change', 'a.b.c', ('b', 'a')) """ def add(node, changes): return REMOVE, node, list(reversed(changes)) def remove(node, changes): return ADD, node, changes def change(node, changes): first, second = changes return CHANGE, node, (second, first) swappers = { REMOVE: remove, ADD: add, CHANGE: change } for action, node, change in diff_result: yield swappers[action](node, change) def revert(diff_result, destination, in_place=False): """Call swap function to revert patched dictionary object. Usage example: >>> from dictdiffer import diff, revert >>> first = {'a': 'b'} >>> second = {'a': 'c'} >>> revert(diff(first, second), second) {'a': 'b'} :param diff_result: Changes returned by ``diff``. :param destination: Structure to apply the changes to. :param in_place: By default, destination dictionary is deep copied before being reverted, and the copy is returned. Setting ``in_place=True`` means that revert will apply the changes directly to and return the destination structure. """ return patch(swap(diff_result), destination, in_place) dictdiffer-0.9.0/dictdiffer/conflict.py000066400000000000000000000046461407627043600201240ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Sub module to recognize conflicts in dictdiffer patches.""" import itertools from .utils import get_path, is_super_path class Conflict(object): """Wrapper class to store and handle two conflicting patches.""" def __init__(self, patch1, patch2): """Initialize Conflict object. :param patch1: First patch tuple :param patch2: Second patch tuple """ self.first_patch = patch1 self.second_patch = patch2 self.take = None def take_patch(self): """Return the patch determined by the *take* attribute.""" if self.take: return self.first_patch if self.take == 'f' else self.second_patch raise Exception('Take attribute not set.') def __repr__(self): """Return string representation.""" return 'Conflict({0}, {1})'.format(self.first_patch, self.second_patch) class ConflictFinder(object): """Responsible for finding conflicting patches.""" def _is_conflict(self, patch1, patch2): """Decide on a conflict between two patches. The conditions are: 1. The paths are identical 2. On of the paths is the super path of the other :param patch1: First patch tuple :param patch2: First patch tuple """ path1 = get_path(patch1) path2 = get_path(patch2) if path1 == path2: return True elif is_super_path(path1, path2) and patch1[0] == 'remove': return True elif is_super_path(path2, path1) and patch2[0] == 'remove': return True return False def find_conflicts(self, first_patches, second_patches): """Find all conflicts between two lists of patches. Iterates over the lists of patches, comparing each patch from list one to each patch from list two. :param first_patches: List of patch tuples :param second_patches: List of patch tuples """ self.conflicts = [Conflict(patch1, patch2) for patch1, patch2 in itertools.product(first_patches, second_patches) if self._is_conflict(patch1, patch2)] return self.conflicts dictdiffer-0.9.0/dictdiffer/merge.py000066400000000000000000000117741407627043600174220ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # Copyright (C) 2017 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Sub module to handle the merging of dictdiffer patches.""" from . import diff from .conflict import ConflictFinder from .resolve import Resolver, UnresolvedConflictsException from .unify import Unifier from .utils import PathLimit class Merger(object): """Class wrapping steps of the automated merging process. Usage: >>> lca = {} >>> first = {'foo': 'bar'} >>> second = {'bar': 'foo'} >>> path_limits = [] >>> actions = {} >>> additional_info = {} >>> m = Merger(lca, first, second, actions, ... path_limits, additional_info) >>> try: ... m.run() ... except UnresolvedConflictsException: ... # fix the conflicts ... m.continue_run() """ def __init__(self, lca, first, second, actions, path_limits=[], additional_info=None): """Initialize the Merger object. :param lca: latest common ancestor of the two diverging data structures :param first: first data structure :param second: second data structure :param path_limits: list of paths, utilized to instantiate a dictdiffer.utils.PathLimit object :param additional_info: Any object containing additional information used by the resolution functions """ self.lca = lca self.first = first self.second = second self.path_limit = PathLimit(path_limits) self.actions = actions self.additional_info = additional_info self.conflict_finder = ConflictFinder() self.resolver = Resolver(self.actions, self.additional_info) self.unifier = Unifier() self.conflicts = [] self.unresolved_conflicts = [] def run(self): """Run the automated merging process. Runs every step necessary for the automated merging process, raising an UnresolvedConflictsException in case that the provided resolution actions can not solve a given conflict. After every performed step, the results are stored inside attributes of the merger object. """ self.extract_patches() self.find_conflicts() self.resolve_conflicts() if self.unresolved_conflicts: raise UnresolvedConflictsException(self.unresolved_conflicts) self.unify_patches() def continue_run(self, picks): """Continue the merge after an UnresolvedConflictsException. :param picks: a list of 'f' or 's' strings, which utilize the Conflicts class *take* attribute """ self.resolver.manual_resolve_conflicts(picks) self.unresolved_conflicts = [] self.unify_patches() def extract_patches(self): """Extract the patches. Extracts the differences between the *lca* and the *first* and *second* data structure and stores them in the attributes *first_patches* and *second_patches*. """ self.first_patches = list(diff(self.lca, self.first, path_limit=self.path_limit, expand=True)) self.second_patches = list(diff(self.lca, self.second, path_limit=self.path_limit, expand=True)) def find_conflicts(self): """Find conflicts between the tow lists of patches. Finds the conflicts between the two difference lists and stores them in the *conflicts* attribute. """ self.conflicts = (self .conflict_finder .find_conflicts(self.first_patches, self.second_patches)) def resolve_conflicts(self): """Resolve the conflicts. Runs the automated conflict resolution process. Occurring unresolvable conflicts are stored in *unresolved_conflicts*. """ try: self.resolver.resolve_conflicts(self.first_patches, self.second_patches, self.conflicts) except UnresolvedConflictsException as e: self.unresolved_conflicts = e.content def unify_patches(self): """Unify the patches after the conflict resolution. Unifies the patches after a successful merge and stores them in *unified_patches*. """ self.unified_patches = self.unifier.unify(self.first_patches, self.second_patches, self.conflicts) dictdiffer-0.9.0/dictdiffer/resolve.py000066400000000000000000000125551407627043600200000ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # Copyright (C) 2017 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Sub module to handle the conflict resolution.""" from .utils import get_path class UnresolvedConflictsException(Exception): """Exception raised in case of an unresolveable conflict. Exception raised in case of conflicts, that can not be resolved using the provided actions in the automated merging process. """ def __init__(self, unresolved_conflicts): """Initialize the UnresolvedConflictsException. :param unresolved_conflicts: list of unresolved conflicts. dictdiffer.conflict.Conflict objects. """ self.message = ("The unresolved conflicts are stored in the *content* " "attribute of this exception or in the " "*unresolved_conflicts* attribute of the " "dictdiffer.merge.Merger object.") self.content = unresolved_conflicts def __repr__(self): """Return the object representation.""" return self.message def __str__(self): """Return the string representation.""" return self.message class NoFurtherResolutionException(Exception): """Exception raised to stop the automated resolution process. Raised in case that the automatic conflict resolution process should stop trying more general keys. """ pass class Resolver(object): """Class handling the conflict resolution process. Presents the given conflicts to actions designed to solve them. """ def __init__(self, actions, additional_info=None): """Initialize the Resolver. :param action: dict object containing the necessary resolution functions :param additional_info: any additional information required by the actions """ self.actions = actions self.additional_info = additional_info self.unresolved_conflicts = [] def _auto_resolve(self, conflict): """Try to auto resolve conflicts. Method trying to auto resolve conflicts in case that the perform the same amendment. """ if conflict.first_patch == conflict.second_patch: conflict.take = 'f' return True return False def _find_conflicting_path(self, conflict): """Return the shortest path commown to two patches.""" p1p = get_path(conflict.first_patch) p2p = get_path(conflict.second_patch) # This returns the shortest path return p1p if len(p1p) <= len(p2p) else p2p def _consecutive_slices(self, iterable): """Build a list of consecutive slices of a given path. >>> r = Resolver(None, None) >>> list(r._consecutive_slices([1, 2, 3])) [[1, 2, 3], [1, 2], [1]] """ return (iterable[:i] for i in reversed(range(1, len(iterable)+1))) def resolve_conflicts(self, first_patches, second_patches, conflicts): """Convert the given conflicts to the actions. The method, will map the conflicts to an actions based on the path of the conflict. In case that the resolution attempt is not successful, it will strip the last element of the path and try again, until the resolution is just not possible. :param first_patches: list of dictdiffer.diff patches :param second_patches: list of dictdiffer.diff patches :param conflicts: list of Conflict objects """ for conflict in conflicts: conflict_path = self._find_conflicting_path(conflict) if self._auto_resolve(conflict): continue # Let's do some cascading here for sub_path in self._consecutive_slices(conflict_path): try: if self.actions[sub_path](conflict, first_patches, second_patches, self.additional_info): break except NoFurtherResolutionException: self.unresolved_conflicts.append(conflict) break except KeyError: pass else: # The conflict could not be resolved self.unresolved_conflicts.append(conflict) if self.unresolved_conflicts: raise UnresolvedConflictsException(self.unresolved_conflicts) def manual_resolve_conflicts(self, picks): """Resolve manually the conflicts. This method resolves conflicts that could not be resolved in an automatic way. The picks parameter utilized the *take* attribute of the Conflict objects. :param picks: list of 'f' or 's' strings, utilizing the *take* parameter of each Conflict object """ if len(picks) != len(self.unresolved_conflicts): raise UnresolvedConflictsException(self.unresolved_conflicts) for pick, conflict in zip(picks, self.unresolved_conflicts): conflict.take = pick self.unresolved_conflicts = [] dictdiffer-0.9.0/dictdiffer/testing.py000066400000000000000000000021421407627043600177650ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2021 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Define helper functions for testing.""" from pprint import pformat from . import diff def assert_no_diff(*args, **kwargs): """Compare two dictionary/list/set objects and raise error on difference. When there is a difference, this will print a formatted diff. This is especially useful for pytest. Usage example: >>> from dictdiffer.testing import assert_no_diff >>> result = {'a': 'b'} >>> expected = {'a': 'c'} >>> assert_no_diff(result, expected) Traceback (most recent call last): File "", line 1, in File "", line 14, in assert_no_diff AssertionError: [('change', 'a', ('b', 'c'))] :param args: Positional arguments to the ``diff`` function. :param second: Named arguments to the ``diff`` function. """ d = [d for d in diff(*args, **kwargs)] assert not d, pformat(d) dictdiffer-0.9.0/dictdiffer/unify.py000066400000000000000000000033711407627043600174470ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Sub module to handle the unification of patches after the merge.""" from .utils import get_path, nested_hash class Unifier(object): """Class handling the unification process after the merge.""" def unify(self, first_patches, second_patches, conflicts): """Unify two lists of patches into one. Takes into account their appearance in the given list of conflicts. :param first_patches: list of dictdiffer.diff patches :param second_patches: list of dictdiffer.diff patches :param conflicts: list of Conflict objects """ self.unified_patches = [] self._build_index(conflicts) sorted_patches = sorted(first_patches + second_patches, key=get_path) for patch in sorted_patches: conflict = self._index.get(nested_hash(patch)) # Apply only the patches that were taken as part of conflict # resolution. if conflict: if conflict.take_patch() != patch: continue self.unified_patches.append(patch) return self.unified_patches def _build_index(self, conflicts): """Create a dictionary attribute mapping patches to conflicts. Creates a dictionary attribute mapping the tuplefied version of each patch to it's containing Conflict object. """ self._index = {} for conflict in conflicts: self._index[nested_hash(conflict.first_patch)] = conflict self._index[nested_hash(conflict.second_patch)] = conflict dictdiffer-0.9.0/dictdiffer/utils.py000066400000000000000000000210731407627043600174540ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # Copyright (C) 2017, 2019 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Utils gathers helper functions, classes for the dictdiffer module.""" import math import sys from itertools import zip_longest num_types = int, float EPSILON = sys.float_info.epsilon class WildcardDict(dict): """Provide possibility to use special wildcard keys to access values. Those wildcards are: *: wildcard for everything that follows +: wildcard for anything on the same path level The intended use case of this are dictionaries, that utilize tuples as keys. >>> from dictdiffer.utils import WildcardDict >>> w = WildcardDict({('foo', '*'): '* card', ... ('banana', '+'): '+ card'}) >>> w[ ('foo', 'bar', 'baz') ] '* card' >>> w[ ('banana', 'apple') ] '+ card' """ def __init__(self, values=None): """Set lookup key indices. :param values: a dictionary """ super(WildcardDict, self).__init__() self.star_keys = set() self.plus_keys = set() if values is not None: for key, value in values.items(): self.__setitem__(key, value) def __getitem__(self, key): """Return the value corresponding to the key, regarding wildcards. If the key doesn't exit it tries the '+' wildcard and then the '*' wildcard. >>> w = WildcardDict({('foo', '*'): '* card', ... ('banana', '+'): '+ card'}) >>> w[ ('foo', 'bar') ] '* card' >>> w[ ('foo', 'bar', 'baz') ] '* card' >>> w[ ('banana', 'apple') ] '+ card' >>> w[ ('banana', 'apple', 'mango') ] Traceback (most recent call last): ... KeyError """ try: return super(WildcardDict, self).__getitem__(key) except KeyError: if key[:-1] in self.plus_keys: return super(WildcardDict, self).__getitem__(key[:-1]+('+',)) for _key in [key[:-i] for i in range(1, len(key)+1)]: if _key in self.star_keys: return super(WildcardDict, self).__getitem__(_key+('*',)) raise KeyError def __setitem__(self, key, value): """Set the item for a given key (path).""" super(WildcardDict, self).__setitem__(key, value) if key[-1] == '+': self.plus_keys.add(key[:-1]) if key[-1] == '*': self.star_keys.add(key[:-1]) def query_path(self, key): """Return the key (path) that matches the queried key. >>> w = WildcardDict({('foo', '*'): 'banana'}) >>> w.query_path(('foo', 'bar', 'baz')) ('foo', '*') """ if key in self: return key if key[:-1] in self.plus_keys: return key[:-1]+('+',) for _key in [key[:-i] for i in range(1, len(key)+1)]: if _key in self.star_keys: return _key+('*',) raise KeyError class PathLimit(object): """Class to limit recursion depth during the dictdiffer.diff execution.""" def __init__(self, path_limits=[], final_key=None): """Initialize a dictionary structure to determine a path limit. :param path_limits: list of keys (tuples) determining the path limits :param final_key: the key used in the dictionary to determin if the path is final >>> pl = PathLimit( [('foo', 'bar')] , final_key='!@#$%FINAL') >>> pl.dict {'foo': {'bar': {'!@#$%FINAL': True}}} """ self.final_key = final_key if final_key else '!@#$FINAL' self.dict = {} for key_path in path_limits: containing = self.dict for key in key_path: try: containing = containing[key] except KeyError: containing[key] = {} containing = containing[key] containing[self.final_key] = True def path_is_limit(self, key_path): """Query the PathLimit object if the given key_path is a limit. >>> pl = PathLimit( [('foo', 'bar')] , final_key='!@#$%FINAL') >>> pl.path_is_limit( ('foo', 'bar') ) True """ containing = self.dict for key in key_path: try: containing = containing[key] except KeyError: try: containing = containing['*'] except KeyError: return False return containing.get(self.final_key, False) def create_dotted_node(node): """Create the *dotted node* notation for the dictdiffer.diff patches. >>> create_dotted_node( ['foo', 'bar', 'baz'] ) 'foo.bar.baz' """ if all(map(lambda x: isinstance(x, str), node)): return '.'.join(node) else: return list(node) def get_path(patch): """Return the path for a given dictdiffer.diff patch.""" if patch[1] != '': keys = (patch[1].split('.') if isinstance(patch[1], str) else patch[1]) else: keys = [] keys = keys + [patch[2][0][0]] if patch[0] != 'change' else keys return tuple(keys) def is_super_path(path1, path2): """Check if one path is the super path of the other. Super path means, that the n values in tuple are equal to the first n of m vales in tuple b. >>> is_super_path( ('foo', 'bar'), ('foo', 'bar') ) True >>> is_super_path( ('foo', 'bar'), ('foo', 'bar', 'baz') ) True >>> is_super_path( ('foo', 'bar'), ('foo', 'apple', 'banana') ) False """ return all(map(lambda x: x[0] == x[1] or x[0] is None, zip_longest(path1, path2))) def nested_hash(obj): """Create a hash of nested, mutable data structures. It shall be noted, that the uniqeness of those hashes in general cases is not assured but it should be enough for the cases occurring during the merging process. """ try: return hash(obj) except TypeError: if isinstance(obj, (list, tuple)): return hash(tuple(map(nested_hash, obj))) elif isinstance(obj, set): return hash(tuple(map(nested_hash, sorted(obj)))) elif isinstance(obj, dict): return hash(tuple(map(nested_hash, sorted(obj.items())))) def dot_lookup(source, lookup, parent=False): """Allow you to reach dictionary items with string or list lookup. Recursively find value by lookup key split by '.'. >>> from dictdiffer.utils import dot_lookup >>> dot_lookup({'a': {'b': 'hello'}}, 'a.b') 'hello' If parent argument is True, returns the parent node of matched object. >>> dot_lookup({'a': {'b': 'hello'}}, 'a.b', parent=True) {'b': 'hello'} If node is empty value, returns the whole dictionary object. >>> dot_lookup({'a': {'b': 'hello'}}, '') {'a': {'b': 'hello'}} """ if lookup is None or lookup == '' or lookup == []: return source value = source if isinstance(lookup, str): keys = lookup.split('.') elif isinstance(lookup, list): keys = lookup else: raise TypeError('lookup must be string or list') if parent: keys = keys[:-1] for key in keys: if isinstance(value, list): key = int(key) value = value[key] return value def are_different(first, second, tolerance, absolute_tolerance=None): """Check if 2 values are different. In case of numerical values, the tolerance is used to check if the values are different. In all other cases, the difference is straight forward. """ if first == second: # values are same - simple case return False first_is_nan, second_is_nan = bool(first != first), bool(second != second) if first_is_nan or second_is_nan: # two 'NaN' values are not different (see issue #114) return not (first_is_nan and second_is_nan) elif isinstance(first, num_types) and isinstance(second, num_types): # two numerical values are compared with tolerance return not math.isclose( first, second, rel_tol=tolerance or 0, abs_tol=absolute_tolerance or 0, ) # we got different values return True dictdiffer-0.9.0/dictdiffer/version.py000066400000000000000000000003031407627043600177720ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Do not change the format of this next line. Doing so risks breaking # setup.py and docs/conf.py """Version information for dictdiffer package.""" __version__ = '0.9.0' dictdiffer-0.9.0/docs/000077500000000000000000000000001407627043600145645ustar00rootroot00000000000000dictdiffer-0.9.0/docs/Makefile000066400000000000000000000155201407627043600162270ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2014 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. # Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Dictdiffer.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Dictdiffer.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Dictdiffer" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Dictdiffer" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." dictdiffer-0.9.0/docs/conf.py000066400000000000000000000217701407627043600160720ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # This file is part of Dictdiffer. # # Copyright (C) 2014, 2016 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. # # Dictdiffer documentation build configuration file, created by # sphinx-quickstart on Tue Aug 26 12:50:15 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. """Sphinx configuration.""" from __future__ import print_function import sys from pkg_resources import get_distribution _html_theme = "sphinx_rtd_theme" _html_theme_path = [] try: import sphinx_rtd_theme _html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except ImportError: print("Template {0} not found, pip install it", file=sys.stderr) _html_theme = "default" # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Do not warn on external images. suppress_warnings = ['image.nonlocal_uri'] # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Dictdiffer' copyright = u'2014, Fatih Erikli' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = get_distribution('dictdiffer').version # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'default' html_theme = _html_theme # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] html_theme_path = _html_theme_path # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Dictdifferdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Dictdiffer.tex', u'Dictdiffer Documentation', u'Fatih Erikli', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'dictdiffer', u'Dictdiffer Documentation', [u'Fatih Erikli'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Dictdiffer', u'Dictdiffer Documentation', u'Fatih Erikli', 'Dictdiffer', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('https://docs.python.org/2.7', None), } dictdiffer-0.9.0/docs/index.rst000066400000000000000000000061631407627043600164330ustar00rootroot00000000000000========== Dictdiffer ========== .. currentmodule:: dictdiffer .. image:: https://github.com/inveniosoftware/dictdiffer/workflows/CI/badge.svg :target: https://github.com/inveniosoftware/dictdiffer/actions .. image:: https://img.shields.io/coveralls/inveniosoftware/dictdiffer.svg :target: https://coveralls.io/r/inveniosoftware/dictdiffer .. image:: https://img.shields.io/github/tag/inveniosoftware/dictdiffer.svg :target: https://github.com/inveniosoftware/dictdiffer/releases .. image:: https://img.shields.io/pypi/dm/dictdiffer.svg :target: https://pypi.python.org/pypi/dictdiffer .. image:: https://img.shields.io/github/license/inveniosoftware/dictdiffer.svg :target: https://github.com/inveniosoftware/dictdiffer/blob/master/LICENSE Dictdiffer is a helper module that helps you to diff and patch dictionaries. Installation ============ Dictdiffer is on PyPI so all you need is: .. code-block:: console $ pip install dictdiffer Usage ===== Let's start with an example on how to find the diff between two dictionaries using :func:`.diff` method: .. code-block:: python from dictdiffer import diff, patch, swap, revert first = { "title": "hello", "fork_count": 20, "stargazers": ["/users/20", "/users/30"], "settings": { "assignees": [100, 101, 201], } } second = { "title": "hellooo", "fork_count": 20, "stargazers": ["/users/20", "/users/30", "/users/40"], "settings": { "assignees": [100, 101, 202], } } result = diff(first, second) assert list(result) == [ ('change', ['settings', 'assignees', 2], (201, 202)), ('add', 'stargazers', [(2, '/users/40')]), ('change', 'title', ('hello', 'hellooo'))] Now we can apply the diff result with :func:`.patch` method: .. code-block:: python result = diff(first, second) patched = patch(result, first) assert patched == second Also we can swap the diff result with :func:`.swap` method: .. code-block:: python result = diff(first, second) swapped = swap(result) assert list(swapped) == [ ('change', ['settings', 'assignees', 2], (202, 201)), ('remove', 'stargazers', [(2, '/users/40')]), ('change', 'title', ('hellooo', 'hello'))] Let's revert the last changes: .. code-block:: python result = diff(first, second) reverted = revert(result, patched) assert reverted == first A tolerance can be used to consider closed values as equal. The tolerance parameter only applies for int and float. Let's try with a tolerance of 10% with the values 10 and 10.5: .. code-block:: python first = {'a': 10.0} second = {'a': 10.5} result = diff(first, second, tolerance=0.1) assert list(result) == [] Now with a tolerance of 1%: .. code-block:: python result = diff(first, second, tolerance=0.01) assert list(result) == ('change', 'a', (10.0, 10.5)) API === .. automodule:: dictdiffer :members: .. include:: ../CHANGES .. include:: ../CONTRIBUTING.rst License ======= .. include:: ../LICENSE .. include:: ../AUTHORS dictdiffer-0.9.0/docs/requirements.txt000066400000000000000000000000211407627043600200410ustar00rootroot00000000000000-e .[docs,tests] dictdiffer-0.9.0/pytest.ini000066400000000000000000000006741407627043600156740ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2014, 2016 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. [pytest] addopts = --isort --pydocstyle --pycodestyle --doctest-glob="*.rst" --doctest-modules --cov=dictdiffer --cov-report=term-missing testpaths = tests dictdiffer filterwarnings = ignore::pytest.PytestDeprecationWarning dictdiffer-0.9.0/run-tests.sh000077500000000000000000000012061407627043600161360ustar00rootroot00000000000000#!/usr/bin/env bash # -*- coding: utf-8 -*- # # This file is part of Dictdiffer. # # Copyright (C) 2013 Fatih Erikli. # Copyright (C) 2014, 2016 CERN. # Copyright (C) 2019 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. # Quit on errors set -o errexit # Quit on unbound symbols set -o nounset python -m check_manifest --ignore ".*-requirements.txt" python -m sphinx.cmd.build -qnNW docs docs/_build/html python -m pytest python -m sphinx.cmd.build -qnNW -b doctest docs docs/_build/doctest dictdiffer-0.9.0/setup.cfg000066400000000000000000000005241407627043600154560ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2016 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. [aliases] test = pytest [build_sphinx] source-dir = docs/ build-dir = docs/_build all_files = 1 [bdist_wheel] universal = 1 dictdiffer-0.9.0/setup.py000066400000000000000000000060631407627043600153530ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2013 Fatih Erikli. # Copyright (C) 2014, 2015, 2016 CERN. # Copyright (C) 2017, 2019 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. """Dictdiffer is a library that helps you to diff and patch dictionaries.""" from __future__ import absolute_import, print_function import os from setuptools import find_packages, setup readme = open('README.rst').read() tests_require = [ 'check-manifest>=0.42', 'mock>=1.3.0', 'pytest==5.4.3;python_version<="3.5"', 'pytest>=6;python_version>"3.5"', 'pytest-cov>=2.10.1', 'pytest-isort>=1.2.0', 'pytest-pycodestyle>=2;python_version<="3.5"', 'pytest-pycodestyle>=2.2.0;python_version>"3.5"', 'pytest-pydocstyle>=2;python_version<="3.5"', 'pytest-pydocstyle>=2.2.0;python_version>"3.5"', 'sphinx>=3', 'tox>=3.7.0', ] extras_require = { 'docs': [ 'Sphinx>=3', 'sphinx-rtd-theme>=0.2', ], 'numpy': [ 'numpy>=1.13.0;python_version<"3.7"', 'numpy>=1.15.0;python_version<"3.8"', 'numpy>=1.18.0;python_version<"3.9"', 'numpy>=1.20.0;python_version>="3.9"', ], 'tests': tests_require, } extras_require['all'] = [] for key, reqs in extras_require.items(): if ':' == key[0]: continue extras_require['all'].extend(reqs) setup_requires = [ 'pytest-runner>=2.7', 'setuptools_scm>=3.1.0', ] packages = find_packages() version_template = """\ # -*- coding: utf-8 -*- # Do not change the format of this next line. Doing so risks breaking # setup.py and docs/conf.py \"\"\"Version information for dictdiffer package.\"\"\" __version__ = {version!r} """ setup( name='dictdiffer', use_scm_version={ 'local_scheme': 'dirty-tag', 'write_to': os.path.join('dictdiffer', 'version.py'), 'write_to_template': version_template, }, description=__doc__, long_description=readme, author='Invenio Collaboration', author_email='info@inveniosoftware.org', url='https://github.com/inveniosoftware/dictdiffer', project_urls={ 'Changelog': ( 'https://github.com/inveniosoftware/dictdiffer' '/blob/master/CHANGES' ), 'Docs': 'https://dictdiffer.rtfd.io/', }, packages=['dictdiffer'], zip_safe=False, extras_require=extras_require, setup_requires=setup_requires, tests_require=tests_require, classifiers=[ 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Utilities', ], ) dictdiffer-0.9.0/tests/000077500000000000000000000000001407627043600147765ustar00rootroot00000000000000dictdiffer-0.9.0/tests/test_conflict.py000066400000000000000000000045641407627043600202210ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest from dictdiffer.conflict import Conflict, ConflictFinder class ConflictTest(unittest.TestCase): def test_init(self): p1 = ('add', '', [(0, 0)]) p2 = ('add', '', [(1, 2)]) c = Conflict(p1, p2) self.assertEqual(c.first_patch, p1) self.assertEqual(c.second_patch, p2) self.assertEqual(c.take, None) def test_take_patch(self): p1 = ('add', '', [(1, 1)]) p2 = ('add', '', [(1, -1)]) c = Conflict(p1, p2) self.assertRaises(Exception, c.take_patch) c.take = 'f' self.assertEqual(c.take_patch(), p1) c.take = 's' self.assertEqual(c.take_patch(), p2) class ConflictFinderTest(unittest.TestCase): def test_is_conflict(self): # SAME LENGTH NO CONFLICT p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(2, 0)]) c = ConflictFinder() self.assertFalse(c._is_conflict(p1, p2)) p1 = ('add', 'foo.bar', [(0, 0)]) p2 = ('add', 'foo.bar', [(2, 0)]) c = ConflictFinder() self.assertFalse(c._is_conflict(p1, p2)) # SAME LENGTH CONFLICT p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 0)]) c = ConflictFinder() self.assertTrue(c._is_conflict(p1, p2)) p1 = ('add', 'foo.bar', [(0, 0)]) p2 = ('add', 'foo.bar', [(0, 0)]) c = ConflictFinder() self.assertTrue(c._is_conflict(p1, p2)) # SUPER PATH p1 = ('remove', '', [('foo', [])]) p2 = ('add', 'foo.bar', [(0, 0)]) c = ConflictFinder() self.assertTrue(c._is_conflict(p1, p2)) p1 = ('add', 'foo.bar', [(0, 0)]) p2 = ('remove', '', [('foo', [])]) c = ConflictFinder() self.assertTrue(c._is_conflict(p1, p2)) def test_find_conflicts(self): p11 = ('add', 'foo.bar', [(0, 0)]) p12 = ('add', 'foo', [(0, 0)]) p21 = ('add', 'foo.bar', [(0, 0)]) p22 = ('add', 'foo', [(1, 0)]) conflicts = [Conflict(p11, p21)] c = ConflictFinder() self.assertEqual(repr(c.find_conflicts([p11, p12], [p21, p22])), repr(conflicts)) dictdiffer-0.9.0/tests/test_dictdiffer.py000066400000000000000000000611061407627043600205160ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # This file is part of Dictdiffer. # # Copyright (C) 2013 Fatih Erikli. # Copyright (C) 2013, 2014, 2015, 2016 CERN. # Copyright (C) 2017-2019 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest from collections import OrderedDict from collections.abc import MutableMapping, MutableSequence import pytest from dictdiffer import HAS_NUMPY, diff, dot_lookup, patch, revert, swap from dictdiffer.utils import PathLimit class DictDifferTests(unittest.TestCase): def test_without_dot_notation(self): (change1,) = diff({'a': {'x': 1}}, {'a': {'x': 2}}, dot_notation=False) assert change1 == ('change', ['a', 'x'], (1, 2)) def test_with_dot_notation(self): (change1,) = diff({'a': {'x': 1}}, {'a': {'x': 2}}) assert change1 == ('change', 'a.x', (1, 2)) def test_addition(self): first = {} second = {'a': 'b'} diffed = next(diff(first, second)) assert ('add', '', [('a', 'b')]) == diffed def test_deletion(self): first = {'a': 'b'} second = {} diffed = next(diff(first, second)) assert ('remove', '', [('a', 'b')]) == diffed def test_change(self): first = {'a': 'b'} second = {'a': 'c'} diffed = next(diff(first, second)) assert ('change', 'a', ('b', 'c')) == diffed first = {'a': None} second = {'a': 'c'} diffed = next(diff(first, second)) assert ('change', 'a', (None, 'c')) == diffed first = {'a': 'c'} second = {'a': None} diffed = next(diff(first, second)) assert ('change', 'a', ('c', None)) == diffed first = {'a': 'c'} second = {'a': u'c'} diffed = list(diff(first, second)) assert [] == diffed first = {'a': 'b'} second = {'a': None} diffed = next(diff(first, second)) assert ('change', 'a', ('b', None)) == diffed first = {'a': 10.0} second = {'a': 10.5} diffed = next(diff(first, second)) assert ('change', 'a', (10.0, 10.5)) == diffed def test_immutable_diffs(self): first = {'a': 'a'} second = {'a': {'b': 'b'}} result = list(diff(first, second)) assert result[0][2][1]['b'] == 'b' second['a']['b'] = 'c' # result MUST stay unchanged assert result[0][2][1]['b'] == 'b' def test_tolerance(self): first = {'a': 'b'} second = {'a': 'c'} diffed = next(diff(first, second, tolerance=0.1)) assert ('change', 'a', ('b', 'c')) == diffed first = {'a': None} second = {'a': 'c'} diffed = next(diff(first, second, tolerance=0.1)) assert ('change', 'a', (None, 'c')) == diffed first = {'a': 10.0} second = {'a': 10.5} diffed = list(diff(first, second, tolerance=0.1)) assert [] == diffed diffed = next(diff(first, second, tolerance=0.01)) assert ('change', 'a', (10.0, 10.5)) == diffed first = {'a': 10.0, 'b': 1.0e-15} second = {'a': 10.5, 'b': 2.5e-15} diffed = sorted(diff( first, second, tolerance=0.01 )) assert [ ('change', 'a', (10.0, 10.5)), ('change', 'b', (1.0e-15, 2.5e-15)), ] == diffed diffed = sorted(diff( first, second, tolerance=0.01, absolute_tolerance=1e-12 )) assert [('change', 'a', (10.0, 10.5))] == diffed diffed = sorted(diff( first, second, tolerance=0.01, absolute_tolerance=1e-18 )) assert [ ('change', 'a', (10.0, 10.5)), ('change', 'b', (1.0e-15, 2.5e-15)), ] == diffed diffed = sorted(diff( first, second, tolerance=0.1, absolute_tolerance=1e-18 )) assert [('change', 'b', (1.0e-15, 2.5e-15))] == diffed diffed = sorted(diff( first, second, tolerance=0.1, absolute_tolerance=1e-12 )) assert [] == diffed diffed = sorted(diff( first, second, tolerance=None, absolute_tolerance=None )) assert [ ('change', 'a', (10.0, 10.5)), ('change', 'b', (1.0e-15, 2.5e-15)), ] == diffed first = {'a': 10.0, 'b': 1.0e-15} second = {'a': 10.0, 'b': 1.0e-15} diffed = sorted(diff( first, second, tolerance=None, absolute_tolerance=None )) assert [] == diffed def test_path_limit_as_list(self): first = {} second = {'author': {'last_name': 'Doe', 'first_name': 'John'}} diffed = list(diff(first, second, path_limit=[('author',)])) res = [('add', '', [('author', {'first_name': 'John', 'last_name': 'Doe'})])] assert res == diffed def test_path_limit_addition(self): first = {} second = {'author': {'last_name': 'Doe', 'first_name': 'John'}} p = PathLimit([('author',)]) diffed = list(diff(first, second, path_limit=p)) res = [('add', '', [('author', {'first_name': 'John', 'last_name': 'Doe'})])] assert res == diffed first = {} second = {'author': {'last_name': 'Doe', 'first_name': 'John'}} p = PathLimit([('author',)]) diffed = list(diff(first, second, path_limit=p, expand=True)) res = [('add', '', [('author', {'first_name': 'John', 'last_name': 'Doe'})])] assert res == diffed first = {} second = {'author': {'last_name': 'Doe', 'first_name': 'John'}} p = PathLimit() diffed = list(diff(first, second, path_limit=p, expand=True)) res = [('add', '', [('author', {})]), ('add', 'author', [('first_name', 'John')]), ('add', 'author', [('last_name', 'Doe')])] assert len(diffed) == 3 for patch in res: assert patch in diffed def test_path_limit_deletion(self): first = {'author': {'last_name': 'Doe', 'first_name': 'John'}} second = {} p = PathLimit([('author',)]) diffed = list(diff(first, second, path_limit=p, expand=True)) res = [('remove', '', [('author', {'first_name': 'John', 'last_name': 'Doe'})])] assert res == diffed def test_path_limit_change(self): first = {'author': {'last_name': 'Do', 'first_name': 'John'}} second = {'author': {'last_name': 'Doe', 'first_name': 'John'}} p = PathLimit([('author',)]) diffed = list(diff(first, second, path_limit=p, expand=True)) res = [('change', ['author'], ({'first_name': 'John', 'last_name': 'Do'}, {'first_name': 'John', 'last_name': 'Doe'}))] assert res == diffed first = {'author': {'last_name': 'Do', 'first_name': 'John'}} second = {'author': {'last_name': 'Doe', 'first_name': 'John'}} p = PathLimit() diffed = list(diff(first, second, path_limit=p, expand=True)) res = [('change', 'author.last_name', ('Do', 'Doe'))] assert res == diffed def test_expand_addition(self): first = {} second = {'foo': 'bar', 'apple': 'banana'} diffed = list(diff(first, second, expand=True)) res = [('add', '', [('foo', 'bar')]), ('add', '', [('apple', 'banana')])] assert len(diffed) == 2 for patch in res: assert patch in diffed def test_expand_deletion(self): first = {'foo': 'bar', 'apple': 'banana'} second = {} diffed = list(diff(first, second, expand=True)) res = [('remove', '', [('foo', 'bar')]), ('remove', '', [('apple', 'banana')])] assert len(diffed) == 2 for patch in res: assert patch in diffed def test_nodes(self): first = {'a': {'b': {'c': 'd'}}} second = {'a': {'b': {'c': 'd', 'e': 'f'}}} diffed = next(diff(first, second)) assert ('add', 'a.b', [('e', 'f')]) == diffed def test_add_list(self): first = {'a': []} second = {'a': ['b']} diffed = next(diff(first, second)) assert ('add', 'a', [(0, 'b')]) == diffed def test_remove_list(self): first = {'a': ['b', 'c']} second = {'a': []} diffed = next(diff(first, second)) assert ('remove', 'a', [(1, 'c'), (0, 'b'), ]) == diffed def test_add_set(self): first = {'a': {1, 2, 3}} second = {'a': {0, 1, 2, 3}} diffed = next(diff(first, second)) assert ('add', 'a', [(0, set([0]))]) == diffed def test_remove_set(self): first = {'a': set([0, 1, 2, 3])} second = {'a': set([1, 2, 3])} diffed = next(diff(first, second)) assert ('remove', 'a', [(0, set([0]))]) == diffed def test_change_set(self): first = {'a': set([0, 1, 2, 3])} second = {'a': set([1, 2, 3, 4])} diffed = list(diff(first, second)) assert ('add', 'a', [(0, set([4]))]) in diffed assert ('remove', 'a', [(0, set([0]))]) in diffed def test_add_set_shift_order(self): first = set(["changeA", "changeB"]) second = set(["changeA", "changeC", "changeB"]) diffed = list(diff(first, second)) # There should only be 1 change reported assert len(diffed) == 1 assert ('add', '', [(0, {'changeC'})]) in diffed def test_change_set_order(self): first = set(["changeA", "changeC", "changeB"]) second = set(["changeB", "changeC", "changeA"]) diffed = list(diff(first, second)) # There should be zero reported diffs assert len(diffed) == 0 def test_types(self): first = {'a': ['a']} second = {'a': 'a'} diffed = next(diff(first, second)) assert ('change', 'a', (['a'], 'a')) == diffed def test_nan(self): value = float('nan') diffed = list(diff([value], [value])) assert [] == diffed diffed = list(diff([value], [3.5])) assert [('change', [0], (value, 3.5))] == diffed @unittest.skipIf(not HAS_NUMPY, 'NumPy is not installed') def test_numpy_nan(self): """Compare NumPy NaNs (#114).""" import numpy as np first = {'a': np.float32('nan')} second = {'a': float('nan')} result = list(diff(first, second)) assert result == [] def test_unicode_keys(self): first = {u'привет': 1} second = {'hello': 1} diffed = list(diff(first, second)) assert ('add', '', [('hello', 1)]) in diffed assert ('remove', '', [(u'привет', 1)]) in diffed diffed = list(diff(first, second, ignore=['hello'])) assert ('remove', '', [(u'привет', 1)]) == diffed[0] diffed = list(diff(first, second, ignore=[u'привет'])) assert ('add', '', [('hello', 1)]) == diffed[0] def test_dotted_key(self): first = {'a.b': {'c.d': 1}} second = {'a.b': {'c.d': 2}} diffed = list(diff(first, second)) assert [('change', ['a.b', 'c.d'], (1, 2))] == diffed def test_ignore_key(self): first = {'a': 'a', 'b': 'b', 'c': 'c'} second = {'a': 'a', 'b': 2, 'c': 3} diffed = next(diff(first, second, ignore=['b'])) assert ('change', 'c', ('c', 3)) == diffed def test_ignore_dotted_key(self): first = {'a': {'aa': 'A', 'ab': 'B', 'ac': 'C'}} second = {'a': {'aa': 1, 'ab': 'B', 'ac': 3}} diffed = next(diff(first, second, ignore=['a.aa'])) assert ('change', 'a.ac', ('C', 3)) == diffed def test_ignore_with_unicode_sub_keys(self): first = {u'a': {u'aא': {u'aa': 'A'}}} second = {u'a': {u'aא': {u'aa': 'B'}}} assert len(list(diff(first, second))) == 1 assert len(list(diff(first, second, ignore=[u'a.aא.aa']))) == 0 assert len( list(diff(first, second, ignore=[[u'a', u'aא', u'aa'] ]))) == 0 def test_ignore_complex_key(self): first = {'a': {1: {'a': 'a', 'b': 'b'}}} second = {'a': {1: {'a': 1, 'b': 2}}} diffed = next(diff(first, second, ignore=[['a', 1, 'a']])) assert ('change', ['a', 1, 'b'], ('b', 2)) == diffed def test_ignore_missing_keys(self): first = {'a': 'a'} second = {'a': 'a', 'b': 'b'} assert len(list(diff(first, second, ignore=['b']))) == 0 assert len(list(diff(second, first, ignore=['b']))) == 0 def test_ignore_missing_complex_keys(self): first = {'a': {1: {'a': 'a', 'b': 'b'}}} second = {'a': {1: {'a': 1}}} diffed = next(diff(first, second, ignore=[['a', 1, 'b']])) assert ('change', ['a', 1, 'a'], ('a', 1)) == diffed diffed = next(diff(second, first, ignore=[['a', 1, 'b']])) assert ('change', ['a', 1, 'a'], (1, 'a')) == diffed def test_ignore_stringofintegers_keys(self): a = {'1': '1', '2': '2', '3': '3'} b = {'1': '1', '2': '2', '3': '99', '4': '100'} assert list(diff(a, b, ignore={'3', '4'})) == [] def test_ignore_integers_keys(self): a = {1: 1, 2: 2, 3: 3} b = {1: 1, 2: 2, 3: 99, 4: 100} assert len(list(diff(a, b, ignore={3, 4}))) == 0 def test_ignore_with_ignorecase(self): class IgnoreCase(set): def __contains__(self, key): return set.__contains__(self, str(key).lower()) assert list(diff({'a': 1, 'b': 2}, {'A': 3, 'b': 4}, ignore=IgnoreCase('a'))) == [('change', 'b', (2, 4))] def test_complex_diff(self): """Check regression on issue #4.""" from decimal import Decimal d1 = { 'id': 1, 'code': None, 'type': u'foo', 'bars': [ {'id': 6934900}, {'id': 6934977}, {'id': 6934992}, {'id': 6934993}, {'id': 6935014}], 'n': 10, 'date_str': u'2013-07-08 00:00:00', 'float_here': 0.454545, 'complex': [{ 'id': 83865, 'goal': Decimal('2.000000'), 'state': u'active'}], 'profile_id': None, 'state': u'active' } d2 = { 'id': u'2', 'code': None, 'type': u'foo', 'bars': [ {'id': 6934900}, {'id': 6934977}, {'id': 6934992}, {'id': 6934993}, {'id': 6935014}], 'n': 10, 'date_str': u'2013-07-08 00:00:00', 'float_here': 0.454545, 'complex': [{ 'id': 83865, 'goal': Decimal('2.000000'), 'state': u'active'}], 'profile_id': None, 'state': u'active' } assert len(list(diff(d1, {}))) > 0 assert d1['id'] == 1 assert d2['id'] == u'2' assert d1 is not d2 assert d1 != d2 assert len(list(diff(d1, d2))) > 0 def test_list_change(self): """Produced diffs should not contain empty list instructions (#30).""" first = {"a": {"b": [100, 101, 201]}} second = {"a": {"b": [100, 101, 202]}} result = list(diff(first, second)) assert len(result) == 1 assert result == [('change', ['a', 'b', 2], (201, 202))] def test_list_same(self): """Diff for the same list should be empty.""" first = {1: [1]} assert len(list(diff(first, first))) == 0 @unittest.skipIf(not HAS_NUMPY, 'NumPy is not installed') def test_numpy_array(self): """Compare NumPy arrays (#68).""" import numpy as np first = np.array([1, 2, 3]) second = np.array([1, 2, 4]) result = list(diff(first, second)) assert result == [('change', [2], (3, 4))] def test_dict_subclasses(self): class Foo(dict): pass first = Foo({2014: [ dict(month=6, category=None, sum=672.00), dict(month=6, category=1, sum=-8954.00), dict(month=7, category=None, sum=7475.17), dict(month=7, category=1, sum=-11745.00), dict(month=8, category=None, sum=-12140.00), dict(month=8, category=1, sum=-11812.00), dict(month=9, category=None, sum=-31719.41), dict(month=9, category=1, sum=-11663.00), ]}) second = Foo({2014: [ dict(month=6, category=None, sum=672.00), dict(month=6, category=1, sum=-8954.00), dict(month=7, category=None, sum=7475.17), dict(month=7, category=1, sum=-11745.00), dict(month=8, category=None, sum=-12141.00), dict(month=8, category=1, sum=-11812.00), dict(month=9, category=None, sum=-31719.41), dict(month=9, category=2, sum=-11663.00), ]}) diffed = next(diff(first, second)) assert ('change', [2014, 4, 'sum'], (-12140.0, -12141.0)) == diffed def test_collection_subclasses(self): class DictA(MutableMapping): def __init__(self, *args, **kwargs): self.__dict__.update(*args, **kwargs) def __setitem__(self, key, value): self.__dict__[key] = value def __getitem__(self, key): return self.__dict__[key] def __delitem__(self, key): del self.__dict__[key] def __iter__(self): return iter(self.__dict__) def __len__(self): return len(self.__dict__) class DictB(MutableMapping): def __init__(self, *args, **kwargs): self.__dict__.update(*args, **kwargs) def __setitem__(self, key, value): self.__dict__[key] = value def __getitem__(self, key): return self.__dict__[key] def __delitem__(self, key): del self.__dict__[key] def __iter__(self): return iter(self.__dict__) def __len__(self): return len(self.__dict__) class ListA(MutableSequence): def __init__(self, *args, **kwargs): self._list = list(*args, **kwargs) def __getitem__(self, index): return self._list[index] def __setitem__(self, index, value): self._list[index] = value def __delitem__(self, index): del self._list[index] def __iter__(self): for value in self._list: yield value def __len__(self): return len(self._list) def insert(self, index, value): self._list.insert(index, value) daa = DictA(a=ListA(['a', 'A'])) dba = DictB(a=ListA(['a', 'A'])) dbb = DictB(a=ListA(['b', 'A'])) assert list(diff(daa, dba)) == [] assert list(diff(daa, dbb)) == [('change', ['a', 0], ('a', 'b'))] assert list(diff(dba, dbb)) == [('change', ['a', 0], ('a', 'b'))] class DiffPatcherTests(unittest.TestCase): def test_addition(self): first = {} second = {'a': 'b'} assert second == patch( [('add', '', [('a', 'b')])], first) first = {'a': {'b': 'c'}} second = {'a': {'b': 'c', 'd': 'e'}} assert second == patch( [('add', 'a', [('d', 'e')])], first) def test_changes(self): first = {'a': 'b'} second = {'a': 'c'} assert second == patch( [('change', 'a', ('b', 'c'))], first) first = {'a': {'b': {'c': 'd'}}} second = {'a': {'b': {'c': 'e'}}} assert second == patch( [('change', 'a.b.c', ('d', 'e'))], first) def test_remove(self): first = {'a': {'b': 'c'}} second = {'a': {}} assert second == patch( [('remove', 'a', [('b', 'c')])], first) first = {'a': 'b'} second = {} assert second == patch( [('remove', '', [('a', 'b')])], first) def test_remove_list(self): first = {'a': [1, 2, 3]} second = {'a': [1, ]} assert second == patch( [('remove', 'a', [(2, 3), (1, 2), ]), ], first) def test_add_list(self): first = {'a': [1]} second = {'a': [1, 2]} assert second == patch( [('add', 'a', [(1, 2)])], first) first = {'a': {'b': [1]}} second = {'a': {'b': [1, 2]}} assert second == patch( [('add', 'a.b', [(1, 2)])], first) def test_change_list(self): first = {'a': ['b']} second = {'a': ['c']} assert second == patch( [('change', 'a.0', ('b', 'c'))], first) first = {'a': {'b': {'c': ['d']}}} second = {'a': {'b': {'c': ['e']}}} assert second == patch( [('change', 'a.b.c.0', ('d', 'e'))], first) first = {'a': {'b': {'c': [{'d': 'e'}]}}} second = {'a': {'b': {'c': [{'d': 'f'}]}}} assert second == patch( [('change', 'a.b.c.0.d', ('e', 'f'))], first) def test_remove_set(self): first = {'a': set([1, 2, 3])} second = {'a': set([1])} assert second == patch( [('remove', 'a', [(0, set([2, 3]))])], first) def test_add_set(self): first = {'a': set([1])} second = {'a': set([1, 2])} assert second == patch( [('add', 'a', [(0, set([2]))])], first) def test_dict_int_key(self): first = {0: 0} second = {0: 'a'} first_patch = [('change', [0], (0, 'a'))] assert second == patch(first_patch, first) def test_dict_combined_key_type(self): first = {0: {'1': {2: 3}}} second = {0: {'1': {2: '3'}}} first_patch = [('change', [0, '1', 2], (3, '3'))] assert second == patch(first_patch, first) assert first_patch[0] == list(diff(first, second))[0] def test_in_place_patch_and_revert(self): first = {'a': 1} second = {'a': 2} changes = list(diff(first, second)) patched_copy = patch(changes, first) assert first != patched_copy reverted_in_place = revert(changes, patched_copy, in_place=True) assert first == reverted_in_place assert patched_copy == reverted_in_place patched_in_place = patch(changes, first, in_place=True) assert first == patched_in_place class SwapperTests(unittest.TestCase): def test_addition(self): result = 'add', '', [('a', 'b')] swapped = 'remove', '', [('a', 'b')] assert next(swap([result])) == swapped result = 'remove', 'a.b', [('c', 'd')] swapped = 'add', 'a.b', [('c', 'd')] assert next(swap([result])) == swapped def test_changes(self): result = 'change', '', ('a', 'b') swapped = 'change', '', ('b', 'a') assert next(swap([result])) == swapped def test_revert(self): first = {'a': [1, 2]} second = {'a': []} diffed = diff(first, second) patched = patch(diffed, first) assert patched == second diffed = diff(first, second) reverted = revert(diffed, second) assert reverted == first def test_list_of_different_length(self): """Check that one can revert list with different length.""" first = [1] second = [1, 2, 3] result = list(diff(first, second)) assert first == revert(result, second) class DotLookupTest(unittest.TestCase): def test_list_lookup(self): source = {0: '0'} assert dot_lookup(source, [0]) == '0' def test_invalit_lookup_type(self): self.assertRaises(TypeError, dot_lookup, {0: '0'}, 0) @pytest.mark.parametrize( 'ignore,dot_notation,diff_size', [ (u'nifi.zookeeper.session.timeout', True, 1), (u'nifi.zookeeper.session.timeout', False, 0), ((u'nifi.zookeeper.session.timeout', ), True, 0), ((u'nifi.zookeeper.session.timeout', ), False, 0), ], ) def test_ignore_dotted_ignore_key(ignore, dot_notation, diff_size): key_to_ignore = u'nifi.zookeeper.session.timeout' config_dict = OrderedDict( [('address', 'devops011-slv-01.gvs.ggn'), (key_to_ignore, '3 secs')]) ref_dict = OrderedDict( [('address', 'devops011-slv-01.gvs.ggn'), (key_to_ignore, '4 secs')]) assert diff_size == len( list(diff(config_dict, ref_dict, dot_notation=dot_notation, ignore=[ignore]))) if __name__ == "__main__": unittest.main() dictdiffer-0.9.0/tests/test_merge.py000066400000000000000000000036721407627043600175160ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest from dictdiffer import patch from dictdiffer.merge import Merger, UnresolvedConflictsException class MergerTest(unittest.TestCase): def test_run(self): lca = {'changeme': 'Jo'} first = {'changeme': 'Joe'} second = {'changeme': 'John'} m = Merger(lca, first, second, {}) self.assertRaises(UnresolvedConflictsException, m.run) def test_continue_run(self): def take_first(conflict, _, __, ___): conflict.take = [('f', x) for x in range(len(conflict.first_patch.patches))] return True lca = {'changeme': 'Jo'} first = {'changeme': 'Joe'} second = {'changeme': 'John'} m = Merger(lca, first, second, {}) try: m.run() except UnresolvedConflictsException: pass m.continue_run(['f']) self.assertEqual(m.unified_patches, [('change', 'changeme', ('Jo', 'Joe'))]) def test_continue_run_multiple_conflicts_per_patch(self): lca = {'foo': [{'x': 1}, {'y': 2}]} first = {'foo': [{'x': 1}, {'y': 2}, {'z': 4}]} second = {'bar': 'baz'} expected = { 'f': {'foo': [{'x': 1}, {'y': 2}, {'z': 4}], 'bar': 'baz'}, 's': {'bar': 'baz'}} for resolution, expected_value in expected.items(): m = Merger(lca, first, second, {}) try: m.run() except UnresolvedConflictsException as e: m.continue_run([resolution for _ in e.content]) self.assertEqual(patch(m.unified_patches, lca), expected_value) if __name__ == '__main__': unittest.main() dictdiffer-0.9.0/tests/test_resolve.py000066400000000000000000000112251407627043600200670ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest from dictdiffer.conflict import Conflict from dictdiffer.resolve import (NoFurtherResolutionException, Resolver, UnresolvedConflictsException) class UnresolvedConflictsExceptionTest(unittest.TestCase): def test_content(self): e = UnresolvedConflictsException(None) self.assertEqual(None, e.content) def test_message(self): e = UnresolvedConflictsException(None) m = ("The unresolved conflicts are stored in the *content* " "attribute of this exception or in the " "*unresolved_conflicts* attribute of the " "dictdiffer.merge.Merger object.") self.assertEqual(m, str(e)) self.assertEqual(m, e.__repr__()) self.assertEqual(m, e.__str__()) class ResolverTest(unittest.TestCase): def test_init(self): # Very basic r = Resolver({}) self.assertEqual(r.actions, {}) self.assertEqual(r.additional_info, None) self.assertEqual(r.unresolved_conflicts, []) # With additional_info r = Resolver({}, {}) self.assertEqual(r.actions, {}) self.assertEqual(r.additional_info, {}) self.assertEqual(r.unresolved_conflicts, []) def test_auto_resolve(self): r = Resolver({}) # Sucessful p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 0)]) c = Conflict(p1, p2) self.assertTrue(r._auto_resolve(c)) self.assertEqual(c.take, 'f') # Fail p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 1)]) c = Conflict(p1, p2) self.assertFalse(r._auto_resolve(c)) def test_find_conflicting_path(self): r = Resolver({}) # A = shortest p1 = ('delete', '', [('foo', [])]) p2 = ('add', 'foo', [(0, 0)]) c = Conflict(p1, p2) self.assertEqual(r._find_conflicting_path(c), ('foo',)) # Same p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 0)]) c = Conflict(p1, p2) self.assertEqual(r._find_conflicting_path(c), ('foo', 0)) # B = shortest p1 = ('add', 'foo', [(0, 0)]) p2 = ('delete', '', [('foo', [])]) c = Conflict(p1, p2) self.assertEqual(r._find_conflicting_path(c), ('foo',)) def test_consecutive_slices(self): r = Resolver({}) slices = [['foo', 'bar', 'apple', 'banana'], ['foo', 'bar', 'apple'], ['foo', 'bar'], ['foo']] self.assertEqual(list(r._consecutive_slices(['foo', 'bar', 'apple', 'banana'])), slices) def test_resolve_conflicts(self): p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 1)]) c = [Conflict(p1, p2)] # KeyError r = Resolver({}) self.assertRaises(UnresolvedConflictsException, r.resolve_conflicts, [p1], [p2], c) # Failing action r = Resolver({('foo', 0): lambda *args: False}) self.assertRaises(UnresolvedConflictsException, r.resolve_conflicts, [p1], [p2], c) # No further resolution exception def no_further(*args): raise NoFurtherResolutionException r = Resolver({('foo', 0): no_further}) self.assertRaises(UnresolvedConflictsException, r.resolve_conflicts, [p1], [p2], c) # Succesful r = Resolver({('foo', 0): lambda *args: True}) r.resolve_conflicts([p1], [p2], c) self.assertEqual(r.unresolved_conflicts, []) # Succesful auto resolve p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 0)]) c = [Conflict(p1, p2)] r = Resolver({}) r.resolve_conflicts([p1], [p2], c) self.assertEqual(r.unresolved_conflicts, []) def test_manual_resolve_conflicts(self): p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 0)]) c = Conflict(p1, p2) r = Resolver({}) r.unresolved_conflicts.append(c) r.manual_resolve_conflicts(['s']) self.assertEqual(c.take, 's') # Raise r = Resolver({}) r.unresolved_conflicts.append(c) self.assertRaises(UnresolvedConflictsException, r.manual_resolve_conflicts, []) dictdiffer-0.9.0/tests/test_testing.py000066400000000000000000000011351407627043600200640ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2021 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest import pytest from dictdiffer.testing import assert_no_diff class AssertNoDiffTest(unittest.TestCase): def test_passes(self): dict1 = {1: '1'} assert_no_diff(dict1, dict1) def test_raises_assertion_error(self): dict1 = {1: '1'} dict2 = {2: '2'} with pytest.raises(AssertionError): assert_no_diff(dict1, dict2) dictdiffer-0.9.0/tests/test_unify.py000066400000000000000000000020071407627043600175400ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest from dictdiffer import patch from dictdiffer.conflict import Conflict from dictdiffer.merge import Merger from dictdiffer.unify import Unifier from dictdiffer.utils import WildcardDict, nested_hash class TestUnifier(unittest.TestCase): def test_build_index(self): u = Unifier() p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 1)]) c = Conflict(p1, p2) u._build_index([c]) self.assertEqual(u._index[nested_hash(p1)], c) self.assertEqual(u._index[nested_hash(p2)], c) def test_unify(self): u = Unifier() p1 = ('add', 'foo', [(0, 0)]) p2 = ('add', 'foo', [(0, 1)]) c = Conflict(p1, p2) c.take = 'f' u.unify([p1], [p2], [c]) self.assertEqual(u.unified_patches, [p1]) dictdiffer-0.9.0/tests/test_utils.py000066400000000000000000000132541407627043600175540ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest from dictdiffer.utils import (PathLimit, WildcardDict, create_dotted_node, dot_lookup, get_path, is_super_path, nested_hash) class UtilsTest(unittest.TestCase): def test_wildcarddict(self): wd = WildcardDict() wd[('authors', '*')] = True self.assertRaises(KeyError, wd.__getitem__, ('authors',)) self.assertTrue(wd[('authors', 1)]) self.assertTrue(wd[('authors', 1, 'name')]) self.assertTrue(wd[('authors', 1, 'affiliation')]) del wd[('authors', '*')] wd[('authors', '+')] = True self.assertRaises(KeyError, wd.__getitem__, ('authors',)) self.assertTrue(wd[('authors', 1)]) self.assertRaises(KeyError, wd.__getitem__, ('authors', 1, 'name')) self.assertRaises(KeyError, wd.__getitem__, ('authors', 1, 'affiliation')) del wd[('authors', '+')] wd[('foo', 'bar')] = True self.assertRaises(KeyError, wd.__getitem__, ('foo',)) self.assertTrue(wd[('foo', 'bar')]) self.assertRaises(KeyError, wd.__getitem__, ('foo', 'bar', 'banana')) # query_path part wd = WildcardDict() wd[('authors', '*')] = True wd[('apple', '+')] = True wd[('foo', 'bar')] = True self.assertRaises(KeyError, wd.query_path, ('utz',)) self.assertRaises(KeyError, wd.query_path, ('foo',)) self.assertRaises(KeyError, wd.query_path, ('bar',)) self.assertRaises(KeyError, wd.query_path, ('apple', 'banana', 'mango')) self.assertEqual(('authors', '*'), wd.query_path(('authors', 1))) self.assertEqual(('authors', '*'), wd.query_path(('authors', 1, 1))) self.assertEqual(('authors', '*'), wd.query_path(('authors', 1, 1, 1))) self.assertEqual(('apple', '+'), wd.query_path(('apple', 'banana'))) self.assertEqual(('apple', '+'), wd.query_path(('apple', 'mango'))) self.assertEqual(('foo', 'bar'), wd.query_path(('foo', 'bar'))) def test_pathlimit(self): path_limit = PathLimit([('author', 'name')]) self.assertFalse(path_limit.path_is_limit(('author'))) self.assertTrue(path_limit.path_is_limit(('author', 'name'))) self.assertFalse(path_limit.path_is_limit(('author', 'name', 'foo'))) path_limit = PathLimit([('authors', '*')]) self.assertFalse(path_limit.path_is_limit(('authors'))) self.assertTrue(path_limit.path_is_limit(('authors', 'name'))) self.assertTrue(path_limit.path_is_limit(('authors', 1))) self.assertTrue(path_limit.path_is_limit(('authors', 2))) self.assertFalse(path_limit.path_is_limit(('authors', 'name', 'foo'))) def test_create_dotted_node(self): node = ('foo', 'bar') self.assertEqual('foo.bar', create_dotted_node(node)) node = ('foo', 1) self.assertEqual(['foo', 1], create_dotted_node(node)) node = ('foo', 1, 'bar') self.assertEqual(['foo', 1, 'bar'], create_dotted_node(node)) def test_get_path(self): patch = ('add/delete', '', [('author', 'Bob')]) self.assertEqual(('author',), get_path(patch)) patch = ('add/delete', 'authors', [('name', 'Bob')]) self.assertEqual(('authors', 'name'), get_path(patch)) patch = ('add/delete', 'foo.bar', [('name', 'Bob')]) self.assertEqual(('foo', 'bar', 'name'), get_path(patch)) patch = ('add/delete', ['foo', 1], [('name', 'Bob')]) self.assertEqual(('foo', 1, 'name'), get_path(patch)) patch = ('change', 'foo', [('John', 'Bob')]) self.assertEqual(('foo',), get_path(patch)) patch = ('change', 'foo.bar', [('John', 'Bob')]) self.assertEqual(('foo', 'bar'), get_path(patch)) patch = ('change', ['foo', 'bar'], [('John', 'Bob')]) self.assertEqual(('foo', 'bar'), get_path(patch)) patch = ('change', ['foo', 1], [('John', 'Bob')]) self.assertEqual(('foo', 1), get_path(patch)) def test_is_super_path(self): # # True path1 = ('authors', 1, 'name') path2 = ('authors', 1, 'name') self.assertTrue(is_super_path(path1, path2)) path1 = ('authors', 1) path2 = ('authors', 1, 'name') self.assertTrue(is_super_path(path1, path2)) path1 = ('authors',) path2 = ('authors', 1, 'name') self.assertTrue(is_super_path(path1, path2)) # # False path1 = ('authors', 1, 'name') path2 = ('authors', 1, 'surname') self.assertFalse(is_super_path(path1, path2)) path1 = ('authors', 2) path2 = ('authors', 1, 'surname') self.assertFalse(is_super_path(path1, path2)) path1 = ('author',) path2 = ('authors', 1, 'surname') self.assertFalse(is_super_path(path1, path2)) def test_dot_lookup(self): self.assertEqual(dot_lookup({'a': {'b': 'hello'}}, 'a.b'), 'hello') self.assertEqual(dot_lookup({'a': {'b': 'hello'}}, ['a', 'b']), 'hello') self.assertEqual(dot_lookup({'a': {'b': 'hello'}}, 'a.b', parent=True), {'b': 'hello'}) self.assertEqual(dot_lookup({'a': {'b': 'hello'}}, ''), {'a': {'b': 'hello'}}) def test_nested_hash(self): # No reasonable way to test this nested_hash([1, 2, 3]) nested_hash((1, 2, 3)) nested_hash(set([1, 2, 3])) nested_hash({'foo': 'bar'}) dictdiffer-0.9.0/tox.ini000066400000000000000000000011451407627043600151500ustar00rootroot00000000000000# This file is part of Dictdiffer. # # Copyright (C) 2014 CERN. # Copyright (C) 2017 ETH Zurich, Swiss Data Science Center, Jiri Kuncar. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. [tox] envlist = py35, py36, py37, py38, py39 [testenv] extras = numpy, tests commands = {envpython} -m check_manifest --ignore ".*-requirements.txt" {envpython} -m sphinx.cmd.build -qnNW docs docs/_build/html {envpython} setup.py test {envpython} -m sphinx.cmd.build -qnNW -b doctest docs docs/_build/doctest