登录
首页 >  Golang >  Go问答

Logrus 错误应该导致代码断言发生恐慌

来源:stackoverflow

时间:2024-02-07 11:09:23 167浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《Logrus 错误应该导致代码断言发生恐慌》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

使用 logrus 时,如何使用 testify 等断言库来断言恐慌?

以下代码为例:

var mylogger = logrus.withcontext("mylogger")

func loadpreparedstatements() {
    db := psql.psqlclient()
    var err error

    mypreparedstatement, err = db.prepare("select * from mytable")
    if err != nil {
        mylogger.panic("loading sql prepared statement failed")
    }
}

当用 testify 编写测试时,我只能捕获以下错误:

panicswitherror(t, "test", func() {
        loadpreparedstatements()
    })
Panic value:    &logrus.Entry{Logger:(*logrus.Logger)(0xc0000ba000), Data:logrus.Fields{"context":"MyLogger"}, Time:time.Date(2022, time.November, 1, 21, 49, 27, 889501622, time.Local), Level:0x0, Caller:(*runtime.Frame)(nil), Message:"Loading SQL Prepared Statement Failed", Buffer:(*bytes.Buffer)(nil), Context:context.Context(nil), err:""}

有没有办法测试返回的消息?


正确答案


除了编写自己的测试之外,我找不到任何方法可以做到这一点。我使用以下代码来实现测试 logrus 响应的断言。如果引发的错误不是来自 logrus,它可能会出现问题,但它允许我编写我想要的断言。

type thelper interface {
    helper()
}

// didpanic returns true if the function passed to it panics. otherwise, it returns false.
func didpanic(f assert.panictestfunc) (didpanic bool, message interface{}, stack string) {
    didpanic = true

    defer func() {
        message = recover()
        if didpanic {
            stack = string(debug.stack())
        }
    }()

    // call the target function
    f()
    didpanic = false

    return
}
func panicswithlogruserror(t assert.testingt, errstring string, f assert.panictestfunc, msgandargs ...interface{}) bool {
    if h, ok := t.(thelper); ok {
        h.helper()
    }

    funcdidpanic, panicvalue, panickedstack := didpanic(f)
    if !funcdidpanic {
        return assert.fail(t, fmt.sprintf("func %#v should panic\n\tpanic value:\t%#v", f, panicvalue), msgandargs...)
    }
    panicerr, ok := panicvalue.(*logrus.entry)

    if !ok || panicerr.message != errstring {
        return assert.fail(t, fmt.sprintf("func %#v should panic with logrus error message:\t%#v\n\tpanic value:\t%#v\n\tpanic stack:\t%s", f, errstring, panicerr.message, panickedstack), msgandargs...)
    }

    return true
}
PanicsWithLogrusError(t, "Loading SQL Prepared Statement Failed", func() {
        LoadPreparedStatements()
    })

以上使测试通过。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>