码迷,mamicode.com
首页 > 其他好文 > 详细

golang subprocess tests

时间:2018-05-19 00:15:12      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:this   tin   改变   cmd   comm   技巧   bin   end   ola   

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

标签:this   tin   改变   cmd   comm   技巧   bin   end   ola   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!