diff --git a/api/api_test.go b/api/api_test.go index 62fa09a25..92298f71c 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -40,7 +40,6 @@ var _ = Describe("API", func() { BeforeSuite(func() { server = common.NewOAuthServer() - server.Start() }) AfterSuite(func() { @@ -55,7 +54,7 @@ var _ = Describe("API", func() { It("returns no error if creation is successful", func() { _, err := api.New(context.TODO(), mockedStorage, &api.Settings{ - TokenIssuerURL: server.URL, + TokenIssuerURL: server.BaseURL, ClientID: "sm", }, nil) Expect(err).ShouldNot(HaveOccurred()) diff --git a/test/auth_test/auth_test.go b/test/auth_test/auth_test.go index e09025c8f..2240e8178 100644 --- a/test/auth_test/auth_test.go +++ b/test/auth_test/auth_test.go @@ -47,7 +47,7 @@ var _ = Describe("Service Manager Authentication", func() { ) BeforeSuite(func() { - ctx = common.NewTestContext(nil) + ctx = common.DefaultTestContext() }) AfterSuite(func() { diff --git a/test/broker_test/broker_test.go b/test/broker_test/broker_test.go index fdcfdc836..627bc089d 100644 --- a/test/broker_test/broker_test.go +++ b/test/broker_test/broker_test.go @@ -76,12 +76,14 @@ var _ = test.DescribeTestsFor(test.TestCase{ if brokerWithLabelsServer != nil { brokerWithLabelsServer.Close() } + + ctx.Cleanup() }) BeforeEach(func() { brokerServer = common.NewBrokerServer() brokerWithLabelsServer = common.NewBrokerServer() - ctx = common.NewTestContext(nil) + ctx = common.DefaultTestContext() brokerServer.Reset() brokerWithLabelsServer.Reset() brokerName := "brokerName" @@ -91,7 +93,7 @@ var _ = test.DescribeTestsFor(test.TestCase{ postBrokerRequestWithNoLabels = common.Object{ "name": brokerName, - "broker_url": brokerServer.URL, + "broker_url": brokerServer.URL(), "description": brokerDescription, "credentials": common.Object{ "basic": common.Object{ @@ -102,7 +104,7 @@ var _ = test.DescribeTestsFor(test.TestCase{ } expectedBrokerResponse = common.Object{ "name": brokerName, - "broker_url": brokerServer.URL, + "broker_url": brokerServer.URL(), "description": brokerDescription, } @@ -113,7 +115,7 @@ var _ = test.DescribeTestsFor(test.TestCase{ postBrokerRequestWithLabels = common.Object{ "name": brokerWithLabelsName, - "broker_url": brokerWithLabelsServer.URL, + "broker_url": brokerWithLabelsServer.URL(), "description": brokerWithLabelsDescription, "credentials": common.Object{ "basic": common.Object{ @@ -513,7 +515,7 @@ var _ = test.DescribeTestsFor(test.TestCase{ anotherBrokerServer.Password = "password" anotherTestBroker = common.Object{ "name": "another_name", - "broker_url": anotherBrokerServer.URL, + "broker_url": anotherBrokerServer.URL(), "description": "another_description", "credentials": common.Object{ "basic": common.Object{ @@ -611,7 +613,7 @@ var _ = test.DescribeTestsFor(test.TestCase{ updatedBrokerJSON = common.Object{ "name": "updated_name", "description": "updated_description", - "broker_url": updatedBrokerServer.URL, + "broker_url": updatedBrokerServer.URL(), "credentials": common.Object{ "basic": common.Object{ "username": updatedBrokerServer.Username, @@ -657,7 +659,7 @@ var _ = test.DescribeTestsFor(test.TestCase{ Context("when broker_url is changed and the credentials are correct", func() { It("returns 200", func() { updatedBrokerJSON := common.Object{ - "broker_url": updatedBrokerServer.URL, + "broker_url": updatedBrokerServer.URL(), } updatedBrokerServer.Username = brokerServer.Username updatedBrokerServer.Password = brokerServer.Password @@ -685,7 +687,7 @@ var _ = test.DescribeTestsFor(test.TestCase{ Context("when broker_url is changed but the credentials are wrong", func() { It("returns 400", func() { updatedBrokerJSON := common.Object{ - "broker_url": updatedBrokerServer.URL, + "broker_url": updatedBrokerServer.URL(), } ctx.SMWithOAuth.PATCH("/v1/service_brokers/"+brokerID). WithJSON(updatedBrokerJSON). diff --git a/test/common/broker.go b/test/common/broker.go index cb660da44..575943d9d 100644 --- a/test/common/broker.go +++ b/test/common/broker.go @@ -53,6 +53,10 @@ type BrokerServer struct { router *mux.Router } +func (b *BrokerServer) URL() string { + return b.Server.URL +} + func JSONToMap(j string) map[string]interface{} { jsonMap := make(map[string]interface{}) if err := json.Unmarshal([]byte(j), &jsonMap); err != nil { diff --git a/test/common/catalog.go b/test/common/catalog.go index d158eda99..4d903e768 100644 --- a/test/common/catalog.go +++ b/test/common/catalog.go @@ -127,7 +127,7 @@ func (sbc *SBCatalog) AddService(service string) { } func (sbc *SBCatalog) AddPlanToService(plan string, serviceIndex int) { - s, err := sjson.Set(string(*sbc), fmt.Sprintf("services.%d.-1", serviceIndex), JSONToMap(plan)) + s, err := sjson.Set(string(*sbc), fmt.Sprintf("services.%d.plans.-1", serviceIndex), JSONToMap(plan)) if err != nil { panic(err) } diff --git a/test/common/common.go b/test/common/common.go index 025ad2a5e..622b54ef8 100644 --- a/test/common/common.go +++ b/test/common/common.go @@ -18,6 +18,7 @@ package common import ( "github.com/onsi/ginkgo" + "github.com/spf13/pflag" "crypto/rand" "crypto/rsa" @@ -45,6 +46,31 @@ import ( type Object = map[string]interface{} type Array = []interface{} +type closer interface { + Close() +} + +type urler interface { + URL() string +} + +type FakeServer interface { + closer + urler +} + +type FlagValue struct { + pflagValue pflag.Value +} + +func (f FlagValue) Set(s string) error { + return f.pflagValue.Set(s) +} + +func (f FlagValue) String() string { + return f.pflagValue.String() +} + func RemoveNonNumericArgs(obj Object) Object { return removeOnCondition(isNotNumeric, obj) } @@ -284,7 +310,7 @@ func GenerateRandomBroker() Object { } o = Object{ "name": UUID.String(), - "broker_url": brokerServer.URL, + "broker_url": brokerServer.URL(), "description": UUID2.String(), "credentials": Object{ "basic": Object{ diff --git a/test/common/oauth_server.go b/test/common/oauth_server.go index 348507d95..a0d616f10 100644 --- a/test/common/oauth_server.go +++ b/test/common/oauth_server.go @@ -27,7 +27,7 @@ import ( ) type OAuthServer struct { - URL string + BaseURL string server *httptest.Server mux *http.ServeMux @@ -48,6 +48,7 @@ func NewOAuthServer() *OAuthServer { os.mux.HandleFunc("/.well-known/openid-configuration", os.getOpenIDConfig) os.mux.HandleFunc("/oauth/token", os.getToken) os.mux.HandleFunc("/token_keys", os.getTokenKeys) + os.Start() return os } @@ -57,7 +58,7 @@ func (os *OAuthServer) Start() { panic("OAuth server already started") } os.server = httptest.NewServer(os.mux) - os.URL = os.server.URL + os.BaseURL = os.server.URL } func (os *OAuthServer) Close() { @@ -67,11 +68,15 @@ func (os *OAuthServer) Close() { } } +func (os *OAuthServer) URL() string { + return os.BaseURL +} + func (os *OAuthServer) getOpenIDConfig(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{ - "issuer": "` + os.URL + `/oauth/token", - "jwks_uri": "` + os.URL + `/token_keys" + "issuer": "` + os.BaseURL + `/oauth/token", + "jwks_uri": "` + os.BaseURL + `/token_keys" }`)) } @@ -88,7 +93,7 @@ func (os *OAuthServer) CreateToken(payload map[string]interface{}) string { if iss, ok := payload["iss"]; ok { issuerURL = iss.(string) } else { - issuerURL = os.URL + "/oauth/token" + issuerURL = os.BaseURL + "/oauth/token" } nextYear := time.Now().Add(365 * 24 * time.Hour) token, err := jwt.Sign(os.signer, &jwt.Options{ diff --git a/test/common/test_context.go b/test/common/test_context.go index 4d3debabb..74c1de453 100644 --- a/test/common/test_context.go +++ b/test/common/test_context.go @@ -19,6 +19,7 @@ package common import ( "context" "flag" + "fmt" "net/http/httptest" "path" "runtime" @@ -37,29 +38,82 @@ import ( . "github.com/onsi/ginkgo" ) -var ( - e env.Environment - _, b, _, _ = runtime.Caller(0) - basePath = path.Dir(b) -) +func init() { + // dummy env to put SM pflags to flags + TestEnv(SetTestFileLocation) +} + +const SMServer = "sm-server" +const OauthServer = "oauth-server" +const BrokerServerPrefix = "broker-" + +type TestContextBuilder struct { + envPreHooks []func(set *pflag.FlagSet) + envPostHooks []func(env env.Environment, servers map[string]FakeServer) + + smExtensions []func(ctx context.Context, smb *sm.ServiceManagerBuilder, env env.Environment) error + defaultTokenClaims map[string]interface{} -type FlagValue struct { - pflagValue pflag.Value + shouldSkipBasicAuthClient bool + + Environment func(f ...func(set *pflag.FlagSet)) env.Environment + Servers map[string]FakeServer } -func (f FlagValue) Set(s string) error { - return f.pflagValue.Set(s) +type TestContext struct { + SM *httpexpect.Expect + SMWithOAuth *httpexpect.Expect + SMWithBasic *httpexpect.Expect + TestPlatform *types.Platform + + Servers map[string]FakeServer } -func (f FlagValue) String() string { - return f.pflagValue.String() +type testSMServer struct { + *httptest.Server } -func init() { - e = TestEnv() +func (ts *testSMServer) URL() string { + return ts.Server.URL +} + +// DefaultTestContext sets up a test context with default values +func DefaultTestContext() *TestContext { + return NewTestContextBuilder().Build() +} + +// NewTestContextBuilder sets up a builder with default values +func NewTestContextBuilder() *TestContextBuilder { + return &TestContextBuilder{ + envPreHooks: []func(set *pflag.FlagSet){ + SetTestFileLocation, + }, + Environment: TestEnv, + envPostHooks: []func(env env.Environment, servers map[string]FakeServer){ + func(env env.Environment, servers map[string]FakeServer) { + env.Set("api.token_issuer_url", servers["oauth-server"].URL()) + }, + func(env env.Environment, servers map[string]FakeServer) { + flag.VisitAll(func(flag *flag.Flag) { + if flag.Value.String() != "" { + // if any of the go test flags have been set, propagate the value in sm env with highest prio + // when env exposes the pflagset it would be better to instead override the pflag value instead + env.Set(flag.Name, flag.Value.String()) + } + }) + }, + }, + smExtensions: []func(ctx context.Context, smb *sm.ServiceManagerBuilder, env env.Environment) error{}, + defaultTokenClaims: make(map[string]interface{}, 0), + Servers: map[string]FakeServer{ + "oauth-server": NewOAuthServer(), + }, + } } func SetTestFileLocation(set *pflag.FlagSet) { + _, b, _, _ := runtime.Caller(0) + basePath := path.Dir(b) set.Set("file.location", basePath) } @@ -80,36 +134,98 @@ func TestEnv(additionalFlagFuncs ...func(set *pflag.FlagSet)) env.Environment { additionalFlagFuncs = append(additionalFlagFuncs, f) - // will be used as default value and overridden if --file.location={{location}} is passed to go test - additionalFlagFuncs = append(additionalFlagFuncs, SetTestFileLocation) - return sm.DefaultEnv(additionalFlagFuncs...) } -type ContextParams struct { - RegisterExtensions func(smb *sm.ServiceManagerBuilder) - DefaultTokenClaims map[string]interface{} - Env env.Environment +func (tcb *TestContextBuilder) SkipBasicAuthClientSetup(shouldSkip bool) *TestContextBuilder { + tcb.shouldSkipBasicAuthClient = shouldSkip + + return tcb +} + +func (tcb *TestContextBuilder) WithDefaultEnv(envCreateFunc func(f ...func(set *pflag.FlagSet)) env.Environment) *TestContextBuilder { + tcb.Environment = envCreateFunc + + return tcb } -func NewSMServer(params *ContextParams, issuerURL string) *httptest.Server { - var smEnv env.Environment - if params.Env != nil { - smEnv = params.Env - } else { - smEnv = e +func (tcb *TestContextBuilder) WithAdditionalFakeServers(additionalFakeServers map[string]FakeServer) *TestContextBuilder { + if tcb.Servers == nil { + tcb.Servers = make(map[string]FakeServer, 0) } - smEnv.Set("api.token_issuer_url", issuerURL) + for name, server := range additionalFakeServers { + tcb.Servers[name] = server + } - flag.VisitAll(func(flag *flag.Flag) { - if flag.Value.String() != "" { - // if any of the go test flags have been set, propagate the value in sm env with highest prio - // when env exposes the pflagset it would be better to instead override the pflag value instead - smEnv.Set(flag.Name, flag.Value.String()) - } + return tcb +} + +func (tcb *TestContextBuilder) WithDefaultTokenClaims(defaultTokenClaims map[string]interface{}) *TestContextBuilder { + tcb.defaultTokenClaims = defaultTokenClaims + + return tcb +} + +func (tcb *TestContextBuilder) WithEnvPreExtensions(fs ...func(set *pflag.FlagSet)) *TestContextBuilder { + tcb.envPreHooks = append(tcb.envPreHooks, fs...) + + return tcb +} + +func (tcb *TestContextBuilder) WithEnvPostExtensions(fs ...func(e env.Environment, servers map[string]FakeServer)) *TestContextBuilder { + tcb.envPostHooks = append(tcb.envPostHooks, fs...) + + return tcb +} + +func (tcb *TestContextBuilder) WithSMExtensions(fs ...func(ctx context.Context, smb *sm.ServiceManagerBuilder, e env.Environment) error) *TestContextBuilder { + tcb.smExtensions = append(tcb.smExtensions, fs...) + + return tcb +} + +func (tcb *TestContextBuilder) Build() *TestContext { + environment := tcb.Environment(tcb.envPreHooks...) + + for _, envPostHook := range tcb.envPostHooks { + envPostHook(environment, tcb.Servers) + } + + smServer := newSMServer(environment, tcb.smExtensions) + tcb.Servers[SMServer] = smServer + + SM := httpexpect.New(GinkgoT(), smServer.URL()) + oauthServer := tcb.Servers[OauthServer].(*OAuthServer) + accessToken := oauthServer.CreateToken(tcb.defaultTokenClaims) + SMWithOAuth := SM.Builder(func(req *httpexpect.Request) { + req.WithHeader("Authorization", "Bearer "+accessToken) }) + RemoveAllBrokers(SMWithOAuth) + RemoveAllPlatforms(SMWithOAuth) + + testContext := &TestContext{ + SM: SM, + SMWithOAuth: SMWithOAuth, + Servers: tcb.Servers, + } + + if !tcb.shouldSkipBasicAuthClient { + platformJSON := MakePlatform("tcb-platform-test", "tcb-platform-test", "platform-type", "test-platform") + platform := RegisterPlatformInSM(platformJSON, SMWithOAuth) + SMWithBasic := SM.Builder(func(req *httpexpect.Request) { + username, password := platform.Credentials.Basic.Username, platform.Credentials.Basic.Password + req.WithBasicAuth(username, password) + }) + testContext.SMWithBasic = SMWithBasic + testContext.TestPlatform = platform + } + return testContext + +} + +func newSMServer(smEnv env.Environment, fs []func(ctx context.Context, smb *sm.ServiceManagerBuilder, env env.Environment) error) *testSMServer { ctx, cancel := context.WithCancel(context.Background()) s := struct { Log *log.Settings @@ -123,60 +239,18 @@ func NewSMServer(params *ContextParams, issuerURL string) *httptest.Server { panic(err) } ctx = log.Configure(ctx, s.Log) - smanagerBuilder := sm.New(ctx, cancel, smEnv) - if params.RegisterExtensions != nil { - params.RegisterExtensions(smanagerBuilder) - } - serviceManager := smanagerBuilder.Build() - return httptest.NewServer(serviceManager.Server.Router) -} - -func NewTestContext(params *ContextParams) *TestContext { - if params == nil { - params = &ContextParams{} + smb := sm.New(ctx, cancel, smEnv) + for _, registerExtensionsFunc := range fs { + if err := registerExtensionsFunc(ctx, smb, smEnv); err != nil { + panic(fmt.Sprintf("error creating test SM server: %s", err)) + } } - - oauthServer := NewOAuthServer() - oauthServer.Start() - - smServer := NewSMServer(params, oauthServer.URL) - SM := httpexpect.New(GinkgoT(), smServer.URL) - - accessToken := oauthServer.CreateToken(params.DefaultTokenClaims) - SMWithOAuth := SM.Builder(func(req *httpexpect.Request) { - req.WithHeader("Authorization", "Bearer "+accessToken) - }) - RemoveAllBrokers(SMWithOAuth) - RemoveAllPlatforms(SMWithOAuth) - - platformJSON := MakePlatform("ctx-platform-test", "ctx-platform-test", "platform-type", "test-platform") - platform := RegisterPlatformInSM(platformJSON, SMWithOAuth) - SMWithBasic := SM.Builder(func(req *httpexpect.Request) { - username, password := platform.Credentials.Basic.Username, platform.Credentials.Basic.Password - req.WithBasicAuth(username, password) - }) - - return &TestContext{ - SM: SM, - SMWithOAuth: SMWithOAuth, - SMWithBasic: SMWithBasic, - TestPlatform: platform, - smServer: smServer, - OAuthServer: oauthServer, - brokers: make(map[string]*BrokerServer), + serviceManager := smb.Build() + return &testSMServer{ + Server: httptest.NewServer(serviceManager.Server.Router), } } -type TestContext struct { - SM *httpexpect.Expect - SMWithOAuth *httpexpect.Expect - SMWithBasic *httpexpect.Expect - TestPlatform *types.Platform - smServer *httptest.Server - OAuthServer *OAuthServer - brokers map[string]*BrokerServer -} - func (ctx *TestContext) RegisterBrokerWithCatalogAndLabels(catalog SBCatalog, labels Object) (string, Object, *BrokerServer) { brokerServer := NewBrokerServerWithCatalog(catalog) UUID, err := uuid.NewV4() @@ -189,7 +263,7 @@ func (ctx *TestContext) RegisterBrokerWithCatalogAndLabels(catalog SBCatalog, la } brokerJSON := Object{ "name": UUID.String(), - "broker_url": brokerServer.URL, + "broker_url": brokerServer.URL(), "description": UUID2.String(), "credentials": Object{ "basic": Object{ @@ -205,7 +279,7 @@ func (ctx *TestContext) RegisterBrokerWithCatalogAndLabels(catalog SBCatalog, la brokerID := RegisterBrokerInSM(brokerJSON, ctx.SMWithOAuth) brokerServer.ResetCallHistory() - ctx.brokers[brokerID] = brokerServer + ctx.Servers[BrokerServerPrefix+brokerID] = brokerServer brokerJSON["id"] = brokerID return brokerID, brokerJSON, brokerServer } @@ -232,36 +306,18 @@ func (ctx *TestContext) RegisterPlatform() *types.Platform { } func (ctx *TestContext) CleanupBroker(id string) { - broker := ctx.brokers[id] + broker := ctx.Servers[BrokerServerPrefix+id] ctx.SMWithOAuth.DELETE("/v1/service_brokers/" + id).Expect() - if broker != nil && broker.Server != nil { - broker.Server.Close() - } - delete(ctx.brokers, id) + broker.Close() + delete(ctx.Servers, BrokerServerPrefix+id) } func (ctx *TestContext) Cleanup() { - if ctx == nil { - return - } - - if ctx.SMWithOAuth != nil { - RemoveAllBrokers(ctx.SMWithOAuth) - RemoveAllPlatforms(ctx.SMWithOAuth) - } - - for _, broker := range ctx.brokers { - if broker != nil && broker.Server != nil { - broker.Server.Close() - } - } - - if ctx.smServer != nil { - ctx.smServer.Close() - } + RemoveAllBrokers(ctx.SMWithOAuth) + RemoveAllPlatforms(ctx.SMWithOAuth) - if ctx.OAuthServer != nil { - ctx.OAuthServer.Close() + for _, server := range ctx.Servers { + server.Close() } } diff --git a/test/filter_test/filter_test.go b/test/filter_test/filter_test.go index f20c960e8..62c5a27c4 100644 --- a/test/filter_test/filter_test.go +++ b/test/filter_test/filter_test.go @@ -1,9 +1,12 @@ package filter_test import ( + "context" "net/http" "testing" + "github.com/Peripli/service-manager/pkg/env" + "github.com/Peripli/service-manager/pkg/sm" "github.com/Peripli/service-manager/pkg/web" @@ -27,11 +30,11 @@ var _ = Describe("Service Manager Filters", func() { var order string JustBeforeEach(func() { - ctx = common.NewTestContext(&common.ContextParams{ - RegisterExtensions: func(smb *sm.ServiceManagerBuilder) { - smb.API.RegisterFilters(testFilters...) - }, - }) + ctx = common.NewTestContextBuilder().WithSMExtensions(func(ctx context.Context, smb *sm.ServiceManagerBuilder, env env.Environment) error { + smb.API.RegisterFilters(testFilters...) + return nil + }).Build() + brokerID, _, _ := ctx.RegisterBroker() osbURL = "/v1/osb/" + brokerID order = "" diff --git a/test/filter_test/public_plans_test.go b/test/filter_test/public_plans_test.go index 09f6d537a..d8ea692da 100644 --- a/test/filter_test/public_plans_test.go +++ b/test/filter_test/public_plans_test.go @@ -17,8 +17,11 @@ package filter_test import ( + "context" "net/http" + "github.com/Peripli/service-manager/pkg/env" + "github.com/Peripli/service-manager/api/filters" "github.com/Peripli/service-manager/pkg/sm" "github.com/Peripli/service-manager/pkg/types" @@ -85,16 +88,15 @@ var _ = Describe("Service Manager Public Plans Filter", func() { } BeforeSuite(func() { - ctx = common.NewTestContext(&common.ContextParams{ - RegisterExtensions: func(smb *sm.ServiceManagerBuilder) { - smb.RegisterFilters(&filters.PublicServicePlansFilter{ - Repository: smb.Storage, - IsCatalogPlanPublicFunc: func(broker *types.Broker, catalogService *types.ServiceOffering, catalogPlan *types.ServicePlan) (b bool, e error) { - return catalogPlan.Free, nil - }, - }) - }, - }) + ctx = common.NewTestContextBuilder().WithSMExtensions(func(ctx context.Context, smb *sm.ServiceManagerBuilder, e env.Environment) error { + smb.RegisterFilters(&filters.PublicServicePlansFilter{ + Repository: smb.Storage, + IsCatalogPlanPublicFunc: func(broker *types.Broker, catalogService *types.ServiceOffering, catalogPlan *types.ServicePlan) (b bool, e error) { + return catalogPlan.Free, nil + }, + }) + return nil + }).Build() }) AfterSuite(func() { diff --git a/test/healthcheck_test/healthcheck_test.go b/test/healthcheck_test/healthcheck_test.go index 94e0b951d..e1ec9f053 100644 --- a/test/healthcheck_test/healthcheck_test.go +++ b/test/healthcheck_test/healthcheck_test.go @@ -34,7 +34,7 @@ var _ = Describe("Healthcheck API", func() { var ctx *common.TestContext BeforeSuite(func() { - ctx = common.NewTestContext(nil) + ctx = common.DefaultTestContext() }) AfterSuite(func() { diff --git a/test/info_test/info_test.go b/test/info_test/info_test.go index c421a2362..ab9336ba9 100644 --- a/test/info_test/info_test.go +++ b/test/info_test/info_test.go @@ -20,18 +20,13 @@ import ( "net/http" "testing" + "github.com/Peripli/service-manager/pkg/env" + "github.com/Peripli/service-manager/api/info" "github.com/Peripli/service-manager/test/common" . "github.com/onsi/ginkgo" ) -type Object = common.Object - -var ( - True = true - False = false -) - func TestInfo(t *testing.T) { RunSpecs(t, "Info Suite") } @@ -39,12 +34,11 @@ func TestInfo(t *testing.T) { var _ = Describe("Info API", func() { cases := []struct { description string - configBasicAuth *bool + configBasicAuth bool expectBasicAuth bool }{ - {"Returns token_issuer_url and token_basic_auth: true by default", nil, true}, - {"Returns token_issuer_url and token_basic_auth: true", &True, true}, - {"Returns token_issuer_url and token_basic_auth: false", &False, false}, + {"Returns token_issuer_url and token_basic_auth: true", true, true}, + {"Returns token_issuer_url and token_basic_auth: false", false, false}, } for _, tc := range cases { @@ -52,11 +46,10 @@ var _ = Describe("Info API", func() { var ctx *common.TestContext BeforeEach(func() { - env := common.TestEnv() - if tc.configBasicAuth != nil { - env.Set("api.token_basic_auth", *tc.configBasicAuth) + postHook := func(e env.Environment, servers map[string]common.FakeServer) { + e.Set("api.token_basic_auth", tc.configBasicAuth) } - ctx = common.NewTestContext(&common.ContextParams{Env: env}) + ctx = common.NewTestContextBuilder().WithEnvPostExtensions(postHook).Build() }) AfterEach(func() { @@ -67,8 +60,8 @@ var _ = Describe("Info API", func() { ctx.SM.GET(info.URL). Expect(). Status(http.StatusOK). - JSON().Object().Equal(Object{ - "token_issuer_url": ctx.OAuthServer.URL, + JSON().Object().Equal(common.Object{ + "token_issuer_url": ctx.Servers[common.OauthServer].URL(), "token_basic_auth": tc.expectBasicAuth, }) }) diff --git a/test/osb_test/osb_test.go b/test/osb_test/osb_test.go index b6ccd6b8d..c42a061f1 100644 --- a/test/osb_test/osb_test.go +++ b/test/osb_test/osb_test.go @@ -148,18 +148,18 @@ var _ = Describe("Service Manager OSB API", func() { ) BeforeSuite(func() { - ctx = common.NewTestContext(nil) + ctx = common.DefaultTestContext() validBrokerID, _, validBrokerServer = ctx.RegisterBroker() - smUrlToWorkingBroker = validBrokerServer.URL + "/v1/osb/" + validBrokerID + smUrlToWorkingBroker = validBrokerServer.URL() + "/v1/osb/" + validBrokerID emptyCatalogBrokerID, _, brokerServerWithEmptyCatalog = ctx.RegisterBrokerWithCatalog(common.NewEmptySBCatalog()) - smUrlToEmptyCatalogBroker = brokerServerWithEmptyCatalog.URL + "/v1/osb/" + emptyCatalogBrokerID + smUrlToEmptyCatalogBroker = brokerServerWithEmptyCatalog.URL() + "/v1/osb/" + emptyCatalogBrokerID simpleBrokerCatalogID, _, brokerServerWithSimpleCatalog := ctx.RegisterBrokerWithCatalog(simpleCatalog) - smUrlToSimpleBrokerCatalogBroker = brokerServerWithSimpleCatalog.URL + "/v1/osb/" + simpleBrokerCatalogID + smUrlToSimpleBrokerCatalogBroker = brokerServerWithSimpleCatalog.URL() + "/v1/osb/" + simpleBrokerCatalogID failingBrokerID, _, failingBrokerServer = ctx.RegisterBroker() - smUrlToFailingBroker = failingBrokerServer.URL + "/v1/osb/" + failingBrokerID + smUrlToFailingBroker = failingBrokerServer.URL() + "/v1/osb/" + failingBrokerID failingBrokerServer.ServiceInstanceHandler = failingHandler failingBrokerServer.BindingHandler = failingHandler failingBrokerServer.CatalogHandler = failingHandler @@ -176,7 +176,7 @@ var _ = Describe("Service Manager OSB API", func() { stoppedBrokerID, _, stoppedBrokerServer = ctx.RegisterBroker() stoppedBrokerServer.Close() - smUrlToStoppedBroker = stoppedBrokerServer.URL + "/v1/osb/" + stoppedBrokerID + smUrlToStoppedBroker = stoppedBrokerServer.URL() + "/v1/osb/" + stoppedBrokerID headerKey, headerValue = generateRandomQueryParam() queryParameterVerificationServerID, _, queryParameterVerificationServer := ctx.RegisterBroker() @@ -185,7 +185,7 @@ var _ = Describe("Service Manager OSB API", func() { queryParameterVerificationServer.CatalogHandler = queryParameterVerificationHandler(headerKey, headerValue) queryParameterVerificationServer.ServiceInstanceLastOpHandler = queryParameterVerificationHandler(headerKey, headerValue) queryParameterVerificationServer.BindingLastOpHandler = queryParameterVerificationHandler(headerKey, headerValue) - smUrlToQueryVerificationBroker = queryParameterVerificationServer.URL + "/v1/osb/" + queryParameterVerificationServerID + smUrlToQueryVerificationBroker = queryParameterVerificationServer.URL() + "/v1/osb/" + queryParameterVerificationServerID }) AfterSuite(func() { @@ -559,15 +559,15 @@ var _ = Describe("Service Manager OSB API", func() { const brokerPathPrefix = "/broker_prefix" var ( - prefixedBrokerServer *httptest.Server - osbURL string - prefixedBrokerID string + server common.FakeServer + osbURL string + prefixedBrokerID string ) BeforeEach(func() { brokerHandler := &prefixedBrokerHandler{brokerPathPrefix} - prefixedBrokerServer = httptest.NewServer(brokerHandler) - brokerURL := prefixedBrokerServer.URL + brokerPathPrefix + server = &prefixedBrokerServer{Server: httptest.NewServer(brokerHandler)} + brokerURL := server.URL() + brokerPathPrefix brokerJSON := common.Object{ "name": "prefixed_broker", @@ -581,14 +581,12 @@ var _ = Describe("Service Manager OSB API", func() { }, } prefixedBrokerID = common.RegisterBrokerInSM(brokerJSON, ctx.SMWithOAuth) + ctx.Servers[common.BrokerServerPrefix+prefixedBrokerID] = server osbURL = "/v1/osb/" + prefixedBrokerID }) AfterEach(func() { ctx.CleanupBroker(prefixedBrokerID) - if prefixedBrokerServer != nil { - prefixedBrokerServer.Close() - } }) It("should get catalog", func() { @@ -611,3 +609,11 @@ func (pbh *prefixedBrokerHandler) ServeHTTP(w http.ResponseWriter, req *http.Req common.SetResponse(w, http.StatusNotFound, common.Object{}) } } + +type prefixedBrokerServer struct { + *httptest.Server +} + +func (pbs *prefixedBrokerServer) URL() string { + return pbs.Server.URL +} diff --git a/test/plugin_test/plugin_test.go b/test/plugin_test/plugin_test.go index 03c0788f4..3546956db 100644 --- a/test/plugin_test/plugin_test.go +++ b/test/plugin_test/plugin_test.go @@ -1,12 +1,15 @@ package plugin_test import ( + "context" "encoding/json" "fmt" "net/http" "strconv" "testing" + "github.com/Peripli/service-manager/pkg/env" + "github.com/Peripli/service-manager/pkg/sm" "github.com/Peripli/service-manager/test/common" @@ -38,11 +41,11 @@ var _ = Describe("Service Manager Plugins", func() { Describe("Partial plugin", func() { BeforeEach(func() { - ctx = common.NewTestContext(&common.ContextParams{ - RegisterExtensions: func(smb *sm.ServiceManagerBuilder) { - smb.API.RegisterPlugins(&PartialPlugin{}) - }, - }) + ctx = common.NewTestContextBuilder().WithSMExtensions(func(ctx context.Context, smb *sm.ServiceManagerBuilder, e env.Environment) error { + smb.API.RegisterPlugins(&PartialPlugin{}) + return nil + }).Build() + var brokerID string brokerID, _, brokerServer = ctx.RegisterBroker() osbURL = "/v1/osb/" + brokerID @@ -67,11 +70,11 @@ var _ = Describe("Service Manager Plugins", func() { BeforeEach(func() { testPlugin = TestPlugin{} - ctx = common.NewTestContext(&common.ContextParams{ - RegisterExtensions: func(smb *sm.ServiceManagerBuilder) { - smb.API.RegisterPlugins(testPlugin) - }, - }) + ctx = common.NewTestContextBuilder().WithSMExtensions(func(ctx context.Context, smb *sm.ServiceManagerBuilder, e env.Environment) error { + smb.API.RegisterPlugins(testPlugin) + return nil + }).Build() + var brokerID string brokerID, _, brokerServer = ctx.RegisterBroker() osbURL = "/v1/osb/" + brokerID @@ -163,7 +166,7 @@ var _ = Describe("Service Manager Plugins", func() { ctx.SMWithBasic.GET(osbURL + "/v2/catalog"). Expect().Status(http.StatusOK) - Expect(brokerServer.Server.URL).To(ContainSubstring(brokerServer.LastRequest.Host)) + Expect(brokerServer.URL()).To(ContainSubstring(brokerServer.LastRequest.Host)) }) osbOperations := []struct { diff --git a/test/sm_test/sm_test.go b/test/sm_test/sm_test.go index 9ed1c3a7c..f39a2656b 100644 --- a/test/sm_test/sm_test.go +++ b/test/sm_test/sm_test.go @@ -53,7 +53,6 @@ var _ = Describe("SM", func() { ctx, cancel = context.WithCancel(context.Background()) oauthServer = common.NewOAuthServer() - oauthServer.Start() }) AfterSuite(func() { @@ -77,7 +76,7 @@ var _ = Describe("SM", func() { It("should panic", func() { Expect(func() { env := sm.DefaultEnv(common.SetTestFileLocation) - env.Set("api.token_issuer_url", oauthServer.URL) + env.Set("api.token_issuer_url", oauthServer.URL()) env.Set("log.level", "invalid") sm.New(ctx, cancel, env) }).To(Panic()) @@ -88,7 +87,7 @@ var _ = Describe("SM", func() { It("should panic", func() { Expect(func() { env := sm.DefaultEnv(common.SetTestFileLocation) - env.Set("api.token_issuer_url", oauthServer.URL) + env.Set("api.token_issuer_url", oauthServer.URL()) env.Set("storage.uri", "invalid") sm.New(ctx, cancel, env) }).To(Panic()) @@ -108,7 +107,7 @@ var _ = Describe("SM", func() { Context("when no API extensions are registered", func() { It("should return working service manager", func() { env := sm.DefaultEnv(common.SetTestFileLocation) - env.Set("api.token_issuer_url", oauthServer.URL) + env.Set("api.token_issuer_url", oauthServer.URL()) smanager := sm.New(ctx, cancel, env) verifyServiceManagerStartsSuccessFully(httptest.NewServer(smanager.Build().Server.Router)) @@ -119,7 +118,7 @@ var _ = Describe("SM", func() { Context("when additional filter is registered", func() { It("should return working service manager with a new filter", func() { env := sm.DefaultEnv(common.SetTestFileLocation) - env.Set("api.token_issuer_url", oauthServer.URL) + env.Set("api.token_issuer_url", oauthServer.URL()) smanager := sm.New(ctx, cancel, env) smanager.RegisterFilters(testFilter{}) @@ -134,7 +133,7 @@ var _ = Describe("SM", func() { Context("when additional controller is registered", func() { It("should return working service manager with additional controller", func() { env := sm.DefaultEnv(common.SetTestFileLocation) - env.Set("api.token_issuer_url", oauthServer.URL) + env.Set("api.token_issuer_url", oauthServer.URL()) smanager := sm.New(ctx, cancel, env) smanager.RegisterControllers(testController{}) diff --git a/test/test.go b/test/test.go index f00268549..04357ec14 100644 --- a/test/test.go +++ b/test/test.go @@ -56,7 +56,7 @@ func DescribeTestsFor(t TestCase) bool { By("==== Preparation for SM tests... ====") defer GinkgoRecover() - ctx = common.NewTestContext(nil) + ctx = common.DefaultTestContext() // A panic outside of Ginkgo's primitives (during test setup) would be recovered // by the deferred GinkgoRecover() and the error will be associated with the first