pax_global_header00006660000000000000000000000064131205252220014504gustar00rootroot0000000000000052 comment=1fc5e2022ff2c5796bd28af56646b135ede4ee71 python-json-patch-1.16/000077500000000000000000000000001312052522200150205ustar00rootroot00000000000000python-json-patch-1.16/.coveragerc000066400000000000000000000006101312052522200171360ustar00rootroot00000000000000# .coveragerc to control coverage.py [run] branch = True [report] # 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 python-json-patch-1.16/.gitignore000066400000000000000000000000621312052522200170060ustar00rootroot00000000000000*.pyc build .coverage dist *.egg-info/ doc/_build python-json-patch-1.16/.travis.yml000066400000000000000000000006251312052522200171340ustar00rootroot00000000000000language: python python: - "2.6" - "2.7" - "3.2" - "3.3" - "3.4" - "3.5" - "3.6" - "pypy" - "pypy3" install: - travis_retry pip install -r requirements.txt - if [ "$TRAVIS_PYTHON_VERSION" == "3.2" ]; then travis_retry pip install 'coverage<4'; fi - travis_retry pip install coveralls script: - coverage run --source=jsonpatch tests.py after_script: - coveralls sudo: false python-json-patch-1.16/AUTHORS000066400000000000000000000002141312052522200160650ustar00rootroot00000000000000Stefan Kögl Alexander Shorin Byron Ruth William Kral python-json-patch-1.16/COPYING000066400000000000000000000026051312052522200160560ustar00rootroot00000000000000Copyright (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. python-json-patch-1.16/MANIFEST.in000066400000000000000000000001611312052522200165540ustar00rootroot00000000000000include requirements.txt include COPYING include README.md include tests.py include ext_tests.py include AUTHORS python-json-patch-1.16/README.md000066400000000000000000000022761312052522200163060ustar00rootroot00000000000000python-json-patch [![Build Status](https://secure.travis-ci.org/stefankoegl/python-json-patch.png?branch=master)](https://travis-ci.org/stefankoegl/python-json-patch) [![Coverage Status](https://coveralls.io/repos/stefankoegl/python-json-patch/badge.png?branch=master)](https://coveralls.io/r/stefankoegl/python-json-patch?branch=master) ![Downloads](https://pypip.in/d/jsonpatch/badge.png) ![Version](https://pypip.in/v/jsonpatch/badge.png) ================= Applying JSON Patches in Python ------------------------------- Library to apply JSON Patches according to [RFC 6902](http://tools.ietf.org/html/rfc6902) See Sourcecode 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 ./ext_tests.py ../json-patch-tests/tests.json python-json-patch-1.16/bin/000077500000000000000000000000001312052522200155705ustar00rootroot00000000000000python-json-patch-1.16/bin/jsondiff000077500000000000000000000017751312052522200173320ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import os.path 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('-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)) sys.exit(1) if __name__ == "__main__": main() python-json-patch-1.16/bin/jsonpatch000077500000000000000000000071201312052522200175070ustar00rootroot00000000000000#!/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__) 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) 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() python-json-patch-1.16/doc/000077500000000000000000000000001312052522200155655ustar00rootroot00000000000000python-json-patch-1.16/doc/Makefile000066400000000000000000000127501312052522200172320ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-json-patch.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-json-patch.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/python-json-patch" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-json-patch" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." python-json-patch-1.16/doc/_static/000077500000000000000000000000001312052522200172135ustar00rootroot00000000000000python-json-patch-1.16/doc/_static/.empty000066400000000000000000000000001312052522200203400ustar00rootroot00000000000000python-json-patch-1.16/doc/commandline.rst000066400000000000000000000043141312052522200206070ustar00rootroot00000000000000Commandline 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] [-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 -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 -v, --version show program's version number and exit 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 [] python-json-patch-1.16/doc/conf.py000066400000000000000000000173471312052522200171000ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # python-json-patch documentation build configuration file, created by # sphinx-quickstart on Sat Apr 13 23:07:23 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.join(os.path.abspath('.'), '..')) import jsonpatch # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-json-patch' copyright = jsonpatch.__author__ # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = jsonpatch.__version__ # The full version, including alpha/beta/rc tags. release = jsonpatch.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-json-patchdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'python-json-patch.tex', u'python-json-patch Documentation', u'Stefan Kögl', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'python-json-patch', u'python-json-patch Documentation', [u'Stefan Kögl'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'python-json-patch', u'python-json-patch Documentation', u'Stefan Kögl', 'python-json-patch', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' python-json-patch-1.16/doc/index.rst000066400000000000000000000012321312052522200174240ustar00rootroot00000000000000.. python-json-patch documentation master file, created by sphinx-quickstart on Sat Apr 13 23:07:23 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. 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. **Contents** .. toctree:: :maxdepth: 2 tutorial mod-jsonpatch commandline RFC 6902 Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-json-patch-1.16/doc/mod-jsonpatch.rst000066400000000000000000000001551312052522200210660ustar00rootroot00000000000000.. mod-jsonpatch: The ``jsonpatch`` module ======================== .. automodule:: jsonpatch :members: python-json-patch-1.16/doc/tutorial.rst000066400000000000000000000035631312052522200201710ustar00rootroot00000000000000Tutorial ======== Please refer to `RFC 6902 `_ for the exact patch syntax. Creating a Patch ---------------- Patches can be created in two ways. One way is to explicitly create a ``JsonPatch`` object from a list of operations. For convenience, the method ``JsonPatch.from_string()`` accepts a string, parses it and constructs the patch object from it. .. code-block:: python >>> import jsonpatch >>> patch = jsonpatch.JsonPatch([ {'op': 'add', 'path': '/foo', 'value': 'bar'}, {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]}, {'op': 'remove', 'path': '/baz/1'}, {'op': 'test', 'path': '/baz', 'value': [1, 3]}, {'op': 'replace', 'path': '/baz/0', 'value': 42}, {'op': 'remove', 'path': '/baz/1'}, ]) # or equivalently >>> patch = jsonpatch.JsonPatch.from_string('[{"op": "add", ....}]') Another way is to *diff* two objects. .. code-block:: python >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = jsonpatch.JsonPatch.from_diff(src, dst) # or equivalently >>> patch = jsonpatch.make_patch(src, dst) Applying a Patch ---------------- A patch is always applied to an object. .. code-block:: python >>> doc = {} >>> result = patch.apply(doc) {'foo': 'bar', 'baz': [42]} The ``apply`` method returns a new object as a result. If ``in_place=True`` the object is modified in place. If a patch is only used once, it is not necessary to create a patch object explicitly. .. code-block:: python >>> obj = {'foo': 'bar'} # from a patch string >>> patch = '[{"op": "add", "path": "/baz", "value": "qux"}]' >>> res = jsonpatch.apply_patch(obj, patch) # or from a list >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] >>> res = jsonpatch.apply_patch(obj, patch) python-json-patch-1.16/ext_tests.py000077500000000000000000000102521312052522200174170ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # python-json-patch - An implementation of the JSON Patch format # https://github.com/stefankoegl/python-json-patch # # 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. # """ Script to run external tests, eg from https://github.com/json-patch/json-patch-tests """ from functools import partial import doctest import unittest import jsonpatch import sys class TestCaseTemplate(unittest.TestCase): """ A generic test case for running external tests """ def _test(self, test): if not 'doc' in test or not 'patch' in test: # incomplete return if test.get('disabled', False): # test is disabled return if 'error' in test: self.assertRaises( (jsonpatch.JsonPatchException, jsonpatch.JsonPointerException), jsonpatch.apply_patch, test['doc'], test['patch'] ) else: 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 if 'expected' in test: self.assertEquals(res, test['expected'], test.get('comment', '')) def make_test_case(tests): class MyTestCase(TestCaseTemplate): pass for n, test in enumerate(tests): add_test_method(MyTestCase, 'test_%d' % n, test) return MyTestCase def add_test_method(cls, name, test): setattr(cls, name, lambda self: self._test(test)) modules = ['jsonpatch'] coverage_modules = [] def get_suite(filenames): suite = unittest.TestSuite() for testfile in filenames: with open(testfile) as 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)) return suite suite = get_suite(sys.argv[1:]) for module in modules: m = __import__(module, fromlist=[module]) coverage_modules.append(m) suite.addTest(doctest.DocTestSuite(m)) runner = unittest.TextTestRunner(verbosity=1) try: import coverage except ImportError: coverage = None if coverage is not None: coverage.erase() coverage.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 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() python-json-patch-1.16/jsonpatch.py000066400000000000000000000643071312052522200173750ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # python-json-patch - An implementation of the JSON Patch format # https://github.com/stefankoegl/python-json-patch # # 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. # """ Apply JSON-Patches (RFC 6902) """ from __future__ import unicode_literals import collections import copy import functools import inspect import itertools import json import sys try: from collections.abc import MutableMapping, MutableSequence except ImportError: from collections import MutableMapping, MutableSequence from jsonpointer import JsonPointer, JsonPointerException # Will be parsed by setup.py to determine package metadata __author__ = 'Stefan Kögl ' __version__ = '1.16' __website__ = 'https://github.com/stefankoegl/python-json-patch' __license__ = 'Modified BSD License' # pylint: disable=E0611,W0404 if sys.version_info >= (3, 0): basestring = (bytes, str) # pylint: disable=C0103,W0622 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 operate with nonexistence object key; - attempt to insert value to array at position beyond of it size; - etc. """ class JsonPatchTestFailed(JsonPatchException, AssertionError): """ A Test operation failed """ 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() ) def get_loadjson(): """ adds the object_pairs_hook parameter to json.load when possible The "object_pairs_hook" parameter is used to handle duplicate keys when loading a JSON object. This parameter does not exist in Python 2.6. This methods returns an unmodified json.load for Python 2.6 and a partial function with object_pairs_hook set to multidict for Python versions that support the parameter. """ if sys.version_info >= (3, 3): args = inspect.signature(json.load).parameters else: args = inspect.getargspec(json.load).args if 'object_pairs_hook' not in args: return json.load return functools.partial(json.load, object_pairs_hook=multidict) json.load = get_loadjson() def apply_patch(doc, patch, in_place=False): """Apply list of patches to specified json document. :param doc: Document object. :type doc: dict :param patch: JSON patch as list of dicts or raw JSON-encoded string. :type patch: list or str :param in_place: While :const:`True` patch will modify target document. By default patch will be applied to document copy. :type in_place: bool :return: Patched document object. :rtype: dict >>> doc = {'foo': 'bar'} >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] >>> other = apply_patch(doc, patch) >>> doc is not other True >>> other == {'foo': 'bar', 'baz': 'qux'} True >>> 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) else: patch = JsonPatch(patch) return patch.apply(doc, in_place) def make_patch(src, dst): """Generates patch by comparing of two document objects. Actually is a proxy to :meth:`JsonPatch.from_diff` method. :param src: Data source document object. :type src: dict :param dst: Data source document object. :type dst: dict >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = make_patch(src, dst) >>> new = patch.apply(src) >>> new == dst True """ # TODO: fix patch optimiztion and remove the following check # fix when patch with optimization is incorrect patch = JsonPatch.from_diff(src, dst) new = patch.apply(src) if new != dst: return JsonPatch.from_diff(src, dst, False) return JsonPatch.from_diff(src, dst) class JsonPatch(object): """A JSON Patch is a list of Patch Operations. >>> patch = JsonPatch([ ... {'op': 'add', 'path': '/foo', 'value': 'bar'}, ... {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]}, ... {'op': 'remove', 'path': '/baz/1'}, ... {'op': 'test', 'path': '/baz', 'value': [1, 3]}, ... {'op': 'replace', 'path': '/baz/0', 'value': 42}, ... {'op': 'remove', 'path': '/baz/1'}, ... ]) >>> doc = {} >>> result = patch.apply(doc) >>> expected = {'foo': 'bar', 'baz': [42]} >>> result == expected True JsonPatch object is iterable, so you could easily access to each patch statement in loop: >>> lpatch = list(patch) >>> expected = {'op': 'add', 'path': '/foo', 'value': 'bar'} >>> lpatch[0] == expected True >>> lpatch == patch.patch True Also JsonPatch could be converted directly to :class:`bool` if it contains any operation statements: >>> bool(patch) True >>> bool(JsonPatch([])) False This behavior is very handy with :func:`make_patch` to write more readable code: >>> old = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> new = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = make_patch(old, new) >>> if patch: ... # document have changed, do something useful ... patch.apply(old) #doctest: +ELLIPSIS {...} """ def __init__(self, patch): self.patch = patch self.operations = { 'remove': RemoveOperation, 'add': AddOperation, 'replace': ReplaceOperation, 'move': MoveOperation, 'test': TestOperation, 'copy': CopyOperation, } def __str__(self): """str(self) -> self.to_string()""" return self.to_string() def __bool__(self): return bool(self.patch) __nonzero__ = __bool__ def __iter__(self): return iter(self.patch) def __hash__(self): return hash(tuple(self._ops)) def __eq__(self, other): if not isinstance(other, JsonPatch): return False return self._ops == other._ops def __ne__(self, other): return not(self == other) @classmethod def from_string(cls, patch_str): """Creates JsonPatch instance from string source. :param patch_str: JSON patch as raw string. :type patch_str: str :return: :class:`JsonPatch` instance. """ patch = json.loads(patch_str) return cls(patch) @classmethod def from_diff(cls, src, dst, optimization=True): """Creates JsonPatch instance based on comparing of two document objects. Json patch would be created for `src` argument against `dst` one. :param src: Data source document object. :type src: dict :param dst: Data source document object. :type dst: dict :return: :class:`JsonPatch` instance. >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = JsonPatch.from_diff(src, dst) >>> new = patch.apply(src) >>> new == dst True """ def compare_values(path, value, other): if value == other: return if isinstance(value, MutableMapping) and \ isinstance(other, MutableMapping): for operation in compare_dicts(path, value, other): yield operation elif isinstance(value, MutableSequence) and \ isinstance(other, MutableSequence): for operation in compare_lists(path, value, other): yield operation else: ptr = JsonPointer.from_parts(path) yield {'op': 'replace', 'path': ptr.path, 'value': other} def compare_dicts(path, src, dst): for key in src: if key not in dst: ptr = JsonPointer.from_parts(path + [key]) yield {'op': 'remove', 'path': ptr.path} continue current = path + [key] for operation in compare_values(current, src[key], dst[key]): yield operation for key in dst: if key not in src: ptr = JsonPointer.from_parts(path + [key]) yield {'op': 'add', 'path': ptr.path, 'value': dst[key]} def compare_lists(path, src, dst): return _compare_lists(path, src, dst, optimization=optimization) return cls(list(compare_values([], src, dst))) def to_string(self): """Returns patch set as JSON string.""" return json.dumps(self.patch) @property def _ops(self): return tuple(map(self._get_operation, self.patch)) def apply(self, obj, in_place=False): """Applies the patch to given object. :param obj: Document object. :type obj: dict :param in_place: Tweaks way how patch would be applied - directly to specified `obj` or to his copy. :type in_place: bool :return: Modified `obj`. """ if not in_place: obj = copy.deepcopy(obj) for operation in self._ops: obj = operation.apply(obj) return obj def _get_operation(self, operation): if 'op' not in operation: raise InvalidJsonPatch("Operation does not contain 'op' member") op = operation['op'] if not isinstance(op, basestring): raise InvalidJsonPatch("Operation must be a string") if op not in self.operations: raise InvalidJsonPatch("Unknown operation {0!r}".format(op)) cls = self.operations[op] return cls(operation) class PatchOperation(object): """A single operation inside a JSON Patch.""" def __init__(self, operation): self.location = operation['path'] self.pointer = JsonPointer(self.location) self.operation = operation def apply(self, obj): """Abstract method that applies patch operation to specified object.""" raise NotImplementedError('should implement patch operation.') 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) class RemoveOperation(PatchOperation): """Removes an object property or an array element.""" def apply(self, obj): subobj, part = self.pointer.to_last(obj) try: del subobj[part] except (KeyError, IndexError) as ex: msg = "can't remove non-existent object '{0}'".format(part) raise JsonPatchConflict(msg) return obj 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: raise TypeError("invalid document type {0}".format(type(subobj))) return obj class ReplaceOperation(PatchOperation): """Replaces an object property or an array element by 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 isinstance(subobj, MutableSequence): if part > len(subobj) or part < 0: raise JsonPatchConflict("can't replace outside of list") elif isinstance(subobj, MutableMapping): if not part in subobj: msg = "can't replace non-existent object '{0}'".format(part) raise JsonPatchConflict(msg) else: raise TypeError("invalid document type {0}".format(type(subobj))) subobj[part] = value return obj class MoveOperation(PatchOperation): """Moves an object property or an array element to new location.""" def apply(self, obj): try: from_ptr = JsonPointer(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 its own children') obj = RemoveOperation({ 'op': 'remove', 'path': self.operation['from'] }).apply(obj) obj = AddOperation({ 'op': 'add', 'path': self.location, 'value': value }).apply(obj) return obj 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 = JsonPointer(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 }).apply(obj) return obj def _compare_lists(path, src, dst, optimization=True): """Compares two lists objects and return JSON patch about.""" patch = list(_compare(path, src, dst, *_split_by_common_seq(src, dst))) if optimization: return list(_optimize(patch)) return patch def _longest_common_subseq(src, dst): """Returns pair of ranges of longest common subsequence for the `src` and `dst` lists. >>> src = [1, 2, 3, 4] >>> dst = [0, 1, 2, 3, 5] >>> # The longest common subsequence for these lists is [1, 2, 3] ... # which is located at (0, 3) index range for src list and (1, 4) for ... # dst one. Tuple of these ranges we should get back. ... assert ((0, 3), (1, 4)) == _longest_common_subseq(src, dst) """ lsrc, ldst = len(src), len(dst) drange = list(range(ldst)) matrix = [[0] * ldst for _ in range(lsrc)] z = 0 # length of the longest subsequence range_src, range_dst = None, None for i, j in itertools.product(range(lsrc), drange): if src[i] == dst[j]: if i == 0 or j == 0: matrix[i][j] = 1 else: matrix[i][j] = matrix[i-1][j-1] + 1 if matrix[i][j] > z: z = matrix[i][j] if matrix[i][j] == z: range_src = (i-z+1, i+1) range_dst = (j-z+1, j+1) else: matrix[i][j] = 0 return range_src, range_dst def _split_by_common_seq(src, dst, bx=(0, -1), by=(0, -1)): """Recursively splits the `dst` list onto two parts: left and right. The left part contains differences on left from common subsequence, same as the right part by for other side. To easily understand the process let's take two lists: [0, 1, 2, 3] as `src` and [1, 2, 4, 5] for `dst`. If we've tried to generate the binary tree where nodes are common subsequence for both lists, leaves on the left side are subsequence for `src` list and leaves on the right one for `dst`, our tree would looks like:: [1, 2] / \ [0] [] / \ [3] [4, 5] This function generate the similar structure as flat tree, but without nodes with common subsequences - since we're don't need them - only with left and right leaves:: [] / \ [0] [] / \ [3] [4, 5] The `bx` is the absolute range for currently processed subsequence of `src` list. The `by` means the same, but for the `dst` list. """ # Prevent useless comparisons in future bx = bx if bx[0] != bx[1] else None by = by if by[0] != by[1] else None if not src: return [None, by] elif not dst: return [bx, None] # note that these ranges are relative for processed sublists x, y = _longest_common_subseq(src, dst) if x is None or y is None: # no more any common subsequence return [bx, by] return [_split_by_common_seq(src[:x[0]], dst[:y[0]], (bx[0], bx[0] + x[0]), (by[0], by[0] + y[0])), _split_by_common_seq(src[x[1]:], dst[y[1]:], (bx[0] + x[1], bx[0] + len(src)), (by[0] + y[1], by[0] + len(dst)))] def _compare(path, src, dst, left, right): """Same as :func:`_compare_with_shift` but strips emitted `shift` value.""" for op, _ in _compare_with_shift(path, src, dst, left, right, 0): yield op def _compare_with_shift(path, src, dst, left, right, shift): """Recursively compares differences from `left` and `right` sides from common subsequences. The `shift` parameter is used to store index shift which caused by ``add`` and ``remove`` operations. Yields JSON patch operations and list index shift. """ if isinstance(left, MutableSequence): for item, shift in _compare_with_shift(path, src, dst, *left, shift=shift): yield item, shift elif left is not None: for item, shift in _compare_left(path, src, left, shift): yield item, shift if isinstance(right, MutableSequence): for item, shift in _compare_with_shift(path, src, dst, *right, shift=shift): yield item, shift elif right is not None: for item, shift in _compare_right(path, dst, right, shift): yield item, shift def _compare_left(path, src, left, shift): """Yields JSON patch ``remove`` operations for elements that are only exists in the `src` list.""" start, end = left if end == -1: end = len(src) # we need to `remove` elements from list tail to not deal with index shift for idx in reversed(range(start + shift, end + shift)): ptr = JsonPointer.from_parts(path + [str(idx)]) yield ( {'op': 'remove', # yes, there should be any value field, but we'll use it # to apply `move` optimization a bit later and will remove # it in _optimize function. 'value': src[idx - shift], 'path': ptr.path, }, shift - 1 ) shift -= 1 def _compare_right(path, dst, right, shift): """Yields JSON patch ``add`` operations for elements that are only exists in the `dst` list""" start, end = right if end == -1: end = len(dst) for idx in range(start, end): ptr = JsonPointer.from_parts(path + [str(idx)]) yield ( {'op': 'add', 'path': ptr.path, 'value': dst[idx]}, shift + 1 ) shift += 1 def _optimize(operations): """Optimizes operations which was produced by lists comparison. Actually it does two kinds of optimizations: 1. Seeks pair of ``remove`` and ``add`` operations against the same path and replaces them with ``replace`` operation. 2. Seeks pair of ``remove`` and ``add`` operations for the same value and replaces them with ``move`` operation. """ result = [] ops_by_path = {} ops_by_value = {} add_remove = set(['add', 'remove']) for item in operations: # could we apply "move" optimization for dict values? hashable_value = not isinstance(item['value'], (MutableMapping, MutableSequence)) if item['path'] in ops_by_path: _optimize_using_replace(ops_by_path[item['path']], item) continue if hashable_value and item['value'] in ops_by_value: prev_item = ops_by_value[item['value']] # ensure that we processing pair of add-remove ops if set([item['op'], prev_item['op']]) == add_remove: _optimize_using_move(prev_item, item) ops_by_value.pop(item['value']) continue result.append(item) ops_by_path[item['path']] = item if hashable_value: ops_by_value[item['value']] = item # cleanup ops_by_path.clear() ops_by_value.clear() for item in result: if item['op'] == 'remove': item.pop('value') # strip our hack yield item def _optimize_using_replace(prev, cur): """Optimises by replacing ``add``/``remove`` with ``replace`` on same path For nested strucures, tries to recurse replacement, see #36 """ prev['op'] = 'replace' if cur['op'] == 'add': # make recursive patch patch = make_patch(prev['value'], cur['value']) # check case when dict "remove" is less than "add" and has a same key if isinstance(prev['value'], dict) and isinstance(cur['value'], dict) and len(prev['value'].keys()) == 1: prev_set = set(prev['value'].keys()) cur_set = set(cur['value'].keys()) if prev_set & cur_set == prev_set: patch = make_patch(cur['value'], prev['value']) if len(patch.patch) == 1 and \ patch.patch[0]['op'] != 'remove' and \ patch.patch[0]['path'] and patch.patch[0]['path'].split('/')[1] in prev['value']: prev['path'] = prev['path'] + patch.patch[0]['path'] prev['value'] = patch.patch[0]['value'] else: prev['value'] = cur['value'] def _optimize_using_move(prev_item, item): """Optimises JSON patch by using ``move`` operation instead of ``remove` and ``add`` against the different paths but for the same value.""" prev_item['op'] = 'move' move_from, move_to = [ (item['path'], prev_item['path']), (prev_item['path'], item['path']), ][item['op'] == 'add'] if item['op'] == 'add': # first was remove then add prev_item['from'] = move_from prev_item['path'] = move_to else: # first was add then remove head, move_from = move_from.rsplit('/', 1) # since add operation was first it incremented # overall index shift value. we have to fix this move_from = int(move_from) - 1 prev_item['from'] = head + '/%d' % move_from prev_item['path'] = move_to python-json-patch-1.16/makefile000066400000000000000000000004641312052522200165240ustar00rootroot00000000000000 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 tests.py coverage: coverage run --source=jsonpatch tests.py coverage report -m python-json-patch-1.16/requirements-dev.txt000066400000000000000000000000171312052522200210560ustar00rootroot00000000000000wheel pypandoc python-json-patch-1.16/requirements.txt000066400000000000000000000000211312052522200202750ustar00rootroot00000000000000jsonpointer>=1.9 python-json-patch-1.16/setup.cfg000066400000000000000000000000341312052522200166360ustar00rootroot00000000000000[bdist_wheel] universal = 1 python-json-patch-1.16/setup.py000066400000000000000000000051411312052522200165330ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import io import re import warnings try: from setuptools import setup has_setuptools = True except ImportError: from distutils.core import setup has_setuptools = False src = io.open('jsonpatch.py', encoding='utf-8').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", src)) docstrings = re.findall('"""([^"]*)"""', src, re.MULTILINE | re.DOTALL) PACKAGE = 'jsonpatch' MODULES = ( 'jsonpatch', ) 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'] VERSION = metadata['version'] WEBSITE = metadata['website'] LICENSE = metadata['license'] DESCRIPTION = docstrings[0] # 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.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', '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, **OPTIONS ) python-json-patch-1.16/tests.js000066400000000000000000000352041312052522200165240ustar00rootroot00000000000000[ { "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" } ] python-json-patch-1.16/tests.py000077500000000000000000000507121312052522200165440ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import json import doctest import unittest import jsonpatch import jsonpointer import sys 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"}]' res = jsonpatch.apply_patch(obj, patch) self.assertTrue(obj is not res) self.assertTrue('baz' in res) self.assertEqual(res['baz'], 'qux') def test_apply_patch_to_copy(self): obj = {'foo': 'bar'} res = jsonpatch.apply_patch(obj, [{'op': 'add', 'path': '/baz', 'value': 'qux'}]) self.assertTrue(obj is not res) def test_apply_patch_to_same_instance(self): obj = {'foo': 'bar'} res = jsonpatch.apply_patch(obj, [{'op': 'add', 'path': '/baz', 'value': 'qux'}], in_place=True) self.assertTrue(obj is res) def test_add_object_key(self): obj = {'foo': 'bar'} res = jsonpatch.apply_patch(obj, [{'op': 'add', 'path': '/baz', 'value': 'qux'}]) self.assertTrue('baz' in res) self.assertEqual(res['baz'], 'qux') def test_add_array_item(self): obj = {'foo': ['bar', 'baz']} res = jsonpatch.apply_patch(obj, [{'op': 'add', 'path': '/foo/1', 'value': 'qux'}]) self.assertEqual(res['foo'], ['bar', 'qux', 'baz']) def test_remove_object_key(self): obj = {'foo': 'bar', 'baz': 'qux'} res = jsonpatch.apply_patch(obj, [{'op': 'remove', 'path': '/baz'}]) self.assertTrue('baz' not in res) def test_remove_array_item(self): obj = {'foo': ['bar', 'qux', 'baz']} res = jsonpatch.apply_patch(obj, [{'op': 'remove', 'path': '/foo/1'}]) self.assertEqual(res['foo'], ['bar', 'baz']) 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'}} res = jsonpatch.apply_patch(obj, [{'op': 'move', 'from': '/foo/waldo', 'path': '/qux/thud'}]) self.assertEqual(res, {'qux': {'thud': 'fred', 'corge': 'grault'}, 'foo': {'bar': 'baz'}}) def test_move_array_item(self): obj = {'foo': ['all', 'grass', 'cows', 'eat']} 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'}} res = jsonpatch.apply_patch(obj, [{'op': 'copy', 'from': '/foo/waldo', 'path': '/qux/thud'}]) self.assertEqual(res, {'qux': {'thud': 'fred', 'corge': 'grault'}, 'foo': {'bar': 'baz', 'waldo': 'fred'}}) def test_copy_array_item(self): obj = {'foo': ['all', 'grass', 'cows', 'eat']} res = jsonpatch.apply_patch(obj, [{'op': 'copy', 'from': '/foo/1', 'path': '/foo/3'}]) self.assertEqual(res, {'foo': ['all', 'grass', 'cows', 'grass', 'eat']}) def test_copy_mutable(self): """ test if mutable objects (dicts and lists) are copied by value """ obj = {'foo': [{'bar': 42}, {'baz': 3.14}], 'boo': []} # copy object somewhere res = jsonpatch.apply_patch(obj, [{'op': 'copy', 'from': '/foo/0', 'path': '/boo/0' }]) self.assertEqual(res, {'foo': [{'bar': 42}, {'baz': 3.14}], 'boo': [{'bar': 42}]}) # modify original object res = jsonpatch.apply_patch(res, [{'op': 'add', 'path': '/foo/0/zoo', 'value': 255}]) # check if that didn't modify the copied object self.assertEqual(res['boo'], [{'bar': 42}]) def test_test_success(self): obj = {'baz': 'qux', 'foo': ['a', 2, 'c']} 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, jsonpatch.apply_patch, obj, [{'op': 'test', 'path': '/bar', 'value': 'bar'}]) def test_test_not_existing(self): obj = {'bar': 'qux'} self.assertRaises(jsonpatch.JsonPatchTestFailed, jsonpatch.apply_patch, obj, [{'op': 'test', 'path': '/baz', 'value': 'bar'}]) def test_test_noval_existing(self): obj = {'bar': 'qux'} self.assertRaises(jsonpatch.InvalidJsonPatch, jsonpatch.apply_patch, obj, [{'op': 'test', 'path': '/bar'}]) def test_test_noval_not_existing(self): obj = {'bar': 'qux'} self.assertRaises(jsonpatch.JsonPatchTestFailed, jsonpatch.apply_patch, obj, [{'op': 'test', 'path': '/baz'}]) def test_test_noval_not_existing_nested(self): obj = {'bar': {'qux': 2}} self.assertRaises(jsonpatch.JsonPatchTestFailed, jsonpatch.apply_patch, obj, [{'op': 'test', 'path': '/baz/qx'}]) def test_unrecognized_element(self): obj = {'foo': 'bar', 'baz': 'qux'} res = jsonpatch.apply_patch(obj, [{'op': 'replace', 'path': '/baz', 'value': 'boo', 'foo': 'ignore'}]) self.assertTrue(res['baz'], 'boo') def test_append(self): obj = {'foo': [1, 2]} res = jsonpatch.apply_patch(obj, [ {'op': 'add', 'path': '/foo/-', 'value': 3}, {'op': 'add', 'path': '/foo/-', 'value': 4}, ]) self.assertEqual(res['foo'], [1, 2, 3, 4]) class EqualityTestCase(unittest.TestCase): def test_patch_equality(self): patch1 = jsonpatch.JsonPatch([{ "op": "add", "path": "/a/b/c", "value": "foo" }]) patch2 = jsonpatch.JsonPatch([{ "path": "/a/b/c", "op": "add", "value": "foo" }]) self.assertEqual(patch1, patch2) def test_patch_unequal(self): patch1 = jsonpatch.JsonPatch([{'op': 'test', 'path': '/test'}]) patch2 = jsonpatch.JsonPatch([{'op': 'test', 'path': '/test1'}]) self.assertNotEqual(patch1, patch2) def test_patch_hash_equality(self): patch1 = jsonpatch.JsonPatch([{ "op": "add", "path": "/a/b/c", "value": "foo" }]) patch2 = jsonpatch.JsonPatch([{ "path": "/a/b/c", "op": "add", "value": "foo" }]) self.assertEqual(hash(patch1), hash(patch2)) def test_patch_hash_unequal(self): patch1 = jsonpatch.JsonPatch([{'op': 'test', 'path': '/test'}]) patch2 = jsonpatch.JsonPatch([{'op': 'test', 'path': '/test1'}]) 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()) class MakePatchTestCase(unittest.TestCase): def test_apply_patch_to_copy(self): src = {'foo': 'bar', 'boo': 'qux'} dst = {'baz': 'qux', 'foo': 'boo'} patch = jsonpatch.make_patch(src, dst) res = patch.apply(src) self.assertTrue(src is not res) def test_apply_patch_to_same_instance(self): src = {'foo': 'bar', 'boo': 'qux'} dst = {'baz': 'qux', 'foo': 'boo'} patch = jsonpatch.make_patch(src, dst) res = patch.apply(src, in_place=True) self.assertTrue(src is res) def test_objects(self): src = {'foo': 'bar', 'boo': 'qux'} dst = {'baz': 'qux', 'foo': 'boo'} patch = jsonpatch.make_patch(src, dst) res = patch.apply(src) self.assertEqual(res, dst) def test_arrays(self): src = {'numbers': [1, 2, 3], 'other': [1, 3, 4, 5]} dst = {'numbers': [1, 3, 4, 5], 'other': [1, 3, 4]} patch = jsonpatch.make_patch(src, dst) res = patch.apply(src) self.assertEqual(res, dst) def test_complex_object(self): src = {'data': [ {'foo': 1}, {'bar': [1, 2, 3]}, {'baz': {'1': 1, '2': 2}} ]} dst = {'data': [ {'foo': [42]}, {'bar': []}, {'baz': {'boo': 'oom!'}} ]} patch = jsonpatch.make_patch(src, dst) res = patch.apply(src) self.assertEqual(res, dst) def test_array_add_remove(self): # see https://github.com/stefankoegl/python-json-patch/issues/4 src = {'numbers': [], 'other': [1, 5, 3, 4]} dst = {'numbers': [1, 3, 4, 5], 'other': []} patch = jsonpatch.make_patch(src, dst) res = patch.apply(src) self.assertEqual(res, dst) def test_add_nested(self): # see http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-03#appendix-A.10 src = {"foo": "bar"} patch_obj = [ { "op": "add", "path": "/child", "value": { "grandchild": { } } } ] res = jsonpatch.apply_patch(src, patch_obj) expected = { "foo": "bar", "child": { "grandchild": { } } } self.assertEqual(expected, res) 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) 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] patch = jsonpatch.make_patch(src, dest) 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) 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)) self.assertEqual(len(patch), 1) self.assertEqual(patch[0]['op'], 'replace') 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) def test_use_move_instead_of_add_remove(self): src = {'foo': [1, 2, 3]} dst = {'foo': [3, 1, 2]} patch = list(jsonpatch.make_patch(src, dst)) self.assertEqual(len(patch), 1) self.assertEqual(patch[0]['op'], 'move') res = jsonpatch.apply_patch(src, patch) self.assertEqual(res, dst) def test_success_if_replace_inside_dict(self): src = [{'a': 1, 'foo': {'b': 2, 'd': 5}}] dst = [{'a': 1, 'foo': {'b': 3, 'd': 6}}] patch = jsonpatch.make_patch(src, dst) self.assertEqual(patch.apply(src), dst) def test_success_if_replace_single_value(self): src = [{'a': 1, 'b': 2, 'd': 5}] dst = [{'a': 1, 'c': 3, 'd': 5}] patch = jsonpatch.make_patch(src, dst) self.assertEqual(patch.apply(src), dst) def test_success_if_replaced_by_object(self): src = [{'a': 1, 'b': 2, 'd': 5}] dst = [{'d': 6}] patch = jsonpatch.make_patch(src, dst) self.assertEqual(patch.apply(src), dst) def test_success_if_correct_patch_appied(self): src = [{'a': 1}, {'b': 2}] dst = [{'a': 1, 'b': 2}] patch = jsonpatch.make_patch(src, dst) self.assertEqual(patch.apply(src), dst) def test_success_if_correct_expected_patch_appied(self): src = [{"a": 1, "b": 2}] dst = [{"b": 2, "c": 2}] exp = [{'path': '/0', 'value': {'c': 2, 'b': 2}, 'op': 'replace'}] patch = jsonpatch.make_patch(src, dst) self.assertEqual(patch.patch, exp) def test_minimal_patch(self): """ Test whether a minimal patch is created, see #36 """ src = [{"foo": 1, "bar": 2}] dst = [{"foo": 2, "bar": 2}] patch = jsonpatch.make_patch(src, dst) exp = [ { "path": "/0/foo", "value": 2, "op": "replace" } ] self.assertEqual(patch.patch, exp) class 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_missing(self): src = {"foo": 1} patch_obj = [ { "op": "replace", "path": "/bar", "value": 10} ] self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) 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(InvalidInputTests)) suite.addTest(unittest.makeSuite(ConflictTests)) suite.addTest(unittest.makeSuite(OptimizationTests)) 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)