-
Notifications
You must be signed in to change notification settings - Fork 4
/
capture03.go
80 lines (70 loc) · 1.77 KB
/
capture03.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Padesátá druhá část
// Pomůcky při tvorbě jednotkových testů v jazyce Go
// https://www.root.cz/clanky/pomucky-pri-tvorbe-jednotkovych-testu-v-jazyce-go/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z padesáté druhé části:
// https://github.com/tisnik/go-root/blob/master/article_52/README.md
package main
import (
"bytes"
"fmt"
"io"
"math"
"os"
"sync"
)
func CaptureStandardOutput(function func()) (string, error) {
// backup of the real stdout
stdout := os.Stdout
// temporary replacement for stdout
reader, writer, err := os.Pipe()
if err != nil {
return "", err
}
// temporarily replace real Stdout by the mocked one
defer func() {
os.Stdout = stdout
}()
os.Stdout = writer
// channel with captured standard output
captured := make(chan string)
// synchronization object
wg := new(sync.WaitGroup)
// we are going to wait for one goroutine only
wg.Add(1)
go func() {
var buf bytes.Buffer
// goroutine is started -> inform main one via WaitGroup object
wg.Done()
io.Copy(&buf, reader)
captured <- buf.String()
}()
// wait for goroutine to start
wg.Wait()
// provided function that (probably) prints something to standard output
function()
writer.Close()
return <-captured, nil
}
func printSinus() {
epsilon := 1e-6
for x := 0.0; x <= 2.0*math.Pi+epsilon; x += math.Pi / 6.0 {
fmt.Printf("sin(%5.2f) = %+5.3f\n", x, math.Sin(x))
}
}
func main() {
str, err := CaptureStandardOutput(printSinus)
if err != nil {
panic(err)
}
fmt.Println("Captured output:")
fmt.Println("-------------------------------")
fmt.Println(str)
fmt.Println("-------------------------------")
}