douyun7718 2016-12-20 16:41
浏览 64
已采纳

如何使用Go日志记录包glog测试代码?

I have implemented a type wrapping glog so that I can add a prefix to log message identifying the emitter of the log in my program and I can change the log level per emitter.

How could I implement the unit tests ? The problem is that glog outputs text to stdErr.

The code is trivial but I would like the have the unit test and 100% coverage like the rest of the code. This programming effort already payed.

  • 写回答

2条回答 默认 最新

  • doufu6196 2016-12-24 04:09
    关注

    Test which captures stderr:

    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)
        }
    }
    

    running test:

    go test -v
    === RUN   TestGlogError
    --- PASS: TestGlogError (0.00s)
    PASS
    ok      command-line-arguments  0.007s
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)