【发布时间】:2018-06-03 19:47:45
【问题描述】:
我使用thisstatsd package 将指标发送到我们的statsd server。为了初始化客户端,我在我的 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 client?
【问题讨论】:
标签: go interface mocking statsd