Skip to content

Increase test coverage #4393

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

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
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
60 changes: 60 additions & 0 deletions tests/test_basics.py
Copy link
Contributor Author

@mgaligniana mgaligniana May 19, 2025

Choose a reason for hiding this comment

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

🎗️ For some reason when I run it alone the coverage is 100%. When I run the whole test suite I get 95%

Copy link
Contributor Author

Choose a reason for hiding this comment

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

🔍 👣 Found it. Couple of tests fail running the entire suite

image

Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,66 @@ def test_attachments_graceful_failure(
assert envelope.items[1].payload.get_bytes() == b""


def test_attachments_exceptions(sentry_init):
sentry_init()

scope = sentry_sdk.get_isolation_scope()

# bytes and path are None
with pytest.raises(TypeError) as e:
scope.add_attachment()

assert str(e.value) == "path or raw bytes required for attachment"

# filename is None
with pytest.raises(TypeError) as e:
scope.add_attachment(bytes=b"Hello World!")

assert str(e.value) == "filename is required for attachment"


def test_attachments_content_type_is_none(sentry_init, capture_envelopes):
sentry_init()
envelopes = capture_envelopes()

scope = sentry_sdk.get_isolation_scope()

scope.add_attachment(
bytes=b"Hello World!", filename="message.txt", content_type="foo/bar"
)
capture_exception(ValueError())

(envelope,) = envelopes
attachments = [x for x in envelope.items if x.type == "attachment"]
(message,) = attachments

assert message.headers["filename"] == "message.txt"
assert message.headers["content_type"] == "foo/bar"


def test_attachments_repr(sentry_init):
sentry_init()

scope = sentry_sdk.get_isolation_scope()

scope.add_attachment(bytes=b"Hello World!", filename="message.txt")

assert repr(scope._attachments[0]) == "<Attachment 'message.txt'>"


def test_attachments_bytes_callable_payload(sentry_init):
sentry_init()

scope = sentry_sdk.get_isolation_scope()

scope.add_attachment(bytes=bytes, filename="message.txt")

attachment = scope._attachments[0]
item = attachment.to_envelope_item()

assert item.payload.bytes == b""


def test_integration_scoping(sentry_init, capture_events):
logger = logging.getLogger("test_basics")

Expand Down
188 changes: 146 additions & 42 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
_get_installed_modules,
_generate_installed_modules,
ensure_integration_enabled,
to_string,
exc_info_from_error,
get_lines_from_file,
package_version,
)


Expand Down Expand Up @@ -61,55 +65,72 @@ def _normalize_distribution_name(name):
return re.sub(r"[-_.]+", "-", name).lower()


@pytest.mark.parametrize(
("input_str", "expected_output"),
isoformat_inputs_and_datetime_outputs = (
(
(
"2021-01-01T00:00:00.000000Z",
datetime(2021, 1, 1, tzinfo=timezone.utc),
), # UTC time
(
"2021-01-01T00:00:00.000000",
datetime(2021, 1, 1).astimezone(timezone.utc),
), # No TZ -- assume local but convert to UTC
(
"2021-01-01T00:00:00Z",
datetime(2021, 1, 1, tzinfo=timezone.utc),
), # UTC - No milliseconds
(
"2021-01-01T00:00:00.000000+00:00",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2021-01-01T00:00:00.000000-00:00",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2021-01-01T00:00:00.000000+0000",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2021-01-01T00:00:00.000000-0000",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2020-12-31T00:00:00.000000+02:00",
datetime(2020, 12, 31, tzinfo=timezone(timedelta(hours=2))),
), # UTC+2 time
(
"2020-12-31T00:00:00.000000-0200",
datetime(2020, 12, 31, tzinfo=timezone(timedelta(hours=-2))),
), # UTC-2 time
(
"2020-12-31T00:00:00-0200",
datetime(2020, 12, 31, tzinfo=timezone(timedelta(hours=-2))),
), # UTC-2 time - no milliseconds
"2021-01-01T00:00:00.000000Z",
datetime(2021, 1, 1, tzinfo=timezone.utc),
), # UTC time
(
"2021-01-01T00:00:00.000000",
datetime(2021, 1, 1).astimezone(timezone.utc),
), # No TZ -- assume local but convert to UTC
(
"2021-01-01T00:00:00Z",
datetime(2021, 1, 1, tzinfo=timezone.utc),
), # UTC - No milliseconds
(
"2021-01-01T00:00:00.000000+00:00",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2021-01-01T00:00:00.000000-00:00",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2021-01-01T00:00:00.000000+0000",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2021-01-01T00:00:00.000000-0000",
datetime(2021, 1, 1, tzinfo=timezone.utc),
),
(
"2020-12-31T00:00:00.000000+02:00",
datetime(2020, 12, 31, tzinfo=timezone(timedelta(hours=2))),
), # UTC+2 time
(
"2020-12-31T00:00:00.000000-0200",
datetime(2020, 12, 31, tzinfo=timezone(timedelta(hours=-2))),
), # UTC-2 time
(
"2020-12-31T00:00:00-0200",
datetime(2020, 12, 31, tzinfo=timezone(timedelta(hours=-2))),
), # UTC-2 time - no milliseconds
)


@pytest.mark.parametrize(
("input_str", "expected_output"),
isoformat_inputs_and_datetime_outputs,
)
def test_datetime_from_isoformat(input_str, expected_output):
assert datetime_from_isoformat(input_str) == expected_output, input_str


@pytest.mark.parametrize(
("input_str", "expected_output"),
isoformat_inputs_and_datetime_outputs,
)
def test_datetime_from_isoformat_with_py_36_or_lower(input_str, expected_output):
"""
`fromisoformat` was added in Python version 3.7
"""
with mock.patch("sentry_sdk.utils.datetime") as datetime_mocked:
datetime_mocked.fromisoformat.side_effect = AttributeError()
datetime_mocked.strptime = datetime.strptime
assert datetime_from_isoformat(input_str) == expected_output, input_str


@pytest.mark.parametrize(
"env_var_value,strict,expected",
[
Expand Down Expand Up @@ -346,6 +367,12 @@ def test_sanitize_url_and_split(url, expected_result):
assert sanitized_url.fragment == expected_result.fragment


def test_sanitize_url_remove_authority_is_false():
url = "https://usr:pwd@example.com"
sanitized_url = sanitize_url(url, remove_authority=False)
assert sanitized_url == url


@pytest.mark.parametrize(
("url", "sanitize", "expected_url", "expected_query", "expected_fragment"),
[
Expand Down Expand Up @@ -629,6 +656,17 @@ def test_get_error_message(error, expected_result):
assert get_error_message(exc_value) == expected_result(exc_value)


def test_safe_str_fails():
class ExplodingStr:
def __str__(self):
raise Exception

obj = ExplodingStr()
result = safe_str(obj)

assert result == repr(obj)


def test_installed_modules():
try:
from importlib.metadata import distributions, version
Expand Down Expand Up @@ -712,6 +750,20 @@ def test_default_release_empty_string():
assert release is None


def test_get_default_release_sentry_release_env(monkeypatch):
monkeypatch.setenv("SENTRY_RELEASE", "sentry-env-release")
assert get_default_release() == "sentry-env-release"


def test_get_default_release_other_release_env(monkeypatch):
monkeypatch.setenv("SOURCE_VERSION", "other-env-release")

with mock.patch("sentry_sdk.utils.get_git_revision", return_value=""):
release = get_default_release()

assert release == "other-env-release"


def test_ensure_integration_enabled_integration_enabled(sentry_init):
def original_function():
return "original"
Expand Down Expand Up @@ -973,3 +1025,55 @@ def test_function(): ...
sentry_sdk.utils.qualname_from_function(test_function)
== "test_qualname_from_function_none_name.<locals>.test_function"
)


def test_to_string_unicode_decode_error():
class BadStr:
def __str__(self):
raise UnicodeDecodeError("utf-8", b"", 0, 1, "reason")

obj = BadStr()
result = to_string(obj)
assert result == repr(obj)[1:-1]


def test_exc_info_from_error_dont_get_an_exc():
class NotAnException:
pass

with pytest.raises(ValueError) as exc:
exc_info_from_error(NotAnException())

assert "Expected Exception object to report, got <class" in str(exc.value)


def test_get_lines_from_file_handle_linecache_errors():
expected_result = ([], None, [])

class Loader:
@staticmethod
def get_source(module):
raise IOError("something went wrong")

result = get_lines_from_file("filename", 10, loader=Loader())
assert result == expected_result

with mock.patch(
"sentry_sdk.utils.linecache.getlines",
side_effect=OSError("something went wrong"),
):
result = get_lines_from_file("filename", 10)
assert result == expected_result

lines = ["line1", "line2", "line3"]

def fake_getlines(filename):
return lines

with mock.patch("sentry_sdk.utils.linecache.getlines", fake_getlines):
result = get_lines_from_file("filename", 10)
assert result == expected_result


def test_package_version_is_none():
assert package_version("non_existent_package") is None
15 changes: 13 additions & 2 deletions tests/utils/test_contextvars.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import pytest
import random
import time
from unittest import mock


@pytest.mark.forked
def test_leaks(maybe_monkeypatched_threading):
def _run_contextvar_threaded_test():
import threading

# Need to explicitly call _get_contextvars because the SDK has already
Expand Down Expand Up @@ -39,3 +39,14 @@ def run():
t.join()

assert len(success) == 20


@pytest.mark.forked
def test_leaks(maybe_monkeypatched_threading):
_run_contextvar_threaded_test()


@pytest.mark.forked
@mock.patch("sentry_sdk.utils._is_contextvars_broken", return_value=True)
def test_leaks_when_is_contextvars_broken_is_false(maybe_monkeypatched_threading):
_run_contextvar_threaded_test()
39 changes: 39 additions & 0 deletions tests/utils/test_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,26 @@ def test_filename():

assert x("bogus", "bogus") == "bogus"

assert x("bogus", "bogus.pyc") == "bogus.py"

assert x("os", os.__file__) == "os.py"

assert x("foo.bar", "path/to/foo/bar.py") == "path/to/foo/bar.py"

import sentry_sdk.utils

assert x("sentry_sdk.utils", sentry_sdk.utils.__file__) == "sentry_sdk/utils.py"


def test_filename_module_file_is_none():
class DummyModule:
__file__ = None

os.sys.modules["foo"] = DummyModule()

assert filename_for_module("foo.bar", "path/to/foo/bar.py") == "path/to/foo/bar.py"


@pytest.mark.parametrize(
"given,expected_envelope",
[
Expand Down Expand Up @@ -120,6 +133,21 @@ def test_parse_invalid_dsn(dsn):
dsn = Dsn(dsn)


@pytest.mark.parametrize(
"dsn,error_message",
[
("foo://barbaz@sentry.io", "Unsupported scheme 'foo'"),
("https://foobar@", "Missing hostname"),
("https://@sentry.io", "Missing public key"),
],
)
def test_dsn_validations(dsn, error_message):
with pytest.raises(BadDsn) as e:
dsn = Dsn(dsn)

assert str(e.value) == error_message


@pytest.mark.parametrize(
"frame,in_app_include,in_app_exclude,project_root,resulting_frame",
[
Expand Down Expand Up @@ -578,6 +606,17 @@ def test_failed_base64_conversion(input):
value="é...", metadata={"len": 8, "rem": [["!limit", "x", 2, 5]]}
),
],
[
"\udfff\udfff\udfff\udfff\udfff\udfff",
5,
AnnotatedValue(
value="\udfff\udfff...",
metadata={
"len": 6,
"rem": [["!limit", "x", 5 - 3, 5]],
},
),
],
],
)
def test_strip_string(input, max_length, result):
Expand Down
Loading