github.com/mailgun/holster/v4@v4.20.0/httpsign/random_test.go (about)

     1  package httpsign
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  var _ = fmt.Printf // for testing
    12  
    13  func TestRealRandom(t *testing.T) {
    14  	// We really can't test the output of the csprng, so let's just check that
    15  	// the output lengths match what we think we ask for.
    16  
    17  	// Get the real random number generator.
    18  	csprng := realRandom{}
    19  
    20  	// Test Bytes().
    21  	b, _ := csprng.bytes(16)
    22  	if g, w := len(b), 16; g != w {
    23  		t.Errorf("&realRandom{}.Bytes(16) produced a slice of length %d; want %d", g, w)
    24  	}
    25  
    26  	// Test HexDigest().
    27  	s, _ := csprng.hexDigest(16)
    28  	if g, w := len(s), 32; g != w {
    29  		t.Errorf("&realRandom{}.HexDigest(16) produced a slice of length %d; want %d", g, w)
    30  	}
    31  }
    32  
    33  func TestFakeRandom(t *testing.T) {
    34  	// Get fake random number generator.
    35  	frng := fakeRandom{}
    36  
    37  	// Test Bytes().
    38  	g0, err := frng.bytes(8)
    39  	if err != nil {
    40  		t.Error("Got unexpected error from frng.Bytes:", err)
    41  	}
    42  	if w := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; !bytes.Equal(g0, w) {
    43  		t.Errorf("&FRNG{}.Bytes(8) = %v; want %v", g0, w)
    44  	}
    45  
    46  	// Test HexDigest().
    47  	g1, err := frng.hexDigest(4)
    48  	if err != nil {
    49  		t.Error("Got unexpected error from frng.HexDigest:", err)
    50  	}
    51  	if w := "00010203"; g1 != w {
    52  		t.Errorf("&FRNG{}.HexDigest(4) = %v; want %v", g1, w)
    53  	}
    54  }
    55  
    56  func TestSeededRNG(t *testing.T) {
    57  	rng := SeededRNG{}
    58  
    59  	// Test Bytes().
    60  	g0, err := rng.bytes(8)
    61  	if err != nil {
    62  		t.Error("Got unexpected error from SeededRNG.Bytes:", err)
    63  	}
    64  	if w := []byte{0xfa, 0x12, 0xf9, 0x2a, 0xfb, 0xe0, 0x0f, 0x85}; !bytes.Equal(g0, w) {
    65  		t.Errorf("&SeededRNG{Seed: 0}.Bytes(8) = %v, want %v", g0, w)
    66  	}
    67  
    68  	// Reseed.
    69  	rng = SeededRNG{}
    70  
    71  	// Test HexDigest().
    72  	g1, err := rng.hexDigest(4)
    73  	assert.NoError(t, err)
    74  	if w := "fa12f92a"; g1 != w {
    75  		t.Errorf("&SeededRNG{Seed: 0}.Bytes(4) = %v, want %v", g1, w)
    76  	}
    77  }