Python jsonpatch.make_patch() Examples

The following are code examples for showing how to use jsonpatch.make_patch(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: ludobox   Author: ludobox   File: history.py    GNU Affero General Public License v3.0 7 votes vote down vote up
def make_update_event(old_content, new_content, user=None):

    # make things immutable
    new = new_content.copy()
    old = old_content.copy()

    # ignore keys we don't want to track in the history events
    ignored_keys = ["history", "files", "errors", "has_errors"]
    for k in ignored_keys:
        new.pop(k, None)
        old.pop(k, None)

    # create json diff
    patch = make_patch(new, old)

    # check if there is actual changes
    if not len(list(patch)) :
        return None

    # create a new event and add it to history
    event = new_event("update", { "changes" : list(patch) }, user)
    return event 
Example 2
Project: drow   Author: Sendhub   File: test_fields.py    MIT License 6 votes vote down vote up
def test_usage_in_patch(self):
        with FakeModelContext() as context:
            MyModel, settings = context
            old_data = {
                'a': 'a'
            }
            new_data = {
                'b': 'b',
                'update_date2': 'asdf',
                'create_date': 'asdf'
            }

            instance = MyModel.objects.create(old_data)
            old_update = instance.data['update_date2']
            old_create = instance.data['create_date']

            patch_data = jsonpatch.make_patch(
                instance.data, new_data)

            result = instance.patch(patch_data)

            self.assertEqual(result.data['create_date'], old_create)
            self.assertNotEqual(result.data['update_date2'], old_update)
            self.assertNotEqual(result.data['update_date2'], 'asdf') 
Example 3
Project: drow   Author: Sendhub   File: test_queries.py    MIT License 6 votes vote down vote up
def test_bad_patch(self):
        # looks like jsonpatch/jsonpointer cannot handle unicode keys :/
        # bug report:
        # https://github.com/stefankoegl/python-json-pointer/issues/18
        old_data = {u'\xee': u'\xee'}
        new_data = deepcopy(old_data)
        patch = jsonpatch.make_patch({}, new_data)

        with self.assertRaises(InvalidPatch):
            validate_patch(patch, old_data)

        incomplete_patch = [{}]

        with self.assertRaises(InvalidPatch):
            validate_patch(incomplete_patch, old_data)

        # Non-unicode
        with self.assertRaises(InvalidPatch):
            validate_patch([{'path': '/ee', 'op': 'add'}], {'ee': 'ee'}) 
Example 4
Project: invenio-checker-old   Author: dset0x   File: conftest2.py    GNU General Public License v2.0 6 votes vote down vote up
def _patches_of_last_execution():
    """Get the full_patches generated during the last check.

    ..note::
        `invenio_records` is populated by the `get_record` function.
    """
    session = Session.session
    invenio_records = session.invenio_records
    redis_worker = session.config.option.redis_worker

    def get_full_patches():
        """Return all the record patches resulting from the last run."""
        for recid, modified_record in invenio_records['temporary'].items():
            original_record = invenio_records['original'][recid]
            patch = jsonpatch.make_patch(original_record, modified_record)
            if patch:
                yield make_fullpatch(recid, hash(original_record), patch, redis_worker.task_id)

    for full_patch in get_full_patches():
        del invenio_records['temporary'][full_patch['recid']]
        yield full_patch


# Runs after exception has been reported to the reporter, after every single fine-grained step 
Example 5
Project: drow   Author: Sendhub   File: test_queries.py    MIT License 5 votes vote down vote up
def test_patch(self):
        with FakeModelContext() as context:
            MyModel, settings = context
            client = settings.RIAK_CLIENT
            bucket = client.bucket()
            old_data = {
                'a': 'a'
            }
            new_data = {
                'b': 'b'
            }

            patch_data = jsonpatch.make_patch(old_data, new_data)

            old_get_side_effect = bucket.get.side_effect

            def get_with_data(key):
                instance = old_get_side_effect(key)
                instance.data = old_data
                return instance

            bucket.get.side_effect = get_with_data

            instance = MyModel('test_key')
            result = instance.patch(patch_data)

            self.assertEqual(MyModel._meta.storage_validator.call_count, 1)
            self.assertEqual(result._state.riak_object.store.call_count, 1)
            self.assertEqual(len(result.data), 1)
            self.assertEqual(result.data, new_data) 
Example 6
Project: f5-cccl   Author: f5devcentral   File: resource.py    Apache License 2.0 5 votes vote down vote up
def merge(self, desired_data):
        u"""Merge in properties from controller instead of replacing"""
        # 1. stop processing if no merging is needed
        prev_updates = self._retrieve_whitelist_updates()
        if desired_data == {} and prev_updates is None:
            # nothing needs to be done (cccl has not and will not make changes
            # to this resource)
            return False

        prev_data = copy.deepcopy(self._data)

        # 2. remove old CCCL updates
        pospatch.convert_to_positional_patch(self._data, prev_updates)

        try:
            # This actually backs out the previous updates
            # to get back to the original F5 resource state.
            if prev_updates:
                self._data = prev_updates.apply(self._data)
        except Exception as e:  # pylint: disable=broad-except
            LOGGER.warning("Failed removing updates to resource %s: %s",
                           self.name, e)

        # 3. perform new merge with latest CCCL specific config
        original_resource = copy.deepcopy(self)
        self._data = merge(self._data, desired_data)
        self.post_merge_adjustments()

        # 4. compute the new updates so we can back out next go-around
        cur_updates = jsonpatch.make_patch(self._data, original_resource.data)

        # 5. remove move / adjust indexes per resource specific
        pospatch.convert_from_positional_patch(self._data, cur_updates)

        changed = self._data != prev_data

        # 6. update metadata with new CCCL updates
        self._save_whitelist_updates(cur_updates)

        # 7. determine if there was a needed change
        return changed 
Example 7
Project: invenio-checker-old   Author: dset0x   File: conftest2.py    GNU General Public License v2.0 5 votes vote down vote up
def _pytest_sessionfinish(session, exitstatus):
    with start_action(action_type='moving added patches to redis'):
        invenio_records = session.invenio_records
        redis_worker = session.config.option.redis_worker

        for recid, modified_record in invenio_records['modified'].items():
            original_record = invenio_records['original'][recid]
            patch = jsonpatch.make_patch(original_record, modified_record)
            if patch:
                # FIXME: Hash is wrong
                redis_worker.patch_to_redis(
                    make_fullpatch(
                        recid, hash(original_record),
                        patch, redis_worker.task_id)
                )