github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/domain/tenant/fetcher_on_demand_test.go (about) 1 package tenant_test 2 3 import ( 4 "fmt" 5 "net/http" 6 "testing" 7 8 "github.com/stretchr/testify/mock" 9 10 "github.com/kyma-incubator/compass/components/director/internal/domain/tenant/automock" 11 12 "github.com/pkg/errors" 13 14 "github.com/kyma-incubator/compass/components/director/internal/domain/tenant" 15 "github.com/stretchr/testify/assert" 16 "github.com/stretchr/testify/require" 17 ) 18 19 func TestFetchOnDemand(t *testing.T) { 20 var ( 21 fetchTenantURL = "https://compass-tenant-fetcher.kyma.local/tenants/v1/fetch" 22 tenantID = "b91b59f7-2563-40b2-aba9-fef726037aa3" 23 parentTenantID = "8d4842ed-0307-4808-85d5-6bbed114c4ff" 24 testErr = errors.New("error") 25 ) 26 27 testCases := []struct { 28 Name string 29 Client func() *automock.Client 30 ExpectedErrorMsg string 31 }{ 32 { 33 Name: "Success", 34 Client: func() *automock.Client { 35 client := &automock.Client{} 36 client.On("Do", mock.Anything).Return(&http.Response{ 37 StatusCode: http.StatusOK, 38 }, nil).Once() 39 return client 40 }, 41 }, 42 { 43 Name: "Error when cannot make the request", 44 Client: func() *automock.Client { 45 client := &automock.Client{} 46 client.On("Do", mock.Anything).Return(nil, testErr).Once() 47 return client 48 }, 49 ExpectedErrorMsg: testErr.Error(), 50 }, 51 { 52 Name: "Error when status code is not 200", 53 Client: func() *automock.Client { 54 client := &automock.Client{} 55 client.On("Do", mock.Anything).Return(&http.Response{ 56 StatusCode: http.StatusInternalServerError, 57 }, nil).Once() 58 return client 59 }, 60 ExpectedErrorMsg: fmt.Sprintf("received status code %d when trying to fetch tenant with ID %s", http.StatusInternalServerError, tenantID), 61 }, 62 } 63 64 for _, testCase := range testCases { 65 t.Run(testCase.Name, func(t *testing.T) { 66 httpClient := testCase.Client() 67 config := tenant.FetchOnDemandAPIConfig{ 68 TenantOnDemandURL: fetchTenantURL, 69 IsDisabled: false, 70 } 71 svc := tenant.NewFetchOnDemandService(httpClient, config) 72 73 // WHEN 74 err := svc.FetchOnDemand(tenantID, parentTenantID) 75 76 // THEN 77 if len(testCase.ExpectedErrorMsg) > 0 { 78 require.Error(t, err) 79 assert.Contains(t, err.Error(), testCase.ExpectedErrorMsg) 80 } else { 81 assert.NoError(t, err) 82 } 83 }) 84 } 85 }