/
retriever_mock.go
65 lines (48 loc) · 1.51 KB
/
retriever_mock.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
package permissions
import (
"context"
"sync"
"testing"
)
type mockedMethods struct {
permissionsMock func(context.Context, []string, string, ...RetrieverOption) (PermissionMap, error)
}
// A MockRetriever allows to mock a permissions.Retriever for unit tests.
type MockRetriever interface {
Retriever
MockPermissions(t *testing.T, impl func(context.Context, []string, string, ...RetrieverOption) (PermissionMap, error))
}
type mockRetriever struct {
mocks map[*testing.T]*mockedMethods
currentTest *testing.T
sync.Mutex
}
// NewMockRetriever returns a MockRetriever.
func NewMockRetriever() MockRetriever {
return &mockRetriever{
mocks: map[*testing.T]*mockedMethods{},
}
}
// MockPermissions replaces the Permission implementation with the given function.
func (r *mockRetriever) MockPermissions(t *testing.T, impl func(context.Context, []string, string, ...RetrieverOption) (PermissionMap, error)) {
r.Lock()
defer r.Unlock()
r.currentMocks(t).permissionsMock = impl
}
func (r *mockRetriever) Permissions(ctx context.Context, claims []string, ns string, opts ...RetrieverOption) (PermissionMap, error) {
r.Lock()
defer r.Unlock()
if mock := r.currentMocks(r.currentTest); mock != nil && mock.permissionsMock != nil {
return mock.permissionsMock(ctx, claims, ns, opts...)
}
return PermissionMap{}, nil
}
func (r *mockRetriever) currentMocks(t *testing.T) *mockedMethods {
mocks := r.mocks[t]
if mocks == nil {
mocks = &mockedMethods{}
r.mocks[t] = mocks
}
r.currentTest = t
return mocks
}