Skip to content

Commit

Permalink
package fake: add exit.go
Browse files Browse the repository at this point in the history
  • Loading branch information
q191201771 committed Dec 3, 2019
1 parent 2e7252f commit a78344e
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pkg/ ...... 源码包
|-- ratelimit/ ...... 限流器,令牌桶
|-- ic/ ...... 将整型切片压缩成二进制字节切片
|-- unique/ ...... 对象唯一 ID
|-- fake/ ...... 实现一些常用的接口,辅助测试其它代码
|-- fake/ ...... stub和mock相关,实现一些常用的接口,辅助测试其它代码
demo/ ...... 示例相关的代码
bin/ ...... 可执行文件编译输出目录
```
Expand Down
48 changes: 48 additions & 0 deletions pkg/fake/exit.go
Original file line number Diff line number Diff line change
@@ -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 ([email protected])

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
}
35 changes: 35 additions & 0 deletions pkg/fake/exit_test.go
Original file line number Diff line number Diff line change
@@ -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 ([email protected])

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)
}

0 comments on commit a78344e

Please sign in to comment.