generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
70 lines (58 loc) · 1.24 KB
/
main_test.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
package main
import (
"io/ioutil"
"os"
"testing"
"time"
"bou.ke/monkey"
"github.com/beevik/ntp"
)
// go test -gcflags=-l
func TestHelloNow(t *testing.T) {
t.Run("test normal behavior", func(t *testing.T) {
layout := "2 Jan 2006 15:04:05"
monkey.Patch(time.Now, func() time.Time {
nowTime, err := time.Parse(layout, "9 May 1945 10:03:00")
if err != nil {
t.Fatal(err)
}
return nowTime
})
monkey.Patch(ntp.Time, func(_ string) (time.Time, error) {
ntpTime, err := time.Parse(layout, "9 May 1945 10:03:02")
if err != nil {
t.Fatal(err)
}
return ntpTime, nil
})
result, err := catchStdout(main)
if err != nil {
t.Fatal(err)
}
expected := `current time: 1945-05-09 10:03:00 +0000 UTC
exact time: 1945-05-09 10:03:02 +0000 UTC
`
if string(result) != expected {
t.Fatalf("invalid output:\n%s, expected:\n%s", result, expected)
}
})
}
func catchStdout(runnable func()) (result []byte, err error) {
realOut := os.Stdout
defer func() { os.Stdout = realOut }()
r, fakeOut, err := os.Pipe()
if err != nil {
return
}
os.Stdout = fakeOut
runnable()
if err = fakeOut.Close(); err != nil {
return
}
result, err = ioutil.ReadAll(r)
if err != nil {
return
}
err = r.Close()
return
}