【问题标题】:How to test code using the Go logging package glog ?如何使用 Go 日志包 glog 测试代码?
【发布时间】:2016-12-20 16:41:24
【问题描述】:

我已经实现了一个类型包装 glog,以便我可以在日志消息中添加一个前缀来标识我的程序中日志的发射器,并且我可以更改每个发射器的日志级别。

如何实施单元测试?问题是 glog 将文本输出到 stdErr。

代码很简单,但我希望像其他代码一样进行单元测试和 100% 的覆盖率。这种编程工作已经付出了代价。

【问题讨论】:

  • glog 输出(如果您指的是github.com/golang/glog)是可配置的。你能输出到文件而不是标准错误吗?
  • 您可以在测试中捕获 stderr,就像在 answer 中捕获的 stdout 一样
  • @JimB 可以。但是,很难测试每次调用我的包装方法所输出的内容。
  • @Maxim Yefremov 的建议正是我想要的。它看起来很棒。请写下答案,以便我为您分配答案。

标签: unit-testing go


【解决方案1】:

捕获标准错误的测试:

package main

import (
    "bytes"
    "io"
    "os"
    "testing"

    "github.com/golang/glog"
    "strings"
)

func captureStderr(f func()) (string, error) {
    old := os.Stderr // keep backup of the real stderr
    r, w, err := os.Pipe()
    if err != nil {
        return "", err
    }
    os.Stderr = w

    outC := make(chan string)
    // copy the output in a separate goroutine so printing can't block indefinitely
    go func() {
        var buf bytes.Buffer
        io.Copy(&buf, r)
        outC <- buf.String()
    }()

    // calling function which stderr we are going to capture:
    f()

    // back to normal state
    w.Close()
    os.Stderr = old // restoring the real stderr
    return <-outC, nil
}

func TestGlogError(t *testing.T) {
    stdErr, err := captureStderr(func() {
        glog.Error("Test error")
    })
    if err != nil {
        t.Errorf("should not be error, instead: %+v", err)
    }
    if !strings.HasSuffix(strings.TrimSpace(stdErr), "Test error") {
        t.Errorf("stderr should end by 'Test error' but it doesn't: %s", stdErr)
    }
}

运行测试:

go test -v
=== RUN   TestGlogError
--- PASS: TestGlogError (0.00s)
PASS
ok      command-line-arguments  0.007s

【讨论】:

    【解决方案2】:

    编写一个描述您的使用情况的界面。如果您使用 V 方法,这将不是很漂亮,但是您有一个包装器,因此您已经完成了修复它所需的艰苦工作。

    对于每个需要测试的包,定义

    type Logger interface {
        Infoln(...interface{}) // the methods you actually use in this package
    }
    

    然后您可以通过不在代码中直接引用 glog 类型轻松地将其替换掉。

    【讨论】:

    • 我已经这样做了。这将允许测试我的包装器的使用。完美的建议。问题是如何测试包装器本身。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2017-12-15
    • 2020-02-21
    • 2014-06-05
    • 1970-01-01
    • 2018-02-22
    相关资源
    最近更新 更多