使用覆盖率信息测试Go中的os.Exit场景(coveralls.io/Goveralls)

abl*_*igh 13 architecture testing unit-testing go coveralls

这个问题:如何测试Go中的os.exit场景(以及其中最高的投票答案),阐述了如何os.Exit()在go中测试场景.由于os.Exit()不能轻易拦截,使用的方法是重新调用二进制文件并检查退出值.这个方法在Andrew Gerrand(Go团队的核心成员之一)的演示文稿第23页中描述; 代码非常简单,下面将全文转载.

相关的测试和主文件看起来像这样(请注意,这对文件本身就是一个MVCE):

package foo

import (
    "os"
    "os/exec"
    "testing"
)

func TestCrasher(t *testing.T) {
    if os.Getenv("BE_CRASHER") == "1" {
        Crasher() // This causes os.Exit(1) to be called
        return
    }
    cmd := exec.Command(os.Args[0], "-test.run=TestCrasher")
    cmd.Env = append(os.Environ(), "BE_CRASHER=1")
    err := cmd.Run()
    if e, ok := err.(*exec.ExitError); ok && !e.Success() {
        fmt.Printf("Error is %v\n", e)
    return
    }
    t.Fatalf("process ran with err %v, want exit status 1", err)
}
Run Code Online (Sandbox Code Playgroud)

package foo

import (
    "fmt"
    "os"
)

// Coverage testing thinks (incorrectly) that the func below is
// never being called
func Crasher() {
    fmt.Println("Going down in flames!")
    os.Exit(1)
}
Run Code Online (Sandbox Code Playgroud)

但是,这种方法似乎受到某些限制:

  1. 使用goveralls/coveralls.io进行覆盖测试不起作用 - 例如参见此处的示例(与上面相同的代码,但为方便起见放入github),这里生成覆盖测试,即它不记录正在运行的测试函数.请注意,您不需要这些链接来回答问题 - 上面的示例将正常工作 - 它们只是用于显示如果将上述内容放入github会发生什么,并将其一直带到travis到coveralls.io

  2. 重新运行测试二进制文件似乎很脆弱.

具体来说,根据要求,这里是覆盖失败的屏幕截图(而不是链接); 红色阴影表示就coveralls.io而言,Crasher()没有被调用.

覆盖测试显示Crasher()未被调用

有没有解决的办法?特别是第一点.

在golang级别,问题是这样的:

  • Goveralls框架运行go test -cover ...,调用上面的测试.

  • 上面的测试exec.Command / .Run没有-cover在OS参数中调用

  • 无条件地将-cover等等放入参数列表中是没有吸引力的,因为它将在非覆盖测试中运行覆盖测试(作为子进程),并且解析参数列表中存在-cover等等似乎是一个重要的解决方案.

  • 即使我把-cover等等放在参数列表中,我的理解是我将两个覆盖输出写入同一个文件,这不会起作用 - 这些需要以某种方式合并.我最接近的就是这个golang问题.


摘要

我所追求的是一种简单的方法来进行覆盖测试(最好是通过travis,goveralls和coveralls.io),其中可以测试测试例程退出的情况OS.exit(),以及注意到该测试的覆盖范围的地方.我非常喜欢使用上面的re-exec方法(如果可以使用),如果可以使用的话.

该解决方案应显示覆盖率测试Crasher().Crasher()从覆盖测试中排除不是一种选择,因为在现实世界中我要做的是测试一个更复杂的功能,在某些深处,在某些条件下,它调用例如log.Fatalf(); 我的覆盖测试是那些条件的测试正常.

icz*_*cza 14

通过轻微的重构,您可以轻松实现100%的覆盖率.

foo/bar.go:

package foo

import (
    "fmt"
    "os"
)

var osExit = os.Exit

func Crasher() {
    fmt.Println("Going down in flames!")
    osExit(1)
}
Run Code Online (Sandbox Code Playgroud)

和测试代码foo/bar_test.go:

package foo

import "testing"

func TestCrasher(t *testing.T) {
    // Save current function and restore at the end:
    oldOsExit := osExit
    defer func() { osExit = oldOsExit }()

    var got int
    myExit := func(code int) {
        got = code
    }

    osExit = myExit
    Crasher()
    if exp := 1; got != exp {
        t.Errorf("Expected exit code: %d, got: %d", exp, got)
    }
}
Run Code Online (Sandbox Code Playgroud)

跑步go test -cover:

Going down in flames!
PASS
coverage: 100.0% of statements
ok      foo        0.002s
Run Code Online (Sandbox Code Playgroud)

是的,您可能会说如果os.Exit()明确调用它会起作用,但如果os.Exit()被其他人调用,例如log.Fatalf()

同样的技术也在那里工作,你只需要切换log.Fatalf()而不是os.Exit(),例如:

相关部分foo/bar.go:

var logFatalf = log.Fatalf

func Crasher() {
    fmt.Println("Going down in flames!")
    logFatalf("Exiting with code: %d", 1)
}
Run Code Online (Sandbox Code Playgroud)

和测试代码:TestCrasher()foo/bar_test.go:

func TestCrasher(t *testing.T) {
    // Save current function and restore at the end:
    oldLogFatalf := logFatalf
    defer func() { logFatalf = oldLogFatalf }()

    var gotFormat string
    var gotV []interface{}
    myFatalf := func(format string, v ...interface{}) {
        gotFormat, gotV = format, v
    }

    logFatalf = myFatalf
    Crasher()
    expFormat, expV := "Exiting with code: %d", []interface{}{1}
    if gotFormat != expFormat || !reflect.DeepEqual(gotV, expV) {
        t.Error("Something went wrong")
    }
}
Run Code Online (Sandbox Code Playgroud)

跑步go test -cover:

Going down in flames!
PASS
coverage: 100.0% of statements
ok      foo     0.002s
Run Code Online (Sandbox Code Playgroud)

  • @abligh可以通过在`logFatal()`之后添加`return`语句来"解决",即使通常它不需要(仅用于使代码可测试). (3认同)

I15*_*159 5

接口和模拟

使用Go接口可以创建可模拟的合成.类型可以将接口作为绑定依赖项.这些依赖关系可以很容易地用适合于接口的模拟代替.

type Exiter interface {
    Exit(int)
}

type osExit struct {}

func (o* osExit) Exit (code int) {
    os.Exit(code)
}

type Crasher struct {
    Exiter
}

func (c *Crasher) Crash() {
    fmt.Println("Going down in flames!")
    c.Exit(1)
}
Run Code Online (Sandbox Code Playgroud)

测试

type MockOsExit struct {
    ExitCode int
}

func (m *MockOsExit) Exit(code int){
    m.ExitCode = code
}

func TestCrasher(t *testing.T) {
    crasher := &Crasher{&MockOsExit{}}
    crasher.Crash() // This causes os.Exit(1) to be called
    f := crasher.Exiter.(*MockOsExit)
    if f.ExitCode == 1 {
        fmt.Printf("Error code is %d\n", f.ExitCode)
        return
    }
    t.Fatalf("Process ran with err code %d, want exit status 1", f.ExitCode)
}
Run Code Online (Sandbox Code Playgroud)

缺点

原始Exit方法仍然不会被测试所以它应该只负责退出,仅此而已.

职能是一等公民

参数依赖

功能是Go的一等公民.函数允许很多操作,所以我们可以直接用函数做一些技巧.

使用'pass as parameter'操作,我们可以执行依赖注入:

type osExit func(code int)

func Crasher(os_exit osExit) {
    fmt.Println("Going down in flames!")
    os_exit(1)
}
Run Code Online (Sandbox Code Playgroud)

测试:

var exit_code int 
func os_exit_mock(code int) {
     exit_code = code
}

func TestCrasher(t *testing.T) {

    Crasher(os_exit_mock) // This causes os.Exit(1) to be called
    if exit_code == 1 {
        fmt.Printf("Error code is %d\n", exit_code)
        return
    }
    t.Fatalf("Process ran with err code %v, want exit status 1", exit_code)
}
Run Code Online (Sandbox Code Playgroud)

缺点

您必须将依赖项作为参数传递.如果你有很多依赖项,那么params列表的长度可能很大.

变量替换

实际上,可以使用"赋值给变量"操作,而无需将函数显式传递为参数.

var osExit = os.Exit

func Crasher() {
    fmt.Println("Going down in flames!")
    osExit(1)
}
Run Code Online (Sandbox Code Playgroud)

测试

var exit_code int
func osExitMock(code int) {
    exit_code = code
}

func TestCrasher(t *testing.T) {
    origOsExit := osExit
    osExit = osExitMock
    // Don't forget to switch functions back!
    defer func() { osExit = origOsExit }()

    Crasher()
    if exit_code != 1 {
        t.Fatalf("Process ran with err code %v, want exit status 1", exit_code)
    }
}
Run Code Online (Sandbox Code Playgroud)

缺点

它隐含且容易崩溃.

设计说明

如果你打算在下面声明一些逻辑Exit,退出逻辑必须在退出后用elseblock或extra 隔离,return因为mock不会停止执行.

func (c *Crasher) Crash() {
    if SomeCondition == true {
        fmt.Println("Going down in flames!")
        c.Exit(1)  // Exit in real situation, invoke mock when testing
    } else {
        DoSomeOtherStuff()
    }

}
Run Code Online (Sandbox Code Playgroud)