Skip to content

Commit

Permalink
fix(serializer): Make sentry_repr dunder method to avoid mock problems (
Browse files Browse the repository at this point in the history
  • Loading branch information
sl0thentr0py authored Mar 8, 2022
1 parent b63b5ae commit a14c127
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
6 changes: 4 additions & 2 deletions sentry_sdk/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ def _serialize_node_impl(
if result is not NotImplemented:
return _flatten_annotated(result)

sentry_repr = getattr(type(obj), "__sentry_repr__", None)

if obj is None or isinstance(obj, (bool, number_types)):
if should_repr_strings or (
isinstance(obj, float) and (math.isinf(obj) or math.isnan(obj))
Expand All @@ -281,8 +283,8 @@ def _serialize_node_impl(
else:
return obj

elif callable(getattr(obj, "sentry_repr", None)):
return obj.sentry_repr()
elif callable(sentry_repr):
return sentry_repr(obj)

elif isinstance(obj, datetime):
return (
Expand Down
15 changes: 13 additions & 2 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import sys

import pytest

from sentry_sdk.serializer import serialize
Expand Down Expand Up @@ -68,8 +67,20 @@ def test_serialize_sets(extra_normalizer):

def test_serialize_custom_mapping(extra_normalizer):
class CustomReprDict(dict):
def sentry_repr(self):
def __sentry_repr__(self):
return "custom!"

result = extra_normalizer(CustomReprDict(one=1, two=2))
assert result == "custom!"


def test_custom_mapping_doesnt_mess_with_mock(extra_normalizer):
"""
Adding the __sentry_repr__ magic method check in the serializer
shouldn't mess with how mock works. This broke some stuff when we added
sentry_repr without the dunders.
"""
mock = pytest.importorskip("unittest.mock")
m = mock.Mock()
extra_normalizer(m)
assert len(m.mock_calls) == 0

0 comments on commit a14c127

Please sign in to comment.