gpt4 book ai didi

go - 在 Go 测试包中模拟 statsd 客户端

转载 作者:数据小太阳 更新时间:2023-10-29 03:12:25 26 4
gpt4 key购买 nike

我使用 this statsd package 将指标发送到我们的 statsd 服务器。为了初始化客户端,我在我的 main 中调用了一个 metrics.Setup() 来执行初始化。这个包看起来像这样:

包:

package metrics

import (
"fmt"

"github.com/cactus/go-statsd-client/statsd"
)

// Client can be used to send stats to
var Client StatsdAccess

// Setup initialises metrics gathering
func Setup() {
if Client == nil {
prefix := fmt.Sprintf("app.%s", logging.GetHost())
std, err := statsd.NewBufferedClient(fmt.Sprintf("localhost:1234", prefix, 0, 0)
if err != nil {
logrus.Errorf("unable to dial the statsd host: %q", err)
return
}
Client = std
}
}

// StatsdAccess is used as interface to statsd functions
type StatsdAccess interface {
Inc(stat string, value int64, rate float32) error
Gauge(stat string, value int64, rate float32) error
Timing(stat string, delta int64, rate float32) error
}

从这一刻起,另一个包通过这个全局客户端发送指标:metrics.Client.Inc("some.counter", 1, 1.0)。这工作正常,但现在我的测试文件有问题。当包实际使用 metrics package 发送指标时,它们现在会失败。这很明显,因为指标包尚未初始化等。所以我的问题 - 我认为 - 是:如何在我的测试文件中模拟 statsd 客户端

最佳答案

我从事的许多项目都使用 statsd,并且在将调用保留在测试中(因为它们非常轻量级)和编程到度量接口(interface)之间摇摇欲坠(正如您已经完成的 StasdAccess ).

由于接口(interface)已经初始化,你应该能够使用接口(interface)来打破代码中的配置依赖,并提供一个test implementation。在你的测试中使用:

package_metrics/
testing.go

// testing.go

type StubStatsd struct {}
func (s StubStatsd) Inc(stat string, value int64, rate float32) error {
return nil
}
func (s StubStatsd) Gauge(...
func (s StubStatsd) Timing(...

现在,当您的测试想要调用方法或初始化需要 StatsdAccess 参数的组件时,它可以使用测试 stub 来满足要求

func TestSomething_NeedsStatsd(t *testing.T) {
statsdStub := StubStatsd{}
someMethodThatRequiresStatsd(stasdStub)
}

关于go - 在 Go 测试包中模拟 statsd 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47919776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com