diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..f0d91db --- /dev/null +++ b/.coveragerc @@ -0,0 +1,21 @@ +# .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 + pragma: no cover + + # No need to test __repr__ + def __repr__ + + # Python 2/3 compatibility + except ImportError + sys.version_info + + # don't include not implemented methods + NotImplementedError 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 15b2a4a..0000000 --- a/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: python -python: - - "2.6" - - "2.7" - - "3.2" - - "3.3" - - "pypy" -# command to install dependencies -install: pip install -r requirements.txt -# command to run tests -script: nosetests tests.py diff --git a/AUTHORS b/AUTHORS index 3504b55..f5f6363 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,3 +1,4 @@ Stefan Kögl Alexander Shorin Byron Ruth +William Kral 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 f9bd145..ca196b9 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1 +1,7 @@ include requirements.txt +include COPYING +include README.md +include tests.py +include ext_tests.py +include AUTHORS +include tests.js diff --git a/README.md b/README.md index d6469bc..ff2b142 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,28 @@ -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) +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 +* Coveralls: https://coveralls.io/r/stefankoegl/python-json-patch Running external tests ---------------------- -To run external tests (such as those from https://github.com/json-patch/json-patch-tests) use ext_test.py +To run external tests (such as those from https://github.com/json-patch/json-patch-tests) use ext_test.py ./ext_tests.py ../json-patch-tests/tests.json diff --git a/bin/jsondiff b/bin/jsondiff new file mode 100755 index 0000000..5ac0090 --- /dev/null +++ b/bin/jsondiff @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import print_function + +import sys +import json +import jsonpatch +import argparse + + +parser = argparse.ArgumentParser(description='Diff two JSON files') +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__) + + +def main(): + try: + diff_files() + except KeyboardInterrupt: + sys.exit(1) + + +def diff_files(): + """ Diffs two JSON files and prints a patch """ + args = parser.parse_args() + doc1 = json.load(args.FILE1) + doc2 = json.load(args.FILE2) + patch = jsonpatch.make_patch(doc1, doc2) + 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 new file mode 100755 index 0000000..a7adf29 --- /dev/null +++ b/bin/jsonpatch @@ -0,0 +1,107 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import sys +import os.path +import json +import jsonpatch +import tempfile +import argparse + + +parser = argparse.ArgumentParser( + description='Apply a JSON patch on a JSON file') +parser.add_argument('ORIGINAL', type=argparse.FileType('r'), + help='Original file') +parser.add_argument('PATCH', type=argparse.FileType('r'), + nargs='?', default=sys.stdin, + help='Patch file (read from stdin if omitted)') +parser.add_argument('--indent', type=int, default=None, + help='Indent output by n spaces') +parser.add_argument('-b', '--backup', action='store_true', + help='Back up ORIGINAL if modifying in-place') +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: + patch_files() + except KeyboardInterrupt: + sys.exit(1) + + +def patch_files(): + """ Diffs two JSON files and prints a patch """ + args = parser.parse_args() + doc = json.load(args.ORIGINAL) + patch = json.load(args.PATCH) + result = jsonpatch.apply_patch(doc, patch) + + if args.in_place: + dirname = os.path.abspath(os.path.dirname(args.ORIGINAL.name)) + + try: + # Attempt to replace the file atomically. We do this by + # creating a temporary file in the same directory as the + # original file so we can atomically move the new file over + # the original later. (This is done in the same directory + # because atomic renames do not work across mount points.) + + fd, pathname = tempfile.mkstemp(dir=dirname) + fp = os.fdopen(fd, 'w') + atomic = True + + except OSError: + # We failed to create the temporary file for an atomic + # replace, so fall back to non-atomic mode by backing up + # the original (if desired) and writing a new file. + + if args.backup: + os.rename(args.ORIGINAL.name, args.ORIGINAL.name + '.orig') + fp = open(args.ORIGINAL.name, 'w') + atomic = False + + else: + # Since we're not replacing the original file in-place, write + # the modified JSON to stdout instead. + + fp = sys.stdout + + # By this point we have some sort of file object we can write the + # modified JSON to. + + json.dump(result, fp, indent=args.indent, ensure_ascii=not(args.preserve_unicode)) + fp.write('\n') + + if args.in_place: + # Close the new file. If we aren't replacing atomically, this + # is our last step, since everything else is already in place. + + fp.close() + + if atomic: + try: + # Complete the atomic replace by linking the original + # to a backup (if desired), fixing up the permissions + # on the temporary file, and moving it into place. + + if args.backup: + os.link(args.ORIGINAL.name, args.ORIGINAL.name + '.orig') + os.chmod(pathname, os.stat(args.ORIGINAL.name).st_mode) + os.rename(pathname, args.ORIGINAL.name) + + except OSError: + # In the event we could not actually do the atomic + # replace, unlink the original to move it out of the + # way and finally move the temporary file into place. + + os.unlink(args.ORIGINAL.name) + os.rename(pathname, args.ORIGINAL.name) + + +if __name__ == "__main__": + main() diff --git a/doc/_static/.empty b/doc/_static/.empty new file mode 100644 index 0000000..e69de29 diff --git a/doc/commandline.rst b/doc/commandline.rst new file mode 100644 index 0000000..a7a78d8 --- /dev/null +++ b/doc/commandline.rst @@ -0,0 +1,113 @@ +Commandline Utilities +===================== + +The JSON patch package contains the commandline utilities ``jsondiff`` and +``jsonpatch``. + +``jsondiff`` +------------ + +The program ``jsondiff`` can be used to create a JSON patch by comparing two +JSON files :: + + usage: jsondiff [-h] [--indent INDENT] [-u] [-v] FILE1 FILE2 + + Diff two JSON files + + positional arguments: + FILE1 + FILE2 + + optional arguments: + -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 +^^^^^^^ + +.. code-block:: bash + + # inspect JSON files + $ cat a.json + { "a": [1, 2], "b": 0 } + + $ cat b.json + { "a": [1, 2, 3], "c": 100 } + + # show patch in "dense" representation + $ jsondiff a.json b.json + [{"path": "/a/2", "value": 3, "op": "add"}, {"path": "/b", "op": "remove"}, {"path": "/c", "value": 100, "op": "add"}] + + # show patch with some indentation + $ jsondiff a.json b.json --indent=2 + [ + { + "path": "/a/2", + "value": 3, + "op": "add" + }, + { + "path": "/b", + "op": "remove" + }, + { + "path": "/c", + "value": 100, + "op": "add" + } + ] + + + +``jsonpatch`` +------------- + +The program ``jsonpatch`` is used to apply JSON patches on JSON files. :: + + usage: jsonpatch [-h] [--indent INDENT] [-v] ORIGINAL PATCH + + Apply a JSON patch on a JSON files + + positional arguments: + ORIGINAL Original file + PATCH Patch file + + optional arguments: + -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 +^^^^^^^ + +.. code-block:: bash + + # create a patch + $ jsondiff a.json b.json > patch.json + + # show the result after applying a patch + $ jsonpatch a.json patch.json + {"a": [1, 2, 3], "c": 100} + + $ jsonpatch a.json patch.json --indent=2 + { + "a": [ + 1, + 2, + 3 + ], + "c": 100 + } + + # pipe result into new file + $ jsonpatch a.json patch.json --indent=2 > c.json + + # c.json now equals b.json + $ jsondiff b.json c.json + [] + diff --git a/doc/index.rst b/doc/index.rst index 8ff216d..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** @@ -18,6 +23,7 @@ and PyPy are supported. tutorial mod-jsonpatch + commandline RFC 6902 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 d7c7585..59a36d2 100755 --- a/ext_tests.py +++ b/ext_tests.py @@ -34,8 +34,6 @@ """ Script to run external tests, eg from https://github.com/json-patch/json-patch-tests """ -from functools import partial -import json import doctest import unittest import jsonpatch @@ -61,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): @@ -94,7 +95,8 @@ def get_suite(filenames): for testfile in filenames: with open(testfile) as f: - tests = json.load(f) + # we use the (potentially) patched version of json.load here + tests = jsonpatch.json.load(f) cls = make_test_case(tests) suite.addTest(unittest.makeSuite(cls)) @@ -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 e115273..d3fc26d 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -30,46 +30,94 @@ # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +""" Apply JSON-Patches (RFC 6902) """ + from __future__ import unicode_literals -""" Apply JSON-Patches (RFC 6902) """ +import collections +import copy +import functools +import json +import sys + +try: + from collections.abc import Sequence +except ImportError: # Python 3 + from collections import Sequence + +try: + from types import MappingProxyType +except ImportError: + # Python < 3.3 + MappingProxyType = dict + +from jsonpointer import JsonPointer, JsonPointerException + + +_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.0' +__version__ = '1.33' __website__ = 'https://github.com/stefankoegl/python-json-patch' __license__ = 'Modified BSD License' -import copy -import sys - -import json - -import jsonpointer +# pylint: disable=E0611,W0404 if sys.version_info >= (3, 0): - basestring = (bytes, str) + basestring = (bytes, str) # pylint: disable=C0103,W0622 -JsonPointerException = jsonpointer.JsonPointerException - class JsonPatchException(Exception): """Base Json Patch exception""" +class InvalidJsonPatch(JsonPatchException): + """ Raised if an invalid JSON Patch is created """ + + 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. """ + class JsonPatchTestFailed(JsonPatchException, AssertionError): """ A Test operation failed """ -def apply_patch(doc, patch, in_place=False): +def multidict(ordered_pairs): + """Convert duplicate keys values to lists.""" + # read all values into lists + mdict = collections.defaultdict(list) + for key, value in ordered_pairs: + mdict[key].append(value) + + return dict( + # unpack lists that have only 1 item + (key, values[0] if len(values) == 1 else values) + for key, values in mdict.items() + ) + + +# 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, pointer_cls=JsonPointer): """Apply list of patches to specified json document. :param doc: Document object. @@ -82,29 +130,35 @@ 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 >>> doc = {'foo': 'bar'} - >>> other = apply_patch(doc, [{'op': 'add', 'path': '/baz', 'value': 'qux'}]) + >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] + >>> other = apply_patch(doc, patch) >>> doc is not other True >>> other == {'foo': 'bar', 'baz': 'qux'} True - >>> apply_patch(doc, [{'op': 'add', 'path': '/baz', 'value': 'qux'}], in_place=True) == {'foo': 'bar', 'baz': 'qux'} + >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] + >>> apply_patch(doc, patch, in_place=True) == {'foo': 'bar', 'baz': 'qux'} True >>> doc == other True """ 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. @@ -113,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) @@ -120,10 +177,343 @@ def make_patch(src, dst): >>> new == dst True """ - return JsonPatch.from_diff(src, dst) + + return JsonPatch.from_diff(src, dst, pointer_cls=pointer_cls) + + +class PatchOperation(object): + """A single operation inside a JSON Patch.""" + + 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") + + 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'") + + self.operation = operation + + def apply(self, obj): + """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())) + + def __eq__(self, other): + if not isinstance(other, PatchOperation): + return False + return self.operation == other.operation + + 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 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.""" + + def apply(self, obj): + try: + value = self.operation["value"] + except KeyError as ex: + raise InvalidJsonPatch( + "The operation does not contain a 'value' member") + + subobj, part = self.pointer.to_last(obj) + + if isinstance(subobj, MutableSequence): + if part == '-': + subobj.append(value) # pylint: disable=E1103 + + elif part > len(subobj) or part < 0: + raise JsonPatchConflict("can't insert outside of list") + + else: + subobj.insert(part, value) # pylint: disable=E1103 + + elif isinstance(subobj, MutableMapping): + if part is None: + obj = value # we're replacing the root + else: + subobj[part] = value + + else: + 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 a new value.""" + + def apply(self, obj): + try: + value = self.operation["value"] + except KeyError as ex: + raise InvalidJsonPatch( + "The operation does not contain a 'value' member") + + subobj, part = self.pointer.to_last(obj) + + if part is None: + return value + + if part == "-": + raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation") + + if isinstance(subobj, MutableSequence): + if part >= len(subobj) or part < 0: + raise JsonPatchConflict("can't replace outside of list") + + elif isinstance(subobj, MutableMapping): + if part not in subobj: + msg = "can't replace a non-existent object '{0}'".format(part) + raise JsonPatchConflict(msg) + else: + 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 a new location.""" + + def apply(self, obj): + try: + 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") + + subobj, part = from_ptr.to_last(obj) + try: + value = subobj[part] + 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 their own children') + + obj = RemoveOperation({ + 'op': 'remove', + 'path': self.operation['from'] + }, pointer_cls=self.pointer_cls).apply(obj) + + obj = AddOperation({ + 'op': 'add', + 'path': self.location, + 'value': value + }, 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.""" + + def apply(self, obj): + try: + subobj, part = self.pointer.to_last(obj) + if part is None: + val = subobj + else: + val = self.pointer.walk(subobj, part) + except JsonPointerException as ex: + raise JsonPatchTestFailed(str(ex)) + + try: + value = self.operation['value'] + except KeyError as ex: + raise InvalidJsonPatch( + "The operation does not contain a 'value' member") + + if val != value: + msg = '{0} ({1}) is not equal to tested value {2} ({3})' + raise JsonPatchTestFailed(msg.format(val, type(val), + value, type(value))) + + return obj + + +class CopyOperation(PatchOperation): + """ Copies an object property or an array element to a new location """ + + def apply(self, obj): + try: + from_ptr = self.pointer_cls(self.operation['from']) + except KeyError as ex: + raise InvalidJsonPatch( + "The operation does not contain a 'from' member") + + subobj, part = from_ptr.to_last(obj) + try: + value = copy.deepcopy(subobj[part]) + except (KeyError, IndexError) as ex: + raise JsonPatchConflict(str(ex)) + + obj = AddOperation({ + 'op': 'add', + 'path': self.location, + 'value': value + }, pointer_cls=self.pointer_cls).apply(obj) + + return obj class JsonPatch(object): + json_dumper = staticmethod(json.dumps) + json_loader = staticmethod(_jsonloads) + + operations = MappingProxyType({ + 'remove': RemoveOperation, + 'add': AddOperation, + 'replace': ReplaceOperation, + 'move': MoveOperation, + 'test': TestOperation, + 'copy': CopyOperation, + }) + """A JSON Patch is a list of Patch Operations. >>> patch = JsonPatch([ @@ -140,8 +530,8 @@ class JsonPatch(object): >>> result == expected True - JsonPatch object is iterable, so you could easily access to each patch - statement in loop: + 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'} @@ -169,17 +559,29 @@ class JsonPatch(object): ... patch.apply(old) #doctest: +ELLIPSIS {...} """ - def __init__(self, patch): + def __init__(self, patch, pointer_cls=JsonPointer): self.patch = patch - - self.operations = { - 'remove': RemoveOperation, - 'add': AddOperation, - 'replace': ReplaceOperation, - 'move': MoveOperation, - 'test': TestOperation, - 'copy': CopyOperation, - } + 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()""" @@ -193,33 +595,43 @@ def __bool__(self): def __iter__(self): return iter(self.patch) - def __hash__(self): - return hash(tuple(self._get_operation(op) for op in self.patch)) - + return hash(tuple(self._ops)) def __eq__(self, other): if not isinstance(other, JsonPatch): return False + return self._ops == other._ops - return self.patch == other.patch - + def __ne__(self, other): + return not(self == other) @classmethod - def from_string(cls, patch_str): + 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. """ - patch = json.loads(patch_str) - return cls(patch) + 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): - """Creates JsonPatch instance based on comparing of two document + 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. @@ -229,6 +641,13 @@ def from_diff(cls, src, dst): :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]} @@ -238,58 +657,29 @@ def from_diff(cls, src, dst): >>> new == dst True """ - def compare_values(path, value, other): - if value == other: - return - if isinstance(value, dict) and isinstance(other, dict): - for operation in compare_dict(path, value, other): - yield operation - elif isinstance(value, list) and isinstance(other, list): - for operation in compare_list(path, value, other): - yield operation - else: - yield {'op': 'replace', 'path': '/'.join(path), 'value': other} + 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 compare_dict(path, src, dst): - for key in src: - if key not in dst: - yield {'op': 'remove', 'path': '/'.join(path + [key])} - 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: - yield {'op': 'add', 'path': '/'.join(path + [key]), 'value': dst[key]} - - def compare_list(path, src, dst): - lsrc, ldst = len(src), len(dst) - for idx in range(min(lsrc, ldst)): - current = path + [str(idx)] - for operation in compare_values(current, src[idx], dst[idx]): - yield operation - if lsrc < ldst: - for idx in range(lsrc, ldst): - current = path + [str(idx)] - yield {'op': 'add', 'path': '/'.join(current), 'value': dst[idx]} - elif lsrc > ldst: - for idx in reversed(range(ldst, lsrc)): - yield {'op': 'remove', 'path': '/'.join(path + [str(idx)])} - - return cls(list(compare_dict([''], src, dst))) - - def to_string(self): + def to_string(self, dumps=None): """Returns patch set as JSON string.""" - return json.dumps(self.patch) + 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 given object. + """Applies the patch to a 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. + :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`. @@ -298,163 +688,244 @@ def apply(self, obj, in_place=False): if not in_place: obj = copy.deepcopy(obj) - for operation in self.patch: - operation = self._get_operation(operation) + for operation in self._ops: obj = operation.apply(obj) return obj def _get_operation(self, operation): if 'op' not in operation: - raise JsonPatchException("Operation does not contain 'op' member") + raise InvalidJsonPatch("Operation does not contain 'op' member") op = operation['op'] - if op not in self.operations: - raise JsonPatchException("Unknown operation '%s'" % op) - cls = self.operations[op] - return cls(operation) - - - -class PatchOperation(object): - """A single operation inside a JSON Patch.""" - - def __init__(self, operation): - self.location = operation['path'] - self.pointer = jsonpointer.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.') - - - def __hash__(self): - return hash(frozenset(self.operation.items())) + 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)) - def __eq__(self, other): - if not isinstance(other, PatchOperation): - return False + cls = self.operations[op] + return cls(operation, pointer_cls=self.pointer_cls) - return self.operation == other.operation +class DiffBuilder(object): -class RemoveOperation(PatchOperation): - """Removes an object property or an array element.""" + 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 apply(self, obj): - subobj, part = self.pointer.to_last(obj) + def store_index(self, value, index, st): + typed_key = (value, type(value)) try: - del subobj[part] - except KeyError as ex: - raise JsonPatchConflict(str(ex)) - - return obj - - -class AddOperation(PatchOperation): - """Adds an object property or an array element.""" - - def apply(self, obj): - value = self.operation["value"] - subobj, part = self.pointer.to_last(obj, None) - - if isinstance(subobj, list): - - if part == '-': - subobj.append(value) - - elif part > len(subobj) or part < 0: - raise JsonPatchConflict("can't insert outside of list") - - else: - subobj.insert(part, value) - - elif isinstance(subobj, dict): - if part is None: - # we're replacing the root - obj = value - + storage = self.index_storage[st] + stored = storage.get(typed_key) + if stored is None: + storage[typed_key] = [index] else: - subobj[part] = value - - else: - raise JsonPatchConflict("can't add to type '%s'" - "" % subobj.__class__.__name__) - - return obj + storage[typed_key].append(index) + except TypeError: + self.index_storage2[st].append((typed_key, index)) -class ReplaceOperation(PatchOperation): - """Replaces an object property or an array element by new value.""" - - def apply(self, obj): - value = self.operation["value"] - subobj, part = self.pointer.to_last(obj) - - if isinstance(subobj, list): - if part > len(subobj) or part < 0: - raise JsonPatchConflict("can't replace outside of list") + 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] - elif isinstance(subobj, dict): - if not part in subobj: - raise JsonPatchConflict("can't replace non-existant object '%s'" - "" % part) + 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: - raise JsonPatchConflict("can't replace in type '%s'" - "" % subobj.__class__.__name__) - - subobj[part] = value - return obj - + 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 -class MoveOperation(PatchOperation): - """Moves an object property or an array element to new location.""" + else: + self.remove(new_index) - def apply(self, obj): - from_ptr = jsonpointer.JsonPointer(self.operation['from']) - subobj, part = from_ptr.to_last(obj) - value = subobj[part] + 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 - if from_ptr.contains(self.pointer): - raise JsonPatchException('Cannot move values into its own children') + elif isinstance(old, MutableMapping) and \ + isinstance(new, MutableMapping): + self._compare_dicts(_path_join(path, key), old, new) - obj = RemoveOperation({'op': 'remove', 'path': self.operation['from']}).apply(obj) - obj = AddOperation({'op': 'add', 'path': self.location, 'value': value}).apply(obj) - return obj + elif isinstance(old, MutableSequence) and \ + isinstance(new, MutableSequence): + self._compare_lists(_path_join(path, key), old, new) + else: + self._item_removed(path, key, old) + self._item_added(path, key, new) -class TestOperation(PatchOperation): - """Test value by specified location.""" + elif len_src > len_dst: + self._item_removed(path, len_dst, src[key]) - def apply(self, obj): - try: - subobj, part = self.pointer.to_last(obj) - if part is None: - val = subobj else: - val = self.pointer.walk(subobj, part) - - except JsonPointerException as ex: - raise JsonPatchTestFailed(str(ex)) + 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 - if 'value' in self.operation: - value = self.operation['value'] - if val != value: - raise JsonPatchTestFailed('%s is not equal to tested value %s (types %s and %s)' % (val, value, type(val), type(value))) + else: + self._item_replaced(path, key, dst) - return obj +def _path_join(path, key): + if key is None: + return path -class CopyOperation(PatchOperation): - """ Copies an object property or an array element to a new location """ - - def apply(self, obj): - from_ptr = jsonpointer.JsonPointer(self.operation['from']) - subobj, part = from_ptr.to_last(obj) - value = copy.deepcopy(subobj[part]) - obj = AddOperation({'op': 'add', 'path': self.location, 'value': value}).apply(obj) - return obj + return path + '/' + str(key).replace('~', '~0').replace('/', '~1') diff --git a/makefile b/makefile new file mode 100644 index 0000000..ec70742 --- /dev/null +++ b/makefile @@ -0,0 +1,18 @@ + +help: + @echo "jsonpatch" + @echo "Makefile targets" + @echo " - test: run tests" + @echo " - coverage: run tests with coverage" + @echo + @echo "To install jsonpatch, type" + @echo " python setup.py install" + @echo + +test: + python -Wd -m coverage run --branch --source=jsonpatch tests.py + coverage report --show-missing + +coverage: + coverage run --source=jsonpatch tests.py + coverage report -m diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..c729ece --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +coverage +wheel +pypandoc diff --git a/requirements.txt b/requirements.txt index a3568cd..cd4b892 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1 @@ -jsonpointer>=1.0 +jsonpointer>=1.9 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 f500075..ab9f32a 100644 --- a/setup.py +++ b/setup.py @@ -1,8 +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 @@ -10,7 +10,7 @@ from distutils.core import setup has_setuptools = False -src = open('jsonpatch.py').read() +src = io.open('jsonpatch.py', encoding='utf-8').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", src)) docstrings = re.findall('"""([^"]*)"""', src, re.MULTILINE | re.DOTALL) @@ -21,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'] @@ -43,14 +38,57 @@ # Extract name and e-mail ("Firstname Lastname ") AUTHOR, EMAIL = re.match(r'(.*) <(.*)>', AUTHOR_EMAIL).groups() +try: + from pypandoc import convert + read_md = lambda f: convert(f, 'rst') +except ImportError: + print('warning: pypandoc module not found, could not convert ' + 'Markdown to RST') + read_md = lambda f: open(f, 'r').read() + +CLASSIFIERS = [ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Console', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + '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', + 'Topic :: Utilities', +] + + setup(name=PACKAGE, version=VERSION, description=DESCRIPTION, + long_description=read_md('README.md'), author=AUTHOR, author_email=EMAIL, license=LICENSE, url=WEBSITE, py_modules=MODULES, 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 d6506e1..d9eea92 100755 --- a/tests.py +++ b/tests.py @@ -3,14 +3,50 @@ 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"}]' @@ -51,17 +87,40 @@ 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'}]) self.assertTrue(res['baz'], 'boo') + def test_replace_whole_document(self): + obj = {'foo': 'bar'} + res = jsonpatch.apply_patch(obj, [{'op': 'replace', 'path': '', 'value': {'baz': 'qux'}}]) + self.assertTrue(res['baz'], 'qux') + + def test_add_replace_whole_document(self): + obj = {'foo': 'bar'} + new_obj = {'baz': 'qux'} + res = jsonpatch.apply_patch(obj, [{'op': 'add', 'path': '', 'value': new_obj}]) + self.assertTrue(res, new_obj) + def test_replace_array_item(self): obj = {'foo': ['bar', 'qux', 'baz']} res = jsonpatch.apply_patch(obj, [{'op': 'replace', 'path': '/foo/1', 'value': 'boo'}]) self.assertEqual(res['foo'], ['bar', 'boo', 'baz']) + def test_move_object_keyerror(self): + obj = {'foo': {'bar': 'baz'}, + 'qux': {'corge': 'grault'}} + patch_obj = [ {'op': 'move', 'from': '/foo/non-existent', 'path': '/qux/thud'} ] + self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, obj, patch_obj) + def test_move_object_key(self): obj = {'foo': {'bar': 'baz', 'waldo': 'fred'}, 'qux': {'corge': 'grault'}} @@ -75,6 +134,18 @@ def test_move_array_item(self): res = jsonpatch.apply_patch(obj, [{'op': 'move', 'from': '/foo/1', 'path': '/foo/3'}]) self.assertEqual(res, {'foo': ['all', 'cows', 'eat', 'grass']}) + def test_move_array_item_into_other_item(self): + obj = [{"foo": []}, {"bar": []}] + patch = [{"op": "move", "from": "/0", "path": "/0/bar/0"}] + res = jsonpatch.apply_patch(obj, patch) + self.assertEqual(res, [{'bar': [{"foo": []}]}]) + + def test_copy_object_keyerror(self): + obj = {'foo': {'bar': 'baz'}, + 'qux': {'corge': 'grault'}} + patch_obj = [{'op': 'copy', 'from': '/foo/non-existent', 'path': '/qux/thud'}] + self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, obj, patch_obj) + def test_copy_object_key(self): obj = {'foo': {'bar': 'baz', 'waldo': 'fred'}, 'qux': {'corge': 'grault'}} @@ -106,6 +177,11 @@ def test_test_success(self): jsonpatch.apply_patch(obj, [{'op': 'test', 'path': '/baz', 'value': 'qux'}, {'op': 'test', 'path': '/foo/1', 'value': 2}]) + def test_test_whole_obj(self): + obj = {'baz': 1} + jsonpatch.apply_patch(obj, [{'op': 'test', 'path': '', 'value': obj}]) + + def test_test_error(self): obj = {'bar': 'qux'} self.assertRaises(jsonpatch.JsonPatchTestFailed, @@ -120,9 +196,17 @@ 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'} - jsonpatch.apply_patch(obj, [{'op': 'test', 'path': '/bar'}]) + self.assertRaises(jsonpatch.InvalidJsonPatch, + jsonpatch.apply_patch, + obj, [{'op': 'test', 'path': '/bar'}]) def test_test_noval_not_existing(self): @@ -153,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): @@ -180,7 +275,53 @@ def test_patch_hash_unequal(self): self.assertNotEqual(hash(patch1), hash(patch2)) + def test_patch_neq_other_objs(self): + p = [{'op': 'test', 'path': '/test'}] + patch = jsonpatch.JsonPatch(p) + # a patch will always compare not-equal to objects of other types + self.assertFalse(patch == p) + self.assertFalse(patch == None) + + # also a patch operation will always compare + # not-equal to objects of other types + op = jsonpatch.PatchOperation(p[0]) + self.assertFalse(op == p[0]) + self.assertFalse(op == None) + + def test_str(self): + patch_obj = [ { "op": "add", "path": "/child", "value": { "grandchild": { } } } ] + patch = jsonpatch.JsonPatch(patch_obj) + + self.assertEqual(json.dumps(patch_obj), str(patch)) + 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): @@ -242,51 +383,695 @@ def test_add_nested(self): } self.assertEqual(expected, res) + # 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)) + self.assertEqual(len(patch), 1) + self.assertEqual(patch[0]['op'], 'add') + 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) -modules = ['jsonpatch'] -coverage_modules = [] + 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 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)) - return suite + 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) -suite = get_suite() + 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) -for module in modules: - m = __import__(module, fromlist=[module]) - coverage_modules.append(m) - suite.addTest(doctest.DocTestSuite(m)) + 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) -runner = unittest.TextTestRunner(verbosity=1) + 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) -try: - import coverage -except ImportError: - coverage = None + 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]} + patch = list(jsonpatch.make_patch(src, dst)) + self.assertEqual(len(patch), 1) + self.assertEqual(patch[0]['op'], 'replace') + 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) -if coverage is not None: - coverage.erase() - coverage.start() + 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]} + patch = list(jsonpatch.make_patch(src, dst)) + self.assertEqual(len(patch), 1) + self.assertEqual(patch[0]['op'], 'move') + res = jsonpatch.apply_patch(src, patch) + self.assertEqual(res, dst) -result = runner.run(suite) + def test_use_move_instead_of_add_remove(self): + 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) -if not result.wasSuccessful(): - sys.exit(1) + 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) -if coverage is not None: - coverage.stop() - coverage.report(coverage_modules) - coverage.erase() + def test_minimal_patch(self): + """ Test whether a minimal patch is created, see #36 """ + src = [{"foo": 1, "bar": 2}] + dst = [{"foo": 2, "bar": 2}] -if coverage is None: - sys.stderr.write(""" -No coverage reporting done (Python module "coverage" is missing) -Please install the python-coverage package to get coverage reporting. -""") - sys.stderr.flush() + 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) + res = patch.apply(src) + self.assertEqual(res, dst) + + def test_fail_prone_list_2(self): + """ Test making and applying a patch of the root is a list """ + 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_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) + + +class InvalidInputTests(unittest.TestCase): + + def test_missing_op(self): + # an "op" member is required + src = {"foo": "bar"} + patch_obj = [ { "path": "/child", "value": { "grandchild": { } } } ] + self.assertRaises(jsonpatch.JsonPatchException, jsonpatch.apply_patch, src, patch_obj) + + + def test_invalid_op(self): + # "invalid" is not a valid operation + src = {"foo": "bar"} + patch_obj = [ { "op": "invalid", "path": "/child", "value": { "grandchild": { } } } ] + self.assertRaises(jsonpatch.JsonPatchException, jsonpatch.apply_patch, src, patch_obj) + + +class ConflictTests(unittest.TestCase): + + def test_remove_indexerror(self): + src = {"foo": [1, 2]} + patch_obj = [ { "op": "remove", "path": "/foo/10"} ] + self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) + + def test_remove_keyerror(self): + src = {"foo": [1, 2]} + patch_obj = [ { "op": "remove", "path": "/foo/b"} ] + self.assertRaises(jsonpointer.JsonPointerException, jsonpatch.apply_patch, src, patch_obj) + + def test_remove_keyerror_dict(self): + src = {'foo': {'bar': 'barz'}} + patch_obj = [ { "op": "remove", "path": "/foo/non-existent"} ] + self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) + + def test_insert_oob(self): + src = {"foo": [1, 2]} + patch_obj = [ { "op": "add", "path": "/foo/10", "value": 1} ] + self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) + + def test_move_into_child(self): + src = {"foo": {"bar": {"baz": 1}}} + patch_obj = [ { "op": "move", "from": "/foo", "path": "/foo/bar" } ] + self.assertRaises(jsonpatch.JsonPatchException, jsonpatch.apply_patch, src, patch_obj) + + def test_replace_oob(self): + src = {"foo": [1, 2]} + 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({}) + + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.MoveOperation({'from': '/source', 'path': '/target'}).apply({}) + + def test_test_operation_structure(self): + with self.assertRaises(jsonpatch.JsonPatchTestFailed): + jsonpatch.TestOperation({'path': '/target'}).apply({}) + + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.TestOperation({'path': '/target'}).apply({'target': 'value'}) + + def test_copy_operation_structure(self): + with self.assertRaises(jsonpatch.InvalidJsonPatch): + jsonpatch.CopyOperation({'path': '/target'}).apply({}) + + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.CopyOperation({'path': '/target', 'from': '/source'}).apply({}) + + with self.assertRaises(jsonpatch.JsonPatchConflict): + jsonpatch.CopyOperation({'path': '/target', 'from': '/source'}).apply({}) + + +class CustomJsonPointer(jsonpointer.JsonPointer): + pass + + +class PrefixJsonPointer(jsonpointer.JsonPointer): + def __init__(self, pointer): + super(PrefixJsonPointer, self).__init__('/foo/bar' + pointer) + + +class CustomJsonPointerTests(unittest.TestCase): + + def test_json_patch_from_string(self): + patch = '[{"op": "add", "path": "/baz", "value": "qux"}]' + res = jsonpatch.JsonPatch.from_string( + patch, pointer_cls=CustomJsonPointer, + ) + self.assertEqual(res.pointer_cls, CustomJsonPointer) + + def test_json_patch_from_object(self): + patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] + res = jsonpatch.JsonPatch( + patch, pointer_cls=CustomJsonPointer, + ) + self.assertEqual(res.pointer_cls, CustomJsonPointer) + + def test_json_patch_from_diff(self): + old = {'foo': 'bar'} + new = {'foo': 'baz'} + res = jsonpatch.JsonPatch.from_diff( + old, new, pointer_cls=CustomJsonPointer, + ) + self.assertEqual(res.pointer_cls, CustomJsonPointer) + + def test_apply_patch_from_string(self): + obj = {'foo': 'bar'} + patch = '[{"op": "add", "path": "/baz", "value": "qux"}]' + res = jsonpatch.apply_patch( + obj, patch, + pointer_cls=CustomJsonPointer, + ) + self.assertTrue(obj is not res) + self.assertTrue('baz' in res) + self.assertEqual(res['baz'], 'qux') + + def test_apply_patch_from_object(self): + obj = {'foo': 'bar'} + res = jsonpatch.apply_patch( + obj, [{'op': 'add', 'path': '/baz', 'value': 'qux'}], + pointer_cls=CustomJsonPointer, + ) + self.assertTrue(obj is not res) + + def test_make_patch(self): + src = {'foo': 'bar', 'boo': 'qux'} + dst = {'baz': 'qux', 'foo': 'boo'} + patch = jsonpatch.make_patch( + src, dst, pointer_cls=CustomJsonPointer, + ) + res = patch.apply(src) + self.assertTrue(src is not res) + self.assertEqual(patch.pointer_cls, CustomJsonPointer) + self.assertTrue(patch._ops) + for op in patch._ops: + self.assertIsInstance(op.pointer, CustomJsonPointer) + self.assertEqual(op.pointer_cls, CustomJsonPointer) + + def test_operations(self): + operations =[ + ( + jsonpatch.AddOperation, { + 'op': 'add', 'path': '/foo', 'value': [1, 2, 3] + } + ), + ( + jsonpatch.MoveOperation, { + 'op': 'move', 'path': '/baz', 'from': '/foo' + }, + ), + ( + jsonpatch.RemoveOperation, { + 'op': 'remove', 'path': '/baz/1' + }, + ), + ( + jsonpatch.TestOperation, { + 'op': 'test', 'path': '/baz', 'value': [1, 3] + }, + ), + ( + jsonpatch.ReplaceOperation, { + 'op': 'replace', 'path': '/baz/0', 'value': 42 + }, + ), + ( + jsonpatch.RemoveOperation, { + 'op': 'remove', 'path': '/baz/1' + }, + ) + ] + for cls, patch in operations: + operation = cls(patch, pointer_cls=CustomJsonPointer) + self.assertEqual(operation.pointer_cls, CustomJsonPointer) + self.assertIsInstance(operation.pointer, CustomJsonPointer) + + def test_operations_from_patch(self): + patch = jsonpatch.JsonPatch([ + {'op': 'add', 'path': '/foo', 'value': [1, 2, 3]}, + {'op': 'move', 'path': '/baz', 'from': '/foo'}, + {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]}, + {'op': 'remove', 'path': '/baz/1'}, + {'op': 'test', 'path': '/baz', 'value': [1, 3]}, + {'op': 'replace', 'path': '/baz/0', 'value': 42}, + {'op': 'remove', 'path': '/baz/1'}, + ], pointer_cls=CustomJsonPointer) + self.assertEqual(patch.apply({}), {'baz': [42]}) + self.assertEqual(patch.pointer_cls, CustomJsonPointer) + self.assertTrue(patch._ops) + for op in patch._ops: + self.assertIsInstance(op.pointer, CustomJsonPointer) + self.assertEqual(op.pointer_cls, CustomJsonPointer) + + def test_json_patch_with_prefix_pointer(self): + res = jsonpatch.apply_patch( + {'foo': {'bar': {}}}, [{'op': 'add', 'path': '/baz', 'value': 'qux'}], + pointer_cls=PrefixJsonPointer, + ) + self.assertEqual(res, {'foo': {'bar': {'baz': 'qux'}}}) + + +class CustomOperationTests(unittest.TestCase): + + def test_custom_operation(self): + + class IdentityOperation(jsonpatch.PatchOperation): + def apply(self, obj): + return obj + + class JsonPatch(jsonpatch.JsonPatch): + operations = MappingProxyType( + dict( + identity=IdentityOperation, + **jsonpatch.JsonPatch.operations + ) + ) + + patch = JsonPatch([{'op': 'identity', 'path': '/'}]) + self.assertIn('identity', patch.operations) + res = patch.apply({}) + self.assertEqual(res, {}) + + +if __name__ == '__main__': + modules = ['jsonpatch'] + + + 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)