You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Sentry进行单元测试?忽略异常测试的实现方案

使用Sentry进行单元测试及忽略异常测试方案

一、Sentry单元测试的基础实现

Sentry官方SDK自带测试工具,能让你在单元测试里验证异常是否被正确捕获,完全不需要依赖真实的Sentry服务实例:

  • 捕获异常事件:借助sentry_sdk.testing里的capture_events上下文管理器,它会拦截所有Sentry事件,方便你断言事件的数量和属性。
    以Python为例,代码示例如下:
    from sentry_sdk import capture_exception, init
    from sentry_sdk.testing import capture_events
    
    def test_sentry_captures_exception():
        # 使用测试专用DSN,无需连接真实服务
        init(dsn="https://examplePublicKey@o0.ingest.sentry.io/0")
        events = capture_events()
        
        try:
            raise ValueError("Test exception")
        except ValueError as e:
            capture_exception(e)
        
        # 断言事件被正确捕获
        assert len(events) == 1
        assert events[0]["exception"]["values"][0]["type"] == "ValueError"
    
  • 验证事件细节:除了异常类型,你还可以断言事件的级别、自定义标签、用户信息等,确保Sentry集成逻辑完全符合预期。

二、测试Sentry忽略的异常(无需连接真实实例)

不管有没有连接Sentry实例,都能通过测试SDK的过滤逻辑,验证被忽略的异常不会被发送:

  • 测试内置忽略规则:如果配置了ignore_errors参数,触发被忽略的异常后,验证没有事件被捕获。
    示例代码:
    from sentry_sdk import init, capture_exception
    from sentry_sdk.testing import capture_events
    
    def test_ignored_exception_not_captured():
        init(
            dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
            ignore_errors=[ValueError]
        )
        events = capture_events()
        
        try:
            raise ValueError("Ignored exception")
        except ValueError as e:
            capture_exception(e)
        
        # 被忽略的异常不会生成事件
        assert len(events) == 0
    
  • 测试自定义过滤逻辑:如果用before_send钩子自定义了过滤规则,既可以直接测试该钩子的返回值,也可以结合capture_events验证事件被过滤。
    示例代码:
    def custom_before_send(event, hint):
        # 忽略TypeError类型的异常
        if event["exception"]["values"][0]["type"] == "TypeError":
            return None
        return event
    
    def test_custom_filter_ignores_exception():
        init(
            dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
            before_send=custom_before_send
        )
        events = capture_events()
        
        try:
            raise TypeError("Custom ignored exception")
        except TypeError as e:
            capture_exception(e)
        
        assert len(events) == 0
    
  • 离线测试技巧:测试时用测试专用DSN(如示例中的),或者干脆不配置DSN,SDK会进入离线模式,依然能捕获事件供你断言,不会尝试发送请求到真实Sentry服务器,完全不依赖网络。

内容的提问来源于stack exchange,提问作者muhammed ozbilici

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 17:35:14