forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_log_scope.go
166 lines (151 loc) · 4.35 KB
/
test_log_scope.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// Copyright 2016 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Raphael 'kena' Poss (knz@cockroachlabs.com)
package log
import (
"fmt"
"io"
"io/ioutil"
"os"
"runtime"
"strings"
"github.com/cockroachdb/cockroach/pkg/util/caller"
)
// TestLogScope represents the lifetime of a logging output. It
// ensures that the log files are stored in a directory specific to a
// test, and asserts that logging output is not written to this
// directory beyond the lifetime of the scope.
type TestLogScope string
// tShim is the part of testing.T used by TestLogScope.
// We can't use testing.T directly because we have
// a linter which forbids its use in public interfaces.
type tShim interface {
Fatal(...interface{})
Failed() bool
Error(...interface{})
Errorf(fmt string, args ...interface{})
}
// Scope creates a TestLogScope which corresponds to the lifetime of a
// logging directory. If testName is empty, the logging directory is
// named after the caller of Scope, up `skip` caller levels. It also
// disables logging to stderr for severity levels below ERROR.
func Scope(t tShim, testName string) TestLogScope {
if testName == "" {
testName = "logUnknown"
if _, _, f := caller.Lookup(1); f != "" {
parts := strings.Split(f, ".")
testName = "log" + parts[len(parts)-1]
}
}
tempDir, err := ioutil.TempDir("", testName)
if err != nil {
t.Fatal(err)
}
if err := dirTestOverride(tempDir); err != nil {
t.Fatal(err)
}
if err := enableLogFileOutput(tempDir, Severity_ERROR); err != nil {
t.Fatal(err)
}
return TestLogScope(tempDir)
}
// enableLogFileOutput turns on logging using the specified directory.
// For unittesting only.
func enableLogFileOutput(dir string, stderrSeverity Severity) error {
logging.mu.Lock()
defer logging.mu.Unlock()
logging.toStderr = false
logging.stderrThreshold = stderrSeverity
return logDir.Set(dir)
}
// Close cleans up a TestLogScope. The directory and its contents are
// deleted, unless the test has failed and the directory is non-empty.
func (l TestLogScope) Close(t tShim) {
if string(l) == "" {
// Never initialized.
return
}
defer func() {
// Check whether there is something to remove.
emptyDir, err := isDirEmpty(string(l))
if err != nil {
t.Fatal(err)
}
if (t.Failed() || calledDuringPanic()) && !emptyDir {
// If the test failed, we keep the log files for further investigation,
// but only if there were any.
fmt.Fprintf(os.Stderr, "test log files left over in: %s\n", l)
} else {
// Clean up.
if err := os.RemoveAll(string(l)); err != nil {
t.Error(err)
}
}
}()
// Flush/Close the log files.
if err := dirTestOverride(""); err != nil {
t.Fatal(err)
}
}
// calledDuringPanic returns true if panic() is one of its callers.
func calledDuringPanic() bool {
pc := make([]uintptr, 40)
nCallers := runtime.Callers(2, pc[:])
frames := runtime.CallersFrames(pc)
for i := 0; i < nCallers; i++ {
f, more := frames.Next()
if f.Function == "runtime.gopanic" {
return true
}
if !more {
break
}
}
return false
}
// dirTestOverride sets the default value for the logging output directory
// for use in tests.
func dirTestOverride(dir string) error {
// Ensure any remaining logs are written.
Flush()
logDir.Lock()
logDir.name = dir
logDir.Unlock()
// When we change the directory we close the current logging
// output, so that a rotation to the new directory is forced on
// the next logging event.
logging.mu.Lock()
err := logging.closeFilesLocked()
logging.mu.Unlock()
return err
}
func isDirEmpty(dirname string) (bool, error) {
f, err := os.Open(dirname)
if err != nil {
if os.IsNotExist(err) {
return true, nil
}
return false, err
}
list, err := f.Readdir(1)
errClose := f.Close()
if err != nil && err != io.EOF {
return false, err
}
if errClose != nil {
return false, errClose
}
return len(list) == 0, nil
}