golang subprocess tests

简介: golang Subprocess testsSometimes you need to test the behavior of a process, not just a function.func Crasher() { fmt.

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 程序,从而改变环境变量.

目录
相关文章
|
1月前
|
Go
golang中make 和 new 的区别
golang中make 和 new 的区别
20 0
|
4月前
|
Go
【golang】Compile 和 MustCompile
【golang】Compile 和 MustCompile
50 0
|
8月前
|
Go 开发工具 C语言
Golang框架:cobra
这些都是命令,二前面的ls、git、gcc等都是我们写的程序。如果不使用 cobra 框架进行编写这些命令,那么程序写起来是相当费劲的。
66 0
|
10月前
|
Go
golang中time的使用
golang中time的使用
|
11月前
|
NoSQL 关系型数据库 MySQL
学习golang(9) 初探:go path与go mod
学习golang(9) 初探:go path与go mod
150 1
golang go get 时提示 no Go files in xxx
golang go get 时提示 no Go files in xxx
golang go get 时提示 no Go files in xxx
|
IDE Go 开发工具
让你的Golang项目在IDE里跑起来(Goland使用入门-GOROOT、GOPATH、src、 pkg、bin、import)
让你的Golang项目在IDE里跑起来(Goland使用入门-GOROOT、GOPATH、src、 pkg、bin、import)
让你的Golang项目在IDE里跑起来(Goland使用入门-GOROOT、GOPATH、src、 pkg、bin、import)
|
Java Linux Go
知识分享之Golang——go mod常用命令解析
知识分享之Golang篇是我在日常使用Golang时学习到的各种各样的知识的记录,将其整理出来以文章的形式分享给大家,来进行共同学习。欢迎大家进行持续关注。 知识分享系列目前包含Java、Golang、Linux、Docker等等。
146 0
知识分享之Golang——go mod常用命令解析
|
JSON 缓存 Go
Go-常用命令go的使用(build、env、run、fmt等)
Go-常用命令go的使用(build、env、run、fmt等)
335 0
Go-常用命令go的使用(build、env、run、fmt等)
golang日常开发系列之一--defer的那些坑"
golang日常开发系列之一--defer的那些坑"
118 0