|
| 1 | +package sessiongate |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "errors" |
| 6 | + "regexp" |
| 7 | + "testing" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +var signKey []byte |
| 12 | + |
| 13 | +func init() { |
| 14 | + signKey = make([]byte, 16) |
| 15 | + rand.Read(signKey) |
| 16 | +} |
| 17 | + |
| 18 | +// TestStart tests the START command for the SessionGate module |
| 19 | +func TestStart(t *testing.T) { |
| 20 | + t.Run("Should fail with missing SignKey", func(t *testing.T) { |
| 21 | + config := &Config{} |
| 22 | + |
| 23 | + _, err := NewSessiongate(config) |
| 24 | + if err == nil { |
| 25 | + t.Fail() |
| 26 | + } |
| 27 | + }) |
| 28 | + |
| 29 | + t.Run("Should fail with negative TTL", func(t *testing.T) { |
| 30 | + config := &Config{ |
| 31 | + SignKey: signKey, |
| 32 | + } |
| 33 | + |
| 34 | + sessiongate, err := NewSessiongate(config) |
| 35 | + if err != nil { |
| 36 | + t.Error(err) |
| 37 | + } |
| 38 | + |
| 39 | + _, err = sessiongate.Start(-1) |
| 40 | + if err == nil { |
| 41 | + t.Error(errors.New("Negative TTL should produce an error")) |
| 42 | + } |
| 43 | + }) |
| 44 | + |
| 45 | + // checkStart checks if the START command does not produce an error and if |
| 46 | + // token is in the expected format |
| 47 | + checkStart := func(config *Config) { |
| 48 | + sessiongate, err := NewSessiongate(config) |
| 49 | + if err != nil { |
| 50 | + t.Error(err) |
| 51 | + } |
| 52 | + |
| 53 | + token, err := sessiongate.Start(300) |
| 54 | + if err != nil { |
| 55 | + t.Error(err) |
| 56 | + } |
| 57 | + |
| 58 | + regex := "^v[0-9]\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$" |
| 59 | + match, err := regexp.MatchString(regex, string(token)) |
| 60 | + if err != nil { |
| 61 | + t.Error(err) |
| 62 | + } |
| 63 | + |
| 64 | + if match == false { |
| 65 | + err = errors.New("The response token does not match the expected format") |
| 66 | + t.Error(err) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + t.Run("Should succeed with default configuration", func(t *testing.T) { |
| 71 | + checkStart(&Config{ |
| 72 | + SignKey: signKey, |
| 73 | + }) |
| 74 | + }) |
| 75 | + |
| 76 | + t.Run("Should succeed with explicit Addr", func(t *testing.T) { |
| 77 | + checkStart(&Config{ |
| 78 | + SignKey: signKey, |
| 79 | + Addr: "localhost:6379", |
| 80 | + }) |
| 81 | + }) |
| 82 | + |
| 83 | + t.Run("Should succeed with explicit MaxIdle", func(t *testing.T) { |
| 84 | + checkStart(&Config{ |
| 85 | + SignKey: signKey, |
| 86 | + MaxIdle: 15, |
| 87 | + }) |
| 88 | + }) |
| 89 | + |
| 90 | + t.Run("Should succeed with explicit IdleTimeout", func(t *testing.T) { |
| 91 | + checkStart(&Config{ |
| 92 | + SignKey: signKey, |
| 93 | + IdleTimeout: 90 * time.Second, |
| 94 | + }) |
| 95 | + }) |
| 96 | +} |
0 commit comments