Skip to content

Commit b7dba57

Browse files
author
Antoine Leblanc
authored
tests: fix stringify function (hasura#4191)
The stackoverflow answer this was copied from has a glaring problem: python really dislikes a dictionary being modified while it is being iterated on. I rewrote the function to instead return a modified copy.
1 parent b53533c commit b7dba57

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed

server/tests-py/validate.py

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -406,26 +406,15 @@ def go(result_node, selset):
406406

407407
# Use this since jsondiff seems to produce object/dict structures that can't
408408
# always be serialized to json.
409-
# Copy-pasta from: https://stackoverflow.com/q/12734517/176841
410409
def stringify_keys(d):
411-
"""Convert a dict's keys to strings if they are not."""
412-
if isinstance(d, dict):
413-
for key in d.keys():
414-
# check inner dict
415-
if isinstance(d[key], dict):
416-
value = stringify_keys(d[key])
417-
else:
418-
value = d[key]
419-
# convert nonstring to string if needed
420-
if not isinstance(key, str):
421-
try:
422-
d[key.decode("utf-8")] = value
423-
except Exception:
424-
try:
425-
d[repr(key)] = value
426-
except Exception:
427-
raise
428-
429-
# delete old key
430-
del d[key]
431-
return d
410+
"""Recursively convert a dict's keys to strings."""
411+
if not isinstance(d, dict): return d
412+
413+
def decode(k):
414+
if isinstance(k, str): return k
415+
try:
416+
return k.decode("utf-8")
417+
except Exception:
418+
return repr(k)
419+
420+
return { decode(k): stringify_keys(v) for k, v in d.items() }

0 commit comments

Comments
 (0)