|
| 1 | +package magickey |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rsa" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | +) |
| 9 | + |
| 10 | +func TestGetReference(t *testing.T) { |
| 11 | + tests := []struct { |
| 12 | + name string |
| 13 | + test func(t *testing.T) |
| 14 | + }{ |
| 15 | + { |
| 16 | + name: "success when called twice returns singleton key", |
| 17 | + test: func(t *testing.T) { |
| 18 | + key1 := GetReference() |
| 19 | + key2 := GetReference() |
| 20 | + assert.Same(t, key1, key2) |
| 21 | + }, |
| 22 | + }, |
| 23 | + { |
| 24 | + name: "success when key is valid RSA 2048", |
| 25 | + test: func(t *testing.T) { |
| 26 | + key := GetReference() |
| 27 | + assert.NotNil(t, key) |
| 28 | + assert.Equal(t, 2048, key.N.BitLen()) |
| 29 | + assert.NotNil(t, key.PublicKey) |
| 30 | + assert.Equal(t, 2048, key.PublicKey.N.BitLen()) |
| 31 | + }, |
| 32 | + }, |
| 33 | + { |
| 34 | + name: "success when key is usable for operations", |
| 35 | + test: func(t *testing.T) { |
| 36 | + key := GetReference() |
| 37 | + assert.NotNil(t, key.Primes) |
| 38 | + assert.Len(t, key.Primes, 2) |
| 39 | + assert.NotNil(t, key.Precomputed) |
| 40 | + }, |
| 41 | + }, |
| 42 | + { |
| 43 | + name: "success when multiple calls return same key", |
| 44 | + test: func(t *testing.T) { |
| 45 | + keys := make([]*rsa.PrivateKey, 10) |
| 46 | + for i := 0; i < 10; i++ { |
| 47 | + keys[i] = GetReference() |
| 48 | + } |
| 49 | + firstKey := keys[0] |
| 50 | + for _, key := range keys { |
| 51 | + assert.Same(t, firstKey, key) |
| 52 | + } |
| 53 | + }, |
| 54 | + }, |
| 55 | + } |
| 56 | + |
| 57 | + for _, tc := range tests { |
| 58 | + t.Run(tc.name, tc.test) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func TestGetReference_Concurrency(t *testing.T) { |
| 63 | + t.Run("success when called concurrently returns singleton", func(t *testing.T) { |
| 64 | + const numGoroutines = 100 |
| 65 | + keys := make(chan *rsa.PrivateKey, numGoroutines) |
| 66 | + for i := 0; i < numGoroutines; i++ { |
| 67 | + go func() { |
| 68 | + keys <- GetReference() |
| 69 | + }() |
| 70 | + } |
| 71 | + collectedKeys := make([]*rsa.PrivateKey, numGoroutines) |
| 72 | + for i := 0; i < numGoroutines; i++ { |
| 73 | + collectedKeys[i] = <-keys |
| 74 | + } |
| 75 | + firstKey := collectedKeys[0] |
| 76 | + for _, key := range collectedKeys { |
| 77 | + assert.Same(t, firstKey, key) |
| 78 | + } |
| 79 | + }) |
| 80 | +} |
| 81 | + |
| 82 | +func BenchmarkGetReference(b *testing.B) { |
| 83 | + b.ResetTimer() |
| 84 | + for i := 0; i < b.N; i++ { |
| 85 | + _ = GetReference() |
| 86 | + } |
| 87 | +} |
0 commit comments