diff --git a/.coveragerc b/.coveragerc index 2a98e09..f0d91db 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,8 +1,10 @@ # .coveragerc to control coverage.py [run] branch = True +source = jsonpatch [report] +show_missing = True # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml new file mode 100644 index 0000000..639e18d --- /dev/null +++ b/.github/workflows/test.yaml @@ -0,0 +1,34 @@ +name: Python package + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + pip install coveralls +# - name: Lint with flake8 +# run: | + # stop the build if there are Python syntax errors or undefined names + # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Test + run: | + coverage run --source=jsonpointer tests.py diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..b8c2f2b --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,22 @@ +# .readthedocs.yaml +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +# Set the version of Python and other tools you might need +build: + os: ubuntu-22.04 + tools: + python: "3.11" + +# Build documentation in the docs/ directory with Sphinx +sphinx: + configuration: doc/conf.py + +# We recommend specifying your dependencies to enable reproducible builds: +# https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html +# python: +# install: +# - requirements: docs/requirements.txt diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6a02844..0000000 --- a/.travis.yml +++ /dev/null @@ -1,33 +0,0 @@ -dist: xenial -language: python -python: -- '2.7' -- '3.5' -- '3.6' -- '3.7' -- '3.8' -- 3.8-dev -- nightly -- pypy -- pypy3 -addons: - apt: - packages: - - pandoc -install: -- travis_retry pip install -r requirements.txt -- travis_retry pip install coveralls -script: -- coverage run --source=jsonpointer tests.py -after_script: -- coveralls -before_deploy: -- pip install -r requirements-dev.txt -deploy: - provider: pypi - user: skoegl - password: - secure: ppMhKu82oIig1INyiNkt9veOd5FUUIKFUXj2TzxMSdzPtzAhQnScJMGPEtPfH8MwXng/CtJiDWS6zJzRFsW/3Ch+JHPkOtxOfkopBs1t1SpCyqNPSvf6Zxh83Dg6Bq6+8GyVW1RPuNIGflsvzY2C3z5i79FQXwZd8EQlg7Vu0Wo= - on: - tags: true - distributions: sdist bdist_wheel diff --git a/COPYING b/COPYING deleted file mode 100644 index 491196d..0000000 --- a/COPYING +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2011 Stefan Kögl -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c8fc60f --- /dev/null +++ b/LICENSE @@ -0,0 +1,11 @@ +Copyright (c) 2011 Stefan Kögl + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/bin/jsondiff b/bin/jsondiff index b79188b..5ac0090 100755 --- a/bin/jsondiff +++ b/bin/jsondiff @@ -14,6 +14,8 @@ parser.add_argument('FILE1', type=argparse.FileType('r')) parser.add_argument('FILE2', type=argparse.FileType('r')) parser.add_argument('--indent', type=int, default=None, help='Indent output by n spaces') +parser.add_argument('-u', '--preserve-unicode', action='store_true', + help='Output Unicode character as-is without using Code Point') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + jsonpatch.__version__) @@ -32,7 +34,7 @@ def diff_files(): doc2 = json.load(args.FILE2) patch = jsonpatch.make_patch(doc1, doc2) if patch.patch: - print(json.dumps(patch.patch, indent=args.indent)) + print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not(args.preserve_unicode))) sys.exit(1) if __name__ == "__main__": diff --git a/bin/jsonpatch b/bin/jsonpatch index 3f01738..a7adf29 100755 --- a/bin/jsonpatch +++ b/bin/jsonpatch @@ -24,7 +24,8 @@ parser.add_argument('-i', '--in-place', action='store_true', help='Modify ORIGINAL in-place instead of to stdout') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + jsonpatch.__version__) - +parser.add_argument('-u', '--preserve-unicode', action='store_true', + help='Output Unicode character as-is without using Code Point') def main(): try: @@ -72,8 +73,8 @@ def patch_files(): # By this point we have some sort of file object we can write the # modified JSON to. - - json.dump(result, fp, indent=args.indent) + + json.dump(result, fp, indent=args.indent, ensure_ascii=not(args.preserve_unicode)) fp.write('\n') if args.in_place: diff --git a/doc/commandline.rst b/doc/commandline.rst index 5644d08..a7a78d8 100644 --- a/doc/commandline.rst +++ b/doc/commandline.rst @@ -10,7 +10,7 @@ The JSON patch package contains the commandline utilities ``jsondiff`` and The program ``jsondiff`` can be used to create a JSON patch by comparing two JSON files :: - usage: jsondiff [-h] [--indent INDENT] [-v] FILE1 FILE2 + usage: jsondiff [-h] [--indent INDENT] [-u] [-v] FILE1 FILE2 Diff two JSON files @@ -19,9 +19,10 @@ JSON files :: FILE2 optional arguments: - -h, --help show this help message and exit - --indent INDENT Indent output by n spaces - -v, --version show program's version number and exit + -h, --help show this help message and exit + --indent INDENT Indent output by n spaces + -u, --preserve-unicode Output Unicode character as-is without using Code Point + -v, --version show program's version number and exit Example ^^^^^^^ @@ -74,10 +75,12 @@ The program ``jsonpatch`` is used to apply JSON patches on JSON files. :: PATCH Patch file optional arguments: - -h, --help show this help message and exit - --indent INDENT Indent output by n spaces - -v, --version show program's version number and exit - + -h, --help show this help message and exit + --indent INDENT Indent output by n spaces + -b, --backup Back up ORIGINAL if modifying in-place + -i, --in-place Modify ORIGINAL in-place instead of to stdout + -v, --version show program's version number and exit + -u, --preserve-unicode Output Unicode character as-is without using Code Point Example ^^^^^^^ diff --git a/doc/index.rst b/doc/index.rst index 2f46921..b97b82b 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -6,10 +6,15 @@ python-json-patch ================= -*python-json-patch* is a Python library for applying JSON patches (`RFC 6902 +`python-json-patch `_ +is a Python library for applying JSON patches (`RFC 6902 `_). Python 2.7 and 3.4+ are supported. Tests are run on both CPython and PyPy. +**Installation** +.. code-block:: bash + $ pip install jsonpatch +.. **Contents** diff --git a/doc/tutorial.rst b/doc/tutorial.rst index 538cd0e..0bb1a9c 100644 --- a/doc/tutorial.rst +++ b/doc/tutorial.rst @@ -67,3 +67,55 @@ explicitly. # or from a list >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] >>> res = jsonpatch.apply_patch(obj, patch) + + +Dealing with Custom Types +------------------------- + +Custom JSON dump and load functions can be used to support custom types such as +`decimal.Decimal`. The following examples shows how the +`simplejson `_ package, which has native +support for Python's ``Decimal`` type, can be used to create a custom +``JsonPatch`` subclass with ``Decimal`` support: + +.. code-block:: python + + >>> import decimal + >>> import simplejson + + >>> class DecimalJsonPatch(jsonpatch.JsonPatch): + @staticmethod + def json_dumper(obj): + return simplejson.dumps(obj) + + @staticmethod + def json_loader(obj): + return simplejson.loads(obj, use_decimal=True, + object_pairs_hook=jsonpatch.multidict) + + >>> src = {} + >>> dst = {'bar': decimal.Decimal('1.10')} + >>> patch = DecimalJsonPatch.from_diff(src, dst) + >>> doc = {'foo': 1} + >>> result = patch.apply(doc) + {'foo': 1, 'bar': Decimal('1.10')} + +Instead of subclassing it is also possible to pass a dump function to +``from_diff``: + + >>> patch = jsonpatch.JsonPatch.from_diff(src, dst, dumps=simplejson.dumps) + +a dumps function to ``to_string``: + + >>> serialized_patch = patch.to_string(dumps=simplejson.dumps) + '[{"op": "add", "path": "/bar", "value": 1.10}]' + +and load function to ``from_string``: + + >>> import functools + >>> loads = functools.partial(simplejson.loads, use_decimal=True, + object_pairs_hook=jsonpatch.multidict) + >>> patch.from_string(serialized_patch, loads=loads) + >>> doc = {'foo': 1} + >>> result = patch.apply(doc) + {'foo': 1, 'bar': Decimal('1.10')} diff --git a/ext_tests.py b/ext_tests.py index 2770c8e..59a36d2 100755 --- a/ext_tests.py +++ b/ext_tests.py @@ -65,9 +65,9 @@ def _test(self, test): raise Exception(test.get('comment', '')) from jpe # if there is no 'expected' we only verify that applying the patch - # does not raies an exception + # does not raise an exception if 'expected' in test: - self.assertEquals(res, test['expected'], test.get('comment', '')) + self.assertEqual(res, test['expected'], test.get('comment', '')) def make_test_case(tests): diff --git a/jsonpatch.py b/jsonpatch.py index 7f31ce5..d3fc26d 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -40,6 +40,17 @@ import json import sys +try: + from collections.abc import Sequence +except ImportError: # Python 3 + from collections import Sequence + +try: + from types import MappingProxyType +except ImportError: + # Python < 3.3 + MappingProxyType = dict + from jsonpointer import JsonPointer, JsonPointerException @@ -56,7 +67,7 @@ # Will be parsed by setup.py to determine package metadata __author__ = 'Stefan Kögl ' -__version__ = '1.24' +__version__ = '1.33' __website__ = 'https://github.com/stefankoegl/python-json-patch' __license__ = 'Modified BSD License' @@ -76,9 +87,9 @@ class InvalidJsonPatch(JsonPatchException): class JsonPatchConflict(JsonPatchException): """Raised if patch could not be applied due to conflict situation such as: - - attempt to add object key then it already exists; + - attempt to add object key when it already exists; - attempt to operate with nonexistence object key; - - attempt to insert value to array at position beyond of it size; + - attempt to insert value to array at position beyond its size; - etc. """ @@ -106,7 +117,7 @@ def multidict(ordered_pairs): _jsonloads = functools.partial(json.loads, object_pairs_hook=multidict) -def apply_patch(doc, patch, in_place=False): +def apply_patch(doc, patch, in_place=False, pointer_cls=JsonPointer): """Apply list of patches to specified json document. :param doc: Document object. @@ -119,6 +130,9 @@ def apply_patch(doc, patch, in_place=False): By default patch will be applied to document copy. :type in_place: bool + :param pointer_cls: JSON pointer class to use. + :type pointer_cls: Type[JsonPointer] + :return: Patched document object. :rtype: dict @@ -137,14 +151,14 @@ def apply_patch(doc, patch, in_place=False): """ if isinstance(patch, basestring): - patch = JsonPatch.from_string(patch) + patch = JsonPatch.from_string(patch, pointer_cls=pointer_cls) else: - patch = JsonPatch(patch) + patch = JsonPatch(patch, pointer_cls=pointer_cls) return patch.apply(doc, in_place) -def make_patch(src, dst): - """Generates patch by comparing of two document objects. Actually is +def make_patch(src, dst, pointer_cls=JsonPointer): + """Generates patch by comparing two document objects. Actually is a proxy to :meth:`JsonPatch.from_diff` method. :param src: Data source document object. @@ -153,6 +167,9 @@ def make_patch(src, dst): :param dst: Data source document object. :type dst: dict + :param pointer_cls: JSON pointer class to use. + :type pointer_cls: Type[JsonPointer] + >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = make_patch(src, dst) @@ -161,191 +178,33 @@ def make_patch(src, dst): True """ - return JsonPatch.from_diff(src, dst) - - -class JsonPatch(object): - """A JSON Patch is a list of Patch Operations. - - >>> patch = JsonPatch([ - ... {'op': 'add', 'path': '/foo', 'value': 'bar'}, - ... {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]}, - ... {'op': 'remove', 'path': '/baz/1'}, - ... {'op': 'test', 'path': '/baz', 'value': [1, 3]}, - ... {'op': 'replace', 'path': '/baz/0', 'value': 42}, - ... {'op': 'remove', 'path': '/baz/1'}, - ... ]) - >>> doc = {} - >>> result = patch.apply(doc) - >>> expected = {'foo': 'bar', 'baz': [42]} - >>> result == expected - True - - JsonPatch object is iterable, so you could easily access to each patch - statement in loop: - - >>> lpatch = list(patch) - >>> expected = {'op': 'add', 'path': '/foo', 'value': 'bar'} - >>> lpatch[0] == expected - True - >>> lpatch == patch.patch - True - - Also JsonPatch could be converted directly to :class:`bool` if it contains - any operation statements: - - >>> bool(patch) - True - >>> bool(JsonPatch([])) - False - - This behavior is very handy with :func:`make_patch` to write more readable - code: - - >>> old = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} - >>> new = {'baz': 'qux', 'numbers': [1, 4, 7]} - >>> patch = make_patch(old, new) - >>> if patch: - ... # document have changed, do something useful - ... patch.apply(old) #doctest: +ELLIPSIS - {...} - """ - def __init__(self, patch): - self.patch = patch - - self.operations = { - 'remove': RemoveOperation, - 'add': AddOperation, - 'replace': ReplaceOperation, - 'move': MoveOperation, - 'test': TestOperation, - 'copy': CopyOperation, - } - - def __str__(self): - """str(self) -> self.to_string()""" - return self.to_string() - - def __bool__(self): - return bool(self.patch) - - __nonzero__ = __bool__ - - def __iter__(self): - return iter(self.patch) - - def __hash__(self): - return hash(tuple(self._ops)) - - def __eq__(self, other): - if not isinstance(other, JsonPatch): - return False - return self._ops == other._ops - - def __ne__(self, other): - return not(self == other) - - @classmethod - def from_string(cls, patch_str): - """Creates JsonPatch instance from string source. - - :param patch_str: JSON patch as raw string. - :type patch_str: str - - :return: :class:`JsonPatch` instance. - """ - patch = _jsonloads(patch_str) - return cls(patch) - - @classmethod - def from_diff(cls, src, dst, optimization=True): - """Creates JsonPatch instance based on comparing of two document - objects. Json patch would be created for `src` argument against `dst` - one. - - :param src: Data source document object. - :type src: dict - - :param dst: Data source document object. - :type dst: dict - - :return: :class:`JsonPatch` instance. - - >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} - >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} - >>> patch = JsonPatch.from_diff(src, dst) - >>> new = patch.apply(src) - >>> new == dst - True - """ - - builder = DiffBuilder() - builder._compare_values('', None, src, dst) - ops = list(builder.execute()) - return cls(ops) - - def to_string(self): - """Returns patch set as JSON string.""" - return json.dumps(self.patch) - - @property - def _ops(self): - return tuple(map(self._get_operation, self.patch)) - - def apply(self, obj, in_place=False): - """Applies the patch to given object. - - :param obj: Document object. - :type obj: dict - - :param in_place: Tweaks way how patch would be applied - directly to - specified `obj` or to his copy. - :type in_place: bool - - :return: Modified `obj`. - """ - - if not in_place: - obj = copy.deepcopy(obj) - - for operation in self._ops: - obj = operation.apply(obj) - - return obj - - def _get_operation(self, operation): - if 'op' not in operation: - raise InvalidJsonPatch("Operation does not contain 'op' member") - - op = operation['op'] - - if not isinstance(op, basestring): - raise InvalidJsonPatch("Operation must be a string") - - if op not in self.operations: - raise InvalidJsonPatch("Unknown operation {0!r}".format(op)) - - cls = self.operations[op] - return cls(operation) + return JsonPatch.from_diff(src, dst, pointer_cls=pointer_cls) class PatchOperation(object): """A single operation inside a JSON Patch.""" - def __init__(self, operation): + def __init__(self, operation, pointer_cls=JsonPointer): + self.pointer_cls = pointer_cls - if isinstance(operation['path'], JsonPointer): + if not operation.__contains__('path'): + raise InvalidJsonPatch("Operation must have a 'path' member") + + if isinstance(operation['path'], self.pointer_cls): self.location = operation['path'].path self.pointer = operation['path'] else: self.location = operation['path'] - self.pointer = JsonPointer(self.location) + try: + self.pointer = self.pointer_cls(self.location) + except TypeError as ex: + raise InvalidJsonPatch("Invalid 'path'") self.operation = operation def apply(self, obj): - """Abstract method that applies patch operation to specified object.""" - raise NotImplementedError('should implement patch operation.') + """Abstract method that applies a patch operation to the specified object.""" + raise NotImplementedError('should implement the patch operation.') def __hash__(self): return hash(frozenset(self.operation.items())) @@ -381,10 +240,14 @@ class RemoveOperation(PatchOperation): def apply(self, obj): subobj, part = self.pointer.to_last(obj) + + if isinstance(subobj, Sequence) and not isinstance(part, int): + raise JsonPointerException("invalid array index '{0}'".format(part)) + try: del subobj[part] except (KeyError, IndexError) as ex: - msg = "can't remove non-existent object '{0}'".format(part) + msg = "can't remove a non-existent object '{0}'".format(part) raise JsonPatchConflict(msg) return obj @@ -459,7 +322,7 @@ def _on_undo_add(self, path, key): class ReplaceOperation(PatchOperation): - """Replaces an object property or an array element by new value.""" + """Replaces an object property or an array element by a new value.""" def apply(self, obj): try: @@ -473,13 +336,16 @@ def apply(self, obj): if part is None: return value + if part == "-": + raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation") + if isinstance(subobj, MutableSequence): if part >= len(subobj) or part < 0: raise JsonPatchConflict("can't replace outside of list") elif isinstance(subobj, MutableMapping): if part not in subobj: - msg = "can't replace non-existent object '{0}'".format(part) + msg = "can't replace a non-existent object '{0}'".format(part) raise JsonPatchConflict(msg) else: if part is None: @@ -498,14 +364,14 @@ def _on_undo_add(self, path, key): class MoveOperation(PatchOperation): - """Moves an object property or an array element to new location.""" + """Moves an object property or an array element to a new location.""" def apply(self, obj): try: - if isinstance(self.operation['from'], JsonPointer): + if isinstance(self.operation['from'], self.pointer_cls): from_ptr = self.operation['from'] else: - from_ptr = JsonPointer(self.operation['from']) + from_ptr = self.pointer_cls(self.operation['from']) except KeyError as ex: raise InvalidJsonPatch( "The operation does not contain a 'from' member") @@ -522,29 +388,29 @@ def apply(self, obj): if isinstance(subobj, MutableMapping) and \ self.pointer.contains(from_ptr): - raise JsonPatchConflict('Cannot move values into its own children') + raise JsonPatchConflict('Cannot move values into their own children') obj = RemoveOperation({ 'op': 'remove', 'path': self.operation['from'] - }).apply(obj) + }, pointer_cls=self.pointer_cls).apply(obj) obj = AddOperation({ 'op': 'add', 'path': self.location, 'value': value - }).apply(obj) + }, pointer_cls=self.pointer_cls).apply(obj) return obj @property def from_path(self): - from_ptr = JsonPointer(self.operation['from']) + from_ptr = self.pointer_cls(self.operation['from']) return '/'.join(from_ptr.parts[:-1]) @property def from_key(self): - from_ptr = JsonPointer(self.operation['from']) + from_ptr = self.pointer_cls(self.operation['from']) try: return int(from_ptr.parts[-1]) except TypeError: @@ -552,7 +418,7 @@ def from_key(self): @from_key.setter def from_key(self, value): - from_ptr = JsonPointer(self.operation['from']) + from_ptr = self.pointer_cls(self.operation['from']) from_ptr.parts[-1] = str(value) self.operation['from'] = from_ptr.path @@ -615,7 +481,7 @@ class CopyOperation(PatchOperation): def apply(self, obj): try: - from_ptr = JsonPointer(self.operation['from']) + from_ptr = self.pointer_cls(self.operation['from']) except KeyError as ex: raise InvalidJsonPatch( "The operation does not contain a 'from' member") @@ -630,41 +496,255 @@ def apply(self, obj): 'op': 'add', 'path': self.location, 'value': value - }).apply(obj) + }, pointer_cls=self.pointer_cls).apply(obj) return obj +class JsonPatch(object): + json_dumper = staticmethod(json.dumps) + json_loader = staticmethod(_jsonloads) + + operations = MappingProxyType({ + 'remove': RemoveOperation, + 'add': AddOperation, + 'replace': ReplaceOperation, + 'move': MoveOperation, + 'test': TestOperation, + 'copy': CopyOperation, + }) + + """A JSON Patch is a list of Patch Operations. + + >>> patch = JsonPatch([ + ... {'op': 'add', 'path': '/foo', 'value': 'bar'}, + ... {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]}, + ... {'op': 'remove', 'path': '/baz/1'}, + ... {'op': 'test', 'path': '/baz', 'value': [1, 3]}, + ... {'op': 'replace', 'path': '/baz/0', 'value': 42}, + ... {'op': 'remove', 'path': '/baz/1'}, + ... ]) + >>> doc = {} + >>> result = patch.apply(doc) + >>> expected = {'foo': 'bar', 'baz': [42]} + >>> result == expected + True + + JsonPatch object is iterable, so you can easily access each patch + statement in a loop: + + >>> lpatch = list(patch) + >>> expected = {'op': 'add', 'path': '/foo', 'value': 'bar'} + >>> lpatch[0] == expected + True + >>> lpatch == patch.patch + True + + Also JsonPatch could be converted directly to :class:`bool` if it contains + any operation statements: + + >>> bool(patch) + True + >>> bool(JsonPatch([])) + False + + This behavior is very handy with :func:`make_patch` to write more readable + code: + + >>> old = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} + >>> new = {'baz': 'qux', 'numbers': [1, 4, 7]} + >>> patch = make_patch(old, new) + >>> if patch: + ... # document have changed, do something useful + ... patch.apply(old) #doctest: +ELLIPSIS + {...} + """ + def __init__(self, patch, pointer_cls=JsonPointer): + self.patch = patch + self.pointer_cls = pointer_cls + + # Verify that the structure of the patch document + # is correct by retrieving each patch element. + # Much of the validation is done in the initializer + # though some is delayed until the patch is applied. + for op in self.patch: + # We're only checking for basestring in the following check + # for two reasons: + # + # - It should come from JSON, which only allows strings as + # dictionary keys, so having a string here unambiguously means + # someone used: {"op": ..., ...} instead of [{"op": ..., ...}]. + # + # - There's no possible false positive: if someone give a sequence + # of mappings, this won't raise. + if isinstance(op, basestring): + raise InvalidJsonPatch("Document is expected to be sequence of " + "operations, got a sequence of strings.") + + self._get_operation(op) + + def __str__(self): + """str(self) -> self.to_string()""" + return self.to_string() + + def __bool__(self): + return bool(self.patch) + + __nonzero__ = __bool__ + + def __iter__(self): + return iter(self.patch) + + def __hash__(self): + return hash(tuple(self._ops)) + + def __eq__(self, other): + if not isinstance(other, JsonPatch): + return False + return self._ops == other._ops + + def __ne__(self, other): + return not(self == other) + + @classmethod + def from_string(cls, patch_str, loads=None, pointer_cls=JsonPointer): + """Creates JsonPatch instance from string source. + + :param patch_str: JSON patch as raw string. + :type patch_str: str + + :param loads: A function of one argument that loads a serialized + JSON string. + :type loads: function + + :param pointer_cls: JSON pointer class to use. + :type pointer_cls: Type[JsonPointer] + + :return: :class:`JsonPatch` instance. + """ + json_loader = loads or cls.json_loader + patch = json_loader(patch_str) + return cls(patch, pointer_cls=pointer_cls) + + @classmethod + def from_diff( + cls, src, dst, optimization=True, dumps=None, + pointer_cls=JsonPointer, + ): + """Creates JsonPatch instance based on comparison of two document + objects. Json patch would be created for `src` argument against `dst` + one. + + :param src: Data source document object. + :type src: dict + + :param dst: Data source document object. + :type dst: dict + + :param dumps: A function of one argument that produces a serialized + JSON string. + :type dumps: function + + :param pointer_cls: JSON pointer class to use. + :type pointer_cls: Type[JsonPointer] + + :return: :class:`JsonPatch` instance. + + >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} + >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} + >>> patch = JsonPatch.from_diff(src, dst) + >>> new = patch.apply(src) + >>> new == dst + True + """ + json_dumper = dumps or cls.json_dumper + builder = DiffBuilder(src, dst, json_dumper, pointer_cls=pointer_cls) + builder._compare_values('', None, src, dst) + ops = list(builder.execute()) + return cls(ops, pointer_cls=pointer_cls) + + def to_string(self, dumps=None): + """Returns patch set as JSON string.""" + json_dumper = dumps or self.json_dumper + return json_dumper(self.patch) + + @property + def _ops(self): + return tuple(map(self._get_operation, self.patch)) + + def apply(self, obj, in_place=False): + """Applies the patch to a given object. + + :param obj: Document object. + :type obj: dict + + :param in_place: Tweaks the way how patch would be applied - directly to + specified `obj` or to its copy. + :type in_place: bool + + :return: Modified `obj`. + """ + + if not in_place: + obj = copy.deepcopy(obj) + + for operation in self._ops: + obj = operation.apply(obj) + + return obj + + def _get_operation(self, operation): + if 'op' not in operation: + raise InvalidJsonPatch("Operation does not contain 'op' member") + + op = operation['op'] + + if not isinstance(op, basestring): + raise InvalidJsonPatch("Operation's op must be a string") + + if op not in self.operations: + raise InvalidJsonPatch("Unknown operation {0!r}".format(op)) + + cls = self.operations[op] + return cls(operation, pointer_cls=self.pointer_cls) + + class DiffBuilder(object): - def __init__(self): + def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer): + self.dumps = dumps + self.pointer_cls = pointer_cls self.index_storage = [{}, {}] self.index_storage2 = [[], []] self.__root = root = [] + self.src_doc = src_doc + self.dst_doc = dst_doc root[:] = [root, root, None] def store_index(self, value, index, st): + typed_key = (value, type(value)) try: storage = self.index_storage[st] - stored = storage.get(value) + stored = storage.get(typed_key) if stored is None: - storage[value] = [index] + storage[typed_key] = [index] else: - storage[value].append(index) + storage[typed_key].append(index) except TypeError: - self.index_storage2[st].append((value, index)) + self.index_storage2[st].append((typed_key, index)) def take_index(self, value, st): + typed_key = (value, type(value)) try: - stored = self.index_storage[st].get(value) + stored = self.index_storage[st].get(typed_key) if stored: return stored.pop() except TypeError: storage = self.index_storage2[st] for i in range(len(storage)-1, -1, -1): - if storage[i][0] == value: + if storage[i][0] == typed_key: return storage.pop(i)[1] def insert(self, op): @@ -706,7 +786,7 @@ def execute(self): 'op': 'replace', 'path': op_second.location, 'value': op_second.operation['value'], - }).operation + }, pointer_cls=self.pointer_cls).operation curr = curr[1][1] continue @@ -727,14 +807,14 @@ def _item_added(self, path, key, item): 'op': 'move', 'from': op.location, 'path': _path_join(path, key), - }) + }, pointer_cls=self.pointer_cls) self.insert(new_op) else: new_op = AddOperation({ 'op': 'add', 'path': _path_join(path, key), 'value': item, - }) + }, pointer_cls=self.pointer_cls) new_index = self.insert(new_op) self.store_index(item, new_index, _ST_ADD) @@ -742,12 +822,17 @@ def _item_removed(self, path, key, item): new_op = RemoveOperation({ 'op': 'remove', 'path': _path_join(path, key), - }) + }, pointer_cls=self.pointer_cls) index = self.take_index(item, _ST_ADD) new_index = self.insert(new_op) if index is not None: op = index[2] - if type(op.key) == int: + # We can't rely on the op.key type since PatchOperation casts + # the .key property to int and this path wrongly ends up being taken + # for numeric string dict keys while the intention is to only handle lists. + # So we do an explicit check on the item affected by the op instead. + added_item = op.pointer.to_last(self.dst_doc)[0] + if type(added_item) == list: for v in self.iter_from(index): op.key = v._on_undo_add(op.path, op.key) @@ -757,7 +842,7 @@ def _item_removed(self, path, key, item): 'op': 'move', 'from': new_op.location, 'path': op.location, - }) + }, pointer_cls=self.pointer_cls) new_index[2] = new_op else: @@ -771,7 +856,7 @@ def _item_replaced(self, path, key, item): 'op': 'replace', 'path': _path_join(path, key), 'value': item, - })) + }, pointer_cls=self.pointer_cls)) def _compare_dicts(self, path, src, dst): src_keys = set(src.keys()) @@ -826,13 +911,13 @@ def _compare_values(self, path, key, src, dst): self._compare_lists(_path_join(path, key), src, dst) # To ensure we catch changes to JSON, we can't rely on a simple - # src == dst, or it would not recognize the difference between + # src == dst, because it would not recognize the difference between # 1 and True, among other things. Using json.dumps is the most # fool-proof way to ensure we catch type changes that matter to JSON # and ignore those that don't. The performance of this could be # improved by doing more direct type checks, but we'd need to be # careful to accept type changes that don't matter when JSONified. - elif json.dumps(src) == json.dumps(dst): + elif self.dumps(src) == self.dumps(dst): return else: diff --git a/requirements-dev.txt b/requirements-dev.txt index 21daf9a..c729ece 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,2 +1,3 @@ +coverage wheel pypandoc diff --git a/setup.py b/setup.py index b01af80..ab9f32a 100644 --- a/setup.py +++ b/setup.py @@ -56,10 +56,12 @@ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', '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', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries', @@ -79,7 +81,7 @@ package_data={'': ['requirements.txt']}, scripts=['bin/jsondiff', 'bin/jsonpatch'], classifiers=CLASSIFIERS, - python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*', + python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*', project_urls={ 'Website': 'https://github.com/stefankoegl/python-json-patch', 'Repository': 'https://github.com/stefankoegl/python-json-patch.git', diff --git a/tests.py b/tests.py index cde90b0..d9eea92 100755 --- a/tests.py +++ b/tests.py @@ -4,11 +4,17 @@ from __future__ import unicode_literals import json +import decimal import doctest import unittest import jsonpatch import jsonpointer import sys +try: + from types import MappingProxyType +except ImportError: + # Python < 3.3 + MappingProxyType = dict class ApplyPatchTestCase(unittest.TestCase): @@ -81,6 +87,12 @@ def test_remove_array_item(self): res = jsonpatch.apply_patch(obj, [{'op': 'remove', 'path': '/foo/1'}]) self.assertEqual(res['foo'], ['bar', 'baz']) + def test_remove_invalid_item(self): + obj = {'foo': ['bar', 'qux', 'baz']} + with self.assertRaises(jsonpointer.JsonPointerException): + jsonpatch.apply_patch(obj, [{'op': 'remove', 'path': '/foo/-'}]) + + def test_replace_object_key(self): obj = {'foo': 'bar', 'baz': 'qux'} res = jsonpatch.apply_patch(obj, [{'op': 'replace', 'path': '/baz', 'value': 'boo'}]) @@ -184,6 +196,12 @@ def test_test_not_existing(self): obj, [{'op': 'test', 'path': '/baz', 'value': 'bar'}]) + def test_forgetting_surrounding_list(self): + obj = {'bar': 'qux'} + self.assertRaises(jsonpatch.InvalidJsonPatch, + jsonpatch.apply_patch, + obj, {'op': 'test', 'path': '/bar'}) + def test_test_noval_existing(self): obj = {'bar': 'qux'} self.assertRaises(jsonpatch.InvalidJsonPatch, @@ -219,6 +237,17 @@ def test_append(self): ]) self.assertEqual(res['foo'], [1, 2, 3, 4]) + def test_add_missing_path(self): + obj = {'bar': 'qux'} + self.assertRaises(jsonpatch.InvalidJsonPatch, + jsonpatch.apply_patch, + obj, [{'op': 'test', 'value': 'bar'}]) + + def test_path_with_null_value(self): + obj = {'bar': 'qux'} + self.assertRaises(jsonpatch.InvalidJsonPatch, + jsonpatch.apply_patch, + obj, '[{"op": "add", "path": null, "value": "bar"}]') class EqualityTestCase(unittest.TestCase): @@ -267,6 +296,34 @@ def test_str(self): self.assertEqual(json.dumps(patch_obj), patch.to_string()) +def custom_types_dumps(obj): + def default(obj): + if isinstance(obj, decimal.Decimal): + return {'__decimal__': str(obj)} + raise TypeError('Unknown type') + + return json.dumps(obj, default=default) + + +def custom_types_loads(obj): + def as_decimal(dct): + if '__decimal__' in dct: + return decimal.Decimal(dct['__decimal__']) + return dct + + return json.loads(obj, object_hook=as_decimal) + + +class CustomTypesJsonPatch(jsonpatch.JsonPatch): + @staticmethod + def json_dumper(obj): + return custom_types_dumps(obj) + + @staticmethod + def json_loader(obj): + return custom_types_loads(obj) + + class MakePatchTestCase(unittest.TestCase): def test_apply_patch_to_copy(self): @@ -436,6 +493,15 @@ def test_issue90(self): self.assertEqual(res, dst) self.assertIsInstance(res['A'], bool) + def test_issue129(self): + """In JSON 1 is different from True even though in python 1 == True Take Two""" + src = {'A': {'D': 1.0}, 'B': {'E': 'a'}} + dst = {'A': {'C': 'a'}, 'B': {'C': True}} + patch = jsonpatch.make_patch(src, dst) + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) + self.assertIsInstance(res['B']['C'], bool) + def test_issue103(self): """In JSON 1 is different from 1.0 even though in python 1 == 1.0""" src = {'A': 1} @@ -445,6 +511,90 @@ def test_issue103(self): self.assertEqual(res, dst) self.assertIsInstance(res['A'], float) + def test_issue119(self): + """Make sure it avoids casting numeric str dict key to int""" + src = [ + {'foobar': {u'1': [u'lettuce', u'cabbage', u'bok choy', u'broccoli'], u'3': [u'ibex'], u'2': [u'apple'], u'5': [], u'4': [u'gerenuk', u'duiker'], u'10_1576156603109': [], u'6': [], u'8_1572034252560': [u'thompson', u'gravie', u'mango', u'coconut'], u'7_1572034204585': []}}, + {'foobar':{u'description': u'', u'title': u''}} + ] + dst = [ + {'foobar': {u'9': [u'almond'], u'10': u'yes', u'12': u'', u'16_1598876845275': [], u'7': [u'pecan']}}, + {'foobar': {u'1': [u'lettuce', u'cabbage', u'bok choy', u'broccoli'], u'3': [u'ibex'], u'2': [u'apple'], u'5': [], u'4': [u'gerenuk', u'duiker'], u'10_1576156603109': [], u'6': [], u'8_1572034252560': [u'thompson', u'gravie', u'mango', u'coconut'], u'7_1572034204585': []}}, + {'foobar': {u'description': u'', u'title': u''}} + ] + patch = jsonpatch.make_patch(src, dst) + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) + + def test_issue120(self): + """Make sure it avoids casting numeric str dict key to int""" + src = [{'foobar': {'821b7213_b9e6_2b73_2e9c_cf1526314553': ['Open Work'], + '6e3d1297_0c5a_88f9_576b_ad9216611c94': ['Many Things'], + '1987bcf0_dc97_59a1_4c62_ce33e51651c7': ['Product']}}, + {'foobar': {'2a7624e_0166_4d75_a92c_06b3f': []}}, + {'foobar': {'10': [], + '11': ['bee', + 'ant', + 'wasp'], + '13': ['phobos', + 'titan', + 'gaea'], + '14': [], + '15': 'run3', + '16': 'service', + '2': ['zero', 'enable']}}] + dst = [{'foobar': {'1': [], '2': []}}, + {'foobar': {'821b7213_b9e6_2b73_2e9c_cf1526314553': ['Open Work'], + '6e3d1297_0c5a_88f9_576b_ad9216611c94': ['Many Things'], + '1987bcf0_dc97_59a1_4c62_ce33e51651c7': ['Product']}}, + {'foobar': {'2a7624e_0166_4d75_a92c_06b3f': []}}, + {'foobar': {'b238d74d_dcf4_448c_9794_c13a2f7b3c0a': [], + 'dcb0387c2_f7ae_b8e5bab_a2b1_94deb7c': []}}, + {'foobar': {'10': [], + '11': ['bee', + 'ant', + 'fly'], + '13': ['titan', + 'phobos', + 'gaea'], + '14': [], + '15': 'run3', + '16': 'service', + '2': ['zero', 'enable']}} + ] + patch = jsonpatch.make_patch(src, dst) + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) + + def test_custom_types_diff(self): + old = {'value': decimal.Decimal('1.0')} + new = {'value': decimal.Decimal('1.00')} + generated_patch = jsonpatch.JsonPatch.from_diff( + old, new, dumps=custom_types_dumps) + str_patch = generated_patch.to_string(dumps=custom_types_dumps) + loaded_patch = jsonpatch.JsonPatch.from_string( + str_patch, loads=custom_types_loads) + self.assertEqual(generated_patch, loaded_patch) + new_from_patch = jsonpatch.apply_patch(old, generated_patch) + self.assertEqual(new, new_from_patch) + + def test_custom_types_subclass(self): + old = {'value': decimal.Decimal('1.0')} + new = {'value': decimal.Decimal('1.00')} + generated_patch = CustomTypesJsonPatch.from_diff(old, new) + str_patch = generated_patch.to_string() + loaded_patch = CustomTypesJsonPatch.from_string(str_patch) + self.assertEqual(generated_patch, loaded_patch) + new_from_patch = jsonpatch.apply_patch(old, loaded_patch) + self.assertEqual(new, new_from_patch) + + def test_custom_types_subclass_load(self): + old = {'value': decimal.Decimal('1.0')} + new = {'value': decimal.Decimal('1.00')} + patch = CustomTypesJsonPatch.from_string( + '[{"op": "replace", "path": "/value", "value": {"__decimal__": "1.00"}}]') + new_from_patch = jsonpatch.apply_patch(old, patch) + self.assertEqual(new, new_from_patch) class OptimizationTests(unittest.TestCase): @@ -660,6 +810,236 @@ def test_create_with_pointer(self): self.assertEqual(result, expected) +class JsonPatchCreationTest(unittest.TestCase): + + def test_creation_fails_with_invalid_patch(self): + invalid_patches = [ + { 'path': '/foo', 'value': 'bar'}, + {'op': 0xADD, 'path': '/foo', 'value': 'bar'}, + {'op': 'boo', 'path': '/foo', 'value': 'bar'}, + {'op': 'add', 'value': 'bar'}, + ] + for patch in invalid_patches: + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.JsonPatch([patch]) + + with self.assertRaises(jsonpointer.JsonPointerException): + jsonpatch.JsonPatch([{'op': 'add', 'path': 'foo', 'value': 'bar'}]) + + +class UtilityMethodTests(unittest.TestCase): + + def test_boolean_coercion(self): + empty_patch = jsonpatch.JsonPatch([]) + self.assertFalse(empty_patch) + + def test_patch_equality(self): + p = jsonpatch.JsonPatch([{'op': 'add', 'path': '/foo', 'value': 'bar'}]) + q = jsonpatch.JsonPatch([{'op': 'add', 'path': '/foo', 'value': 'bar'}]) + different_op = jsonpatch.JsonPatch([{'op': 'remove', 'path': '/foo'}]) + different_path = jsonpatch.JsonPatch([{'op': 'add', 'path': '/bar', 'value': 'bar'}]) + different_value = jsonpatch.JsonPatch([{'op': 'add', 'path': '/foo', 'value': 'foo'}]) + self.assertNotEqual(p, different_op) + self.assertNotEqual(p, different_path) + self.assertNotEqual(p, different_value) + self.assertEqual(p, q) + + def test_operation_equality(self): + add = jsonpatch.AddOperation({'path': '/new-element', 'value': 'new-value'}) + add2 = jsonpatch.AddOperation({'path': '/new-element', 'value': 'new-value'}) + rm = jsonpatch.RemoveOperation({'path': '/target'}) + self.assertEqual(add, add2) + self.assertNotEqual(add, rm) + + def test_add_operation_structure(self): + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.AddOperation({'path': '/'}).apply({}) + + def test_replace_operation_structure(self): + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.ReplaceOperation({'path': '/'}).apply({}) + + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.ReplaceOperation({'path': '/top/-', 'value': 'foo'}).apply({'top': {'inner': 'value'}}) + + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.ReplaceOperation({'path': '/top/missing', 'value': 'foo'}).apply({'top': {'inner': 'value'}}) + + def test_move_operation_structure(self): + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.MoveOperation({'path': '/target'}).apply({}) + + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.MoveOperation({'from': '/source', 'path': '/target'}).apply({}) + + def test_test_operation_structure(self): + with self.assertRaises(jsonpatch.JsonPatchTestFailed): + jsonpatch.TestOperation({'path': '/target'}).apply({}) + + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.TestOperation({'path': '/target'}).apply({'target': 'value'}) + + def test_copy_operation_structure(self): + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.CopyOperation({'path': '/target'}).apply({}) + + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.CopyOperation({'path': '/target', 'from': '/source'}).apply({}) + + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.CopyOperation({'path': '/target', 'from': '/source'}).apply({}) + + +class CustomJsonPointer(jsonpointer.JsonPointer): + pass + + +class PrefixJsonPointer(jsonpointer.JsonPointer): + def __init__(self, pointer): + super(PrefixJsonPointer, self).__init__('/foo/bar' + pointer) + + +class CustomJsonPointerTests(unittest.TestCase): + + def test_json_patch_from_string(self): + patch = '[{"op": "add", "path": "/baz", "value": "qux"}]' + res = jsonpatch.JsonPatch.from_string( + patch, pointer_cls=CustomJsonPointer, + ) + self.assertEqual(res.pointer_cls, CustomJsonPointer) + + def test_json_patch_from_object(self): + patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] + res = jsonpatch.JsonPatch( + patch, pointer_cls=CustomJsonPointer, + ) + self.assertEqual(res.pointer_cls, CustomJsonPointer) + + def test_json_patch_from_diff(self): + old = {'foo': 'bar'} + new = {'foo': 'baz'} + res = jsonpatch.JsonPatch.from_diff( + old, new, pointer_cls=CustomJsonPointer, + ) + self.assertEqual(res.pointer_cls, CustomJsonPointer) + + def test_apply_patch_from_string(self): + obj = {'foo': 'bar'} + patch = '[{"op": "add", "path": "/baz", "value": "qux"}]' + res = jsonpatch.apply_patch( + obj, patch, + pointer_cls=CustomJsonPointer, + ) + self.assertTrue(obj is not res) + self.assertTrue('baz' in res) + self.assertEqual(res['baz'], 'qux') + + def test_apply_patch_from_object(self): + obj = {'foo': 'bar'} + res = jsonpatch.apply_patch( + obj, [{'op': 'add', 'path': '/baz', 'value': 'qux'}], + pointer_cls=CustomJsonPointer, + ) + self.assertTrue(obj is not res) + + def test_make_patch(self): + src = {'foo': 'bar', 'boo': 'qux'} + dst = {'baz': 'qux', 'foo': 'boo'} + patch = jsonpatch.make_patch( + src, dst, pointer_cls=CustomJsonPointer, + ) + res = patch.apply(src) + self.assertTrue(src is not res) + self.assertEqual(patch.pointer_cls, CustomJsonPointer) + self.assertTrue(patch._ops) + for op in patch._ops: + self.assertIsInstance(op.pointer, CustomJsonPointer) + self.assertEqual(op.pointer_cls, CustomJsonPointer) + + def test_operations(self): + operations =[ + ( + jsonpatch.AddOperation, { + 'op': 'add', 'path': '/foo', 'value': [1, 2, 3] + } + ), + ( + jsonpatch.MoveOperation, { + 'op': 'move', 'path': '/baz', 'from': '/foo' + }, + ), + ( + jsonpatch.RemoveOperation, { + 'op': 'remove', 'path': '/baz/1' + }, + ), + ( + jsonpatch.TestOperation, { + 'op': 'test', 'path': '/baz', 'value': [1, 3] + }, + ), + ( + jsonpatch.ReplaceOperation, { + 'op': 'replace', 'path': '/baz/0', 'value': 42 + }, + ), + ( + jsonpatch.RemoveOperation, { + 'op': 'remove', 'path': '/baz/1' + }, + ) + ] + for cls, patch in operations: + operation = cls(patch, pointer_cls=CustomJsonPointer) + self.assertEqual(operation.pointer_cls, CustomJsonPointer) + self.assertIsInstance(operation.pointer, CustomJsonPointer) + + def test_operations_from_patch(self): + patch = jsonpatch.JsonPatch([ + {'op': 'add', 'path': '/foo', 'value': [1, 2, 3]}, + {'op': 'move', 'path': '/baz', 'from': '/foo'}, + {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]}, + {'op': 'remove', 'path': '/baz/1'}, + {'op': 'test', 'path': '/baz', 'value': [1, 3]}, + {'op': 'replace', 'path': '/baz/0', 'value': 42}, + {'op': 'remove', 'path': '/baz/1'}, + ], pointer_cls=CustomJsonPointer) + self.assertEqual(patch.apply({}), {'baz': [42]}) + self.assertEqual(patch.pointer_cls, CustomJsonPointer) + self.assertTrue(patch._ops) + for op in patch._ops: + self.assertIsInstance(op.pointer, CustomJsonPointer) + self.assertEqual(op.pointer_cls, CustomJsonPointer) + + def test_json_patch_with_prefix_pointer(self): + res = jsonpatch.apply_patch( + {'foo': {'bar': {}}}, [{'op': 'add', 'path': '/baz', 'value': 'qux'}], + pointer_cls=PrefixJsonPointer, + ) + self.assertEqual(res, {'foo': {'bar': {'baz': 'qux'}}}) + + +class CustomOperationTests(unittest.TestCase): + + def test_custom_operation(self): + + class IdentityOperation(jsonpatch.PatchOperation): + def apply(self, obj): + return obj + + class JsonPatch(jsonpatch.JsonPatch): + operations = MappingProxyType( + dict( + identity=IdentityOperation, + **jsonpatch.JsonPatch.operations + ) + ) + + patch = JsonPatch([{'op': 'identity', 'path': '/'}]) + self.assertIn('identity', patch.operations) + res = patch.apply({}) + self.assertEqual(res, {}) + if __name__ == '__main__': modules = ['jsonpatch'] @@ -676,6 +1056,10 @@ def get_suite(): suite.addTest(unittest.makeSuite(ConflictTests)) suite.addTest(unittest.makeSuite(OptimizationTests)) suite.addTest(unittest.makeSuite(JsonPointerTests)) + suite.addTest(unittest.makeSuite(JsonPatchCreationTest)) + suite.addTest(unittest.makeSuite(UtilityMethodTests)) + suite.addTest(unittest.makeSuite(CustomJsonPointerTests)) + suite.addTest(unittest.makeSuite(CustomOperationTests)) return suite