github.com/ethersphere/bee/v2@v2.2.0/pkg/util/testutil/helpers_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 testutil_test
     6  
     7  import (
     8  	"bytes"
     9  	"testing"
    10  
    11  	"github.com/ethersphere/bee/v2/pkg/util/testutil"
    12  )
    13  
    14  func TestRandBytes(t *testing.T) {
    15  	t.Parallel()
    16  
    17  	const size = 32
    18  
    19  	randBytes := testutil.RandBytes(t, size)
    20  
    21  	if got := len(randBytes); got != size {
    22  		t.Fatalf("expected %d, got %d", size, got)
    23  	}
    24  
    25  	if bytes.Equal(randBytes, make([]byte, size)) {
    26  		t.Fatalf("bytes should not be zero value")
    27  	}
    28  }
    29  
    30  func TestRandBytesWithSeed(t *testing.T) {
    31  	t.Parallel()
    32  
    33  	const size = 32
    34  
    35  	randBytes1 := testutil.RandBytesWithSeed(t, size, 1)
    36  	randBytes2 := testutil.RandBytesWithSeed(t, size, 1)
    37  
    38  	if got := len(randBytes1); got != size {
    39  		t.Fatalf("expected %d, got %d", size, got)
    40  	}
    41  
    42  	if !bytes.Equal(randBytes1, randBytes2) {
    43  		t.Fatalf("bytes generated with same seed should be equal")
    44  	}
    45  }
    46  
    47  func TestCleanupCloser(t *testing.T) {
    48  	t.Parallel()
    49  
    50  	newCloser := func(c chan struct{}) closerFn {
    51  		return func() error {
    52  			c <- struct{}{}
    53  			return nil
    54  		}
    55  	}
    56  
    57  	c1 := make(chan struct{}, 1)
    58  	c2 := make(chan struct{}, 1)
    59  
    60  	// Test first add it's own Cleanup function which will
    61  	// assert that all Close method is being invoked
    62  	t.Cleanup(func() {
    63  		if got := len(c1); got != 1 {
    64  			t.Fatalf("expected %d, got %d", 1, got)
    65  		}
    66  		if got := len(c2); got != 1 {
    67  			t.Fatalf("expected %d, got %d", 1, got)
    68  		}
    69  	})
    70  
    71  	testutil.CleanupCloser(t,
    72  		nil,           // nil closers should be allowed
    73  		newCloser(c1), // create closer which will write to chan c1
    74  		newCloser(c2), // create closer which will write to chan c2
    75  	)
    76  }
    77  
    78  type closerFn func() error
    79  
    80  func (c closerFn) Close() error { return c() }