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 e4a40ad..0000000 --- a/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: python -python: - - "2.6" - - "2.7" - - "3.2" - - "3.3" - - "3.4" - - "3.5" - - "pypy" - - "pypy3" - -install: - - travis_retry pip install -r requirements.txt - - travis_retry pip install coveralls - -script: - - coverage run --source=jsonpatch tests.py - -after_script: - - coveralls - -sudo: false 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/MANIFEST.in b/MANIFEST.in index d356d15..ca196b9 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,3 +4,4 @@ include README.md include tests.py include ext_tests.py include AUTHORS +include tests.js diff --git a/README.md b/README.md index e8b8bcb..ff2b142 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,24 @@ -python-json-patch [![Build Status](https://secure.travis-ci.org/stefankoegl/python-json-patch.png?branch=master)](https://travis-ci.org/stefankoegl/python-json-patch) [![Coverage Status](https://coveralls.io/repos/stefankoegl/python-json-patch/badge.png?branch=master)](https://coveralls.io/r/stefankoegl/python-json-patch?branch=master) ![Downloads](https://pypip.in/d/jsonpatch/badge.png) ![Version](https://pypip.in/v/jsonpatch/badge.png) +python-json-patch ================= + +[![PyPI version](https://img.shields.io/pypi/v/jsonpatch.svg)](https://pypi.python.org/pypi/jsonpatch/) +[![Supported Python versions](https://img.shields.io/pypi/pyversions/jsonpatch.svg)](https://pypi.python.org/pypi/jsonpatch/) +[![Build Status](https://travis-ci.org/stefankoegl/python-json-patch.png?branch=master)](https://travis-ci.org/stefankoegl/python-json-patch) +[![Coverage Status](https://coveralls.io/repos/stefankoegl/python-json-patch/badge.png?branch=master)](https://coveralls.io/r/stefankoegl/python-json-patch?branch=master) + Applying JSON Patches in Python ------------------------------- Library to apply JSON Patches according to [RFC 6902](http://tools.ietf.org/html/rfc6902) -See Sourcecode for Examples +See source code for examples * Website: https://github.com/stefankoegl/python-json-patch * Repository: https://github.com/stefankoegl/python-json-patch.git * Documentation: https://python-json-patch.readthedocs.org/ * PyPI: https://pypi.python.org/pypi/jsonpatch -* Travis-CI: https://travis-ci.org/stefankoegl/python-json-patch +* Travis CI: https://travis-ci.org/stefankoegl/python-json-patch * Coveralls: https://coveralls.io/r/stefankoegl/python-json-patch Running external tests diff --git a/bin/jsondiff b/bin/jsondiff index 81c83a7..5ac0090 100755 --- a/bin/jsondiff +++ b/bin/jsondiff @@ -4,7 +4,6 @@ from __future__ import print_function import sys -import os.path import json import jsonpatch import argparse @@ -15,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,8 +33,9 @@ def diff_files(): doc1 = json.load(args.FILE1) doc2 = json.load(args.FILE2) patch = jsonpatch.make_patch(doc1, doc2) - print(json.dumps(patch.patch, indent=args.indent)) - + if patch.patch: + print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not(args.preserve_unicode))) + sys.exit(1) if __name__ == "__main__": 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 674c9e5..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 2.6, 2.7, 3.2, 3.3 -and PyPy are supported. - +`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 5e5ded8..59a36d2 100755 --- a/ext_tests.py +++ b/ext_tests.py @@ -34,7 +34,6 @@ """ Script to run external tests, eg from https://github.com/json-patch/json-patch-tests """ -from functools import partial import doctest import unittest import jsonpatch @@ -60,12 +59,15 @@ def _test(self, test): ) else: - res = jsonpatch.apply_patch(test['doc'], test['patch']) + try: + res = jsonpatch.apply_patch(test['doc'], test['patch']) + except jsonpatch.JsonPatchException as jpe: + 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']) + self.assertEqual(res, test['expected'], test.get('comment', '')) def make_test_case(tests): @@ -112,24 +114,25 @@ def get_suite(filenames): try: import coverage + cov = coverage.Coverage() except ImportError: - coverage = None + cov = None -if coverage is not None: - coverage.erase() - coverage.start() +if cov is not None: + cov.erase() + cov.start() result = runner.run(suite) if not result.wasSuccessful(): sys.exit(1) -if coverage is not None: - coverage.stop() - coverage.report(coverage_modules) - coverage.erase() +if cov is not None: + cov.stop() + cov.report(coverage_modules) + cov.erase() -if coverage is None: +if cov is None: sys.stderr.write(""" No coverage reporting done (Python module "coverage" is missing) Please install the python-coverage package to get coverage reporting. diff --git a/jsonpatch.py b/jsonpatch.py index f62aa94..d3fc26d 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -37,21 +37,37 @@ import collections import copy import functools -import inspect -import itertools import json import sys try: - from collections.abc import MutableMapping, MutableSequence + from collections.abc import Sequence +except ImportError: # Python 3 + from collections import Sequence + +try: + from types import MappingProxyType except ImportError: - from collections import MutableMapping, MutableSequence + # Python < 3.3 + MappingProxyType = dict from jsonpointer import JsonPointer, JsonPointerException + +_ST_ADD = 0 +_ST_REMOVE = 1 + + +try: + from collections.abc import MutableMapping, MutableSequence + +except ImportError: + from collections import MutableMapping, MutableSequence + str = unicode + # Will be parsed by setup.py to determine package metadata __author__ = 'Stefan Kögl ' -__version__ = '1.11' +__version__ = '1.33' __website__ = 'https://github.com/stefankoegl/python-json-patch' __license__ = 'Modified BSD License' @@ -71,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. """ @@ -96,25 +112,12 @@ def multidict(ordered_pairs): ) -def get_loadjson(): - """ adds the object_pairs_hook parameter to json.load when possible - - The "object_pairs_hook" parameter is used to handle duplicate keys when - loading a JSON object. This parameter does not exist in Python 2.6. This - methods returns an unmodified json.load for Python 2.6 and a partial - function with object_pairs_hook set to multidict for Python versions that - support the parameter. """ - - argspec = inspect.getargspec(json.load) - if 'object_pairs_hook' not in argspec.args: - return json.load - - return functools.partial(json.load, object_pairs_hook=multidict) - -json.load = get_loadjson() +# The "object_pairs_hook" parameter is used to handle duplicate keys when +# loading a JSON object. +_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. @@ -127,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 @@ -145,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. @@ -161,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) @@ -168,215 +177,34 @@ def make_patch(src, dst): >>> new == 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 = json.loads(patch_str) - return cls(patch) - - @classmethod - def from_diff(cls, src, dst): - """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 - """ - def compare_values(path, value, other): - if value == other: - return - if isinstance(value, MutableMapping) and \ - isinstance(other, MutableMapping): - for operation in compare_dicts(path, value, other): - yield operation - elif isinstance(value, MutableSequence) and \ - isinstance(other, MutableSequence): - for operation in compare_lists(path, value, other): - yield operation - else: - ptr = JsonPointer.from_parts(path) - yield {'op': 'replace', 'path': ptr.path, 'value': other} - - def compare_dicts(path, src, dst): - for key in src: - if key not in dst: - ptr = JsonPointer.from_parts(path + [key]) - yield {'op': 'remove', 'path': ptr.path} - continue - current = path + [key] - for operation in compare_values(current, src[key], dst[key]): - yield operation - for key in dst: - if key not in src: - ptr = JsonPointer.from_parts(path + [key]) - yield {'op': 'add', - 'path': ptr.path, - 'value': dst[key]} - - def compare_lists(path, src, dst): - return _compare_lists(path, src, dst) - - return cls(list(compare_values([], src, dst))) - - 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") + return JsonPatch.from_diff(src, dst, pointer_cls=pointer_cls) - 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)) +class PatchOperation(object): + """A single operation inside a JSON Patch.""" - cls = self.operations[op] - return cls(operation) + def __init__(self, operation, pointer_cls=JsonPointer): + self.pointer_cls = pointer_cls + if not operation.__contains__('path'): + raise InvalidJsonPatch("Operation must have a 'path' member") -class PatchOperation(object): - """A single operation inside a JSON Patch.""" + if isinstance(operation['path'], self.pointer_cls): + self.location = operation['path'].path + self.pointer = operation['path'] + else: + self.location = operation['path'] + try: + self.pointer = self.pointer_cls(self.location) + except TypeError as ex: + raise InvalidJsonPatch("Invalid 'path'") - def __init__(self, operation): - self.location = operation['path'] - self.pointer = JsonPointer(self.location) 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())) @@ -389,20 +217,57 @@ def __eq__(self, other): def __ne__(self, other): return not(self == other) + @property + def path(self): + return '/'.join(self.pointer.parts[:-1]) + + @property + def key(self): + try: + return int(self.pointer.parts[-1]) + except ValueError: + return self.pointer.parts[-1] + + @key.setter + def key(self, value): + self.pointer.parts[-1] = str(value) + self.location = self.pointer.path + self.operation['path'] = self.location + class RemoveOperation(PatchOperation): """Removes an object property or an array element.""" 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 + def _on_undo_remove(self, path, key): + if self.path == path: + if self.key >= key: + self.key += 1 + else: + key -= 1 + return key + + def _on_undo_add(self, path, key): + if self.path == path: + if self.key > key: + self.key -= 1 + else: + key -= 1 + return key + class AddOperation(PatchOperation): """Adds an object property or an array element.""" @@ -433,13 +298,31 @@ def apply(self, obj): subobj[part] = value else: - raise TypeError("invalid document type {0}".format(type(subobj))) - + if part is None: + raise TypeError("invalid document type {0}".format(type(subobj))) + else: + raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part)) return obj + def _on_undo_remove(self, path, key): + if self.path == path: + if self.key > key: + self.key += 1 + else: + key += 1 + return key + + def _on_undo_add(self, path, key): + if self.path == path: + if self.key > key: + self.key -= 1 + else: + key += 1 + return 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: @@ -453,27 +336,42 @@ 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: + if part >= len(subobj) or part < 0: raise JsonPatchConflict("can't replace outside of list") elif isinstance(subobj, MutableMapping): - if not part in subobj: - msg = "can't replace non-existent object '{0}'".format(part) + if part not in subobj: + msg = "can't replace a non-existent object '{0}'".format(part) raise JsonPatchConflict(msg) else: - raise TypeError("invalid document type {0}".format(type(subobj))) + if part is None: + raise TypeError("invalid document type {0}".format(type(subobj))) + else: + raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part)) subobj[part] = value return obj + def _on_undo_remove(self, path, key): + return key + + def _on_undo_add(self, path, key): + return 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: - from_ptr = JsonPointer(self.operation['from']) + if isinstance(self.operation['from'], self.pointer_cls): + from_ptr = self.operation['from'] + else: + from_ptr = self.pointer_cls(self.operation['from']) except KeyError as ex: raise InvalidJsonPatch( "The operation does not contain a 'from' member") @@ -484,23 +382,72 @@ def apply(self, obj): except (KeyError, IndexError) as ex: raise JsonPatchConflict(str(ex)) + # If source and target are equal, this is a no-op + if self.pointer == from_ptr: + return 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 = self.pointer_cls(self.operation['from']) + return '/'.join(from_ptr.parts[:-1]) + + @property + def from_key(self): + from_ptr = self.pointer_cls(self.operation['from']) + try: + return int(from_ptr.parts[-1]) + except TypeError: + return from_ptr.parts[-1] + + @from_key.setter + def from_key(self, value): + from_ptr = self.pointer_cls(self.operation['from']) + from_ptr.parts[-1] = str(value) + self.operation['from'] = from_ptr.path + + def _on_undo_remove(self, path, key): + if self.from_path == path: + if self.from_key >= key: + self.from_key += 1 + else: + key -= 1 + if self.path == path: + if self.key > key: + self.key += 1 + else: + key += 1 + return key + + def _on_undo_add(self, path, key): + if self.from_path == path: + if self.from_key > key: + self.from_key -= 1 + else: + key -= 1 + if self.path == path: + if self.key > key: + self.key -= 1 + else: + key += 1 + return key + class TestOperation(PatchOperation): """Test value by specified location.""" @@ -534,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") @@ -549,235 +496,436 @@ def apply(self, obj): 'op': 'add', 'path': self.location, 'value': value - }).apply(obj) + }, pointer_cls=self.pointer_cls).apply(obj) return obj -def _compare_lists(path, src, dst): - """Compares two lists objects and return JSON patch about.""" - return _optimize(_compare(path, src, dst, *_split_by_common_seq(src, dst))) +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 -def _longest_common_subseq(src, dst): - """Returns pair of ranges of longest common subsequence for the `src` - and `dst` lists. + This behavior is very handy with :func:`make_patch` to write more readable + code: - >>> src = [1, 2, 3, 4] - >>> dst = [0, 1, 2, 3, 5] - >>> # The longest common subsequence for these lists is [1, 2, 3] - ... # which is located at (0, 3) index range for src list and (1, 4) for - ... # dst one. Tuple of these ranges we should get back. - ... assert ((0, 3), (1, 4)) == _longest_common_subseq(src, dst) + >>> 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 + {...} """ - lsrc, ldst = len(src), len(dst) - drange = list(range(ldst)) - matrix = [[0] * ldst for _ in range(lsrc)] - z = 0 # length of the longest subsequence - range_src, range_dst = None, None - for i, j in itertools.product(range(lsrc), drange): - if src[i] == dst[j]: - if i == 0 or j == 0: - matrix[i][j] = 1 + 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, 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(typed_key) + if stored is None: + storage[typed_key] = [index] else: - matrix[i][j] = matrix[i-1][j-1] + 1 - if matrix[i][j] > z: - z = matrix[i][j] - if matrix[i][j] == z: - range_src = (i-z+1, i+1) - range_dst = (j-z+1, j+1) + storage[typed_key].append(index) + + except TypeError: + 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(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] == typed_key: + return storage.pop(i)[1] + + def insert(self, op): + root = self.__root + last = root[0] + last[1] = root[0] = [last, root, op] + return root[0] + + def remove(self, index): + link_prev, link_next, _ = index + link_prev[1] = link_next + link_next[0] = link_prev + index[:] = [] + + def iter_from(self, start): + root = self.__root + curr = start[1] + while curr is not root: + yield curr[2] + curr = curr[1] + + def __iter__(self): + root = self.__root + curr = root[1] + while curr is not root: + yield curr[2] + curr = curr[1] + + def execute(self): + root = self.__root + curr = root[1] + while curr is not root: + if curr[1] is not root: + op_first, op_second = curr[2], curr[1][2] + if op_first.location == op_second.location and \ + type(op_first) == RemoveOperation and \ + type(op_second) == AddOperation: + yield ReplaceOperation({ + 'op': 'replace', + 'path': op_second.location, + 'value': op_second.operation['value'], + }, pointer_cls=self.pointer_cls).operation + curr = curr[1][1] + continue + + yield curr[2].operation + curr = curr[1] + + def _item_added(self, path, key, item): + index = self.take_index(item, _ST_REMOVE) + if index is not None: + op = index[2] + if type(op.key) == int and type(key) == int: + for v in self.iter_from(index): + op.key = v._on_undo_remove(op.path, op.key) + + self.remove(index) + if op.location != _path_join(path, key): + new_op = MoveOperation({ + 'op': 'move', + 'from': op.location, + 'path': _path_join(path, key), + }, pointer_cls=self.pointer_cls) + self.insert(new_op) else: - matrix[i][j] = 0 - return range_src, range_dst - - -def _split_by_common_seq(src, dst, bx=(0, -1), by=(0, -1)): - """Recursively splits the `dst` list onto two parts: left and right. - The left part contains differences on left from common subsequence, - same as the right part by for other side. - - To easily understand the process let's take two lists: [0, 1, 2, 3] as - `src` and [1, 2, 4, 5] for `dst`. If we've tried to generate the binary tree - where nodes are common subsequence for both lists, leaves on the left - side are subsequence for `src` list and leaves on the right one for `dst`, - our tree would looks like:: - - [1, 2] - / \ - [0] [] - / \ - [3] [4, 5] - - This function generate the similar structure as flat tree, but without - nodes with common subsequences - since we're don't need them - only with - left and right leaves:: - - [] - / \ - [0] [] - / \ - [3] [4, 5] - - The `bx` is the absolute range for currently processed subsequence of - `src` list. The `by` means the same, but for the `dst` list. - """ - # Prevent useless comparisons in future - bx = bx if bx[0] != bx[1] else None - by = by if by[0] != by[1] else None + 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) + + 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] + # 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) + + self.remove(index) + if new_op.location != op.location: + new_op = MoveOperation({ + 'op': 'move', + 'from': new_op.location, + 'path': op.location, + }, pointer_cls=self.pointer_cls) + new_index[2] = new_op - if not src: - return [None, by] - elif not dst: - return [bx, None] + else: + self.remove(new_index) + + else: + self.store_index(item, new_index, _ST_REMOVE) + + def _item_replaced(self, path, key, item): + self.insert(ReplaceOperation({ + '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()) + dst_keys = set(dst.keys()) + added_keys = dst_keys - src_keys + removed_keys = src_keys - dst_keys + + for key in removed_keys: + self._item_removed(path, str(key), src[key]) + + for key in added_keys: + self._item_added(path, str(key), dst[key]) + + for key in src_keys & dst_keys: + self._compare_values(path, key, src[key], dst[key]) + + def _compare_lists(self, path, src, dst): + len_src, len_dst = len(src), len(dst) + max_len = max(len_src, len_dst) + min_len = min(len_src, len_dst) + for key in range(max_len): + if key < min_len: + old, new = src[key], dst[key] + if old == new: + continue - # note that these ranges are relative for processed sublists - x, y = _longest_common_subseq(src, dst) + elif isinstance(old, MutableMapping) and \ + isinstance(new, MutableMapping): + self._compare_dicts(_path_join(path, key), old, new) - if x is None or y is None: # no more any common subsequence - return [bx, by] + elif isinstance(old, MutableSequence) and \ + isinstance(new, MutableSequence): + self._compare_lists(_path_join(path, key), old, new) - return [_split_by_common_seq(src[:x[0]], dst[:y[0]], - (bx[0], bx[0] + x[0]), - (by[0], by[0] + y[0])), - _split_by_common_seq(src[x[1]:], dst[y[1]:], - (bx[0] + x[1], bx[0] + len(src)), - (bx[0] + y[1], bx[0] + len(dst)))] + else: + self._item_removed(path, key, old) + self._item_added(path, key, new) + elif len_src > len_dst: + self._item_removed(path, len_dst, src[key]) -def _compare(path, src, dst, left, right): - """Same as :func:`_compare_with_shift` but strips emitted `shift` value.""" - for op, _ in _compare_with_shift(path, src, dst, left, right, 0): - yield op + else: + self._item_added(path, key, dst[key]) + + def _compare_values(self, path, key, src, dst): + if isinstance(src, MutableMapping) and \ + isinstance(dst, MutableMapping): + self._compare_dicts(_path_join(path, key), src, dst) + + elif isinstance(src, MutableSequence) and \ + isinstance(dst, MutableSequence): + 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, 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 self.dumps(src) == self.dumps(dst): + return + else: + self._item_replaced(path, key, dst) -def _compare_with_shift(path, src, dst, left, right, shift): - """Recursively compares differences from `left` and `right` sides - from common subsequences. - The `shift` parameter is used to store index shift which caused - by ``add`` and ``remove`` operations. +def _path_join(path, key): + if key is None: + return path - Yields JSON patch operations and list index shift. - """ - if isinstance(left, MutableSequence): - for item, shift in _compare_with_shift(path, src, dst, *left, - shift=shift): - yield item, shift - elif left is not None: - for item, shift in _compare_left(path, src, left, shift): - yield item, shift - - if isinstance(right, MutableSequence): - for item, shift in _compare_with_shift(path, src, dst, *right, - shift=shift): - yield item, shift - elif right is not None: - for item, shift in _compare_right(path, dst, right, shift): - yield item, shift - - -def _compare_left(path, src, left, shift): - """Yields JSON patch ``remove`` operations for elements that are only - exists in the `src` list.""" - start, end = left - if end == -1: - end = len(src) - # we need to `remove` elements from list tail to not deal with index shift - for idx in reversed(range(start + shift, end + shift)): - ptr = JsonPointer.from_parts(path + [str(idx)]) - yield ( - {'op': 'remove', - # yes, there should be any value field, but we'll use it - # to apply `move` optimization a bit later and will remove - # it in _optimize function. - 'value': src[idx - shift], - 'path': ptr.path, - }, - shift - 1 - ) - shift -= 1 - - -def _compare_right(path, dst, right, shift): - """Yields JSON patch ``add`` operations for elements that are only - exists in the `dst` list""" - start, end = right - if end == -1: - end = len(dst) - for idx in range(start, end): - ptr = JsonPointer.from_parts(path + [str(idx)]) - yield ( - {'op': 'add', 'path': ptr.path, 'value': dst[idx]}, - shift + 1 - ) - shift += 1 - - -def _optimize(operations): - """Optimizes operations which was produced by lists comparison. - - Actually it does two kinds of optimizations: - - 1. Seeks pair of ``remove`` and ``add`` operations against the same path - and replaces them with ``replace`` operation. - 2. Seeks pair of ``remove`` and ``add`` operations for the same value - and replaces them with ``move`` operation. - """ - result = [] - ops_by_path = {} - ops_by_value = {} - add_remove = set(['add', 'remove']) - for item in operations: - # could we apply "move" optimization for dict values? - hashable_value = not isinstance(item['value'], - (MutableMapping, MutableSequence)) - if item['path'] in ops_by_path: - _optimize_using_replace(ops_by_path[item['path']], item) - continue - if hashable_value and item['value'] in ops_by_value: - prev_item = ops_by_value[item['value']] - # ensure that we processing pair of add-remove ops - if set([item['op'], prev_item['op']]) == add_remove: - _optimize_using_move(prev_item, item) - ops_by_value.pop(item['value']) - continue - result.append(item) - ops_by_path[item['path']] = item - if hashable_value: - ops_by_value[item['value']] = item - - # cleanup - ops_by_path.clear() - ops_by_value.clear() - for item in result: - if item['op'] == 'remove': - item.pop('value') # strip our hack - yield item - - -def _optimize_using_replace(prev, cur): - """Optimises JSON patch by using ``replace`` operation instead of - ``remove`` and ``add`` against the same path.""" - prev['op'] = 'replace' - if cur['op'] == 'add': - prev['value'] = cur['value'] - - -def _optimize_using_move(prev_item, item): - """Optimises JSON patch by using ``move`` operation instead of - ``remove` and ``add`` against the different paths but for the same value.""" - prev_item['op'] = 'move' - move_from, move_to = [ - (item['path'], prev_item['path']), - (prev_item['path'], item['path']), - ][item['op'] == 'add'] - if item['op'] == 'add': # first was remove then add - prev_item['from'] = move_from - prev_item['path'] = move_to - else: # first was add then remove - head, move_from = move_from.rsplit('/', 1) - # since add operation was first it incremented - # overall index shift value. we have to fix this - move_from = int(move_from) - 1 - prev_item['from'] = head + '/%d' % move_from - prev_item['path'] = move_to + return path + '/' + str(key).replace('~', '~0').replace('/', '~1') diff --git a/makefile b/makefile index 01cef8a..ec70742 100644 --- a/makefile +++ b/makefile @@ -10,7 +10,8 @@ help: @echo test: - python tests.py + python -Wd -m coverage run --branch --source=jsonpatch tests.py + coverage report --show-missing coverage: coverage run --source=jsonpatch tests.py 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.cfg b/setup.cfg new file mode 100644 index 0000000..2a9acf1 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal = 1 diff --git a/setup.py b/setup.py index d31b990..ab9f32a 100644 --- a/setup.py +++ b/setup.py @@ -1,9 +1,8 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- -import sys import io import re -import warnings try: from setuptools import setup has_setuptools = True @@ -22,17 +21,12 @@ ) REQUIREMENTS = list(open('requirements.txt')) -if sys.version_info < (2, 6): - REQUIREMENTS += ['simplejson'] if has_setuptools: OPTIONS = { 'install_requires': REQUIREMENTS } else: - if sys.version_info < (2, 6): - warnings.warn('No setuptools installed. Be sure that you have ' - 'json or simplejson package installed') OPTIONS = {} AUTHOR_EMAIL = metadata['author'] @@ -60,12 +54,14 @@ 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.3', - 'Programming Language :: Python :: 3.4', + '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', @@ -85,5 +81,14 @@ 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.*, !=3.5.*, !=3.6.*', + project_urls={ + 'Website': 'https://github.com/stefankoegl/python-json-patch', + 'Repository': 'https://github.com/stefankoegl/python-json-patch.git', + 'Documentation': "https://python-json-patch.readthedocs.org/", + 'PyPI': 'https://pypi.org/pypi/jsonpatch', + 'Tests': 'https://travis-ci.org/stefankoegl/python-json-patch', + 'Test Coverage': 'https://coveralls.io/r/stefankoegl/python-json-patch', + }, **OPTIONS ) diff --git a/tests.js b/tests.js new file mode 100644 index 0000000..a09a8d6 --- /dev/null +++ b/tests.js @@ -0,0 +1,398 @@ +[ + { "comment": "empty list, empty docs", + "doc": {}, + "patch": [], + "expected": {} }, + + { "comment": "empty patch list", + "doc": {"foo": 1}, + "patch": [], + "expected": {"foo": 1} }, + + { "comment": "rearrangements OK?", + "doc": {"foo": 1, "bar": 2}, + "patch": [], + "expected": {"bar":2, "foo": 1} }, + + { "comment": "rearrangements OK? How about one level down ... array", + "doc": [{"foo": 1, "bar": 2}], + "patch": [], + "expected": [{"bar":2, "foo": 1}] }, + + { "comment": "rearrangements OK? How about one level down...", + "doc": {"foo":{"foo": 1, "bar": 2}}, + "patch": [], + "expected": {"foo":{"bar":2, "foo": 1}} }, + + { "comment": "add replaces any existing field", + "doc": {"foo": null}, + "patch": [{"op": "add", "path": "/foo", "value":1}], + "expected": {"foo": 1} }, + + { "comment": "toplevel array", + "doc": [], + "patch": [{"op": "add", "path": "/0", "value": "foo"}], + "expected": ["foo"] }, + + { "comment": "toplevel array, no change", + "doc": ["foo"], + "patch": [], + "expected": ["foo"] }, + + { "comment": "toplevel object, numeric string", + "doc": {}, + "patch": [{"op": "add", "path": "/foo", "value": "1"}], + "expected": {"foo":"1"} }, + + { "comment": "toplevel object, integer", + "doc": {}, + "patch": [{"op": "add", "path": "/foo", "value": 1}], + "expected": {"foo":1} }, + + { "comment": "Toplevel scalar values OK?", + "doc": "foo", + "patch": [{"op": "replace", "path": "", "value": "bar"}], + "expected": "bar", + "disabled": true }, + + { "comment": "Add, / target", + "doc": {}, + "patch": [ {"op": "add", "path": "/", "value":1 } ], + "expected": {"":1} }, + + { "comment": "Add, /foo/ deep target (trailing slash)", + "doc": {"foo": {}}, + "patch": [ {"op": "add", "path": "/foo/", "value":1 } ], + "expected": {"foo":{"": 1}} }, + + { "comment": "Add composite value at top level", + "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": [1, 2]}], + "expected": {"foo": 1, "bar": [1, 2]} }, + + { "comment": "Add into composite value", + "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "add", "path": "/baz/0/foo", "value": "world"}], + "expected": {"foo": 1, "baz": [{"qux": "hello", "foo": "world"}]} }, + + { "doc": {"bar": [1, 2]}, + "patch": [{"op": "add", "path": "/bar/8", "value": "5"}], + "error": "Out of bounds (upper)" }, + + { "doc": {"bar": [1, 2]}, + "patch": [{"op": "add", "path": "/bar/-1", "value": "5"}], + "error": "Out of bounds (lower)" }, + + { "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": true}], + "expected": {"foo": 1, "bar": true} }, + + { "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": false}], + "expected": {"foo": 1, "bar": false} }, + + { "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/bar", "value": null}], + "expected": {"foo": 1, "bar": null} }, + + { "comment": "0 can be an array index or object element name", + "doc": {"foo": 1}, + "patch": [{"op": "add", "path": "/0", "value": "bar"}], + "expected": {"foo": 1, "0": "bar" } }, + + { "doc": ["foo"], + "patch": [{"op": "add", "path": "/1", "value": "bar"}], + "expected": ["foo", "bar"] }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/1", "value": "bar"}], + "expected": ["foo", "bar", "sil"] }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/0", "value": "bar"}], + "expected": ["bar", "foo", "sil"] }, + + { "comment": "push item to array via last index + 1", + "doc": ["foo", "sil"], + "patch": [{"op":"add", "path": "/2", "value": "bar"}], + "expected": ["foo", "sil", "bar"] }, + + { "comment": "add item to array at index > length should fail", + "doc": ["foo", "sil"], + "patch": [{"op":"add", "path": "/3", "value": "bar"}], + "error": "index is greater than number of items in array" }, + + { "comment": "test against implementation-specific numeric parsing", + "doc": {"1e0": "foo"}, + "patch": [{"op": "test", "path": "/1e0", "value": "foo"}], + "expected": {"1e0": "foo"} }, + + { "comment": "test with bad number should fail", + "doc": ["foo", "bar"], + "patch": [{"op": "test", "path": "/1e0", "value": "bar"}], + "error": "test op shouldn't get array element 1" }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/bar", "value": 42}], + "error": "Object operation on array target" }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/1", "value": ["bar", "baz"]}], + "expected": ["foo", ["bar", "baz"], "sil"], + "comment": "value in array add not flattened" }, + + { "doc": {"foo": 1, "bar": [1, 2, 3, 4]}, + "patch": [{"op": "remove", "path": "/bar"}], + "expected": {"foo": 1} }, + + { "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "remove", "path": "/baz/0/qux"}], + "expected": {"foo": 1, "baz": [{}]} }, + + { "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "replace", "path": "/foo", "value": [1, 2, 3, 4]}], + "expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]} }, + + { "doc": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]}, + "patch": [{"op": "replace", "path": "/baz/0/qux", "value": "world"}], + "expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "world"}]} }, + + { "doc": ["foo"], + "patch": [{"op": "replace", "path": "/0", "value": "bar"}], + "expected": ["bar"] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": 0}], + "expected": [0] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": true}], + "expected": [true] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": false}], + "expected": [false] }, + + { "doc": [""], + "patch": [{"op": "replace", "path": "/0", "value": null}], + "expected": [null] }, + + { "doc": ["foo", "sil"], + "patch": [{"op": "replace", "path": "/1", "value": ["bar", "baz"]}], + "expected": ["foo", ["bar", "baz"]], + "comment": "value in array replace not flattened" }, + + { "comment": "replace whole document", + "doc": {"foo": "bar"}, + "patch": [{"op": "replace", "path": "", "value": {"baz": "qux"}}], + "expected": {"baz": "qux"} }, + + { "comment": "spurious patch properties", + "doc": {"foo": 1}, + "patch": [{"op": "test", "path": "/foo", "value": 1, "spurious": 1}], + "expected": {"foo": 1} }, + + { "doc": {"foo": null}, + "patch": [{"op": "test", "path": "/foo", "value": null}], + "comment": "null value should be valid obj property" }, + + { "doc": {"foo": null}, + "patch": [{"op": "replace", "path": "/foo", "value": "truthy"}], + "expected": {"foo": "truthy"}, + "comment": "null value should be valid obj property to be replaced with something truthy" }, + + { "doc": {"foo": null}, + "patch": [{"op": "move", "from": "/foo", "path": "/bar"}], + "expected": {"bar": null}, + "comment": "null value should be valid obj property to be moved" }, + + { "doc": {"foo": null}, + "patch": [{"op": "copy", "from": "/foo", "path": "/bar"}], + "expected": {"foo": null, "bar": null}, + "comment": "null value should be valid obj property to be copied" }, + + { "doc": {"foo": null}, + "patch": [{"op": "remove", "path": "/foo"}], + "expected": {}, + "comment": "null value should be valid obj property to be removed" }, + + { "doc": {"foo": "bar"}, + "patch": [{"op": "replace", "path": "/foo", "value": null}], + "expected": {"foo": null}, + "comment": "null value should still be valid obj property replace other value" }, + + { "doc": {"foo": {"foo": 1, "bar": 2}}, + "patch": [{"op": "test", "path": "/foo", "value": {"bar": 2, "foo": 1}}], + "comment": "test should pass despite rearrangement" }, + + { "doc": {"foo": [{"foo": 1, "bar": 2}]}, + "patch": [{"op": "test", "path": "/foo", "value": [{"bar": 2, "foo": 1}]}], + "comment": "test should pass despite (nested) rearrangement" }, + + { "doc": {"foo": {"bar": [1, 2, 5, 4]}}, + "patch": [{"op": "test", "path": "/foo", "value": {"bar": [1, 2, 5, 4]}}], + "comment": "test should pass - no error" }, + + { "doc": {"foo": {"bar": [1, 2, 5, 4]}}, + "patch": [{"op": "test", "path": "/foo", "value": [1, 2]}], + "error": "test op should fail" }, + + { "comment": "Whole document", + "doc": { "foo": 1 }, + "patch": [{"op": "test", "path": "", "value": {"foo": 1}}], + "disabled": true }, + + { "comment": "Empty-string element", + "doc": { "": 1 }, + "patch": [{"op": "test", "path": "/", "value": 1}] }, + + { "doc": { + "foo": ["bar", "baz"], + "": 0, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + " ": 7, + "m~n": 8 + }, + "patch": [{"op": "test", "path": "/foo", "value": ["bar", "baz"]}, + {"op": "test", "path": "/foo/0", "value": "bar"}, + {"op": "test", "path": "/", "value": 0}, + {"op": "test", "path": "/a~1b", "value": 1}, + {"op": "test", "path": "/c%d", "value": 2}, + {"op": "test", "path": "/e^f", "value": 3}, + {"op": "test", "path": "/g|h", "value": 4}, + {"op": "test", "path": "/i\\j", "value": 5}, + {"op": "test", "path": "/k\"l", "value": 6}, + {"op": "test", "path": "/ ", "value": 7}, + {"op": "test", "path": "/m~0n", "value": 8}] }, + + { "comment": "Move to same location has no effect", + "doc": {"foo": 1}, + "patch": [{"op": "move", "from": "/foo", "path": "/foo"}], + "expected": {"foo": 1} }, + + { "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "move", "from": "/foo", "path": "/bar"}], + "expected": {"baz": [{"qux": "hello"}], "bar": 1} }, + + { "doc": {"baz": [{"qux": "hello"}], "bar": 1}, + "patch": [{"op": "move", "from": "/baz/0/qux", "path": "/baz/1"}], + "expected": {"baz": [{}, "hello"], "bar": 1} }, + + { "doc": {"baz": [{"qux": "hello"}], "bar": 1}, + "patch": [{"op": "copy", "from": "/baz/0", "path": "/boo"}], + "expected": {"baz":[{"qux":"hello"}],"bar":1,"boo":{"qux":"hello"}} }, + + { "comment": "replacing the root of the document is possible with add", + "doc": {"foo": "bar"}, + "patch": [{"op": "add", "path": "", "value": {"baz": "qux"}}], + "expected": {"baz":"qux"}}, + + { "comment": "Adding to \"/-\" adds to the end of the array", + "doc": [ 1, 2 ], + "patch": [ { "op": "add", "path": "/-", "value": { "foo": [ "bar", "baz" ] } } ], + "expected": [ 1, 2, { "foo": [ "bar", "baz" ] } ]}, + + { "comment": "Adding to \"/-\" adds to the end of the array, even n levels down", + "doc": [ 1, 2, [ 3, [ 4, 5 ] ] ], + "patch": [ { "op": "add", "path": "/2/1/-", "value": { "foo": [ "bar", "baz" ] } } ], + "expected": [ 1, 2, [ 3, [ 4, 5, { "foo": [ "bar", "baz" ] } ] ] ]}, + + { "comment": "test remove with bad number should fail", + "doc": {"foo": 1, "baz": [{"qux": "hello"}]}, + "patch": [{"op": "remove", "path": "/baz/1e0/qux"}], + "error": "remove op shouldn't remove from array with bad number" }, + + { "comment": "test remove on array", + "doc": [1, 2, 3, 4], + "patch": [{"op": "remove", "path": "/0"}], + "expected": [2, 3, 4] }, + + { "comment": "test repeated removes", + "doc": [1, 2, 3, 4], + "patch": [{ "op": "remove", "path": "/1" }, + { "op": "remove", "path": "/2" }], + "expected": [1, 3] }, + + { "comment": "test remove with bad index should fail", + "doc": [1, 2, 3, 4], + "patch": [{"op": "remove", "path": "/1e0"}], + "error": "remove op shouldn't remove from array with bad number" }, + + { "comment": "test replace with bad number should fail", + "doc": [""], + "patch": [{"op": "replace", "path": "/1e0", "value": false}], + "error": "replace op shouldn't replace in array with bad number" }, + + { "comment": "test copy with bad number should fail", + "doc": {"baz": [1,2,3], "bar": 1}, + "patch": [{"op": "copy", "from": "/baz/1e0", "path": "/boo"}], + "error": "copy op shouldn't work with bad number" }, + + { "comment": "test move with bad number should fail", + "doc": {"foo": 1, "baz": [1,2,3,4]}, + "patch": [{"op": "move", "from": "/baz/1e0", "path": "/foo"}], + "error": "move op shouldn't work with bad number" }, + + { "comment": "test add with bad number should fail", + "doc": ["foo", "sil"], + "patch": [{"op": "add", "path": "/1e0", "value": "bar"}], + "error": "add op shouldn't add to array with bad number" }, + + { "comment": "missing 'value' parameter to add", + "doc": [ 1 ], + "patch": [ { "op": "add", "path": "/-" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing 'value' parameter to replace", + "doc": [ 1 ], + "patch": [ { "op": "replace", "path": "/0" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing 'value' parameter to test", + "doc": [ null ], + "patch": [ { "op": "test", "path": "/0" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing value parameter to test - where undef is falsy", + "doc": [ false ], + "patch": [ { "op": "test", "path": "/0" } ], + "error": "missing 'value' parameter" }, + + { "comment": "missing from parameter to copy", + "doc": [ 1 ], + "patch": [ { "op": "copy", "path": "/-" } ], + "error": "missing 'from' parameter" }, + + { "comment": "missing from parameter to move", + "doc": { "foo": 1 }, + "patch": [ { "op": "move", "path": "" } ], + "error": "missing 'from' parameter" }, + + { "comment": "duplicate ops", + "doc": { "foo": "bar" }, + "patch": [ { "op": "add", "path": "/baz", "value": "qux", + "op": "move", "from":"/foo" } ], + "error": "patch has two 'op' members", + "disabled": true }, + + { "comment": "unrecognized op should fail", + "doc": {"foo": 1}, + "patch": [{"op": "spam", "path": "/foo", "value": 1}], + "error": "Unrecognized op 'spam'" }, + + { "comment": "test with bad array number that has leading zeros", + "doc": ["foo", "bar"], + "patch": [{"op": "test", "path": "/00", "value": "foo"}], + "error": "test op should reject the array value, it has leading zeros" }, + + { "comment": "test with bad array number that has leading zeros", + "doc": ["foo", "bar"], + "patch": [{"op": "test", "path": "/01", "value": "bar"}], + "error": "test op should reject the array value, it has leading zeros" } + +] diff --git a/tests.py b/tests.py index 5cbff33..d9eea92 100755 --- a/tests.py +++ b/tests.py @@ -4,15 +4,49 @@ 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): + def test_js_file(self): + with open('./tests.js', 'r') as f: + tests = json.load(f) + for test in tests: + try: + if 'expected' not in test: + continue + result = jsonpatch.apply_patch(test['doc'], test['patch']) + self.assertEqual(result, test['expected']) + except Exception: + if test.get('error'): + continue + else: + raise + + def test_success_if_replaced_dict(self): + src = [{'a': 1}, {'b': 2}] + dst = [{'a': 1, 'b': 2}] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.apply(src), dst) + + def test_success_if_raise_no_error(self): + src = [{}] + dst = [{'key': ''}] + patch = jsonpatch.make_patch(src, dst) + patch.apply(src) + self.assertTrue(True) + def test_apply_patch_from_string(self): obj = {'foo': 'bar'} patch = '[{"op": "add", "path": "/baz", "value": "qux"}]' @@ -53,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'}]) @@ -156,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, @@ -191,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): @@ -239,6 +296,33 @@ 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): @@ -299,7 +383,9 @@ def test_add_nested(self): } self.assertEqual(expected, res) - def test_should_just_add_new_item_not_rebuild_all_list(self): + # TODO: this test is currently disabled, as the optimized patch is + # not ideal + def _test_should_just_add_new_item_not_rebuild_all_list(self): src = {'foo': [1, 2, 3]} dst = {'foo': [3, 1, 2, 3]} patch = list(jsonpatch.make_patch(src, dst)) @@ -308,6 +394,210 @@ def test_should_just_add_new_item_not_rebuild_all_list(self): res = jsonpatch.apply_patch(src, patch) self.assertEqual(res, dst) + def test_escape(self): + src = {"x/y": 1} + dst = {"x/y": 2} + patch = jsonpatch.make_patch(src, dst) + self.assertEqual([{"path": "/x~1y", "value": 2, "op": "replace"}], patch.patch) + res = patch.apply(src) + self.assertEqual(res, dst) + + def test_root_list(self): + """ Test making and applying a patch of the root is a list """ + src = [{'foo': 'bar', 'boo': 'qux'}] + dst = [{'baz': 'qux', 'foo': 'boo'}] + patch = jsonpatch.make_patch(src, dst) + res = patch.apply(src) + self.assertEqual(res, dst) + + def test_make_patch_unicode(self): + """ Test if unicode keys and values are handled correctly """ + src = {} + dst = {'\xee': '\xee'} + patch = jsonpatch.make_patch(src, dst) + res = patch.apply(src) + self.assertEqual(res, dst) + + def test_issue40(self): + """ Tests an issue in _split_by_common_seq reported in #40 """ + + src = [8, 7, 2, 1, 0, 9, 4, 3, 5, 6] + dest = [7, 2, 1, 0, 9, 4, 3, 6, 5, 8] + jsonpatch.make_patch(src, dest) + + def test_issue76(self): + """ Make sure op:remove does not include a 'value' field """ + + src = { "name": "fred", "friend": "barney", "spouse": "wilma" } + dst = { "name": "fred", "spouse": "wilma" } + expected = [{"path": "/friend", "op": "remove"}] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.patch, expected) + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) + + def test_json_patch(self): + old = { + 'queue': {'teams_out': [{'id': 3, 'reason': 'If tied'}, {'id': 5, 'reason': 'If tied'}]}, + } + new = { + 'queue': {'teams_out': [{'id': 5, 'reason': 'If lose'}]} + } + patch = jsonpatch.make_patch(old, new) + new_from_patch = jsonpatch.apply_patch(old, patch) + self.assertEqual(new, new_from_patch) + + def test_arrays_one_element_sequences(self): + """ Tests the case of multiple common one element sequences inside an array """ + # see https://github.com/stefankoegl/python-json-patch/issues/30#issuecomment-155070128 + src = [1,2,3] + dst = [3,1,4,2] + patch = jsonpatch.make_patch(src, dst) + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) + + def test_list_in_dict(self): + """ Test patch creation with a list within a dict, as reported in #74 + + https://github.com/stefankoegl/python-json-patch/issues/74 """ + old = {'key': [{'someNumber': 0, 'someArray': [1, 2, 3]}]} + new = {'key': [{'someNumber': 0, 'someArray': [1, 2, 3, 4]}]} + patch = jsonpatch.make_patch(old, new) + new_from_patch = jsonpatch.apply_patch(old, patch) + self.assertEqual(new, new_from_patch) + + def test_nested(self): + """ Patch creation with nested dicts, as reported in #41 + + https://github.com/stefankoegl/python-json-patch/issues/41 """ + old = {'school':{'names':['Kevin','Carl']}} + new = {'school':{'names':['Carl','Kate','Kevin','Jake']}} + patch = jsonpatch.JsonPatch.from_diff(old, new) + new_from_patch = jsonpatch.apply_patch(old, patch) + self.assertEqual(new, new_from_patch) + + def test_move_from_numeric_to_alpha_dict_key(self): + #https://github.com/stefankoegl/python-json-patch/issues/97 + src = {'13': 'x'} + dst = {'A': 'a', 'b': 'x'} + patch = jsonpatch.make_patch(src, dst) + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) + + def test_issue90(self): + """In JSON 1 is different from True even though in python 1 == True""" + src = {'A': 1} + dst = {'A': True} + patch = jsonpatch.make_patch(src, dst) + res = jsonpatch.apply_patch(src, patch) + 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} + dst = {'A': 1.0} + patch = jsonpatch.make_patch(src, dst) + res = jsonpatch.apply_patch(src, patch) + 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): def test_use_replace_instead_of_remove_add(self): src = {'foo': [1, 2, 3]} dst = {'foo': [3, 2, 3]} @@ -317,6 +607,17 @@ def test_use_replace_instead_of_remove_add(self): res = jsonpatch.apply_patch(src, patch) self.assertEqual(res, dst) + def test_use_replace_instead_of_remove_add_nested(self): + src = {'foo': [{'bar': 1, 'baz': 2}, {'bar': 2, 'baz': 3}]} + dst = {'foo': [{'bar': 1}, {'bar': 2, 'baz': 3}]} + patch = list(jsonpatch.make_patch(src, dst)) + + exp = [{'op': 'remove', 'path': '/foo/0/baz'}] + self.assertEqual(patch, exp) + + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) + def test_use_move_instead_of_remove_add(self): src = {'foo': [4, 1, 2, 3]} dst = {'foo': [1, 2, 3, 4]} @@ -327,34 +628,104 @@ def test_use_move_instead_of_remove_add(self): self.assertEqual(res, dst) def test_use_move_instead_of_add_remove(self): - src = {'foo': [1, 2, 3]} - dst = {'foo': [3, 1, 2]} - patch = list(jsonpatch.make_patch(src, dst)) - self.assertEqual(len(patch), 1) - self.assertEqual(patch[0]['op'], 'move') + def fn(_src, _dst): + patch = list(jsonpatch.make_patch(_src, _dst)) + # Check if there are only 'move' operations + for p in patch: + self.assertEqual(p['op'], 'move') + res = jsonpatch.apply_patch(_src, patch) + self.assertEqual(res, _dst) + + fn({'foo': [1, 2, 3]}, {'foo': [3, 1, 2]}) + fn([1, 2, 3], [3, 1, 2]) + fn({'foo': [1, 2, 3]}, {'foo': [3, 2, 1]}) + fn([1, 2, 3], [3, 2, 1]) + + def test_success_if_replace_inside_dict(self): + src = [{'a': 1, 'foo': {'b': 2, 'd': 5}}] + dst = [{'a': 1, 'foo': {'b': 3, 'd': 6}}] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.apply(src), dst) + + def test_success_if_replace_single_value(self): + src = [{'a': 1, 'b': 2, 'd': 5}] + dst = [{'a': 1, 'c': 3, 'd': 5}] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.apply(src), dst) + + def test_success_if_replaced_by_object(self): + src = [{'a': 1, 'b': 2, 'd': 5}] + dst = [{'d': 6}] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.apply(src), dst) + + def test_success_if_correct_patch_appied(self): + src = [{'a': 1}, {'b': 2}] + dst = [{'a': 1, 'b': 2}] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.apply(src), dst) + + def test_success_if_correct_expected_patch_appied(self): + src = [{"a": 1, "b": 2}] + dst = [{"b": 2, "c": 2}] + exp = [ + {'path': '/0/a', 'op': 'remove'}, + {'path': '/0/c', 'op': 'add', 'value': 2} + ] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.patch, exp) + # verify that this patch does what we expect res = jsonpatch.apply_patch(src, patch) self.assertEqual(res, dst) - def test_escape(self): - src = {"x/y": 1} - dst = {"x/y": 2} + def test_minimal_patch(self): + """ Test whether a minimal patch is created, see #36 """ + src = [{"foo": 1, "bar": 2}] + dst = [{"foo": 2, "bar": 2}] + + patch = jsonpatch.make_patch(src, dst) + + exp = [ + { + "path": "/0/foo", + "value": 2, + "op": "replace" + } + ] + + self.assertEqual(patch.patch, exp) + + +class ListTests(unittest.TestCase): + + def test_fail_prone_list_1(self): + """ Test making and applying a patch of the root is a list """ + src = ['a', 'r', 'b'] + dst = ['b', 'o'] patch = jsonpatch.make_patch(src, dst) - self.assertEqual([{"path": "/x~1y", "value": 2, "op": "replace"}], patch.patch) res = patch.apply(src) self.assertEqual(res, dst) - def test_root_list(self): + def test_fail_prone_list_2(self): """ Test making and applying a patch of the root is a list """ - src = [{'foo': 'bar', 'boo': 'qux'}] - dst = [{'baz': 'qux', 'foo': 'boo'}] + src = ['a', 'r', 'b', 'x', 'm', 'n'] + dst = ['b', 'o', 'm', 'n'] patch = jsonpatch.make_patch(src, dst) res = patch.apply(src) self.assertEqual(res, dst) - def test_make_patch_unicode(self): - """ Test if unicode keys and values are handled correctly """ - src = {} - dst = {'\xee': '\xee'} + def test_fail_prone_list_3(self): + """ Test making and applying a patch of the root is a list """ + src = ['boo1', 'bar', 'foo1', 'qux'] + dst = ['qux', 'bar'] + patch = jsonpatch.make_patch(src, dst) + res = patch.apply(src) + self.assertEqual(res, dst) + + def test_fail_prone_list_4(self): + """ Test making and applying a patch of the root is a list """ + src = ['bar1', 59, 'foo1', 'foo'] + dst = ['foo', 'bar', 'foo1'] patch = jsonpatch.make_patch(src, dst) res = patch.apply(src) self.assertEqual(res, dst) @@ -408,36 +779,299 @@ def test_replace_oob(self): patch_obj = [ { "op": "replace", "path": "/foo/10", "value": 10} ] self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) + def test_replace_oob_length(self): + src = {"foo": [0, 1]} + patch_obj = [ { "op": "replace", "path": "/foo/2", "value": 2} ] + self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) + def test_replace_missing(self): src = {"foo": 1} patch_obj = [ { "op": "replace", "path": "/bar", "value": 10} ] self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) +class JsonPointerTests(unittest.TestCase): + + def test_create_with_pointer(self): + + patch = jsonpatch.JsonPatch([ + {'op': 'add', 'path': jsonpointer.JsonPointer('/foo'), 'value': 'bar'}, + {'op': 'add', 'path': jsonpointer.JsonPointer('/baz'), 'value': [1, 2, 3]}, + {'op': 'remove', 'path': jsonpointer.JsonPointer('/baz/1')}, + {'op': 'test', 'path': jsonpointer.JsonPointer('/baz'), 'value': [1, 3]}, + {'op': 'replace', 'path': jsonpointer.JsonPointer('/baz/0'), 'value': 42}, + {'op': 'remove', 'path': jsonpointer.JsonPointer('/baz/1')}, + {'op': 'move', 'from': jsonpointer.JsonPointer('/foo'), 'path': jsonpointer.JsonPointer('/bar')}, + + ]) + doc = {} + result = patch.apply(doc) + expected = {'bar': 'bar', 'baz': [42]} + 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({}) -modules = ['jsonpatch'] + 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({}) -def get_suite(): - suite = unittest.TestSuite() - suite.addTest(doctest.DocTestSuite(jsonpatch)) - suite.addTest(unittest.makeSuite(ApplyPatchTestCase)) - suite.addTest(unittest.makeSuite(EqualityTestCase)) - suite.addTest(unittest.makeSuite(MakePatchTestCase)) - suite.addTest(unittest.makeSuite(InvalidInputTests)) - suite.addTest(unittest.makeSuite(ConflictTests)) - return suite + 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({}) -suite = get_suite() + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.CopyOperation({'path': '/target', 'from': '/source'}).apply({}) -for module in modules: - m = __import__(module, fromlist=[module]) - suite.addTest(doctest.DocTestSuite(m)) + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.CopyOperation({'path': '/target', 'from': '/source'}).apply({}) -runner = unittest.TextTestRunner(verbosity=1) -result = runner.run(suite) +class CustomJsonPointer(jsonpointer.JsonPointer): + pass -if not result.wasSuccessful(): - sys.exit(1) + +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'] + + + def get_suite(): + suite = unittest.TestSuite() + suite.addTest(doctest.DocTestSuite(jsonpatch)) + suite.addTest(unittest.makeSuite(ApplyPatchTestCase)) + suite.addTest(unittest.makeSuite(EqualityTestCase)) + suite.addTest(unittest.makeSuite(MakePatchTestCase)) + suite.addTest(unittest.makeSuite(ListTests)) + suite.addTest(unittest.makeSuite(InvalidInputTests)) + 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 + + + suite = get_suite() + + for module in modules: + m = __import__(module, fromlist=[module]) + suite.addTest(doctest.DocTestSuite(m)) + + runner = unittest.TextTestRunner(verbosity=1) + + result = runner.run(suite) + + if not result.wasSuccessful(): + sys.exit(1)