-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathcontext_test.go
64 lines (48 loc) · 1.76 KB
/
context_test.go
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
package httpctx_test
import (
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/TykTechnologies/tyk/internal/httpctx"
)
func TestValue_SetAndGet(t *testing.T) {
// Define a key and instantiate a new Value with type map[string]any
key := "testKey"
value := httpctx.NewValue[map[string]any](key)
// Prepare a map to store in context
expectedData := map[string]any{
"userID": 123,
"userRole": "admin",
}
// Create a new HTTP request using httptest
req := httptest.NewRequest("GET", "/", nil)
// Set the value in the request's context
req = value.Set(req, expectedData)
// Retrieve the value from the context
retrievedData := value.Get(req)
assert.Equal(t, expectedData, retrievedData, "Retrieved data does not match expected data")
}
func TestValue_GetWithMissingKey(t *testing.T) {
// Define a key and instantiate a new Value with type map[string]any
key := "missingKey"
value := httpctx.NewValue[map[string]any](key)
// Create a new HTTP request using httptest
req := httptest.NewRequest("GET", "/", nil)
// Try to retrieve the value from the context
retrievedData := value.Get(req)
// Expect not to find any data
assert.Nil(t, retrievedData, "Expected retrieved data to be nil for a missing key")
}
func TestValue_SetDifferentTypes(t *testing.T) {
// Test using a different type for Value, e.g., int
intKey := "intKey"
intValue := httpctx.NewValue[int](intKey)
// Create a new HTTP request using httptest
req := httptest.NewRequest("GET", "/", nil)
// Set an int value in the context
expectedInt := 42
req = intValue.Set(req, expectedInt)
// Retrieve the int value from the context
retrievedInt := intValue.Get(req)
assert.Equal(t, expectedInt, retrievedInt, "Retrieved int value does not match expected value")
}