Projet

Général

Profil

0001-unflatten-add-an-escape-character-70474.patch

Emmanuel Cazenave, 19 octobre 2022 14:52

Télécharger (2,55 ko)

Voir les différences:

Subject: [PATCH] unflatten : add an escape character (#70474)

 passerelle/utils/json.py | 21 +++++++++++++++++----
 tests/test_utils_json.py | 20 ++++++++++++++++++++
 2 files changed, 37 insertions(+), 4 deletions(-)
passerelle/utils/json.py
29 29
# You should have received a copy of the GNU Affero General Public License
30 30
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
31 31

  
32
import re
32 33

  
33 34
from passerelle.utils.validation import is_number
34 35

  
......
49 50

  
50 51
    # ok d is a dict
51 52

  
52
    def map_digits(l):
53
        return [int(x) if is_number(x) else x for x in l]
54

  
55
    keys = [(map_digits(key.split(separator)), key) for key in d]
53
    def split_key(key):
54
        def map_key(x):
55
            if is_number(x):
56
                return int(x)
57
            elif isinstance(x, str):
58
                return x.replace('%s%s' % (FLATTEN_SEPARATOR, FLATTEN_SEPARATOR), FLATTEN_SEPARATOR)
59
            return x
60

  
61
        return [
62
            map_key(x)
63
            for x in re.split(
64
                r'(?<!%s)%s(?!%s)' % (FLATTEN_SEPARATOR, FLATTEN_SEPARATOR, FLATTEN_SEPARATOR), key
65
            )
66
        ]
67

  
68
    keys = [(split_key(key), key) for key in d]
56 69
    keys.sort()
57 70

  
58 71
    def set_path(path, orig_key, d, value, i=0):
tests/test_utils_json.py
63 63
        }
64 64
    }
65 65

  
66
    assert unflatten(
67
        {
68
            'a' + SEP + SEP + 'b': 1,
69
        }
70
    ) == {'a' + SEP + 'b': 1}
71

  
72
    assert unflatten(
73
        {
74
            'a' + SEP + SEP + 'b': 1,
75
            'a' + SEP + SEP + 'c' + SEP + 'd': 1,
76
        }
77
    ) == {'a' + SEP + 'b': 1, 'a' + SEP + 'c': {'d': 1}}
78

  
66 79

  
67 80
def test_unflatten_array():
68 81
    assert unflatten(
......
74 87
        }
75 88
    ) == [{'b': [1, True]}, {'c': [[1], 'a']}]
76 89

  
90
    assert unflatten(
91
        {
92
            '0' + SEP + 'b' + SEP + '0': 1,
93
            '1' + SEP + 'c' + SEP + SEP + '0': 1,
94
        }
95
    ) == [{'b': [1]}, {'c' + SEP + '0': 1}]
96

  
77 97

  
78 98
def test_unflatten_missing_final_index():
79 99
    with pytest.raises(ValueError) as exc_info:
80
-