Skip to content

fix(serializer): Make sentry_repr dunder method to avoid mock problems #1364

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

Merged
merged 5 commits into from
Mar 8, 2022
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
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