Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added utility function to get an item from a nested dict #1358

Merged
merged 1 commit into from
Oct 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions elasticapm/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,13 @@ def starmatch_to_regex(pattern):
else:
res.append(re.escape(c))
return re.compile(r"(?:%s)\Z" % "".join(res), options)


def nested_key(d: dict, *args):
for arg in args:
try:
d = d[arg]
except (TypeError, KeyError):
d = None
break
return d
20 changes: 20 additions & 0 deletions tests/utils/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from elasticapm.utils import (
get_name_from_func,
get_url_dict,
nested_key,
read_pem_file,
sanitize_url,
starmatch_to_regex,
Expand Down Expand Up @@ -240,3 +241,22 @@ def test_read_pem_file_chain():
with open(os.path.join(os.path.dirname(__file__), "..", "ca", "chain.crt"), mode="rb") as f:
result = read_pem_file(f)
assert result.endswith(b"\xc8\xae")


@pytest.mark.parametrize(
"data,key,expected",
[
(None, "x", None),
({}, "x", None),
({"x": 1}, "x", 1),
({"x": {"y": 1}}, "x.y", 1),
({"x": 1}, "x.y", None),
({"x": {"y": {}}}, "x.y.z", None),
],
)
def test_nested_key(data, key, expected):
r = nested_key(data, *key.split("."))
if expected is None:
assert r is expected
else:
assert r == expected