github.com/ethersphere/bee/v2@v2.2.0/pkg/util/testutil/helpers.go (about) 1 // Copyright 2023 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package testutil 6 7 import ( 8 "crypto/rand" 9 "io" 10 mrand "math/rand" 11 "reflect" 12 "testing" 13 14 "github.com/ethersphere/bee/v2/pkg/log" 15 "github.com/ethersphere/bee/v2/pkg/util/ioutil" 16 ) 17 18 // RandBytes returns bytes slice of specified size filled with random values. 19 func RandBytes(tb testing.TB, size int) []byte { 20 tb.Helper() 21 22 buf := make([]byte, size) 23 n, err := rand.Read(buf) 24 if err != nil { 25 tb.Fatal(err) 26 } 27 if n != size { 28 tb.Fatalf("expected to read %d, got %d", size, n) 29 } 30 31 return buf 32 } 33 34 // RandBytesWithSeed returns bytes slice of specified size filled with random values generated using seed. 35 func RandBytesWithSeed(tb testing.TB, size int, seed int64) []byte { 36 tb.Helper() 37 38 buf := make([]byte, size) 39 40 r := mrand.New(mrand.NewSource(seed)) 41 n, err := io.ReadFull(r, buf) 42 if err != nil { 43 tb.Fatal(err) 44 } 45 if n != size { 46 tb.Fatalf("expected to read %d, got %d", size, n) 47 } 48 49 return buf 50 } 51 52 // CleanupCloser adds Cleanup function to Test which will close supplied Closers. 53 func CleanupCloser(t *testing.T, closers ...io.Closer) { 54 t.Helper() 55 56 t.Cleanup(func() { 57 for _, c := range closers { 58 if c == nil { 59 continue 60 } 61 62 if err := c.Close(); err != nil { 63 t.Fatalf("failed to gracefully close %s: %s", reflect.TypeOf(c), err) 64 } 65 } 66 }) 67 } 68 69 // NewLogger returns a new log.Logger that uses t.Log method 70 // as the log sink. It is particularly useful for debugging tests. 71 func NewLogger(t *testing.T) log.Logger { 72 t.Helper() 73 74 testWriter := ioutil.WriterFunc(func(p []byte) (int, error) { 75 t.Log(string(p)) 76 return len(p), nil 77 }) 78 79 return log.NewLogger(t.Name(), log.WithSink(testWriter)) 80 }