mv captureStdout as public func

Signed-off-by: yxxhero <aiopsclub@163.com>
This commit is contained in:
yxxhero
2022-04-03 22:24:38 +08:00
parent 01b5b79a01
commit e0244bc341
4 changed files with 89 additions and 37 deletions
+40
View File
@@ -0,0 +1,40 @@
package testutil
import (
"bytes"
"io"
"log"
"os"
"sync"
)
// CaptureStdout is a helper function to capture stdout.
func CaptureStdout(f func()) string {
reader, writer, err := os.Pipe()
if err != nil {
panic(err)
}
stdout := os.Stdout
defer func() {
os.Stdout = stdout
log.SetOutput(os.Stderr)
}()
os.Stdout = writer
log.SetOutput(writer)
out := make(chan string)
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
var buf bytes.Buffer
wg.Done()
_, err = io.Copy(&buf, reader)
if err != nil {
panic(err)
}
out <- buf.String()
}()
wg.Wait()
f()
writer.Close()
return <-out
}
+40
View File
@@ -0,0 +1,40 @@
package testutil
import (
"fmt"
"testing"
)
// TestCaptureStdout tests the CaptureStdout function.
func TestCaptureStdout(t *testing.T) {
tests := []struct {
output string
expected string
}{
{
output: "123",
expected: "123",
},
{
output: "test",
expected: "test",
},
{
output: "",
expected: "",
},
{
output: "...",
expected: "...",
},
}
for _, test := range tests {
result := CaptureStdout(func() {
fmt.Print(test.output)
})
if result != test.expected {
t.Errorf("CaptureStdout() = %v, want %v", result, test.expected)
}
}
}