Source file src/crypto/rand/rand_test.go

     1  // Copyright 2010 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  package rand
     6  
     7  import (
     8  	"bytes"
     9  	"compress/flate"
    10  	"io"
    11  	"testing"
    12  )
    13  
    14  func TestRead(t *testing.T) {
    15  	var n int = 4e6
    16  	if testing.Short() {
    17  		n = 1e5
    18  	}
    19  	b := make([]byte, n)
    20  	n, err := io.ReadFull(Reader, b)
    21  	if n != len(b) || err != nil {
    22  		t.Fatalf("ReadFull(buf) = %d, %s", n, err)
    23  	}
    24  
    25  	var z bytes.Buffer
    26  	f, _ := flate.NewWriter(&z, 5)
    27  	f.Write(b)
    28  	f.Close()
    29  	if z.Len() < len(b)*99/100 {
    30  		t.Fatalf("Compressed %d -> %d", len(b), z.Len())
    31  	}
    32  }
    33  
    34  func TestReadEmpty(t *testing.T) {
    35  	n, err := Reader.Read(make([]byte, 0))
    36  	if n != 0 || err != nil {
    37  		t.Fatalf("Read(make([]byte, 0)) = %d, %v", n, err)
    38  	}
    39  	n, err = Reader.Read(nil)
    40  	if n != 0 || err != nil {
    41  		t.Fatalf("Read(nil) = %d, %v", n, err)
    42  	}
    43  }
    44  
    45  func BenchmarkRead(b *testing.B) {
    46  	b.Run("32", func(b *testing.B) {
    47  		benchmarkRead(b, 32)
    48  	})
    49  	b.Run("4K", func(b *testing.B) {
    50  		benchmarkRead(b, 4<<10)
    51  	})
    52  }
    53  
    54  func benchmarkRead(b *testing.B, size int) {
    55  	b.SetBytes(int64(size))
    56  	buf := make([]byte, size)
    57  	for i := 0; i < b.N; i++ {
    58  		if _, err := Read(buf); err != nil {
    59  			b.Fatal(err)
    60  		}
    61  	}
    62  }
    63  

View as plain text