[TrivialFix] Correct regex used in jsonpath_replace

The regex in jsonpath_replace is capturing paths with numeric
values inappropriately, because the characters [ and ] aren't
escaped, leading to things like foo0 result in an array trying to
be created. This has been corrected such that now an array
should only be created for foo[0] whereas for foo0 an object
should be created.

Unit tests have been added for the function.

Change-Id: Iebb4167a0bbb9c465c348c32f55e818c41aba53d
This commit is contained in:
Felipe Monteiro 2018-02-28 22:13:28 +00:00
parent 02c6a8dc1f
commit 86ae1ba9ee
2 changed files with 43 additions and 1 deletions

View File

@ -0,0 +1,42 @@
# Copyright 2018 AT&T Intellectual Property. All other rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from deckhand.tests.unit import base as test_base
from deckhand import utils
class TestUtils(test_base.DeckhandTestCase):
def test_jsonpath_replace_creates_object(self):
path = ".values.endpoints.admin"
expected = {'values': {'endpoints': {'admin': 'foo'}}}
result = utils.jsonpath_replace({}, 'foo', path)
self.assertEqual(expected, result)
def test_jsonpath_replace_with_array_index_creates_array(self):
path = ".values.endpoints[0].admin"
expected = {'values': {'endpoints': [{'admin': 'foo'}]}}
result = utils.jsonpath_replace({}, 'foo', path)
self.assertEqual(expected, result)
path = ".values.endpoints[1].admin"
expected = {'values': {'endpoints': [{}, {'admin': 'foo'}]}}
result = utils.jsonpath_replace({}, 'foo', path)
self.assertEqual(expected, result)
def test_jsonpath_replace_with_numeric_value_creates_object(self):
path = ".values.endpoints0.admin"
expected = {'values': {'endpoints0': {'admin': 'foo'}}}
result = utils.jsonpath_replace({}, 'foo', path)
self.assertEqual(expected, result)

View File

@ -89,7 +89,7 @@ def _populate_data_with_attributes(jsonpath, data):
# Populates ``data`` with any path specified in ``jsonpath``. For example,
# if jsonpath is ".foo[0].bar.baz" then for each subpath -- foo[0], bar,
# and baz -- that key will be added to ``data`` if missing.
array_re = re.compile(r'.*[\d].*')
array_re = re.compile(r'.*\[\d\].*')
d = data
for path in jsonpath.split('.')[1:]: