...

Source file src/crypto/rand/rand_batched_test.go

Documentation: crypto/rand

     1  // Copyright 2014 The Go 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  //go:build unix
     6  
     7  package rand
     8  
     9  import (
    10  	"bytes"
    11  	"errors"
    12  	prand "math/rand"
    13  	"testing"
    14  )
    15  
    16  func TestBatched(t *testing.T) {
    17  	fillBatched := batched(func(p []byte) error {
    18  		for i := range p {
    19  			p[i] = byte(i)
    20  		}
    21  		return nil
    22  	}, 5)
    23  
    24  	p := make([]byte, 13)
    25  	if err := fillBatched(p); err != nil {
    26  		t.Fatalf("batched function returned error: %s", err)
    27  	}
    28  	expected := []byte{0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2}
    29  	if !bytes.Equal(expected, p) {
    30  		t.Errorf("incorrect batch result: got %x, want %x", p, expected)
    31  	}
    32  }
    33  
    34  func TestBatchedBuffering(t *testing.T) {
    35  	backingStore := make([]byte, 1<<23)
    36  	prand.Read(backingStore)
    37  	backingMarker := backingStore[:]
    38  	output := make([]byte, len(backingStore))
    39  	outputMarker := output[:]
    40  
    41  	fillBatched := batched(func(p []byte) error {
    42  		n := copy(p, backingMarker)
    43  		backingMarker = backingMarker[n:]
    44  		return nil
    45  	}, 731)
    46  
    47  	for len(outputMarker) > 0 {
    48  		max := 9200
    49  		if max > len(outputMarker) {
    50  			max = len(outputMarker)
    51  		}
    52  		howMuch := prand.Intn(max + 1)
    53  		if err := fillBatched(outputMarker[:howMuch]); err != nil {
    54  			t.Fatalf("batched function returned error: %s", err)
    55  		}
    56  		outputMarker = outputMarker[howMuch:]
    57  	}
    58  	if !bytes.Equal(backingStore, output) {
    59  		t.Error("incorrect batch result")
    60  	}
    61  }
    62  
    63  func TestBatchedError(t *testing.T) {
    64  	b := batched(func(p []byte) error { return errors.New("failure") }, 5)
    65  	if b(make([]byte, 13)) == nil {
    66  		t.Fatal("batched function should have returned an error")
    67  	}
    68  }
    69  
    70  func TestBatchedEmpty(t *testing.T) {
    71  	b := batched(func(p []byte) error { return errors.New("failure") }, 5)
    72  	if b(make([]byte, 0)) != nil {
    73  		t.Fatal("empty slice should always return successful")
    74  	}
    75  }
    76  

View as plain text