~samwhited/xmpp

ref: a42ef11e9469b0b65746f979e1bdf5155d1c13dd xmpp/internal/idgen_test.go -rw-r--r-- 1.2 KiB
a42ef11eSam Whited all: update copyright message 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright 2016 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

package internal

import (
	"errors"
	"testing"
)

type zeroReader struct{}

func (z zeroReader) Read(b []byte) (n int, err error) {
	for i := range b {
		b[i] = 0
	}

	return len(b), nil
}

func TestRandomIDLength(t *testing.T) {
	for i := 0; i <= 15; i++ {
		if s := randomID(i, zeroReader{}); len(s) != i {
			t.Logf("Expected length %d got %d", i, len(s))
			t.Fail()
		}
	}
}

type errorReader struct{}

func (errorReader) Read(p []byte) (int, error) {
	return 0, errors.New("Expected error from error reader")
}

type nopReader struct{}

func (nopReader) Read(p []byte) (int, error) {
	return 0, nil
}

func TestRandomPanicsIfRandReadFails(t *testing.T) {
	defer func() {
		if r := recover(); r == nil {
			t.Error("Expected randomID to panic if reading random bytes failed")
		}
	}()
	randomID(16, errorReader{})
}

func TestRandomPanicsIfRandReadWrongLen(t *testing.T) {
	defer func() {
		if r := recover(); r == nil {
			t.Error("Expected randomID to panic if no random bytes were read")
		}
	}()
	randomID(16, nopReader{})
}