-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
118 lines (93 loc) · 2.12 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package goissue34681_test
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/alexbrainman/goissue34681"
)
func displayFile(t *testing.T, path string) {
t.Helper()
data, err := ioutil.ReadFile(path)
if err != nil {
t.Logf("display faild: %v", err)
return
}
t.Logf("displaying %v", path)
lines := bytes.Split(data, []byte{'\n'})
for _, line := range lines {
t.Logf("%q", line)
}
}
func TestRotateFiles(t *testing.T) {
temp, err := ioutil.TempDir("", "TestRotateFiles")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(temp)
logpath := filepath.Join(temp, "log.txt")
var renameCounter int
backupName := func(counter int) string {
return filepath.Join(temp, fmt.Sprintf("log%d.txt", counter))
}
rename := func() error {
renameCounter++
return os.Rename(logpath, backupName(renameCounter))
}
f1, err := goissue34681.OpenFile(logpath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
defer f1.Close()
write := func(f *os.File, s string) {
_, err := f.Write([]byte(s))
if err != nil {
t.Fatal(err)
}
}
write(f1, "line1\n")
err = rename()
if err != nil {
t.Fatal(err)
}
write(f1, "line2\n")
f2, err := goissue34681.OpenFile(logpath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
defer f1.Close()
write(f2, "line3\n")
write(f1, "line4\n")
err = rename()
if err != nil {
t.Fatal(err)
}
f3, err := goissue34681.OpenFile(logpath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
defer f3.Close()
write(f3, "liner5\n")
f4, err := goissue34681.OpenFile(logpath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
defer f4.Close()
write(f4, "liner6\n")
write(f3, "liner7\n")
f5, err := goissue34681.Open(logpath)
if err != nil {
t.Fatal(err)
}
defer f5.Close()
// display files
displayFile(t, logpath)
for i := 1; i <= renameCounter; i++ {
displayFile(t, backupName(i))
}
}