diff --git a/pkg/controller/usernames_test.go b/pkg/controller/usernames_test.go index a7551526..3fe507ff 100644 --- a/pkg/controller/usernames_test.go +++ b/pkg/controller/usernames_test.go @@ -1,21 +1,24 @@ package controller_test import ( + "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" - toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" "github.com/codeready-toolchain/registration-service/pkg/controller" + "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/username" "github.com/codeready-toolchain/registration-service/test" "github.com/codeready-toolchain/registration-service/test/fake" + commontest "github.com/codeready-toolchain/toolchain-common/pkg/test" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "sigs.k8s.io/controller-runtime/pkg/client" ) type TestUsernamesSuite struct { @@ -31,13 +34,13 @@ func (s *TestUsernamesSuite) TestUsernamesGetHandler() { req, err := http.NewRequest(http.MethodGet, "/api/v1/usernames", nil) require.NoError(s.T(), err) - fakeClient := fake.InitClient(s.T(), + fakeClient := commontest.NewFakeClient(s.T(), fake.NewMasterUserRecord("johnny"), ) s.Run("success", func() { - fakeInformer := fake.GetInformerService(fakeClient)() + fakeInformer := service.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(fakeInformer) // Create Usernames controller instance. @@ -97,9 +100,11 @@ func (s *TestUsernamesSuite) TestUsernamesGetHandler() { s.Run("error", func() { // force error while retrieving MUR - fakeInformer := fake.GetInformerService(fakeClient, fake.WithGetMurFunc(func(_ string) (*toolchainv1alpha1.MasterUserRecord, error) { - return nil, fmt.Errorf("mock error") - }))() + fakeClient := commontest.NewFakeClient(s.T()) + fakeClient.MockGet = func(_ context.Context, _ client.ObjectKey, _ client.Object, _ ...client.GetOption) error { + return fmt.Errorf("mock error") + } + fakeInformer := service.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(fakeInformer) // Create Usernames controller instance. diff --git a/pkg/proxy/handlers/spacelister_get_test.go b/pkg/proxy/handlers/spacelister_get_test.go index 2328fcb6..762cd3e1 100644 --- a/pkg/proxy/handlers/spacelister_get_test.go +++ b/pkg/proxy/handlers/spacelister_get_test.go @@ -12,6 +12,7 @@ import ( toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" "github.com/codeready-toolchain/registration-service/pkg/application/service" rcontext "github.com/codeready-toolchain/registration-service/pkg/context" + infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/proxy/handlers" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" proxytest "github.com/codeready-toolchain/registration-service/pkg/proxy/test" @@ -20,14 +21,12 @@ import ( commoncluster "github.com/codeready-toolchain/toolchain-common/pkg/cluster" commonproxy "github.com/codeready-toolchain/toolchain-common/pkg/proxy" "github.com/codeready-toolchain/toolchain-common/pkg/test" - spacetest "github.com/codeready-toolchain/toolchain-common/pkg/test/space" spacebindingrequesttest "github.com/codeready-toolchain/toolchain-common/pkg/test/spacebindingrequest" "github.com/gin-gonic/gin" "github.com/labstack/echo/v4" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/labels" runtimeclient "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -47,9 +46,8 @@ func TestSpaceListerGet(t *testing.T) { } func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { - fakeSignupService, fakeClient := buildSpaceListerFakes(t) - memberFakeClient := fake.InitClient(t, + memberFakeClient := test.NewFakeClient(t, // spacebinding requests spacebindingrequesttest.NewSpaceBindingRequest("animelover-sbr", "dancelover-dev", spacebindingrequesttest.WithSpaceRole("viewer"), @@ -63,7 +61,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { ), ) - memberClientErrorList := fake.InitClient(t) + memberClientErrorList := test.NewFakeClient(t) memberClientErrorList.MockList = func(ctx context.Context, list runtimeclient.ObjectList, opts ...runtimeclient.ListOption) error { if _, ok := list.(*toolchainv1alpha1.SpaceBindingRequestList); ok { return fmt.Errorf("mock list error") @@ -75,19 +73,19 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { // given tests := map[string]struct { username string - expectedWs []toolchainv1alpha1.Workspace + expectedWs func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace expectedErr string expectedErrCode int expectedWorkspace string overrideSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupComplete bool) (*signup.Signup, error) - overrideInformerFunc func() service.InformerService + mockFakeClient func(fakeClient *test.FakeClient) overrideGetMembersFunc func(conditions ...commoncluster.Condition) []*commoncluster.CachedToolchainCluster overrideMemberClient *test.FakeClient }{ "dancelover gets dancelover space": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "dancelover", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "dancelover", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }, @@ -117,15 +115,15 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { }, }, }), - ), + )} }, expectedErr: "", expectedWorkspace: "dancelover", }, "dancelover gets movielover space": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "movielover", "other", false, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "movielover", "other", false, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -150,15 +148,15 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string(nil), // this is system generated so no actions for the user }, }), - ), + )} }, expectedErr: "", expectedWorkspace: "movielover", }, "dancelover gets foodlover space": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "foodlover", "admin", false, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "foodlover", "admin", false, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -174,15 +172,15 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string{"override"}, // since the binding is inherited from parent space, then it can only be overridden }, }), - ), + )} }, expectedErr: "", expectedWorkspace: "foodlover", }, "movielover gets movielover space": { username: "movie.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "movielover", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "movielover", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -208,22 +206,22 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string(nil), // this is system generated so no actions for the user }, }), - ), + )} }, expectedErr: "", expectedWorkspace: "movielover", }, "movielover cannot get dancelover space": { username: "movie.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"dancelover\\\" not found\"", expectedWorkspace: "dancelover", expectedErrCode: 404, }, "signup not ready yet": { username: "movie.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "movielover", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "movielover", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -248,27 +246,29 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string(nil), // this is system generated so no actions for the user }, }), - ), + )} }, expectedErr: "", expectedWorkspace: "movielover", }, "get nstemplatetier error": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "nstemplatetier error", expectedErrCode: 500, - overrideInformerFunc: func() service.InformerService { - informerFunc := fake.GetInformerService(fakeClient, fake.WithGetNSTemplateTierFunc(func(_ string) (*toolchainv1alpha1.NSTemplateTier, error) { - return nil, fmt.Errorf("nstemplatetier error") - })) - return informerFunc() + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockGet = func(ctx context.Context, key runtimeclient.ObjectKey, obj runtimeclient.Object, opts ...runtimeclient.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.NSTemplateTier); ok && key.Name == "base1ns" { + return fmt.Errorf("nstemplatetier error") + } + return fakeClient.Client.Get(ctx, key, obj, opts...) + } }, expectedWorkspace: "dancelover", }, "get signup error": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "signup error", expectedErrCode: 500, overrideSignupFunc: func(_ *gin.Context, _, _ string, _ bool) (*signup.Signup, error) { @@ -278,63 +278,64 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { }, "signup has no compliant username set": { username: "racing.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"racinglover\\\" not found\"", expectedErrCode: 404, expectedWorkspace: "racinglover", }, "list spacebindings error": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "list spacebindings error", expectedErrCode: 500, - overrideInformerFunc: func() service.InformerService { - listSpaceBindingFunc := func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return nil, fmt.Errorf("list spacebindings error") + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockList = func(ctx context.Context, list runtimeclient.ObjectList, opts ...runtimeclient.ListOption) error { + if _, ok := list.(*toolchainv1alpha1.SpaceBindingList); ok { + return fmt.Errorf("list spacebindings error") + } + return fakeClient.Client.List(ctx, list, opts...) } - return fake.GetInformerService(fakeClient, fake.WithListSpaceBindingFunc(listSpaceBindingFunc))() }, expectedWorkspace: "dancelover", }, "unable to get space": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"dancelover\\\" not found\"", expectedErrCode: 404, - overrideInformerFunc: func() service.InformerService { - getSpaceFunc := func(_ string) (*toolchainv1alpha1.Space, error) { - return nil, fmt.Errorf("no space") + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockGet = func(ctx context.Context, key runtimeclient.ObjectKey, obj runtimeclient.Object, opts ...runtimeclient.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.Space); ok && key.Name == "dancelover" { + return fmt.Errorf("no space") + } + return fakeClient.Client.Get(ctx, key, obj, opts...) } - return fake.GetInformerService(fakeClient, fake.WithGetSpaceFunc(getSpaceFunc))() }, expectedWorkspace: "dancelover", }, "unable to get parent-space": { username: "food.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "Internal error occurred: unable to get parent-space: parent-space error", expectedErrCode: 500, - overrideInformerFunc: func() service.InformerService { - getSpaceFunc := func(name string) (*toolchainv1alpha1.Space, error) { - if name == "dancelover" { - // return the error only when trying to get the parent space - return nil, fmt.Errorf("parent-space error") + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockGet = func(ctx context.Context, key runtimeclient.ObjectKey, obj runtimeclient.Object, opts ...runtimeclient.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.Space); ok && key.Name == "dancelover" { + return fmt.Errorf("parent-space error") } - // return the foodlover space - return fake.NewSpace("foodlover", "member-2", "foodlover", spacetest.WithSpecParentSpace("dancelover")), nil + return fakeClient.Client.Get(ctx, key, obj, opts...) } - return fake.GetInformerService(fakeClient, fake.WithGetSpaceFunc(getSpaceFunc))() }, expectedWorkspace: "foodlover", }, "error spaceBinding request has no name": { username: "anime.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "animelover", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "animelover", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), - ), + )} }, expectedErr: "Internal error occurred: SpaceBindingRequest name not found on binding: carlover-sb-from-sbr", expectedErrCode: 500, @@ -342,12 +343,12 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { }, "error spaceBinding request has no namespace set": { username: "car.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "carlover", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "carlover", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), - ), + )} }, expectedErr: "Internal error occurred: SpaceBindingRequest namespace not found on binding: animelover-sb-from-sbr", expectedErrCode: 500, @@ -355,8 +356,8 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { }, "parent can list parentspace": { username: "parent.space", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "parentspace", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "parentspace", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -367,14 +368,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string(nil), // this is system generated so no actions for the user }, }), - ), + )} }, expectedWorkspace: "parentspace", }, "parent can list childspace": { username: "parent.space", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "childspace", "admin", false, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "childspace", "admin", false, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -390,14 +391,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string{"override"}, }, }), - ), + )} }, expectedWorkspace: "childspace", }, "parent can list grandchildspace": { username: "parent.space", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "grandchildspace", "admin", false, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "grandchildspace", "admin", false, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -418,13 +419,13 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string{"override"}, }, }), - ), + )} }, expectedWorkspace: "grandchildspace", }, "child cannot list parentspace": { username: "child.space", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"parentspace\\\" not found\"", expectedErrCode: 404, expectedWorkspace: "parentspace", @@ -432,8 +433,8 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { "child can list childspace": { username: "child.space", expectedWorkspace: "childspace", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "childspace", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "childspace", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -449,14 +450,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string{"override"}, }, }), - ), + )} }, }, "child can list grandchildspace": { username: "child.space", expectedWorkspace: "grandchildspace", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "grandchildspace", "admin", false, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "grandchildspace", "admin", false, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -477,13 +478,13 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string{"override"}, }, }), - ), + )} }, }, "grandchild can list grandchildspace": { username: "grandchild.space", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "grandchildspace", "admin", true, + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "grandchildspace", "admin", true, commonproxy.WithAvailableRoles([]string{ "admin", "viewer", }), @@ -504,7 +505,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { AvailableActions: []string{"override"}, }, }), - ), + )} }, expectedWorkspace: "grandchildspace", }, @@ -513,14 +514,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "parentspace", expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"parentspace\\\" not found\"", expectedErrCode: 404, - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, }, "grandchild cannot list childspace": { username: "grandchild.space", expectedWorkspace: "childspace", expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"childspace\\\" not found\"", expectedErrCode: 404, - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, }, "no member clusters found": { username: "movie.lover", @@ -543,22 +544,24 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { for k, tc := range tests { t.Run(k, func(t *testing.T) { // given + fakeSignupService, fakeClient := buildSpaceListerFakes(t) + if tc.mockFakeClient != nil { + tc.mockFakeClient(fakeClient) + } + signupProvider := fakeSignupService.GetSignupFromInformer if tc.overrideSignupFunc != nil { signupProvider = tc.overrideSignupFunc } - informerFunc := fake.GetInformerService(fakeClient) - if tc.overrideInformerFunc != nil { - informerFunc = tc.overrideInformerFunc - } - proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ - GetSignupFunc: signupProvider, - GetInformerServiceFunc: informerFunc, - ProxyMetrics: proxyMetrics, + GetSignupFunc: signupProvider, + GetInformerServiceFunc: func() service.InformerService { + return infservice.NewInformerService(fakeClient, test.HostOperatorNs) + }, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -592,10 +595,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { // get workspace case workspace, decodeErr := decodeResponseToWorkspace(rec.Body.Bytes()) require.NoError(t, decodeErr) - require.Len(t, tc.expectedWs, 1, "test case should have exactly one expected item since it's a get request") - for i := range tc.expectedWs { - assert.Equal(t, tc.expectedWs[i].Name, workspace.Name) - assert.Equal(t, tc.expectedWs[i].Status, workspace.Status) + var expectedWorkspaces []toolchainv1alpha1.Workspace + if tc.expectedWs != nil { + expectedWorkspaces = tc.expectedWs(t, fakeClient) + } + require.Len(t, expectedWorkspaces, 1, "test case should have exactly one expected item since it's a get request") + for i := range expectedWorkspaces { + assert.Equal(t, expectedWorkspaces[i].Name, workspace.Name) + assert.Equal(t, expectedWorkspaces[i].Status, workspace.Status) } } }) @@ -610,32 +617,20 @@ func TestGetUserWorkspace(t *testing.T) { newSignup("robin", "robin.space", true), ) - fakeClient := fake.InitClient(t, - // space - fake.NewSpace("batman", "member-1", "batman"), - fake.NewSpace("robin", "member-1", "robin"), - - fake.NewSpaceBinding("robin-1", "robin", "robin", "admin"), - // 2 spacebindings to force the error - fake.NewSpaceBinding("batman-1", "batman", "batman", "admin"), - fake.NewSpaceBinding("batman-2", "batman", "batman", "maintainer"), - fake.NewSpaceBinding("community-robin", toolchainv1alpha1.KubesawAuthenticatedUsername, "robin", "viewer"), - ) - - robinWS := workspaceFor(t, fakeClient, "robin", "admin", true) - tests := map[string]struct { - username string - expectedErr string - workspaceRequest string - expectedWorkspace *toolchainv1alpha1.Workspace - overrideInformerFunc func() service.InformerService - overrideSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupComplete bool) (*signup.Signup, error) + username string + expectedErr string + workspaceRequest string + expectedWorkspace func(t *testing.T, fakeClient *test.FakeClient) toolchainv1alpha1.Workspace + mockFakeClient func(fakeClient *test.FakeClient) + overrideSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupComplete bool) (*signup.Signup, error) }{ "get robin workspace": { - username: "robin.space", - workspaceRequest: "robin", - expectedWorkspace: &robinWS, + username: "robin.space", + workspaceRequest: "robin", + expectedWorkspace: func(t *testing.T, fakeClient *test.FakeClient) toolchainv1alpha1.Workspace { + return workspaceFor(t, fakeClient, "robin", "admin", true) + }, }, "invalid number of spacebindings": { username: "batman.space", @@ -654,22 +649,26 @@ func TestGetUserWorkspace(t *testing.T) { "space not found": { username: "invalid.user", workspaceRequest: "batman", - overrideInformerFunc: func() service.InformerService { - getSpaceFunc := func(_ string) (*toolchainv1alpha1.Space, error) { - return nil, fmt.Errorf("no space") + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockGet = func(ctx context.Context, key runtimeclient.ObjectKey, obj runtimeclient.Object, opts ...runtimeclient.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.Space); ok { + return fmt.Errorf("no space") + } + return fakeClient.Client.Get(ctx, key, obj, opts...) } - return fake.GetInformerService(fakeClient, fake.WithGetSpaceFunc(getSpaceFunc))() }, expectedWorkspace: nil, // user is not authorized }, "error getting usersignup": { username: "invalid.user", workspaceRequest: "batman", - overrideInformerFunc: func() service.InformerService { - getSpaceFunc := func(_ string) (*toolchainv1alpha1.Space, error) { - return nil, fmt.Errorf("no space") + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockGet = func(ctx context.Context, key runtimeclient.ObjectKey, obj runtimeclient.Object, opts ...runtimeclient.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.Space); ok { + return fmt.Errorf("no space") + } + return fakeClient.Client.Get(ctx, key, obj, opts...) } - return fake.GetInformerService(fakeClient, fake.WithGetSpaceFunc(getSpaceFunc))() }, expectedWorkspace: nil, // user is not authorized }, @@ -686,11 +685,13 @@ func TestGetUserWorkspace(t *testing.T) { username: "robin.space", workspaceRequest: "robin", expectedErr: "list spacebindings error", - overrideInformerFunc: func() service.InformerService { - listSpaceBindingFunc := func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return nil, fmt.Errorf("list spacebindings error") + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockList = func(ctx context.Context, list runtimeclient.ObjectList, opts ...runtimeclient.ListOption) error { + if _, ok := list.(*toolchainv1alpha1.SpaceBindingList); ok { + return fmt.Errorf("list spacebindings error") + } + return fakeClient.Client.List(ctx, list, opts...) } - return fake.GetInformerService(fakeClient, fake.WithListSpaceBindingFunc(listSpaceBindingFunc))() }, expectedWorkspace: nil, }, @@ -711,20 +712,33 @@ func TestGetUserWorkspace(t *testing.T) { for k, tc := range tests { t.Run(k, func(t *testing.T) { // given + fakeClient := test.NewFakeClient(t, + // space + fake.NewSpace("batman", "member-1", "batman"), + fake.NewSpace("robin", "member-1", "robin"), + + fake.NewSpaceBinding("robin-1", "robin", "robin", "admin"), + // 2 spacebindings to force the error + fake.NewSpaceBinding("batman-1", "batman", "batman", "admin"), + fake.NewSpaceBinding("batman-2", "batman", "batman", "maintainer"), + fake.NewSpaceBinding("community-robin", toolchainv1alpha1.KubesawAuthenticatedUsername, "robin", "viewer"), + ) + if tc.mockFakeClient != nil { + tc.mockFakeClient(fakeClient) + } + signupProvider := fakeSignupService.GetSignupFromInformer if tc.overrideSignupFunc != nil { signupProvider = tc.overrideSignupFunc } - informerFunc := fake.GetInformerService(fakeClient) - if tc.overrideInformerFunc != nil { - informerFunc = tc.overrideInformerFunc - } proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ - GetSignupFunc: signupProvider, - GetInformerServiceFunc: informerFunc, - ProxyMetrics: proxyMetrics, + GetSignupFunc: signupProvider, + GetInformerServiceFunc: func() service.InformerService { + return infservice.NewInformerService(fakeClient, test.HostOperatorNs) + }, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -748,7 +762,7 @@ func TestGetUserWorkspace(t *testing.T) { } if tc.expectedWorkspace != nil { - require.Equal(t, tc.expectedWorkspace, wrk) + require.Equal(t, tc.expectedWorkspace(t, fakeClient), *wrk) } else { require.Nil(t, wrk) // user is not authorized to get this workspace } @@ -764,7 +778,7 @@ func TestSpaceListerGetPublicViewerEnabled(t *testing.T) { newSignup("gordon", "gordon.no-space", false), ) - fakeClient := fake.InitClient(t, + fakeClient := test.NewFakeClient(t, // space fake.NewSpace("robin", "member-1", "robin"), fake.NewSpace("batman", "member-1", "batman"), @@ -826,13 +840,14 @@ func TestSpaceListerGetPublicViewerEnabled(t *testing.T) { t.Run(k, func(t *testing.T) { // given signupProvider := fakeSignupService.GetSignupFromInformer - informerFunc := fake.GetInformerService(fakeClient) proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ - GetSignupFunc: signupProvider, - GetInformerServiceFunc: informerFunc, - ProxyMetrics: proxyMetrics, + GetSignupFunc: signupProvider, + GetInformerServiceFunc: func() service.InformerService { + return infservice.NewInformerService(fakeClient, test.HostOperatorNs) + }, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -868,7 +883,7 @@ func TestGetUserWorkspaceWithBindingsWithPublicViewerEnabled(t *testing.T) { newSignup("gordon", "gordon.no-space", false), ) - fakeClient := fake.InitClient(t, + fakeClient := test.NewFakeClient(t, // NSTemplateTiers fake.NewBase1NSTemplateTier(), @@ -962,13 +977,14 @@ func TestGetUserWorkspaceWithBindingsWithPublicViewerEnabled(t *testing.T) { t.Run(k, func(t *testing.T) { // given signupProvider := fakeSignupService.GetSignupFromInformer - informerFunc := fake.GetInformerService(fakeClient) proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ - GetSignupFunc: signupProvider, - GetInformerServiceFunc: informerFunc, - ProxyMetrics: proxyMetrics, + GetSignupFunc: signupProvider, + GetInformerServiceFunc: func() service.InformerService { + return infservice.NewInformerService(fakeClient, test.HostOperatorNs) + }, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -984,7 +1000,7 @@ func TestGetUserWorkspaceWithBindingsWithPublicViewerEnabled(t *testing.T) { getMembersFuncMock := func(_ ...commoncluster.Condition) []*commoncluster.CachedToolchainCluster { return []*commoncluster.CachedToolchainCluster{ { - Client: fake.InitClient(t), + Client: test.NewFakeClient(t), Config: &commoncluster.Config{ Name: "not-me", }, diff --git a/pkg/proxy/handlers/spacelister_list_test.go b/pkg/proxy/handlers/spacelister_list_test.go index 1402f367..7ca5eff4 100644 --- a/pkg/proxy/handlers/spacelister_list_test.go +++ b/pkg/proxy/handlers/spacelister_list_test.go @@ -1,6 +1,7 @@ package handlers_test import ( + "context" "fmt" "net/http" "net/http/httptest" @@ -8,13 +9,14 @@ import ( "testing" "time" + infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/gin-gonic/gin" "github.com/labstack/echo/v4" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" + runtimeclient "sigs.k8s.io/controller-runtime/pkg/client" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" "github.com/codeready-toolchain/registration-service/pkg/application/service" @@ -71,14 +73,15 @@ func TestListUserWorkspaces(t *testing.T) { t.Run(k, func(t *testing.T) { // given signupProvider := fakeSignupService.GetSignupFromInformer - informerFunc := fake.GetInformerService(fakeClient) proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ - GetSignupFunc: signupProvider, - GetInformerServiceFunc: informerFunc, - ProxyMetrics: proxyMetrics, + GetSignupFunc: signupProvider, + GetInformerServiceFunc: func() service.InformerService { + return infservice.NewInformerService(fakeClient, test.HostOperatorNs) + }, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -114,68 +117,72 @@ func TestHandleSpaceListRequest(t *testing.T) { } for k, rtc := range tt { - fakeSignupService, fakeClient := buildSpaceListerFakes(t) t.Run(k, func(t *testing.T) { // given tests := map[string]struct { - username string - expectedWs []toolchainv1alpha1.Workspace - expectedErr string - expectedErrCode int - expectedWorkspace string - overrideSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupComplete bool) (*signup.Signup, error) - overrideInformerFunc func() service.InformerService + username string + expectedWs func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace + expectedErr string + expectedErrCode int + expectedWorkspace string + overrideSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupComplete bool) (*signup.Signup, error) + mockFakeClient func(fakeClient *test.FakeClient) }{ "dancelover lists spaces": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "dancelover", "admin", true), - workspaceFor(t, fakeClient, "movielover", "other", false), + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{ + workspaceFor(t, fakeClient, "dancelover", "admin", true), + workspaceFor(t, fakeClient, "movielover", "other", false), + } }, expectedErr: "", }, "movielover lists spaces": { username: "movie.lover", - expectedWs: []toolchainv1alpha1.Workspace{ - workspaceFor(t, fakeClient, "movielover", "admin", true), + expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { + return []toolchainv1alpha1.Workspace{ + workspaceFor(t, fakeClient, "movielover", "admin", true), + } }, expectedErr: "", }, "signup has no compliant username set": { username: "racing.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "", expectedErrCode: 200, }, "space not initialized yet": { username: "panda.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "", expectedErrCode: 200, }, "no spaces found": { username: "user.nospace", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "", expectedErrCode: 200, }, "informer error": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "list spacebindings error", expectedErrCode: 500, - overrideInformerFunc: func() service.InformerService { - inf := fake.NewFakeInformer() - inf.ListSpaceBindingFunc = func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return nil, fmt.Errorf("list spacebindings error") + mockFakeClient: func(fakeClient *test.FakeClient) { + fakeClient.MockList = func(ctx context.Context, list runtimeclient.ObjectList, opts ...runtimeclient.ListOption) error { + if _, ok := list.(*toolchainv1alpha1.SpaceBindingList); ok { + return fmt.Errorf("list spacebindings error") + } + return fakeClient.Client.List(ctx, list, opts...) } - return inf }, }, "get signup error": { username: "dance.lover", - expectedWs: []toolchainv1alpha1.Workspace{}, + expectedWs: nil, expectedErr: "signup error", expectedErrCode: 500, overrideSignupFunc: func(_ *gin.Context, _, _ string, _ bool) (*signup.Signup, error) { @@ -187,22 +194,24 @@ func TestHandleSpaceListRequest(t *testing.T) { for k, tc := range tests { t.Run(k, func(t *testing.T) { // given + fakeSignupService, fakeClient := buildSpaceListerFakes(t) + if tc.mockFakeClient != nil { + tc.mockFakeClient(fakeClient) + } + signupProvider := fakeSignupService.GetSignupFromInformer if tc.overrideSignupFunc != nil { signupProvider = tc.overrideSignupFunc } - informerFunc := fake.GetInformerService(fakeClient) - if tc.overrideInformerFunc != nil { - informerFunc = tc.overrideInformerFunc - } - proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ - GetSignupFunc: signupProvider, - GetInformerServiceFunc: informerFunc, - ProxyMetrics: proxyMetrics, + GetSignupFunc: signupProvider, + GetInformerServiceFunc: func() service.InformerService { + return infservice.NewInformerService(fakeClient, test.HostOperatorNs) + }, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -226,10 +235,14 @@ func TestHandleSpaceListRequest(t *testing.T) { // list workspace case workspaceList, decodeErr := decodeResponseToWorkspaceList(rec.Body.Bytes()) require.NoError(t, decodeErr) - require.Equal(t, len(tc.expectedWs), len(workspaceList.Items)) - for i := range tc.expectedWs { - assert.Equal(t, tc.expectedWs[i].Name, workspaceList.Items[i].Name) - assert.Equal(t, tc.expectedWs[i].Status, workspaceList.Items[i].Status) + var expectedWorkspaces []toolchainv1alpha1.Workspace + if tc.expectedWs != nil { + expectedWorkspaces = tc.expectedWs(t, fakeClient) + } + require.Equal(t, len(expectedWorkspaces), len(workspaceList.Items)) + for i := range expectedWorkspaces { + assert.Equal(t, expectedWorkspaces[i].Name, workspaceList.Items[i].Name) + assert.Equal(t, expectedWorkspaces[i].Status, workspaceList.Items[i].Status) } } }) diff --git a/pkg/proxy/handlers/spacelister_test.go b/pkg/proxy/handlers/spacelister_test.go index f03b465d..240914f9 100644 --- a/pkg/proxy/handlers/spacelister_test.go +++ b/pkg/proxy/handlers/spacelister_test.go @@ -13,7 +13,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" - "github.com/codeready-toolchain/registration-service/pkg/configuration" "github.com/codeready-toolchain/registration-service/pkg/signup" "github.com/codeready-toolchain/registration-service/test/fake" commonproxy "github.com/codeready-toolchain/toolchain-common/pkg/proxy" @@ -100,9 +99,8 @@ func buildSpaceListerFakesWithResources(t *testing.T, signups []fake.SignupDef, //nstemplatetier fake.NewBase1NSTemplateTier(), ) - fakeClient := fake.InitClient(t, oo...) - return fakeSignupService, fakeClient + return fakeSignupService, test.NewFakeClient(t, oo...) } func newSignup(signupName, username string, ready bool) fake.SignupDef { @@ -146,7 +144,7 @@ func decodeResponseToWorkspaceList(data []byte) (*toolchainv1alpha1.WorkspaceLis func workspaceFor(t *testing.T, fakeClient client.Client, name, role string, isHomeWorkspace bool, additionalWSOptions ...commonproxy.WorkspaceOption) toolchainv1alpha1.Workspace { // get the space for the user space := &toolchainv1alpha1.Space{} - err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: configuration.Namespace()}, space) + err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: test.HostOperatorNs}, space) require.NoError(t, err) // create the workspace based on the space diff --git a/pkg/proxy/proxy_test.go b/pkg/proxy/proxy_test.go index 43902df1..6bd9ad6c 100644 --- a/pkg/proxy/proxy_test.go +++ b/pkg/proxy/proxy_test.go @@ -19,7 +19,7 @@ import ( appservice "github.com/codeready-toolchain/registration-service/pkg/application/service" "github.com/codeready-toolchain/registration-service/pkg/auth" - "github.com/codeready-toolchain/registration-service/pkg/configuration" + infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/proxy/access" "github.com/codeready-toolchain/registration-service/pkg/proxy/handlers" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" @@ -29,6 +29,7 @@ import ( "github.com/codeready-toolchain/registration-service/test" "github.com/codeready-toolchain/registration-service/test/fake" "github.com/prometheus/client_golang/prometheus" + "k8s.io/client-go/kubernetes/scheme" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" commoncluster "github.com/codeready-toolchain/toolchain-common/pkg/cluster" @@ -43,7 +44,6 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" @@ -61,7 +61,7 @@ var ( bannedUser = toolchainv1alpha1.BannedUser{ ObjectMeta: metav1.ObjectMeta{ Name: "alice", - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.BannedUserEmailHashLabelKey: hash.EncodeString("alice@redhat.com"), }, @@ -91,24 +91,24 @@ func (s *TestProxySuite) TestProxy() { s.SetConfig(testconfig.RegistrationService(). Environment(string(environment))) - inf := fake.GetInformerService( - fake.InitClient(s.T()), - fake.WithGetBannedUsersByEmailFunc(func(email string) ([]toolchainv1alpha1.BannedUser, error) { - switch email { - case bannedUser.Spec.Email: - return []toolchainv1alpha1.BannedUser{bannedUser}, nil - case bannedUserListErrorEmailValue: - return nil, fmt.Errorf("list banned user error") - default: - return nil, nil - } - }))() + fakeClient := commontest.NewFakeClient(s.T(), &bannedUser) + fakeClient.MockList = func(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + listOptions := &client.ListOptions{} + for _, opt := range opts { + opt.ApplyToList(listOptions) + } + if strings.Contains(listOptions.LabelSelector.String(), hash.EncodeString(bannedUserListErrorEmailValue)) { + return fmt.Errorf("list banned user error") + } + return fakeClient.Client.List(ctx, list, opts...) + } + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) fakeApp := &fake.ProxyFakeApp{ InformerServiceMock: inf, } proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) - p, err := newProxyWithClusterClient(fakeApp, nil, proxyMetrics, proxytest.NewGetMembersFunc(fake.InitClient(s.T()))) + p, err := newProxyWithClusterClient(fakeApp, nil, proxyMetrics, proxytest.NewGetMembersFunc(commontest.NewFakeClient(s.T()))) require.NoError(s.T(), err) server := p.StartProxy(DefaultPort) @@ -724,49 +724,28 @@ func (s *TestProxySuite) checkProxyOK(fakeApp *fake.ProxyFakeApp, p *Proxy) { }), ) s.Application.MockSignupService(fakeApp.SignupServiceMock) - inf := fake.NewFakeInformer() - inf.GetSpaceFunc = func(name string) (*toolchainv1alpha1.Space, error) { - switch name { - case "mycoolworkspace": - return fake.NewSpace("mycoolworkspace", "member-2", "smith2"), nil - } - return nil, fmt.Errorf("space not found error") - } - inf.ListSpaceBindingFunc = func(reqs ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - // always return a spacebinding for the purposes of the proxy tests, actual testing of the space lister is covered in the space lister tests - spaceBindings := []toolchainv1alpha1.SpaceBinding{} - for _, req := range reqs { - if req.Values().List()[0] == "smith2" || req.Values().List()[0] == "mycoolworkspace" { - spaceBindings = []toolchainv1alpha1.SpaceBinding{*fake.NewSpaceBinding("mycoolworkspace-smith2", "smith2", "mycoolworkspace", "admin")} - } - } - return spaceBindings, nil - } - inf.GetProxyPluginConfigFunc = func(name string) (*toolchainv1alpha1.ProxyPlugin, error) { - switch name { - case "myplugin": - return &toolchainv1alpha1.ProxyPlugin{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: metav1.NamespaceDefault, - Name: "myplugin", - }, - Spec: toolchainv1alpha1.ProxyPluginSpec{ - OpenShiftRouteTargetEndpoint: &toolchainv1alpha1.OpenShiftRouteTarget{ - Namespace: metav1.NamespaceDefault, - Name: metav1.NamespaceDefault, - }, - }, - Status: toolchainv1alpha1.ProxyPluginStatus{}, - }, nil - } - return nil, fmt.Errorf("proxy plugin not found") - } - inf.GetNSTemplateTierFunc = func(_ string) (*toolchainv1alpha1.NSTemplateTier, error) { - return fake.NewBase1NSTemplateTier(), nil - } - inf.ListBannedUsersByEmailFunc = func(_ string) ([]toolchainv1alpha1.BannedUser, error) { - return nil, nil + + proxyPlugin := &toolchainv1alpha1.ProxyPlugin{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: commontest.HostOperatorNs, + Name: "myplugin", + }, + Spec: toolchainv1alpha1.ProxyPluginSpec{ + OpenShiftRouteTargetEndpoint: &toolchainv1alpha1.OpenShiftRouteTarget{ + Namespace: commontest.HostOperatorNs, + Name: "proxy-plugin", + }, + }, + Status: toolchainv1alpha1.ProxyPluginStatus{}, } + require.NoError(s.T(), routev1.Install(scheme.Scheme)) + fakeClient := commontest.NewFakeClient(s.T(), + fake.NewSpace("mycoolworkspace", "member-2", "smith2"), + fake.NewSpaceBinding("mycoolworkspace-smith2", "smith2", "mycoolworkspace", "admin"), + proxyPlugin, + fake.NewBase1NSTemplateTier()) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) + s.Application.MockInformerService(inf) fakeApp.MemberClusterServiceMock = s.newMemberClusterServiceWithMembers(testServer.URL) @@ -811,7 +790,6 @@ type headerToAdd struct { } func (s *TestProxySuite) newMemberClusterServiceWithMembers(serverURL string) appservice.MemberClusterService { - fakeClient := commontest.NewFakeClient(s.T()) serverHost := serverURL switch { case strings.HasPrefix(serverURL, "http://"): @@ -819,21 +797,24 @@ func (s *TestProxySuite) newMemberClusterServiceWithMembers(serverURL string) ap case strings.HasPrefix(serverURL, "https://"): serverHost = strings.TrimPrefix(serverURL, "https://") } - fakeClient.MockGet = func(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { - route, ok := obj.(*routev1.Route) - if ok && key.Namespace == metav1.NamespaceDefault && key.Name == metav1.NamespaceDefault { - route.Namespace = key.Namespace - route.Name = key.Name - route.Spec.Port = &routev1.RoutePort{TargetPort: intstr.FromString("http")} - route.Status.Ingress = []routev1.RouteIngress{ + + route := &routev1.Route{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: commontest.HostOperatorNs, + Name: "proxy-plugin", + }, + Spec: routev1.RouteSpec{ + Port: &routev1.RoutePort{TargetPort: intstr.FromString("http")}, + }, + Status: routev1.RouteStatus{ + Ingress: []routev1.RouteIngress{ { Host: serverHost, }, - } - return nil - } - return fakeClient.Client.Get(ctx, key, obj, opts...) + }, + }, } + fakeClient := commontest.NewFakeClient(s.T(), route) return service.NewMemberClusterService( fake.MemberClusterServiceContext{ CrtClient: s, diff --git a/pkg/proxy/service/cluster_service_test.go b/pkg/proxy/service/cluster_service_test.go index 408b94ec..3379f0b2 100644 --- a/pkg/proxy/service/cluster_service_test.go +++ b/pkg/proxy/service/cluster_service_test.go @@ -7,6 +7,7 @@ import ( "net/url" "testing" + infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/proxy/access" "github.com/codeready-toolchain/registration-service/pkg/proxy/service" "github.com/codeready-toolchain/registration-service/pkg/signup" @@ -69,35 +70,25 @@ func (s *TestClusterServiceSuite) TestGetClusterAccess() { })) s.Application.MockSignupService(sc) - inf := fake.NewFakeInformer() - inf.GetSpaceFunc = func(name string) (*toolchainv1alpha1.Space, error) { - switch name { - case "noise1", "teamspace": - return fake.NewSpace(name, "member-1", name), nil - case "smith2": - return fake.NewSpace(name, "member-2", name), nil - case "unknown-cluster": - return fake.NewSpace(name, "unknown-cluster", name), nil - } - return nil, fmt.Errorf("space not found error") - } - inf.GetProxyPluginConfigFunc = func(name string) (*toolchainv1alpha1.ProxyPlugin, error) { - if name != "tekton-results" { - return nil, errors.New("not found") - } - pp := &toolchainv1alpha1.ProxyPlugin{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - Spec: toolchainv1alpha1.ProxyPluginSpec{ - OpenShiftRouteTargetEndpoint: &toolchainv1alpha1.OpenShiftRouteTarget{ - Namespace: "tekton-results", - Name: "tekton-results", - }, + pp := &toolchainv1alpha1.ProxyPlugin{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tekton-results", + Namespace: commontest.HostOperatorNs, + }, + Spec: toolchainv1alpha1.ProxyPluginSpec{ + OpenShiftRouteTargetEndpoint: &toolchainv1alpha1.OpenShiftRouteTarget{ + Namespace: "tekton-results", + Name: "tekton-results", }, - } - return pp, nil + }, } + fakeClient := commontest.NewFakeClient(s.T(), + fake.NewSpace("noise1", "member-1", "noise1"), + fake.NewSpace("teamspace", "member-1", "teamspace"), + fake.NewSpace("smith2", "member-2", "smith2"), + fake.NewSpace("unknown-cluster", "unknown-cluster", "unknown-cluster"), + pp) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewMemberClusterService( @@ -172,14 +163,16 @@ func (s *TestClusterServiceSuite) TestGetClusterAccess() { s.Run("unable to get space", func() { s.Run("informer service returns error", func() { - original := inf.GetSpaceFunc - defer func() { // restore original GetSpaceFunc after test - inf.GetSpaceFunc = original - s.Application.MockInformerService(inf) - }() - inf.GetSpaceFunc = func(_ string) (*toolchainv1alpha1.Space, error) { // informer error - return nil, fmt.Errorf("oopsi woopsi") + fakeClient.MockGet = func(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.Space); ok && key.Name == "smith2" { + return fmt.Errorf("oopsi woopsi") + } + return fakeClient.Client.Get(ctx, key, obj, opts...) } + defer func() { + fakeClient.MockGet = nil + }() + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) // when diff --git a/pkg/signup/service/signup_service_test.go b/pkg/signup/service/signup_service_test.go index dcfe641d..c39f5658 100644 --- a/pkg/signup/service/signup_service_test.go +++ b/pkg/signup/service/signup_service_test.go @@ -2,6 +2,7 @@ package service_test import ( "bytes" + gocontext "context" "errors" "fmt" "hash/crc32" @@ -15,15 +16,17 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/configuration" "github.com/codeready-toolchain/registration-service/pkg/context" errors2 "github.com/codeready-toolchain/registration-service/pkg/errors" + infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/signup/service" "github.com/codeready-toolchain/registration-service/pkg/util" "github.com/codeready-toolchain/registration-service/test" "github.com/codeready-toolchain/registration-service/test/fake" + "sigs.k8s.io/controller-runtime/pkg/client" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" commonconfig "github.com/codeready-toolchain/toolchain-common/pkg/configuration" "github.com/codeready-toolchain/toolchain-common/pkg/states" - test2 "github.com/codeready-toolchain/toolchain-common/pkg/test" + commontest "github.com/codeready-toolchain/toolchain-common/pkg/test" testconfig "github.com/codeready-toolchain/toolchain-common/pkg/test/config" recaptchapb "cloud.google.com/go/recaptchaenterprise/v2/apiv1/recaptchaenterprisepb" @@ -36,7 +39,6 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) @@ -52,7 +54,7 @@ func TestRunSignupServiceSuite(t *testing.T) { func (s *TestSignupServiceSuite) ServiceConfiguration(namespace string, verificationEnabled bool, excludedDomains string, verificationCodeExpiresInMin int) { - test2.SetEnvVarAndRestore(s.T(), commonconfig.WatchNamespaceEnvVar, namespace) + commontest.SetEnvVarAndRestore(s.T(), commonconfig.WatchNamespaceEnvVar, namespace) s.OverrideApplicationDefault( testconfig.RegistrationService(). @@ -62,7 +64,7 @@ func (s *TestSignupServiceSuite) ServiceConfiguration(namespace string, verifica } func (s *TestSignupServiceSuite) TestSignup() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) // given userID, err := uuid.NewV4() require.NoError(s.T(), err) @@ -74,7 +76,7 @@ func (s *TestSignupServiceSuite) TestSignup() { require.NoError(s.T(), err) gvr, _ := meta.UnsafeGuessKindToResource(gvk) - values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, configuration.Namespace()) + values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, commontest.HostOperatorNs) require.NoError(s.T(), err) userSignups := values.(*toolchainv1alpha1.UserSignupList) @@ -82,7 +84,7 @@ func (s *TestSignupServiceSuite) TestSignup() { require.Len(s.T(), userSignups.Items, 1) val := userSignups.Items[0] - require.Equal(s.T(), configuration.Namespace(), val.Namespace) + require.Equal(s.T(), commontest.HostOperatorNs, val.Namespace) require.Equal(s.T(), username, val.Name) require.True(s.T(), states.VerificationRequired(&val)) require.Equal(s.T(), "a7b1b413c1cbddbcd19a51222ef8e20a", val.Labels[toolchainv1alpha1.UserSignupUserEmailHashLabelKey]) @@ -132,7 +134,7 @@ func (s *TestSignupServiceSuite) TestSignup() { deactivatedUS.Annotations[toolchainv1alpha1.UserSignupLastTargetClusterAnnotationKey] = "member-3" // assume the user was targeted to member-3 states.SetDeactivated(deactivatedUS, true) deactivatedUS.Status.Conditions = deactivated() - err := s.FakeUserSignupClient.Tracker.Update(gvr, deactivatedUS, configuration.Namespace()) + err := s.FakeUserSignupClient.Tracker.Update(gvr, deactivatedUS, commontest.HostOperatorNs) require.NoError(s.T(), err) // when @@ -154,7 +156,7 @@ func (s *TestSignupServiceSuite) TestSignup() { // also, alter the activation counter annotation delete(deactivatedUS.Annotations, toolchainv1alpha1.UserSignupActivationCounterAnnotationKey) delete(deactivatedUS.Annotations, toolchainv1alpha1.UserSignupLastTargetClusterAnnotationKey) - err := s.FakeUserSignupClient.Tracker.Update(gvr, deactivatedUS, configuration.Namespace()) + err := s.FakeUserSignupClient.Tracker.Update(gvr, deactivatedUS, commontest.HostOperatorNs) require.NoError(s.T(), err) // when @@ -173,7 +175,7 @@ func (s *TestSignupServiceSuite) TestSignup() { deactivatedUS := existing.DeepCopy() states.SetDeactivated(deactivatedUS, true) deactivatedUS.Status.Conditions = deactivated() - err := s.FakeUserSignupClient.Tracker.Update(gvr, deactivatedUS, configuration.Namespace()) + err := s.FakeUserSignupClient.Tracker.Update(gvr, deactivatedUS, commontest.HostOperatorNs) require.NoError(s.T(), err) s.FakeUserSignupClient.MockUpdate = func(signup *toolchainv1alpha1.UserSignup) (*toolchainv1alpha1.UserSignup, error) { if signup.Name == "jsmith" { @@ -262,14 +264,15 @@ func (s *TestSignupServiceSuite) TestGetSignupFailsWithNotFoundThenOtherError() s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == "000" { - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) + fakeClient := commontest.NewFakeClient(t) + fakeClient.MockGet = func(ctx gocontext.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.UserSignup); ok && key.Name != "000" { + return errors2.NewInternalError(errors.New("something quite unfortunate happened"), "something bad") } - return nil, errors2.NewInternalError(errors.New("something quite unfortunate happened"), "something bad") + return fakeClient.Client.Get(ctx, key, obj, opts...) } + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -287,7 +290,7 @@ func (s *TestSignupServiceSuite) TestGetSignupFailsWithNotFoundThenOtherError() } func (s *TestSignupServiceSuite) TestSignupNoSpaces() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) // given userID, err := uuid.NewV4() @@ -315,7 +318,7 @@ func (s *TestSignupServiceSuite) TestSignupNoSpaces() { require.NoError(s.T(), err) gvr, _ := meta.UnsafeGuessKindToResource(gvk) - values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, configuration.Namespace()) + values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, commontest.HostOperatorNs) require.NoError(s.T(), err) userSignups := values.(*toolchainv1alpha1.UserSignupList) @@ -327,7 +330,7 @@ func (s *TestSignupServiceSuite) TestSignupNoSpaces() { } func (s *TestSignupServiceSuite) TestSignupWithCaptchaEnabled() { - test2.SetEnvVarAndRestore(s.T(), commonconfig.WatchNamespaceEnvVar, configuration.Namespace()) + commontest.SetEnvVarAndRestore(s.T(), commonconfig.WatchNamespaceEnvVar, commontest.HostOperatorNs) // captcha is enabled serviceOption := func(svc *service.ServiceImpl) { @@ -373,7 +376,7 @@ func (s *TestSignupServiceSuite) TestSignupWithCaptchaEnabled() { require.NoError(s.T(), err) gvr, _ := meta.UnsafeGuessKindToResource(gvk) - values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, configuration.Namespace()) + values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, commontest.HostOperatorNs) require.NoError(s.T(), err) userSignups := values.(*toolchainv1alpha1.UserSignupList) @@ -385,7 +388,7 @@ func (s *TestSignupServiceSuite) TestSignupWithCaptchaEnabled() { } func (s *TestSignupServiceSuite) TestUserSignupWithInvalidSubjectPrefix() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) // given userID, err := uuid.NewV4() @@ -412,7 +415,7 @@ func (s *TestSignupServiceSuite) TestUserSignupWithInvalidSubjectPrefix() { require.NoError(s.T(), err) gvr, _ := meta.UnsafeGuessKindToResource(gvk) - values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, configuration.Namespace()) + values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, commontest.HostOperatorNs) require.NoError(s.T(), err) userSignups := values.(*toolchainv1alpha1.UserSignupList) @@ -462,7 +465,7 @@ func (s *TestSignupServiceSuite) TestEncodeUserID() { } func (s *TestSignupServiceSuite) TestUserWithExcludedDomainEmailSignsUp() { - s.ServiceConfiguration(configuration.Namespace(), true, "redhat.com", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "redhat.com", 5) userID, err := uuid.NewV4() require.NoError(s.T(), err) @@ -484,7 +487,7 @@ func (s *TestSignupServiceSuite) TestUserWithExcludedDomainEmailSignsUp() { require.NoError(s.T(), err) gvr, _ := meta.UnsafeGuessKindToResource(gvk) - values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, configuration.Namespace()) + values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, commontest.HostOperatorNs) require.NoError(s.T(), err) userSignups := values.(*toolchainv1alpha1.UserSignupList) @@ -496,7 +499,7 @@ func (s *TestSignupServiceSuite) TestUserWithExcludedDomainEmailSignsUp() { } func (s *TestSignupServiceSuite) TestCRTAdminUserSignup() { - s.ServiceConfiguration(configuration.Namespace(), true, "redhat.com", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "redhat.com", 5) userID, err := uuid.NewV4() require.NoError(s.T(), err) @@ -516,7 +519,7 @@ func (s *TestSignupServiceSuite) TestCRTAdminUserSignup() { } func (s *TestSignupServiceSuite) TestFailsIfUserSignupNameAlreadyExists() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) userID, err := uuid.NewV4() require.NoError(s.T(), err) @@ -524,7 +527,7 @@ func (s *TestSignupServiceSuite) TestFailsIfUserSignupNameAlreadyExists() { TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: userID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, }, Spec: toolchainv1alpha1.UserSignupSpec{}, }) @@ -541,7 +544,7 @@ func (s *TestSignupServiceSuite) TestFailsIfUserSignupNameAlreadyExists() { } func (s *TestSignupServiceSuite) TestFailsIfUserBanned() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) // given userID, err := uuid.NewV4() @@ -554,7 +557,7 @@ func (s *TestSignupServiceSuite) TestFailsIfUserBanned() { TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: bannedUserID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.BannedUserEmailHashLabelKey: "a7b1b413c1cbddbcd19a51222ef8e20a", }, @@ -584,7 +587,7 @@ func (s *TestSignupServiceSuite) TestFailsIfUserBanned() { } func (s *TestSignupServiceSuite) TestPhoneNumberAlreadyInUseBannedUser() { - s.ServiceConfiguration(configuration.Namespace(), true, "redhat.com", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "redhat.com", 5) userID, err := uuid.NewV4() require.NoError(s.T(), err) @@ -596,7 +599,7 @@ func (s *TestSignupServiceSuite) TestPhoneNumberAlreadyInUseBannedUser() { TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: bannedUserID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.BannedUserEmailHashLabelKey: "a7b1b413c1cbddbcd19a51222ef8e20a", toolchainv1alpha1.BannedUserPhoneNumberHashLabelKey: "fd276563a8232d16620da8ec85d0575f", @@ -618,7 +621,7 @@ func (s *TestSignupServiceSuite) TestPhoneNumberAlreadyInUseBannedUser() { } func (s *TestSignupServiceSuite) TestPhoneNumberAlreadyInUseUserSignup() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) userID, err := uuid.NewV4() require.NoError(s.T(), err) @@ -627,7 +630,7 @@ func (s *TestSignupServiceSuite) TestPhoneNumberAlreadyInUseUserSignup() { TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: userID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.UserSignupUserEmailHashLabelKey: "a7b1b413c1cbddbcd19a51222ef8e20a", toolchainv1alpha1.UserSignupUserPhoneHashLabelKey: "fd276563a8232d16620da8ec85d0575f", @@ -649,7 +652,7 @@ func (s *TestSignupServiceSuite) TestPhoneNumberAlreadyInUseUserSignup() { } func (s *TestSignupServiceSuite) TestOKIfOtherUserBanned() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) userID, err := uuid.NewV4() require.NoError(s.T(), err) @@ -661,7 +664,7 @@ func (s *TestSignupServiceSuite) TestOKIfOtherUserBanned() { TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: bannedUserID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.BannedUserEmailHashLabelKey: "1df66fbb427ff7e64ac46af29cc74b71", }, @@ -685,7 +688,7 @@ func (s *TestSignupServiceSuite) TestOKIfOtherUserBanned() { require.NoError(s.T(), err) gvr, _ := meta.UnsafeGuessKindToResource(gvk) - values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, configuration.Namespace()) + values, err := s.FakeUserSignupClient.Tracker.List(gvr, gvk, commontest.HostOperatorNs) require.NoError(s.T(), err) userSignups := values.(*toolchainv1alpha1.UserSignupList) @@ -693,7 +696,7 @@ func (s *TestSignupServiceSuite) TestOKIfOtherUserBanned() { require.Len(s.T(), userSignups.Items, 1) val := userSignups.Items[0] - require.Equal(s.T(), configuration.Namespace(), val.Namespace) + require.Equal(s.T(), commontest.HostOperatorNs, val.Namespace) require.Equal(s.T(), "jsmith", val.Name) require.False(s.T(), states.ApprovedManually(&val)) require.Equal(s.T(), "a7b1b413c1cbddbcd19a51222ef8e20a", val.Labels[toolchainv1alpha1.UserSignupUserEmailHashLabelKey]) @@ -719,14 +722,15 @@ func (s *TestSignupServiceSuite) TestGetUserSignupFails() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == username { - return nil, errors.New("an error occurred") + fakeClient := commontest.NewFakeClient(t) + fakeClient.MockGet = func(ctx gocontext.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if key.Name != username { + return errors.New("an error occurred") } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) + return fakeClient.Client.Get(ctx, key, obj, opts...) } + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -755,12 +759,8 @@ func (s *TestSignupServiceSuite) TestGetSignupNotFound() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - + fakeClient := commontest.NewFakeClient(t) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -780,18 +780,18 @@ func (s *TestSignupServiceSuite) TestGetSignupNotFound() { func (s *TestSignupServiceSuite) TestGetSignupStatusNotComplete() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) userID, err := uuid.NewV4() require.NoError(s.T(), err) c, _ := gin.CreateTestContext(httptest.NewRecorder()) - userSignupNotComplete := toolchainv1alpha1.UserSignup{ + userSignupNotComplete := &toolchainv1alpha1.UserSignup{ TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: userID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, }, Spec: toolchainv1alpha1.UserSignupSpec{ IdentityClaims: toolchainv1alpha1.IdentityClaimsEmbedded{ @@ -815,9 +815,9 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusNotComplete() { }, }, } - states.SetVerificationRequired(&userSignupNotComplete, true) + states.SetVerificationRequired(userSignupNotComplete, true) - err = s.FakeUserSignupClient.Tracker.Add(&userSignupNotComplete) + err = s.FakeUserSignupClient.Tracker.Add(userSignupNotComplete) require.NoError(s.T(), err) // when @@ -846,14 +846,8 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusNotComplete() { s.T().Run("informer - with check for usersignup complete condition", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == userID.String() { - return &userSignupNotComplete, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - + fakeClient := commontest.NewFakeClient(t, userSignupNotComplete) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -887,7 +881,7 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusNotComplete() { s.T().Run("informer - with no check for UserSignup complete condition", func(t *testing.T) { // given - states.SetVerificationRequired(&userSignupNotComplete, false) + states.SetVerificationRequired(userSignupNotComplete, false) svc := service.NewSignupService( fake.MemberClusterServiceContext{ CrtClient: s, @@ -910,28 +904,8 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusNotComplete() { err = s.FakeToolchainStatusClient.Tracker.Add(toolchainStatus) require.NoError(t, err) - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == userID.String() { - return &userSignupNotComplete, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetMurFunc = func(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - if name == mur.Name { - return mur, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetSpaceFunc = func(_ string) (*toolchainv1alpha1.Space, error) { - return space, nil - } - inf.ListSpaceBindingFunc = func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return []toolchainv1alpha1.SpaceBinding{*spacebinding}, nil - } - inf.GetToolchainStatusFunc = func() (*toolchainv1alpha1.ToolchainStatus, error) { - return toolchainStatus, nil - } + fakeClient := commontest.NewFakeClient(t, userSignupNotComplete, mur, space, spacebinding, toolchainStatus) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) // when @@ -961,7 +935,7 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusNotComplete() { func (s *TestSignupServiceSuite) TestGetSignupNoStatusNotCompleteCondition() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) noCondition := toolchainv1alpha1.UserSignupStatus{} pendingApproval := toolchainv1alpha1.UserSignupStatus{ @@ -994,11 +968,11 @@ func (s *TestSignupServiceSuite) TestGetSignupNoStatusNotCompleteCondition() { c, _ := gin.CreateTestContext(httptest.NewRecorder()) - userSignup := toolchainv1alpha1.UserSignup{ + userSignup := &toolchainv1alpha1.UserSignup{ TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: userID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, }, Spec: toolchainv1alpha1.UserSignupSpec{ IdentityClaims: toolchainv1alpha1.IdentityClaimsEmbedded{ @@ -1008,9 +982,9 @@ func (s *TestSignupServiceSuite) TestGetSignupNoStatusNotCompleteCondition() { Status: status, } - states.SetVerificationRequired(&userSignup, true) + states.SetVerificationRequired(userSignup, true) - err = s.FakeUserSignupClient.Tracker.Add(&userSignup) + err = s.FakeUserSignupClient.Tracker.Add(userSignup) require.NoError(s.T(), err) // when @@ -1037,14 +1011,8 @@ func (s *TestSignupServiceSuite) TestGetSignupNoStatusNotCompleteCondition() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == userID.String() { - return &userSignup, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - + fakeClient := commontest.NewFakeClient(t, userSignup) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1080,7 +1048,7 @@ func (s *TestSignupServiceSuite) TestGetSignupNoStatusNotCompleteCondition() { func (s *TestSignupServiceSuite) TestGetSignupDeactivated() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) us := s.newUserSignupComplete() us.Status.Conditions = deactivated() @@ -1098,14 +1066,8 @@ func (s *TestSignupServiceSuite) TestGetSignupDeactivated() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == us.Name { - return us, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - + fakeClient := commontest.NewFakeClient(t, us) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1128,7 +1090,7 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusOK() { for _, appsSubDomain := range []string{".apps.", ".apps-"} { s.SetupTest() s.T().Run("for apps subdomain: "+appsSubDomain, func(t *testing.T) { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) us := s.newUserSignupComplete() err := s.FakeUserSignupClient.Tracker.Add(us) @@ -1179,29 +1141,8 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusOK() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == us.Name { - return us, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetMurFunc = func(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - if name == mur.Name { - return mur, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetToolchainStatusFunc = func() (*toolchainv1alpha1.ToolchainStatus, error) { - return toolchainStatus, nil - } - inf.GetSpaceFunc = func(_ string) (*toolchainv1alpha1.Space, error) { - return space, nil - } - inf.ListSpaceBindingFunc = func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return []toolchainv1alpha1.SpaceBinding{*spacebinding}, nil - } - + fakeClient := commontest.NewFakeClient(t, us, mur, toolchainStatus, space, spacebinding) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1237,7 +1178,7 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusOK() { func (s *TestSignupServiceSuite) TestGetSignupByUsernameOK() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) us := s.newUserSignupComplete() us.Name = service.EncodeUserIdentifier(us.Spec.IdentityClaims.PreferredUsername) @@ -1307,29 +1248,8 @@ func (s *TestSignupServiceSuite) TestGetSignupByUsernameOK() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == us.Name { - return us, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetMurFunc = func(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - if name == mur.Name { - return mur, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetToolchainStatusFunc = func() (*toolchainv1alpha1.ToolchainStatus, error) { - return toolchainStatus, nil - } - inf.GetSpaceFunc = func(_ string) (*toolchainv1alpha1.Space, error) { - return space, nil - } - inf.ListSpaceBindingFunc = func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return []toolchainv1alpha1.SpaceBinding{*spacebinding}, nil - } - + fakeClient := commontest.NewFakeClient(t, us, mur, toolchainStatus, space, spacebinding) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1367,7 +1287,7 @@ func (s *TestSignupServiceSuite) newToolchainStatus(appsSubDomain string) *toolc TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: "toolchain-status", - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, }, Status: toolchainv1alpha1.ToolchainStatusStatus{ Members: []toolchainv1alpha1.Member{ @@ -1402,7 +1322,7 @@ func (s *TestSignupServiceSuite) newToolchainStatus(appsSubDomain string) *toolc func (s *TestSignupServiceSuite) TestGetSignupStatusFailGetToolchainStatus() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) c, _ := gin.CreateTestContext(httptest.NewRecorder()) @@ -1424,29 +1344,8 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusFailGetToolchainStatus() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == us.Name { - return us, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetMurFunc = func(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - if name == mur.Name { - return mur, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetSpaceFunc = func(name string) (*toolchainv1alpha1.Space, error) { - if name == space.Name { - return space, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetToolchainStatusFunc = func() (*toolchainv1alpha1.ToolchainStatus, error) { - return nil, apierrors.NewNotFound(schema.GroupResource{}, "toolchain-status") - } - + fakeClient := commontest.NewFakeClient(t, us, mur, space) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1459,13 +1358,13 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusFailGetToolchainStatus() { _, err := svc.GetSignupFromInformer(c, us.Name, "", true) // then - require.EqualError(t, err, fmt.Sprintf("error when retrieving ToolchainStatus to set Che Dashboard for completed UserSignup %s: \"toolchain-status\" not found", us.Name)) + require.EqualError(t, err, fmt.Sprintf("error when retrieving ToolchainStatus to set Che Dashboard for completed UserSignup %s: toolchainstatuses.toolchain.dev.openshift.com \"toolchain-status\" not found", us.Name)) }) } func (s *TestSignupServiceSuite) TestGetSignupMURGetFails() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) us := s.newUserSignupComplete() err := s.FakeUserSignupClient.Tracker.Add(us) @@ -1489,20 +1388,14 @@ func (s *TestSignupServiceSuite) TestGetSignupMURGetFails() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == us.Name { - return us, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetMurFunc = func(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - if name == us.Status.CompliantUsername { - return nil, returnedErr + fakeClient := commontest.NewFakeClient(t, us) + fakeClient.MockGet = func(ctx gocontext.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*toolchainv1alpha1.MasterUserRecord); ok && key.Name == us.Status.CompliantUsername { + return returnedErr } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) + return fakeClient.Client.Get(ctx, key, obj, opts...) } - + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1521,7 +1414,7 @@ func (s *TestSignupServiceSuite) TestGetSignupMURGetFails() { func (s *TestSignupServiceSuite) TestGetSignupReadyConditionStatus() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) us := s.newUserSignupComplete() err := s.FakeUserSignupClient.Tracker.Add(us) @@ -1533,7 +1426,7 @@ func (s *TestSignupServiceSuite) TestGetSignupReadyConditionStatus() { TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: "ted", - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, }, } @@ -1610,29 +1503,8 @@ func (s *TestSignupServiceSuite) TestGetSignupReadyConditionStatus() { // informer case // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == us.Name { - return us, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetMurFunc = func(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - if name == mur.Name { - return mur, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetSpaceFunc = func(name string) (*toolchainv1alpha1.Space, error) { - if name == space.Name { - return space, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - inf.GetToolchainStatusFunc = func() (*toolchainv1alpha1.ToolchainStatus, error) { - return toolchainStatus, nil - } - + fakeClient := commontest.NewFakeClient(t, us, mur, toolchainStatus, space) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1657,7 +1529,7 @@ func (s *TestSignupServiceSuite) TestGetSignupReadyConditionStatus() { func (s *TestSignupServiceSuite) TestGetSignupBannedUserEmail() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) us := s.newBannedUserSignup() err := s.FakeUserSignupClient.Tracker.Add(us) @@ -1680,14 +1552,8 @@ func (s *TestSignupServiceSuite) TestGetSignupBannedUserEmail() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetUserSignupFunc = func(name string) (*toolchainv1alpha1.UserSignup, error) { - if name == us.Name { - return us, nil - } - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - + fakeClient := commontest.NewFakeClient(t, us) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) s.Application.MockInformerService(inf) svc := service.NewSignupService( fake.MemberClusterServiceContext{ @@ -1709,7 +1575,7 @@ func (s *TestSignupServiceSuite) TestGetSignupBannedUserEmail() { func (s *TestSignupServiceSuite) TestGetDefaultUserNamespace() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) space := s.newSpace("dave") err := s.FakeSpaceClient.Tracker.Add(space) @@ -1724,10 +1590,8 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespace() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetSpaceFunc = func(_ string) (*toolchainv1alpha1.Space, error) { - return space, nil - } + fakeClient := commontest.NewFakeClient(t, space) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) // when targetCluster, defaultUserNamespace := service.GetDefaultUserTarget(inf, "dave", "dave") @@ -1742,7 +1606,7 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespace() { // This is valuable when user doesn't have default home space created, but has access to some shared spaces func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFromFirstUnownedSpace() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) // space created for userA space := s.newSpace("userA") err := s.FakeSpaceClient.Tracker.Add(space) @@ -1772,13 +1636,8 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFromFirstUnownedSpac s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetSpaceFunc = func(_ string) (*toolchainv1alpha1.Space, error) { - return space, nil - } - inf.ListSpaceBindingFunc = func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return []toolchainv1alpha1.SpaceBinding{*spacebindingB, *spaceCindingC}, nil - } + fakeClient := commontest.NewFakeClient(t, space, spacebindingB, spaceCindingC) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) // when targetCluster, defaultUserNamespace := service.GetDefaultUserTarget(inf, "", "userB") @@ -1792,7 +1651,7 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFromFirstUnownedSpac // TestGetDefaultUserNamespaceMultiSpace tests that the home Space created for the user is prioritized when there are multiple spaces func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceMultiSpace() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) // space1 created by userA space1 := s.newSpace("userA") @@ -1824,20 +1683,8 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceMultiSpace() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetSpaceFunc = func(name string) (*toolchainv1alpha1.Space, error) { - switch name { - case space1.Name: - return space1, nil - case space2.Name: - return space2, nil - default: - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } - } - inf.ListSpaceBindingFunc = func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return []toolchainv1alpha1.SpaceBinding{*spacebinding1, *spacebinding2}, nil - } + fakeClient := commontest.NewFakeClient(t, space1, space2, spacebinding1, spacebinding2) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) // when targetCluster, defaultUserNamespace := service.GetDefaultUserTarget(inf, "userB", "userB") @@ -1850,7 +1697,7 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceMultiSpace() { func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFailNoHomeSpaceNoSpaceBinding() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) space := s.newSpace("dave") err := s.FakeSpaceClient.Tracker.Add(space) @@ -1865,13 +1712,14 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFailNoHomeSpaceNoSpa s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetSpaceFunc = func(_ string) (*toolchainv1alpha1.Space, error) { - return space, nil - } - inf.ListSpaceBindingFunc = func(_ ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - return nil, apierrors.NewInternalError(fmt.Errorf("something went wrong")) + fakeClient := commontest.NewFakeClient(t, space) + fakeClient.MockList = func(ctx gocontext.Context, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*toolchainv1alpha1.SpaceBindingList); ok { + return apierrors.NewInternalError(fmt.Errorf("something went wrong")) + } + return fakeClient.Client.List(ctx, list, opts...) } + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) // when targetCluster, defaultUserNamespace := service.GetDefaultUserTarget(inf, "", "dave") @@ -1884,7 +1732,7 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFailNoHomeSpaceNoSpa func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFailNoSpace() { // given - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) // when targetCluster, defaultUserNamespace := service.GetDefaultUserTarget(s, "dave", "dave") @@ -1895,10 +1743,8 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFailNoSpace() { s.T().Run("informer", func(t *testing.T) { // given - inf := fake.NewFakeInformer() - inf.GetSpaceFunc = func(name string) (*toolchainv1alpha1.Space, error) { - return nil, apierrors.NewNotFound(schema.GroupResource{}, name) - } + fakeClient := commontest.NewFakeClient(t) + inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) // when targetCluster, defaultUserNamespace := service.GetDefaultUserTarget(inf, "dave", "dave") @@ -1910,7 +1756,7 @@ func (s *TestSignupServiceSuite) TestGetDefaultUserNamespaceFailNoSpace() { } func (s *TestSignupServiceSuite) TestGetUserSignup() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) s.Run("getusersignup ok", func() { us := s.newUserSignupComplete() @@ -1942,7 +1788,7 @@ func (s *TestSignupServiceSuite) TestGetUserSignup() { } func (s *TestSignupServiceSuite) TestUpdateUserSignup() { - s.ServiceConfiguration(configuration.Namespace(), true, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, true, "", 5) us := s.newUserSignupComplete() err := s.FakeUserSignupClient.Tracker.Add(us) @@ -1975,7 +1821,7 @@ func (s *TestSignupServiceSuite) TestUpdateUserSignup() { } func (s *TestSignupServiceSuite) TestIsPhoneVerificationRequired() { - test2.SetEnvVarAndRestore(s.T(), commonconfig.WatchNamespaceEnvVar, configuration.Namespace()) + commontest.SetEnvVarAndRestore(s.T(), commonconfig.WatchNamespaceEnvVar, commontest.HostOperatorNs) s.Run("phone verification is required", func() { s.Run("captcha verification is disabled", func() { @@ -2094,7 +1940,7 @@ func (s *TestSignupServiceSuite) TestIsPhoneVerificationRequired() { func (s *TestSignupServiceSuite) TestGetSignupUpdatesUserSignupIdentityClaims() { - s.ServiceConfiguration(configuration.Namespace(), false, "", 5) + s.ServiceConfiguration(commontest.HostOperatorNs, false, "", 5) // Create a new UserSignup, set its UserID and AccountID annotations userSignup := s.newUserSignupComplete() @@ -2106,7 +1952,7 @@ func (s *TestSignupServiceSuite) TestGetSignupUpdatesUserSignupIdentityClaims() TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: userSignup.Status.CompliantUsername, - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, }, Spec: toolchainv1alpha1.MasterUserRecordSpec{ UserAccounts: []toolchainv1alpha1.UserAccountEmbedded{{TargetCluster: "member-123"}}, @@ -2235,7 +2081,7 @@ func (s *TestSignupServiceSuite) newUserSignupCompleteWithReason(reason string) TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: userID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Annotations: map[string]string{ toolchainv1alpha1.UserSignupUserEmailHashLabelKey: "90cb861692508c36933b85dfe43f5369", }, @@ -2282,7 +2128,7 @@ func (s *TestSignupServiceSuite) newBannedUserSignup() *toolchainv1alpha1.UserSi TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: userID.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Annotations: map[string]string{ toolchainv1alpha1.UserSignupUserEmailHashLabelKey: "a7b1b413c1cbddbcd19a51222ef8e20a", }, @@ -2325,7 +2171,7 @@ func (s *TestSignupServiceSuite) newProvisionedMUR(name string) *toolchainv1alph TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: name, - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, }, Spec: toolchainv1alpha1.MasterUserRecordSpec{ UserAccounts: []toolchainv1alpha1.UserAccountEmbedded{{TargetCluster: "member-123"}}, @@ -2352,7 +2198,7 @@ func (s *TestSignupServiceSuite) newSpace(name string) *toolchainv1alpha1.Space TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: name, - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.SpaceCreatorLabelKey: name, }, @@ -2382,7 +2228,7 @@ func (s *TestSignupServiceSuite) newSpaceBinding(murName, spaceName string) *too TypeMeta: v1.TypeMeta{}, ObjectMeta: v1.ObjectMeta{ Name: name.String(), - Namespace: configuration.Namespace(), + Namespace: commontest.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.SpaceBindingSpaceLabelKey: spaceName, toolchainv1alpha1.SpaceBindingMasterUserRecordLabelKey: murName, diff --git a/test/fake/informer.go b/test/fake/informer.go index c51e297c..dbbb1fa6 100644 --- a/test/fake/informer.go +++ b/test/fake/informer.go @@ -1,94 +1,13 @@ package fake import ( - "context" - "testing" - toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" - "github.com/codeready-toolchain/registration-service/pkg/application/service" "github.com/codeready-toolchain/registration-service/pkg/configuration" "github.com/codeready-toolchain/toolchain-common/pkg/test" spacetest "github.com/codeready-toolchain/toolchain-common/pkg/test/space" - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" ) -func NewFakeInformer() Informer { - return Informer{} -} - -type Informer struct { - GetMurFunc func(name string) (*toolchainv1alpha1.MasterUserRecord, error) - GetSpaceFunc func(name string) (*toolchainv1alpha1.Space, error) - GetToolchainStatusFunc func() (*toolchainv1alpha1.ToolchainStatus, error) - GetUserSignupFunc func(name string) (*toolchainv1alpha1.UserSignup, error) - ListSpaceBindingFunc func(reqs ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) - GetProxyPluginConfigFunc func(name string) (*toolchainv1alpha1.ProxyPlugin, error) - GetNSTemplateTierFunc func(name string) (*toolchainv1alpha1.NSTemplateTier, error) - ListBannedUsersByEmailFunc func(email string) ([]toolchainv1alpha1.BannedUser, error) -} - -func (f Informer) GetProxyPluginConfig(name string) (*toolchainv1alpha1.ProxyPlugin, error) { - if f.GetProxyPluginConfigFunc != nil { - return f.GetProxyPluginConfigFunc(name) - } - panic("not supposed to call GetProxyPluginConfig") -} - -func (f Informer) GetMasterUserRecord(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - if f.GetMurFunc != nil { - return f.GetMurFunc(name) - } - panic("not supposed to call GetMasterUserRecord") -} - -func (f Informer) GetSpace(name string) (*toolchainv1alpha1.Space, error) { - if f.GetSpaceFunc != nil { - return f.GetSpaceFunc(name) - } - panic("not supposed to call GetSpace") -} - -func (f Informer) GetToolchainStatus() (*toolchainv1alpha1.ToolchainStatus, error) { - if f.GetToolchainStatusFunc != nil { - return f.GetToolchainStatusFunc() - } - panic("not supposed to call GetToolchainStatus") -} - -func (f Informer) GetUserSignup(name string) (*toolchainv1alpha1.UserSignup, error) { - if f.GetUserSignupFunc != nil { - return f.GetUserSignupFunc(name) - } - panic("not supposed to call GetUserSignup") -} - -func (f Informer) ListSpaceBindings(req ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - if f.ListSpaceBindingFunc != nil { - return f.ListSpaceBindingFunc(req...) - } - panic("not supposed to call ListSpaceBindings") -} - -func (f Informer) GetNSTemplateTier(tier string) (*toolchainv1alpha1.NSTemplateTier, error) { - if f.GetNSTemplateTierFunc != nil { - return f.GetNSTemplateTierFunc(tier) - } - panic("not supposed to call GetNSTemplateTierFunc") -} - -func (f Informer) ListBannedUsersByEmail(email string) ([]toolchainv1alpha1.BannedUser, error) { - if f.ListBannedUsersByEmailFunc != nil { - return f.ListBannedUsersByEmailFunc(email) - } - panic("not supposed to call BannedUsersByEmail") -} - func NewSpace(name, targetCluster, compliantUserName string, spaceTestOptions ...spacetest.Option) *toolchainv1alpha1.Space { spaceTestOptions = append(spaceTestOptions, @@ -108,7 +27,7 @@ func NewSpace(name, targetCluster, compliantUserName string, spaceTestOptions .. }, ), ) - return spacetest.NewSpace(configuration.Namespace(), name, + return spacetest.NewSpace(test.HostOperatorNs, name, spaceTestOptions..., ) } @@ -116,7 +35,8 @@ func NewSpace(name, targetCluster, compliantUserName string, spaceTestOptions .. func NewSpaceBinding(name, murLabelValue, spaceLabelValue, role string) *toolchainv1alpha1.SpaceBinding { return &toolchainv1alpha1.SpaceBinding{ ObjectMeta: metav1.ObjectMeta{ - Name: name, + Name: name, + Namespace: test.HostOperatorNs, Labels: map[string]string{ toolchainv1alpha1.SpaceBindingMasterUserRecordLabelKey: murLabelValue, toolchainv1alpha1.SpaceBindingSpaceLabelKey: spaceLabelValue, @@ -133,7 +53,7 @@ func NewSpaceBinding(name, murLabelValue, spaceLabelValue, role string) *toolcha func NewBase1NSTemplateTier() *toolchainv1alpha1.NSTemplateTier { return &toolchainv1alpha1.NSTemplateTier{ ObjectMeta: metav1.ObjectMeta{ - Namespace: configuration.Namespace(), + Namespace: test.HostOperatorNs, Name: "base1ns", }, Spec: toolchainv1alpha1.NSTemplateTierSpec{ @@ -180,79 +100,3 @@ func NewMasterUserRecord(name string) *toolchainv1alpha1.MasterUserRecord { }, } } - -type InformerServiceOptions func(informer *Informer) - -func WithGetNSTemplateTierFunc(getNsTemplateTierFunc func(tier string) (*toolchainv1alpha1.NSTemplateTier, error)) InformerServiceOptions { - return func(informer *Informer) { - informer.GetNSTemplateTierFunc = getNsTemplateTierFunc - } -} - -func WithListSpaceBindingFunc(listSpaceBindingFunc func(reqs ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error)) InformerServiceOptions { - return func(informer *Informer) { - informer.ListSpaceBindingFunc = listSpaceBindingFunc - } -} - -func WithGetSpaceFunc(getSpaceFunc func(name string) (*toolchainv1alpha1.Space, error)) InformerServiceOptions { - return func(informer *Informer) { - informer.GetSpaceFunc = getSpaceFunc - } -} - -func WithGetMurFunc(getMurFunc func(name string) (*toolchainv1alpha1.MasterUserRecord, error)) InformerServiceOptions { - return func(informer *Informer) { - informer.GetMurFunc = getMurFunc - } -} - -func WithGetBannedUsersByEmailFunc(bannedUsersByEmail func(ermail string) ([]toolchainv1alpha1.BannedUser, error)) InformerServiceOptions { - return func(informer *Informer) { - informer.ListBannedUsersByEmailFunc = bannedUsersByEmail - } -} - -func GetInformerService(fakeClient client.Client, options ...InformerServiceOptions) func() service.InformerService { - return func() service.InformerService { - - inf := NewFakeInformer() - inf.GetSpaceFunc = func(name string) (*toolchainv1alpha1.Space, error) { - space := &toolchainv1alpha1.Space{} - err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: configuration.Namespace()}, space) - return space, err - } - inf.ListSpaceBindingFunc = func(reqs ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - sbList := &toolchainv1alpha1.SpaceBindingList{} - err := fakeClient.List(context.TODO(), sbList, &client.ListOptions{LabelSelector: labels.NewSelector().Add(reqs...)}) - return sbList.Items, err - } - inf.GetNSTemplateTierFunc = func(tier string) (*toolchainv1alpha1.NSTemplateTier, error) { - nsTemplateTier := &toolchainv1alpha1.NSTemplateTier{} - err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: tier, Namespace: configuration.Namespace()}, nsTemplateTier) - return nsTemplateTier, err - } - inf.GetMurFunc = func(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - mur := &toolchainv1alpha1.MasterUserRecord{} - err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: configuration.Namespace()}, mur) - return mur, err - } - - for _, modify := range options { - modify(&inf) - } - - return inf - } -} - -func InitClient(t *testing.T, initObjs ...runtime.Object) *test.FakeClient { - scheme := runtime.NewScheme() - var AddToSchemes runtime.SchemeBuilder - addToSchemes := append(AddToSchemes, - toolchainv1alpha1.AddToScheme) - err := addToSchemes.AddToScheme(scheme) - require.NoError(t, err) - cl := test.NewFakeClient(t, initObjs...) - return cl -}