mirror of
https://github.com/helmfile/helmfile.git
synced 2026-10-17 21:56:08 +02:00
mv captureStdout as public func
Signed-off-by: yxxhero <aiopsclub@163.com>
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user