github.com/thanos-io/thanos@v0.32.5/internal/cortex/tenant/resolver_test.go (about) 1 // Copyright (c) The Cortex Authors. 2 // Licensed under the Apache License 2.0. 3 4 package tenant 5 6 import ( 7 "context" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 "github.com/weaveworks/common/user" 12 ) 13 14 func strptr(s string) *string { 15 return &s 16 } 17 18 type resolverTestCase struct { 19 name string 20 headerValue *string 21 errTenantID error 22 errTenantIDs error 23 tenantID string 24 tenantIDs []string 25 } 26 27 func (tc *resolverTestCase) test(r Resolver) func(t *testing.T) { 28 return func(t *testing.T) { 29 30 ctx := context.Background() 31 if tc.headerValue != nil { 32 ctx = user.InjectOrgID(ctx, *tc.headerValue) 33 } 34 35 tenantID, err := r.TenantID(ctx) 36 if tc.errTenantID != nil { 37 assert.Equal(t, tc.errTenantID, err) 38 } else { 39 assert.NoError(t, err) 40 assert.Equal(t, tc.tenantID, tenantID) 41 } 42 43 tenantIDs, err := r.TenantIDs(ctx) 44 if tc.errTenantIDs != nil { 45 assert.Equal(t, tc.errTenantIDs, err) 46 } else { 47 assert.NoError(t, err) 48 assert.Equal(t, tc.tenantIDs, tenantIDs) 49 } 50 } 51 } 52 53 var commonResolverTestCases = []resolverTestCase{ 54 { 55 name: "no-header", 56 errTenantID: user.ErrNoOrgID, 57 errTenantIDs: user.ErrNoOrgID, 58 }, 59 { 60 name: "empty", 61 headerValue: strptr(""), 62 tenantIDs: []string{""}, 63 }, 64 { 65 name: "single-tenant", 66 headerValue: strptr("tenant-a"), 67 tenantID: "tenant-a", 68 tenantIDs: []string{"tenant-a"}, 69 }, 70 { 71 name: "parent-dir", 72 headerValue: strptr(".."), 73 errTenantID: errInvalidTenantID, 74 errTenantIDs: errInvalidTenantID, 75 }, 76 { 77 name: "current-dir", 78 headerValue: strptr("."), 79 errTenantID: errInvalidTenantID, 80 errTenantIDs: errInvalidTenantID, 81 }, 82 } 83 84 func TestSingleResolver(t *testing.T) { 85 r := NewSingleResolver() 86 for _, tc := range append(commonResolverTestCases, []resolverTestCase{ 87 { 88 name: "multi-tenant", 89 headerValue: strptr("tenant-a|tenant-b"), 90 tenantID: "tenant-a|tenant-b", 91 tenantIDs: []string{"tenant-a|tenant-b"}, 92 }, 93 { 94 name: "containing-forward-slash", 95 headerValue: strptr("forward/slash"), 96 errTenantID: errInvalidTenantID, 97 errTenantIDs: errInvalidTenantID, 98 }, 99 { 100 name: "containing-backward-slash", 101 headerValue: strptr(`backward\slash`), 102 errTenantID: errInvalidTenantID, 103 errTenantIDs: errInvalidTenantID, 104 }, 105 }...) { 106 t.Run(tc.name, tc.test(r)) 107 } 108 }