Skip to content

Commit caa1ebe

Browse files
authored
Fix Django CI (#3659)
1 parent e32d286 commit caa1ebe

File tree

6 files changed

+91
-93
lines changed

6 files changed

+91
-93
lines changed

sentry_sdk/integrations/django/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -652,8 +652,8 @@ def execute(self, sql, params=None):
652652
_set_db_data(span, self)
653653
result = real_execute(self, sql, params)
654654

655-
with capture_internal_exceptions():
656-
add_query_source(span)
655+
with capture_internal_exceptions():
656+
add_query_source(span)
657657

658658
return result
659659

@@ -672,8 +672,8 @@ def executemany(self, sql, param_list):
672672

673673
result = real_executemany(self, sql, param_list)
674674

675-
with capture_internal_exceptions():
676-
add_query_source(span)
675+
with capture_internal_exceptions():
676+
add_query_source(span)
677677

678678
return result
679679

sentry_sdk/integrations/django/templates.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,9 @@ def rendered_content(self):
7373
name=_get_template_name_description(self.template_name),
7474
origin=DjangoIntegration.origin,
7575
) as span:
76-
span.set_data("context", self.context_data)
76+
if isinstance(self.context_data, dict):
77+
for k, v in self.context_data.items():
78+
span.set_data(f"context.{k}", v)
7779
return real_rendered_content.fget(self)
7880

7981
SimpleTemplateResponse.rendered_content = rendered_content
@@ -101,7 +103,8 @@ def render(request, template_name, context=None, *args, **kwargs):
101103
name=_get_template_name_description(template_name),
102104
origin=DjangoIntegration.origin,
103105
) as span:
104-
span.set_data("context", context)
106+
for k, v in context.items():
107+
span.set_data(f"context.{k}", v)
105108
return real_render(request, template_name, context, *args, **kwargs)
106109

107110
django.shortcuts.render = render

tests/integrations/django/test_basic.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from werkzeug.test import Client
99

1010
from django import VERSION as DJANGO_VERSION
11-
from django.contrib.auth.models import User
1211
from django.core.management import execute_from_command_line
1312
from django.db.utils import OperationalError, ProgrammingError, DataError
1413
from django.http.request import RawPostDataException
@@ -288,6 +287,9 @@ def test_user_captured(sentry_init, client, capture_events):
288287
def test_queryset_repr(sentry_init, capture_events):
289288
sentry_init(integrations=[DjangoIntegration()])
290289
events = capture_events()
290+
291+
from django.contrib.auth.models import User
292+
291293
User.objects.create_user("john", "[email protected]", "johnpassword")
292294

293295
try:
@@ -374,7 +376,7 @@ def test_sql_queries(sentry_init, capture_events, with_integration):
374376
crumb = event["breadcrumbs"]["values"][-1]
375377

376378
assert crumb["message"] == "SELECT count(*) FROM people_person WHERE foo = %s"
377-
assert crumb["data"]["db.params"] == [123]
379+
assert crumb["data"]["db.params"] == "[123]"
378380

379381

380382
@pytest.mark.forked
@@ -409,7 +411,7 @@ def test_sql_dict_query_params(sentry_init, capture_events):
409411
assert crumb["message"] == (
410412
"SELECT count(*) FROM people_person WHERE foo = %(my_foo)s"
411413
)
412-
assert crumb["data"]["db.params"] == {"my_foo": 10}
414+
assert crumb["data"]["db.params"] == str({"my_foo": 10})
413415

414416

415417
@pytest.mark.forked
@@ -471,7 +473,7 @@ def test_sql_psycopg2_string_composition(sentry_init, capture_events, query):
471473
(event,) = events
472474
crumb = event["breadcrumbs"]["values"][-1]
473475
assert crumb["message"] == ('SELECT %(my_param)s FROM "foobar"')
474-
assert crumb["data"]["db.params"] == {"my_param": 10}
476+
assert crumb["data"]["db.params"] == str({"my_param": 10})
475477

476478

477479
@pytest.mark.forked
@@ -524,7 +526,7 @@ def test_sql_psycopg2_placeholders(sentry_init, capture_events):
524526
{
525527
"category": "query",
526528
"data": {
527-
"db.params": {"first_var": "fizz", "second_var": "not a date"},
529+
"db.params": str({"first_var": "fizz", "second_var": "not a date"}),
528530
"db.paramstyle": "format",
529531
},
530532
"message": 'insert into my_test_table ("foo", "bar") values (%(first_var)s, '
@@ -928,6 +930,11 @@ def test_render_spans(sentry_init, client, capture_events, render_span_tree):
928930
transaction = events[0]
929931
assert expected_line in render_span_tree(transaction)
930932

933+
render_span = next(
934+
span for span in transaction["spans"] if span["op"] == "template.render"
935+
)
936+
assert "context.user_age" in render_span["data"]
937+
931938

932939
if DJANGO_VERSION >= (1, 10):
933940
EXPECTED_MIDDLEWARE_SPANS = """\

tests/integrations/django/test_cache_module.py

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,9 @@ def test_cache_spans_item_size(sentry_init, client, capture_events, use_django_c
511511

512512
@pytest.mark.forked
513513
@pytest_mark_django_db_decorator()
514-
def test_cache_spans_get_many(sentry_init, capture_events, use_django_caching):
514+
def test_cache_spans_get_many(
515+
sentry_init, capture_events, use_django_caching, render_span_tree
516+
):
515517
sentry_init(
516518
integrations=[
517519
DjangoIntegration(
@@ -528,39 +530,34 @@ def test_cache_spans_get_many(sentry_init, capture_events, use_django_caching):
528530

529531
from django.core.cache import cache
530532

531-
with sentry_sdk.start_transaction():
533+
with sentry_sdk.start_transaction(name="caches"):
532534
cache.get_many([f"S{id}", f"S{id+1}"])
533535
cache.set(f"S{id}", "Sensitive1")
534536
cache.get_many([f"S{id}", f"S{id+1}"])
535537

536538
(transaction,) = events
537539
assert len(transaction["spans"]) == 7
538540

539-
assert transaction["spans"][0]["op"] == "cache.get"
540-
assert transaction["spans"][0]["description"] == f"S{id}, S{id+1}"
541-
542-
assert transaction["spans"][1]["op"] == "cache.get"
543-
assert transaction["spans"][1]["description"] == f"S{id}"
544-
545-
assert transaction["spans"][2]["op"] == "cache.get"
546-
assert transaction["spans"][2]["description"] == f"S{id+1}"
547-
548-
assert transaction["spans"][3]["op"] == "cache.put"
549-
assert transaction["spans"][3]["description"] == f"S{id}"
550-
551-
assert transaction["spans"][4]["op"] == "cache.get"
552-
assert transaction["spans"][4]["description"] == f"S{id}, S{id+1}"
553-
554-
assert transaction["spans"][5]["op"] == "cache.get"
555-
assert transaction["spans"][5]["description"] == f"S{id}"
556-
557-
assert transaction["spans"][6]["op"] == "cache.get"
558-
assert transaction["spans"][6]["description"] == f"S{id+1}"
541+
assert (
542+
render_span_tree(transaction)
543+
== f"""\
544+
- op="caches": description=null
545+
- op="cache.get": description="S{id}, S{id+1}"
546+
- op="cache.get": description="S{id}"
547+
- op="cache.get": description="S{id+1}"
548+
- op="cache.put": description="S{id}"
549+
- op="cache.get": description="S{id}, S{id+1}"
550+
- op="cache.get": description="S{id}"
551+
- op="cache.get": description="S{id+1}"\
552+
""" # noqa: E221
553+
)
559554

560555

561556
@pytest.mark.forked
562557
@pytest_mark_django_db_decorator()
563-
def test_cache_spans_set_many(sentry_init, capture_events, use_django_caching):
558+
def test_cache_spans_set_many(
559+
sentry_init, capture_events, use_django_caching, render_span_tree
560+
):
564561
sentry_init(
565562
integrations=[
566563
DjangoIntegration(
@@ -577,24 +574,23 @@ def test_cache_spans_set_many(sentry_init, capture_events, use_django_caching):
577574

578575
from django.core.cache import cache
579576

580-
with sentry_sdk.start_transaction():
577+
with sentry_sdk.start_transaction(name="caches"):
581578
cache.set_many({f"S{id}": "Sensitive1", f"S{id+1}": "Sensitive2"})
582579
cache.get(f"S{id}")
583580

584581
(transaction,) = events
585582
assert len(transaction["spans"]) == 4
586583

587-
assert transaction["spans"][0]["op"] == "cache.put"
588-
assert transaction["spans"][0]["description"] == f"S{id}, S{id+1}"
589-
590-
assert transaction["spans"][1]["op"] == "cache.put"
591-
assert transaction["spans"][1]["description"] == f"S{id}"
592-
593-
assert transaction["spans"][2]["op"] == "cache.put"
594-
assert transaction["spans"][2]["description"] == f"S{id+1}"
595-
596-
assert transaction["spans"][3]["op"] == "cache.get"
597-
assert transaction["spans"][3]["description"] == f"S{id}"
584+
assert (
585+
render_span_tree(transaction)
586+
== f"""\
587+
- op="caches": description=null
588+
- op="cache.put": description="S{id}, S{id+1}"
589+
- op="cache.put": description="S{id}"
590+
- op="cache.put": description="S{id+1}"
591+
- op="cache.get": description="S{id}"\
592+
""" # noqa: E221
593+
)
598594

599595

600596
@pytest.mark.forked

tests/integrations/django/test_db_query_data.py

Lines changed: 38 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22

33
import pytest
4+
from contextlib import contextmanager
45
from datetime import datetime
56
from unittest import mock
67

@@ -15,7 +16,7 @@
1516
from freezegun import freeze_time
1617
from werkzeug.test import Client
1718

18-
from sentry_sdk import start_transaction
19+
from sentry_sdk import start_transaction, start_span
1920
from sentry_sdk.consts import SPANDATA
2021
from sentry_sdk.integrations.django import DjangoIntegration
2122
from sentry_sdk.tracing_utils import record_sql_queries
@@ -347,29 +348,24 @@ def test_no_query_source_if_duration_too_short(sentry_init, client, capture_even
347348

348349
events = capture_events()
349350

350-
class fake_record_sql_queries: # noqa: N801
351-
def __init__(self, *args, **kwargs):
352-
with freeze_time(datetime(2024, 1, 1, microsecond=0)):
353-
with record_sql_queries(*args, **kwargs) as span:
354-
self.span = span
355-
freezer = freeze_time(datetime(2024, 1, 1, microsecond=99999))
356-
freezer.start()
357-
358-
freezer.stop()
359-
360-
def __enter__(self):
361-
return self.span
362-
363-
def __exit__(self, type, value, traceback):
364-
pass
365-
366-
with mock.patch(
367-
"sentry_sdk.integrations.django.record_sql_queries",
368-
fake_record_sql_queries,
369-
):
370-
_, status, _ = unpack_werkzeug_response(
371-
client.get(reverse("postgres_select_orm"))
372-
)
351+
def fake_start_span(*args, **kwargs): # noqa: N801
352+
with freeze_time(datetime(2024, 1, 1, microsecond=0)):
353+
return start_span(*args, **kwargs)
354+
355+
@contextmanager
356+
def fake_record_sql_queries(*args, **kwargs): # noqa: N801
357+
with freeze_time(datetime(2024, 1, 1, microsecond=99999)):
358+
with record_sql_queries(*args, **kwargs) as span:
359+
yield span
360+
361+
with mock.patch("sentry_sdk.start_span", fake_start_span):
362+
with mock.patch(
363+
"sentry_sdk.integrations.django.record_sql_queries",
364+
fake_record_sql_queries,
365+
):
366+
_, status, _ = unpack_werkzeug_response(
367+
client.get(reverse("postgres_select_orm"))
368+
)
373369

374370
assert status == "200 OK"
375371

@@ -407,29 +403,24 @@ def test_query_source_if_duration_over_threshold(sentry_init, client, capture_ev
407403

408404
events = capture_events()
409405

410-
class fake_record_sql_queries: # noqa: N801
411-
def __init__(self, *args, **kwargs):
412-
with freeze_time(datetime(2024, 1, 1, microsecond=0)):
413-
with record_sql_queries(*args, **kwargs) as span:
414-
self.span = span
415-
freezer = freeze_time(datetime(2024, 1, 1, microsecond=99999))
416-
freezer.start()
417-
418-
freezer.stop()
419-
420-
def __enter__(self):
421-
return self.span
422-
423-
def __exit__(self, type, value, traceback):
424-
pass
425-
426-
with mock.patch(
427-
"sentry_sdk.integrations.django.record_sql_queries",
428-
fake_record_sql_queries,
429-
):
430-
_, status, _ = unpack_werkzeug_response(
431-
client.get(reverse("postgres_select_orm"))
432-
)
406+
def fake_start_span(*args, **kwargs): # noqa: N801
407+
with freeze_time(datetime(2024, 1, 1, microsecond=0)):
408+
return start_span(*args, **kwargs)
409+
410+
@contextmanager
411+
def fake_record_sql_queries(*args, **kwargs): # noqa: N801
412+
with freeze_time(datetime(2024, 1, 1, microsecond=100001)):
413+
with record_sql_queries(*args, **kwargs) as span:
414+
yield span
415+
416+
with mock.patch("sentry_sdk.start_span", fake_start_span):
417+
with mock.patch(
418+
"sentry_sdk.integrations.django.record_sql_queries",
419+
fake_record_sql_queries,
420+
):
421+
_, status, _ = unpack_werkzeug_response(
422+
client.get(reverse("postgres_select_orm"))
423+
)
433424

434425
assert status == "200 OK"
435426

tests/integrations/django/test_transactions.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
included_url_conf = ((re_path(r"^foo/bar/(?P<param>[\w]+)", lambda x: ""),), "")
2222

2323
from sentry_sdk.integrations.django.transactions import RavenResolver
24+
from tests.integrations.django.myapp.wsgi import application # noqa: F401
2425

2526

2627
example_url_conf = (

0 commit comments

Comments
 (0)