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

Update black #1379

Merged
merged 7 commits into from Apr 1, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion linter-requirements.txt
@@ -1,4 +1,4 @@
black==21.7b0
black==22.3.0
flake8==3.9.2
flake8-import-order==0.18.1
mypy==0.782
Expand Down
1 change: 0 additions & 1 deletion sentry_sdk/client.py
Expand Up @@ -451,7 +451,6 @@ class get_options(ClientConstructor, Dict[str, Any]): # noqa: N801
class Client(ClientConstructor, _Client):
pass


else:
# Alias `get_options` for actual usage. Go through the lambda indirection
# to throw PyCharm off of the weakly typed signature (it would otherwise
Expand Down
1 change: 0 additions & 1 deletion sentry_sdk/hub.py
Expand Up @@ -120,7 +120,6 @@ def _init(*args, **kwargs):
class init(ClientConstructor, ContextManager[Any]): # noqa: N801
pass


else:
# Alias `init` for actual usage. Go through the lambda indirection to throw
# PyCharm off of the weakly typed signature (it would otherwise discover
Expand Down
4 changes: 2 additions & 2 deletions sentry_sdk/integrations/_wsgi_common.py
Expand Up @@ -39,8 +39,8 @@ def request_body_within_bounds(client, content_length):
bodies = client.options["request_bodies"]
return not (
bodies == "never"
or (bodies == "small" and content_length > 10 ** 3)
or (bodies == "medium" and content_length > 10 ** 4)
or (bodies == "small" and content_length > 10**3)
or (bodies == "medium" and content_length > 10**4)
)


Expand Down
3 changes: 1 addition & 2 deletions sentry_sdk/integrations/django/__init__.py
Expand Up @@ -69,7 +69,6 @@ def is_authenticated(request_user):
# type: (Any) -> bool
return request_user.is_authenticated()


else:

def is_authenticated(request_user):
Expand Down Expand Up @@ -202,7 +201,7 @@ def _django_queryset_repr(value, hint):
# querysets. This might be surprising to the user but it's likely
# less annoying.

return u"<%s from %s at 0x%x>" % (
return "<%s from %s at 0x%x>" % (
value.__class__.__name__,
value.__module__,
id(value),
Expand Down
1 change: 0 additions & 1 deletion sentry_sdk/integrations/pyramid.py
Expand Up @@ -40,7 +40,6 @@ def authenticated_userid(request):
# type: (Request) -> Optional[Any]
return request.authenticated_userid


else:
# bw-compat for pyramid < 1.5
from pyramid.security import authenticated_userid # type: ignore
Expand Down
1 change: 0 additions & 1 deletion sentry_sdk/integrations/wsgi.py
Expand Up @@ -46,7 +46,6 @@ def wsgi_decoding_dance(s, charset="utf-8", errors="replace"):
# type: (str, str, str) -> str
return s.decode(charset, errors)


else:

def wsgi_decoding_dance(s, charset="utf-8", errors="replace"):
Expand Down
6 changes: 3 additions & 3 deletions sentry_sdk/serializer.py
Expand Up @@ -66,11 +66,11 @@
# Can be overwritten if wanting to send more bytes, e.g. with a custom server.
# When changing this, keep in mind that events may be a little bit larger than
# this value due to attached metadata, so keep the number conservative.
MAX_EVENT_BYTES = 10 ** 6
MAX_EVENT_BYTES = 10**6

MAX_DATABAG_DEPTH = 5
MAX_DATABAG_BREADTH = 10
CYCLE_MARKER = u"<cyclic>"
CYCLE_MARKER = "<cyclic>"


global_repr_processors = [] # type: List[ReprProcessor]
Expand Down Expand Up @@ -228,7 +228,7 @@ def _serialize_node(
capture_internal_exception(sys.exc_info())

if is_databag:
return u"<failed to serialize, use init(debug=True) to see error logs>"
return "<failed to serialize, use init(debug=True) to see error logs>"

return None
finally:
Expand Down
38 changes: 22 additions & 16 deletions sentry_sdk/tracing.py
Expand Up @@ -132,14 +132,17 @@ def init_span_recorder(self, maxlen):

def __repr__(self):
# type: () -> str
return "<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>" % (
self.__class__.__name__,
self.op,
self.description,
self.trace_id,
self.span_id,
self.parent_span_id,
self.sampled,
return (
"<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>"
% (
self.__class__.__name__,
self.op,
self.description,
self.trace_id,
self.span_id,
self.parent_span_id,
self.sampled,
)
)

def __enter__(self):
Expand Down Expand Up @@ -515,14 +518,17 @@ def __init__(

def __repr__(self):
# type: () -> str
return "<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>" % (
self.__class__.__name__,
self.name,
self.op,
self.trace_id,
self.span_id,
self.parent_span_id,
self.sampled,
return (
"<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>"
% (
self.__class__.__name__,
self.name,
self.op,
self.trace_id,
self.span_id,
self.parent_span_id,
self.sampled,
)
)

@property
Expand Down
10 changes: 4 additions & 6 deletions sentry_sdk/utils.py
Expand Up @@ -161,7 +161,7 @@ def __init__(self, value):
return
parts = urlparse.urlsplit(text_type(value))

if parts.scheme not in (u"http", u"https"):
if parts.scheme not in ("http", "https"):
raise BadDsn("Unsupported scheme %r" % parts.scheme)
self.scheme = parts.scheme

Expand Down Expand Up @@ -280,7 +280,7 @@ def to_header(self, timestamp=None):
rv.append(("sentry_client", self.client))
if self.secret_key is not None:
rv.append(("sentry_secret", self.secret_key))
return u"Sentry " + u", ".join("%s=%s" % (key, value) for key, value in rv)
return "Sentry " + ", ".join("%s=%s" % (key, value) for key, value in rv)


class AnnotatedValue(object):
Expand Down Expand Up @@ -440,8 +440,7 @@ def safe_repr(value):
return rv
except Exception:
# If e.g. the call to `repr` already fails
return u"<broken repr>"

return "<broken repr>"

else:

Expand Down Expand Up @@ -606,7 +605,6 @@ def walk_exception_chain(exc_info):
exc_value = cause
tb = getattr(cause, "__traceback__", None)


else:

def walk_exception_chain(exc_info):
Expand Down Expand Up @@ -772,7 +770,7 @@ def strip_string(value, max_length=None):

if length > max_length:
return AnnotatedValue(
value=value[: max_length - 3] + u"...",
value=value[: max_length - 3] + "...",
metadata={
"len": length,
"rem": [["!limit", "x", max_length - 3, max_length]],
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -39,7 +39,7 @@ def get_file_text(file_name):
license="BSD",
install_requires=["urllib3>=1.10.0", "certifi"],
extras_require={
"flask": ["flask>=0.11", "blinker>=1.1"],
"flask": ["flask>=0.11,<2.1.0", "blinker>=1.1"],
"quart": ["quart>=0.16.1", "blinker>=1.1"],
"bottle": ["bottle>=0.12.13"],
"falcon": ["falcon>=1.4"],
Expand Down
2 changes: 1 addition & 1 deletion test-requirements.txt
Expand Up @@ -2,7 +2,7 @@ pytest<7
pytest-forked<=1.4.0
pytest-watch==4.2.0
tox==3.7.0
Werkzeug
Werkzeug<2.1.0
pytest-localserver==0.5.0
pytest-cov==2.8.1
jsonschema==3.2.0
Expand Down
1 change: 0 additions & 1 deletion tests/conftest.py
Expand Up @@ -39,7 +39,6 @@
def benchmark():
return lambda x: x()


else:
del pytest_benchmark

Expand Down
2 changes: 1 addition & 1 deletion tests/integrations/bottle/test_bottle.py
Expand Up @@ -196,7 +196,7 @@ def index():
assert len(event["request"]["data"]["foo"]) == 512


@pytest.mark.parametrize("input_char", [u"a", b"a"])
@pytest.mark.parametrize("input_char", ["a", b"a"])
def test_too_large_raw_request(
sentry_init, input_char, capture_events, app, get_client
):
Expand Down
1 change: 0 additions & 1 deletion tests/integrations/django/myapp/views.py
Expand Up @@ -29,7 +29,6 @@ def rest_hello(request):
def rest_permission_denied_exc(request):
raise PermissionDenied("bye")


except ImportError:
pass

Expand Down
8 changes: 4 additions & 4 deletions tests/integrations/django/test_basic.py
Expand Up @@ -576,15 +576,15 @@ def test_template_exception(

if with_executing_integration:
assert filenames[-3:] == [
(u"Parser.parse", u"django.template.base"),
("Parser.parse", "django.template.base"),
(None, None),
(u"Parser.invalid_block_tag", u"django.template.base"),
("Parser.invalid_block_tag", "django.template.base"),
]
else:
assert filenames[-3:] == [
(u"parse", u"django.template.base"),
("parse", "django.template.base"),
(None, None),
(u"invalid_block_tag", u"django.template.base"),
("invalid_block_tag", "django.template.base"),
]


Expand Down
4 changes: 3 additions & 1 deletion tests/test_client.py
Expand Up @@ -496,7 +496,9 @@ def test_scope_initialized_before_client(sentry_init, capture_events):
def test_weird_chars(sentry_init, capture_events):
sentry_init()
events = capture_events()
# fmt: off
capture_message(u"föö".encode("latin1"))
# fmt: on
(event,) = events
assert json.loads(json.dumps(event)) == event

Expand Down Expand Up @@ -812,7 +814,7 @@ def __repr__(self):
"dsn",
[
"http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2",
u"http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2",
"http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2",
],
)
def test_init_string_types(dsn, sentry_init):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_serializer.py
Expand Up @@ -50,7 +50,9 @@ def inner(message, **kwargs):
def test_bytes_serialization_decode(message_normalizer):
binary = b"abc123\x80\xf0\x9f\x8d\x95"
result = message_normalizer(binary, should_repr_strings=False)
# fmt: off
assert result == u"abc123\ufffd\U0001f355"
# fmt: on


@pytest.mark.xfail(sys.version_info < (3,), reason="Known safe_repr bugs in Py2.7")
Expand Down
72 changes: 33 additions & 39 deletions tests/utils/test_general.py
Expand Up @@ -31,19 +31,23 @@
def test_safe_repr_never_broken_for_strings(x):
r = safe_repr(x)
assert isinstance(r, text_type)
assert u"broken repr" not in r
assert "broken repr" not in r


def test_safe_repr_regressions():
# fmt: off
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are these needed?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So that black does not remove the u"" from the strings and breaks our tests.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can "turn off" black formatting for parts of the code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no but why did you remove most of the other u""'s but not these ones?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

strings containing only ascii characters do not need u"" in python 2.7. Only strings containing unicode chars need the u"". (hence "u")

I think Python (2) did a really bad job in adding unicode support to the language

assert u"лошадь" in safe_repr(u"лошадь")
# fmt: on


@pytest.mark.xfail(
sys.version_info < (3,),
reason="Fixing this in Python 2 would break other behaviors",
)
@pytest.mark.parametrize("prefix", (u"", u"abcd", u"лошадь"))
# fmt: off
@pytest.mark.parametrize("prefix", ("", "abcd", u"лошадь"))
@pytest.mark.parametrize("character", u"\x00\x07\x1b\n")
# fmt: on
def test_safe_repr_non_printable(prefix, character):
"""Check that non-printable characters are escaped"""
string = prefix + character
Expand Down Expand Up @@ -129,49 +133,38 @@ def test_parse_invalid_dsn(dsn):

@pytest.mark.parametrize("empty", [None, []])
def test_in_app(empty):
assert (
handle_in_app_impl(
[{"module": "foo"}, {"module": "bar"}],
in_app_include=["foo"],
in_app_exclude=empty,
)
== [{"module": "foo", "in_app": True}, {"module": "bar"}]
)

assert (
handle_in_app_impl(
[{"module": "foo"}, {"module": "bar"}],
in_app_include=["foo"],
in_app_exclude=["foo"],
)
== [{"module": "foo", "in_app": True}, {"module": "bar"}]
)

assert (
handle_in_app_impl(
[{"module": "foo"}, {"module": "bar"}],
in_app_include=empty,
in_app_exclude=["foo"],
)
== [{"module": "foo", "in_app": False}, {"module": "bar", "in_app": True}]
)
assert handle_in_app_impl(
[{"module": "foo"}, {"module": "bar"}],
in_app_include=["foo"],
in_app_exclude=empty,
) == [{"module": "foo", "in_app": True}, {"module": "bar"}]

assert handle_in_app_impl(
[{"module": "foo"}, {"module": "bar"}],
in_app_include=["foo"],
in_app_exclude=["foo"],
) == [{"module": "foo", "in_app": True}, {"module": "bar"}]

assert handle_in_app_impl(
[{"module": "foo"}, {"module": "bar"}],
in_app_include=empty,
in_app_exclude=["foo"],
) == [{"module": "foo", "in_app": False}, {"module": "bar", "in_app": True}]


def test_iter_stacktraces():
assert (
set(
iter_event_stacktraces(
{
"threads": {"values": [{"stacktrace": 1}]},
"stacktrace": 2,
"exception": {"values": [{"stacktrace": 3}]},
}
)
assert set(
iter_event_stacktraces(
{
"threads": {"values": [{"stacktrace": 1}]},
"stacktrace": 2,
"exception": {"values": [{"stacktrace": 3}]},
}
)
== {1, 2, 3}
)
) == {1, 2, 3}


# fmt: off
@pytest.mark.parametrize(
("original", "base64_encoded"),
[
Expand All @@ -191,6 +184,7 @@ def test_iter_stacktraces():
),
],
)
# fmt: on
def test_successful_base64_conversion(original, base64_encoded):
# all unicode characters should be handled correctly
assert to_base64(original) == base64_encoded
Expand Down