github.com/ethersphere/bee/v2@v2.2.0/pkg/util/testutil/pseudorand/reader_test.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 pseudorand_test 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 "io" 12 "math/rand" 13 "testing" 14 15 "github.com/ethersphere/bee/v2/pkg/util/testutil/pseudorand" 16 ) 17 18 func TestReader(t *testing.T) { 19 size := 42000 20 seed := make([]byte, 32) 21 r := pseudorand.NewReader(seed, size) 22 content, err := io.ReadAll(r) 23 if err != nil { 24 t.Fatal(err) 25 } 26 t.Run("deterministicity", func(t *testing.T) { 27 r2 := pseudorand.NewReader(seed, size) 28 content2, err := io.ReadAll(r2) 29 if err != nil { 30 t.Fatal(err) 31 } 32 if !bytes.Equal(content, content2) { 33 t.Fatal("content mismatch") 34 } 35 }) 36 t.Run("randomness", func(t *testing.T) { 37 bufSize := 4096 38 if bytes.Equal(content[:bufSize], content[bufSize:2*bufSize]) { 39 t.Fatal("buffers should not match") 40 } 41 }) 42 t.Run("re-readability", func(t *testing.T) { 43 ns, err := r.Seek(0, io.SeekStart) 44 if err != nil { 45 t.Fatal(err) 46 } 47 if ns != 0 { 48 t.Fatal("seek mismatch") 49 } 50 var read []byte 51 buf := make([]byte, 8200) 52 total := 0 53 for { 54 s := rand.Intn(820) 55 n, err := r.Read(buf[:s]) 56 total += n 57 read = append(read, buf[:n]...) 58 if errors.Is(err, io.EOF) { 59 break 60 } 61 if err != nil { 62 t.Fatal(err) 63 } 64 } 65 read = read[:total] 66 if len(read) != len(content) { 67 t.Fatal("content length mismatch. expected", len(content), "got", len(read)) 68 } 69 if !bytes.Equal(content, read) { 70 t.Fatal("content mismatch") 71 } 72 }) 73 t.Run("comparison", func(t *testing.T) { 74 ns, err := r.Seek(0, io.SeekStart) 75 if err != nil { 76 t.Fatal(err) 77 } 78 if ns != 0 { 79 t.Fatal("seek mismatch") 80 } 81 if eq, err := r.Equal(bytes.NewBuffer(content)); err != nil { 82 t.Fatal(err) 83 } else if !eq { 84 t.Fatal("content mismatch") 85 } 86 ns, err = r.Seek(0, io.SeekStart) 87 if err != nil { 88 t.Fatal(err) 89 } 90 if ns != 0 { 91 t.Fatal("seek mismatch") 92 } 93 if eq, err := r.Equal(bytes.NewBuffer(content[:len(content)-1])); err != nil { 94 t.Fatal(err) 95 } else if eq { 96 t.Fatal("content should match") 97 } 98 }) 99 t.Run("seek and match", func(t *testing.T) { 100 for i := 0; i < 20; i++ { 101 off := rand.Intn(size) 102 n := rand.Intn(size - off) 103 t.Run(fmt.Sprintf("off=%d n=%d", off, n), func(t *testing.T) { 104 ns, err := r.Seek(int64(off), io.SeekStart) 105 if err != nil { 106 t.Fatal(err) 107 } 108 if ns != int64(off) { 109 t.Fatal("seek mismatch") 110 } 111 ok, err := r.Match(bytes.NewBuffer(content[off:off+n]), n) 112 if err != nil { 113 t.Fatal(err) 114 } 115 if !ok { 116 t.Fatal("content mismatch") 117 } 118 }) 119 } 120 }) 121 }