From a78344ec9424c9fdcf18b543cb8a492cca12996b Mon Sep 17 00:00:00 2001 From: q191201771 <191201771@qq.com> Date: Tue, 3 Dec 2019 17:44:12 +0800 Subject: [PATCH] package fake: add exit.go --- README.md | 2 +- pkg/fake/exit.go | 48 +++++++++++++++++++++++++++++++++++++++++++ pkg/fake/exit_test.go | 35 +++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 pkg/fake/exit.go create mode 100644 pkg/fake/exit_test.go diff --git a/README.md b/README.md index ffd1225..86c7b58 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ pkg/ ...... 源码包 |-- ratelimit/ ...... 限流器,令牌桶 |-- ic/ ...... 将整型切片压缩成二进制字节切片 |-- unique/ ...... 对象唯一 ID - |-- fake/ ...... 实现一些常用的接口,辅助测试其它代码 + |-- fake/ ...... stub和mock相关,实现一些常用的接口,辅助测试其它代码 demo/ ...... 示例相关的代码 bin/ ...... 可执行文件编译输出目录 ``` diff --git a/pkg/fake/exit.go b/pkg/fake/exit.go new file mode 100644 index 0000000..19673e8 --- /dev/null +++ b/pkg/fake/exit.go @@ -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 +} diff --git a/pkg/fake/exit_test.go b/pkg/fake/exit_test.go new file mode 100644 index 0000000..e1ca23e --- /dev/null +++ b/pkg/fake/exit_test.go @@ -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) +}