From c9d00c9379977b07c1b3f09d32ecc7a973d3403b Mon Sep 17 00:00:00 2001 From: Zhennan Wang Date: Fri, 1 Oct 2021 14:05:28 -0500 Subject: [PATCH] feat(CBR): Added Context-Based-Restrictions (#136) --- .gitignore | 1 + README.md | 1 + context-based-restrictions/v1.ts | 1330 +++++++++++++++++ .../context-based-restrictions.v1.test.js | 511 +++++++ scripts/typedoc/generate_typedoc.sh | 1 + .../context-based-restrictions.v1.test.js | 832 +++++++++++ .../context-based-restrictions.v1.test.js | 1236 +++++++++++++++ 7 files changed, 3912 insertions(+) create mode 100644 context-based-restrictions/v1.ts create mode 100644 examples/context-based-restrictions.v1.test.js create mode 100644 test/integration/context-based-restrictions.v1.test.js create mode 100644 test/unit/context-based-restrictions.v1.test.js diff --git a/.gitignore b/.gitignore index 3d318c92..c3b206b7 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ lib/*.js case-management/*.js catalog-management/*.js configuration-governance/*.js +context-based-restrictions/*.js enterprise-billing-units/*.js enterprise-management/*.js enterprise-usage-reports/*.js diff --git a/README.md b/README.md index 7b7c8a5f..a4ca1429 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ Service Name | Import Path [Case Management](https://cloud.ibm.com/apidocs/case-management?code=node) | @ibm-cloud/platform-services/case-management/v1 [Catalog Management](https://cloud.ibm.com/apidocs/resource-catalog/private-catalog?code=node) | @ibm-cloud/platform-services/catalog-management/v1 [Configuration Governance](https://cloud.ibm.com/apidocs/security-compliance/config?code=node) | @ibm-cloud/platform-services/configuration-governance/v1 +[Context Based Restrictions](https://cloud.ibm.com/apidocs/context-based-restrictions?code=node) | @ibm-cloud/platform-services/context-based-restrictions/v1 [Enterprise Billing Units](https://cloud.ibm.com/apidocs/enterprise-apis/billing-unit?code=node) | @ibm-cloud/platform-services/enterprise-billing-units/v1 [Enterprise Management](https://cloud.ibm.com/apidocs/enterprise-apis/enterprise?code=node) | @ibm-cloud/platform-services/enterprise-management/v1 [Enterprise Usage Reports](https://cloud.ibm.com/apidocs/enterprise-apis/resource-usage-reports?code=node) | @ibm-cloud/platform-services/enterprise-usage-reports/v1 diff --git a/context-based-restrictions/v1.ts b/context-based-restrictions/v1.ts new file mode 100644 index 00000000..50166c19 --- /dev/null +++ b/context-based-restrictions/v1.ts @@ -0,0 +1,1330 @@ +/** + * (C) Copyright IBM Corp. 2021. + * + * 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.38.1-1037b405-20210908-184149 + */ + +import * as extend from 'extend'; +import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'; +import { + Authenticator, + BaseService, + getAuthenticatorFromEnvironment, + getMissingParams, + UserOptions, +} from 'ibm-cloud-sdk-core'; +import { getSdkHeaders } from '../lib/common'; + +/** + * With the Context Based Restrictions API, you can: + * * Create, list, get, update, and delete network zones + * * Create, list, get, update, and delete context-based restriction rules + * * Get account settings + * + * API Version: 1.0.0 + */ + +class ContextBasedRestrictionsV1 extends BaseService { + static DEFAULT_SERVICE_URL: string = 'https://cbr.cloud.ibm.com'; + + static DEFAULT_SERVICE_NAME: string = 'context_based_restrictions'; + + /************************* + * Factory method + ************************/ + + /** + * Constructs an instance of ContextBasedRestrictionsV1 with passed in options and external configuration. + * + * @param {UserOptions} [options] - The parameters to send to the service. + * @param {string} [options.serviceName] - The name of the service to configure + * @param {Authenticator} [options.authenticator] - The Authenticator object used to authenticate requests to the service + * @param {string} [options.serviceUrl] - The URL for the service + * @returns {ContextBasedRestrictionsV1} + */ + + public static newInstance(options: UserOptions): ContextBasedRestrictionsV1 { + options = options || {}; + + if (!options.serviceName) { + options.serviceName = this.DEFAULT_SERVICE_NAME; + } + if (!options.authenticator) { + options.authenticator = getAuthenticatorFromEnvironment(options.serviceName); + } + const service = new ContextBasedRestrictionsV1(options); + service.configureService(options.serviceName); + if (options.serviceUrl) { + service.setServiceUrl(options.serviceUrl); + } + return service; + } + + /** + * Construct a ContextBasedRestrictionsV1 object. + * + * @param {Object} options - Options for the service. + * @param {string} [options.serviceUrl] - The base url to use when contacting the service. The base url may differ between IBM Cloud regions. + * @param {OutgoingHttpHeaders} [options.headers] - Default headers that shall be included with every request to the service. + * @param {Authenticator} options.authenticator - The Authenticator object used to authenticate requests to the service + * @constructor + * @returns {ContextBasedRestrictionsV1} + */ + constructor(options: UserOptions) { + options = options || {}; + + super(options); + if (options.serviceUrl) { + this.setServiceUrl(options.serviceUrl); + } else { + this.setServiceUrl(ContextBasedRestrictionsV1.DEFAULT_SERVICE_URL); + } + } + + /************************* + * zones + ************************/ + + /** + * Create a zone. + * + * This operation creates a network zone for the specified account. + * + * @param {Object} [params] - The parameters to send to the service. + * @param {string} [params.name] - The name of the zone. + * @param {string} [params.accountId] - The id of the account owning this zone. + * @param {Address[]} [params.addresses] - The list of addresses in the zone. + * @param {string} [params.description] - The description of the zone. + * @param {Address[]} [params.excluded] - The list of excluded addresses in the zone. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public createZone( + params?: ContextBasedRestrictionsV1.CreateZoneParams + ): Promise> { + const _params = { ...params }; + + const body = { + 'name': _params.name, + 'account_id': _params.accountId, + 'addresses': _params.addresses, + 'description': _params.description, + 'excluded': _params.excluded, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'createZone' + ); + + const parameters = { + options: { + url: '/v1/zones', + method: 'POST', + body, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * List network zones. + * + * This operation lists network zones in the specified account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The ID of the managing account. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {string} [params.name] - The name of the zone. + * @param {string} [params.sort] - Sorts results by using a valid sort field. To learn more, see + * [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting). + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public listZones( + params: ContextBasedRestrictionsV1.ListZonesParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['accountId']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const query = { + 'account_id': _params.accountId, + 'name': _params.name, + 'sort': _params.sort, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'listZones' + ); + + const parameters = { + options: { + url: '/v1/zones', + method: 'GET', + qs: query, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Get the specified network zone. + * + * This operation returns the network zone for the specified ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.zoneId - The ID of a zone. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public getZone( + params: ContextBasedRestrictionsV1.GetZoneParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['zoneId']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const path = { + 'zone_id': _params.zoneId, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'getZone' + ); + + const parameters = { + options: { + url: '/v1/zones/{zone_id}', + method: 'GET', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Update the specified network zone. + * + * This operation updates the network zone with the specified ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.zoneId - The ID of a zone. + * @param {string} params.ifMatch - The current revision of the resource being updated. This can be found in the + * Create/Get/Update resource response ETag header. + * @param {string} [params.name] - The name of the zone. + * @param {string} [params.accountId] - The id of the account owning this zone. + * @param {Address[]} [params.addresses] - The list of addresses in the zone. + * @param {string} [params.description] - The description of the zone. + * @param {Address[]} [params.excluded] - The list of excluded addresses in the zone. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public replaceZone( + params: ContextBasedRestrictionsV1.ReplaceZoneParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['zoneId', 'ifMatch']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const body = { + 'name': _params.name, + 'account_id': _params.accountId, + 'addresses': _params.addresses, + 'description': _params.description, + 'excluded': _params.excluded, + }; + + const path = { + 'zone_id': _params.zoneId, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'replaceZone' + ); + + const parameters = { + options: { + url: '/v1/zones/{zone_id}', + method: 'PUT', + body, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'If-Match': _params.ifMatch, + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Delete the specified network zone. + * + * This operation deletes the network zone with the specified home ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.zoneId - The ID of a zone. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public deleteZone( + params: ContextBasedRestrictionsV1.DeleteZoneParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['zoneId']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const path = { + 'zone_id': _params.zoneId, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'deleteZone' + ); + + const parameters = { + options: { + url: '/v1/zones/{zone_id}', + method: 'DELETE', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * List available service reference targets. + * + * This operation lists all available service reference targets. + * + * @param {Object} [params] - The parameters to send to the service. + * @param {string} [params.type] - Specifies the types of services to retrieve. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public listAvailableServicerefTargets( + params?: ContextBasedRestrictionsV1.ListAvailableServicerefTargetsParams + ): Promise> { + const _params = { ...params }; + + const query = { + 'type': _params.type, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'listAvailableServicerefTargets' + ); + + const parameters = { + options: { + url: '/v1/zones/serviceref_targets', + method: 'GET', + qs: query, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + /************************* + * rules + ************************/ + + /** + * Create a rule. + * + * This operation creates a rule for the specified account. + * + * @param {Object} [params] - The parameters to send to the service. + * @param {RuleContext[]} [params.contexts] - The contexts this rule applies to. + * @param {Resource[]} [params.resources] - The resources this rule apply to. + * @param {string} [params.description] - The description of the rule. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public createRule( + params?: ContextBasedRestrictionsV1.CreateRuleParams + ): Promise> { + const _params = { ...params }; + + const body = { + 'contexts': _params.contexts, + 'resources': _params.resources, + 'description': _params.description, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'createRule' + ); + + const parameters = { + options: { + url: '/v1/rules', + method: 'POST', + body, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * List rules. + * + * This operation lists rules for the specified account. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The ID of the managing account. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {string} [params.region] - The `region` resource attribute. + * @param {string} [params.resource] - The `resource` resource attribute. + * @param {string} [params.resourceType] - The `resourceType` resource attribute. + * @param {string} [params.serviceInstance] - The `serviceInstance` resource attribute. + * @param {string} [params.serviceName] - The `serviceName` resource attribute. + * @param {string} [params.serviceType] - The rule's `serviceType` resource attribute. + * @param {string} [params.zoneId] - The globally unique ID of the zone. + * @param {string} [params.sort] - Sorts results by using a valid sort field. To learn more, see + * [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting). + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public listRules( + params: ContextBasedRestrictionsV1.ListRulesParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['accountId']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const query = { + 'account_id': _params.accountId, + 'region': _params.region, + 'resource': _params.resource, + 'resource_type': _params.resourceType, + 'service_instance': _params.serviceInstance, + 'service_name': _params.serviceName, + 'service_type': _params.serviceType, + 'zone_id': _params.zoneId, + 'sort': _params.sort, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'listRules' + ); + + const parameters = { + options: { + url: '/v1/rules', + method: 'GET', + qs: query, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Get the specified rule. + * + * This operation gets the rule for the specified ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.ruleId - The ID of a rule. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public getRule( + params: ContextBasedRestrictionsV1.GetRuleParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['ruleId']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const path = { + 'rule_id': _params.ruleId, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'getRule' + ); + + const parameters = { + options: { + url: '/v1/rules/{rule_id}', + method: 'GET', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Update the specified rule. + * + * This operation updates the rule for the specified ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.ruleId - The ID of a rule. + * @param {string} params.ifMatch - The current revision of the resource being updated. This can be found in the + * Create/Get/Update resource response ETag header. + * @param {RuleContext[]} [params.contexts] - The contexts this rule applies to. + * @param {Resource[]} [params.resources] - The resources this rule apply to. + * @param {string} [params.description] - The description of the rule. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public replaceRule( + params: ContextBasedRestrictionsV1.ReplaceRuleParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['ruleId', 'ifMatch']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const body = { + 'contexts': _params.contexts, + 'resources': _params.resources, + 'description': _params.description, + }; + + const path = { + 'rule_id': _params.ruleId, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'replaceRule' + ); + + const parameters = { + options: { + url: '/v1/rules/{rule_id}', + method: 'PUT', + body, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'If-Match': _params.ifMatch, + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Delete the specified rule. + * + * This operation deletes the rule for the specified home ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.ruleId - The ID of a rule. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public deleteRule( + params: ContextBasedRestrictionsV1.DeleteRuleParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['ruleId']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const path = { + 'rule_id': _params.ruleId, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'deleteRule' + ); + + const parameters = { + options: { + url: '/v1/rules/{rule_id}', + method: 'DELETE', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + /************************* + * accountSettings + ************************/ + + /** + * Get the specified account settings. + * + * This operation gets the settings for the specified account ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The ID of the account the settings are for. + * @param {string} [params.transactionId] - The UUID that is used to correlate and track transactions. If you omit + * this field, the service generates and sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with each + * request. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public getAccountSettings( + params: ContextBasedRestrictionsV1.GetAccountSettingsParams + ): Promise> { + const _params = { ...params }; + const requiredParams = ['accountId']; + + const missingParams = getMissingParams(_params, requiredParams); + if (missingParams) { + return Promise.reject(missingParams); + } + + const path = { + 'account_id': _params.accountId, + }; + + const sdkHeaders = getSdkHeaders( + ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME, + 'v1', + 'getAccountSettings' + ); + + const parameters = { + options: { + url: '/v1/account_settings/{account_id}', + method: 'GET', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Transaction-Id': _params.transactionId, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } +} + +/************************* + * interfaces + ************************/ + +namespace ContextBasedRestrictionsV1 { + /** An operation response. */ + export interface Response { + result: T; + status: number; + statusText: string; + headers: IncomingHttpHeaders; + } + + /** The callback for a service request. */ + export type Callback = (error: any, response?: Response) => void; + + /** The body of a service request that returns no response data. */ + export interface Empty {} + + /** A standard JS object, defined to avoid the limitations of `Object` and `object` */ + export interface JsonObject { + [key: string]: any; + } + + /************************* + * request interfaces + ************************/ + + /** Parameters for the `createZone` operation. */ + export interface CreateZoneParams { + /** The name of the zone. */ + name?: string; + /** The id of the account owning this zone. */ + accountId?: string; + /** The list of addresses in the zone. */ + addresses?: Address[]; + /** The description of the zone. */ + description?: string; + /** The list of excluded addresses in the zone. */ + excluded?: Address[]; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `listZones` operation. */ + export interface ListZonesParams { + /** The ID of the managing account. */ + accountId: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + /** The name of the zone. */ + name?: string; + /** Sorts results by using a valid sort field. To learn more, see + * [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting). + */ + sort?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `getZone` operation. */ + export interface GetZoneParams { + /** The ID of a zone. */ + zoneId: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `replaceZone` operation. */ + export interface ReplaceZoneParams { + /** The ID of a zone. */ + zoneId: string; + /** The current revision of the resource being updated. This can be found in the Create/Get/Update resource + * response ETag header. + */ + ifMatch: string; + /** The name of the zone. */ + name?: string; + /** The id of the account owning this zone. */ + accountId?: string; + /** The list of addresses in the zone. */ + addresses?: Address[]; + /** The description of the zone. */ + description?: string; + /** The list of excluded addresses in the zone. */ + excluded?: Address[]; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `deleteZone` operation. */ + export interface DeleteZoneParams { + /** The ID of a zone. */ + zoneId: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `listAvailableServicerefTargets` operation. */ + export interface ListAvailableServicerefTargetsParams { + /** Specifies the types of services to retrieve. */ + type?: ListAvailableServicerefTargetsConstants.Type | string; + headers?: OutgoingHttpHeaders; + } + + /** Constants for the `listAvailableServicerefTargets` operation. */ + export namespace ListAvailableServicerefTargetsConstants { + /** Specifies the types of services to retrieve. */ + export enum Type { + ALL = 'all', + PLATFORM_SERVICE = 'platform_service', + } + } + + /** Parameters for the `createRule` operation. */ + export interface CreateRuleParams { + /** The contexts this rule applies to. */ + contexts?: RuleContext[]; + /** The resources this rule apply to. */ + resources?: Resource[]; + /** The description of the rule. */ + description?: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `listRules` operation. */ + export interface ListRulesParams { + /** The ID of the managing account. */ + accountId: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + /** The `region` resource attribute. */ + region?: string; + /** The `resource` resource attribute. */ + resource?: string; + /** The `resourceType` resource attribute. */ + resourceType?: string; + /** The `serviceInstance` resource attribute. */ + serviceInstance?: string; + /** The `serviceName` resource attribute. */ + serviceName?: string; + /** The rule's `serviceType` resource attribute. */ + serviceType?: string; + /** The globally unique ID of the zone. */ + zoneId?: string; + /** Sorts results by using a valid sort field. To learn more, see + * [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting). + */ + sort?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `getRule` operation. */ + export interface GetRuleParams { + /** The ID of a rule. */ + ruleId: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `replaceRule` operation. */ + export interface ReplaceRuleParams { + /** The ID of a rule. */ + ruleId: string; + /** The current revision of the resource being updated. This can be found in the Create/Get/Update resource + * response ETag header. + */ + ifMatch: string; + /** The contexts this rule applies to. */ + contexts?: RuleContext[]; + /** The resources this rule apply to. */ + resources?: Resource[]; + /** The description of the rule. */ + description?: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `deleteRule` operation. */ + export interface DeleteRuleParams { + /** The ID of a rule. */ + ruleId: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `getAccountSettings` operation. */ + export interface GetAccountSettingsParams { + /** The ID of the account the settings are for. */ + accountId: string; + /** The UUID that is used to correlate and track transactions. If you omit this field, the service generates and + * sends a transaction ID in the response. + * **Note:** To help with debugging, we strongly recommend that you generate and supply a `Transaction-Id` with + * each request. + */ + transactionId?: string; + headers?: OutgoingHttpHeaders; + } + + /************************* + * model interfaces + ************************/ + + /** An output account settings. */ + export interface AccountSettings { + /** The globally unique ID of the account settings. */ + id: string; + /** The account settings CRN. */ + crn: string; + /** the max number of rules allowed for the account. */ + rule_count_limit: number; + /** the max number of zones allowed for the account. */ + zone_count_limit: number; + /** the current number of rules used by the account. */ + current_rule_count: number; + /** the current number of zones used by the account. */ + current_zone_count: number; + /** The href link to the resource. */ + href: string; + /** The time the resource was created. */ + created_at: string; + /** IAM ID of the user or service which created the resource. */ + created_by_id: string; + /** The last time the resource was modified. */ + last_modified_at: string; + /** IAM ID of the user or service which modified the resource. */ + last_modified_by_id: string; + } + + /** A zone address. */ + export interface Address { + /** The type of address. */ + type?: string; + } + + /** An rule resource. */ + export interface Resource { + /** The resource attributes. */ + attributes: ResourceAttribute[]; + /** The optional resource tags. */ + tags?: ResourceTagAttribute[]; + } + + /** A rule resource attribute. */ + export interface ResourceAttribute { + /** The attribute name. */ + name: string; + /** The attribute value. */ + value: string; + /** The attribute operator. */ + operator?: string; + } + + /** A rule resource tag attribute. */ + export interface ResourceTagAttribute { + /** The tag attribute name. */ + name: string; + /** The tag attribute value. */ + value: string; + /** The attribute operator. */ + operator?: string; + } + + /** An output rule. */ + export interface Rule { + /** The globally unique ID of the rule. */ + id: string; + /** The rule CRN. */ + crn: string; + /** The description of the rule. */ + description: string; + /** The contexts this rule applies to. */ + contexts: RuleContext[]; + /** The resources this rule apply to. */ + resources: Resource[]; + /** The href link to the resource. */ + href: string; + /** The time the resource was created. */ + created_at: string; + /** IAM ID of the user or service which created the resource. */ + created_by_id: string; + /** The last time the resource was modified. */ + last_modified_at: string; + /** IAM ID of the user or service which modified the resource. */ + last_modified_by_id: string; + } + + /** A rule context. */ + export interface RuleContext { + /** The attributes. */ + attributes: RuleContextAttribute[]; + } + + /** An rule context attribute. */ + export interface RuleContextAttribute { + /** The attribute name. */ + name: string; + /** The attribute value. */ + value: string; + } + + /** The response object of the ListRules operation. */ + export interface RuleList { + /** The number of returned results. */ + count: number; + /** The returned rules. */ + rules: Rule[]; + } + + /** Summary information about a service reference target. */ + export interface ServiceRefTarget { + /** The name of the service. */ + service_name: string; + /** The type of the service. */ + service_type?: string; + } + + /** A list of service reference targets. */ + export interface ServiceRefTargetList { + /** The number of returned results. */ + count: number; + /** The list of service reference targets. */ + targets: ServiceRefTarget[]; + } + + /** A service reference value. */ + export interface ServiceRefValue { + /** The id of the account owning the service. */ + account_id: string; + /** The service type. */ + service_type?: string; + /** The service name. */ + service_name?: string; + /** The service instance. */ + service_instance?: string; + } + + /** An output zone. */ + export interface Zone { + /** The globally unique ID of the zone. */ + id: string; + /** The zone CRN. */ + crn: string; + /** The number of addresses in the zone. */ + address_count: number; + /** The number of excluded addresses in the zone. */ + excluded_count: number; + /** The name of the zone. */ + name: string; + /** The id of the account owning this zone. */ + account_id: string; + /** The description of the zone. */ + description: string; + /** The list of addresses in the zone. */ + addresses: Address[]; + /** The list of excluded addresses in the zone. */ + excluded: Address[]; + /** The href link to the resource. */ + href: string; + /** The time the resource was created. */ + created_at: string; + /** IAM ID of the user or service which created the resource. */ + created_by_id: string; + /** The last time the resource was modified. */ + last_modified_at: string; + /** IAM ID of the user or service which modified the resource. */ + last_modified_by_id: string; + } + + /** The response object of the ListZones operation. */ + export interface ZoneList { + /** The number of returned results. */ + count: number; + /** The returned zones. */ + zones: ZoneSummary[]; + } + + /** An output zone summary. */ + export interface ZoneSummary { + /** The globally unique ID of the zone. */ + id: string; + /** The zone CRN. */ + crn: string; + /** The name of the zone. */ + name: string; + /** The description of the zone. */ + description?: string; + /** A preview of addresses in the zone (3 addresses maximum). */ + addresses_preview: Address[]; + /** The number of addresses in the zone. */ + address_count: number; + /** The number of excluded addresses in the zone. */ + excluded_count: number; + /** The href link to the resource. */ + href: string; + /** The time the resource was created. */ + created_at: string; + /** IAM ID of the user or service which created the resource. */ + created_by_id: string; + /** The last time the resource was modified. */ + last_modified_at: string; + /** IAM ID of the user or service which modified the resource. */ + last_modified_by_id: string; + } + + /** A single IP address. */ + export interface AddressIPAddress extends Address { + /** The type of address. */ + type: string; + /** The IP address. */ + value: string; + } + + /** An IP address range. */ + export interface AddressIPAddressRange extends Address { + /** The type of address. */ + type: string; + /** The ip range in - format. */ + value: string; + } + + /** A service reference. */ + export interface AddressServiceRef extends Address { + /** The type of address. */ + type: string; + /** A service reference value. */ + ref: ServiceRefValue; + } + + /** A subnet in CIDR format. */ + export interface AddressSubnet extends Address { + /** The type of address. */ + type: string; + /** The subnet in CIDR format. */ + value: string; + } + + /** A single VPC address. */ + export interface AddressVPC extends Address { + /** The type of address. */ + type: string; + /** The VPC CRN. */ + value: string; + } +} + +export = ContextBasedRestrictionsV1; diff --git a/examples/context-based-restrictions.v1.test.js b/examples/context-based-restrictions.v1.test.js new file mode 100644 index 00000000..849f2d22 --- /dev/null +++ b/examples/context-based-restrictions.v1.test.js @@ -0,0 +1,511 @@ +/** + * @jest-environment node + */ +/** + * (C) Copyright IBM Corp. 2021. + * + * 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. + */ + +/* eslint-disable no-console */ + +const ContextBasedRestrictionsV1 = require('../dist/context-based-restrictions/v1'); +// eslint-disable-next-line node/no-unpublished-require +const authHelper = require('../test/resources/auth-helper.js'); +// You can use the readExternalSources method to access additional configuration values +const { readExternalSources } = require('ibm-cloud-sdk-core'); + +// +// This file provides an example of how to use the Context Based Restrictions service. +// +// The following configuration properties are assumed to be defined: +// CONTEXT_BASED_RESTRICTIONS_URL= +// CONTEXT_BASED_RESTRICTIONS_AUTH_TYPE=iam +// CONTEXT_BASED_RESTRICTIONS_APIKEY= +// CONTEXT_BASED_RESTRICTIONS_AUTH_URL= +// CONTEXT_BASED_RESTRICTIONS_TEST_ACCOUNT_ID= +// CONTEXT_BASED_RESTRICTIONS_TEST_SERVICE_NAME= +// +// These configuration properties can be exported as environment variables, or stored +// in a configuration file and then: +// export IBM_CREDENTIALS_FILE= +// +const configFile = 'context_based_restrictions_v1.env'; + +const describe = authHelper.prepareTests(configFile); + +const originalLog = console.log; + +const consoleLogMock = jest.spyOn(console, 'log'); +const consoleWarnMock = jest.spyOn(console, 'warn'); + +describe('ContextBasedRestrictionsV1', () => { + const contextBasedRestrictionsService = ContextBasedRestrictionsV1.newInstance({}); + const config = readExternalSources(ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME); + const { + apikey: apiKey, + url: URL, + authUrl, + authType, + testAccountId: accountId, + testServiceName: serviceName, + } = config; + + expect(config).not.toBeNull(); + expect(accountId).not.toBeNull(); + expect(accountId).toBeDefined(); + expect(apiKey).not.toBeNull(); + expect(apiKey).toBeDefined(); + expect(URL).not.toBeNull(); + expect(URL).toBeDefined(); + expect(authUrl).not.toBeNull(); + expect(authUrl).toBeDefined(); + expect(authType).not.toBeNull(); + expect(authType).toBeDefined(); + expect(serviceName).not.toBeNull(); + expect(serviceName).toBeDefined(); + + let zoneId; + let zoneRev; + let ruleId; + let ruleRev; + + test('createZone request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('createZone() result:'); + + // begin-create_zone + + const addressModel = { + type: 'ipAddress', + value: '169.23.56.234', + }; + + const params = { + name: 'SDK TEST - an example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of zone', + }; + + await contextBasedRestrictionsService + .createZone(params) + .then((res) => { + zoneId = res.result.id; + zoneRev = res.headers.etag; + + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-create_zone + }); + + test('listZones request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('listZones() result:'); + + // begin-list_zones + + const params = { + accountId, + }; + + await contextBasedRestrictionsService + .listZones(params) + .then((res) => { + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-list_zones + }); + + test('getZone request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('getZone() result:'); + + // begin-get_zone + + const params = { + zoneId, + }; + + await contextBasedRestrictionsService + .getZone(params) + .then((res) => { + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-get_zone + }); + + test('replaceZone request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('replaceZone() result:'); + + // begin-replace_zone + + const addressModel = { + type: 'ipAddress', + value: '169.23.56.234', + }; + + const params = { + zoneId, + ifMatch: zoneRev, + name: 'SDK TEST - an example of updated zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of updated zone', + }; + + await contextBasedRestrictionsService + .replaceZone(params) + .then((res) => { + zoneId = res.result.id; + zoneRev = res.headers.etag; + + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-replace_zone + }); + + test('listAvailableServicerefTargets request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('listAvailableServicerefTargets() result:'); + + // begin-list_available_serviceref_targets + + await contextBasedRestrictionsService + .listAvailableServicerefTargets({}) + .then((res) => { + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-list_available_serviceref_targets + }); + + test('createRule request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('createRule() result:'); + + // begin-create_rule + + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: serviceName, + operator: 'stringEquals', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + }; + + const params = { + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of rule', + }; + + await contextBasedRestrictionsService + .createRule(params) + .then((res) => { + ruleId = res.result.id; + ruleRev = res.headers.etag; + + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-create_rule + }); + + test('listRules request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('listRules() result:'); + + // begin-list_rules + + const params = { + accountId, + }; + + await contextBasedRestrictionsService + .listRules(params) + .then((res) => { + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-list_rules + }); + + test('getRule request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('getRule() result:'); + + // begin-get_rule + + const params = { + ruleId, + }; + + await contextBasedRestrictionsService + .getRule(params) + .then((res) => { + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-get_rule + }); + + test('replaceRule request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('replaceRule() result:'); + + // begin-replace_rule + + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: serviceName, + }; + + const resourceTagAttributeModel = { + name: 'TagName', + value: 'aTagValue', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + tags: [resourceTagAttributeModel], + }; + + const params = { + ruleId, + ifMatch: ruleRev, + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of updated rule', + }; + + await contextBasedRestrictionsService + .replaceRule(params) + .then((res) => { + ruleId = res.result.id; + ruleRev = res.headers.etag; + + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-replace_rule + }); + + test('getAccountSettings request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + originalLog('getAccountSettings() result:'); + + // begin-get_account_settings + + const params = { + accountId, + }; + + await contextBasedRestrictionsService + .getAccountSettings(params) + .then((res) => { + console.log(JSON.stringify(res.result, null, 2)); + }) + .catch((err) => { + console.warn(err); + }); + + // end-get_account_settings + }); + + test('deleteRule request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + // begin-delete_rule + + const params = { + ruleId, + }; + + await contextBasedRestrictionsService + .deleteRule(params) + .then((res) => { + done(); + }) + .catch((err) => { + console.warn(err); + }); + + // end-delete_rule + }); + + test('deleteZone request example', async (done) => { + consoleLogMock.mockImplementation((output) => { + originalLog(output); + done(); + }); + consoleWarnMock.mockImplementation((output) => { + done(output); + }); + + // begin-delete_zone + + const params = { + zoneId, + }; + + await contextBasedRestrictionsService + .deleteZone(params) + .then((res) => { + done(); + }) + .catch((err) => { + console.warn(err); + }); + + // end-delete_zone + }); +}); diff --git a/scripts/typedoc/generate_typedoc.sh b/scripts/typedoc/generate_typedoc.sh index ea0b86c9..2376909c 100755 --- a/scripts/typedoc/generate_typedoc.sh +++ b/scripts/typedoc/generate_typedoc.sh @@ -6,6 +6,7 @@ ./case-management/v1.ts \ ./catalog-management/v1.ts \ ./configuration-governance/v1.ts \ + ./context-based-restrictions/v1.ts \ ./enterprise-billing-units/v1.ts \ ./enterprise-management/v1.ts \ ./enterprise-usage-reports/v1.ts \ diff --git a/test/integration/context-based-restrictions.v1.test.js b/test/integration/context-based-restrictions.v1.test.js new file mode 100644 index 00000000..8345e27c --- /dev/null +++ b/test/integration/context-based-restrictions.v1.test.js @@ -0,0 +1,832 @@ +/* eslint-disable no-console */ +/** + * (C) Copyright IBM Corp. 2021. + * + * 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. + */ + +const { readExternalSources } = require('ibm-cloud-sdk-core'); +const { v4: uuidv4 } = require('uuid'); +const ContextBasedRestrictionsV1 = require('../../dist/context-based-restrictions/v1'); + +const authHelper = require('../resources/auth-helper.js'); +// const { doesNotReject } = require('assert'); + +// testcase timeout value (200s). +const timeout = 200000; + +// Location of our config file. +const configFile = 'context_based_restrictions_v1.env'; + +const describe = authHelper.prepareTests(configFile); + +let zoneId; +let zoneEtag; +let ruleId; +let ruleEtag; +const unexistingZoneId = '648961210dab8fdffac52cc2f28e200f'; +const unexistingRuleId = '648961210dab8fdffac52cc2f28e200f'; +const invalidID = 'this_is_an_invalid_id'; + +describe('ContextBasedRestrictionsV1_integration', () => { + const contextBasedRestrictionsService = ContextBasedRestrictionsV1.newInstance({}); + + expect(contextBasedRestrictionsService).not.toBeNull(); + + const config = readExternalSources(ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME); + const { + apikey: apiKey, + url: URL, + authUrl, + authType, + testAccountId: accountId, + testServiceName: serviceName, + } = config; + + expect(config).not.toBeNull(); + expect(accountId).not.toBeNull(); + expect(accountId).toBeDefined(); + expect(apiKey).not.toBeNull(); + expect(apiKey).toBeDefined(); + expect(URL).not.toBeNull(); + expect(URL).toBeDefined(); + expect(authUrl).not.toBeNull(); + expect(authUrl).toBeDefined(); + expect(authType).not.toBeNull(); + expect(authType).toBeDefined(); + expect(serviceName).not.toBeNull(); + expect(serviceName).toBeDefined(); + + jest.setTimeout(timeout); + + contextBasedRestrictionsService.enableRetries(); + + test('createZone() - 201', async (done) => { + const addressModel = { + type: 'ipAddress', + value: '169.23.56.234', + }; + + const params = { + name: 'SDK TEST - an example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of zone', + transactionId: uuidv4(), + }; + + let res; + try { + res = await contextBasedRestrictionsService.createZone(params); + } catch (err) { + done(err); + } + + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + + zoneId = res.result.id; + zoneEtag = res.headers.etag; + + done(); + }); + + test('createZone() - 400 - Create a zone with "invalid ip address format" error', async () => { + // The zone could not be created due to an invalid ip address format. + + const addressModel = { + type: 'invalideType', + value: '169.23.56.234.', + }; + + const params = { + name: 'SDK TEST - another example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is another example of zone', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.createZone(params)).rejects.toMatchObject({ + status: 400, + }); + }); + + test('createZone() - 409 - Create a zone with "duplicated name" error', async () => { + // The zone could not be created due to an already existing zone with the same name. + + const addressModel = { + type: 'ipAddress', + value: '169.23.57.235', + }; + + const params = { + name: 'SDK TEST - an example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of zone', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.createZone(params)).rejects.toMatchObject({ + status: 409, + }); + }); + + test('listZones() - 200', async () => { + const params = { + accountId, + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.listZones(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listZones() - 400 - List zones with "invalid AccountID parameter" error', async () => { + // The zones could not be retrieved due to an invalid accountId. + + const params = { + accountId: invalidID, + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.listZones(params)).rejects.toMatchObject({ + status: 400, + }); + }); + + test('listZones() - 400 - List zones with "missing AccountID parameter" error', async () => { + // The zones could not be retrieved due to missing accountId. + + const params = { + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.listZones(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: accountId', + }); + }); + + test('getZone() - 200 - Get the specified zone', async () => { + const params = { + zoneId, + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.getZone(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('getZone() - 400 - Get zone with "missing required ZoneID parameter" error', async () => { + // The zone could not be found due to missing zone ID. + + const params = { + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.getZone(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: zoneId', + }); + }); + + test('getZone() - 404 - Get zone with "zone not found" error', async () => { + // The zone could not be found due to unexisting zone ID. + + const params = { + zoneId: unexistingZoneId, + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.getZone(params)).rejects.toMatchObject({ + status: 404, + }); + }); + + test('replaceZone() - 200 - Update the specified zone', async () => { + const addressModel = { + type: 'ipAddress', + value: '169.24.57.235', + }; + + const params = { + zoneId, + ifMatch: zoneEtag, + name: 'SDK TEST - an example of updated zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of updated zone', + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.replaceZone(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('replaceZone() - 400 - invalid type: Address', async () => { + // The zone could not be updated due to invalid type 'Address'. + + const addressModel = { + type: 'Address', + value: '169.24.57.235', + }; + + const params = { + zoneId, + ifMatch: zoneEtag, + name: 'SDK TEST - an example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of zone', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.replaceZone(params)).rejects.toMatchObject({ + status: 400, + }); + }); + + test('replaceZone() - 400 - Update zone with "Missing required parameters: ifMatch" error', async () => { + // The zone could not be updated due to missing required parameter: ifMatch'. + + const addressModel = { + type: 'ipAddress', + value: '169.24.57.235', + }; + + const params = { + zoneId, + name: 'SDK TEST - an example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of zone', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.replaceZone(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: ifMatch', + }); + }); + + test('replaceZone() - 404 - Update zone with "zone not found" error', async () => { + // The zone could not be updated due to zone is not found. + + const addressModel = { + type: 'ipAddress', + value: '169.24.57.235', + }; + + const params = { + zoneId: unexistingZoneId, + ifMatch: zoneEtag, + name: 'SDK TEST - an example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of zone', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.replaceZone(params)).rejects.toMatchObject({ + status: 404, + }); + }); + + test('replaceZone() - 412 - Update zone with "invalid IfMath parameter" error', async () => { + // The zone could not be updated due to invalid IfMath parameter. + + const addressModel = { + type: 'ipAddress', + value: '169.24.57.235', + }; + + const params = { + zoneId, + ifMatch: 'abc', + name: 'SDK TEST - an example of zone', + accountId, + addresses: [addressModel], + description: 'SDK TEST - this is an example of zone', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.replaceZone(params)).rejects.toMatchObject({ + status: 412, + }); + }); + + test('listAvailableServicerefTargets() - 200 - List available service reference targets', async () => { + const params = { + type: 'all', + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.listAvailableServicerefTargets(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listAvailableServicerefTargets() - 400 - List available service reference targets with "invalid type parameter" error', async () => { + // type value is not supported + const params = { + type: 'invalid-type', + transactionId: uuidv4(), + }; + + await expect( + contextBasedRestrictionsService.listAvailableServicerefTargets(params) + ).rejects.toMatchObject({ + status: 400, + }); + }); + + test('createRule() - 201 - Create a rule', async (done) => { + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + operator: 'stringEquals', + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: serviceName, + operator: 'stringEquals', + }; + + const resourceTagAttributeModel = { + name: 'aTagName', + value: 'aTagValue', + operator: 'stringEquals', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + tags: [resourceTagAttributeModel], + }; + + const params = { + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of rule', + transactionId: uuidv4(), + }; + + let res; + try { + res = await contextBasedRestrictionsService.createRule(params); + } catch (err) { + done(err); + } + + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + + ruleId = res.result.id; + ruleEtag = res.headers.etag; + + done(); + }); + + test('createRule() - 400 - Create a rule with "service not cbr enabled" error', async () => { + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + operator: 'stringEquals', + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: 'cbr-not-enabled', + operator: 'stringEquals', + }; + + const resourceTagAttributeModel = { + name: 'aTagName', + value: 'aTagValue', + operator: 'stringEquals', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + tags: [resourceTagAttributeModel], + }; + + const params = { + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of rule', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.createRule(params)).rejects.toMatchObject({ + status: 400, + }); + }); + + test('listRules() - 200 - List rules', async () => { + const params = { + accountId, + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.listRules(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listRules() - 400 - List rules with "invalid AccountID parameter" error', async () => { + // The rules could not be retrieved due to invalid accountId. + + const params = { + accountId: invalidID, + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.listRules(params)).rejects.toMatchObject({ + status: 400, + }); + }); + + test('listRules() - 400 - List rules with "missing required AccountID parameter" error', async () => { + // The rules could not be retrieved due to missing accountId. + + const params = { + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.listRules(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: accountId', + }); + }); + + test('getRule() - 200 - Get the specified rule', async () => { + const params = { + ruleId, + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.getRule(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('getRule() - 404 - Get rule with "rule not found" error', async () => { + // The rule could not be found due to unexisting rule ID . + + const params = { + ruleId: unexistingRuleId, + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.getRule(params)).rejects.toMatchObject({ + status: 404, + }); + }); + + test('getRule() - 400 - Get rule with "Missing required parameters: ruleId" error', async () => { + // The rule could not be found due to missing ruleId . + + const params = { + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.getRule(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: ruleId', + }); + }); + + test('replaceRule() - 200 - Update the specified rule', async () => { + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + operator: 'stringEquals', + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: serviceName, + operator: 'stringEquals', + }; + + const resourceTagAttributeModel = { + name: 'TagName-2', + value: 'aTagValue-2', + operator: 'stringEquals', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + tags: [resourceTagAttributeModel], + }; + + const params = { + ruleId, + ifMatch: ruleEtag, + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of updated rule', + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.replaceRule(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('replaceRule() - 400 - Update rule with "Missing required parameters: ifMatch" error', async () => { + // The rule could not be found due to missing ifMatch. + + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + operator: 'stringEquals', + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: serviceName, + operator: 'stringEquals', + }; + + const resourceTagAttributeModel = { + name: 'TagName-2', + value: 'aTagValue-2', + operator: 'stringEquals', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + tags: [resourceTagAttributeModel], + }; + + const params = { + ruleId: unexistingRuleId, + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of rule', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.replaceRule(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: ifMatch', + }); + }); + + test('replaceRule() - 404 - Update rule with "rule not found" error', async () => { + // The rule could not be found due to unexisting rule ID. + + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + operator: 'stringEquals', + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: serviceName, + operator: 'stringEquals', + }; + + const resourceTagAttributeModel = { + name: 'TagName-2', + value: 'aTagValue-2', + operator: 'stringEquals', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + tags: [resourceTagAttributeModel], + }; + + const params = { + ruleId: unexistingRuleId, + ifMatch: ruleEtag, + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of rule', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.replaceRule(params)).rejects.toMatchObject({ + status: 404, + }); + }); + + test('replaceRule() - 412 - unsupported attribute name: networkZoneID', async () => { + // The rule could not be updated due to unsupported attribute name 'networkZoneID'. + + const ruleContextAttributeModel = { + name: 'networkZoneID', + value: zoneId, + }; + + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + const resourceAttributeAccountIdModel = { + name: 'accountId', + value: accountId, + operator: 'stringEquals', + }; + + const resourceAttributeServiceNameModel = { + name: 'serviceName', + value: serviceName, + operator: 'stringEquals', + }; + + const resourceTagAttributeModel = { + name: 'TagName-2', + value: 'aTagValue-2', + operator: 'stringEquals', + }; + + const resourceModel = { + attributes: [resourceAttributeAccountIdModel, resourceAttributeServiceNameModel], + tags: [resourceTagAttributeModel], + }; + + const params = { + ruleId, + ifMatch: ruleEtag, + contexts: [ruleContextModel], + resources: [resourceModel], + description: 'SDK TEST - this is an example of rule', + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.replaceRule(params)).rejects.toMatchObject({ + status: 412, + }); + }); + + test('getAccountSettings() - 200 - Get the specified account settings', async () => { + const params = { + accountId, + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.getAccountSettings(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('getAccountSettings() - 400 - Get account settings with "Missing required parameters: accountId" error', async () => { + const params = { + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.getAccountSettings(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: accountId', + }); + }); + + test('getAccountSettings() - 400 - Get account settings with "invalid AccountID parameter" error', async () => { + const params = { + accountId: invalidID, + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.getAccountSettings(params)).rejects.toMatchObject({ + 'message': 'The parameter "account_id" in path has an error.', + }); + }); + + test('deleteRule() - 400 - Delete rule with "Missing required parameters: ruleId" error', async () => { + // The rule could not be deleted due to unexisting ruleId. + const params = { + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.deleteRule(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: ruleId', + }); + }); + + test('deleteRule() - 404 - Delete rule with "rule not found" error', async () => { + // The rule could not be deleted due to unexisting rule ID. + const params = { + ruleId: unexistingRuleId, + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.deleteRule(params)).rejects.toMatchObject({ + status: 404, + }); + }); + + test('deleteRule() - 204 - Delete the specified zone', async () => { + const params = { + ruleId, + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.deleteRule(params); + expect(res).toBeDefined(); + expect(res.status).toBe(204); + expect(res.result).toBeDefined(); + }); + + test('deleteZone() - 404 - Delete zone with "zone not found" error', async () => { + // The zone could not be deleted due to unexisting zone ID. + const params = { + zoneId: unexistingZoneId, + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.deleteZone(params)).rejects.toMatchObject({ + status: 404, + }); + }); + + test('deleteZone() - 404 - Delete zone with "Missing required parameters: zoneId" error', async () => { + // The zone could not be deleted due to missing zone ID. + const params = { + transactionId: uuidv4(), + }; + + await expect(contextBasedRestrictionsService.deleteZone(params)).rejects.toMatchObject({ + 'message': 'Missing required parameters: zoneId', + }); + }); + + test('deleteZone() - 204 - Delete the specified zone', async () => { + const params = { + zoneId, + transactionId: uuidv4(), + }; + + const res = await contextBasedRestrictionsService.deleteZone(params); + expect(res).toBeDefined(); + expect(res.status).toBe(204); + expect(res.result).toBeDefined(); + }); +}); diff --git a/test/unit/context-based-restrictions.v1.test.js b/test/unit/context-based-restrictions.v1.test.js new file mode 100644 index 00000000..bcddb719 --- /dev/null +++ b/test/unit/context-based-restrictions.v1.test.js @@ -0,0 +1,1236 @@ +/** + * (C) Copyright IBM Corp. 2021. + * + * 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. + */ + +// need to import the whole package to mock getAuthenticatorFromEnvironment +const core = require('ibm-cloud-sdk-core'); + +const { NoAuthAuthenticator, unitTestUtils } = core; + +const ContextBasedRestrictionsV1 = require('../../dist/context-based-restrictions/v1'); + +const { + getOptions, + checkUrlAndMethod, + checkMediaHeaders, + expectToBePromise, + checkUserHeader, + checkForSuccessfulExecution, +} = unitTestUtils; + +const contextBasedRestrictionsServiceOptions = { + authenticator: new NoAuthAuthenticator(), + url: 'https://cbr.cloud.ibm.com', +}; + +const contextBasedRestrictionsService = new ContextBasedRestrictionsV1(contextBasedRestrictionsServiceOptions); + +// dont actually create a request +const createRequestMock = jest.spyOn(contextBasedRestrictionsService, 'createRequest'); +createRequestMock.mockImplementation(() => Promise.resolve()); + +// dont actually construct an authenticator +const getAuthenticatorMock = jest.spyOn(core, 'getAuthenticatorFromEnvironment'); +getAuthenticatorMock.mockImplementation(() => new NoAuthAuthenticator()); + +afterEach(() => { + createRequestMock.mockClear(); + getAuthenticatorMock.mockClear(); +}); + +describe('ContextBasedRestrictionsV1', () => { + describe('the newInstance method', () => { + test('should use defaults when options not provided', () => { + const testInstance = ContextBasedRestrictionsV1.newInstance(); + + expect(getAuthenticatorMock).toHaveBeenCalled(); + expect(testInstance.baseOptions.authenticator).toBeInstanceOf(NoAuthAuthenticator); + expect(testInstance.baseOptions.serviceName).toBe(ContextBasedRestrictionsV1.DEFAULT_SERVICE_NAME); + expect(testInstance.baseOptions.serviceUrl).toBe(ContextBasedRestrictionsV1.DEFAULT_SERVICE_URL); + expect(testInstance).toBeInstanceOf(ContextBasedRestrictionsV1); + }); + + test('should set serviceName, serviceUrl, and authenticator when provided', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + serviceUrl: 'custom.com', + serviceName: 'my-service', + }; + + const testInstance = ContextBasedRestrictionsV1.newInstance(options); + + expect(getAuthenticatorMock).not.toHaveBeenCalled(); + expect(testInstance.baseOptions.authenticator).toBeInstanceOf(NoAuthAuthenticator); + expect(testInstance.baseOptions.serviceUrl).toBe('custom.com'); + expect(testInstance.baseOptions.serviceName).toBe('my-service'); + expect(testInstance).toBeInstanceOf(ContextBasedRestrictionsV1); + }); + }); + describe('the constructor', () => { + test('use user-given service url', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + serviceUrl: 'custom.com', + }; + + const testInstance = new ContextBasedRestrictionsV1(options); + + expect(testInstance.baseOptions.serviceUrl).toBe('custom.com'); + }); + + test('use default service url', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + }; + + const testInstance = new ContextBasedRestrictionsV1(options); + + expect(testInstance.baseOptions.serviceUrl).toBe(ContextBasedRestrictionsV1.DEFAULT_SERVICE_URL); + }); + }); + describe('createZone', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // AddressIPAddress + const addressModel = { + type: 'ipAddress', + value: '169.23.56.234', + }; + + function __createZoneTest() { + // Construct the params object for operation createZone + const name = 'an example of zone'; + const accountId = '12ab34cd56ef78ab90cd12ef34ab56cd'; + const addresses = [addressModel]; + const description = 'this is an example of zone'; + const excluded = [addressModel]; + const transactionId = 'testString'; + const params = { + name: name, + accountId: accountId, + addresses: addresses, + description: description, + excluded: excluded, + transactionId: transactionId, + }; + + const createZoneResult = contextBasedRestrictionsService.createZone(params); + + // all methods should return a Promise + expectToBePromise(createZoneResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/zones', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.account_id).toEqual(accountId); + expect(mockRequestOptions.body.addresses).toEqual(addresses); + expect(mockRequestOptions.body.description).toEqual(description); + expect(mockRequestOptions.body.excluded).toEqual(excluded); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createZoneTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __createZoneTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __createZoneTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.createZone(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + + test('should not have any problems when no parameters are passed in', () => { + // invoke the method with no parameters + contextBasedRestrictionsService.createZone({}); + checkForSuccessfulExecution(createRequestMock); + }); + }); + }); + describe('listZones', () => { + describe('positive tests', () => { + function __listZonesTest() { + // Construct the params object for operation listZones + const accountId = 'testString'; + const transactionId = 'testString'; + const name = 'testString'; + const sort = 'testString'; + const params = { + accountId: accountId, + transactionId: transactionId, + name: name, + sort: sort, + }; + + const listZonesResult = contextBasedRestrictionsService.listZones(params); + + // all methods should return a Promise + expectToBePromise(listZonesResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/zones', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.qs.name).toEqual(name); + expect(mockRequestOptions.qs.sort).toEqual(sort); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listZonesTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __listZonesTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __listZonesTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + accountId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.listZones(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.listZones({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const listZonesPromise = contextBasedRestrictionsService.listZones(); + expectToBePromise(listZonesPromise); + + listZonesPromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('getZone', () => { + describe('positive tests', () => { + function __getZoneTest() { + // Construct the params object for operation getZone + const zoneId = 'testString'; + const transactionId = 'testString'; + const params = { + zoneId: zoneId, + transactionId: transactionId, + }; + + const getZoneResult = contextBasedRestrictionsService.getZone(params); + + // all methods should return a Promise + expectToBePromise(getZoneResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/zones/{zone_id}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.path.zone_id).toEqual(zoneId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getZoneTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __getZoneTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __getZoneTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const zoneId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + zoneId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.getZone(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.getZone({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const getZonePromise = contextBasedRestrictionsService.getZone(); + expectToBePromise(getZonePromise); + + getZonePromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('replaceZone', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // AddressIPAddress + const addressModel = { + type: 'ipAddress', + value: '169.23.56.234', + }; + + function __replaceZoneTest() { + // Construct the params object for operation replaceZone + const zoneId = 'testString'; + const ifMatch = 'testString'; + const name = 'an example of zone'; + const accountId = '12ab34cd56ef78ab90cd12ef34ab56cd'; + const addresses = [addressModel]; + const description = 'this is an example of zone'; + const excluded = [addressModel]; + const transactionId = 'testString'; + const params = { + zoneId: zoneId, + ifMatch: ifMatch, + name: name, + accountId: accountId, + addresses: addresses, + description: description, + excluded: excluded, + transactionId: transactionId, + }; + + const replaceZoneResult = contextBasedRestrictionsService.replaceZone(params); + + // all methods should return a Promise + expectToBePromise(replaceZoneResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/zones/{zone_id}', 'PUT'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.account_id).toEqual(accountId); + expect(mockRequestOptions.body.addresses).toEqual(addresses); + expect(mockRequestOptions.body.description).toEqual(description); + expect(mockRequestOptions.body.excluded).toEqual(excluded); + expect(mockRequestOptions.path.zone_id).toEqual(zoneId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __replaceZoneTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __replaceZoneTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __replaceZoneTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const zoneId = 'testString'; + const ifMatch = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + zoneId, + ifMatch, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.replaceZone(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.replaceZone({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const replaceZonePromise = contextBasedRestrictionsService.replaceZone(); + expectToBePromise(replaceZonePromise); + + replaceZonePromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('deleteZone', () => { + describe('positive tests', () => { + function __deleteZoneTest() { + // Construct the params object for operation deleteZone + const zoneId = 'testString'; + const transactionId = 'testString'; + const params = { + zoneId: zoneId, + transactionId: transactionId, + }; + + const deleteZoneResult = contextBasedRestrictionsService.deleteZone(params); + + // all methods should return a Promise + expectToBePromise(deleteZoneResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/zones/{zone_id}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.path.zone_id).toEqual(zoneId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteZoneTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __deleteZoneTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __deleteZoneTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const zoneId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + zoneId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.deleteZone(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.deleteZone({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const deleteZonePromise = contextBasedRestrictionsService.deleteZone(); + expectToBePromise(deleteZonePromise); + + deleteZonePromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('listAvailableServicerefTargets', () => { + describe('positive tests', () => { + function __listAvailableServicerefTargetsTest() { + // Construct the params object for operation listAvailableServicerefTargets + const type = 'all'; + const params = { + type: type, + }; + + const listAvailableServicerefTargetsResult = contextBasedRestrictionsService.listAvailableServicerefTargets(params); + + // all methods should return a Promise + expectToBePromise(listAvailableServicerefTargetsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/zones/serviceref_targets', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.type).toEqual(type); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listAvailableServicerefTargetsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __listAvailableServicerefTargetsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __listAvailableServicerefTargetsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.listAvailableServicerefTargets(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + + test('should not have any problems when no parameters are passed in', () => { + // invoke the method with no parameters + contextBasedRestrictionsService.listAvailableServicerefTargets({}); + checkForSuccessfulExecution(createRequestMock); + }); + }); + }); + describe('createRule', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // RuleContextAttribute + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: '65810ac762004f22ac19f8f8edf70a34', + }; + + // RuleContext + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + // ResourceAttribute + const resourceAttributeModel = { + name: 'accountId', + value: '12ab34cd56ef78ab90cd12ef34ab56cd', + operator: 'testString', + }; + + // ResourceTagAttribute + const resourceTagAttributeModel = { + name: 'testString', + value: 'testString', + operator: 'testString', + }; + + // Resource + const resourceModel = { + attributes: [resourceAttributeModel], + tags: [resourceTagAttributeModel], + }; + + function __createRuleTest() { + // Construct the params object for operation createRule + const contexts = [ruleContextModel]; + const resources = [resourceModel]; + const description = 'this is an example of rule'; + const transactionId = 'testString'; + const params = { + contexts: contexts, + resources: resources, + description: description, + transactionId: transactionId, + }; + + const createRuleResult = contextBasedRestrictionsService.createRule(params); + + // all methods should return a Promise + expectToBePromise(createRuleResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/rules', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.body.contexts).toEqual(contexts); + expect(mockRequestOptions.body.resources).toEqual(resources); + expect(mockRequestOptions.body.description).toEqual(description); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createRuleTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __createRuleTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __createRuleTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.createRule(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + + test('should not have any problems when no parameters are passed in', () => { + // invoke the method with no parameters + contextBasedRestrictionsService.createRule({}); + checkForSuccessfulExecution(createRequestMock); + }); + }); + }); + describe('listRules', () => { + describe('positive tests', () => { + function __listRulesTest() { + // Construct the params object for operation listRules + const accountId = 'testString'; + const transactionId = 'testString'; + const region = 'testString'; + const resource = 'testString'; + const resourceType = 'testString'; + const serviceInstance = 'testString'; + const serviceName = 'testString'; + const serviceType = 'testString'; + const zoneId = 'testString'; + const sort = 'testString'; + const params = { + accountId: accountId, + transactionId: transactionId, + region: region, + resource: resource, + resourceType: resourceType, + serviceInstance: serviceInstance, + serviceName: serviceName, + serviceType: serviceType, + zoneId: zoneId, + sort: sort, + }; + + const listRulesResult = contextBasedRestrictionsService.listRules(params); + + // all methods should return a Promise + expectToBePromise(listRulesResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/rules', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.qs.region).toEqual(region); + expect(mockRequestOptions.qs.resource).toEqual(resource); + expect(mockRequestOptions.qs.resource_type).toEqual(resourceType); + expect(mockRequestOptions.qs.service_instance).toEqual(serviceInstance); + expect(mockRequestOptions.qs.service_name).toEqual(serviceName); + expect(mockRequestOptions.qs.service_type).toEqual(serviceType); + expect(mockRequestOptions.qs.zone_id).toEqual(zoneId); + expect(mockRequestOptions.qs.sort).toEqual(sort); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listRulesTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __listRulesTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __listRulesTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + accountId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.listRules(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.listRules({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const listRulesPromise = contextBasedRestrictionsService.listRules(); + expectToBePromise(listRulesPromise); + + listRulesPromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('getRule', () => { + describe('positive tests', () => { + function __getRuleTest() { + // Construct the params object for operation getRule + const ruleId = 'testString'; + const transactionId = 'testString'; + const params = { + ruleId: ruleId, + transactionId: transactionId, + }; + + const getRuleResult = contextBasedRestrictionsService.getRule(params); + + // all methods should return a Promise + expectToBePromise(getRuleResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/rules/{rule_id}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.path.rule_id).toEqual(ruleId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getRuleTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __getRuleTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __getRuleTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const ruleId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + ruleId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.getRule(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.getRule({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const getRulePromise = contextBasedRestrictionsService.getRule(); + expectToBePromise(getRulePromise); + + getRulePromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('replaceRule', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // RuleContextAttribute + const ruleContextAttributeModel = { + name: 'networkZoneId', + value: '76921bd873115033bd2a0909fe081b45', + }; + + // RuleContext + const ruleContextModel = { + attributes: [ruleContextAttributeModel], + }; + + // ResourceAttribute + const resourceAttributeModel = { + name: 'accountId', + value: '12ab34cd56ef78ab90cd12ef34ab56cd', + operator: 'testString', + }; + + // ResourceTagAttribute + const resourceTagAttributeModel = { + name: 'testString', + value: 'testString', + operator: 'testString', + }; + + // Resource + const resourceModel = { + attributes: [resourceAttributeModel], + tags: [resourceTagAttributeModel], + }; + + function __replaceRuleTest() { + // Construct the params object for operation replaceRule + const ruleId = 'testString'; + const ifMatch = 'testString'; + const contexts = [ruleContextModel]; + const resources = [resourceModel]; + const description = 'this is an example of rule'; + const transactionId = 'testString'; + const params = { + ruleId: ruleId, + ifMatch: ifMatch, + contexts: contexts, + resources: resources, + description: description, + transactionId: transactionId, + }; + + const replaceRuleResult = contextBasedRestrictionsService.replaceRule(params); + + // all methods should return a Promise + expectToBePromise(replaceRuleResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/rules/{rule_id}', 'PUT'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.body.contexts).toEqual(contexts); + expect(mockRequestOptions.body.resources).toEqual(resources); + expect(mockRequestOptions.body.description).toEqual(description); + expect(mockRequestOptions.path.rule_id).toEqual(ruleId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __replaceRuleTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __replaceRuleTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __replaceRuleTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const ruleId = 'testString'; + const ifMatch = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + ruleId, + ifMatch, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.replaceRule(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.replaceRule({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const replaceRulePromise = contextBasedRestrictionsService.replaceRule(); + expectToBePromise(replaceRulePromise); + + replaceRulePromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('deleteRule', () => { + describe('positive tests', () => { + function __deleteRuleTest() { + // Construct the params object for operation deleteRule + const ruleId = 'testString'; + const transactionId = 'testString'; + const params = { + ruleId: ruleId, + transactionId: transactionId, + }; + + const deleteRuleResult = contextBasedRestrictionsService.deleteRule(params); + + // all methods should return a Promise + expectToBePromise(deleteRuleResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/rules/{rule_id}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.path.rule_id).toEqual(ruleId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteRuleTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __deleteRuleTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __deleteRuleTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const ruleId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + ruleId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.deleteRule(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.deleteRule({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const deleteRulePromise = contextBasedRestrictionsService.deleteRule(); + expectToBePromise(deleteRulePromise); + + deleteRulePromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); + describe('getAccountSettings', () => { + describe('positive tests', () => { + function __getAccountSettingsTest() { + // Construct the params object for operation getAccountSettings + const accountId = 'testString'; + const transactionId = 'testString'; + const params = { + accountId: accountId, + transactionId: transactionId, + }; + + const getAccountSettingsResult = contextBasedRestrictionsService.getAccountSettings(params); + + // all methods should return a Promise + expectToBePromise(getAccountSettingsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v1/account_settings/{account_id}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Transaction-Id', transactionId); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getAccountSettingsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.enableRetries(); + __getAccountSettingsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + contextBasedRestrictionsService.disableRetries(); + __getAccountSettingsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const params = { + accountId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + contextBasedRestrictionsService.getAccountSettings(params); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async (done) => { + let err; + try { + await contextBasedRestrictionsService.getAccountSettings({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + + test('should reject promise when required params are not given', (done) => { + const getAccountSettingsPromise = contextBasedRestrictionsService.getAccountSettings(); + expectToBePromise(getAccountSettingsPromise); + + getAccountSettingsPromise.catch((err) => { + expect(err.message).toMatch(/Missing required parameters/); + done(); + }); + }); + }); + }); +});