/
utils.go
427 lines (363 loc) · 9.79 KB
/
utils.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//
// (C) Copyright 2018-2024 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package test
import (
"bufio"
"context"
"fmt"
"io"
"io/fs"
"io/ioutil"
"net"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"sync"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/testing/protocmp"
"github.com/daos-stack/daos/src/control/logging"
)
// AssertTrue asserts b is true
func AssertTrue(t *testing.T, b bool, message string) {
t.Helper()
if !b {
t.Fatal(message)
}
}
// AssertFalse asserts b is false
func AssertFalse(t *testing.T, b bool, message string) {
t.Helper()
if b {
t.Fatal(message)
}
}
// AssertEqual asserts b is equal to a
//
// Whilst suitable in most situations, reflect.DeepEqual() may not be
// suitable for nontrivial struct element comparisons, go-cmp should
// then be used.
func AssertEqual(
t *testing.T, a interface{}, b interface{}, message string) {
t.Helper()
if reflect.DeepEqual(a, b) {
return
}
if len(message) > 0 {
message += ", "
}
t.Fatalf(message+"%#v != %#v", a, b)
}
// AssertNotEqual asserts b is not equal to a
//
// Whilst suitable in most situations, reflect.DeepEqual() may not be
// suitable for nontrivial struct element comparisons, go-cmp should
// then be used.
func AssertNotEqual(
t *testing.T, a interface{}, b interface{}, message string) {
t.Helper()
if !reflect.DeepEqual(a, b) {
return
}
if len(message) > 0 {
message += ", "
}
t.Fatalf(message+"%#v == %#v", a, b)
}
// AssertStringsEqual sorts string slices before comparing.
func AssertStringsEqual(
t *testing.T, a []string, b []string, message string) {
t.Helper()
sort.Strings(a)
sort.Strings(b)
AssertEqual(t, a, b, message)
}
// ExpectError asserts error contains expected message
func ExpectError(t *testing.T, actualErr error, expectedMessage string, desc interface{}) {
t.Helper()
if actualErr == nil {
if expectedMessage != "" {
t.Fatalf("expected a non-nil error: %v", desc)
}
} else if diff := cmp.Diff(expectedMessage, actualErr.Error()); diff != "" {
t.Fatalf("unexpected error (-want, +got):\n%s\n", diff)
}
}
// CmpErrBool compares two errors and returns a boolean value indicating equality
// or at least close similarity between their messages.
func CmpErrBool(want, got error) bool {
if want == got {
return true
}
if want == nil || got == nil {
return false
}
if !strings.Contains(got.Error(), want.Error()) {
return false
}
return true
}
// CmpErr compares two errors for equality or at least close similarity in their messages.
func CmpErr(t *testing.T, want, got error) {
t.Helper()
if want != nil && want.Error() == "" {
t.Fatal("comparison with empty error will always return true, don't do it")
}
if !CmpErrBool(want, got) {
t.Fatalf("unexpected error\n(wanted: %v, got: %v)", want, got)
}
}
// SplitFile separates file content into contiguous sections separated by
// a blank line.
func SplitFile(path string) (sections [][]string, err error) {
file, err := os.Open(path)
if err != nil {
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
if scanner.Text() == "" {
sections = append(sections, lines)
lines = make([]string, 0)
} else {
lines = append(lines, scanner.Text())
}
}
if len(lines) > 0 {
sections = append(sections, lines)
}
return
}
// LoadTestFiles reads inputs and outputs from file and do basic sanity checks.
// Both files contain entries of multiple lines separated by blank line.
// Return inputs and outputs, both of which are slices of string slices.
func LoadTestFiles(inFile string, outFile string) (
inputs [][]string, outputs [][]string, err error) {
inputs, err = SplitFile(inFile)
if err != nil {
return
}
outputs, err = SplitFile(outFile)
if err != nil {
return
}
if len(inputs) < 1 {
err = fmt.Errorf("no inputs read from file")
} else if len(inputs) != len(outputs) {
err = fmt.Errorf("number of inputs and outputs not equal")
}
return
}
// ShowBufferOnFailure displays captured output on test failure. Should be run
// via defer in the test function.
func ShowBufferOnFailure(t *testing.T, buf fmt.Stringer) {
t.Helper()
if t.Failed() {
fmt.Printf("captured log output:\n%s", buf.String())
}
if r, ok := buf.(interface{ Reset() }); ok {
r.Reset()
}
}
// DefaultCmpOpts gets default go-cmp comparison options for tests.
func DefaultCmpOpts() []cmp.Option {
return []cmp.Option{
cmpopts.IgnoreTypes(sync.Mutex{}, sync.RWMutex{}),
protocmp.Transform(), // makes Protobuf structs comparable
}
}
// CmpOptIgnoreFieldAnyType creates a cmp.Option that allows go-cmp comparisons to ignore all
// fields with a specific name in any type.
func CmpOptIgnoreFieldAnyType(field string) cmp.Option {
return cmp.FilterPath(
func(p cmp.Path) bool {
return p.Last().String() == field || p.Last().String() == ("."+field)
},
cmp.Ignore())
}
// CmpOptEquateErrorMessages creates a cmp.Option that allows go-cmp to compare errors by message.
func CmpOptEquateErrorMessages() cmp.Option {
areConcreteErrors := func(x, y interface{}) bool {
_, ok1 := x.(error)
_, ok2 := y.(error)
return ok1 && ok2
}
return cmp.FilterValues(areConcreteErrors, cmp.Comparer(func(x, y interface{}) bool {
xe := x.(error)
ye := y.(error)
return xe.Error() == ye.Error()
}))
}
// CreateTestDir creates a temporary test directory.
// It returns the path to the directory and a cleanup function.
func CreateTestDir(t *testing.T) (string, func()) {
t.Helper()
name := strings.Replace(t.Name(), "/", "-", -1)
tmpDir, err := ioutil.TempDir("", name)
if err != nil {
t.Fatalf("Couldn't create temporary directory: %v", err)
}
return tmpDir, func() {
err := os.RemoveAll(tmpDir)
if err != nil {
t.Fatalf("Couldn't remove tmp dir: %v", err)
}
}
}
// CreateTestFile creates a file in the given directory with a random name, and
// writes the content string to the file. It returns the path to the file.
func CreateTestFile(t *testing.T, dir, content string) string {
t.Helper()
file, err := ioutil.TempFile(dir, "")
if err != nil {
t.Fatal(err)
}
defer file.Close()
_, err = file.WriteString(content)
if err != nil {
t.Fatal(err)
}
return file.Name()
}
// CreateTestSocket creates a Unix Domain Socket that can listen for connections
// on a given path. It returns the listener and a cleanup function.
func CreateTestSocket(t *testing.T, sockPath string) (*net.UnixListener, func()) {
t.Helper()
addr := &net.UnixAddr{Name: sockPath, Net: "unixpacket"}
sock, err := net.ListenUnix("unixpacket", addr)
if err != nil {
t.Fatalf("Couldn't set up test socket: %v", err)
}
cleanup := func() {
t.Helper()
sock.Close()
if err := unix.Unlink(sockPath); err != nil && !os.IsNotExist(err) {
t.Fatalf("Unlink(%s): %s", sockPath, err)
}
}
err = os.Chmod(sockPath, 0777)
if err != nil {
cleanup()
t.Fatalf("Unable to set permissions on test socket: %v", err)
}
return sock, cleanup
}
// SetupTestListener sets up a Unix Domain Socket in a temp directory to listen
// and receive one connection.
// The server-side connection object is sent through the conn channel when a client
// connects.
// It returns the path to the socket, to allow the client to connect, and a
// cleanup function.
func SetupTestListener(t *testing.T, conn chan *net.UnixConn) (string, func()) {
t.Helper()
tmpDir, tmpCleanup := CreateTestDir(t)
path := filepath.Join(tmpDir, "test.sock")
sock, socketCleanup := CreateTestSocket(t, path)
cleanup := func() {
socketCleanup()
tmpCleanup()
}
go func() {
newConn, err := sock.AcceptUnix()
if err != nil {
t.Logf("Failed to accept connection: %v", err)
return
}
conn <- newConn
}()
return path, cleanup
}
// CopyFile copies the src file to dst. Any existing file will be overwritten and
// will not copy file attributes.
func CopyFile(t *testing.T, src, dst string) {
t.Helper()
in, err := os.Open(src)
if err != nil {
t.Fatal(err)
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
t.Fatal(err)
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
t.Fatal(err)
}
}
// CopyDir will recursively copy src to test. Fails if src does
// not exist or dst already exists.
func CopyDir(t *testing.T, src, dst string) {
t.Helper()
if _, err := os.Stat(dst); err == nil {
t.Fatalf("dst already exists: %s", dst)
}
srcStat, err := os.Stat(src)
if err != nil {
t.Fatal(err)
}
if !srcStat.IsDir() {
t.Fatalf("%s is not a directory", src)
}
if err := os.MkdirAll(dst, srcStat.Mode()); err != nil {
t.Fatal(err)
}
if err := filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
switch {
case d.IsDir():
if path == src || d.Name() == "." || d.Name() == ".." {
return nil
}
CopyDir(t, path, filepath.Join(dst, d.Name()))
return nil
case d.Type() == os.ModeSymlink:
link, err := os.Readlink(path)
if err != nil {
return err
}
return os.Symlink(link, filepath.Join(dst, d.Name()))
case d.Type().IsRegular():
info, err := d.Info()
if err != nil {
return err
}
destPath := filepath.Join(dst, d.Name())
CopyFile(t, path, destPath)
return os.Chmod(destPath, info.Mode())
default:
return fmt.Errorf("unsupported file type: %s", d.Type())
}
}); err != nil {
t.Fatal(err)
}
}
// Context returns a context that is canceled when the test is done.
func Context(t *testing.T) context.Context {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
return ctx
}
// MustLogContext returns a context containing the supplied logger.
// Canceled when the test is done.
func MustLogContext(t *testing.T, log logging.Logger) context.Context {
t.Helper()
ctx, err := logging.ToContext(Context(t), log)
if err != nil {
t.Fatal(err)
}
return ctx
}