~mendelmaleh/checksum

ref: e71e2f6f91dd70e3fd9fce07672614204fce5348 checksum/luhn_test.go -rw-r--r-- 2.2 KiB
e71e2f6fMendel E Initial commit 1 year, 3 months 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package checksum

import (
	"math/rand"
	"strconv"
	"testing"
)

func TestLuhn(t *testing.T) {
	cases := []int{18, 273, 79927398713}

	for i, test := range cases {
		if !Luhn(test) {
			t.Errorf("Luhn [%d] (%d) failed", i, test)
		}
	}
}

func TestGetLuhn(t *testing.T) {
	cases := []struct {
		num, check int
	}{
		{1, 8},
		{27, 3},
		{7992739871, 3},
	}

	for i, test := range cases {
		if res := GetLuhn(test.num); res != test.check {
			t.Errorf("GetLuhn [%d] (%d): expected check %d, got %d", i, test.num, test.check, res)
		}
	}
}

func TestLuhnString(t *testing.T) {
	cases := []string{"18", "273", "79927398713", "79 92   7398   713"}

	for i, test := range cases {
		res, err := LuhnString(test)
		if err != nil {
			t.Error(err)
		}

		if !res {
			t.Errorf("LuhnString [%d] (%s) failed", i, test)
		}
	}
}

func TestGetLuhnString(t *testing.T) {
	cases := []struct {
		num   string
		check int
	}{
		{"1", 8},
		{"27", 3},
		{"7992739871", 3},
		{"79 92   7398   71", 3},
	}

	for i, test := range cases {
		res, err := GetLuhnString(test.num)
		if err != nil {
			t.Error(err)
		}

		if res != test.check {
			t.Errorf("GetLuhnString [%d] (%s): expected check %d, got %d", i, test.num, test.check, res)
		}
	}
}

func BenchmarkLuhn(b *testing.B) {
	for n := 0; n < b.N; n++ {
		Luhn(rand.Int())
	}
}

func BenchmarkGetLuhn(b *testing.B) {
	for n := 0; n < b.N; n++ {
		GetLuhn(rand.Int())
	}
}

func BenchmarkLuhnString(b *testing.B) {
	for n := 0; n < b.N; n++ {
		LuhnString(strconv.Itoa(rand.Int()))
	}
}

func BenchmarkGetLuhnString(b *testing.B) {
	for n := 0; n < b.N; n++ {
		GetLuhnString(strconv.Itoa(rand.Int()))
	}
}

func BenchmarkLuhn_Atoi(b *testing.B) {
	for n := 0; n < b.N; n++ {
		s, _ := strconv.Atoi(strconv.Itoa(rand.Int()))
		Luhn(s)
	}
}

func BenchmarkGetLuhn_Atoi(b *testing.B) {
	for n := 0; n < b.N; n++ {
		s, _ := strconv.Atoi(strconv.Itoa(rand.Int()))
		GetLuhn(s)
	}
}

func Benchmark_randInt(b *testing.B) {
	for n := 0; n < b.N; n++ {
		rand.Int()
	}
}

func Benchmark_Itoa(b *testing.B) {
	for n := 0; n < b.N; n++ {
		strconv.Itoa(rand.Int())
	}
}

func Benchmark_Atoi(b *testing.B) {
	for n := 0; n < b.N; n++ {
		strconv.Atoi(strconv.Itoa(rand.Int()))
	}
}