From 412980eb96afb6d5866a931f5717624048ba0cff Mon Sep 17 00:00:00 2001 From: Jonathan Date-chong Date: Wed, 23 Nov 2022 11:48:10 -0800 Subject: [PATCH 1/2] fix: rename Account_Summary billing_month property Signed-off-by: Jonathan Date-chong --- test/unit/usage-reports.v4.test.js | 744 +++++++++++++++++++++-------- usage-reports/v4.ts | 365 ++++++++++++-- 2 files changed, 857 insertions(+), 252 deletions(-) diff --git a/test/unit/usage-reports.v4.test.js b/test/unit/usage-reports.v4.test.js index 53338f5a..907ceecc 100644 --- a/test/unit/usage-reports.v4.test.js +++ b/test/unit/usage-reports.v4.test.js @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2021. + * (C) Copyright IBM Corp. 2022. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; // need to import the whole package to mock getAuthenticatorFromEnvironment const core = require('ibm-cloud-sdk-core'); + const { NoAuthAuthenticator, unitTestUtils } = core; const UsageReportsV4 = require('../../dist/usage-reports/v4'); +const nock = require('nock'); + +/* eslint-disable no-await-in-loop */ const { getOptions, @@ -36,20 +39,37 @@ const usageReportsServiceOptions = { const usageReportsService = new UsageReportsV4(usageReportsServiceOptions); -// dont actually create a request -const createRequestMock = jest.spyOn(usageReportsService, 'createRequest'); -createRequestMock.mockImplementation(() => Promise.resolve()); +let createRequestMock = null; +function mock_createRequest() { + if (!createRequestMock) { + createRequestMock = jest.spyOn(usageReportsService, 'createRequest'); + createRequestMock.mockImplementation(() => Promise.resolve()); + } +} +function unmock_createRequest() { + if (createRequestMock) { + createRequestMock.mockRestore(); + createRequestMock = null; + } +} // dont actually construct an authenticator const getAuthenticatorMock = jest.spyOn(core, 'getAuthenticatorFromEnvironment'); getAuthenticatorMock.mockImplementation(() => new NoAuthAuthenticator()); -afterEach(() => { - createRequestMock.mockClear(); - getAuthenticatorMock.mockClear(); -}); - describe('UsageReportsV4', () => { + + beforeEach(() => { + mock_createRequest(); + }); + + afterEach(() => { + if (createRequestMock) { + createRequestMock.mockClear(); + } + getAuthenticatorMock.mockClear(); + }); + describe('the newInstance method', () => { test('should use defaults when options not provided', () => { const testInstance = UsageReportsV4.newInstance(); @@ -77,6 +97,7 @@ describe('UsageReportsV4', () => { expect(testInstance).toBeInstanceOf(UsageReportsV4); }); }); + describe('the constructor', () => { test('use user-given service url', () => { const options = { @@ -99,18 +120,19 @@ describe('UsageReportsV4', () => { expect(testInstance.baseOptions.serviceUrl).toBe(UsageReportsV4.DEFAULT_SERVICE_URL); }); }); + describe('getAccountSummary', () => { describe('positive tests', () => { - test('should pass the right params to createRequest', () => { + function __getAccountSummaryTest() { // Construct the params object for operation getAccountSummary const accountId = 'testString'; const billingmonth = 'testString'; - const params = { - accountId: accountId, - billingmonth: billingmonth, + const getAccountSummaryParams = { + accountId, + billingmonth, }; - const getAccountSummaryResult = usageReportsService.getAccountSummary(params); + const getAccountSummaryResult = usageReportsService.getAccountSummary(getAccountSummaryParams); // all methods should return a Promise expectToBePromise(getAccountSummaryResult); @@ -118,14 +140,29 @@ describe('UsageReportsV4', () => { // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); - const options = getOptions(createRequestMock); + const mockRequestOptions = getOptions(createRequestMock); - checkUrlAndMethod(options, '/v4/accounts/{account_id}/summary/{billingmonth}', 'GET'); + checkUrlAndMethod(mockRequestOptions, '/v4/accounts/{account_id}/summary/{billingmonth}', 'GET'); const expectedAccept = 'application/json'; const expectedContentType = undefined; checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); - expect(options.path['account_id']).toEqual(accountId); - expect(options.path['billingmonth']).toEqual(billingmonth); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.billingmonth).toEqual(billingmonth); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getAccountSummaryTest(); + + // enable retries and test again + createRequestMock.mockClear(); + usageReportsService.enableRetries(); + __getAccountSummaryTest(); + + // disable retries and test again + createRequestMock.mockClear(); + usageReportsService.disableRetries(); + __getAccountSummaryTest(); }); test('should prioritize user-given headers', () => { @@ -134,7 +171,7 @@ describe('UsageReportsV4', () => { const billingmonth = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const params = { + const getAccountSummaryParams = { accountId, billingmonth, headers: { @@ -143,7 +180,7 @@ describe('UsageReportsV4', () => { }, }; - usageReportsService.getAccountSummary(params); + usageReportsService.getAccountSummary(getAccountSummaryParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -160,33 +197,35 @@ describe('UsageReportsV4', () => { expect(err.message).toMatch(/Missing required parameters/); }); - test('should reject promise when required params are not given', done => { - const getAccountSummaryPromise = usageReportsService.getAccountSummary(); - expectToBePromise(getAccountSummaryPromise); + test('should reject promise when required params are not given', async () => { + let err; + try { + await usageReportsService.getAccountSummary(); + } catch (e) { + err = e; + } - getAccountSummaryPromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); + expect(err.message).toMatch(/Missing required parameters/); }); }); }); + describe('getAccountUsage', () => { describe('positive tests', () => { - test('should pass the right params to createRequest', () => { + function __getAccountUsageTest() { // Construct the params object for operation getAccountUsage const accountId = 'testString'; const billingmonth = 'testString'; const names = true; const acceptLanguage = 'testString'; - const params = { - accountId: accountId, - billingmonth: billingmonth, - names: names, - acceptLanguage: acceptLanguage, + const getAccountUsageParams = { + accountId, + billingmonth, + names, + acceptLanguage, }; - const getAccountUsageResult = usageReportsService.getAccountUsage(params); + const getAccountUsageResult = usageReportsService.getAccountUsage(getAccountUsageParams); // all methods should return a Promise expectToBePromise(getAccountUsageResult); @@ -194,16 +233,31 @@ describe('UsageReportsV4', () => { // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); - const options = getOptions(createRequestMock); + const mockRequestOptions = getOptions(createRequestMock); - checkUrlAndMethod(options, '/v4/accounts/{account_id}/usage/{billingmonth}', 'GET'); + checkUrlAndMethod(mockRequestOptions, '/v4/accounts/{account_id}/usage/{billingmonth}', 'GET'); const expectedAccept = 'application/json'; const expectedContentType = undefined; checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); - expect(options.qs['_names']).toEqual(names); - expect(options.path['account_id']).toEqual(accountId); - expect(options.path['billingmonth']).toEqual(billingmonth); + expect(mockRequestOptions.qs._names).toEqual(names); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.billingmonth).toEqual(billingmonth); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getAccountUsageTest(); + + // enable retries and test again + createRequestMock.mockClear(); + usageReportsService.enableRetries(); + __getAccountUsageTest(); + + // disable retries and test again + createRequestMock.mockClear(); + usageReportsService.disableRetries(); + __getAccountUsageTest(); }); test('should prioritize user-given headers', () => { @@ -212,7 +266,7 @@ describe('UsageReportsV4', () => { const billingmonth = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const params = { + const getAccountUsageParams = { accountId, billingmonth, headers: { @@ -221,7 +275,7 @@ describe('UsageReportsV4', () => { }, }; - usageReportsService.getAccountUsage(params); + usageReportsService.getAccountUsage(getAccountUsageParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -238,35 +292,37 @@ describe('UsageReportsV4', () => { expect(err.message).toMatch(/Missing required parameters/); }); - test('should reject promise when required params are not given', done => { - const getAccountUsagePromise = usageReportsService.getAccountUsage(); - expectToBePromise(getAccountUsagePromise); + test('should reject promise when required params are not given', async () => { + let err; + try { + await usageReportsService.getAccountUsage(); + } catch (e) { + err = e; + } - getAccountUsagePromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); + expect(err.message).toMatch(/Missing required parameters/); }); }); }); + describe('getResourceGroupUsage', () => { describe('positive tests', () => { - test('should pass the right params to createRequest', () => { + function __getResourceGroupUsageTest() { // Construct the params object for operation getResourceGroupUsage const accountId = 'testString'; const resourceGroupId = 'testString'; const billingmonth = 'testString'; const names = true; const acceptLanguage = 'testString'; - const params = { - accountId: accountId, - resourceGroupId: resourceGroupId, - billingmonth: billingmonth, - names: names, - acceptLanguage: acceptLanguage, + const getResourceGroupUsageParams = { + accountId, + resourceGroupId, + billingmonth, + names, + acceptLanguage, }; - const getResourceGroupUsageResult = usageReportsService.getResourceGroupUsage(params); + const getResourceGroupUsageResult = usageReportsService.getResourceGroupUsage(getResourceGroupUsageParams); // all methods should return a Promise expectToBePromise(getResourceGroupUsageResult); @@ -274,17 +330,32 @@ describe('UsageReportsV4', () => { // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); - const options = getOptions(createRequestMock); + const mockRequestOptions = getOptions(createRequestMock); - checkUrlAndMethod(options, '/v4/accounts/{account_id}/resource_groups/{resource_group_id}/usage/{billingmonth}', 'GET'); + checkUrlAndMethod(mockRequestOptions, '/v4/accounts/{account_id}/resource_groups/{resource_group_id}/usage/{billingmonth}', 'GET'); const expectedAccept = 'application/json'; const expectedContentType = undefined; checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); - expect(options.qs['_names']).toEqual(names); - expect(options.path['account_id']).toEqual(accountId); - expect(options.path['resource_group_id']).toEqual(resourceGroupId); - expect(options.path['billingmonth']).toEqual(billingmonth); + expect(mockRequestOptions.qs._names).toEqual(names); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.resource_group_id).toEqual(resourceGroupId); + expect(mockRequestOptions.path.billingmonth).toEqual(billingmonth); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getResourceGroupUsageTest(); + + // enable retries and test again + createRequestMock.mockClear(); + usageReportsService.enableRetries(); + __getResourceGroupUsageTest(); + + // disable retries and test again + createRequestMock.mockClear(); + usageReportsService.disableRetries(); + __getResourceGroupUsageTest(); }); test('should prioritize user-given headers', () => { @@ -294,7 +365,7 @@ describe('UsageReportsV4', () => { const billingmonth = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const params = { + const getResourceGroupUsageParams = { accountId, resourceGroupId, billingmonth, @@ -304,7 +375,7 @@ describe('UsageReportsV4', () => { }, }; - usageReportsService.getResourceGroupUsage(params); + usageReportsService.getResourceGroupUsage(getResourceGroupUsageParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -321,20 +392,22 @@ describe('UsageReportsV4', () => { expect(err.message).toMatch(/Missing required parameters/); }); - test('should reject promise when required params are not given', done => { - const getResourceGroupUsagePromise = usageReportsService.getResourceGroupUsage(); - expectToBePromise(getResourceGroupUsagePromise); + test('should reject promise when required params are not given', async () => { + let err; + try { + await usageReportsService.getResourceGroupUsage(); + } catch (e) { + err = e; + } - getResourceGroupUsagePromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); + expect(err.message).toMatch(/Missing required parameters/); }); }); }); + describe('getResourceUsageAccount', () => { describe('positive tests', () => { - test('should pass the right params to createRequest', () => { + function __getResourceUsageAccountTest() { // Construct the params object for operation getResourceUsageAccount const accountId = 'testString'; const billingmonth = 'testString'; @@ -348,22 +421,22 @@ describe('UsageReportsV4', () => { const resourceId = 'testString'; const planId = 'testString'; const region = 'testString'; - const params = { - accountId: accountId, - billingmonth: billingmonth, - names: names, - acceptLanguage: acceptLanguage, - limit: limit, - start: start, - resourceGroupId: resourceGroupId, - organizationId: organizationId, - resourceInstanceId: resourceInstanceId, - resourceId: resourceId, - planId: planId, - region: region, + const getResourceUsageAccountParams = { + accountId, + billingmonth, + names, + acceptLanguage, + limit, + start, + resourceGroupId, + organizationId, + resourceInstanceId, + resourceId, + planId, + region, }; - const getResourceUsageAccountResult = usageReportsService.getResourceUsageAccount(params); + const getResourceUsageAccountResult = usageReportsService.getResourceUsageAccount(getResourceUsageAccountParams); // all methods should return a Promise expectToBePromise(getResourceUsageAccountResult); @@ -371,24 +444,39 @@ describe('UsageReportsV4', () => { // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); - const options = getOptions(createRequestMock); + const mockRequestOptions = getOptions(createRequestMock); - checkUrlAndMethod(options, '/v4/accounts/{account_id}/resource_instances/usage/{billingmonth}', 'GET'); + checkUrlAndMethod(mockRequestOptions, '/v4/accounts/{account_id}/resource_instances/usage/{billingmonth}', 'GET'); const expectedAccept = 'application/json'; const expectedContentType = undefined; checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); - expect(options.qs['_names']).toEqual(names); - expect(options.qs['_limit']).toEqual(limit); - expect(options.qs['_start']).toEqual(start); - expect(options.qs['resource_group_id']).toEqual(resourceGroupId); - expect(options.qs['organization_id']).toEqual(organizationId); - expect(options.qs['resource_instance_id']).toEqual(resourceInstanceId); - expect(options.qs['resource_id']).toEqual(resourceId); - expect(options.qs['plan_id']).toEqual(planId); - expect(options.qs['region']).toEqual(region); - expect(options.path['account_id']).toEqual(accountId); - expect(options.path['billingmonth']).toEqual(billingmonth); + expect(mockRequestOptions.qs._names).toEqual(names); + expect(mockRequestOptions.qs._limit).toEqual(limit); + expect(mockRequestOptions.qs._start).toEqual(start); + expect(mockRequestOptions.qs.resource_group_id).toEqual(resourceGroupId); + expect(mockRequestOptions.qs.organization_id).toEqual(organizationId); + expect(mockRequestOptions.qs.resource_instance_id).toEqual(resourceInstanceId); + expect(mockRequestOptions.qs.resource_id).toEqual(resourceId); + expect(mockRequestOptions.qs.plan_id).toEqual(planId); + expect(mockRequestOptions.qs.region).toEqual(region); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.billingmonth).toEqual(billingmonth); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getResourceUsageAccountTest(); + + // enable retries and test again + createRequestMock.mockClear(); + usageReportsService.enableRetries(); + __getResourceUsageAccountTest(); + + // disable retries and test again + createRequestMock.mockClear(); + usageReportsService.disableRetries(); + __getResourceUsageAccountTest(); }); test('should prioritize user-given headers', () => { @@ -397,7 +485,7 @@ describe('UsageReportsV4', () => { const billingmonth = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const params = { + const getResourceUsageAccountParams = { accountId, billingmonth, headers: { @@ -406,7 +494,7 @@ describe('UsageReportsV4', () => { }, }; - usageReportsService.getResourceUsageAccount(params); + usageReportsService.getResourceUsageAccount(getResourceUsageAccountParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -423,20 +511,90 @@ describe('UsageReportsV4', () => { expect(err.message).toMatch(/Missing required parameters/); }); - test('should reject promise when required params are not given', done => { - const getResourceUsageAccountPromise = usageReportsService.getResourceUsageAccount(); - expectToBePromise(getResourceUsageAccountPromise); + test('should reject promise when required params are not given', async () => { + let err; + try { + await usageReportsService.getResourceUsageAccount(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('GetResourceUsageAccountPager tests', () => { + const serviceUrl = usageReportsServiceOptions.url; + const path = '/v4/accounts/testString/resource_instances/usage/testString'; + const mockPagerResponse1 = + '{"next":{"href":"https://myhost.com/somePath?_start=1"},"total_count":2,"limit":1,"resources":[{"account_id":"account_id","resource_instance_id":"resource_instance_id","resource_instance_name":"resource_instance_name","resource_id":"resource_id","resource_name":"resource_name","resource_group_id":"resource_group_id","resource_group_name":"resource_group_name","organization_id":"organization_id","organization_name":"organization_name","space_id":"space_id","space_name":"space_name","consumer_id":"consumer_id","region":"region","pricing_region":"pricing_region","pricing_country":"USA","currency_code":"USD","billable":true,"plan_id":"plan_id","plan_name":"plan_name","month":"2017-08","usage":[{"metric":"UP-TIME","metric_name":"UP-TIME","quantity":711.11,"rateable_quantity":700,"cost":123.45,"rated_cost":130.0,"price":["anyValue"],"unit":"HOURS","unit_name":"HOURS","non_chargeable":true,"discounts":[{"ref":"Discount-d27beddb-111b-4bbf-8cb1-b770f531c1a9","name":"platform-discount","display_name":"Platform Service Discount","discount":5}]}]}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"resources":[{"account_id":"account_id","resource_instance_id":"resource_instance_id","resource_instance_name":"resource_instance_name","resource_id":"resource_id","resource_name":"resource_name","resource_group_id":"resource_group_id","resource_group_name":"resource_group_name","organization_id":"organization_id","organization_name":"organization_name","space_id":"space_id","space_name":"space_name","consumer_id":"consumer_id","region":"region","pricing_region":"pricing_region","pricing_country":"USA","currency_code":"USD","billable":true,"plan_id":"plan_id","plan_name":"plan_name","month":"2017-08","usage":[{"metric":"UP-TIME","metric_name":"UP-TIME","quantity":711.11,"rateable_quantity":700,"cost":123.45,"rated_cost":130.0,"price":["anyValue"],"unit":"HOURS","unit_name":"HOURS","non_chargeable":true,"discounts":[{"ref":"Discount-d27beddb-111b-4bbf-8cb1-b770f531c1a9","name":"platform-discount","display_name":"Platform Service Discount","discount":5}]}]}]}'; + + beforeEach(() => { + unmock_createRequest(); + const scope = nock(serviceUrl) + .get(uri => uri.includes(path)) + .reply(200, mockPagerResponse1) + .get(uri => uri.includes(path)) + .reply(200, mockPagerResponse2); + }); + + afterEach(() => { + nock.cleanAll(); + mock_createRequest(); + }); + + test('getNext()', async () => { + const params = { + accountId: 'testString', + billingmonth: 'testString', + names: true, + acceptLanguage: 'testString', + limit: 1, + resourceGroupId: 'testString', + organizationId: 'testString', + resourceInstanceId: 'testString', + resourceId: 'testString', + planId: 'testString', + region: 'testString', + }; + const allResults = []; + const pager = new UsageReportsV4.GetResourceUsageAccountPager(usageReportsService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); - getResourceUsageAccountPromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); + test('getAll()', async () => { + const params = { + accountId: 'testString', + billingmonth: 'testString', + names: true, + acceptLanguage: 'testString', + limit: 1, + resourceGroupId: 'testString', + organizationId: 'testString', + resourceInstanceId: 'testString', + resourceId: 'testString', + planId: 'testString', + region: 'testString', + }; + const pager = new UsageReportsV4.GetResourceUsageAccountPager(usageReportsService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); }); }); }); + describe('getResourceUsageResourceGroup', () => { describe('positive tests', () => { - test('should pass the right params to createRequest', () => { + function __getResourceUsageResourceGroupTest() { // Construct the params object for operation getResourceUsageResourceGroup const accountId = 'testString'; const resourceGroupId = 'testString'; @@ -449,21 +607,21 @@ describe('UsageReportsV4', () => { const resourceId = 'testString'; const planId = 'testString'; const region = 'testString'; - const params = { - accountId: accountId, - resourceGroupId: resourceGroupId, - billingmonth: billingmonth, - names: names, - acceptLanguage: acceptLanguage, - limit: limit, - start: start, - resourceInstanceId: resourceInstanceId, - resourceId: resourceId, - planId: planId, - region: region, + const getResourceUsageResourceGroupParams = { + accountId, + resourceGroupId, + billingmonth, + names, + acceptLanguage, + limit, + start, + resourceInstanceId, + resourceId, + planId, + region, }; - const getResourceUsageResourceGroupResult = usageReportsService.getResourceUsageResourceGroup(params); + const getResourceUsageResourceGroupResult = usageReportsService.getResourceUsageResourceGroup(getResourceUsageResourceGroupParams); // all methods should return a Promise expectToBePromise(getResourceUsageResourceGroupResult); @@ -471,23 +629,38 @@ describe('UsageReportsV4', () => { // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); - const options = getOptions(createRequestMock); + const mockRequestOptions = getOptions(createRequestMock); - checkUrlAndMethod(options, '/v4/accounts/{account_id}/resource_groups/{resource_group_id}/resource_instances/usage/{billingmonth}', 'GET'); + checkUrlAndMethod(mockRequestOptions, '/v4/accounts/{account_id}/resource_groups/{resource_group_id}/resource_instances/usage/{billingmonth}', 'GET'); const expectedAccept = 'application/json'; const expectedContentType = undefined; checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); - expect(options.qs['_names']).toEqual(names); - expect(options.qs['_limit']).toEqual(limit); - expect(options.qs['_start']).toEqual(start); - expect(options.qs['resource_instance_id']).toEqual(resourceInstanceId); - expect(options.qs['resource_id']).toEqual(resourceId); - expect(options.qs['plan_id']).toEqual(planId); - expect(options.qs['region']).toEqual(region); - expect(options.path['account_id']).toEqual(accountId); - expect(options.path['resource_group_id']).toEqual(resourceGroupId); - expect(options.path['billingmonth']).toEqual(billingmonth); + expect(mockRequestOptions.qs._names).toEqual(names); + expect(mockRequestOptions.qs._limit).toEqual(limit); + expect(mockRequestOptions.qs._start).toEqual(start); + expect(mockRequestOptions.qs.resource_instance_id).toEqual(resourceInstanceId); + expect(mockRequestOptions.qs.resource_id).toEqual(resourceId); + expect(mockRequestOptions.qs.plan_id).toEqual(planId); + expect(mockRequestOptions.qs.region).toEqual(region); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.resource_group_id).toEqual(resourceGroupId); + expect(mockRequestOptions.path.billingmonth).toEqual(billingmonth); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getResourceUsageResourceGroupTest(); + + // enable retries and test again + createRequestMock.mockClear(); + usageReportsService.enableRetries(); + __getResourceUsageResourceGroupTest(); + + // disable retries and test again + createRequestMock.mockClear(); + usageReportsService.disableRetries(); + __getResourceUsageResourceGroupTest(); }); test('should prioritize user-given headers', () => { @@ -497,7 +670,7 @@ describe('UsageReportsV4', () => { const billingmonth = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const params = { + const getResourceUsageResourceGroupParams = { accountId, resourceGroupId, billingmonth, @@ -507,7 +680,7 @@ describe('UsageReportsV4', () => { }, }; - usageReportsService.getResourceUsageResourceGroup(params); + usageReportsService.getResourceUsageResourceGroup(getResourceUsageResourceGroupParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -524,20 +697,88 @@ describe('UsageReportsV4', () => { expect(err.message).toMatch(/Missing required parameters/); }); - test('should reject promise when required params are not given', done => { - const getResourceUsageResourceGroupPromise = usageReportsService.getResourceUsageResourceGroup(); - expectToBePromise(getResourceUsageResourceGroupPromise); + test('should reject promise when required params are not given', async () => { + let err; + try { + await usageReportsService.getResourceUsageResourceGroup(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('GetResourceUsageResourceGroupPager tests', () => { + const serviceUrl = usageReportsServiceOptions.url; + const path = '/v4/accounts/testString/resource_groups/testString/resource_instances/usage/testString'; + const mockPagerResponse1 = + '{"next":{"href":"https://myhost.com/somePath?_start=1"},"total_count":2,"limit":1,"resources":[{"account_id":"account_id","resource_instance_id":"resource_instance_id","resource_instance_name":"resource_instance_name","resource_id":"resource_id","resource_name":"resource_name","resource_group_id":"resource_group_id","resource_group_name":"resource_group_name","organization_id":"organization_id","organization_name":"organization_name","space_id":"space_id","space_name":"space_name","consumer_id":"consumer_id","region":"region","pricing_region":"pricing_region","pricing_country":"USA","currency_code":"USD","billable":true,"plan_id":"plan_id","plan_name":"plan_name","month":"2017-08","usage":[{"metric":"UP-TIME","metric_name":"UP-TIME","quantity":711.11,"rateable_quantity":700,"cost":123.45,"rated_cost":130.0,"price":["anyValue"],"unit":"HOURS","unit_name":"HOURS","non_chargeable":true,"discounts":[{"ref":"Discount-d27beddb-111b-4bbf-8cb1-b770f531c1a9","name":"platform-discount","display_name":"Platform Service Discount","discount":5}]}]}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"resources":[{"account_id":"account_id","resource_instance_id":"resource_instance_id","resource_instance_name":"resource_instance_name","resource_id":"resource_id","resource_name":"resource_name","resource_group_id":"resource_group_id","resource_group_name":"resource_group_name","organization_id":"organization_id","organization_name":"organization_name","space_id":"space_id","space_name":"space_name","consumer_id":"consumer_id","region":"region","pricing_region":"pricing_region","pricing_country":"USA","currency_code":"USD","billable":true,"plan_id":"plan_id","plan_name":"plan_name","month":"2017-08","usage":[{"metric":"UP-TIME","metric_name":"UP-TIME","quantity":711.11,"rateable_quantity":700,"cost":123.45,"rated_cost":130.0,"price":["anyValue"],"unit":"HOURS","unit_name":"HOURS","non_chargeable":true,"discounts":[{"ref":"Discount-d27beddb-111b-4bbf-8cb1-b770f531c1a9","name":"platform-discount","display_name":"Platform Service Discount","discount":5}]}]}]}'; + + beforeEach(() => { + unmock_createRequest(); + const scope = nock(serviceUrl) + .get(uri => uri.includes(path)) + .reply(200, mockPagerResponse1) + .get(uri => uri.includes(path)) + .reply(200, mockPagerResponse2); + }); - getResourceUsageResourceGroupPromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); + afterEach(() => { + nock.cleanAll(); + mock_createRequest(); + }); + + test('getNext()', async () => { + const params = { + accountId: 'testString', + resourceGroupId: 'testString', + billingmonth: 'testString', + names: true, + acceptLanguage: 'testString', + limit: 1, + resourceInstanceId: 'testString', + resourceId: 'testString', + planId: 'testString', + region: 'testString', + }; + const allResults = []; + const pager = new UsageReportsV4.GetResourceUsageResourceGroupPager(usageReportsService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + + test('getAll()', async () => { + const params = { + accountId: 'testString', + resourceGroupId: 'testString', + billingmonth: 'testString', + names: true, + acceptLanguage: 'testString', + limit: 1, + resourceInstanceId: 'testString', + resourceId: 'testString', + planId: 'testString', + region: 'testString', + }; + const pager = new UsageReportsV4.GetResourceUsageResourceGroupPager(usageReportsService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); }); }); }); + describe('getResourceUsageOrg', () => { describe('positive tests', () => { - test('should pass the right params to createRequest', () => { + function __getResourceUsageOrgTest() { // Construct the params object for operation getResourceUsageOrg const accountId = 'testString'; const organizationId = 'testString'; @@ -550,21 +791,21 @@ describe('UsageReportsV4', () => { const resourceId = 'testString'; const planId = 'testString'; const region = 'testString'; - const params = { - accountId: accountId, - organizationId: organizationId, - billingmonth: billingmonth, - names: names, - acceptLanguage: acceptLanguage, - limit: limit, - start: start, - resourceInstanceId: resourceInstanceId, - resourceId: resourceId, - planId: planId, - region: region, + const getResourceUsageOrgParams = { + accountId, + organizationId, + billingmonth, + names, + acceptLanguage, + limit, + start, + resourceInstanceId, + resourceId, + planId, + region, }; - const getResourceUsageOrgResult = usageReportsService.getResourceUsageOrg(params); + const getResourceUsageOrgResult = usageReportsService.getResourceUsageOrg(getResourceUsageOrgParams); // all methods should return a Promise expectToBePromise(getResourceUsageOrgResult); @@ -572,23 +813,38 @@ describe('UsageReportsV4', () => { // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); - const options = getOptions(createRequestMock); + const mockRequestOptions = getOptions(createRequestMock); - checkUrlAndMethod(options, '/v4/accounts/{account_id}/organizations/{organization_id}/resource_instances/usage/{billingmonth}', 'GET'); + checkUrlAndMethod(mockRequestOptions, '/v4/accounts/{account_id}/organizations/{organization_id}/resource_instances/usage/{billingmonth}', 'GET'); const expectedAccept = 'application/json'; const expectedContentType = undefined; checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); - expect(options.qs['_names']).toEqual(names); - expect(options.qs['_limit']).toEqual(limit); - expect(options.qs['_start']).toEqual(start); - expect(options.qs['resource_instance_id']).toEqual(resourceInstanceId); - expect(options.qs['resource_id']).toEqual(resourceId); - expect(options.qs['plan_id']).toEqual(planId); - expect(options.qs['region']).toEqual(region); - expect(options.path['account_id']).toEqual(accountId); - expect(options.path['organization_id']).toEqual(organizationId); - expect(options.path['billingmonth']).toEqual(billingmonth); + expect(mockRequestOptions.qs._names).toEqual(names); + expect(mockRequestOptions.qs._limit).toEqual(limit); + expect(mockRequestOptions.qs._start).toEqual(start); + expect(mockRequestOptions.qs.resource_instance_id).toEqual(resourceInstanceId); + expect(mockRequestOptions.qs.resource_id).toEqual(resourceId); + expect(mockRequestOptions.qs.plan_id).toEqual(planId); + expect(mockRequestOptions.qs.region).toEqual(region); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.organization_id).toEqual(organizationId); + expect(mockRequestOptions.path.billingmonth).toEqual(billingmonth); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getResourceUsageOrgTest(); + + // enable retries and test again + createRequestMock.mockClear(); + usageReportsService.enableRetries(); + __getResourceUsageOrgTest(); + + // disable retries and test again + createRequestMock.mockClear(); + usageReportsService.disableRetries(); + __getResourceUsageOrgTest(); }); test('should prioritize user-given headers', () => { @@ -598,7 +854,7 @@ describe('UsageReportsV4', () => { const billingmonth = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const params = { + const getResourceUsageOrgParams = { accountId, organizationId, billingmonth, @@ -608,7 +864,7 @@ describe('UsageReportsV4', () => { }, }; - usageReportsService.getResourceUsageOrg(params); + usageReportsService.getResourceUsageOrg(getResourceUsageOrgParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -625,35 +881,103 @@ describe('UsageReportsV4', () => { expect(err.message).toMatch(/Missing required parameters/); }); - test('should reject promise when required params are not given', done => { - const getResourceUsageOrgPromise = usageReportsService.getResourceUsageOrg(); - expectToBePromise(getResourceUsageOrgPromise); + test('should reject promise when required params are not given', async () => { + let err; + try { + await usageReportsService.getResourceUsageOrg(); + } catch (e) { + err = e; + } - getResourceUsageOrgPromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('GetResourceUsageOrgPager tests', () => { + const serviceUrl = usageReportsServiceOptions.url; + const path = '/v4/accounts/testString/organizations/testString/resource_instances/usage/testString'; + const mockPagerResponse1 = + '{"next":{"href":"https://myhost.com/somePath?_start=1"},"total_count":2,"limit":1,"resources":[{"account_id":"account_id","resource_instance_id":"resource_instance_id","resource_instance_name":"resource_instance_name","resource_id":"resource_id","resource_name":"resource_name","resource_group_id":"resource_group_id","resource_group_name":"resource_group_name","organization_id":"organization_id","organization_name":"organization_name","space_id":"space_id","space_name":"space_name","consumer_id":"consumer_id","region":"region","pricing_region":"pricing_region","pricing_country":"USA","currency_code":"USD","billable":true,"plan_id":"plan_id","plan_name":"plan_name","month":"2017-08","usage":[{"metric":"UP-TIME","metric_name":"UP-TIME","quantity":711.11,"rateable_quantity":700,"cost":123.45,"rated_cost":130.0,"price":["anyValue"],"unit":"HOURS","unit_name":"HOURS","non_chargeable":true,"discounts":[{"ref":"Discount-d27beddb-111b-4bbf-8cb1-b770f531c1a9","name":"platform-discount","display_name":"Platform Service Discount","discount":5}]}]}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"resources":[{"account_id":"account_id","resource_instance_id":"resource_instance_id","resource_instance_name":"resource_instance_name","resource_id":"resource_id","resource_name":"resource_name","resource_group_id":"resource_group_id","resource_group_name":"resource_group_name","organization_id":"organization_id","organization_name":"organization_name","space_id":"space_id","space_name":"space_name","consumer_id":"consumer_id","region":"region","pricing_region":"pricing_region","pricing_country":"USA","currency_code":"USD","billable":true,"plan_id":"plan_id","plan_name":"plan_name","month":"2017-08","usage":[{"metric":"UP-TIME","metric_name":"UP-TIME","quantity":711.11,"rateable_quantity":700,"cost":123.45,"rated_cost":130.0,"price":["anyValue"],"unit":"HOURS","unit_name":"HOURS","non_chargeable":true,"discounts":[{"ref":"Discount-d27beddb-111b-4bbf-8cb1-b770f531c1a9","name":"platform-discount","display_name":"Platform Service Discount","discount":5}]}]}]}'; + + beforeEach(() => { + unmock_createRequest(); + const scope = nock(serviceUrl) + .get(uri => uri.includes(path)) + .reply(200, mockPagerResponse1) + .get(uri => uri.includes(path)) + .reply(200, mockPagerResponse2); + }); + + afterEach(() => { + nock.cleanAll(); + mock_createRequest(); + }); + + test('getNext()', async () => { + const params = { + accountId: 'testString', + organizationId: 'testString', + billingmonth: 'testString', + names: true, + acceptLanguage: 'testString', + limit: 1, + resourceInstanceId: 'testString', + resourceId: 'testString', + planId: 'testString', + region: 'testString', + }; + const allResults = []; + const pager = new UsageReportsV4.GetResourceUsageOrgPager(usageReportsService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + + test('getAll()', async () => { + const params = { + accountId: 'testString', + organizationId: 'testString', + billingmonth: 'testString', + names: true, + acceptLanguage: 'testString', + limit: 1, + resourceInstanceId: 'testString', + resourceId: 'testString', + planId: 'testString', + region: 'testString', + }; + const pager = new UsageReportsV4.GetResourceUsageOrgPager(usageReportsService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); }); }); }); + describe('getOrgUsage', () => { describe('positive tests', () => { - test('should pass the right params to createRequest', () => { + function __getOrgUsageTest() { // Construct the params object for operation getOrgUsage const accountId = 'testString'; const organizationId = 'testString'; const billingmonth = 'testString'; const names = true; const acceptLanguage = 'testString'; - const params = { - accountId: accountId, - organizationId: organizationId, - billingmonth: billingmonth, - names: names, - acceptLanguage: acceptLanguage, + const getOrgUsageParams = { + accountId, + organizationId, + billingmonth, + names, + acceptLanguage, }; - const getOrgUsageResult = usageReportsService.getOrgUsage(params); + const getOrgUsageResult = usageReportsService.getOrgUsage(getOrgUsageParams); // all methods should return a Promise expectToBePromise(getOrgUsageResult); @@ -661,17 +985,32 @@ describe('UsageReportsV4', () => { // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); - const options = getOptions(createRequestMock); + const mockRequestOptions = getOptions(createRequestMock); - checkUrlAndMethod(options, '/v4/accounts/{account_id}/organizations/{organization_id}/usage/{billingmonth}', 'GET'); + checkUrlAndMethod(mockRequestOptions, '/v4/accounts/{account_id}/organizations/{organization_id}/usage/{billingmonth}', 'GET'); const expectedAccept = 'application/json'; const expectedContentType = undefined; checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); - expect(options.qs['_names']).toEqual(names); - expect(options.path['account_id']).toEqual(accountId); - expect(options.path['organization_id']).toEqual(organizationId); - expect(options.path['billingmonth']).toEqual(billingmonth); + expect(mockRequestOptions.qs._names).toEqual(names); + expect(mockRequestOptions.path.account_id).toEqual(accountId); + expect(mockRequestOptions.path.organization_id).toEqual(organizationId); + expect(mockRequestOptions.path.billingmonth).toEqual(billingmonth); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getOrgUsageTest(); + + // enable retries and test again + createRequestMock.mockClear(); + usageReportsService.enableRetries(); + __getOrgUsageTest(); + + // disable retries and test again + createRequestMock.mockClear(); + usageReportsService.disableRetries(); + __getOrgUsageTest(); }); test('should prioritize user-given headers', () => { @@ -681,7 +1020,7 @@ describe('UsageReportsV4', () => { const billingmonth = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const params = { + const getOrgUsageParams = { accountId, organizationId, billingmonth, @@ -691,7 +1030,7 @@ describe('UsageReportsV4', () => { }, }; - usageReportsService.getOrgUsage(params); + usageReportsService.getOrgUsage(getOrgUsageParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -708,14 +1047,15 @@ describe('UsageReportsV4', () => { expect(err.message).toMatch(/Missing required parameters/); }); - test('should reject promise when required params are not given', done => { - const getOrgUsagePromise = usageReportsService.getOrgUsage(); - expectToBePromise(getOrgUsagePromise); + test('should reject promise when required params are not given', async () => { + let err; + try { + await usageReportsService.getOrgUsage(); + } catch (e) { + err = e; + } - getOrgUsagePromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); + expect(err.message).toMatch(/Missing required parameters/); }); }); }); diff --git a/usage-reports/v4.ts b/usage-reports/v4.ts index a7e13482..a4f84a33 100644 --- a/usage-reports/v4.ts +++ b/usage-reports/v4.ts @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2021. + * (C) Copyright IBM Corp. 2022. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,22 +15,28 @@ */ /** - * IBM OpenAPI SDK Code Generator Version: 3.36.0-6f5b0381-20210716-180747 + * IBM OpenAPI SDK Code Generator Version: 3.62.0-a2a22f95-20221115-162524 */ +/* eslint-disable max-classes-per-file */ +/* eslint-disable no-await-in-loop */ + import * as extend from 'extend'; import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'; import { Authenticator, BaseService, getAuthenticatorFromEnvironment, - getMissingParams, + validateParams, UserOptions, } from 'ibm-cloud-sdk-core'; import { getSdkHeaders } from '../lib/common'; +import { getQueryParam } from 'ibm-cloud-sdk-core'; /** * Usage reports for IBM Cloud accounts + * + * API Version: 4.0.6 */ class UsageReportsV4 extends BaseService { @@ -111,11 +117,11 @@ class UsageReportsV4 extends BaseService { params: UsageReportsV4.GetAccountSummaryParams ): Promise> { const _params = { ...params }; - const requiredParams = ['accountId', 'billingmonth']; - - const missingParams = getMissingParams(_params, requiredParams); - if (missingParams) { - return Promise.reject(missingParams); + const _requiredParams = ['accountId', 'billingmonth']; + const _validParams = ['accountId', 'billingmonth', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } const path = { @@ -171,11 +177,11 @@ class UsageReportsV4 extends BaseService { params: UsageReportsV4.GetAccountUsageParams ): Promise> { const _params = { ...params }; - const requiredParams = ['accountId', 'billingmonth']; - - const missingParams = getMissingParams(_params, requiredParams); - if (missingParams) { - return Promise.reject(missingParams); + const _requiredParams = ['accountId', 'billingmonth']; + const _validParams = ['accountId', 'billingmonth', 'names', 'acceptLanguage', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } const query = { @@ -187,7 +193,11 @@ class UsageReportsV4 extends BaseService { 'billingmonth': _params.billingmonth, }; - const sdkHeaders = getSdkHeaders(UsageReportsV4.DEFAULT_SERVICE_NAME, 'v4', 'getAccountUsage'); + const sdkHeaders = getSdkHeaders( + UsageReportsV4.DEFAULT_SERVICE_NAME, + 'v4', + 'getAccountUsage' + ); const parameters = { options: { @@ -211,7 +221,6 @@ class UsageReportsV4 extends BaseService { return this.createRequest(parameters); } - /************************* * resourceOperations ************************/ @@ -238,11 +247,11 @@ class UsageReportsV4 extends BaseService { params: UsageReportsV4.GetResourceGroupUsageParams ): Promise> { const _params = { ...params }; - const requiredParams = ['accountId', 'resourceGroupId', 'billingmonth']; - - const missingParams = getMissingParams(_params, requiredParams); - if (missingParams) { - return Promise.reject(missingParams); + const _requiredParams = ['accountId', 'resourceGroupId', 'billingmonth']; + const _validParams = ['accountId', 'resourceGroupId', 'billingmonth', 'names', 'acceptLanguage', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } const query = { @@ -298,7 +307,7 @@ class UsageReportsV4 extends BaseService { * resource group. * @param {string} [params.acceptLanguage] - Prioritize the names returned in the order of the specified languages. * Language will default to English. - * @param {number} [params.limit] - Number of usage records returned. The default value is 10. Maximum value is 20. + * @param {number} [params.limit] - Number of usage records returned. The default value is 30. Maximum value is 200. * @param {string} [params.start] - The offset from which the records must be fetched. Offset information is included * in the response. * @param {string} [params.resourceGroupId] - Filter by resource group. @@ -314,11 +323,11 @@ class UsageReportsV4 extends BaseService { params: UsageReportsV4.GetResourceUsageAccountParams ): Promise> { const _params = { ...params }; - const requiredParams = ['accountId', 'billingmonth']; - - const missingParams = getMissingParams(_params, requiredParams); - if (missingParams) { - return Promise.reject(missingParams); + const _requiredParams = ['accountId', 'billingmonth']; + const _validParams = ['accountId', 'billingmonth', 'names', 'acceptLanguage', 'limit', 'start', 'resourceGroupId', 'organizationId', 'resourceInstanceId', 'resourceId', 'planId', 'region', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } const query = { @@ -382,7 +391,7 @@ class UsageReportsV4 extends BaseService { * resource group. * @param {string} [params.acceptLanguage] - Prioritize the names returned in the order of the specified languages. * Language will default to English. - * @param {number} [params.limit] - Number of usage records returned. The default value is 10. Maximum value is 20. + * @param {number} [params.limit] - Number of usage records returned. The default value is 30. Maximum value is 200. * @param {string} [params.start] - The offset from which the records must be fetched. Offset information is included * in the response. * @param {string} [params.resourceInstanceId] - Filter by resource instance id. @@ -396,11 +405,11 @@ class UsageReportsV4 extends BaseService { params: UsageReportsV4.GetResourceUsageResourceGroupParams ): Promise> { const _params = { ...params }; - const requiredParams = ['accountId', 'resourceGroupId', 'billingmonth']; - - const missingParams = getMissingParams(_params, requiredParams); - if (missingParams) { - return Promise.reject(missingParams); + const _requiredParams = ['accountId', 'resourceGroupId', 'billingmonth']; + const _validParams = ['accountId', 'resourceGroupId', 'billingmonth', 'names', 'acceptLanguage', 'limit', 'start', 'resourceInstanceId', 'resourceId', 'planId', 'region', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } const query = { @@ -463,7 +472,7 @@ class UsageReportsV4 extends BaseService { * resource group. * @param {string} [params.acceptLanguage] - Prioritize the names returned in the order of the specified languages. * Language will default to English. - * @param {number} [params.limit] - Number of usage records returned. The default value is 10. Maximum value is 20. + * @param {number} [params.limit] - Number of usage records returned. The default value is 30. Maximum value is 200. * @param {string} [params.start] - The offset from which the records must be fetched. Offset information is included * in the response. * @param {string} [params.resourceInstanceId] - Filter by resource instance id. @@ -477,11 +486,11 @@ class UsageReportsV4 extends BaseService { params: UsageReportsV4.GetResourceUsageOrgParams ): Promise> { const _params = { ...params }; - const requiredParams = ['accountId', 'organizationId', 'billingmonth']; - - const missingParams = getMissingParams(_params, requiredParams); - if (missingParams) { - return Promise.reject(missingParams); + const _requiredParams = ['accountId', 'organizationId', 'billingmonth']; + const _validParams = ['accountId', 'organizationId', 'billingmonth', 'names', 'acceptLanguage', 'limit', 'start', 'resourceInstanceId', 'resourceId', 'planId', 'region', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } const query = { @@ -528,7 +537,6 @@ class UsageReportsV4 extends BaseService { return this.createRequest(parameters); } - /************************* * organizationOperations ************************/ @@ -555,11 +563,11 @@ class UsageReportsV4 extends BaseService { params: UsageReportsV4.GetOrgUsageParams ): Promise> { const _params = { ...params }; - const requiredParams = ['accountId', 'organizationId', 'billingmonth']; - - const missingParams = getMissingParams(_params, requiredParams); - if (missingParams) { - return Promise.reject(missingParams); + const _requiredParams = ['accountId', 'organizationId', 'billingmonth']; + const _validParams = ['accountId', 'organizationId', 'billingmonth', 'names', 'acceptLanguage', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } const query = { @@ -572,7 +580,11 @@ class UsageReportsV4 extends BaseService { 'billingmonth': _params.billingmonth, }; - const sdkHeaders = getSdkHeaders(UsageReportsV4.DEFAULT_SERVICE_NAME, 'v4', 'getOrgUsage'); + const sdkHeaders = getSdkHeaders( + UsageReportsV4.DEFAULT_SERVICE_NAME, + 'v4', + 'getOrgUsage' + ); const parameters = { options: { @@ -615,7 +627,7 @@ namespace UsageReportsV4 { export type Callback = (error: any, response?: Response) => void; /** The body of a service request that returns no response data. */ - export interface Empty {} + export interface EmptyObject {} /** A standard JS object, defined to avoid the limitations of `Object` and `object` */ export interface JsonObject { @@ -673,7 +685,7 @@ namespace UsageReportsV4 { names?: boolean; /** Prioritize the names returned in the order of the specified languages. Language will default to English. */ acceptLanguage?: string; - /** Number of usage records returned. The default value is 10. Maximum value is 20. */ + /** Number of usage records returned. The default value is 30. Maximum value is 200. */ limit?: number; /** The offset from which the records must be fetched. Offset information is included in the response. */ start?: string; @@ -704,7 +716,7 @@ namespace UsageReportsV4 { names?: boolean; /** Prioritize the names returned in the order of the specified languages. Language will default to English. */ acceptLanguage?: string; - /** Number of usage records returned. The default value is 10. Maximum value is 20. */ + /** Number of usage records returned. The default value is 30. Maximum value is 200. */ limit?: number; /** The offset from which the records must be fetched. Offset information is included in the response. */ start?: string; @@ -731,7 +743,7 @@ namespace UsageReportsV4 { names?: boolean; /** Prioritize the names returned in the order of the specified languages. Language will default to English. */ acceptLanguage?: string; - /** Number of usage records returned. The default value is 10. Maximum value is 20. */ + /** Number of usage records returned. The default value is 30. Maximum value is 200. */ limit?: number; /** The offset from which the records must be fetched. Offset information is included in the response. */ start?: string; @@ -770,7 +782,7 @@ namespace UsageReportsV4 { /** The ID of the account. */ account_id: string; /** The month in which usages were incurred. Represented in yyyy-mm format. */ - billing_month: string; + month: string; /** Country. */ billing_country_code: string; /** The currency in which the account is billed. */ @@ -1082,6 +1094,259 @@ namespace UsageReportsV4 { /** Additional support cost for the month. */ overage: number; } + + /************************* + * pager classes + ************************/ + + /** + * GetResourceUsageAccountPager can be used to simplify the use of getResourceUsageAccount(). + */ + export class GetResourceUsageAccountPager { + protected _hasNext: boolean; + protected pageContext: any; + + protected client: UsageReportsV4; + + protected params: UsageReportsV4.GetResourceUsageAccountParams; + + /** + * Construct a GetResourceUsageAccountPager object. + * + * @param {UsageReportsV4} client - The service client instance used to invoke getResourceUsageAccount() + * @param {Object} params - The parameters to be passed to getResourceUsageAccount() + * @constructor + * @returns {GetResourceUsageAccountPager} + */ + constructor( + client: UsageReportsV4, + params: UsageReportsV4.GetResourceUsageAccountParams + ) { + if (params && params.start) { + throw new Error(`the params.start field should not be set`); + } + + this._hasNext = true; + this.pageContext = { next: undefined }; + this.client = client; + this.params = JSON.parse(JSON.stringify(params || {})); + } + + /** + * Returns true if there are potentially more results to be retrieved by invoking getNext(). + * @returns {boolean} + */ + public hasNext(): boolean { + return this._hasNext; + } + + /** + * Returns the next page of results by invoking getResourceUsageAccount(). + * @returns {Promise} + */ + public async getNext(): Promise { + if (!this.hasNext()) { + throw new Error('No more results available'); + } + + if (this.pageContext.next) { + this.params.start = this.pageContext.next; + } + const response = await this.client.getResourceUsageAccount(this.params); + const { result } = response; + + let next = null; + if (result && result.next) { + if (result.next.href) { + next = getQueryParam(result.next.href, '_start'); + } + } + this.pageContext.next = next; + if (!this.pageContext.next) { + this._hasNext = false; + } + return result.resources; + } + + /** + * Returns all results by invoking getResourceUsageAccount() repeatedly until all pages of results have been retrieved. + * @returns {Promise} + */ + public async getAll(): Promise { + const results: InstanceUsage[] = []; + while (this.hasNext()) { + const nextPage = await this.getNext(); + results.push(...nextPage); + } + return results; + } + } + + /** + * GetResourceUsageResourceGroupPager can be used to simplify the use of getResourceUsageResourceGroup(). + */ + export class GetResourceUsageResourceGroupPager { + protected _hasNext: boolean; + protected pageContext: any; + + protected client: UsageReportsV4; + + protected params: UsageReportsV4.GetResourceUsageResourceGroupParams; + + /** + * Construct a GetResourceUsageResourceGroupPager object. + * + * @param {UsageReportsV4} client - The service client instance used to invoke getResourceUsageResourceGroup() + * @param {Object} params - The parameters to be passed to getResourceUsageResourceGroup() + * @constructor + * @returns {GetResourceUsageResourceGroupPager} + */ + constructor( + client: UsageReportsV4, + params: UsageReportsV4.GetResourceUsageResourceGroupParams + ) { + if (params && params.start) { + throw new Error(`the params.start field should not be set`); + } + + this._hasNext = true; + this.pageContext = { next: undefined }; + this.client = client; + this.params = JSON.parse(JSON.stringify(params || {})); + } + + /** + * Returns true if there are potentially more results to be retrieved by invoking getNext(). + * @returns {boolean} + */ + public hasNext(): boolean { + return this._hasNext; + } + + /** + * Returns the next page of results by invoking getResourceUsageResourceGroup(). + * @returns {Promise} + */ + public async getNext(): Promise { + if (!this.hasNext()) { + throw new Error('No more results available'); + } + + if (this.pageContext.next) { + this.params.start = this.pageContext.next; + } + const response = await this.client.getResourceUsageResourceGroup(this.params); + const { result } = response; + + let next = null; + if (result && result.next) { + if (result.next.href) { + next = getQueryParam(result.next.href, '_start'); + } + } + this.pageContext.next = next; + if (!this.pageContext.next) { + this._hasNext = false; + } + return result.resources; + } + + /** + * Returns all results by invoking getResourceUsageResourceGroup() repeatedly until all pages of results have been retrieved. + * @returns {Promise} + */ + public async getAll(): Promise { + const results: InstanceUsage[] = []; + while (this.hasNext()) { + const nextPage = await this.getNext(); + results.push(...nextPage); + } + return results; + } + } + + /** + * GetResourceUsageOrgPager can be used to simplify the use of getResourceUsageOrg(). + */ + export class GetResourceUsageOrgPager { + protected _hasNext: boolean; + protected pageContext: any; + + protected client: UsageReportsV4; + + protected params: UsageReportsV4.GetResourceUsageOrgParams; + + /** + * Construct a GetResourceUsageOrgPager object. + * + * @param {UsageReportsV4} client - The service client instance used to invoke getResourceUsageOrg() + * @param {Object} params - The parameters to be passed to getResourceUsageOrg() + * @constructor + * @returns {GetResourceUsageOrgPager} + */ + constructor( + client: UsageReportsV4, + params: UsageReportsV4.GetResourceUsageOrgParams + ) { + if (params && params.start) { + throw new Error(`the params.start field should not be set`); + } + + this._hasNext = true; + this.pageContext = { next: undefined }; + this.client = client; + this.params = JSON.parse(JSON.stringify(params || {})); + } + + /** + * Returns true if there are potentially more results to be retrieved by invoking getNext(). + * @returns {boolean} + */ + public hasNext(): boolean { + return this._hasNext; + } + + /** + * Returns the next page of results by invoking getResourceUsageOrg(). + * @returns {Promise} + */ + public async getNext(): Promise { + if (!this.hasNext()) { + throw new Error('No more results available'); + } + + if (this.pageContext.next) { + this.params.start = this.pageContext.next; + } + const response = await this.client.getResourceUsageOrg(this.params); + const { result } = response; + + let next = null; + if (result && result.next) { + if (result.next.href) { + next = getQueryParam(result.next.href, '_start'); + } + } + this.pageContext.next = next; + if (!this.pageContext.next) { + this._hasNext = false; + } + return result.resources; + } + + /** + * Returns all results by invoking getResourceUsageOrg() repeatedly until all pages of results have been retrieved. + * @returns {Promise} + */ + public async getAll(): Promise { + const results: InstanceUsage[] = []; + while (this.hasNext()) { + const nextPage = await this.getNext(); + results.push(...nextPage); + } + return results; + } + } } export = UsageReportsV4; From 4511ceb365d241685f72e1b3081c0aae4462fcea Mon Sep 17 00:00:00 2001 From: Jonathan Date-chong Date: Fri, 2 Dec 2022 15:21:46 -0800 Subject: [PATCH 2/2] lint Signed-off-by: Jonathan Date-chong --- usage-reports/v4.ts | 91 +++++++++++++++++++++++++++++++++------------ 1 file changed, 67 insertions(+), 24 deletions(-) diff --git a/usage-reports/v4.ts b/usage-reports/v4.ts index a4f84a33..4cf2b021 100644 --- a/usage-reports/v4.ts +++ b/usage-reports/v4.ts @@ -29,9 +29,9 @@ import { getAuthenticatorFromEnvironment, validateParams, UserOptions, + getQueryParam, } from 'ibm-cloud-sdk-core'; import { getSdkHeaders } from '../lib/common'; -import { getQueryParam } from 'ibm-cloud-sdk-core'; /** * Usage reports for IBM Cloud accounts @@ -193,11 +193,7 @@ class UsageReportsV4 extends BaseService { 'billingmonth': _params.billingmonth, }; - const sdkHeaders = getSdkHeaders( - UsageReportsV4.DEFAULT_SERVICE_NAME, - 'v4', - 'getAccountUsage' - ); + const sdkHeaders = getSdkHeaders(UsageReportsV4.DEFAULT_SERVICE_NAME, 'v4', 'getAccountUsage'); const parameters = { options: { @@ -248,7 +244,14 @@ class UsageReportsV4 extends BaseService { ): Promise> { const _params = { ...params }; const _requiredParams = ['accountId', 'resourceGroupId', 'billingmonth']; - const _validParams = ['accountId', 'resourceGroupId', 'billingmonth', 'names', 'acceptLanguage', 'headers']; + const _validParams = [ + 'accountId', + 'resourceGroupId', + 'billingmonth', + 'names', + 'acceptLanguage', + 'headers', + ]; const _validationErrors = validateParams(_params, _requiredParams, _validParams); if (_validationErrors) { return Promise.reject(_validationErrors); @@ -324,7 +327,21 @@ class UsageReportsV4 extends BaseService { ): Promise> { const _params = { ...params }; const _requiredParams = ['accountId', 'billingmonth']; - const _validParams = ['accountId', 'billingmonth', 'names', 'acceptLanguage', 'limit', 'start', 'resourceGroupId', 'organizationId', 'resourceInstanceId', 'resourceId', 'planId', 'region', 'headers']; + const _validParams = [ + 'accountId', + 'billingmonth', + 'names', + 'acceptLanguage', + 'limit', + 'start', + 'resourceGroupId', + 'organizationId', + 'resourceInstanceId', + 'resourceId', + 'planId', + 'region', + 'headers', + ]; const _validationErrors = validateParams(_params, _requiredParams, _validParams); if (_validationErrors) { return Promise.reject(_validationErrors); @@ -406,7 +423,20 @@ class UsageReportsV4 extends BaseService { ): Promise> { const _params = { ...params }; const _requiredParams = ['accountId', 'resourceGroupId', 'billingmonth']; - const _validParams = ['accountId', 'resourceGroupId', 'billingmonth', 'names', 'acceptLanguage', 'limit', 'start', 'resourceInstanceId', 'resourceId', 'planId', 'region', 'headers']; + const _validParams = [ + 'accountId', + 'resourceGroupId', + 'billingmonth', + 'names', + 'acceptLanguage', + 'limit', + 'start', + 'resourceInstanceId', + 'resourceId', + 'planId', + 'region', + 'headers', + ]; const _validationErrors = validateParams(_params, _requiredParams, _validParams); if (_validationErrors) { return Promise.reject(_validationErrors); @@ -487,7 +517,20 @@ class UsageReportsV4 extends BaseService { ): Promise> { const _params = { ...params }; const _requiredParams = ['accountId', 'organizationId', 'billingmonth']; - const _validParams = ['accountId', 'organizationId', 'billingmonth', 'names', 'acceptLanguage', 'limit', 'start', 'resourceInstanceId', 'resourceId', 'planId', 'region', 'headers']; + const _validParams = [ + 'accountId', + 'organizationId', + 'billingmonth', + 'names', + 'acceptLanguage', + 'limit', + 'start', + 'resourceInstanceId', + 'resourceId', + 'planId', + 'region', + 'headers', + ]; const _validationErrors = validateParams(_params, _requiredParams, _validParams); if (_validationErrors) { return Promise.reject(_validationErrors); @@ -564,7 +607,14 @@ class UsageReportsV4 extends BaseService { ): Promise> { const _params = { ...params }; const _requiredParams = ['accountId', 'organizationId', 'billingmonth']; - const _validParams = ['accountId', 'organizationId', 'billingmonth', 'names', 'acceptLanguage', 'headers']; + const _validParams = [ + 'accountId', + 'organizationId', + 'billingmonth', + 'names', + 'acceptLanguage', + 'headers', + ]; const _validationErrors = validateParams(_params, _requiredParams, _validParams); if (_validationErrors) { return Promise.reject(_validationErrors); @@ -580,11 +630,7 @@ class UsageReportsV4 extends BaseService { 'billingmonth': _params.billingmonth, }; - const sdkHeaders = getSdkHeaders( - UsageReportsV4.DEFAULT_SERVICE_NAME, - 'v4', - 'getOrgUsage' - ); + const sdkHeaders = getSdkHeaders(UsageReportsV4.DEFAULT_SERVICE_NAME, 'v4', 'getOrgUsage'); const parameters = { options: { @@ -1104,6 +1150,7 @@ namespace UsageReportsV4 { */ export class GetResourceUsageAccountPager { protected _hasNext: boolean; + protected pageContext: any; protected client: UsageReportsV4; @@ -1118,10 +1165,7 @@ namespace UsageReportsV4 { * @constructor * @returns {GetResourceUsageAccountPager} */ - constructor( - client: UsageReportsV4, - params: UsageReportsV4.GetResourceUsageAccountParams - ) { + constructor(client: UsageReportsV4, params: UsageReportsV4.GetResourceUsageAccountParams) { if (params && params.start) { throw new Error(`the params.start field should not be set`); } @@ -1187,6 +1231,7 @@ namespace UsageReportsV4 { */ export class GetResourceUsageResourceGroupPager { protected _hasNext: boolean; + protected pageContext: any; protected client: UsageReportsV4; @@ -1270,6 +1315,7 @@ namespace UsageReportsV4 { */ export class GetResourceUsageOrgPager { protected _hasNext: boolean; + protected pageContext: any; protected client: UsageReportsV4; @@ -1284,10 +1330,7 @@ namespace UsageReportsV4 { * @constructor * @returns {GetResourceUsageOrgPager} */ - constructor( - client: UsageReportsV4, - params: UsageReportsV4.GetResourceUsageOrgParams - ) { + constructor(client: UsageReportsV4, params: UsageReportsV4.GetResourceUsageOrgParams) { if (params && params.start) { throw new Error(`the params.start field should not be set`); }