-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmulti_tenancy_test.go
97 lines (91 loc) · 2.29 KB
/
multi_tenancy_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
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
package gin
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/go-saas/saas"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func SetUp() *gin.Engine {
r := gin.Default()
r.Use(MultiTenancy(saas.NewMemoryTenantStore(
[]saas.TenantConfig{
{ID: "1", Name: "Test1"},
{ID: "2", Name: "Test3"},
})))
r.GET("/", func(c *gin.Context) {
rCtx := c.Request.Context()
tenantInfo, _ := saas.FromCurrentTenant(rCtx)
trR := saas.FromTenantResolveRes(rCtx)
c.JSON(200, gin.H{
"tenantId": tenantInfo.GetId(),
"resolvers": trR.AppliedResolvers,
})
})
return r
}
func getW(url string, f func(r *http.Request)) *httptest.ResponseRecorder {
r := SetUp()
req, _ := http.NewRequest("GET", url, nil)
f(req)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestHostMultiTenancy(t *testing.T) {
w := getW("/", func(r *http.Request) {
})
assert.Equal(t, http.StatusOK, w.Code)
var response map[string]interface{}
err := json.Unmarshal([]byte(w.Body.String()), &response)
value, exists := response["tenantId"]
assert.True(t, exists)
assert.Equal(t, "", value)
assert.Nil(t, err)
}
func TestNotFoundMultiTenancy(t *testing.T) {
w := getW("/", func(r *http.Request) {
r.Header.Set("__tenant", "1000")
})
assert.Equal(t, http.StatusNotFound, w.Code)
}
func TestCookieMultiTenancy(t *testing.T) {
w := getW("/", func(r *http.Request) {
r.AddCookie(&http.Cookie{
Name: "__tenant",
Value: "1",
Path: "",
Domain: "",
Expires: time.Time{},
RawExpires: "",
MaxAge: 0,
Secure: false,
HttpOnly: false,
SameSite: 0,
Raw: "",
Unparsed: nil,
})
})
assert.Equal(t, http.StatusOK, w.Code)
var response map[string]interface{}
err := json.Unmarshal([]byte(w.Body.String()), &response)
value, exists := response["tenantId"]
assert.True(t, exists)
assert.Equal(t, "1", value)
assert.Nil(t, err)
}
func TestHeaderMultiTenancy(t *testing.T) {
w := getW("/", func(r *http.Request) {
r.Header.Set("__tenant", "1")
})
assert.Equal(t, http.StatusOK, w.Code)
var response map[string]interface{}
err := json.Unmarshal([]byte(w.Body.String()), &response)
value, exists := response["tenantId"]
assert.True(t, exists)
assert.Equal(t, "1", value)
assert.Nil(t, err)
}