Skip to content

Commit

Permalink
chore(di): better support for builtin collections
Browse files Browse the repository at this point in the history
We improve the support for the serialisation of some builtin collection
types when rendering template messages.
  • Loading branch information
P403n1x87 committed Oct 7, 2024
1 parent c4cfa38 commit 131f333
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 17 deletions.
31 changes: 14 additions & 17 deletions ddtrace/debugging/_signal/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from collections import deque
from itertools import islice
from itertools import takewhile
from types import FrameType
Expand Down Expand Up @@ -73,19 +74,7 @@ def serialize(
if not level:
return repr(type(value))

if type(value) not in BUILTIN_CONTAINER_TYPES:
return "%s(%s)" % (
type(value).__name__,
", ".join(
(
"=".join((k, serialize(v, level - 1, maxsize, maxlen, maxfields)))
for k, v in islice(get_fields(value).items(), maxfields)
if not redact(k)
)
),
)

if type(value) is dict:
if type(value) in BUILTIN_MAPPING_TYPES:
return "{%s}" % ", ".join(
(
": ".join(
Expand All @@ -97,15 +86,23 @@ def serialize(
for k, v in islice(value.items(), maxsize)
)
)
elif type(value) is list:
elif type(value) in {list, deque}:
return _serialize_collection(value, "[]", level, maxsize, maxlen, maxfields)
elif type(value) is tuple:
return _serialize_collection(value, "()", level, maxsize, maxlen, maxfields)
elif type(value) is set:
elif type(value) in {set, frozenset}:
return _serialize_collection(value, r"{}", level, maxsize, maxlen, maxfields) if value else "set()"

msg = f"Unhandled type: {type(value)}"
raise TypeError(msg)
return "%s(%s)" % (
type(value).__name__,
", ".join(
(
"=".join((k, serialize(v, level - 1, maxsize, maxlen, maxfields)))
for k, v in islice(get_fields(value).items(), maxfields)
if not redact(k)
)
),
)


def capture_stack(top_frame: FrameType, max_height: int = 4096) -> List[dict]:
Expand Down
12 changes: 12 additions & 0 deletions tests/debugging/test_encoding.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-

from collections import defaultdict
import inspect
import json
import sys
Expand Down Expand Up @@ -663,3 +664,14 @@ def test_capture_value_sequence_type(_type):
],
"size": 1,
}


@pytest.mark.parametrize(
"value,expected",
[
(defaultdict(int, {"bar": 42}), "{'bar': 42}"),
(frozenset({"foo"}), "{'foo'}"),
],
)
def test_serialize_builtins(value, expected):
assert utils.serialize(value) == expected

0 comments on commit 131f333

Please sign in to comment.