登录
首页 >  Golang >  Go问答

Golang中Gauge值的Prometheus单元测试

来源:stackoverflow

时间:2024-04-24 08:18:34 116浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《Golang中Gauge值的Prometheus单元测试》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我有一个函数可以计算一个值,然后使用 prometheus 仪表变量将其保存(或至少准备好被抓取)在 prometheus 中。所以设置如下:

// prometheus variable: enclosure ambient temperature.
    errorlog = prometheus.newgauge(prometheus.gaugeopts{
        name: "encoded_messages",
        help: "encoded system info/warning/error messages",
    })

在我的函数中,该值最终保存到数据库中,如下所示:

errorLog.Set(float64(123)) // Capture message to database

为了清楚起见,我已将(计算出的)变量替换为 123。在计算我的值时,(理论上)应该很容易验证保存到数据库(或至少准备好抓取)的值是否为事实上 123。

主要功能没有问题,但是现在我想编写一个单元测试来测试所述功能。我有许多其他(未经测试的)功能已经在工作,并且数据已成功抓取,但我也需要为这些功能创建单元测试。

在单元测试期间,我不希望将任何虚假数据保存到数据库中,因此确实需要有一种模拟 html 抓取页面的方法,对吗?

我查看了一些选项,例如这里提到的: 使用golang prometheus testutil进行单元测试

我还阅读了此处为 prometheus 提供的实用程序: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/testutil?utm_source=godoc#collectandcompare 不幸的是没有给出例子。我想也许“collectandcompare”就是我所需要的,但我一直无法让它工作。

干杯!


正确答案


您需要作为 reader 传递文本输出(与您在 /metrics 端点获得的相同)

这是我对从数据库中提取的一些数据的测试

func TestCollect(t *testing.T) {

// setup dummy test data
    fetchFromDB = func() (ok bool, voltage float64, temp float64, power float64, frequency float64, etoday float64) {
        return true, 123.1, 99.0, 567.8, 55.5, 789.0
    }
    collector := newCollector()
    ch := make(chan prometheus.Metric)
    go collector.Collect(ch)

    expected := strings.NewReader(
        `# HELP voltage voltage
# TYPE voltage gauge
voltage 123.1
# HELP EToday Total Power today Wh
# TYPE EToday gauge
EToday 789.0
# HELP Frequency AC Frequency
# TYPE Frequency gauge
Frequency 55.5
# HELP Power power
# TYPE Power gauge
Power 567.8
# HELP Temperature temp
# TYPE Temperature gauge
Temperature 99.0
`)
    err := testutil.CollectAndCompare(collector, expected, "voltage", "EToday", "Frequency", "Temperature", "Power")
    if err != nil {
        t.Errorf("%s", err.Error())
    }

}

源代码中有一些很好的测试示例

https://github.com/prometheus/client_golang/blob/v1.14.0/prometheus/testutil/testutil_test.go#L125

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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