diff --git a/README.md b/README.md index 8bb1e248..e2d5d571 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ Service Name | Package name [IAM Identity Service](https://cloud.ibm.com/apidocs/iam-identity-token-api?code=go) | iamidentityv1 [IAM Policy Management](https://cloud.ibm.com/apidocs/iam-policy-management?code=go) | iampolicymanagementv1 [IBM Cloud Shell](https://cloud.ibm.com/apidocs/cloudshell?code=go) | ibmcloudshellv1 +[Metrics Router](https://cloud.ibm.com/apidocs/metrics-router/metrics-router-v3) | metricsrouterv3 [Open Service Broker](https://cloud.ibm.com/apidocs/resource-controller/ibm-cloud-osb-api?code=go) | openservicebrokerv1 [Resource Controller](https://cloud.ibm.com/apidocs/resource-controller/resource-controller?code=go) | resourcecontrollerv2 [Resource Manager](https://cloud.ibm.com/apidocs/resource-controller/resource-manager?code=go) | resourcemanagerv2 diff --git a/metricsrouterv3/metrics_router_v3.go b/metricsrouterv3/metrics_router_v3.go new file mode 100644 index 00000000..4394f93b --- /dev/null +++ b/metricsrouterv3/metrics_router_v3.go @@ -0,0 +1,1801 @@ +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * IBM OpenAPI SDK Code Generator Version: 3.61.0-1667892a-20221109-194550 + */ + +// Package metricsrouterv3 : Operations and models for the MetricsRouterV3 service +package metricsrouterv3 + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "reflect" + "time" + + "github.com/IBM/go-sdk-core/v5/core" + common "github.com/IBM/platform-services-go-sdk/common" + "github.com/go-openapi/strfmt" +) + +// MetricsRouterV3 : IBM Cloud Metrics Routing allows you to configure how to route platform metrics in your account. +// +// API Version: 3.0.0 +type MetricsRouterV3 struct { + Service *core.BaseService +} + +// DefaultServiceURL is the default URL to make service requests to. +const DefaultServiceURL = "https://au-syd.metrics-router.cloud.ibm.com/api/v3" + +// DefaultServiceName is the default key used to find external configuration information. +const DefaultServiceName = "metrics_router" + +// MetricsRouterV3Options : Service options +type MetricsRouterV3Options struct { + ServiceName string + URL string + Authenticator core.Authenticator +} + +// NewMetricsRouterV3UsingExternalConfig : constructs an instance of MetricsRouterV3 with passed in options and external configuration. +func NewMetricsRouterV3UsingExternalConfig(options *MetricsRouterV3Options) (metricsRouter *MetricsRouterV3, err error) { + if options.ServiceName == "" { + options.ServiceName = DefaultServiceName + } + + if options.Authenticator == nil { + options.Authenticator, err = core.GetAuthenticatorFromEnvironment(options.ServiceName) + if err != nil { + return + } + } + + metricsRouter, err = NewMetricsRouterV3(options) + if err != nil { + return + } + + err = metricsRouter.Service.ConfigureService(options.ServiceName) + if err != nil { + return + } + + if options.URL != "" { + err = metricsRouter.Service.SetServiceURL(options.URL) + } + return +} + +// NewMetricsRouterV3 : constructs an instance of MetricsRouterV3 with passed in options. +func NewMetricsRouterV3(options *MetricsRouterV3Options) (service *MetricsRouterV3, err error) { + serviceOptions := &core.ServiceOptions{ + URL: DefaultServiceURL, + Authenticator: options.Authenticator, + } + + baseService, err := core.NewBaseService(serviceOptions) + if err != nil { + return + } + + if options.URL != "" { + err = baseService.SetServiceURL(options.URL) + if err != nil { + return + } + } + + service = &MetricsRouterV3{ + Service: baseService, + } + + return +} + +// GetServiceURLForRegion returns the service URL to be used for the specified region +func GetServiceURLForRegion(region string) (string, error) { + var endpoints = map[string]string{ + "au-syd": "https://au-syd.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the au-syd region. + "private.au-syd": "https://private.au-syd.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the au-syd region with private endpoint. + "eu-de": "https://eu-de.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the eu-de region. + "private.eu-de": "https://private.eu-de.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the eu-de region with private endpoint. + "eu-gb": "https://eu-gb.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the eu-gb region. + "private.eu-gb": "https://private.eu-gb.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the eu-gb region with private endpoint. + "us-east": "https://us-east.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the us-east region. + "private.us-east": "https://private.us-east.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the us-east region with private endpoint. + "us-south": "https://us-south.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the us-south region. + "private.us-south": "https://private.us-south.metrics-router.cloud.ibm.com/api/v3", // The server for IBM Cloud Metrics Routing Service in the us-south region with private endpoint. + } + + if url, ok := endpoints[region]; ok { + return url, nil + } + return "", fmt.Errorf("service URL for region '%s' not found", region) +} + +// Clone makes a copy of "metricsRouter" suitable for processing requests. +func (metricsRouter *MetricsRouterV3) Clone() *MetricsRouterV3 { + if core.IsNil(metricsRouter) { + return nil + } + clone := *metricsRouter + clone.Service = metricsRouter.Service.Clone() + return &clone +} + +// SetServiceURL sets the service URL +func (metricsRouter *MetricsRouterV3) SetServiceURL(url string) error { + return metricsRouter.Service.SetServiceURL(url) +} + +// GetServiceURL returns the service URL +func (metricsRouter *MetricsRouterV3) GetServiceURL() string { + return metricsRouter.Service.GetServiceURL() +} + +// SetDefaultHeaders sets HTTP headers to be sent in every request +func (metricsRouter *MetricsRouterV3) SetDefaultHeaders(headers http.Header) { + metricsRouter.Service.SetDefaultHeaders(headers) +} + +// SetEnableGzipCompression sets the service's EnableGzipCompression field +func (metricsRouter *MetricsRouterV3) SetEnableGzipCompression(enableGzip bool) { + metricsRouter.Service.SetEnableGzipCompression(enableGzip) +} + +// GetEnableGzipCompression returns the service's EnableGzipCompression field +func (metricsRouter *MetricsRouterV3) GetEnableGzipCompression() bool { + return metricsRouter.Service.GetEnableGzipCompression() +} + +// EnableRetries enables automatic retries for requests invoked for this service instance. +// If either parameter is specified as 0, then a default value is used instead. +func (metricsRouter *MetricsRouterV3) EnableRetries(maxRetries int, maxRetryInterval time.Duration) { + metricsRouter.Service.EnableRetries(maxRetries, maxRetryInterval) +} + +// DisableRetries disables automatic retries for requests invoked for this service instance. +func (metricsRouter *MetricsRouterV3) DisableRetries() { + metricsRouter.Service.DisableRetries() +} + +// CreateTarget : Create a target +// Creates a target that includes information about the destination required to write platform metrics to that target. +// You can send your platform metrics from all regions to a single target, different targets or multiple targets. One +// target per region is not required. You can define up to 16 targets per account. +func (metricsRouter *MetricsRouterV3) CreateTarget(createTargetOptions *CreateTargetOptions) (result *Target, response *core.DetailedResponse, err error) { + return metricsRouter.CreateTargetWithContext(context.Background(), createTargetOptions) +} + +// CreateTargetWithContext is an alternate form of the CreateTarget method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) CreateTargetWithContext(ctx context.Context, createTargetOptions *CreateTargetOptions) (result *Target, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createTargetOptions, "createTargetOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(createTargetOptions, "createTargetOptions") + if err != nil { + return + } + + builder := core.NewRequestBuilder(core.POST) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/targets`, nil) + if err != nil { + return + } + + for headerName, headerValue := range createTargetOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "CreateTarget") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if createTargetOptions.Name != nil { + body["name"] = createTargetOptions.Name + } + if createTargetOptions.DestinationCRN != nil { + body["destination_crn"] = createTargetOptions.DestinationCRN + } + if createTargetOptions.Region != nil { + body["region"] = createTargetOptions.Region + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTarget) + if err != nil { + return + } + response.Result = result + } + + return +} + +// ListTargets : List targets +// List all targets that are defined for your account. +func (metricsRouter *MetricsRouterV3) ListTargets(listTargetsOptions *ListTargetsOptions) (result *TargetCollection, response *core.DetailedResponse, err error) { + return metricsRouter.ListTargetsWithContext(context.Background(), listTargetsOptions) +} + +// ListTargetsWithContext is an alternate form of the ListTargets method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) ListTargetsWithContext(ctx context.Context, listTargetsOptions *ListTargetsOptions) (result *TargetCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listTargetsOptions, "listTargetsOptions") + if err != nil { + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/targets`, nil) + if err != nil { + return + } + + for headerName, headerValue := range listTargetsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "ListTargets") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTargetCollection) + if err != nil { + return + } + response.Result = result + } + + return +} + +// GetTarget : Get details of a target +// Retrieve the configuration details of a target. +func (metricsRouter *MetricsRouterV3) GetTarget(getTargetOptions *GetTargetOptions) (result *Target, response *core.DetailedResponse, err error) { + return metricsRouter.GetTargetWithContext(context.Background(), getTargetOptions) +} + +// GetTargetWithContext is an alternate form of the GetTarget method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) GetTargetWithContext(ctx context.Context, getTargetOptions *GetTargetOptions) (result *Target, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getTargetOptions, "getTargetOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(getTargetOptions, "getTargetOptions") + if err != nil { + return + } + + pathParamsMap := map[string]string{ + "id": *getTargetOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/targets/{id}`, pathParamsMap) + if err != nil { + return + } + + for headerName, headerValue := range getTargetOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "GetTarget") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTarget) + if err != nil { + return + } + response.Result = result + } + + return +} + +// UpdateTarget : Update a target +// Update the configuration details of a target. +func (metricsRouter *MetricsRouterV3) UpdateTarget(updateTargetOptions *UpdateTargetOptions) (result *Target, response *core.DetailedResponse, err error) { + return metricsRouter.UpdateTargetWithContext(context.Background(), updateTargetOptions) +} + +// UpdateTargetWithContext is an alternate form of the UpdateTarget method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) UpdateTargetWithContext(ctx context.Context, updateTargetOptions *UpdateTargetOptions) (result *Target, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateTargetOptions, "updateTargetOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(updateTargetOptions, "updateTargetOptions") + if err != nil { + return + } + + pathParamsMap := map[string]string{ + "id": *updateTargetOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/targets/{id}`, pathParamsMap) + if err != nil { + return + } + + for headerName, headerValue := range updateTargetOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "UpdateTarget") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if updateTargetOptions.Name != nil { + body["name"] = updateTargetOptions.Name + } + if updateTargetOptions.DestinationCRN != nil { + body["destination_crn"] = updateTargetOptions.DestinationCRN + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTarget) + if err != nil { + return + } + response.Result = result + } + + return +} + +// DeleteTarget : Delete a target +// Delete a target. +func (metricsRouter *MetricsRouterV3) DeleteTarget(deleteTargetOptions *DeleteTargetOptions) (response *core.DetailedResponse, err error) { + return metricsRouter.DeleteTargetWithContext(context.Background(), deleteTargetOptions) +} + +// DeleteTargetWithContext is an alternate form of the DeleteTarget method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) DeleteTargetWithContext(ctx context.Context, deleteTargetOptions *DeleteTargetOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteTargetOptions, "deleteTargetOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(deleteTargetOptions, "deleteTargetOptions") + if err != nil { + return + } + + pathParamsMap := map[string]string{ + "id": *deleteTargetOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/targets/{id}`, pathParamsMap) + if err != nil { + return + } + + for headerName, headerValue := range deleteTargetOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "DeleteTarget") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + request, err := builder.Build() + if err != nil { + return + } + + response, err = metricsRouter.Service.Request(request, nil) + + return +} + +// CreateRoute : Create a route +// Create a route with rules that specify how to manage platform metrics routing. +func (metricsRouter *MetricsRouterV3) CreateRoute(createRouteOptions *CreateRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + return metricsRouter.CreateRouteWithContext(context.Background(), createRouteOptions) +} + +// CreateRouteWithContext is an alternate form of the CreateRoute method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) CreateRouteWithContext(ctx context.Context, createRouteOptions *CreateRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createRouteOptions, "createRouteOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(createRouteOptions, "createRouteOptions") + if err != nil { + return + } + + builder := core.NewRequestBuilder(core.POST) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/routes`, nil) + if err != nil { + return + } + + for headerName, headerValue := range createRouteOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "CreateRoute") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if createRouteOptions.Name != nil { + body["name"] = createRouteOptions.Name + } + if createRouteOptions.Rules != nil { + body["rules"] = createRouteOptions.Rules + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + if err != nil { + return + } + response.Result = result + } + + return +} + +// ListRoutes : List routes +// List the routes that are configured for an account. +func (metricsRouter *MetricsRouterV3) ListRoutes(listRoutesOptions *ListRoutesOptions) (result *RouteCollection, response *core.DetailedResponse, err error) { + return metricsRouter.ListRoutesWithContext(context.Background(), listRoutesOptions) +} + +// ListRoutesWithContext is an alternate form of the ListRoutes method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) ListRoutesWithContext(ctx context.Context, listRoutesOptions *ListRoutesOptions) (result *RouteCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listRoutesOptions, "listRoutesOptions") + if err != nil { + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/routes`, nil) + if err != nil { + return + } + + for headerName, headerValue := range listRoutesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "ListRoutes") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRouteCollection) + if err != nil { + return + } + response.Result = result + } + + return +} + +// GetRoute : Get details of a route +// Get the configuration details of a route. +func (metricsRouter *MetricsRouterV3) GetRoute(getRouteOptions *GetRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + return metricsRouter.GetRouteWithContext(context.Background(), getRouteOptions) +} + +// GetRouteWithContext is an alternate form of the GetRoute method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) GetRouteWithContext(ctx context.Context, getRouteOptions *GetRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getRouteOptions, "getRouteOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(getRouteOptions, "getRouteOptions") + if err != nil { + return + } + + pathParamsMap := map[string]string{ + "id": *getRouteOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/routes/{id}`, pathParamsMap) + if err != nil { + return + } + + for headerName, headerValue := range getRouteOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "GetRoute") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + if err != nil { + return + } + response.Result = result + } + + return +} + +// UpdateRoute : Update a route +// Update the configuration details of a route. +func (metricsRouter *MetricsRouterV3) UpdateRoute(updateRouteOptions *UpdateRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + return metricsRouter.UpdateRouteWithContext(context.Background(), updateRouteOptions) +} + +// UpdateRouteWithContext is an alternate form of the UpdateRoute method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) UpdateRouteWithContext(ctx context.Context, updateRouteOptions *UpdateRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateRouteOptions, "updateRouteOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(updateRouteOptions, "updateRouteOptions") + if err != nil { + return + } + + pathParamsMap := map[string]string{ + "id": *updateRouteOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/routes/{id}`, pathParamsMap) + if err != nil { + return + } + + for headerName, headerValue := range updateRouteOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "UpdateRoute") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if updateRouteOptions.Name != nil { + body["name"] = updateRouteOptions.Name + } + if updateRouteOptions.Rules != nil { + body["rules"] = updateRouteOptions.Rules + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + if err != nil { + return + } + response.Result = result + } + + return +} + +// DeleteRoute : Delete a route +// Deletes a route. +func (metricsRouter *MetricsRouterV3) DeleteRoute(deleteRouteOptions *DeleteRouteOptions) (response *core.DetailedResponse, err error) { + return metricsRouter.DeleteRouteWithContext(context.Background(), deleteRouteOptions) +} + +// DeleteRouteWithContext is an alternate form of the DeleteRoute method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) DeleteRouteWithContext(ctx context.Context, deleteRouteOptions *DeleteRouteOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteRouteOptions, "deleteRouteOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(deleteRouteOptions, "deleteRouteOptions") + if err != nil { + return + } + + pathParamsMap := map[string]string{ + "id": *deleteRouteOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/routes/{id}`, pathParamsMap) + if err != nil { + return + } + + for headerName, headerValue := range deleteRouteOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "DeleteRoute") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + request, err := builder.Build() + if err != nil { + return + } + + response, err = metricsRouter.Service.Request(request, nil) + + return +} + +// GetSettings : Get settings +// Get information about the current account level settings for Metrics Routing service. +func (metricsRouter *MetricsRouterV3) GetSettings(getSettingsOptions *GetSettingsOptions) (result *Setting, response *core.DetailedResponse, err error) { + return metricsRouter.GetSettingsWithContext(context.Background(), getSettingsOptions) +} + +// GetSettingsWithContext is an alternate form of the GetSettings method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) GetSettingsWithContext(ctx context.Context, getSettingsOptions *GetSettingsOptions) (result *Setting, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(getSettingsOptions, "getSettingsOptions") + if err != nil { + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/settings`, nil) + if err != nil { + return + } + + for headerName, headerValue := range getSettingsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "GetSettings") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSetting) + if err != nil { + return + } + response.Result = result + } + + return +} + +// UpdateSettings : Modify settings +// Modify the current account level settings such as default targets, permitted target regions, metadata region primary +// and secondary. +func (metricsRouter *MetricsRouterV3) UpdateSettings(updateSettingsOptions *UpdateSettingsOptions) (result *Setting, response *core.DetailedResponse, err error) { + return metricsRouter.UpdateSettingsWithContext(context.Background(), updateSettingsOptions) +} + +// UpdateSettingsWithContext is an alternate form of the UpdateSettings method which supports a Context parameter +func (metricsRouter *MetricsRouterV3) UpdateSettingsWithContext(ctx context.Context, updateSettingsOptions *UpdateSettingsOptions) (result *Setting, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateSettingsOptions, "updateSettingsOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(updateSettingsOptions, "updateSettingsOptions") + if err != nil { + return + } + + builder := core.NewRequestBuilder(core.PATCH) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = metricsRouter.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(metricsRouter.Service.Options.URL, `/settings`, nil) + if err != nil { + return + } + + for headerName, headerValue := range updateSettingsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("metrics_router", "V3", "UpdateSettings") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if updateSettingsOptions.DefaultTargets != nil { + body["default_targets"] = updateSettingsOptions.DefaultTargets + } + if updateSettingsOptions.PermittedTargetRegions != nil { + body["permitted_target_regions"] = updateSettingsOptions.PermittedTargetRegions + } + if updateSettingsOptions.PrimaryMetadataRegion != nil { + body["primary_metadata_region"] = updateSettingsOptions.PrimaryMetadataRegion + } + if updateSettingsOptions.BackupMetadataRegion != nil { + body["backup_metadata_region"] = updateSettingsOptions.BackupMetadataRegion + } + if updateSettingsOptions.PrivateAPIEndpointOnly != nil { + body["private_api_endpoint_only"] = updateSettingsOptions.PrivateAPIEndpointOnly + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = metricsRouter.Service.Request(request, &rawResponse) + if err != nil { + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSetting) + if err != nil { + return + } + response.Result = result + } + + return +} + +// CreateRouteOptions : The CreateRoute options. +type CreateRouteOptions struct { + // The name of the route. The name must be 1000 characters or less and cannot include any special characters other than + // `(space) - . _ :`. Do not include any personal identifying information (PII) in any resource names. + Name *string `json:"name" validate:"required"` + + // Routing rules that will be evaluated in their order of the array. + Rules []RulePrototype `json:"rules" validate:"required"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewCreateRouteOptions : Instantiate CreateRouteOptions +func (*MetricsRouterV3) NewCreateRouteOptions(name string, rules []RulePrototype) *CreateRouteOptions { + return &CreateRouteOptions{ + Name: core.StringPtr(name), + Rules: rules, + } +} + +// SetName : Allow user to set Name +func (_options *CreateRouteOptions) SetName(name string) *CreateRouteOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetRules : Allow user to set Rules +func (_options *CreateRouteOptions) SetRules(rules []RulePrototype) *CreateRouteOptions { + _options.Rules = rules + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *CreateRouteOptions) SetHeaders(param map[string]string) *CreateRouteOptions { + options.Headers = param + return options +} + +// CreateTargetOptions : The CreateTarget options. +type CreateTargetOptions struct { + // The name of the target. The name must be 1000 characters or less, and cannot include any special characters other + // than `(space) - . _ :`. Do not include any personal identifying information (PII) in any resource names. + Name *string `json:"name" validate:"required"` + + // The CRN of a destination service instance or resource. + DestinationCRN *string `json:"destination_crn" validate:"required"` + + // Include this optional field if you want to create a target in a different region other than the one you are + // connected. + Region *string `json:"region,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewCreateTargetOptions : Instantiate CreateTargetOptions +func (*MetricsRouterV3) NewCreateTargetOptions(name string, destinationCRN string) *CreateTargetOptions { + return &CreateTargetOptions{ + Name: core.StringPtr(name), + DestinationCRN: core.StringPtr(destinationCRN), + } +} + +// SetName : Allow user to set Name +func (_options *CreateTargetOptions) SetName(name string) *CreateTargetOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetDestinationCRN : Allow user to set DestinationCRN +func (_options *CreateTargetOptions) SetDestinationCRN(destinationCRN string) *CreateTargetOptions { + _options.DestinationCRN = core.StringPtr(destinationCRN) + return _options +} + +// SetRegion : Allow user to set Region +func (_options *CreateTargetOptions) SetRegion(region string) *CreateTargetOptions { + _options.Region = core.StringPtr(region) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *CreateTargetOptions) SetHeaders(param map[string]string) *CreateTargetOptions { + options.Headers = param + return options +} + +// DeleteRouteOptions : The DeleteRoute options. +type DeleteRouteOptions struct { + // The v4 UUID that uniquely identifies the route. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewDeleteRouteOptions : Instantiate DeleteRouteOptions +func (*MetricsRouterV3) NewDeleteRouteOptions(id string) *DeleteRouteOptions { + return &DeleteRouteOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *DeleteRouteOptions) SetID(id string) *DeleteRouteOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *DeleteRouteOptions) SetHeaders(param map[string]string) *DeleteRouteOptions { + options.Headers = param + return options +} + +// DeleteTargetOptions : The DeleteTarget options. +type DeleteTargetOptions struct { + // The v4 UUID that uniquely identifies the target. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewDeleteTargetOptions : Instantiate DeleteTargetOptions +func (*MetricsRouterV3) NewDeleteTargetOptions(id string) *DeleteTargetOptions { + return &DeleteTargetOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *DeleteTargetOptions) SetID(id string) *DeleteTargetOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *DeleteTargetOptions) SetHeaders(param map[string]string) *DeleteTargetOptions { + options.Headers = param + return options +} + +// GetRouteOptions : The GetRoute options. +type GetRouteOptions struct { + // The v4 UUID that uniquely identifies the route. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewGetRouteOptions : Instantiate GetRouteOptions +func (*MetricsRouterV3) NewGetRouteOptions(id string) *GetRouteOptions { + return &GetRouteOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *GetRouteOptions) SetID(id string) *GetRouteOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *GetRouteOptions) SetHeaders(param map[string]string) *GetRouteOptions { + options.Headers = param + return options +} + +// GetSettingsOptions : The GetSettings options. +type GetSettingsOptions struct { + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewGetSettingsOptions : Instantiate GetSettingsOptions +func (*MetricsRouterV3) NewGetSettingsOptions() *GetSettingsOptions { + return &GetSettingsOptions{} +} + +// SetHeaders : Allow user to set Headers +func (options *GetSettingsOptions) SetHeaders(param map[string]string) *GetSettingsOptions { + options.Headers = param + return options +} + +// GetTargetOptions : The GetTarget options. +type GetTargetOptions struct { + // The v4 UUID that uniquely identifies the target. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewGetTargetOptions : Instantiate GetTargetOptions +func (*MetricsRouterV3) NewGetTargetOptions(id string) *GetTargetOptions { + return &GetTargetOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *GetTargetOptions) SetID(id string) *GetTargetOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *GetTargetOptions) SetHeaders(param map[string]string) *GetTargetOptions { + options.Headers = param + return options +} + +// InclusionFilter : A list of conditions to be satisfied for routing metrics to pre-defined target. +type InclusionFilter struct { + // Part of CRN that can be compared with values. + Operand *string `json:"operand" validate:"required"` + + // The operation to be performed between operand and the provided values. 'is' to be used with one value and 'in' can + // support upto 20 values in the array. + Operator *string `json:"operator" validate:"required"` + + // The provided string values of the operand to be compared with. + Values []string `json:"values" validate:"required"` +} + +// Constants associated with the InclusionFilter.Operand property. +// Part of CRN that can be compared with values. +const ( + InclusionFilterOperandLocationConst = "location" + InclusionFilterOperandResourceConst = "resource" + InclusionFilterOperandResourceTypeConst = "resource_type" + InclusionFilterOperandServiceInstanceConst = "service_instance" + InclusionFilterOperandServiceNameConst = "service_name" +) + +// Constants associated with the InclusionFilter.Operator property. +// The operation to be performed between operand and the provided values. 'is' to be used with one value and 'in' can +// support upto 20 values in the array. +const ( + InclusionFilterOperatorInConst = "in" + InclusionFilterOperatorIsConst = "is" +) + +// UnmarshalInclusionFilter unmarshals an instance of InclusionFilter from the specified map of raw messages. +func UnmarshalInclusionFilter(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(InclusionFilter) + err = core.UnmarshalPrimitive(m, "operand", &obj.Operand) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "operator", &obj.Operator) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "values", &obj.Values) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// InclusionFilterPrototype : A list of conditions to be satisfied for routing metrics to pre-defined targets. +type InclusionFilterPrototype struct { + // Part of CRN that can be compared with values. + Operand *string `json:"operand" validate:"required"` + + // The operation to be performed between operand and the provided values. 'is' to be used with one value and 'in' can + // support upto 20 values in the array. + Operator *string `json:"operator" validate:"required"` + + // The provided string values of the operand to be compared with. + Values []string `json:"values" validate:"required"` +} + +// Constants associated with the InclusionFilterPrototype.Operand property. +// Part of CRN that can be compared with values. +const ( + InclusionFilterPrototypeOperandLocationConst = "location" + InclusionFilterPrototypeOperandResourceConst = "resource" + InclusionFilterPrototypeOperandResourceTypeConst = "resource_type" + InclusionFilterPrototypeOperandServiceInstanceConst = "service_instance" + InclusionFilterPrototypeOperandServiceNameConst = "service_name" +) + +// Constants associated with the InclusionFilterPrototype.Operator property. +// The operation to be performed between operand and the provided values. 'is' to be used with one value and 'in' can +// support upto 20 values in the array. +const ( + InclusionFilterPrototypeOperatorInConst = "in" + InclusionFilterPrototypeOperatorIsConst = "is" +) + +// NewInclusionFilterPrototype : Instantiate InclusionFilterPrototype (Generic Model Constructor) +func (*MetricsRouterV3) NewInclusionFilterPrototype(operand string, operator string, values []string) (_model *InclusionFilterPrototype, err error) { + _model = &InclusionFilterPrototype{ + Operand: core.StringPtr(operand), + Operator: core.StringPtr(operator), + Values: values, + } + err = core.ValidateStruct(_model, "required parameters") + return +} + +// UnmarshalInclusionFilterPrototype unmarshals an instance of InclusionFilterPrototype from the specified map of raw messages. +func UnmarshalInclusionFilterPrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(InclusionFilterPrototype) + err = core.UnmarshalPrimitive(m, "operand", &obj.Operand) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "operator", &obj.Operator) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "values", &obj.Values) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ListRoutesOptions : The ListRoutes options. +type ListRoutesOptions struct { + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewListRoutesOptions : Instantiate ListRoutesOptions +func (*MetricsRouterV3) NewListRoutesOptions() *ListRoutesOptions { + return &ListRoutesOptions{} +} + +// SetHeaders : Allow user to set Headers +func (options *ListRoutesOptions) SetHeaders(param map[string]string) *ListRoutesOptions { + options.Headers = param + return options +} + +// ListTargetsOptions : The ListTargets options. +type ListTargetsOptions struct { + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewListTargetsOptions : Instantiate ListTargetsOptions +func (*MetricsRouterV3) NewListTargetsOptions() *ListTargetsOptions { + return &ListTargetsOptions{} +} + +// SetHeaders : Allow user to set Headers +func (options *ListTargetsOptions) SetHeaders(param map[string]string) *ListTargetsOptions { + options.Headers = param + return options +} + +// Route : The route resource. The scope of the route is account wide. That means all the routes are evaluated in all regions, +// except the ones limited by region. +type Route struct { + // The UUID of the route resource. + ID *string `json:"id" validate:"required"` + + // The name of the route. + Name *string `json:"name" validate:"required"` + + // The crn of the route resource. + CRN *string `json:"crn" validate:"required"` + + // The routing rules that will be evaluated in their order of the array. Once a rule is matched, the remaining rules in + // the route definition will be skipped. + Rules []Rule `json:"rules" validate:"required"` + + // The timestamp of the route creation time. + CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` + + // The timestamp of the route last updated time. + UpdatedAt *strfmt.DateTime `json:"updated_at" validate:"required"` +} + +// UnmarshalRoute unmarshals an instance of Route from the specified map of raw messages. +func UnmarshalRoute(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(Route) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + return + } + err = core.UnmarshalModel(m, "rules", &obj.Rules, UnmarshalRule) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "updated_at", &obj.UpdatedAt) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// RouteCollection : A list of route resources. +type RouteCollection struct { + // A list of route resources. + Routes []Route `json:"routes" validate:"required"` +} + +// UnmarshalRouteCollection unmarshals an instance of RouteCollection from the specified map of raw messages. +func UnmarshalRouteCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(RouteCollection) + err = core.UnmarshalModel(m, "routes", &obj.Routes, UnmarshalRoute) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Rule : A configuration to route metrics to pre-defined target. +type Rule struct { + // The action if the inclusion_filters matches, default is `send` action. + Action *string `json:"action,omitempty"` + + // The target ID List. All the metrics will be sent to all targets listed in the rule. You can include targets from + // other regions. + Targets []TargetReference `json:"targets" validate:"required"` + + // A list of conditions to be satisfied for routing metrics to pre-defined target. + InclusionFilters []InclusionFilter `json:"inclusion_filters" validate:"required"` +} + +// Constants associated with the Rule.Action property. +// The action if the inclusion_filters matches, default is `send` action. +const ( + RuleActionDropConst = "drop" + RuleActionSendConst = "send" +) + +// UnmarshalRule unmarshals an instance of Rule from the specified map of raw messages. +func UnmarshalRule(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(Rule) + err = core.UnmarshalPrimitive(m, "action", &obj.Action) + if err != nil { + return + } + err = core.UnmarshalModel(m, "targets", &obj.Targets, UnmarshalTargetReference) + if err != nil { + return + } + err = core.UnmarshalModel(m, "inclusion_filters", &obj.InclusionFilters, UnmarshalInclusionFilter) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// RulePrototype : A configuration to route metrics to pre-defined target. +type RulePrototype struct { + // The action if the inclusion_filters matches, default is `send` action. + Action *string `json:"action,omitempty"` + + // A collection of targets with ID in the request. + Targets []TargetIdentity `json:"targets" validate:"required"` + + // A list of conditions to be satisfied for routing metrics to pre-defined target. + InclusionFilters []InclusionFilterPrototype `json:"inclusion_filters" validate:"required"` +} + +// Constants associated with the RulePrototype.Action property. +// The action if the inclusion_filters matches, default is `send` action. +const ( + RulePrototypeActionDropConst = "drop" + RulePrototypeActionSendConst = "send" +) + +// NewRulePrototype : Instantiate RulePrototype (Generic Model Constructor) +func (*MetricsRouterV3) NewRulePrototype(targets []TargetIdentity, inclusionFilters []InclusionFilterPrototype) (_model *RulePrototype, err error) { + _model = &RulePrototype{ + Targets: targets, + InclusionFilters: inclusionFilters, + } + err = core.ValidateStruct(_model, "required parameters") + return +} + +// UnmarshalRulePrototype unmarshals an instance of RulePrototype from the specified map of raw messages. +func UnmarshalRulePrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(RulePrototype) + err = core.UnmarshalPrimitive(m, "action", &obj.Action) + if err != nil { + return + } + err = core.UnmarshalModel(m, "targets", &obj.Targets, UnmarshalTargetIdentity) + if err != nil { + return + } + err = core.UnmarshalModel(m, "inclusion_filters", &obj.InclusionFilters, UnmarshalInclusionFilterPrototype) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Setting : Metrics routing settings response. +type Setting struct { + // A list of default target references. + DefaultTargets []TargetReference `json:"default_targets" validate:"required"` + + // If present then only these regions may be used to define a target. + PermittedTargetRegions []string `json:"permitted_target_regions" validate:"required"` + + // To store all your meta data in a single region. + PrimaryMetadataRegion *string `json:"primary_metadata_region" validate:"required"` + + // To backup all your meta data in a different region. + BackupMetadataRegion *string `json:"backup_metadata_region,omitempty"` + + // If you set this true then you cannot access api through public network. + PrivateAPIEndpointOnly *bool `json:"private_api_endpoint_only" validate:"required"` +} + +// UnmarshalSetting unmarshals an instance of Setting from the specified map of raw messages. +func UnmarshalSetting(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(Setting) + err = core.UnmarshalModel(m, "default_targets", &obj.DefaultTargets, UnmarshalTargetReference) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "permitted_target_regions", &obj.PermittedTargetRegions) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "primary_metadata_region", &obj.PrimaryMetadataRegion) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "backup_metadata_region", &obj.BackupMetadataRegion) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "private_api_endpoint_only", &obj.PrivateAPIEndpointOnly) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Target : Property values for a target in responses. +type Target struct { + // The UUID of the target resource. + ID *string `json:"id" validate:"required"` + + // The name of the target resource. + Name *string `json:"name" validate:"required"` + + // The crn of the target resource. + CRN *string `json:"crn" validate:"required"` + + // The CRN of the destination service instance or resource. + DestinationCRN *string `json:"destination_crn" validate:"required"` + + // The type of the target. + TargetType *string `json:"target_type" validate:"required"` + + // Include this optional field if you used it to create a target in a different region other than the one you are + // connected. + Region *string `json:"region,omitempty"` + + // The timestamp of the target creation time. + CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` + + // The timestamp of the target last updated time. + UpdatedAt *strfmt.DateTime `json:"updated_at" validate:"required"` +} + +// Constants associated with the Target.TargetType property. +// The type of the target. +const ( + TargetTargetTypeSysdigMonitorConst = "sysdig_monitor" +) + +// UnmarshalTarget unmarshals an instance of Target from the specified map of raw messages. +func UnmarshalTarget(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(Target) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "destination_crn", &obj.DestinationCRN) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "target_type", &obj.TargetType) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "region", &obj.Region) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "updated_at", &obj.UpdatedAt) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// TargetCollection : A list of target resources. +type TargetCollection struct { + // A list of target resources. + Targets []Target `json:"targets" validate:"required"` +} + +// UnmarshalTargetCollection unmarshals an instance of TargetCollection from the specified map of raw messages. +func UnmarshalTargetCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TargetCollection) + err = core.UnmarshalModel(m, "targets", &obj.Targets, UnmarshalTarget) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// TargetIdentity : A configuration to route metrics to pre-defined target. +type TargetIdentity struct { + // The target uuid for a pre-defined metrics router target. + ID *string `json:"id" validate:"required"` +} + +// NewTargetIdentity : Instantiate TargetIdentity (Generic Model Constructor) +func (*MetricsRouterV3) NewTargetIdentity(id string) (_model *TargetIdentity, err error) { + _model = &TargetIdentity{ + ID: core.StringPtr(id), + } + err = core.ValidateStruct(_model, "required parameters") + return +} + +// UnmarshalTargetIdentity unmarshals an instance of TargetIdentity from the specified map of raw messages. +func UnmarshalTargetIdentity(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TargetIdentity) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// TargetReference : A configuration to route metrics to pre-defined target. +type TargetReference struct { + // The target uuid for a pre-defined metrics router target. + ID *string `json:"id" validate:"required"` + + // The CRN of a pre-defined metrics-router target. + CRN *string `json:"crn" validate:"required"` + + // The name of a pre-defined metrics-router target. + Name *string `json:"name" validate:"required"` + + // The type of the target. + TargetType *string `json:"target_type" validate:"required"` +} + +// Constants associated with the TargetReference.TargetType property. +// The type of the target. +const ( + TargetReferenceTargetTypeSysdigMonitorConst = "sysdig_monitor" +) + +// UnmarshalTargetReference unmarshals an instance of TargetReference from the specified map of raw messages. +func UnmarshalTargetReference(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TargetReference) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "target_type", &obj.TargetType) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// UpdateRouteOptions : The UpdateRoute options. +type UpdateRouteOptions struct { + // The v4 UUID that uniquely identifies the route. + ID *string `json:"id" validate:"required,ne="` + + // The name of the route. The name must be 1000 characters or less and cannot include any special characters other than + // `(space) - . _ :`. Do not include any personal identifying information (PII) in any resource names. + Name *string `json:"name,omitempty"` + + // Routing rules that will be evaluated in their order of the array. + Rules []RulePrototype `json:"rules,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewUpdateRouteOptions : Instantiate UpdateRouteOptions +func (*MetricsRouterV3) NewUpdateRouteOptions(id string) *UpdateRouteOptions { + return &UpdateRouteOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *UpdateRouteOptions) SetID(id string) *UpdateRouteOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetName : Allow user to set Name +func (_options *UpdateRouteOptions) SetName(name string) *UpdateRouteOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetRules : Allow user to set Rules +func (_options *UpdateRouteOptions) SetRules(rules []RulePrototype) *UpdateRouteOptions { + _options.Rules = rules + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdateRouteOptions) SetHeaders(param map[string]string) *UpdateRouteOptions { + options.Headers = param + return options +} + +// UpdateSettingsOptions : The UpdateSettings options. +type UpdateSettingsOptions struct { + // A list of default target references. + DefaultTargets []TargetIdentity `json:"default_targets,omitempty"` + + // If present then only these regions may be used to define a target. + PermittedTargetRegions []string `json:"permitted_target_regions,omitempty"` + + // To store all your meta data in a single region. + PrimaryMetadataRegion *string `json:"primary_metadata_region,omitempty"` + + // To backup all your meta data in a different region. + BackupMetadataRegion *string `json:"backup_metadata_region,omitempty"` + + // If you set this true then you cannot access api through public network. + PrivateAPIEndpointOnly *bool `json:"private_api_endpoint_only,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewUpdateSettingsOptions : Instantiate UpdateSettingsOptions +func (*MetricsRouterV3) NewUpdateSettingsOptions() *UpdateSettingsOptions { + return &UpdateSettingsOptions{} +} + +// SetDefaultTargets : Allow user to set DefaultTargets +func (_options *UpdateSettingsOptions) SetDefaultTargets(defaultTargets []TargetIdentity) *UpdateSettingsOptions { + _options.DefaultTargets = defaultTargets + return _options +} + +// SetPermittedTargetRegions : Allow user to set PermittedTargetRegions +func (_options *UpdateSettingsOptions) SetPermittedTargetRegions(permittedTargetRegions []string) *UpdateSettingsOptions { + _options.PermittedTargetRegions = permittedTargetRegions + return _options +} + +// SetPrimaryMetadataRegion : Allow user to set PrimaryMetadataRegion +func (_options *UpdateSettingsOptions) SetPrimaryMetadataRegion(primaryMetadataRegion string) *UpdateSettingsOptions { + _options.PrimaryMetadataRegion = core.StringPtr(primaryMetadataRegion) + return _options +} + +// SetBackupMetadataRegion : Allow user to set BackupMetadataRegion +func (_options *UpdateSettingsOptions) SetBackupMetadataRegion(backupMetadataRegion string) *UpdateSettingsOptions { + _options.BackupMetadataRegion = core.StringPtr(backupMetadataRegion) + return _options +} + +// SetPrivateAPIEndpointOnly : Allow user to set PrivateAPIEndpointOnly +func (_options *UpdateSettingsOptions) SetPrivateAPIEndpointOnly(privateAPIEndpointOnly bool) *UpdateSettingsOptions { + _options.PrivateAPIEndpointOnly = core.BoolPtr(privateAPIEndpointOnly) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdateSettingsOptions) SetHeaders(param map[string]string) *UpdateSettingsOptions { + options.Headers = param + return options +} + +// UpdateTargetOptions : The UpdateTarget options. +type UpdateTargetOptions struct { + // The v4 UUID that uniquely identifies the target. + ID *string `json:"id" validate:"required,ne="` + + // The name of the target. The name must be 1000 characters or less, and cannot include any special characters other + // than `(space) - . _ :`. Do not include any personal identifying information (PII) in any resource names. + Name *string `json:"name,omitempty"` + + // The CRN of the destination service instance or resource. + DestinationCRN *string `json:"destination_crn,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewUpdateTargetOptions : Instantiate UpdateTargetOptions +func (*MetricsRouterV3) NewUpdateTargetOptions(id string) *UpdateTargetOptions { + return &UpdateTargetOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *UpdateTargetOptions) SetID(id string) *UpdateTargetOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetName : Allow user to set Name +func (_options *UpdateTargetOptions) SetName(name string) *UpdateTargetOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetDestinationCRN : Allow user to set DestinationCRN +func (_options *UpdateTargetOptions) SetDestinationCRN(destinationCRN string) *UpdateTargetOptions { + _options.DestinationCRN = core.StringPtr(destinationCRN) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdateTargetOptions) SetHeaders(param map[string]string) *UpdateTargetOptions { + options.Headers = param + return options +} diff --git a/metricsrouterv3/metrics_router_v3_examples_test.go b/metricsrouterv3/metrics_router_v3_examples_test.go new file mode 100644 index 00000000..97bbb68e --- /dev/null +++ b/metricsrouterv3/metrics_router_v3_examples_test.go @@ -0,0 +1,375 @@ +// +build examples + +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package metricsrouterv3_test + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/platform-services-go-sdk/metricsrouterv3" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +// +// This file provides an example of how to use the metrics-router service. +// +// The following configuration properties are assumed to be defined: +// METRICS_ROUTER_URL= +// METRICS_ROUTER_AUTH_TYPE=iam +// METRICS_ROUTER_APIKEY= +// METRICS_ROUTER_AUTH_URL= +// +// These configuration properties can be exported as environment variables, or stored +// in a configuration file and then: +// export IBM_CREDENTIALS_FILE= +// +var _ = Describe(`MetricsRouterV3 Examples Tests`, func() { + + const externalConfigFile = "../metrics_router_v3.env" + + var ( + metricsRouterService *metricsrouterv3.MetricsRouterV3 + config map[string]string + + // Variables to hold link values + routeIDLink string + targetIDLink string + ) + + var shouldSkipTest = func() { + Skip("External configuration is not available, skipping examples...") + } + + Describe(`External configuration`, func() { + It("Successfully load the configuration", func() { + var err error + _, err = os.Stat(externalConfigFile) + if err != nil { + Skip("External configuration file not found, skipping examples: " + err.Error()) + } + + os.Setenv("IBM_CREDENTIALS_FILE", externalConfigFile) + config, err = core.GetServiceProperties(metricsrouterv3.DefaultServiceName) + if err != nil { + Skip("Error loading service properties, skipping examples: " + err.Error()) + } else if len(config) == 0 { + Skip("Unable to load service properties, skipping examples") + } + + shouldSkipTest = func() {} + }) + }) + + Describe(`Client initialization`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It("Successfully construct the service client instance", func() { + var err error + + // begin-common + + metricsRouterServiceOptions := &metricsrouterv3.MetricsRouterV3Options{} + + metricsRouterService, err = metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(metricsRouterServiceOptions) + + if err != nil { + panic(err) + } + + // end-common + + Expect(metricsRouterService).ToNot(BeNil()) + }) + }) + + Describe(`MetricsRouterV3 request examples`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`CreateTarget request example`, func() { + fmt.Println("\nCreateTarget() result:") + // begin-create_target + + createTargetOptions := metricsRouterService.NewCreateTargetOptions( + "my-mr-target", + "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", + ) + + target, response, err := metricsRouterService.CreateTarget(createTargetOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(target, "", " ") + fmt.Println(string(b)) + + // end-create_target + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(201)) + Expect(target).ToNot(BeNil()) + + targetIDLink = *target.ID + fmt.Fprintf(GinkgoWriter, "Saved targetIDLink value: %v\n", targetIDLink) + }) + It(`CreateRoute request example`, func() { + fmt.Println("\nCreateRoute() result:") + // begin-create_route + + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south"}, + } + + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + + createRouteOptions := metricsRouterService.NewCreateRouteOptions( + "my-route", + []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + ) + + route, response, err := metricsRouterService.CreateRoute(createRouteOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(route, "", " ") + fmt.Println(string(b)) + + // end-create_route + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(201)) + Expect(route).ToNot(BeNil()) + + routeIDLink = *route.ID + fmt.Fprintf(GinkgoWriter, "Saved routeIDLink value: %v\n", routeIDLink) + }) + It(`ListTargets request example`, func() { + fmt.Println("\nListTargets() result:") + // begin-list_targets + + listTargetsOptions := metricsRouterService.NewListTargetsOptions() + + targetCollection, response, err := metricsRouterService.ListTargets(listTargetsOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(targetCollection, "", " ") + fmt.Println(string(b)) + + // end-list_targets + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(targetCollection).ToNot(BeNil()) + }) + It(`GetTarget request example`, func() { + fmt.Println("\nGetTarget() result:") + // begin-get_target + + getTargetOptions := metricsRouterService.NewGetTargetOptions( + targetIDLink, + ) + + target, response, err := metricsRouterService.GetTarget(getTargetOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(target, "", " ") + fmt.Println(string(b)) + + // end-get_target + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(target).ToNot(BeNil()) + }) + It(`UpdateTarget request example`, func() { + fmt.Println("\nUpdateTarget() result:") + // begin-update_target + + updateTargetOptions := metricsRouterService.NewUpdateTargetOptions( + targetIDLink, + ) + + target, response, err := metricsRouterService.UpdateTarget(updateTargetOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(target, "", " ") + fmt.Println(string(b)) + + // end-update_target + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(target).ToNot(BeNil()) + }) + It(`ListRoutes request example`, func() { + fmt.Println("\nListRoutes() result:") + // begin-list_routes + + listRoutesOptions := metricsRouterService.NewListRoutesOptions() + + routeCollection, response, err := metricsRouterService.ListRoutes(listRoutesOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(routeCollection, "", " ") + fmt.Println(string(b)) + + // end-list_routes + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(routeCollection).ToNot(BeNil()) + }) + It(`GetRoute request example`, func() { + fmt.Println("\nGetRoute() result:") + // begin-get_route + + getRouteOptions := metricsRouterService.NewGetRouteOptions( + routeIDLink, + ) + + route, response, err := metricsRouterService.GetRoute(getRouteOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(route, "", " ") + fmt.Println(string(b)) + + // end-get_route + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(route).ToNot(BeNil()) + }) + It(`UpdateRoute request example`, func() { + fmt.Println("\nUpdateRoute() result:") + // begin-update_route + + updateRouteOptions := metricsRouterService.NewUpdateRouteOptions( + routeIDLink, + ) + + route, response, err := metricsRouterService.UpdateRoute(updateRouteOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(route, "", " ") + fmt.Println(string(b)) + + // end-update_route + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(route).ToNot(BeNil()) + }) + It(`GetSettings request example`, func() { + fmt.Println("\nGetSettings() result:") + // begin-get_settings + + getSettingsOptions := metricsRouterService.NewGetSettingsOptions() + + setting, response, err := metricsRouterService.GetSettings(getSettingsOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(setting, "", " ") + fmt.Println(string(b)) + + // end-get_settings + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(setting).ToNot(BeNil()) + }) + It(`UpdateSettings request example`, func() { + fmt.Println("\nUpdateSettings() result:") + // begin-update_settings + + updateSettingsOptions := metricsRouterService.NewUpdateSettingsOptions() + + setting, response, err := metricsRouterService.UpdateSettings(updateSettingsOptions) + if err != nil { + panic(err) + } + b, _ := json.MarshalIndent(setting, "", " ") + fmt.Println(string(b)) + + // end-update_settings + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(setting).ToNot(BeNil()) + }) + It(`DeleteRoute request example`, func() { + // begin-delete_route + + deleteRouteOptions := metricsRouterService.NewDeleteRouteOptions( + routeIDLink, + ) + + response, err := metricsRouterService.DeleteRoute(deleteRouteOptions) + if err != nil { + panic(err) + } + if response.StatusCode != 204 { + fmt.Printf("\nUnexpected response status code received from DeleteRoute(): %d\n", response.StatusCode) + } + + // end-delete_route + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(204)) + }) + It(`DeleteTarget request example`, func() { + // begin-delete_target + + deleteTargetOptions := metricsRouterService.NewDeleteTargetOptions( + targetIDLink, + ) + + response, err := metricsRouterService.DeleteTarget(deleteTargetOptions) + if err != nil { + panic(err) + } + if response.StatusCode != 204 { + fmt.Printf("\nUnexpected response status code received from DeleteTarget(): %d\n", response.StatusCode) + } + + // end-delete_target + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(204)) + }) + }) +}) diff --git a/metricsrouterv3/metrics_router_v3_integration_test.go b/metricsrouterv3/metrics_router_v3_integration_test.go new file mode 100644 index 00000000..fb6409cc --- /dev/null +++ b/metricsrouterv3/metrics_router_v3_integration_test.go @@ -0,0 +1,818 @@ +//go:build integration +// +build integration + +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package metricsrouterv3_test + +import ( + "fmt" + "log" + "os" + "time" + + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/platform-services-go-sdk/metricsrouterv3" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +/** + * This file contains an integration test for the metricsrouterv3 package. + * + * Notes: + * + * The integration test will automatically skip tests if the required config file is not available. + */ + +var _ = Describe(`MetricsRouterV3 Integration Tests`, func() { + const externalConfigFile = "../metrics_router_v3.env" + const notFoundTargetID = "ffffffff-1111-1111-1111-111111111111" + const notFoundRouteID = "ffffffff-2222-2222-2222-222222222222" + + var ( + err error + metricsRouterService *metricsrouterv3.MetricsRouterV3 + metricsrouterServiceNotAuthorized *metricsrouterv3.MetricsRouterV3 + serviceURL string + config map[string]string + + // Variables to hold link values + routeIDLink string + routeIDLink1 string + targetIDLink string + ) + + var shouldSkipTest = func() { + Skip("External configuration is not available, skipping tests...") + } + + Describe(`External configuration`, func() { + It("Successfully load the configuration", func() { + _, err = os.Stat(externalConfigFile) + if err != nil { + Skip("External configuration file not found, skipping tests: " + err.Error()) + } + + os.Setenv("IBM_CREDENTIALS_FILE", externalConfigFile) + config, err = core.GetServiceProperties(metricsrouterv3.DefaultServiceName) + if err != nil { + Skip("Error loading service properties, skipping tests: " + err.Error()) + } + serviceURL = config["URL"] + if serviceURL == "" { + Skip("Unable to load service URL configuration property, skipping tests") + } + + fmt.Fprintf(GinkgoWriter, "Service URL: %v\n", serviceURL) + shouldSkipTest = func() {} + }) + }) + + Describe(`Client initialization`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It("Successfully construct the service client instance", func() { + metricsRouterServiceOptions := &metricsrouterv3.MetricsRouterV3Options{} + + metricsRouterService, err = metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(metricsRouterServiceOptions) + Expect(err).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + Expect(metricsRouterService.Service.Options.URL).To(Equal(serviceURL)) + + metricsrouterUnauthorizedServiceOptions := &metricsrouterv3.MetricsRouterV3Options{ + ServiceName: "NOT_AUTHORIZED", + } + metricsrouterServiceNotAuthorized, err = metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(metricsrouterUnauthorizedServiceOptions) + Expect(err).To(BeNil()) + Expect(metricsrouterServiceNotAuthorized).ToNot(BeNil()) + Expect(metricsrouterServiceNotAuthorized.Service.Options.URL).To(Equal(serviceURL)) + + core.SetLogger(core.NewLogger(core.LevelDebug, log.New(GinkgoWriter, "", log.LstdFlags), log.New(GinkgoWriter, "", log.LstdFlags))) + metricsRouterService.EnableRetries(4, 30*time.Second) + }) + }) + + Describe(`CreateTarget - Create a target`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`CreateTarget(createTargetOptions *CreateTargetOptions)`, func() { + createTargetOptions := &metricsrouterv3.CreateTargetOptions{ + Name: core.StringPtr("my-mr-target"), + DestinationCRN: core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::"), + Region: core.StringPtr("us-south"), + } + + target, response, err := metricsRouterService.CreateTarget(createTargetOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(201)) + Expect(target).ToNot(BeNil()) + + targetIDLink = *target.ID + fmt.Fprintf(GinkgoWriter, "Saved targetIDLink value: %v\n", targetIDLink) + }) + + It(`Returns 403 when user is not authorized`, func() { + createTargetOptions := &metricsrouterv3.CreateTargetOptions{ + Name: core.StringPtr("my-mr-target"), + DestinationCRN: core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::"), + Region: core.StringPtr("us-south"), + } + + _, response, err := metricsrouterServiceNotAuthorized.CreateTarget(createTargetOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + }) + + Describe(`CreateRoute - Create a route`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`CreateRoute(createRouteOptions *CreateRouteOptions)`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south"}, + } + + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-route"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + route, response, err := metricsRouterService.CreateRoute(createRouteOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(201)) + Expect(route).ToNot(BeNil()) + + routeIDLink = *route.ID + fmt.Fprintf(GinkgoWriter, "Saved routeIDLink value: %v\n", routeIDLink) + }) + + It(`CreateRoute(createRouteOptions *CreateRouteOptions) with in operator`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"us-south", "us-east"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-route-with-in"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + route, response, err := metricsRouterService.CreateRoute(createRouteOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(201)) + Expect(route).ToNot(BeNil()) + + routeIDLink1 = *route.ID + fmt.Fprintf(GinkgoWriter, "Saved routeIDLink value: %v\n", routeIDLink1) + }) + + It(`CreateRoute fails when multiple values used with 'is' filter operator`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south", "us-east"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-route-with-multiple-value-is-operator"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + route, response, err := metricsRouterService.CreateRoute(createRouteOptions) + Expect(err).ToNot(BeNil()) + Expect(response.StatusCode).To(Equal(400)) + Expect(route).To(BeNil()) + }) + + It(`CreateRoute fails when filter value length greater than limit`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-route-with-filter-length-more-than-limit"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + route, response, err := metricsRouterService.CreateRoute(createRouteOptions) + Expect(err).ToNot(BeNil()) + Expect(response.StatusCode).To(Equal(400)) + Expect(route).To(BeNil()) + }) + + It(`CreateRoute fails when filter value length equal to zero`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{""}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-route-with-zero-length-value"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + route, response, err := metricsRouterService.CreateRoute(createRouteOptions) + Expect(err).ToNot(BeNil()) + Expect(response.StatusCode).To(Equal(400)) + Expect(route).To(BeNil()) + }) + + It(`CreateRoute fails when filter length exceeded the limit`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := []metricsrouterv3.InclusionFilterPrototype{ + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"us-south"}, + }, + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"us-east"}, + }, + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"au-syd"}, + }, + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"eu-de"}, + }, + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"eu-gb"}, + }, + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"us-south"}, + }, + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"us-south"}, + }, + metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("in"), + Values: []string{"us-south"}, + }, + } + + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: inclusionFilterPrototypeModel, + } + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-route-with-more-filter-length"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + route, response, err := metricsRouterService.CreateRoute(createRouteOptions) + Expect(err).ToNot(BeNil()) + Expect(response.StatusCode).To(Equal(400)) + Expect(route).To(BeNil()) + }) + + It(`Returns 403 when user is not authorized`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-unauthorized-route"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + _, response, err := metricsrouterServiceNotAuthorized.CreateRoute(createRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + + It(`Returns 400 when input validation fails`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: core.StringPtr(notFoundTargetID), + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + createRouteOptions := &metricsrouterv3.CreateRouteOptions{ + Name: core.StringPtr("my-wrong-input-route"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + _, response, err := metricsRouterService.CreateRoute(createRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(400)) + }) + }) + + Describe(`ListTargets - List targets`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`ListTargets(listTargetsOptions *ListTargetsOptions)`, func() { + listTargetsOptions := &metricsrouterv3.ListTargetsOptions{} + + targetCollection, response, err := metricsRouterService.ListTargets(listTargetsOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(targetCollection).ToNot(BeNil()) + }) + + It(`Returns 403 when user is not authorized)`, func() { + + listTargetsOptions := &metricsrouterv3.ListTargetsOptions{} + + _, response, err := metricsrouterServiceNotAuthorized.ListTargets(listTargetsOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + }) + + Describe(`GetTarget - Get details of a target`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`GetTarget(getTargetOptions *GetTargetOptions)`, func() { + getTargetOptions := &metricsrouterv3.GetTargetOptions{ + ID: &targetIDLink, + } + + target, response, err := metricsRouterService.GetTarget(getTargetOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(target).ToNot(BeNil()) + }) + + It(`Returns 403 when user is not authorized`, func() { + getTargetOptions := &metricsrouterv3.GetTargetOptions{ + ID: &targetIDLink, + } + + _, response, err := metricsrouterServiceNotAuthorized.GetTarget(getTargetOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + + It(`Returns 404 when target id is not found`, func() { + + getTargetOptions := &metricsrouterv3.GetTargetOptions{ + ID: core.StringPtr(notFoundTargetID), + } + + _, response, err := metricsRouterService.GetTarget(getTargetOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(404)) + }) + }) + + Describe(`UpdateTarget - Update a target`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`UpdateTarget(updateTargetOptions *UpdateTargetOptions)`, func() { + updateTargetOptions := &metricsrouterv3.UpdateTargetOptions{ + ID: &targetIDLink, + Name: core.StringPtr("my-mr-target"), + DestinationCRN: core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::"), + } + + target, response, err := metricsRouterService.UpdateTarget(updateTargetOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(target).ToNot(BeNil()) + }) + + It(`Returns 404 when target id is not found`, func() { + + updateTargetOptions := &metricsrouterv3.UpdateTargetOptions{ + ID: core.StringPtr(notFoundTargetID), + Name: core.StringPtr("my-mr-target"), + DestinationCRN: core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::"), + } + + _, response, err := metricsRouterService.UpdateTarget(updateTargetOptions) + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(404)) + }) + }) + + Describe(`ListRoutes - List routes`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`ListRoutes(listRoutesOptions *ListRoutesOptions)`, func() { + listRoutesOptions := &metricsrouterv3.ListRoutesOptions{} + + routeCollection, response, err := metricsRouterService.ListRoutes(listRoutesOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(routeCollection).ToNot(BeNil()) + }) + + It(`Returns 403 when user is not authorized`, func() { + + listRoutesOptions := &metricsrouterv3.ListRoutesOptions{} + + _, response, err := metricsrouterServiceNotAuthorized.ListRoutes(listRoutesOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + }) + + Describe(`GetRoute - Get details of a route`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`GetRoute(getRouteOptions *GetRouteOptions)`, func() { + getRouteOptions := &metricsrouterv3.GetRouteOptions{ + ID: &routeIDLink, + } + + route, response, err := metricsRouterService.GetRoute(getRouteOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(route).ToNot(BeNil()) + }) + + It(`Returns 403 when user is not authorized`, func() { + getRouteOptions := &metricsrouterv3.GetRouteOptions{ + ID: &routeIDLink, + } + + _, response, err := metricsrouterServiceNotAuthorized.GetRoute(getRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + + It(`Returns 404 when route id is not found`, func() { + getRouteOptions := &metricsrouterv3.GetRouteOptions{ + ID: core.StringPtr(notFoundRouteID), + } + + _, response, err := metricsRouterService.GetRoute(getRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(404)) + }) + }) + + Describe(`UpdateRoute - Update a route`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`UpdateRoute(updateRouteOptions *UpdateRouteOptions)`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + updateRouteOptions := &metricsrouterv3.UpdateRouteOptions{ + ID: &routeIDLink, + Name: core.StringPtr("my-route"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + route, response, err := metricsRouterService.UpdateRoute(updateRouteOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(route).ToNot(BeNil()) + }) + + It(`Returns 403 when user is not authorized`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + updateRouteOptions := &metricsrouterv3.UpdateRouteOptions{ + ID: &routeIDLink, + Name: core.StringPtr("my-route"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + _, response, err := metricsrouterServiceNotAuthorized.UpdateRoute(updateRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + + It(`Returns 404 when route id is not found`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + inclusionFilterPrototypeModel := &metricsrouterv3.InclusionFilterPrototype{ + Operand: core.StringPtr("location"), + Operator: core.StringPtr("is"), + Values: []string{"us-south"}, + } + rulePrototypeModel := &metricsrouterv3.RulePrototype{ + Action: core.StringPtr("send"), + Targets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + InclusionFilters: []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel}, + } + updateRouteOptions := &metricsrouterv3.UpdateRouteOptions{ + ID: core.StringPtr(notFoundRouteID), + Name: core.StringPtr("my-route"), + Rules: []metricsrouterv3.RulePrototype{*rulePrototypeModel}, + } + + _, response, err := metricsRouterService.UpdateRoute(updateRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(404)) + }) + }) + + Describe(`GetSettings - Get settings`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`GetSettings(getSettingsOptions *GetSettingsOptions)`, func() { + getSettingsOptions := &metricsrouterv3.GetSettingsOptions{} + + setting, response, err := metricsRouterService.GetSettings(getSettingsOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(setting).ToNot(BeNil()) + }) + + It(`Returns 403 when user is not authorized`, func() { + getSettingsOptions := &metricsrouterv3.GetSettingsOptions{} + + _, response, err := metricsrouterServiceNotAuthorized.GetSettings(getSettingsOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + }) + + Describe(`UpdateSettings - Modify settings`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + It(`UpdateSettings(updateSettingsOptions *UpdateSettingsOptions)`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + + updateSettingsOptions := &metricsrouterv3.UpdateSettingsOptions{ + DefaultTargets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + PermittedTargetRegions: []string{"us-south"}, + PrimaryMetadataRegion: core.StringPtr("us-south"), + BackupMetadataRegion: core.StringPtr("us-east"), + PrivateAPIEndpointOnly: core.BoolPtr(false), + } + + setting, response, err := metricsRouterService.UpdateSettings(updateSettingsOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(setting).ToNot(BeNil()) + }) + + It(`DeleteTarget will fail when target is a default target added in settings`, func() { + deleteTargetOptions := &metricsrouterv3.DeleteTargetOptions{ + ID: &targetIDLink, + } + + response, err := metricsRouterService.DeleteTarget(deleteTargetOptions) + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(400)) + }) + + It(`Returns 403 when user is not authorized`, func() { + targetIdentityModel := &metricsrouterv3.TargetIdentity{ + ID: &targetIDLink, + } + + updateSettingsOptions := &metricsrouterv3.UpdateSettingsOptions{ + DefaultTargets: []metricsrouterv3.TargetIdentity{*targetIdentityModel}, + PermittedTargetRegions: []string{"us-south"}, + PrimaryMetadataRegion: core.StringPtr("us-south"), + BackupMetadataRegion: core.StringPtr("us-east"), + PrivateAPIEndpointOnly: core.BoolPtr(false), + } + + _, response, err := metricsrouterServiceNotAuthorized.UpdateSettings(updateSettingsOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + + It(`Removing default targets`, func() { + updateSettingsOptions := &metricsrouterv3.UpdateSettingsOptions{ + DefaultTargets: []metricsrouterv3.TargetIdentity{}, + PermittedTargetRegions: []string{"us-south"}, + PrimaryMetadataRegion: core.StringPtr("us-south"), + BackupMetadataRegion: core.StringPtr("us-east"), + PrivateAPIEndpointOnly: core.BoolPtr(false), + } + + setting, response, err := metricsRouterService.UpdateSettings(updateSettingsOptions) + + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(200)) + Expect(setting).ToNot(BeNil()) + }) + + }) + + Describe(`DeleteRoute - Delete a route`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + + It(`Returns 403 when user is not authorized`, func() { + deleteRouteOptions := &metricsrouterv3.DeleteRouteOptions{ + ID: &routeIDLink, + } + + response, err := metricsrouterServiceNotAuthorized.DeleteRoute(deleteRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + + It(`Returns 404 when route id is not found`, func() { + deleteRouteOptions := &metricsrouterv3.DeleteRouteOptions{ + ID: core.StringPtr(notFoundRouteID), + } + + response, err := metricsRouterService.DeleteRoute(deleteRouteOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(404)) + }) + + It(`DeleteRoute(deleteRouteOptions *DeleteRouteOptions)`, func() { + deleteRouteOptions := &metricsrouterv3.DeleteRouteOptions{ + ID: &routeIDLink, + } + + response, err := metricsRouterService.DeleteRoute(deleteRouteOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(204)) + }) + + It(`DeleteRoute with in operator(deleteRouteOptions *DeleteRouteOptions)`, func() { + deleteRouteOptions := &metricsrouterv3.DeleteRouteOptions{ + ID: &routeIDLink1, + } + + response, err := metricsRouterService.DeleteRoute(deleteRouteOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(204)) + }) + }) + + Describe(`DeleteTarget - Delete a target`, func() { + BeforeEach(func() { + shouldSkipTest() + }) + + It(`Returns 403 when user is not authorized`, func() { + deleteTargetOptions := &metricsrouterv3.DeleteTargetOptions{ + ID: &targetIDLink, + } + + response, err := metricsrouterServiceNotAuthorized.DeleteTarget(deleteTargetOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(403)) + }) + + It(`Returns 404 when target id is not found`, func() { + + deleteTargetOptions := &metricsrouterv3.DeleteTargetOptions{ + ID: core.StringPtr(notFoundTargetID), + } + + response, err := metricsRouterService.DeleteTarget(deleteTargetOptions) + + Expect(err).NotTo(BeNil()) + Expect(response.StatusCode).To(Equal(404)) + }) + + It(`DeleteTarget(deleteTargetOptions *DeleteTargetOptions)`, func() { + deleteTargetOptions := &metricsrouterv3.DeleteTargetOptions{ + ID: &targetIDLink, + } + + response, err := metricsRouterService.DeleteTarget(deleteTargetOptions) + Expect(err).To(BeNil()) + Expect(response.StatusCode).To(Equal(204)) + }) + }) +}) + +// +// Utility functions are declared in the unit test file +// diff --git a/metricsrouterv3/metrics_router_v3_suite_test.go b/metricsrouterv3/metrics_router_v3_suite_test.go new file mode 100644 index 00000000..19729729 --- /dev/null +++ b/metricsrouterv3/metrics_router_v3_suite_test.go @@ -0,0 +1,29 @@ +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package metricsrouterv3_test + +import ( + "testing" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +func TestMetricsRouterV3(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "MetricsRouterV3 Suite") +} diff --git a/metricsrouterv3/metrics_router_v3_test.go b/metricsrouterv3/metrics_router_v3_test.go new file mode 100644 index 00000000..d5d77531 --- /dev/null +++ b/metricsrouterv3/metrics_router_v3_test.go @@ -0,0 +1,3101 @@ +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package metricsrouterv3_test + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "time" + + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/platform-services-go-sdk/metricsrouterv3" + "github.com/go-openapi/strfmt" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe(`MetricsRouterV3`, func() { + var testServer *httptest.Server + Describe(`Service constructor tests`, func() { + It(`Instantiate service client`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(metricsRouterService).ToNot(BeNil()) + Expect(serviceErr).To(BeNil()) + }) + It(`Instantiate service client with error: Invalid URL`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: "{BAD_URL_STRING", + }) + Expect(metricsRouterService).To(BeNil()) + Expect(serviceErr).ToNot(BeNil()) + }) + It(`Instantiate service client with error: Invalid Auth`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: "https://metricsrouterv3/api", + Authenticator: &core.BasicAuthenticator{ + Username: "", + Password: "", + }, + }) + Expect(metricsRouterService).To(BeNil()) + Expect(serviceErr).ToNot(BeNil()) + }) + }) + Describe(`Service constructor tests using external config`, func() { + Context(`Using external config, construct service client instances`, func() { + // Map containing environment variables used in testing. + var testEnvironment = map[string]string{ + "METRICS_ROUTER_URL": "https://metricsrouterv3/api", + "METRICS_ROUTER_AUTH_TYPE": "noauth", + } + + It(`Create service client using external config successfully`, func() { + SetTestEnvironment(testEnvironment) + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(&metricsrouterv3.MetricsRouterV3Options{}) + Expect(metricsRouterService).ToNot(BeNil()) + Expect(serviceErr).To(BeNil()) + ClearTestEnvironment(testEnvironment) + + clone := metricsRouterService.Clone() + Expect(clone).ToNot(BeNil()) + Expect(clone.Service != metricsRouterService.Service).To(BeTrue()) + Expect(clone.GetServiceURL()).To(Equal(metricsRouterService.GetServiceURL())) + Expect(clone.Service.Options.Authenticator).To(Equal(metricsRouterService.Service.Options.Authenticator)) + }) + It(`Create service client using external config and set url from constructor successfully`, func() { + SetTestEnvironment(testEnvironment) + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(&metricsrouterv3.MetricsRouterV3Options{ + URL: "https://testService/api", + }) + Expect(metricsRouterService).ToNot(BeNil()) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService.Service.GetServiceURL()).To(Equal("https://testService/api")) + ClearTestEnvironment(testEnvironment) + + clone := metricsRouterService.Clone() + Expect(clone).ToNot(BeNil()) + Expect(clone.Service != metricsRouterService.Service).To(BeTrue()) + Expect(clone.GetServiceURL()).To(Equal(metricsRouterService.GetServiceURL())) + Expect(clone.Service.Options.Authenticator).To(Equal(metricsRouterService.Service.Options.Authenticator)) + }) + It(`Create service client using external config and set url programatically successfully`, func() { + SetTestEnvironment(testEnvironment) + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(&metricsrouterv3.MetricsRouterV3Options{}) + err := metricsRouterService.SetServiceURL("https://testService/api") + Expect(err).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService.Service.GetServiceURL()).To(Equal("https://testService/api")) + ClearTestEnvironment(testEnvironment) + + clone := metricsRouterService.Clone() + Expect(clone).ToNot(BeNil()) + Expect(clone.Service != metricsRouterService.Service).To(BeTrue()) + Expect(clone.GetServiceURL()).To(Equal(metricsRouterService.GetServiceURL())) + Expect(clone.Service.Options.Authenticator).To(Equal(metricsRouterService.Service.Options.Authenticator)) + }) + }) + Context(`Using external config, construct service client instances with error: Invalid Auth`, func() { + // Map containing environment variables used in testing. + var testEnvironment = map[string]string{ + "METRICS_ROUTER_URL": "https://metricsrouterv3/api", + "METRICS_ROUTER_AUTH_TYPE": "someOtherAuth", + } + + SetTestEnvironment(testEnvironment) + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(&metricsrouterv3.MetricsRouterV3Options{}) + + It(`Instantiate service client with error`, func() { + Expect(metricsRouterService).To(BeNil()) + Expect(serviceErr).ToNot(BeNil()) + ClearTestEnvironment(testEnvironment) + }) + }) + Context(`Using external config, construct service client instances with error: Invalid URL`, func() { + // Map containing environment variables used in testing. + var testEnvironment = map[string]string{ + "METRICS_ROUTER_AUTH_TYPE": "NOAuth", + } + + SetTestEnvironment(testEnvironment) + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3UsingExternalConfig(&metricsrouterv3.MetricsRouterV3Options{ + URL: "{BAD_URL_STRING", + }) + + It(`Instantiate service client with error`, func() { + Expect(metricsRouterService).To(BeNil()) + Expect(serviceErr).ToNot(BeNil()) + ClearTestEnvironment(testEnvironment) + }) + }) + }) + Describe(`Regional endpoint tests`, func() { + It(`GetServiceURLForRegion(region string)`, func() { + var url string + var err error + url, err = metricsrouterv3.GetServiceURLForRegion("au-syd") + Expect(url).To(Equal("https://au-syd.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("private.au-syd") + Expect(url).To(Equal("https://private.au-syd.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("eu-de") + Expect(url).To(Equal("https://eu-de.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("private.eu-de") + Expect(url).To(Equal("https://private.eu-de.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("eu-gb") + Expect(url).To(Equal("https://eu-gb.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("private.eu-gb") + Expect(url).To(Equal("https://private.eu-gb.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("us-east") + Expect(url).To(Equal("https://us-east.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("private.us-east") + Expect(url).To(Equal("https://private.us-east.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("us-south") + Expect(url).To(Equal("https://us-south.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("private.us-south") + Expect(url).To(Equal("https://private.us-south.metrics-router.cloud.ibm.com/api/v3")) + Expect(err).To(BeNil()) + + url, err = metricsrouterv3.GetServiceURLForRegion("INVALID_REGION") + Expect(url).To(BeEmpty()) + Expect(err).ToNot(BeNil()) + fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error()) + }) + }) + Describe(`CreateTarget(createTargetOptions *CreateTargetOptions) - Operation response error`, func() { + createTargetPath := "/targets" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(createTargetPath)) + Expect(req.Method).To(Equal("POST")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(201) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke CreateTarget with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the CreateTargetOptions model + createTargetOptionsModel := new(metricsrouterv3.CreateTargetOptions) + createTargetOptionsModel.Name = core.StringPtr("my-mr-target") + createTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + createTargetOptionsModel.Region = core.StringPtr("us-south") + createTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.CreateTarget(createTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.CreateTarget(createTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`CreateTarget(createTargetOptions *CreateTargetOptions)`, func() { + createTargetPath := "/targets" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(createTargetPath)) + Expect(req.Method).To(Equal("POST")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(201) + fmt.Fprintf(res, "%s", `{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke CreateTarget successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the CreateTargetOptions model + createTargetOptionsModel := new(metricsrouterv3.CreateTargetOptions) + createTargetOptionsModel.Name = core.StringPtr("my-mr-target") + createTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + createTargetOptionsModel.Region = core.StringPtr("us-south") + createTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.CreateTargetWithContext(ctx, createTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.CreateTarget(createTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.CreateTargetWithContext(ctx, createTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(createTargetPath)) + Expect(req.Method).To(Equal("POST")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(201) + fmt.Fprintf(res, "%s", `{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke CreateTarget successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.CreateTarget(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the CreateTargetOptions model + createTargetOptionsModel := new(metricsrouterv3.CreateTargetOptions) + createTargetOptionsModel.Name = core.StringPtr("my-mr-target") + createTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + createTargetOptionsModel.Region = core.StringPtr("us-south") + createTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.CreateTarget(createTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke CreateTarget with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the CreateTargetOptions model + createTargetOptionsModel := new(metricsrouterv3.CreateTargetOptions) + createTargetOptionsModel.Name = core.StringPtr("my-mr-target") + createTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + createTargetOptionsModel.Region = core.StringPtr("us-south") + createTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.CreateTarget(createTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + // Construct a second instance of the CreateTargetOptions model with no property values + createTargetOptionsModelNew := new(metricsrouterv3.CreateTargetOptions) + // Invoke operation with invalid model (negative test) + result, response, operationErr = metricsRouterService.CreateTarget(createTargetOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(201) + })) + }) + It(`Invoke CreateTarget successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the CreateTargetOptions model + createTargetOptionsModel := new(metricsrouterv3.CreateTargetOptions) + createTargetOptionsModel.Name = core.StringPtr("my-mr-target") + createTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + createTargetOptionsModel.Region = core.StringPtr("us-south") + createTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.CreateTarget(createTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`ListTargets(listTargetsOptions *ListTargetsOptions) - Operation response error`, func() { + listTargetsPath := "/targets" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(listTargetsPath)) + Expect(req.Method).To(Equal("GET")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke ListTargets with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the ListTargetsOptions model + listTargetsOptionsModel := new(metricsrouterv3.ListTargetsOptions) + listTargetsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.ListTargets(listTargetsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.ListTargets(listTargetsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`ListTargets(listTargetsOptions *ListTargetsOptions)`, func() { + listTargetsPath := "/targets" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(listTargetsPath)) + Expect(req.Method).To(Equal("GET")) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"targets": [{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}]}`) + })) + }) + It(`Invoke ListTargets successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the ListTargetsOptions model + listTargetsOptionsModel := new(metricsrouterv3.ListTargetsOptions) + listTargetsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.ListTargetsWithContext(ctx, listTargetsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.ListTargets(listTargetsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.ListTargetsWithContext(ctx, listTargetsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(listTargetsPath)) + Expect(req.Method).To(Equal("GET")) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"targets": [{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}]}`) + })) + }) + It(`Invoke ListTargets successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.ListTargets(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the ListTargetsOptions model + listTargetsOptionsModel := new(metricsrouterv3.ListTargetsOptions) + listTargetsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.ListTargets(listTargetsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke ListTargets with error: Operation request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the ListTargetsOptions model + listTargetsOptionsModel := new(metricsrouterv3.ListTargetsOptions) + listTargetsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.ListTargets(listTargetsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke ListTargets successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the ListTargetsOptions model + listTargetsOptionsModel := new(metricsrouterv3.ListTargetsOptions) + listTargetsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.ListTargets(listTargetsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`GetTarget(getTargetOptions *GetTargetOptions) - Operation response error`, func() { + getTargetPath := "/targets/testString" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getTargetPath)) + Expect(req.Method).To(Equal("GET")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke GetTarget with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetTargetOptions model + getTargetOptionsModel := new(metricsrouterv3.GetTargetOptions) + getTargetOptionsModel.ID = core.StringPtr("testString") + getTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.GetTarget(getTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.GetTarget(getTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`GetTarget(getTargetOptions *GetTargetOptions)`, func() { + getTargetPath := "/targets/testString" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getTargetPath)) + Expect(req.Method).To(Equal("GET")) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke GetTarget successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the GetTargetOptions model + getTargetOptionsModel := new(metricsrouterv3.GetTargetOptions) + getTargetOptionsModel.ID = core.StringPtr("testString") + getTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.GetTargetWithContext(ctx, getTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.GetTarget(getTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.GetTargetWithContext(ctx, getTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getTargetPath)) + Expect(req.Method).To(Equal("GET")) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke GetTarget successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.GetTarget(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the GetTargetOptions model + getTargetOptionsModel := new(metricsrouterv3.GetTargetOptions) + getTargetOptionsModel.ID = core.StringPtr("testString") + getTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.GetTarget(getTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke GetTarget with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetTargetOptions model + getTargetOptionsModel := new(metricsrouterv3.GetTargetOptions) + getTargetOptionsModel.ID = core.StringPtr("testString") + getTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.GetTarget(getTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + // Construct a second instance of the GetTargetOptions model with no property values + getTargetOptionsModelNew := new(metricsrouterv3.GetTargetOptions) + // Invoke operation with invalid model (negative test) + result, response, operationErr = metricsRouterService.GetTarget(getTargetOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke GetTarget successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetTargetOptions model + getTargetOptionsModel := new(metricsrouterv3.GetTargetOptions) + getTargetOptionsModel.ID = core.StringPtr("testString") + getTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.GetTarget(getTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`UpdateTarget(updateTargetOptions *UpdateTargetOptions) - Operation response error`, func() { + updateTargetPath := "/targets/testString" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateTargetPath)) + Expect(req.Method).To(Equal("PATCH")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke UpdateTarget with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the UpdateTargetOptions model + updateTargetOptionsModel := new(metricsrouterv3.UpdateTargetOptions) + updateTargetOptionsModel.ID = core.StringPtr("testString") + updateTargetOptionsModel.Name = core.StringPtr("my-mr-target") + updateTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + updateTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.UpdateTarget(updateTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.UpdateTarget(updateTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`UpdateTarget(updateTargetOptions *UpdateTargetOptions)`, func() { + updateTargetPath := "/targets/testString" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateTargetPath)) + Expect(req.Method).To(Equal("PATCH")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke UpdateTarget successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the UpdateTargetOptions model + updateTargetOptionsModel := new(metricsrouterv3.UpdateTargetOptions) + updateTargetOptionsModel.ID = core.StringPtr("testString") + updateTargetOptionsModel.Name = core.StringPtr("my-mr-target") + updateTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + updateTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.UpdateTargetWithContext(ctx, updateTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.UpdateTarget(updateTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.UpdateTargetWithContext(ctx, updateTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateTargetPath)) + Expect(req.Method).To(Equal("PATCH")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "name": "a-mr-target-us-south", "crn": "crn:v1:bluemix:public:metrics-router:us-south:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:target:f7dcfae6-e7c5-08ca-451b-fdfa696c9bb6", "destination_crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "target_type": "sysdig_monitor", "region": "us-south", "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke UpdateTarget successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.UpdateTarget(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the UpdateTargetOptions model + updateTargetOptionsModel := new(metricsrouterv3.UpdateTargetOptions) + updateTargetOptionsModel.ID = core.StringPtr("testString") + updateTargetOptionsModel.Name = core.StringPtr("my-mr-target") + updateTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + updateTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.UpdateTarget(updateTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke UpdateTarget with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the UpdateTargetOptions model + updateTargetOptionsModel := new(metricsrouterv3.UpdateTargetOptions) + updateTargetOptionsModel.ID = core.StringPtr("testString") + updateTargetOptionsModel.Name = core.StringPtr("my-mr-target") + updateTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + updateTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.UpdateTarget(updateTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + // Construct a second instance of the UpdateTargetOptions model with no property values + updateTargetOptionsModelNew := new(metricsrouterv3.UpdateTargetOptions) + // Invoke operation with invalid model (negative test) + result, response, operationErr = metricsRouterService.UpdateTarget(updateTargetOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke UpdateTarget successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the UpdateTargetOptions model + updateTargetOptionsModel := new(metricsrouterv3.UpdateTargetOptions) + updateTargetOptionsModel.ID = core.StringPtr("testString") + updateTargetOptionsModel.Name = core.StringPtr("my-mr-target") + updateTargetOptionsModel.DestinationCRN = core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + updateTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.UpdateTarget(updateTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`DeleteTarget(deleteTargetOptions *DeleteTargetOptions)`, func() { + deleteTargetPath := "/targets/testString" + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(deleteTargetPath)) + Expect(req.Method).To(Equal("DELETE")) + + res.WriteHeader(204) + })) + }) + It(`Invoke DeleteTarget successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + response, operationErr := metricsRouterService.DeleteTarget(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + + // Construct an instance of the DeleteTargetOptions model + deleteTargetOptionsModel := new(metricsrouterv3.DeleteTargetOptions) + deleteTargetOptionsModel.ID = core.StringPtr("testString") + deleteTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + response, operationErr = metricsRouterService.DeleteTarget(deleteTargetOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + }) + It(`Invoke DeleteTarget with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the DeleteTargetOptions model + deleteTargetOptionsModel := new(metricsrouterv3.DeleteTargetOptions) + deleteTargetOptionsModel.ID = core.StringPtr("testString") + deleteTargetOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + response, operationErr := metricsRouterService.DeleteTarget(deleteTargetOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + // Construct a second instance of the DeleteTargetOptions model with no property values + deleteTargetOptionsModelNew := new(metricsrouterv3.DeleteTargetOptions) + // Invoke operation with invalid model (negative test) + response, operationErr = metricsRouterService.DeleteTarget(deleteTargetOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`CreateRoute(createRouteOptions *CreateRouteOptions) - Operation response error`, func() { + createRoutePath := "/routes" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(createRoutePath)) + Expect(req.Method).To(Equal("POST")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(201) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke CreateRoute with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the CreateRouteOptions model + createRouteOptionsModel := new(metricsrouterv3.CreateRouteOptions) + createRouteOptionsModel.Name = core.StringPtr("my-route") + createRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + createRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.CreateRoute(createRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.CreateRoute(createRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`CreateRoute(createRouteOptions *CreateRouteOptions)`, func() { + createRoutePath := "/routes" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(createRoutePath)) + Expect(req.Method).To(Equal("POST")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(201) + fmt.Fprintf(res, "%s", `{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke CreateRoute successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the CreateRouteOptions model + createRouteOptionsModel := new(metricsrouterv3.CreateRouteOptions) + createRouteOptionsModel.Name = core.StringPtr("my-route") + createRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + createRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.CreateRouteWithContext(ctx, createRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.CreateRoute(createRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.CreateRouteWithContext(ctx, createRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(createRoutePath)) + Expect(req.Method).To(Equal("POST")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(201) + fmt.Fprintf(res, "%s", `{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke CreateRoute successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.CreateRoute(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the CreateRouteOptions model + createRouteOptionsModel := new(metricsrouterv3.CreateRouteOptions) + createRouteOptionsModel.Name = core.StringPtr("my-route") + createRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + createRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.CreateRoute(createRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke CreateRoute with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the CreateRouteOptions model + createRouteOptionsModel := new(metricsrouterv3.CreateRouteOptions) + createRouteOptionsModel.Name = core.StringPtr("my-route") + createRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + createRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.CreateRoute(createRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + // Construct a second instance of the CreateRouteOptions model with no property values + createRouteOptionsModelNew := new(metricsrouterv3.CreateRouteOptions) + // Invoke operation with invalid model (negative test) + result, response, operationErr = metricsRouterService.CreateRoute(createRouteOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(201) + })) + }) + It(`Invoke CreateRoute successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the CreateRouteOptions model + createRouteOptionsModel := new(metricsrouterv3.CreateRouteOptions) + createRouteOptionsModel.Name = core.StringPtr("my-route") + createRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + createRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.CreateRoute(createRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`ListRoutes(listRoutesOptions *ListRoutesOptions) - Operation response error`, func() { + listRoutesPath := "/routes" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(listRoutesPath)) + Expect(req.Method).To(Equal("GET")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke ListRoutes with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the ListRoutesOptions model + listRoutesOptionsModel := new(metricsrouterv3.ListRoutesOptions) + listRoutesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.ListRoutes(listRoutesOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.ListRoutes(listRoutesOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`ListRoutes(listRoutesOptions *ListRoutesOptions)`, func() { + listRoutesPath := "/routes" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(listRoutesPath)) + Expect(req.Method).To(Equal("GET")) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"routes": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}]}`) + })) + }) + It(`Invoke ListRoutes successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the ListRoutesOptions model + listRoutesOptionsModel := new(metricsrouterv3.ListRoutesOptions) + listRoutesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.ListRoutesWithContext(ctx, listRoutesOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.ListRoutes(listRoutesOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.ListRoutesWithContext(ctx, listRoutesOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(listRoutesPath)) + Expect(req.Method).To(Equal("GET")) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"routes": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}]}`) + })) + }) + It(`Invoke ListRoutes successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.ListRoutes(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the ListRoutesOptions model + listRoutesOptionsModel := new(metricsrouterv3.ListRoutesOptions) + listRoutesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.ListRoutes(listRoutesOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke ListRoutes with error: Operation request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the ListRoutesOptions model + listRoutesOptionsModel := new(metricsrouterv3.ListRoutesOptions) + listRoutesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.ListRoutes(listRoutesOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke ListRoutes successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the ListRoutesOptions model + listRoutesOptionsModel := new(metricsrouterv3.ListRoutesOptions) + listRoutesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.ListRoutes(listRoutesOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`GetRoute(getRouteOptions *GetRouteOptions) - Operation response error`, func() { + getRoutePath := "/routes/testString" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getRoutePath)) + Expect(req.Method).To(Equal("GET")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke GetRoute with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetRouteOptions model + getRouteOptionsModel := new(metricsrouterv3.GetRouteOptions) + getRouteOptionsModel.ID = core.StringPtr("testString") + getRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.GetRoute(getRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.GetRoute(getRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`GetRoute(getRouteOptions *GetRouteOptions)`, func() { + getRoutePath := "/routes/testString" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getRoutePath)) + Expect(req.Method).To(Equal("GET")) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke GetRoute successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the GetRouteOptions model + getRouteOptionsModel := new(metricsrouterv3.GetRouteOptions) + getRouteOptionsModel.ID = core.StringPtr("testString") + getRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.GetRouteWithContext(ctx, getRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.GetRoute(getRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.GetRouteWithContext(ctx, getRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getRoutePath)) + Expect(req.Method).To(Equal("GET")) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke GetRoute successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.GetRoute(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the GetRouteOptions model + getRouteOptionsModel := new(metricsrouterv3.GetRouteOptions) + getRouteOptionsModel.ID = core.StringPtr("testString") + getRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.GetRoute(getRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke GetRoute with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetRouteOptions model + getRouteOptionsModel := new(metricsrouterv3.GetRouteOptions) + getRouteOptionsModel.ID = core.StringPtr("testString") + getRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.GetRoute(getRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + // Construct a second instance of the GetRouteOptions model with no property values + getRouteOptionsModelNew := new(metricsrouterv3.GetRouteOptions) + // Invoke operation with invalid model (negative test) + result, response, operationErr = metricsRouterService.GetRoute(getRouteOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke GetRoute successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetRouteOptions model + getRouteOptionsModel := new(metricsrouterv3.GetRouteOptions) + getRouteOptionsModel.ID = core.StringPtr("testString") + getRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.GetRoute(getRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`UpdateRoute(updateRouteOptions *UpdateRouteOptions) - Operation response error`, func() { + updateRoutePath := "/routes/testString" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateRoutePath)) + Expect(req.Method).To(Equal("PATCH")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke UpdateRoute with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the UpdateRouteOptions model + updateRouteOptionsModel := new(metricsrouterv3.UpdateRouteOptions) + updateRouteOptionsModel.ID = core.StringPtr("testString") + updateRouteOptionsModel.Name = core.StringPtr("my-route") + updateRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + updateRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.UpdateRoute(updateRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.UpdateRoute(updateRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`UpdateRoute(updateRouteOptions *UpdateRouteOptions)`, func() { + updateRoutePath := "/routes/testString" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateRoutePath)) + Expect(req.Method).To(Equal("PATCH")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke UpdateRoute successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the UpdateRouteOptions model + updateRouteOptionsModel := new(metricsrouterv3.UpdateRouteOptions) + updateRouteOptionsModel.ID = core.StringPtr("testString") + updateRouteOptionsModel.Name = core.StringPtr("my-route") + updateRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + updateRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.UpdateRouteWithContext(ctx, updateRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.UpdateRoute(updateRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.UpdateRouteWithContext(ctx, updateRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateRoutePath)) + Expect(req.Method).To(Equal("PATCH")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "name": "my-route", "crn": "crn:v1:bluemix:public:metrics-router:global:a/0be5ad401ae913d8ff665d92680664ed:b6eec08b-5201-08ca-451b-cd71523e3626:route:c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "rules": [{"action": "send", "targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "inclusion_filters": [{"operand": "location", "operator": "is", "values": ["us-south"]}]}], "created_at": "2021-05-18T20:15:12.353Z", "updated_at": "2021-05-18T20:15:12.353Z"}`) + })) + }) + It(`Invoke UpdateRoute successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.UpdateRoute(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the UpdateRouteOptions model + updateRouteOptionsModel := new(metricsrouterv3.UpdateRouteOptions) + updateRouteOptionsModel.ID = core.StringPtr("testString") + updateRouteOptionsModel.Name = core.StringPtr("my-route") + updateRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + updateRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.UpdateRoute(updateRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke UpdateRoute with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the UpdateRouteOptions model + updateRouteOptionsModel := new(metricsrouterv3.UpdateRouteOptions) + updateRouteOptionsModel.ID = core.StringPtr("testString") + updateRouteOptionsModel.Name = core.StringPtr("my-route") + updateRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + updateRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.UpdateRoute(updateRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + // Construct a second instance of the UpdateRouteOptions model with no property values + updateRouteOptionsModelNew := new(metricsrouterv3.UpdateRouteOptions) + // Invoke operation with invalid model (negative test) + result, response, operationErr = metricsRouterService.UpdateRoute(updateRouteOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke UpdateRoute successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + + // Construct an instance of the UpdateRouteOptions model + updateRouteOptionsModel := new(metricsrouterv3.UpdateRouteOptions) + updateRouteOptionsModel.ID = core.StringPtr("testString") + updateRouteOptionsModel.Name = core.StringPtr("my-route") + updateRouteOptionsModel.Rules = []metricsrouterv3.RulePrototype{*rulePrototypeModel} + updateRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.UpdateRoute(updateRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`DeleteRoute(deleteRouteOptions *DeleteRouteOptions)`, func() { + deleteRoutePath := "/routes/testString" + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(deleteRoutePath)) + Expect(req.Method).To(Equal("DELETE")) + + res.WriteHeader(204) + })) + }) + It(`Invoke DeleteRoute successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + response, operationErr := metricsRouterService.DeleteRoute(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + + // Construct an instance of the DeleteRouteOptions model + deleteRouteOptionsModel := new(metricsrouterv3.DeleteRouteOptions) + deleteRouteOptionsModel.ID = core.StringPtr("testString") + deleteRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + response, operationErr = metricsRouterService.DeleteRoute(deleteRouteOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + }) + It(`Invoke DeleteRoute with error: Operation validation and request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the DeleteRouteOptions model + deleteRouteOptionsModel := new(metricsrouterv3.DeleteRouteOptions) + deleteRouteOptionsModel.ID = core.StringPtr("testString") + deleteRouteOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + response, operationErr := metricsRouterService.DeleteRoute(deleteRouteOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + // Construct a second instance of the DeleteRouteOptions model with no property values + deleteRouteOptionsModelNew := new(metricsrouterv3.DeleteRouteOptions) + // Invoke operation with invalid model (negative test) + response, operationErr = metricsRouterService.DeleteRoute(deleteRouteOptionsModelNew) + Expect(operationErr).ToNot(BeNil()) + Expect(response).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`GetSettings(getSettingsOptions *GetSettingsOptions) - Operation response error`, func() { + getSettingsPath := "/settings" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getSettingsPath)) + Expect(req.Method).To(Equal("GET")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke GetSettings with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetSettingsOptions model + getSettingsOptionsModel := new(metricsrouterv3.GetSettingsOptions) + getSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.GetSettings(getSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.GetSettings(getSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`GetSettings(getSettingsOptions *GetSettingsOptions)`, func() { + getSettingsPath := "/settings" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getSettingsPath)) + Expect(req.Method).To(Equal("GET")) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"default_targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "permitted_target_regions": ["us-south"], "primary_metadata_region": "us-south", "backup_metadata_region": "us-east", "private_api_endpoint_only": false}`) + })) + }) + It(`Invoke GetSettings successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the GetSettingsOptions model + getSettingsOptionsModel := new(metricsrouterv3.GetSettingsOptions) + getSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.GetSettingsWithContext(ctx, getSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.GetSettings(getSettingsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.GetSettingsWithContext(ctx, getSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(getSettingsPath)) + Expect(req.Method).To(Equal("GET")) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"default_targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "permitted_target_regions": ["us-south"], "primary_metadata_region": "us-south", "backup_metadata_region": "us-east", "private_api_endpoint_only": false}`) + })) + }) + It(`Invoke GetSettings successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.GetSettings(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the GetSettingsOptions model + getSettingsOptionsModel := new(metricsrouterv3.GetSettingsOptions) + getSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.GetSettings(getSettingsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke GetSettings with error: Operation request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetSettingsOptions model + getSettingsOptionsModel := new(metricsrouterv3.GetSettingsOptions) + getSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.GetSettings(getSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke GetSettings successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the GetSettingsOptions model + getSettingsOptionsModel := new(metricsrouterv3.GetSettingsOptions) + getSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.GetSettings(getSettingsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`UpdateSettings(updateSettingsOptions *UpdateSettingsOptions) - Operation response error`, func() { + updateSettingsPath := "/settings" + Context(`Using mock server endpoint with invalid JSON response`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateSettingsPath)) + Expect(req.Method).To(Equal("PATCH")) + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprint(res, `} this is not valid json {`) + })) + }) + It(`Invoke UpdateSettings with error: Operation response processing error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the UpdateSettingsOptions model + updateSettingsOptionsModel := new(metricsrouterv3.UpdateSettingsOptions) + updateSettingsOptionsModel.DefaultTargets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + updateSettingsOptionsModel.PermittedTargetRegions = []string{"us-south"} + updateSettingsOptionsModel.PrimaryMetadataRegion = core.StringPtr("us-south") + updateSettingsOptionsModel.BackupMetadataRegion = core.StringPtr("us-east") + updateSettingsOptionsModel.PrivateAPIEndpointOnly = core.BoolPtr(false) + updateSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Expect response parsing to fail since we are receiving a text/plain response + result, response, operationErr := metricsRouterService.UpdateSettings(updateSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + + // Enable retries and test again + metricsRouterService.EnableRetries(0, 0) + result, response, operationErr = metricsRouterService.UpdateSettings(updateSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`UpdateSettings(updateSettingsOptions *UpdateSettingsOptions)`, func() { + updateSettingsPath := "/settings" + Context(`Using mock server endpoint with timeout`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateSettingsPath)) + Expect(req.Method).To(Equal("PATCH")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Sleep a short time to support a timeout test + time.Sleep(100 * time.Millisecond) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"default_targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "permitted_target_regions": ["us-south"], "primary_metadata_region": "us-south", "backup_metadata_region": "us-east", "private_api_endpoint_only": false}`) + })) + }) + It(`Invoke UpdateSettings successfully with retries`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + metricsRouterService.EnableRetries(0, 0) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the UpdateSettingsOptions model + updateSettingsOptionsModel := new(metricsrouterv3.UpdateSettingsOptions) + updateSettingsOptionsModel.DefaultTargets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + updateSettingsOptionsModel.PermittedTargetRegions = []string{"us-south"} + updateSettingsOptionsModel.PrimaryMetadataRegion = core.StringPtr("us-south") + updateSettingsOptionsModel.BackupMetadataRegion = core.StringPtr("us-east") + updateSettingsOptionsModel.PrivateAPIEndpointOnly = core.BoolPtr(false) + updateSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with a Context to test a timeout error + ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc() + _, _, operationErr := metricsRouterService.UpdateSettingsWithContext(ctx, updateSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + + // Disable retries and test again + metricsRouterService.DisableRetries() + result, response, operationErr := metricsRouterService.UpdateSettings(updateSettingsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + // Re-test the timeout error with retries disabled + ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancelFunc2() + _, _, operationErr = metricsRouterService.UpdateSettingsWithContext(ctx, updateSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded")) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Verify the contents of the request + Expect(req.URL.EscapedPath()).To(Equal(updateSettingsPath)) + Expect(req.Method).To(Equal("PATCH")) + + // For gzip-disabled operation, verify Content-Encoding is not set. + Expect(req.Header.Get("Content-Encoding")).To(BeEmpty()) + + // If there is a body, then make sure we can read it + bodyBuf := new(bytes.Buffer) + if req.Header.Get("Content-Encoding") == "gzip" { + body, err := core.NewGzipDecompressionReader(req.Body) + Expect(err).To(BeNil()) + _, err = bodyBuf.ReadFrom(body) + Expect(err).To(BeNil()) + } else { + _, err := bodyBuf.ReadFrom(req.Body) + Expect(err).To(BeNil()) + } + fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String()) + + // Set mock response + res.Header().Set("Content-type", "application/json") + res.WriteHeader(200) + fmt.Fprintf(res, "%s", `{"default_targets": [{"id": "c3af557f-fb0e-4476-85c3-0889e7fe7bc4", "crn": "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::", "name": "a-mr-target-us-south", "target_type": "sysdig_monitor"}], "permitted_target_regions": ["us-south"], "primary_metadata_region": "us-south", "backup_metadata_region": "us-east", "private_api_endpoint_only": false}`) + })) + }) + It(`Invoke UpdateSettings successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Invoke operation with nil options model (negative test) + result, response, operationErr := metricsRouterService.UpdateSettings(nil) + Expect(operationErr).NotTo(BeNil()) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the UpdateSettingsOptions model + updateSettingsOptionsModel := new(metricsrouterv3.UpdateSettingsOptions) + updateSettingsOptionsModel.DefaultTargets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + updateSettingsOptionsModel.PermittedTargetRegions = []string{"us-south"} + updateSettingsOptionsModel.PrimaryMetadataRegion = core.StringPtr("us-south") + updateSettingsOptionsModel.BackupMetadataRegion = core.StringPtr("us-east") + updateSettingsOptionsModel.PrivateAPIEndpointOnly = core.BoolPtr(false) + updateSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation with valid options model (positive test) + result, response, operationErr = metricsRouterService.UpdateSettings(updateSettingsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + Expect(result).ToNot(BeNil()) + + }) + It(`Invoke UpdateSettings with error: Operation request error`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the UpdateSettingsOptions model + updateSettingsOptionsModel := new(metricsrouterv3.UpdateSettingsOptions) + updateSettingsOptionsModel.DefaultTargets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + updateSettingsOptionsModel.PermittedTargetRegions = []string{"us-south"} + updateSettingsOptionsModel.PrimaryMetadataRegion = core.StringPtr("us-south") + updateSettingsOptionsModel.BackupMetadataRegion = core.StringPtr("us-east") + updateSettingsOptionsModel.PrivateAPIEndpointOnly = core.BoolPtr(false) + updateSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + // Invoke operation with empty URL (negative test) + err := metricsRouterService.SetServiceURL("") + Expect(err).To(BeNil()) + result, response, operationErr := metricsRouterService.UpdateSettings(updateSettingsOptionsModel) + Expect(operationErr).ToNot(BeNil()) + Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING)) + Expect(response).To(BeNil()) + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + Context(`Using mock server endpoint with missing response body`, func() { + BeforeEach(func() { + testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + defer GinkgoRecover() + + // Set success status code with no respoonse body + res.WriteHeader(200) + })) + }) + It(`Invoke UpdateSettings successfully`, func() { + metricsRouterService, serviceErr := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: testServer.URL, + Authenticator: &core.NoAuthAuthenticator{}, + }) + Expect(serviceErr).To(BeNil()) + Expect(metricsRouterService).ToNot(BeNil()) + + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + + // Construct an instance of the UpdateSettingsOptions model + updateSettingsOptionsModel := new(metricsrouterv3.UpdateSettingsOptions) + updateSettingsOptionsModel.DefaultTargets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + updateSettingsOptionsModel.PermittedTargetRegions = []string{"us-south"} + updateSettingsOptionsModel.PrimaryMetadataRegion = core.StringPtr("us-south") + updateSettingsOptionsModel.BackupMetadataRegion = core.StringPtr("us-east") + updateSettingsOptionsModel.PrivateAPIEndpointOnly = core.BoolPtr(false) + updateSettingsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"} + + // Invoke operation + result, response, operationErr := metricsRouterService.UpdateSettings(updateSettingsOptionsModel) + Expect(operationErr).To(BeNil()) + Expect(response).ToNot(BeNil()) + + // Verify a nil result + Expect(result).To(BeNil()) + }) + AfterEach(func() { + testServer.Close() + }) + }) + }) + Describe(`Model constructor tests`, func() { + Context(`Using a service client instance`, func() { + metricsRouterService, _ := metricsrouterv3.NewMetricsRouterV3(&metricsrouterv3.MetricsRouterV3Options{ + URL: "http://metricsrouterv3modelgenerator.com", + Authenticator: &core.NoAuthAuthenticator{}, + }) + It(`Invoke NewCreateRouteOptions successfully`, func() { + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + Expect(targetIdentityModel).ToNot(BeNil()) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + Expect(targetIdentityModel.ID).To(Equal(core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4"))) + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + Expect(inclusionFilterPrototypeModel).ToNot(BeNil()) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + Expect(inclusionFilterPrototypeModel.Operand).To(Equal(core.StringPtr("location"))) + Expect(inclusionFilterPrototypeModel.Operator).To(Equal(core.StringPtr("is"))) + Expect(inclusionFilterPrototypeModel.Values).To(Equal([]string{"us-south"})) + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + Expect(rulePrototypeModel).ToNot(BeNil()) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + Expect(rulePrototypeModel.Action).To(Equal(core.StringPtr("send"))) + Expect(rulePrototypeModel.Targets).To(Equal([]metricsrouterv3.TargetIdentity{*targetIdentityModel})) + Expect(rulePrototypeModel.InclusionFilters).To(Equal([]metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel})) + + // Construct an instance of the CreateRouteOptions model + createRouteOptionsName := "my-route" + createRouteOptionsRules := []metricsrouterv3.RulePrototype{} + createRouteOptionsModel := metricsRouterService.NewCreateRouteOptions(createRouteOptionsName, createRouteOptionsRules) + createRouteOptionsModel.SetName("my-route") + createRouteOptionsModel.SetRules([]metricsrouterv3.RulePrototype{*rulePrototypeModel}) + createRouteOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(createRouteOptionsModel).ToNot(BeNil()) + Expect(createRouteOptionsModel.Name).To(Equal(core.StringPtr("my-route"))) + Expect(createRouteOptionsModel.Rules).To(Equal([]metricsrouterv3.RulePrototype{*rulePrototypeModel})) + Expect(createRouteOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewCreateTargetOptions successfully`, func() { + // Construct an instance of the CreateTargetOptions model + createTargetOptionsName := "my-mr-target" + createTargetOptionsDestinationCRN := "crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::" + createTargetOptionsModel := metricsRouterService.NewCreateTargetOptions(createTargetOptionsName, createTargetOptionsDestinationCRN) + createTargetOptionsModel.SetName("my-mr-target") + createTargetOptionsModel.SetDestinationCRN("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + createTargetOptionsModel.SetRegion("us-south") + createTargetOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(createTargetOptionsModel).ToNot(BeNil()) + Expect(createTargetOptionsModel.Name).To(Equal(core.StringPtr("my-mr-target"))) + Expect(createTargetOptionsModel.DestinationCRN).To(Equal(core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::"))) + Expect(createTargetOptionsModel.Region).To(Equal(core.StringPtr("us-south"))) + Expect(createTargetOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewDeleteRouteOptions successfully`, func() { + // Construct an instance of the DeleteRouteOptions model + id := "testString" + deleteRouteOptionsModel := metricsRouterService.NewDeleteRouteOptions(id) + deleteRouteOptionsModel.SetID("testString") + deleteRouteOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(deleteRouteOptionsModel).ToNot(BeNil()) + Expect(deleteRouteOptionsModel.ID).To(Equal(core.StringPtr("testString"))) + Expect(deleteRouteOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewDeleteTargetOptions successfully`, func() { + // Construct an instance of the DeleteTargetOptions model + id := "testString" + deleteTargetOptionsModel := metricsRouterService.NewDeleteTargetOptions(id) + deleteTargetOptionsModel.SetID("testString") + deleteTargetOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(deleteTargetOptionsModel).ToNot(BeNil()) + Expect(deleteTargetOptionsModel.ID).To(Equal(core.StringPtr("testString"))) + Expect(deleteTargetOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewGetRouteOptions successfully`, func() { + // Construct an instance of the GetRouteOptions model + id := "testString" + getRouteOptionsModel := metricsRouterService.NewGetRouteOptions(id) + getRouteOptionsModel.SetID("testString") + getRouteOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(getRouteOptionsModel).ToNot(BeNil()) + Expect(getRouteOptionsModel.ID).To(Equal(core.StringPtr("testString"))) + Expect(getRouteOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewGetSettingsOptions successfully`, func() { + // Construct an instance of the GetSettingsOptions model + getSettingsOptionsModel := metricsRouterService.NewGetSettingsOptions() + getSettingsOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(getSettingsOptionsModel).ToNot(BeNil()) + Expect(getSettingsOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewGetTargetOptions successfully`, func() { + // Construct an instance of the GetTargetOptions model + id := "testString" + getTargetOptionsModel := metricsRouterService.NewGetTargetOptions(id) + getTargetOptionsModel.SetID("testString") + getTargetOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(getTargetOptionsModel).ToNot(BeNil()) + Expect(getTargetOptionsModel.ID).To(Equal(core.StringPtr("testString"))) + Expect(getTargetOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewInclusionFilterPrototype successfully`, func() { + operand := "location" + operator := "is" + values := []string{"us-south"} + _model, err := metricsRouterService.NewInclusionFilterPrototype(operand, operator, values) + Expect(_model).ToNot(BeNil()) + Expect(err).To(BeNil()) + }) + It(`Invoke NewListRoutesOptions successfully`, func() { + // Construct an instance of the ListRoutesOptions model + listRoutesOptionsModel := metricsRouterService.NewListRoutesOptions() + listRoutesOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(listRoutesOptionsModel).ToNot(BeNil()) + Expect(listRoutesOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewListTargetsOptions successfully`, func() { + // Construct an instance of the ListTargetsOptions model + listTargetsOptionsModel := metricsRouterService.NewListTargetsOptions() + listTargetsOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(listTargetsOptionsModel).ToNot(BeNil()) + Expect(listTargetsOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewRulePrototype successfully`, func() { + targets := []metricsrouterv3.TargetIdentity{} + inclusionFilters := []metricsrouterv3.InclusionFilterPrototype{} + _model, err := metricsRouterService.NewRulePrototype(targets, inclusionFilters) + Expect(_model).ToNot(BeNil()) + Expect(err).To(BeNil()) + }) + It(`Invoke NewTargetIdentity successfully`, func() { + id := "c3af557f-fb0e-4476-85c3-0889e7fe7bc4" + _model, err := metricsRouterService.NewTargetIdentity(id) + Expect(_model).ToNot(BeNil()) + Expect(err).To(BeNil()) + }) + It(`Invoke NewUpdateRouteOptions successfully`, func() { + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + Expect(targetIdentityModel).ToNot(BeNil()) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + Expect(targetIdentityModel.ID).To(Equal(core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4"))) + + // Construct an instance of the InclusionFilterPrototype model + inclusionFilterPrototypeModel := new(metricsrouterv3.InclusionFilterPrototype) + Expect(inclusionFilterPrototypeModel).ToNot(BeNil()) + inclusionFilterPrototypeModel.Operand = core.StringPtr("location") + inclusionFilterPrototypeModel.Operator = core.StringPtr("is") + inclusionFilterPrototypeModel.Values = []string{"us-south"} + Expect(inclusionFilterPrototypeModel.Operand).To(Equal(core.StringPtr("location"))) + Expect(inclusionFilterPrototypeModel.Operator).To(Equal(core.StringPtr("is"))) + Expect(inclusionFilterPrototypeModel.Values).To(Equal([]string{"us-south"})) + + // Construct an instance of the RulePrototype model + rulePrototypeModel := new(metricsrouterv3.RulePrototype) + Expect(rulePrototypeModel).ToNot(BeNil()) + rulePrototypeModel.Action = core.StringPtr("send") + rulePrototypeModel.Targets = []metricsrouterv3.TargetIdentity{*targetIdentityModel} + rulePrototypeModel.InclusionFilters = []metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel} + Expect(rulePrototypeModel.Action).To(Equal(core.StringPtr("send"))) + Expect(rulePrototypeModel.Targets).To(Equal([]metricsrouterv3.TargetIdentity{*targetIdentityModel})) + Expect(rulePrototypeModel.InclusionFilters).To(Equal([]metricsrouterv3.InclusionFilterPrototype{*inclusionFilterPrototypeModel})) + + // Construct an instance of the UpdateRouteOptions model + id := "testString" + updateRouteOptionsModel := metricsRouterService.NewUpdateRouteOptions(id) + updateRouteOptionsModel.SetID("testString") + updateRouteOptionsModel.SetName("my-route") + updateRouteOptionsModel.SetRules([]metricsrouterv3.RulePrototype{*rulePrototypeModel}) + updateRouteOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(updateRouteOptionsModel).ToNot(BeNil()) + Expect(updateRouteOptionsModel.ID).To(Equal(core.StringPtr("testString"))) + Expect(updateRouteOptionsModel.Name).To(Equal(core.StringPtr("my-route"))) + Expect(updateRouteOptionsModel.Rules).To(Equal([]metricsrouterv3.RulePrototype{*rulePrototypeModel})) + Expect(updateRouteOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewUpdateSettingsOptions successfully`, func() { + // Construct an instance of the TargetIdentity model + targetIdentityModel := new(metricsrouterv3.TargetIdentity) + Expect(targetIdentityModel).ToNot(BeNil()) + targetIdentityModel.ID = core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4") + Expect(targetIdentityModel.ID).To(Equal(core.StringPtr("c3af557f-fb0e-4476-85c3-0889e7fe7bc4"))) + + // Construct an instance of the UpdateSettingsOptions model + updateSettingsOptionsModel := metricsRouterService.NewUpdateSettingsOptions() + updateSettingsOptionsModel.SetDefaultTargets([]metricsrouterv3.TargetIdentity{*targetIdentityModel}) + updateSettingsOptionsModel.SetPermittedTargetRegions([]string{"us-south"}) + updateSettingsOptionsModel.SetPrimaryMetadataRegion("us-south") + updateSettingsOptionsModel.SetBackupMetadataRegion("us-east") + updateSettingsOptionsModel.SetPrivateAPIEndpointOnly(false) + updateSettingsOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(updateSettingsOptionsModel).ToNot(BeNil()) + Expect(updateSettingsOptionsModel.DefaultTargets).To(Equal([]metricsrouterv3.TargetIdentity{*targetIdentityModel})) + Expect(updateSettingsOptionsModel.PermittedTargetRegions).To(Equal([]string{"us-south"})) + Expect(updateSettingsOptionsModel.PrimaryMetadataRegion).To(Equal(core.StringPtr("us-south"))) + Expect(updateSettingsOptionsModel.BackupMetadataRegion).To(Equal(core.StringPtr("us-east"))) + Expect(updateSettingsOptionsModel.PrivateAPIEndpointOnly).To(Equal(core.BoolPtr(false))) + Expect(updateSettingsOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + It(`Invoke NewUpdateTargetOptions successfully`, func() { + // Construct an instance of the UpdateTargetOptions model + id := "testString" + updateTargetOptionsModel := metricsRouterService.NewUpdateTargetOptions(id) + updateTargetOptionsModel.SetID("testString") + updateTargetOptionsModel.SetName("my-mr-target") + updateTargetOptionsModel.SetDestinationCRN("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::") + updateTargetOptionsModel.SetHeaders(map[string]string{"foo": "bar"}) + Expect(updateTargetOptionsModel).ToNot(BeNil()) + Expect(updateTargetOptionsModel.ID).To(Equal(core.StringPtr("testString"))) + Expect(updateTargetOptionsModel.Name).To(Equal(core.StringPtr("my-mr-target"))) + Expect(updateTargetOptionsModel.DestinationCRN).To(Equal(core.StringPtr("crn:v1:bluemix:public:sysdig-monitor:us-south:a/0be5ad401ae913d8ff665d92680664ed:22222222-2222-2222-2222-222222222222::"))) + Expect(updateTargetOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"})) + }) + }) + }) + Describe(`Utility function tests`, func() { + It(`Invoke CreateMockByteArray() successfully`, func() { + mockByteArray := CreateMockByteArray("This is a test") + Expect(mockByteArray).ToNot(BeNil()) + }) + It(`Invoke CreateMockUUID() successfully`, func() { + mockUUID := CreateMockUUID("9fab83da-98cb-4f18-a7ba-b6f0435c9673") + Expect(mockUUID).ToNot(BeNil()) + }) + It(`Invoke CreateMockReader() successfully`, func() { + mockReader := CreateMockReader("This is a test.") + Expect(mockReader).ToNot(BeNil()) + }) + It(`Invoke CreateMockDate() successfully`, func() { + mockDate := CreateMockDate("2019-01-01") + Expect(mockDate).ToNot(BeNil()) + }) + It(`Invoke CreateMockDateTime() successfully`, func() { + mockDateTime := CreateMockDateTime("2019-01-01T12:00:00.000Z") + Expect(mockDateTime).ToNot(BeNil()) + }) + }) +}) + +// +// Utility functions used by the generated test code +// + +func CreateMockByteArray(mockData string) *[]byte { + ba := make([]byte, 0) + ba = append(ba, mockData...) + return &ba +} + +func CreateMockUUID(mockData string) *strfmt.UUID { + uuid := strfmt.UUID(mockData) + return &uuid +} + +func CreateMockReader(mockData string) io.ReadCloser { + return io.NopCloser(bytes.NewReader([]byte(mockData))) +} + +func CreateMockDate(mockData string) *strfmt.Date { + d, err := core.ParseDate(mockData) + if err != nil { + return nil + } + return &d +} + +func CreateMockDateTime(mockData string) *strfmt.DateTime { + d, err := core.ParseDateTime(mockData) + if err != nil { + return nil + } + return &d +} + +func SetTestEnvironment(testEnvironment map[string]string) { + for key, value := range testEnvironment { + os.Setenv(key, value) + } +} + +func ClearTestEnvironment(testEnvironment map[string]string) { + for key := range testEnvironment { + os.Unsetenv(key) + } +}