首页 > 其他 > 详细

golang subprocess tests

时间:2018-05-18 23:54:54      阅读:254      评论:0      收藏:0      [点我收藏+]

golang Subprocess tests

Sometimes you need to test the behavior of a process, not just a function.

func Crasher() {
    fmt.Println("Going down in flames!")
    os.Exit(1)
}

To test this code, we invoke the test binary itself as a subprocess:

func TestCrasher(t *testing.T) {
    if os.Getenv("BE_CRASHER") == "1" {
        Crasher()
        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() {
        return
    }
    t.Fatalf("process ran with err %v, want exit status 1", err)
}

核心技巧在于os.args[0]可以获取到真实的可执行 test 程序,从而改变环境变量.

golang subprocess tests

原文:https://www.cnblogs.com/baizx/p/9058372.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!