package fake: add exit.go

pull/2/head
q191201771 5 years ago
parent 2e7252fae2
commit a78344ec94

@ -45,7 +45,7 @@ pkg/ ...... 源码包
|-- ratelimit/ ...... 限流器,令牌桶
|-- ic/ ...... 将整型切片压缩成二进制字节切片
|-- unique/ ...... 对象唯一 ID
|-- fake/ ...... 实现一些常用的接口,辅助测试其它代码
|-- fake/ ...... stub和mock相关实现一些常用的接口,辅助测试其它代码
demo/ ...... 示例相关的代码
bin/ ...... 可执行文件编译输出目录
```

@ -0,0 +1,48 @@
// Copyright 2019, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package fake
import "os"
var (
exit = os.Exit
)
type ExitResult struct {
HasExit bool
ExitCode int
}
var exitResult ExitResult
// 正常情况下,调用 os.Exit单元测试时可配置为不调用 os.Exit
func Exit(code int) {
exit(code)
}
func WithFakeExit(fn func()) ExitResult {
startFakeExit()
fn()
stopFakeExit()
return exitResult
}
func startFakeExit() {
exitResult.HasExit = false
exitResult.ExitCode = 0
exit = func(code int) {
exitResult.HasExit = true
exitResult.ExitCode = code
}
}
func stopFakeExit() {
exit = os.Exit
}

@ -0,0 +1,35 @@
// Copyright 2019, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package fake_test
import (
"testing"
"github.com/q191201771/naza/pkg/assert"
"github.com/q191201771/naza/pkg/fake"
)
func TestWithFakeExit(t *testing.T) {
var er fake.ExitResult
er = fake.WithFakeExit(func() {
fake.Exit(1)
})
assert.Equal(t, true, er.HasExit)
assert.Equal(t, 1, er.ExitCode)
er = fake.WithFakeExit(func() {
})
assert.Equal(t, false, er.HasExit)
er = fake.WithFakeExit(func() {
fake.Exit(2)
})
assert.Equal(t, true, er.HasExit)
assert.Equal(t, 2, er.ExitCode)
}
Loading…
Cancel
Save