Python sentry_sdk.integrations.django.DjangoIntegration() Examples

The following are 25 code examples of sentry_sdk.integrations.django.DjangoIntegration(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sentry_sdk.integrations.django , or try the search function .
Example #1
Source File: test_settings.py    From mitoc-trips with GNU General Public License v3.0 6 votes vote down vote up
def test_sentry_initialized_from_envvar(self):
        """ The DSN for Sentry comes from config. """
        fake_dsn = 'https://hex-code@sentry.io/123446'

        with mock.patch.dict('os.environ', {'RAVEN_DSN': fake_dsn}):
            with mock.patch.object(settings.sentry_sdk, 'init') as init_sentry:
                self._fresh_settings_load()
        init_sentry.assert_called_once_with(
            fake_dsn,
            integrations=[mock.ANY, mock.ANY],  # Django & Celery, checked separately
            send_default_pii=True,
        )
        integrations = init_sentry.call_args_list[0][1]['integrations']

        self.assertTrue(isinstance(integrations[0], DjangoIntegration))
        self.assertTrue(isinstance(integrations[1], CeleryIntegration)) 
Example #2
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_request_captured(sentry_init, client, capture_events):
    sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
    events = capture_events()
    content, status, headers = client.get(reverse("message"))
    assert b"".join(content) == b"ok"

    (event,) = events
    assert event["transaction"] == "/message"
    assert event["request"] == {
        "cookies": {},
        "env": {"SERVER_NAME": "localhost", "SERVER_PORT": "80"},
        "headers": {"Host": "localhost"},
        "method": "GET",
        "query_string": "",
        "url": "http://localhost/message",
    } 
Example #3
Source File: settings.py    From richie with MIT License 6 votes vote down vote up
def post_setup(cls):
        """Post setup configuration.
        This is the place where you can configure settings that require other
        settings to be loaded.
        """
        super().post_setup()

        # The SENTRY_DSN setting should be available to activate sentry for an environment
        if cls.SENTRY_DSN is not None:
            sentry_sdk.init(
                dsn=cls.SENTRY_DSN,
                environment=cls.ENVIRONMENT,
                release=cls.RELEASE,
                integrations=[DjangoIntegration()],
            )
            with sentry_sdk.configure_scope() as scope:
                scope.set_extra("application", "backend") 
Example #4
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_user_captured(sentry_init, client, capture_events):
    sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
    events = capture_events()
    content, status, headers = client.get(reverse("mylogin"))
    assert b"".join(content) == b"ok"

    assert not events

    content, status, headers = client.get(reverse("message"))
    assert b"".join(content) == b"ok"

    (event,) = events

    assert event["user"] == {
        "email": "lennon@thebeatles.com",
        "username": "john",
        "id": "1",
    } 
Example #5
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_custom_error_handler_request_context(sentry_init, client, capture_events):
    sentry_init(integrations=[DjangoIntegration()])
    events = capture_events()
    content, status, headers = client.post("/404")
    assert status.lower() == "404 not found"

    (event,) = events

    assert event["message"] == "not found"
    assert event["level"] == "error"
    assert event["request"] == {
        "env": {"SERVER_NAME": "localhost", "SERVER_PORT": "80"},
        "headers": {"Host": "localhost"},
        "method": "POST",
        "query_string": "",
        "url": "http://localhost/404",
    } 
Example #6
Source File: asgi.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def patch_channels_asgi_handler_impl(cls):
    # type: (Any) -> None
    old_app = cls.__call__

    async def sentry_patched_asgi_handler(self, receive, send):
        # type: (Any, Any, Any) -> Any
        if Hub.current.get_integration(DjangoIntegration) is None:
            return await old_app(self, receive, send)

        middleware = SentryAsgiMiddleware(
            lambda _scope: old_app.__get__(self, cls), unsafe_context_data=True
        )

        return await middleware(self.scope)(receive, send)

    cls.__call__ = sentry_patched_asgi_handler 
Example #7
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_sql_psycopg2_string_composition(sentry_init, capture_events, query):
    sentry_init(
        integrations=[DjangoIntegration()],
        send_default_pii=True,
        _experiments={"record_sql_params": True},
    )
    from django.db import connections

    if "postgres" not in connections:
        pytest.skip("postgres tests disabled")

    import psycopg2.sql

    sql = connections["postgres"].cursor()

    events = capture_events()
    with pytest.raises(ProgrammingError):
        sql.execute(query(psycopg2.sql), {"my_param": 10})

    capture_message("HI")

    (event,) = events
    crumb = event["breadcrumbs"][-1]
    assert crumb["message"] == ('SELECT %(my_param)s FROM "foobar"')
    assert crumb["data"]["db.params"] == {"my_param": 10} 
Example #8
Source File: settings.py    From marsha with MIT License 6 votes vote down vote up
def post_setup(cls):
        """Post setup configuration.

        This is the place where you can configure settings that require other
        settings to be loaded.
        """
        super().post_setup()

        # The DJANGO_SENTRY_DSN environment variable should be set to activate
        # sentry for an environment
        if cls.SENTRY_DSN is not None:
            sentry_sdk.init(
                dsn=cls.SENTRY_DSN,
                environment=cls.ENVIRONMENT,
                release=cls.RELEASE,
                integrations=[DjangoIntegration()],
            )
            with sentry_sdk.configure_scope() as scope:
                scope.set_extra("application", "backend") 
Example #9
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_rest_framework_basic(
    sentry_init, client, capture_events, capture_exceptions, ct, body, route
):
    pytest.importorskip("rest_framework")
    sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
    exceptions = capture_exceptions()
    events = capture_events()

    if ct == "application/json":
        client.post(
            reverse(route), data=json.dumps(body), content_type="application/json"
        )
    elif ct == "application/x-www-form-urlencoded":
        client.post(reverse(route), data=body)
    else:
        assert False

    (error,) = exceptions
    assert isinstance(error, ZeroDivisionError)

    (event,) = events
    assert event["exception"]["values"][0]["mechanism"]["type"] == "django"

    assert event["request"]["data"] == body
    assert event["request"]["headers"]["Content-Type"] == ct 
Example #10
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_request_body(sentry_init, client, capture_events):
    sentry_init(integrations=[DjangoIntegration()])
    events = capture_events()
    content, status, headers = client.post(
        reverse("post_echo"), data=b"heyooo", content_type="text/plain"
    )
    assert status.lower() == "200 ok"
    assert b"".join(content) == b"heyooo"

    (event,) = events

    assert event["message"] == "hi"
    assert event["request"]["data"] == ""
    assert event["_meta"]["request"]["data"][""] == {
        "len": 6,
        "rem": [["!raw", "x", 0, 6]],
    }

    del events[:]

    content, status, headers = client.post(
        reverse("post_echo"), data=b'{"hey": 42}', content_type="application/json"
    )
    assert status.lower() == "200 ok"
    assert b"".join(content) == b'{"hey": 42}'

    (event,) = events

    assert event["message"] == "hi"
    assert event["request"]["data"] == {"hey": 42}
    assert "" not in event 
Example #11
Source File: sentry.py    From donate-wagtail with Mozilla Public License 2.0 5 votes vote down vote up
def pre_setup(cls):
        super().pre_setup()

        import sentry_sdk
        from sentry_sdk.integrations.django import DjangoIntegration
        sentry_sdk.init(
            dsn=cls.SENTRY_DSN,
            integrations=[DjangoIntegration()],
            release=cls.HEROKU_RELEASE_VERSION,
            environment=cls.SENTRY_ENVIRONMENT
        ) 
Example #12
Source File: sentry.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def sentry_init(env=None):
    sentry_sdk.init(
        dsn=get_env_setting('SENTRY_DSN'),
        integrations=[DjangoIntegration()],
        environment={'PROD': "production", 'UAT': "staging"}.get(env, "development"),

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        # send_default_pii=True,
    ) 
Example #13
Source File: asgi.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def patch_django_asgi_handler_impl(cls):
    # type: (Any) -> None
    old_app = cls.__call__

    async def sentry_patched_asgi_handler(self, scope, receive, send):
        # type: (Any, Any, Any, Any) -> Any
        if Hub.current.get_integration(DjangoIntegration) is None:
            return await old_app(self, scope, receive, send)

        middleware = SentryAsgiMiddleware(
            old_app.__get__(self, cls), unsafe_context_data=True
        )._run_asgi3
        return await middleware(scope, receive, send)

    cls.__call__ = sentry_patched_asgi_handler 
Example #14
Source File: test_asgi.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_basic(sentry_init, capture_events, application, request):
    sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)

    events = capture_events()

    comm = HttpCommunicator(application, "GET", "/view-exc?test=query")
    response = await comm.get_response()
    assert response["status"] == 500

    (event,) = events

    (exception,) = event["exception"]["values"]
    assert exception["type"] == "ZeroDivisionError"

    # Test that the ASGI middleware got set up correctly. Right now this needs
    # to be installed manually (see myapp/asgi.py)
    assert event["transaction"] == "/view-exc"
    assert event["request"] == {
        "cookies": {},
        "headers": {},
        "method": "GET",
        "query_string": "test=query",
        "url": "/view-exc",
    }

    capture_message("hi")
    event = events[-1]
    assert "request" not in event 
Example #15
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_middleware_spans_disabled(sentry_init, client, capture_events):
    sentry_init(
        integrations=[DjangoIntegration(middleware_spans=False)], traces_sample_rate=1.0
    )
    events = capture_events()

    _content, status, _headers = client.get(reverse("message"))

    message, transaction = events

    assert message["message"] == "hi"

    assert not transaction["spans"] 
Example #16
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_middleware_spans(sentry_init, client, capture_events):
    sentry_init(
        integrations=[DjangoIntegration()],
        traces_sample_rate=1.0,
        _experiments={"record_sql_params": True},
    )
    events = capture_events()

    _content, status, _headers = client.get(reverse("message"))

    message, transaction = events

    assert message["message"] == "hi"

    for middleware in transaction["spans"]:
        assert middleware["op"] == "django.middleware"

    if DJANGO_VERSION >= (1, 10):
        reference_value = [
            "django.contrib.sessions.middleware.SessionMiddleware.__call__",
            "django.contrib.auth.middleware.AuthenticationMiddleware.__call__",
            "tests.integrations.django.myapp.settings.TestMiddleware.__call__",
            "tests.integrations.django.myapp.settings.TestFunctionMiddleware.__call__",
        ]
    else:
        reference_value = [
            "django.contrib.sessions.middleware.SessionMiddleware.process_request",
            "django.contrib.auth.middleware.AuthenticationMiddleware.process_request",
            "tests.integrations.django.myapp.settings.TestMiddleware.process_request",
            "tests.integrations.django.myapp.settings.TestMiddleware.process_response",
            "django.contrib.sessions.middleware.SessionMiddleware.process_response",
        ]

    assert [t["description"] for t in transaction["spans"]] == reference_value 
Example #17
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_template_exception(sentry_init, client, capture_events):
    sentry_init(integrations=[DjangoIntegration()])
    events = capture_events()

    content, status, headers = client.get(reverse("template_exc"))
    assert status.lower() == "500 internal server error"

    (event,) = events
    exception = event["exception"]["values"][-1]
    assert exception["type"] == "TemplateSyntaxError"

    frames = [
        f
        for f in exception["stacktrace"]["frames"]
        if not f["filename"].startswith("django/")
    ]
    view_frame, template_frame = frames[-2:]

    assert template_frame["context_line"] == "{% invalid template tag %}\n"
    assert template_frame["pre_context"] == ["5\n", "6\n", "7\n", "8\n", "9\n"]

    assert template_frame["post_context"] == ["11\n", "12\n", "13\n", "14\n", "15\n"]
    assert template_frame["lineno"] == 10
    assert template_frame["in_app"]
    assert template_frame["filename"].endswith("error.html")

    filenames = [
        (f.get("function"), f.get("module")) for f in exception["stacktrace"]["frames"]
    ]
    assert filenames[-3:] == [
        (u"parse", u"django.template.base"),
        (None, None),
        (u"invalid_block_tag", u"django.template.base"),
    ] 
Example #18
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_read_request(sentry_init, client, capture_events):
    sentry_init(integrations=[DjangoIntegration()])
    events = capture_events()

    content, status, headers = client.post(
        reverse("read_body_and_view_exc"),
        data=b'{"hey": 42}',
        content_type="application/json",
    )

    assert status.lower() == "500 internal server error"

    (event,) = events

    assert "data" not in event["request"] 
Example #19
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_transaction_style(
    sentry_init, client, capture_events, transaction_style, expected_transaction
):
    sentry_init(
        integrations=[DjangoIntegration(transaction_style=transaction_style)],
        send_default_pii=True,
    )
    events = capture_events()
    content, status, headers = client.get(reverse("message"))
    assert b"".join(content) == b"ok"

    (event,) = events
    assert event["transaction"] == expected_transaction 
Example #20
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_sql_dict_query_params(sentry_init, capture_events):
    sentry_init(
        integrations=[DjangoIntegration()],
        send_default_pii=True,
        _experiments={"record_sql_params": True},
    )

    from django.db import connections

    if "postgres" not in connections:
        pytest.skip("postgres tests disabled")

    sql = connections["postgres"].cursor()

    events = capture_events()
    with pytest.raises(ProgrammingError):
        sql.execute(
            """SELECT count(*) FROM people_person WHERE foo = %(my_foo)s""",
            {"my_foo": 10},
        )

    capture_message("HI")
    (event,) = events

    crumb = event["breadcrumbs"][-1]
    assert crumb["message"] == (
        "SELECT count(*) FROM people_person WHERE foo = %(my_foo)s"
    )
    assert crumb["data"]["db.params"] == {"my_foo": 10} 
Example #21
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_sql_queries(sentry_init, capture_events, with_integration):
    sentry_init(
        integrations=[DjangoIntegration()] if with_integration else [],
        send_default_pii=True,
        _experiments={"record_sql_params": True},
    )

    from django.db import connection

    sentry_init(
        integrations=[DjangoIntegration()],
        send_default_pii=True,
        _experiments={"record_sql_params": True},
    )

    events = capture_events()

    sql = connection.cursor()

    with pytest.raises(OperationalError):
        # table doesn't even exist
        sql.execute("""SELECT count(*) FROM people_person WHERE foo = %s""", [123])

    capture_message("HI")

    (event,) = events

    if with_integration:
        crumb = event["breadcrumbs"][-1]

        assert crumb["message"] == "SELECT count(*) FROM people_person WHERE foo = %s"
        assert crumb["data"]["db.params"] == [123] 
Example #22
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_500(sentry_init, client, capture_events):
    sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
    events = capture_events()

    content, status, headers = client.get("/view-exc")
    assert status.lower() == "500 internal server error"
    content = b"".join(content).decode("utf-8")

    (event,) = events
    event_id = event["event_id"]
    assert content == "Sentry error: %s" % event_id 
Example #23
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_transaction_with_class_view(sentry_init, client, capture_events):
    sentry_init(
        integrations=[DjangoIntegration(transaction_style="function_name")],
        send_default_pii=True,
    )
    events = capture_events()
    content, status, headers = client.head(reverse("classbased"))
    assert status.lower() == "200 ok"

    (event,) = events

    assert (
        event["transaction"] == "tests.integrations.django.myapp.views.ClassBasedView"
    )
    assert event["message"] == "hi" 
Example #24
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_middleware_exceptions(sentry_init, client, capture_exceptions):
    sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
    exceptions = capture_exceptions()
    client.get(reverse("middleware_exc"))

    (error,) = exceptions
    assert isinstance(error, ZeroDivisionError) 
Example #25
Source File: test_basic.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_view_exceptions(sentry_init, client, capture_exceptions, capture_events):
    sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
    exceptions = capture_exceptions()
    events = capture_events()
    client.get(reverse("view_exc"))

    (error,) = exceptions
    assert isinstance(error, ZeroDivisionError)

    (event,) = events
    assert event["exception"]["values"][0]["mechanism"]["type"] == "django"