diff --git a/.cra/.cveignore b/.cra/.cveignore new file mode 100644 index 0000000..0712464 --- /dev/null +++ b/.cra/.cveignore @@ -0,0 +1,6 @@ +[ + { + "cve": "CVE-2021-3807", + "alwaysOmit": true + } +] \ No newline at end of file diff --git a/.eslintignore b/.eslintignore index 0aec804..1fc0723 100644 --- a/.eslintignore +++ b/.eslintignore @@ -4,12 +4,17 @@ doc/ coverage/ dist/ node_modules/ +examples/**/node_modules/ +!examples/**/*.js +example/*.js +examples/*.js example/**/node_modules/ -example/ +scripts/*.js test/resources/auth.js # ignore emitted js **/*v*.js !test/**/*.js +!examples/**/*.js lib/*.js -scripts/typedoc/ \ No newline at end of file +scripts/typedoc/ diff --git a/.eslintrc.js b/.eslintrc.js index d7b63ba..315079f 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,24 +1,54 @@ module.exports = { - "env": { - "node": true - }, - "plugins": [ - "node", - "prettier", + 'root': true, + 'overrides': [ + { + 'env': { + 'node': true, + }, + 'files': ['**/*.js', '**/*.jsx'], + 'plugins': ['node', 'jest', 'prettier'], + 'extends': ['airbnb-base', 'plugin:jest/recommended', 'plugin:jest/style', 'prettier'], + 'rules': { + 'camelcase': 'off', + 'import/extensions': 'off', + 'no-template-curly-in-string': 'off', + 'no-underscore-dangle': 'off', + 'prefer-const': 'error', + 'prettier/prettier': 'error', + }, + }, + { + 'files': ['*.test.js', '*.test.jsx'], + 'rules': { + 'jest/expect-expect': 'off', + 'jest/no-conditional-expect': 'off', + 'jest/no-done-callback': 'off', + 'jest/no-standalone-expect': 'off', + 'jest/no-try-expect': 'off', + 'no-unused-vars': 'off', + }, + }, + { + 'files': ['**/*.ts', '**/*.tsx'], + 'env': { + 'node': true, + }, + 'extends': ['airbnb-typescript/base', 'prettier'], + 'parser': '@typescript-eslint/parser', + 'parserOptions': { + 'project': 'tsconfig.json', + 'sourceType': 'module', + }, + 'plugins': ['eslint-plugin-jsdoc', 'eslint-plugin-import', '@typescript-eslint', 'prettier'], + 'rules': { + '@typescript-eslint/naming-convention': 'off', + '@typescript-eslint/no-unused-vars': 'off', + 'max-len': 'off', + 'no-param-reassign': 'off', + 'no-underscore-dangle': 'off', + 'prettier/prettier': 'error', + 'spaced-comment': ['error', 'always', { 'exceptions': ['*'] }], + }, + }, ], - "extends": [ - "eslint:recommended", - "google", - "plugin:node/recommended", - "prettier", - ], - "rules": { - "prettier/prettier": ["error", {"singleQuote": true, "printWidth": 100}], - "prefer-const": "error", - "prefer-rest-params": "off", // https://github.com/mysticatea/eslint-plugin-node/issues/63 - // The rest of these override rules that are enabled by one of the configs we extend but not compatible with current codebase - // todo: fix issues and then remove overrides here - "valid-jsdoc": "off", // too many issues; drowns out everything else - "camelcase": "off", // todo: determine if we should keep this off globally, or disable it on a per-line basis - } }; diff --git a/.gitattributes b/.gitattributes index 7d2b3cf..3bfcae6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -*.enc binary +*.enc binary \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 3cd8ad8..81f071a 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,7 +1,6 @@ ## PR summary -**Fixes:** ## PR Checklist Please make sure that your PR fulfills the following requirements: diff --git a/.gitignore b/.gitignore index b3aca2f..bb65adc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,4 @@ -# development guide ignores -swagger.json -openapi-sdkgen - +### Specific to this repository ### # tsc outputs lib/*.js auth/*.js @@ -9,7 +6,8 @@ auth/*.js **/*.js.map # service-specific tsc outputs (js files) -ibm-cloud-code-engine/*.js +example-service/*.js +# IGNORE YOUR SERVICE FILES HERE # file holding service credentials test/resources/auth.js @@ -86,3 +84,9 @@ secrets.tar # SDK generator .openapi-generator* + +.npmrc + +# ignore the generated integration test files, as they cannot be used without manual editing +test/integration/code-engine.v1.test.js +test/integration/code-engine.v2.test.js \ No newline at end of file diff --git a/.npmignore b/.npmignore index de016d6..7068af8 100644 --- a/.npmignore +++ b/.npmignore @@ -9,4 +9,3 @@ tslint.json .github *.ts !*.d.ts -example/ diff --git a/.npmrc_public b/.npmrc_public new file mode 100644 index 0000000..eede920 --- /dev/null +++ b/.npmrc_public @@ -0,0 +1 @@ +registry=https://registry.npmjs.com/ \ No newline at end of file diff --git a/.prettierrc.js b/.prettierrc.js index 414cf40..49a201a 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,5 +1,6 @@ module.exports = { - trailingComma: "es5", + semi: true, + trailingComma: 'es5', singleQuote: true, printWidth: 100, quoteProps: 'preserve', diff --git a/.releaserc b/.releaserc deleted file mode 100644 index 26448d3..0000000 --- a/.releaserc +++ /dev/null @@ -1,13 +0,0 @@ -{ - "branches": "main", - "verifyConditions": ["@semantic-release/changelog", "@semantic-release/npm", "@semantic-release/git"], - "prepare": ["@semantic-release/changelog", "@semantic-release/npm", "@semantic-release/git"], - "publish": [ - ["@semantic-release/npm", { - "pkgRoot": "dist" - }], - { - "path": "@semantic-release/github" - } - ] -} \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 23a976b..4cebae7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,38 +1,21 @@ -os: linux +dist: focal + language: node_js -sudo: false +node_js: + - 18 +cache: npm -# Only run on main (still tests PRs) branches: only: - main -node_js: -- 12 -- 14 - -# before_install: -# - 'openssl aes-256-cbc -K $my_key -iv $my_iv -in myservice.env.enc -out myservice.env -d || true' - -install: -- npm install -- npm run build - -script: -# - npm run lint -- npm run test-travis || travis_terminate 1 -- npm run check-packages -- ./test-integration.sh -# - sh scripts/typedoc/generate_typedoc.sh currently in progress - -after_success: -- npm run report-coverage - -# To enable semantic-release, uncomment this section. -deploy: -- provider: script - skip_cleanup: true - script: npx semantic-release - on: - node: 12 - branch: main +jobs: + include: + - stage: verify + install: + - npm install + script: + - npm run build + - npm run test-unit-travis || travis_terminate 1 + - npm run lint + - npm run check-packages diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 7303c87..01ca05c 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -55,7 +55,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at phil_adams@us.ibm.com. All +reported by contacting the project team at devxsdk@us.ibm.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8083001..76f466c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,10 +5,10 @@ please ask a question at # Issues If you encounter an issue with the SDK, you are welcome to submit -a [bug report](https://github.com/IBM/code-engine-node-sdk/issues). +a [bug report](/issues). Before that, please search for similar issues. It's possible someone has already encountered this issue. # General Information For general guidance on contributing to this project, please see -[this link](https://github.com/IBM/ibm-cloud-sdk-common/blob/master/CONTRIBUTING_nodejs.md) +[this link](https://github.com/IBM/ibm-cloud-sdk-common/blob/main/CONTRIBUTING_nodejs.md) diff --git a/README.md b/README.md index e609cd5..9e2ede4 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,6 @@ # NodeJS SDK for IBM Cloud Code Engine Node.js client library to interact with the [Code Engine API](https://cloud.ibm.com/apidocs/codeengine). -Disclaimer: this SDK is being released initially as a **pre-release** version. -Changes might occur which impact applications that use this SDK. - ## Table of Contents ~" README.md - GH_SLUG="$( sed 's~.*.com/~~' <<< "$PROJECT_GIT_URL" )" - sed -i.bak "s~CloudEngineering/node-sdk-template~${GH_SLUG}~g" README.md - sed -i.bak "s/node-sdk-template/${NPM_PACKAGE_NAME}/" README.md - - rm README.md.bak - printf "\n>>>>> README.md updated." - - sed -i.bak "s~~${PROJECT_GIT_URL}~" CONTRIBUTING.md - rm CONTRIBUTING.md.bak - printf "\n>>>>> CONTRIBUTING.md updated." - - printf "\n>>>>> Project Initialized Successfully!\n" -fi diff --git a/scripts/report_integration_test.js b/scripts/report_integration_test.js index 72ba290..a450dcb 100644 --- a/scripts/report_integration_test.js +++ b/scripts/report_integration_test.js @@ -12,22 +12,22 @@ const ansi_regex = new RegExp( 'g' ); -const failed_suits = test_ouput_json.testResults.filter(suite => suite.status === 'failed'); +const failed_suits = test_ouput_json.testResults.filter((suite) => suite.status === 'failed'); const errors = { service: [], test: [], }; -failed_suits.map(suite => { - const failed_tests = suite.assertionResults.filter(test => test.status === 'failed'); +failed_suits.map((suite) => { + const failed_tests = suite.assertionResults.filter((test) => test.status === 'failed'); const error_suite = { name: suite.name.split('node-sdk/test')[1], service: [], test: [], }; - failed_tests.map(result => { + failed_tests.map((result) => { const message_clean = result.failureMessages.join('\n').replace(ansi_regex, ''); error_suite[message_clean.indexOf(/^Received: 5/m) > 0 ? 'service' : 'test'].push( `${result.fullName}\n${message_clean}` @@ -53,7 +53,7 @@ if (process.env.TRAVIS_PULL_REQUEST && process.env.TRAVIS_PULL_REQUEST !== 'fals .post( `https://api.github.com/repos/${process.env.TRAVIS_REPO_SLUG}/issues/${process.env.TRAVIS_PULL_REQUEST}/comments`, { - body: body, + body, }, { headers: { @@ -62,7 +62,7 @@ if (process.env.TRAVIS_PULL_REQUEST && process.env.TRAVIS_PULL_REQUEST !== 'fals }, } ) - .catch(error => { + .catch((error) => { console.error(error); // eslint-disable-line }) .then(() => { diff --git a/test/integration/v1.test.js b/test/integration/v1.test.js new file mode 100644 index 0000000..a8d7d26 --- /dev/null +++ b/test/integration/v1.test.js @@ -0,0 +1,60 @@ +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable no-console */ + +const { readExternalSources } = require('ibm-cloud-sdk-core'); +const CodeEngineV1 = require('../../dist/ibm-cloud-code-engine/v1'); +const authHelper = require('../resources/auth-helper.js'); + +// testcase timeout value (200s). +const timeout = 200000; + +// Location of our config file. +const configFile = 'code_engine_v1.env'; + +const describe = authHelper.prepareTests(configFile); + +describe('CodeEngineV1_integration', () => { + jest.setTimeout(timeout); + + // Service instance + let codeEngineService; + + test('Initialize service', async () => { + codeEngineService = CodeEngineV1.newInstance(); + + expect(codeEngineService).not.toBeNull(); + + const config = readExternalSources(CodeEngineV1.DEFAULT_SERVICE_NAME); + expect(config).not.toBeNull(); + + codeEngineService.enableRetries(); + }); + + test('projectConfigGet()', async () => { + const params = { + xDelegatedRefreshToken: 'testString', + projectGuid: 'testString', + endpoint: 'testString', + }; + + const res = await codeEngineService.projectConfigGet(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); +}); diff --git a/test/integration/v2.test.js b/test/integration/v2.test.js new file mode 100644 index 0000000..909b9ff --- /dev/null +++ b/test/integration/v2.test.js @@ -0,0 +1,1013 @@ +/* eslint-disable no-plusplus */ +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable no-console */ +/* eslint-disable no-await-in-loop */ + +const { readExternalSources } = require('ibm-cloud-sdk-core'); +const CodeEngineV2 = require('../../dist/code-engine/v2'); +const authHelper = require('../resources/auth-helper.js'); + +// testcase timeout value (200s). +const timeout = 200000; + +// Location of our config file. +const configFile = 'code_engine_v2.env'; + +const describe = authHelper.prepareTests(configFile); + +// the e2e default project +let e2eTestProjectId; + +// helper function to allow the code to wait for a while +function sleep(time) { + return new Promise((resolve) => setTimeout(resolve, time)); +} + +describe('CodeEngineV2_integration', () => { + jest.setTimeout(timeout); + + // Service instance + let codeEngineService; + + test('Initialize service', async () => { + codeEngineService = CodeEngineV2.newInstance(); + + expect(codeEngineService).not.toBeNull(); + + const config = readExternalSources(CodeEngineV2.DEFAULT_SERVICE_NAME); + expect(config).not.toBeNull(); + + codeEngineService.enableRetries(); + }); + + test('listProjects()', async () => { + const params = { + limit: 100, + start: 'testString', + }; + + const res = await codeEngineService.listProjects(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listProjects() via ProjectsPager', async () => { + const params = { + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.ProjectsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.ProjectsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createProject()', async () => { + const params = { + name: `sdk-e2e-node-${Date.now()}`, + tags: ['testString'], + }; + + const res = await codeEngineService.createProject(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + e2eTestProjectId = res.result.id; + console.log(`Created project ${e2eTestProjectId}`); + }); + + test('getProject()', async () => { + const params = { + id: e2eTestProjectId, + }; + + const res = await codeEngineService.getProject(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + + // + // Assume that the project creation takes some time + const times = 20; + let obtainedProject; + for (let i = 0; i < times; i++) { + await sleep(10000); + try { + const projRes = await codeEngineService.getProject({ + id: e2eTestProjectId, + }); + obtainedProject = projRes.result; + console.info( + `Obtained status of project '${obtainedProject.name}' (guid: '${obtainedProject.id}'): ${obtainedProject.status}.` + ); + if (obtainedProject.status === 'active') { + break; + } + } catch (err) { + console.warn(`Failed to obtain project`, err); + throw err; + } + } + expect(obtainedProject.status).toBe('active'); + }); + + test('listApps()', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const res = await codeEngineService.listApps(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listApps() via AppsPager', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.AppsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.AppsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createApp()', async () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + const params = { + projectId: e2eTestProjectId, + imageReference: 'icr.io/codeengine/helloworld', + name: 'my-app', + imagePort: 8080, + imageSecret: 'my-secret', + managedDomainMappings: 'local_public', + runArguments: ['testString'], + runAsUser: 1001, + runCommands: ['testString'], + runEnvVariables: [envVarPrototypeModel], + runServiceAccount: 'default', + runVolumeMounts: [volumeMountPrototypeModel], + scaleConcurrency: 100, + scaleConcurrencyTarget: 80, + scaleCpuLimit: '1', + scaleEphemeralStorageLimit: '4G', + scaleInitialInstances: 1, + scaleMaxInstances: 10, + scaleMemoryLimit: '4G', + scaleMinInstances: 0, + scaleRequestTimeout: 300, + }; + + const res = await codeEngineService.createApp(params); + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + }); + + test('getApp()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-app', + }; + + const res = await codeEngineService.getApp(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('updateApp()', async () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + const params = { + projectId: e2eTestProjectId, + name: 'my-app', + ifMatch: '*', + imagePort: 8080, + imageReference: 'icr.io/codeengine/helloworld', + imageSecret: 'my-secret', + managedDomainMappings: 'local_public', + runArguments: ['testString'], + runAsUser: 1001, + runCommands: ['testString'], + runEnvVariables: [envVarPrototypeModel], + runServiceAccount: 'default', + runVolumeMounts: [volumeMountPrototypeModel], + scaleConcurrency: 100, + scaleConcurrencyTarget: 80, + scaleCpuLimit: '1', + scaleEphemeralStorageLimit: '4G', + scaleInitialInstances: 1, + scaleMaxInstances: 10, + scaleMemoryLimit: '4G', + scaleMinInstances: 0, + scaleRequestTimeout: 300, + }; + + const res = await codeEngineService.updateApp(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listAppRevisions()', async () => { + const params = { + projectId: e2eTestProjectId, + appName: 'my-app', + limit: 100, + }; + + const res = await codeEngineService.listAppRevisions(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listAppRevisions() via AppRevisionsPager', async () => { + const params = { + projectId: e2eTestProjectId, + appName: 'my-app', + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.AppRevisionsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.AppRevisionsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('getAppRevision()', async () => { + const params = { + projectId: e2eTestProjectId, + appName: 'my-app', + name: 'my-app-00001', + }; + + const res = await codeEngineService.getAppRevision(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listJobs()', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const res = await codeEngineService.listJobs(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listJobs() via JobsPager', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.JobsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.JobsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createJob()', async () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + const params = { + projectId: e2eTestProjectId, + imageReference: 'icr.io/codeengine/helloworld', + name: 'my-job', + imageSecret: 'my-secret', + runArguments: ['testString'], + runAsUser: 1001, + runCommands: ['testString'], + runEnvVariables: [envVarPrototypeModel], + runMode: 'task', + runServiceAccount: 'default', + runVolumeMounts: [volumeMountPrototypeModel], + scaleArraySpec: '1-5,7-8,10', + scaleCpuLimit: '1', + scaleEphemeralStorageLimit: '4G', + scaleMaxExecutionTime: 7200, + scaleMemoryLimit: '4G', + scaleRetryLimit: 3, + }; + + const res = await codeEngineService.createJob(params); + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + }); + + test('getJob()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-job', + }; + + const res = await codeEngineService.getJob(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('updateJob()', async () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + const params = { + projectId: e2eTestProjectId, + name: 'my-job', + ifMatch: '*', + imageReference: 'icr.io/codeengine/helloworld', + imageSecret: 'my-secret', + runArguments: ['testString'], + runAsUser: 1001, + runCommands: ['testString'], + runEnvVariables: [envVarPrototypeModel], + runMode: 'task', + runServiceAccount: 'default', + runVolumeMounts: [volumeMountPrototypeModel], + scaleArraySpec: '1-5,7-8,10', + scaleCpuLimit: '1', + scaleEphemeralStorageLimit: '4G', + scaleMaxExecutionTime: 7200, + scaleMemoryLimit: '4G', + scaleRetryLimit: 3, + }; + + const res = await codeEngineService.updateJob(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listJobRuns()', async () => { + const params = { + projectId: e2eTestProjectId, + jobName: 'my-job', + limit: 100, + }; + + const res = await codeEngineService.listJobRuns(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listJobRuns() via JobRunsPager', async () => { + const params = { + projectId: e2eTestProjectId, + jobName: 'my-job', + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.JobRunsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.JobRunsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createJobRun()', async () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + const params = { + projectId: e2eTestProjectId, + imageReference: 'icr.io/codeengine/helloworld', + imageSecret: 'my-secret', + name: 'my-job-run', + runArguments: ['testString'], + runAsUser: 1001, + runCommands: ['testString'], + runEnvVariables: [envVarPrototypeModel], + runMode: 'task', + runServiceAccount: 'default', + runVolumeMounts: [volumeMountPrototypeModel], + scaleArraySpec: '1-5,7-8,10', + scaleCpuLimit: '1', + scaleEphemeralStorageLimit: '4G', + scaleMaxExecutionTime: 7200, + scaleMemoryLimit: '4G', + scaleRetryLimit: 3, + }; + + const res = await codeEngineService.createJobRun(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('getJobRun()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-job-run', + }; + + const res = await codeEngineService.getJobRun(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listBuilds()', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const res = await codeEngineService.listBuilds(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listBuilds() via BuildsPager', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.BuildsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.BuildsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createBuild()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-build', + outputImage: 'private.de.icr.io/icr_namespace/image-name', + outputSecret: 'ce-auto-icr-private-eu-de', + sourceUrl: 'https://github.com/IBM/CodeEngine', + strategyType: 'dockerfile', + sourceContextDir: 'some/subfolder', + sourceRevision: 'main', + sourceSecret: 'my-secret', + sourceType: 'git', + strategySize: 'medium', + strategySpecFile: 'Dockerfile', + timeout: 600, + }; + + const res = await codeEngineService.createBuild(params); + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + }); + + test('getBuild()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-build', + }; + + const res = await codeEngineService.getBuild(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('updateBuild()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-build', + ifMatch: '*', + outputImage: 'private.de.icr.io/icr_namespace/image-name', + outputSecret: 'ce-auto-icr-private-eu-de', + sourceContextDir: 'some/subfolder', + sourceRevision: 'main', + sourceSecret: 'my-secret', + sourceType: 'git', + sourceUrl: 'https://github.com/IBM/CodeEngine', + strategySize: 'medium', + strategySpecFile: 'Dockerfile', + strategyType: 'dockerfile', + timeout: 600, + }; + + const res = await codeEngineService.updateBuild(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listBuildRuns()', async () => { + const params = { + projectId: e2eTestProjectId, + buildName: 'my-build', + limit: 100, + }; + + const res = await codeEngineService.listBuildRuns(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listBuildRuns() via BuildRunsPager', async () => { + const params = { + projectId: e2eTestProjectId, + buildName: 'my-build', + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.BuildRunsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.BuildRunsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createBuildRun()', async () => { + const params = { + projectId: e2eTestProjectId, + buildName: 'my-build', + name: 'my-build-run', + outputImage: 'private.de.icr.io/icr_namespace/image-name', + outputSecret: 'ce-auto-icr-private-eu-de', + serviceAccount: 'default', + sourceContextDir: 'some/subfolder', + sourceRevision: 'main', + sourceSecret: 'my-secret', + sourceType: 'git', + sourceUrl: 'https://github.com/IBM/CodeEngine', + strategySize: 'medium', + strategySpecFile: 'Dockerfile', + strategyType: 'dockerfile', + timeout: 600, + }; + + const res = await codeEngineService.createBuildRun(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('getBuildRun()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-build-run', + }; + + const res = await codeEngineService.getBuildRun(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listConfigMaps()', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const res = await codeEngineService.listConfigMaps(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listConfigMaps() via ConfigMapsPager', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.ConfigMapsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.ConfigMapsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createConfigMap()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-config-map', + data: { 'key1': 'testString' }, + }; + + const res = await codeEngineService.createConfigMap(params); + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + }); + + test('getConfigMap()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-config-map', + }; + + const res = await codeEngineService.getConfigMap(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('replaceConfigMap()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-config-map', + ifMatch: '*', + data: { 'key1': 'testString' }, + }; + + const res = await codeEngineService.replaceConfigMap(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listSecrets()', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const res = await codeEngineService.listSecrets(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('listSecrets() via SecretsPager', async () => { + const params = { + projectId: e2eTestProjectId, + limit: 100, + }; + + const allResults = []; + + // Test getNext(). + let pager = new CodeEngineV2.SecretsPager(codeEngineService, params); + while (pager.hasNext()) { + const nextPage = await pager.getNext(); + expect(nextPage).not.toBeNull(); + allResults.push(...nextPage); + } + + // Test getAll(). + pager = new CodeEngineV2.SecretsPager(codeEngineService, params); + const allItems = await pager.getAll(); + expect(allItems).not.toBeNull(); + expect(allItems).toHaveLength(allResults.length); + console.log(`Retrieved a total of ${allResults.length} items(s) with pagination.`); + }); + + test('createSecret()', async () => { + const params = { + projectId: e2eTestProjectId, + format: 'generic', + name: 'my-secret', + data: { 'key1': 'testString' }, + }; + + const res = await codeEngineService.createSecret(params); + expect(res).toBeDefined(); + expect(res.status).toBe(201); + expect(res.result).toBeDefined(); + }); + + test('getSecret()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-secret', + }; + + const res = await codeEngineService.getSecret(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('replaceSecret()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-secret', + ifMatch: '*', + data: { 'key1': 'testString' }, + format: 'generic', + }; + + const res = await codeEngineService.replaceSecret(params); + expect(res).toBeDefined(); + expect(res.status).toBe(200); + expect(res.result).toBeDefined(); + }); + + test('deleteAppRevision()', async () => { + const params = { + projectId: e2eTestProjectId, + appName: 'my-app', + name: 'my-app-00001', + }; + + const res = await codeEngineService.deleteAppRevision(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteApp()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-app', + }; + + const res = await codeEngineService.deleteApp(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteJobRun()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-job-run', + }; + + const res = await codeEngineService.deleteJobRun(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteJob()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-job', + }; + + const res = await codeEngineService.deleteJob(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteBuild()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-build', + }; + + const res = await codeEngineService.deleteBuild(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteBuildRun()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-build-run', + }; + + const res = await codeEngineService.deleteBuildRun(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteConfigMap()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-config-map', + }; + + const res = await codeEngineService.deleteConfigMap(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteSecret()', async () => { + const params = { + projectId: e2eTestProjectId, + name: 'my-secret', + }; + + const res = await codeEngineService.deleteSecret(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); + + test('deleteProject()', async () => { + const params = { + id: e2eTestProjectId, + }; + + const res = await codeEngineService.deleteProject(params); + expect(res).toBeDefined(); + expect(res.status).toBe(202); + expect(res.result).toBeDefined(); + }); +}); diff --git a/test/resources/auth-helper.js b/test/resources/auth-helper.js index a6ee2e2..0c23947 100644 --- a/test/resources/auth-helper.js +++ b/test/resources/auth-helper.js @@ -14,8 +14,6 @@ * limitations under the License. */ -'use strict'; - const fs = require('fs'); const dotenv = require('dotenv'); @@ -30,7 +28,7 @@ let configFileExists; // `filename` is the location of the credentials file // returns the appropriate "describe" to be used for the tests. -module.exports.prepareTests = filename => { +module.exports.prepareTests = (filename) => { // Save off the name of the config file. configFilename = filename; @@ -50,9 +48,7 @@ module.exports.prepareTests = filename => { return describeToUse; }; -module.exports.getDescribe = () => { - return describeToUse; -}; +module.exports.getDescribe = () => describeToUse; // This function will load the contents of "configFilename" and // set the properties as environment variables. diff --git a/test/unit/code-engine.v2.test.js b/test/unit/code-engine.v2.test.js new file mode 100644 index 0000000..ddb170f --- /dev/null +++ b/test/unit/code-engine.v2.test.js @@ -0,0 +1,4672 @@ +/** + * (C) Copyright IBM Corp. 2023. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// need to import the whole package to mock getAuthenticatorFromEnvironment +const core = require('ibm-cloud-sdk-core'); + +const { NoAuthAuthenticator, unitTestUtils } = core; + +const nock = require('nock'); +const CodeEngineV2 = require('../../dist/code-engine/v2'); + +/* eslint-disable no-await-in-loop */ + +const { + getOptions, + checkUrlAndMethod, + checkMediaHeaders, + expectToBePromise, + checkUserHeader, + checkForSuccessfulExecution, +} = unitTestUtils; + +const codeEngineServiceOptions = { + authenticator: new NoAuthAuthenticator(), + url: 'https://api.au-syd.codeengine.cloud.ibm.com/v2', +}; + +const codeEngineService = new CodeEngineV2(codeEngineServiceOptions); + +let createRequestMock = null; +function mock_createRequest() { + if (!createRequestMock) { + createRequestMock = jest.spyOn(codeEngineService, '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()); + +describe('CodeEngineV2', () => { + beforeEach(() => { + mock_createRequest(); + }); + + afterEach(() => { + if (createRequestMock) { + createRequestMock.mockClear(); + } + getAuthenticatorMock.mockClear(); + }); + + describe('the newInstance method', () => { + test('should use defaults when options not provided', () => { + const testInstance = CodeEngineV2.newInstance(); + + expect(getAuthenticatorMock).toHaveBeenCalled(); + expect(testInstance.baseOptions.authenticator).toBeInstanceOf(NoAuthAuthenticator); + expect(testInstance.baseOptions.serviceName).toBe(CodeEngineV2.DEFAULT_SERVICE_NAME); + expect(testInstance.baseOptions.serviceUrl).toBe(CodeEngineV2.DEFAULT_SERVICE_URL); + expect(testInstance).toBeInstanceOf(CodeEngineV2); + }); + + test('should set serviceName, serviceUrl, and authenticator when provided', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + serviceUrl: 'custom.com', + serviceName: 'my-service', + }; + + const testInstance = CodeEngineV2.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(CodeEngineV2); + }); + }); + + describe('the constructor', () => { + test('use user-given service url', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + serviceUrl: 'custom.com', + }; + + const testInstance = new CodeEngineV2(options); + + expect(testInstance.baseOptions.serviceUrl).toBe('custom.com'); + }); + + test('use default service url', () => { + const options = { + authenticator: new NoAuthAuthenticator(), + }; + + const testInstance = new CodeEngineV2(options); + + expect(testInstance.baseOptions.serviceUrl).toBe(CodeEngineV2.DEFAULT_SERVICE_URL); + }); + }); + + describe('listProjects', () => { + describe('positive tests', () => { + function __listProjectsTest() { + // Construct the params object for operation listProjects + const limit = 100; + const start = 'testString'; + const listProjectsParams = { + limit, + start, + }; + + const listProjectsResult = codeEngineService.listProjects(listProjectsParams); + + // all methods should return a Promise + expectToBePromise(listProjectsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listProjectsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listProjectsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listProjectsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listProjectsParams = { + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listProjects(listProjectsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + + test('should not have any problems when no parameters are passed in', () => { + // invoke the method with no parameters + codeEngineService.listProjects({}); + checkForSuccessfulExecution(createRequestMock); + }); + }); + + describe('ProjectsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"projects":[{"account_id":"4329073d16d2f3663f74bfa955259139","created_at":"2021-03-29T12:18:13.992359829Z","crn":"crn:v1:bluemix:public:codeengine:eu-de:a/4329073d16d2f3663f74bfa955259139:4e49b3e0-27a8-48d2-a784-c7ee48bb863b::","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b","id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","name":"project-name","region":"us-east","resource_group_id":"5c49eabcf5e85881a37e2d100a33b3df","resource_type":"project_v2","status":"active"}],"total_count":2,"limit":1}'; + const mockPagerResponse2 = + '{"projects":[{"account_id":"4329073d16d2f3663f74bfa955259139","created_at":"2021-03-29T12:18:13.992359829Z","crn":"crn:v1:bluemix:public:codeengine:eu-de:a/4329073d16d2f3663f74bfa955259139:4e49b3e0-27a8-48d2-a784-c7ee48bb863b::","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b","id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","name":"project-name","region":"us-east","resource_group_id":"5c49eabcf5e85881a37e2d100a33b3df","resource_type":"project_v2","status":"active"}],"total_count":2,"limit":1}'; + + 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 = { + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.ProjectsPager(codeEngineService, 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 = { + limit: 100, + }; + const pager = new CodeEngineV2.ProjectsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createProject', () => { + describe('positive tests', () => { + function __createProjectTest() { + // Construct the params object for operation createProject + const name = 'my-project'; + const resourceGroupId = 'b91e849cedb04e7e92bd68c040c672dc'; + const tags = ['testString']; + const createProjectParams = { + name, + resourceGroupId, + tags, + }; + + const createProjectResult = codeEngineService.createProject(createProjectParams); + + // all methods should return a Promise + expectToBePromise(createProjectResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.resource_group_id).toEqual(resourceGroupId); + expect(mockRequestOptions.body.tags).toEqual(tags); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createProjectTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createProjectTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createProjectTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const name = 'my-project'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createProjectParams = { + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createProject(createProjectParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createProject({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createProject(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getProject', () => { + describe('positive tests', () => { + function __getProjectTest() { + // Construct the params object for operation getProject + const id = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const getProjectParams = { + id, + }; + + const getProjectResult = codeEngineService.getProject(getProjectParams); + + // all methods should return a Promise + expectToBePromise(getProjectResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{id}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.id).toEqual(id); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getProjectTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getProjectTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getProjectTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const id = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getProjectParams = { + id, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getProject(getProjectParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getProject({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getProject(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteProject', () => { + describe('positive tests', () => { + function __deleteProjectTest() { + // Construct the params object for operation deleteProject + const id = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const deleteProjectParams = { + id, + }; + + const deleteProjectResult = codeEngineService.deleteProject(deleteProjectParams); + + // all methods should return a Promise + expectToBePromise(deleteProjectResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{id}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.id).toEqual(id); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteProjectTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteProjectTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteProjectTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const id = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteProjectParams = { + id, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteProject(deleteProjectParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteProject({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteProject(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listApps', () => { + describe('positive tests', () => { + function __listAppsTest() { + // Construct the params object for operation listApps + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const limit = 100; + const start = 'testString'; + const listAppsParams = { + projectId, + limit, + start, + }; + + const listAppsResult = codeEngineService.listApps(listAppsParams); + + // all methods should return a Promise + expectToBePromise(listAppsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/apps', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listAppsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listAppsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listAppsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listAppsParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listApps(listAppsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listApps({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listApps(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('AppsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/apps'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"total_count":2,"limit":1,"apps":[{"created_at":"2022-09-13T11:41:35+02:00","endpoint":"https://my-app.vg67hzldruk.eu-de.codeengine.appdomain.cloud","endpoint_internal":"http://my-app.vg67hzldruk.svc.cluster.local","entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/apps/my-app","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_port":8080,"image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","managed_domain_mappings":"local_public","name":"my-app","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"app_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_concurrency":100,"scale_concurrency_target":80,"scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_initial_instances":1,"scale_max_instances":10,"scale_memory_limit":"4G","scale_min_instances":1,"scale_request_timeout":300,"status":"ready","status_details":{"latest_created_revision":"my-app-00001","latest_ready_revision":"my-app-00001","reason":"ready"}}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"apps":[{"created_at":"2022-09-13T11:41:35+02:00","endpoint":"https://my-app.vg67hzldruk.eu-de.codeengine.appdomain.cloud","endpoint_internal":"http://my-app.vg67hzldruk.svc.cluster.local","entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/apps/my-app","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_port":8080,"image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","managed_domain_mappings":"local_public","name":"my-app","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"app_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_concurrency":100,"scale_concurrency_target":80,"scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_initial_instances":1,"scale_max_instances":10,"scale_memory_limit":"4G","scale_min_instances":1,"scale_request_timeout":300,"status":"ready","status_details":{"latest_created_revision":"my-app-00001","latest_ready_revision":"my-app-00001","reason":"ready"}}]}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.AppsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const pager = new CodeEngineV2.AppsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createApp', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + function __createAppTest() { + // Construct the params object for operation createApp + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const imageReference = 'icr.io/codeengine/helloworld'; + const name = 'my-app'; + const imagePort = 8080; + const imageSecret = 'my-secret'; + const managedDomainMappings = 'local_public'; + const runArguments = ['testString']; + const runAsUser = 1001; + const runCommands = ['testString']; + const runEnvVariables = [envVarPrototypeModel]; + const runServiceAccount = 'default'; + const runVolumeMounts = [volumeMountPrototypeModel]; + const scaleConcurrency = 100; + const scaleConcurrencyTarget = 80; + const scaleCpuLimit = '1'; + const scaleEphemeralStorageLimit = '4G'; + const scaleInitialInstances = 1; + const scaleMaxInstances = 10; + const scaleMemoryLimit = '4G'; + const scaleMinInstances = 1; + const scaleRequestTimeout = 300; + const createAppParams = { + projectId, + imageReference, + name, + imagePort, + imageSecret, + managedDomainMappings, + runArguments, + runAsUser, + runCommands, + runEnvVariables, + runServiceAccount, + runVolumeMounts, + scaleConcurrency, + scaleConcurrencyTarget, + scaleCpuLimit, + scaleEphemeralStorageLimit, + scaleInitialInstances, + scaleMaxInstances, + scaleMemoryLimit, + scaleMinInstances, + scaleRequestTimeout, + }; + + const createAppResult = codeEngineService.createApp(createAppParams); + + // all methods should return a Promise + expectToBePromise(createAppResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/apps', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.image_reference).toEqual(imageReference); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.image_port).toEqual(imagePort); + expect(mockRequestOptions.body.image_secret).toEqual(imageSecret); + expect(mockRequestOptions.body.managed_domain_mappings).toEqual(managedDomainMappings); + expect(mockRequestOptions.body.run_arguments).toEqual(runArguments); + expect(mockRequestOptions.body.run_as_user).toEqual(runAsUser); + expect(mockRequestOptions.body.run_commands).toEqual(runCommands); + expect(mockRequestOptions.body.run_env_variables).toEqual(runEnvVariables); + expect(mockRequestOptions.body.run_service_account).toEqual(runServiceAccount); + expect(mockRequestOptions.body.run_volume_mounts).toEqual(runVolumeMounts); + expect(mockRequestOptions.body.scale_concurrency).toEqual(scaleConcurrency); + expect(mockRequestOptions.body.scale_concurrency_target).toEqual(scaleConcurrencyTarget); + expect(mockRequestOptions.body.scale_cpu_limit).toEqual(scaleCpuLimit); + expect(mockRequestOptions.body.scale_ephemeral_storage_limit).toEqual( + scaleEphemeralStorageLimit + ); + expect(mockRequestOptions.body.scale_initial_instances).toEqual(scaleInitialInstances); + expect(mockRequestOptions.body.scale_max_instances).toEqual(scaleMaxInstances); + expect(mockRequestOptions.body.scale_memory_limit).toEqual(scaleMemoryLimit); + expect(mockRequestOptions.body.scale_min_instances).toEqual(scaleMinInstances); + expect(mockRequestOptions.body.scale_request_timeout).toEqual(scaleRequestTimeout); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createAppTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createAppTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createAppTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const imageReference = 'icr.io/codeengine/helloworld'; + const name = 'my-app'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createAppParams = { + projectId, + imageReference, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createApp(createAppParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createApp({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createApp(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getApp', () => { + describe('positive tests', () => { + function __getAppTest() { + // Construct the params object for operation getApp + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-app'; + const getAppParams = { + projectId, + name, + }; + + const getAppResult = codeEngineService.getApp(getAppParams); + + // all methods should return a Promise + expectToBePromise(getAppResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/apps/{name}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getAppTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getAppTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getAppTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-app'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getAppParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getApp(getAppParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getApp({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getApp(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteApp', () => { + describe('positive tests', () => { + function __deleteAppTest() { + // Construct the params object for operation deleteApp + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-app'; + const deleteAppParams = { + projectId, + name, + }; + + const deleteAppResult = codeEngineService.deleteApp(deleteAppParams); + + // all methods should return a Promise + expectToBePromise(deleteAppResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/apps/{name}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteAppTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteAppTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteAppTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-app'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteAppParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteApp(deleteAppParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteApp({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteApp(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('updateApp', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + function __updateAppTest() { + // Construct the params object for operation updateApp + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-app'; + const ifMatch = 'testString'; + const imagePort = 8080; + const imageReference = 'icr.io/codeengine/helloworld'; + const imageSecret = 'my-secret'; + const managedDomainMappings = 'local_public'; + const runArguments = ['testString']; + const runAsUser = 1001; + const runCommands = ['testString']; + const runEnvVariables = [envVarPrototypeModel]; + const runServiceAccount = 'default'; + const runVolumeMounts = [volumeMountPrototypeModel]; + const scaleConcurrency = 100; + const scaleConcurrencyTarget = 80; + const scaleCpuLimit = '1'; + const scaleEphemeralStorageLimit = '4G'; + const scaleInitialInstances = 1; + const scaleMaxInstances = 10; + const scaleMemoryLimit = '4G'; + const scaleMinInstances = 1; + const scaleRequestTimeout = 300; + const updateAppParams = { + projectId, + name, + ifMatch, + imagePort, + imageReference, + imageSecret, + managedDomainMappings, + runArguments, + runAsUser, + runCommands, + runEnvVariables, + runServiceAccount, + runVolumeMounts, + scaleConcurrency, + scaleConcurrencyTarget, + scaleCpuLimit, + scaleEphemeralStorageLimit, + scaleInitialInstances, + scaleMaxInstances, + scaleMemoryLimit, + scaleMinInstances, + scaleRequestTimeout, + }; + + const updateAppResult = codeEngineService.updateApp(updateAppParams); + + // all methods should return a Promise + expectToBePromise(updateAppResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/apps/{name}', 'PATCH'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/merge-patch+json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + expect(mockRequestOptions.body.image_port).toEqual(imagePort); + expect(mockRequestOptions.body.image_reference).toEqual(imageReference); + expect(mockRequestOptions.body.image_secret).toEqual(imageSecret); + expect(mockRequestOptions.body.managed_domain_mappings).toEqual(managedDomainMappings); + expect(mockRequestOptions.body.run_arguments).toEqual(runArguments); + expect(mockRequestOptions.body.run_as_user).toEqual(runAsUser); + expect(mockRequestOptions.body.run_commands).toEqual(runCommands); + expect(mockRequestOptions.body.run_env_variables).toEqual(runEnvVariables); + expect(mockRequestOptions.body.run_service_account).toEqual(runServiceAccount); + expect(mockRequestOptions.body.run_volume_mounts).toEqual(runVolumeMounts); + expect(mockRequestOptions.body.scale_concurrency).toEqual(scaleConcurrency); + expect(mockRequestOptions.body.scale_concurrency_target).toEqual(scaleConcurrencyTarget); + expect(mockRequestOptions.body.scale_cpu_limit).toEqual(scaleCpuLimit); + expect(mockRequestOptions.body.scale_ephemeral_storage_limit).toEqual( + scaleEphemeralStorageLimit + ); + expect(mockRequestOptions.body.scale_initial_instances).toEqual(scaleInitialInstances); + expect(mockRequestOptions.body.scale_max_instances).toEqual(scaleMaxInstances); + expect(mockRequestOptions.body.scale_memory_limit).toEqual(scaleMemoryLimit); + expect(mockRequestOptions.body.scale_min_instances).toEqual(scaleMinInstances); + expect(mockRequestOptions.body.scale_request_timeout).toEqual(scaleRequestTimeout); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __updateAppTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __updateAppTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __updateAppTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-app'; + const ifMatch = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const updateAppParams = { + projectId, + name, + ifMatch, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.updateApp(updateAppParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.updateApp({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.updateApp(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listAppRevisions', () => { + describe('positive tests', () => { + function __listAppRevisionsTest() { + // Construct the params object for operation listAppRevisions + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const appName = 'my-app'; + const limit = 100; + const start = 'testString'; + const listAppRevisionsParams = { + projectId, + appName, + limit, + start, + }; + + const listAppRevisionsResult = codeEngineService.listAppRevisions(listAppRevisionsParams); + + // all methods should return a Promise + expectToBePromise(listAppRevisionsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod( + mockRequestOptions, + '/projects/{project_id}/apps/{app_name}/revisions', + 'GET' + ); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.app_name).toEqual(appName); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listAppRevisionsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listAppRevisionsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listAppRevisionsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const appName = 'my-app'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listAppRevisionsParams = { + projectId, + appName, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listAppRevisions(listAppRevisionsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listAppRevisions({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listAppRevisions(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('AppRevisionsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/apps/my-app/revisions'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"total_count":2,"limit":1,"revisions":[{"app_name":"my-app","created_at":"2022-09-13T11:41:35+02:00","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/apps/my-app/revisions/my-app-00001","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_port":8080,"image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","name":"my-app-00001","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"app_revision_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_concurrency":100,"scale_concurrency_target":80,"scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_initial_instances":1,"scale_max_instances":10,"scale_memory_limit":"4G","scale_min_instances":1,"scale_request_timeout":300,"status":"ready","status_details":{"actual_instances":1,"reason":"ready"}}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"revisions":[{"app_name":"my-app","created_at":"2022-09-13T11:41:35+02:00","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/apps/my-app/revisions/my-app-00001","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_port":8080,"image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","name":"my-app-00001","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"app_revision_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_concurrency":100,"scale_concurrency_target":80,"scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_initial_instances":1,"scale_max_instances":10,"scale_memory_limit":"4G","scale_min_instances":1,"scale_request_timeout":300,"status":"ready","status_details":{"actual_instances":1,"reason":"ready"}}]}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + appName: 'my-app', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.AppRevisionsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + appName: 'my-app', + limit: 100, + }; + const pager = new CodeEngineV2.AppRevisionsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('getAppRevision', () => { + describe('positive tests', () => { + function __getAppRevisionTest() { + // Construct the params object for operation getAppRevision + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const appName = 'my-app'; + const name = 'my-app-001'; + const getAppRevisionParams = { + projectId, + appName, + name, + }; + + const getAppRevisionResult = codeEngineService.getAppRevision(getAppRevisionParams); + + // all methods should return a Promise + expectToBePromise(getAppRevisionResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod( + mockRequestOptions, + '/projects/{project_id}/apps/{app_name}/revisions/{name}', + 'GET' + ); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.app_name).toEqual(appName); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getAppRevisionTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getAppRevisionTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getAppRevisionTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const appName = 'my-app'; + const name = 'my-app-001'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getAppRevisionParams = { + projectId, + appName, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getAppRevision(getAppRevisionParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getAppRevision({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getAppRevision(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteAppRevision', () => { + describe('positive tests', () => { + function __deleteAppRevisionTest() { + // Construct the params object for operation deleteAppRevision + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const appName = 'my-app'; + const name = 'my-app-001'; + const deleteAppRevisionParams = { + projectId, + appName, + name, + }; + + const deleteAppRevisionResult = + codeEngineService.deleteAppRevision(deleteAppRevisionParams); + + // all methods should return a Promise + expectToBePromise(deleteAppRevisionResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod( + mockRequestOptions, + '/projects/{project_id}/apps/{app_name}/revisions/{name}', + 'DELETE' + ); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.app_name).toEqual(appName); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteAppRevisionTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteAppRevisionTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteAppRevisionTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const appName = 'my-app'; + const name = 'my-app-001'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteAppRevisionParams = { + projectId, + appName, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteAppRevision(deleteAppRevisionParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteAppRevision({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteAppRevision(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listJobs', () => { + describe('positive tests', () => { + function __listJobsTest() { + // Construct the params object for operation listJobs + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const limit = 100; + const start = 'testString'; + const listJobsParams = { + projectId, + limit, + start, + }; + + const listJobsResult = codeEngineService.listJobs(listJobsParams); + + // all methods should return a Promise + expectToBePromise(listJobsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/jobs', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listJobsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listJobsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listJobsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listJobsParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listJobs(listJobsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listJobs({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listJobs(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('JobsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/jobs'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"total_count":2,"jobs":[{"created_at":"2022-09-13T11:41:35+02:00","entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/jobs/my-job","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","name":"my-job","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"job_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_mode":"daemon","run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_array_spec":"1-5,7-8,10","scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_max_execution_time":7200,"scale_memory_limit":"4G","scale_retry_limit":3}],"limit":1}'; + const mockPagerResponse2 = + '{"total_count":2,"jobs":[{"created_at":"2022-09-13T11:41:35+02:00","entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/jobs/my-job","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","name":"my-job","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"job_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_mode":"daemon","run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_array_spec":"1-5,7-8,10","scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_max_execution_time":7200,"scale_memory_limit":"4G","scale_retry_limit":3}],"limit":1}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.JobsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const pager = new CodeEngineV2.JobsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createJob', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + function __createJobTest() { + // Construct the params object for operation createJob + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const imageReference = 'icr.io/codeengine/helloworld'; + const name = 'my-job'; + const imageSecret = 'my-secret'; + const runArguments = ['testString']; + const runAsUser = 1001; + const runCommands = ['testString']; + const runEnvVariables = [envVarPrototypeModel]; + const runMode = 'daemon'; + const runServiceAccount = 'default'; + const runVolumeMounts = [volumeMountPrototypeModel]; + const scaleArraySpec = '1-5,7-8,10'; + const scaleCpuLimit = '1'; + const scaleEphemeralStorageLimit = '4G'; + const scaleMaxExecutionTime = 7200; + const scaleMemoryLimit = '4G'; + const scaleRetryLimit = 3; + const createJobParams = { + projectId, + imageReference, + name, + imageSecret, + runArguments, + runAsUser, + runCommands, + runEnvVariables, + runMode, + runServiceAccount, + runVolumeMounts, + scaleArraySpec, + scaleCpuLimit, + scaleEphemeralStorageLimit, + scaleMaxExecutionTime, + scaleMemoryLimit, + scaleRetryLimit, + }; + + const createJobResult = codeEngineService.createJob(createJobParams); + + // all methods should return a Promise + expectToBePromise(createJobResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/jobs', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.image_reference).toEqual(imageReference); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.image_secret).toEqual(imageSecret); + expect(mockRequestOptions.body.run_arguments).toEqual(runArguments); + expect(mockRequestOptions.body.run_as_user).toEqual(runAsUser); + expect(mockRequestOptions.body.run_commands).toEqual(runCommands); + expect(mockRequestOptions.body.run_env_variables).toEqual(runEnvVariables); + expect(mockRequestOptions.body.run_mode).toEqual(runMode); + expect(mockRequestOptions.body.run_service_account).toEqual(runServiceAccount); + expect(mockRequestOptions.body.run_volume_mounts).toEqual(runVolumeMounts); + expect(mockRequestOptions.body.scale_array_spec).toEqual(scaleArraySpec); + expect(mockRequestOptions.body.scale_cpu_limit).toEqual(scaleCpuLimit); + expect(mockRequestOptions.body.scale_ephemeral_storage_limit).toEqual( + scaleEphemeralStorageLimit + ); + expect(mockRequestOptions.body.scale_max_execution_time).toEqual(scaleMaxExecutionTime); + expect(mockRequestOptions.body.scale_memory_limit).toEqual(scaleMemoryLimit); + expect(mockRequestOptions.body.scale_retry_limit).toEqual(scaleRetryLimit); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createJobTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createJobTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createJobTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const imageReference = 'icr.io/codeengine/helloworld'; + const name = 'my-job'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createJobParams = { + projectId, + imageReference, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createJob(createJobParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createJob({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createJob(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getJob', () => { + describe('positive tests', () => { + function __getJobTest() { + // Construct the params object for operation getJob + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const getJobParams = { + projectId, + name, + }; + + const getJobResult = codeEngineService.getJob(getJobParams); + + // all methods should return a Promise + expectToBePromise(getJobResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/jobs/{name}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getJobTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getJobTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getJobTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getJobParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getJob(getJobParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getJob({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getJob(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteJob', () => { + describe('positive tests', () => { + function __deleteJobTest() { + // Construct the params object for operation deleteJob + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const deleteJobParams = { + projectId, + name, + }; + + const deleteJobResult = codeEngineService.deleteJob(deleteJobParams); + + // all methods should return a Promise + expectToBePromise(deleteJobResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/jobs/{name}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteJobTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteJobTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteJobTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteJobParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteJob(deleteJobParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteJob({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteJob(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('updateJob', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + function __updateJobTest() { + // Construct the params object for operation updateJob + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const ifMatch = 'testString'; + const imageReference = 'icr.io/codeengine/helloworld'; + const imageSecret = 'my-secret'; + const runArguments = ['testString']; + const runAsUser = 1001; + const runCommands = ['testString']; + const runEnvVariables = [envVarPrototypeModel]; + const runMode = 'daemon'; + const runServiceAccount = 'default'; + const runVolumeMounts = [volumeMountPrototypeModel]; + const scaleArraySpec = '1-5,7-8,10'; + const scaleCpuLimit = '1'; + const scaleEphemeralStorageLimit = '4G'; + const scaleMaxExecutionTime = 7200; + const scaleMemoryLimit = '4G'; + const scaleRetryLimit = 3; + const updateJobParams = { + projectId, + name, + ifMatch, + imageReference, + imageSecret, + runArguments, + runAsUser, + runCommands, + runEnvVariables, + runMode, + runServiceAccount, + runVolumeMounts, + scaleArraySpec, + scaleCpuLimit, + scaleEphemeralStorageLimit, + scaleMaxExecutionTime, + scaleMemoryLimit, + scaleRetryLimit, + }; + + const updateJobResult = codeEngineService.updateJob(updateJobParams); + + // all methods should return a Promise + expectToBePromise(updateJobResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/jobs/{name}', 'PATCH'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/merge-patch+json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + expect(mockRequestOptions.body.image_reference).toEqual(imageReference); + expect(mockRequestOptions.body.image_secret).toEqual(imageSecret); + expect(mockRequestOptions.body.run_arguments).toEqual(runArguments); + expect(mockRequestOptions.body.run_as_user).toEqual(runAsUser); + expect(mockRequestOptions.body.run_commands).toEqual(runCommands); + expect(mockRequestOptions.body.run_env_variables).toEqual(runEnvVariables); + expect(mockRequestOptions.body.run_mode).toEqual(runMode); + expect(mockRequestOptions.body.run_service_account).toEqual(runServiceAccount); + expect(mockRequestOptions.body.run_volume_mounts).toEqual(runVolumeMounts); + expect(mockRequestOptions.body.scale_array_spec).toEqual(scaleArraySpec); + expect(mockRequestOptions.body.scale_cpu_limit).toEqual(scaleCpuLimit); + expect(mockRequestOptions.body.scale_ephemeral_storage_limit).toEqual( + scaleEphemeralStorageLimit + ); + expect(mockRequestOptions.body.scale_max_execution_time).toEqual(scaleMaxExecutionTime); + expect(mockRequestOptions.body.scale_memory_limit).toEqual(scaleMemoryLimit); + expect(mockRequestOptions.body.scale_retry_limit).toEqual(scaleRetryLimit); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __updateJobTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __updateJobTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __updateJobTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const ifMatch = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const updateJobParams = { + projectId, + name, + ifMatch, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.updateJob(updateJobParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.updateJob({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.updateJob(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listJobRuns', () => { + describe('positive tests', () => { + function __listJobRunsTest() { + // Construct the params object for operation listJobRuns + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const jobName = 'my-job'; + const limit = 100; + const start = 'testString'; + const listJobRunsParams = { + projectId, + jobName, + limit, + start, + }; + + const listJobRunsResult = codeEngineService.listJobRuns(listJobRunsParams); + + // all methods should return a Promise + expectToBePromise(listJobRunsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/job_runs', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.job_name).toEqual(jobName); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listJobRunsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listJobRunsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listJobRunsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listJobRunsParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listJobRuns(listJobRunsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listJobRuns({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listJobRuns(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('JobRunsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/job_runs'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"job_runs":[{"created_at":"2022-09-13T11:41:35+02:00","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/job_runs/my-job-run","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","job_name":"my-job","name":"my-job-run","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"job_run_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_mode":"daemon","run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_array_spec":"1-5,7-8,10","scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_max_execution_time":7200,"scale_memory_limit":"4G","scale_retry_limit":3,"status":"completed","status_details":{"completion_time":"2022-09-22T17:40:00Z","failed":0,"pending":0,"requested":0,"running":0,"start_time":"2022-09-22T17:34:00Z","succeeded":1,"unknown":0}}],"total_count":2,"limit":1}'; + const mockPagerResponse2 = + '{"job_runs":[{"created_at":"2022-09-13T11:41:35+02:00","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/job_runs/my-job-run","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","image_reference":"icr.io/codeengine/helloworld","image_secret":"my-secret","job_name":"my-job","name":"my-job-run","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"job_run_v2","run_arguments":["run_arguments"],"run_as_user":1001,"run_commands":["run_commands"],"run_env_variables":[{"key":"MY_VARIABLE","name":"SOME","prefix":"PREFIX_","reference":"my-secret","type":"literal","value":"VALUE"}],"run_mode":"daemon","run_service_account":"default","run_volume_mounts":[{"mount_path":"/app","name":"codeengine-mount-b69u90","reference":"my-secret","type":"secret"}],"scale_array_spec":"1-5,7-8,10","scale_cpu_limit":"1","scale_ephemeral_storage_limit":"4G","scale_max_execution_time":7200,"scale_memory_limit":"4G","scale_retry_limit":3,"status":"completed","status_details":{"completion_time":"2022-09-22T17:40:00Z","failed":0,"pending":0,"requested":0,"running":0,"start_time":"2022-09-22T17:34:00Z","succeeded":1,"unknown":0}}],"total_count":2,"limit":1}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + jobName: 'my-job', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.JobRunsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + jobName: 'my-job', + limit: 100, + }; + const pager = new CodeEngineV2.JobRunsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createJobRun', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // EnvVarPrototype + const envVarPrototypeModel = { + key: 'MY_VARIABLE', + name: 'SOME', + prefix: 'PREFIX_', + reference: 'my-secret', + type: 'literal', + value: 'VALUE', + }; + + // VolumeMountPrototype + const volumeMountPrototypeModel = { + mount_path: '/app', + name: 'codeengine-mount-b69u90', + reference: 'my-secret', + type: 'secret', + }; + + function __createJobRunTest() { + // Construct the params object for operation createJobRun + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const imageReference = 'icr.io/codeengine/helloworld'; + const imageSecret = 'my-secret'; + const jobName = 'my-job'; + const name = 'my-job-run'; + const runArguments = ['testString']; + const runAsUser = 1001; + const runCommands = ['testString']; + const runEnvVariables = [envVarPrototypeModel]; + const runMode = 'daemon'; + const runServiceAccount = 'default'; + const runVolumeMounts = [volumeMountPrototypeModel]; + const scaleArraySpec = '1-5,7-8,10'; + const scaleCpuLimit = '1'; + const scaleEphemeralStorageLimit = '4G'; + const scaleMaxExecutionTime = 7200; + const scaleMemoryLimit = '4G'; + const scaleRetryLimit = 3; + const createJobRunParams = { + projectId, + imageReference, + imageSecret, + jobName, + name, + runArguments, + runAsUser, + runCommands, + runEnvVariables, + runMode, + runServiceAccount, + runVolumeMounts, + scaleArraySpec, + scaleCpuLimit, + scaleEphemeralStorageLimit, + scaleMaxExecutionTime, + scaleMemoryLimit, + scaleRetryLimit, + }; + + const createJobRunResult = codeEngineService.createJobRun(createJobRunParams); + + // all methods should return a Promise + expectToBePromise(createJobRunResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/job_runs', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.image_reference).toEqual(imageReference); + expect(mockRequestOptions.body.image_secret).toEqual(imageSecret); + expect(mockRequestOptions.body.job_name).toEqual(jobName); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.run_arguments).toEqual(runArguments); + expect(mockRequestOptions.body.run_as_user).toEqual(runAsUser); + expect(mockRequestOptions.body.run_commands).toEqual(runCommands); + expect(mockRequestOptions.body.run_env_variables).toEqual(runEnvVariables); + expect(mockRequestOptions.body.run_mode).toEqual(runMode); + expect(mockRequestOptions.body.run_service_account).toEqual(runServiceAccount); + expect(mockRequestOptions.body.run_volume_mounts).toEqual(runVolumeMounts); + expect(mockRequestOptions.body.scale_array_spec).toEqual(scaleArraySpec); + expect(mockRequestOptions.body.scale_cpu_limit).toEqual(scaleCpuLimit); + expect(mockRequestOptions.body.scale_ephemeral_storage_limit).toEqual( + scaleEphemeralStorageLimit + ); + expect(mockRequestOptions.body.scale_max_execution_time).toEqual(scaleMaxExecutionTime); + expect(mockRequestOptions.body.scale_memory_limit).toEqual(scaleMemoryLimit); + expect(mockRequestOptions.body.scale_retry_limit).toEqual(scaleRetryLimit); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createJobRunTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createJobRunTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createJobRunTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createJobRunParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createJobRun(createJobRunParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createJobRun({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createJobRun(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getJobRun', () => { + describe('positive tests', () => { + function __getJobRunTest() { + // Construct the params object for operation getJobRun + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const getJobRunParams = { + projectId, + name, + }; + + const getJobRunResult = codeEngineService.getJobRun(getJobRunParams); + + // all methods should return a Promise + expectToBePromise(getJobRunResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/job_runs/{name}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getJobRunTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getJobRunTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getJobRunTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getJobRunParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getJobRun(getJobRunParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getJobRun({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getJobRun(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteJobRun', () => { + describe('positive tests', () => { + function __deleteJobRunTest() { + // Construct the params object for operation deleteJobRun + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const deleteJobRunParams = { + projectId, + name, + }; + + const deleteJobRunResult = codeEngineService.deleteJobRun(deleteJobRunParams); + + // all methods should return a Promise + expectToBePromise(deleteJobRunResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/job_runs/{name}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteJobRunTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteJobRunTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteJobRunTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-job'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteJobRunParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteJobRun(deleteJobRunParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteJobRun({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteJobRun(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listBuilds', () => { + describe('positive tests', () => { + function __listBuildsTest() { + // Construct the params object for operation listBuilds + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const limit = 100; + const start = 'testString'; + const listBuildsParams = { + projectId, + limit, + start, + }; + + const listBuildsResult = codeEngineService.listBuilds(listBuildsParams); + + // all methods should return a Promise + expectToBePromise(listBuildsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/builds', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listBuildsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listBuildsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listBuildsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listBuildsParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listBuilds(listBuildsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listBuilds({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listBuilds(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('BuildsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/builds'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"total_count":2,"limit":1,"builds":[{"created_at":"2022-09-13T11:41:35+02:00","entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/builds/my-build","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-build","output_image":"private.de.icr.io/icr_namespace/image-name","output_secret":"ce-auto-icr-private-eu-de","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"build_v2","source_context_dir":"some/subfolder","source_revision":"main","source_secret":"source_secret","source_type":"git","source_url":"https://github.com/IBM/CodeEngine","status":"ready","status_details":{"reason":"registered"},"strategy_size":"medium","strategy_spec_file":"Dockerfile","strategy_type":"dockerfile","timeout":600}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"builds":[{"created_at":"2022-09-13T11:41:35+02:00","entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/builds/my-build","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-build","output_image":"private.de.icr.io/icr_namespace/image-name","output_secret":"ce-auto-icr-private-eu-de","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"build_v2","source_context_dir":"some/subfolder","source_revision":"main","source_secret":"source_secret","source_type":"git","source_url":"https://github.com/IBM/CodeEngine","status":"ready","status_details":{"reason":"registered"},"strategy_size":"medium","strategy_spec_file":"Dockerfile","strategy_type":"dockerfile","timeout":600}]}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.BuildsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const pager = new CodeEngineV2.BuildsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createBuild', () => { + describe('positive tests', () => { + function __createBuildTest() { + // Construct the params object for operation createBuild + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const outputImage = 'private.de.icr.io/icr_namespace/image-name'; + const outputSecret = 'ce-auto-icr-private-eu-de'; + const sourceUrl = 'https://github.com/IBM/CodeEngine'; + const strategyType = 'dockerfile'; + const sourceContextDir = 'some/subfolder'; + const sourceRevision = 'main'; + const sourceSecret = 'testString'; + const sourceType = 'git'; + const strategySize = 'medium'; + const strategySpecFile = 'Dockerfile'; + const timeout = 600; + const createBuildParams = { + projectId, + name, + outputImage, + outputSecret, + sourceUrl, + strategyType, + sourceContextDir, + sourceRevision, + sourceSecret, + sourceType, + strategySize, + strategySpecFile, + timeout, + }; + + const createBuildResult = codeEngineService.createBuild(createBuildParams); + + // all methods should return a Promise + expectToBePromise(createBuildResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/builds', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.output_image).toEqual(outputImage); + expect(mockRequestOptions.body.output_secret).toEqual(outputSecret); + expect(mockRequestOptions.body.source_url).toEqual(sourceUrl); + expect(mockRequestOptions.body.strategy_type).toEqual(strategyType); + expect(mockRequestOptions.body.source_context_dir).toEqual(sourceContextDir); + expect(mockRequestOptions.body.source_revision).toEqual(sourceRevision); + expect(mockRequestOptions.body.source_secret).toEqual(sourceSecret); + expect(mockRequestOptions.body.source_type).toEqual(sourceType); + expect(mockRequestOptions.body.strategy_size).toEqual(strategySize); + expect(mockRequestOptions.body.strategy_spec_file).toEqual(strategySpecFile); + expect(mockRequestOptions.body.timeout).toEqual(timeout); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createBuildTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createBuildTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createBuildTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const outputImage = 'private.de.icr.io/icr_namespace/image-name'; + const outputSecret = 'ce-auto-icr-private-eu-de'; + const sourceUrl = 'https://github.com/IBM/CodeEngine'; + const strategyType = 'dockerfile'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createBuildParams = { + projectId, + name, + outputImage, + outputSecret, + sourceUrl, + strategyType, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createBuild(createBuildParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createBuild({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createBuild(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getBuild', () => { + describe('positive tests', () => { + function __getBuildTest() { + // Construct the params object for operation getBuild + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const getBuildParams = { + projectId, + name, + }; + + const getBuildResult = codeEngineService.getBuild(getBuildParams); + + // all methods should return a Promise + expectToBePromise(getBuildResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/builds/{name}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getBuildTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getBuildTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getBuildTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getBuildParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getBuild(getBuildParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getBuild({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getBuild(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteBuild', () => { + describe('positive tests', () => { + function __deleteBuildTest() { + // Construct the params object for operation deleteBuild + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const deleteBuildParams = { + projectId, + name, + }; + + const deleteBuildResult = codeEngineService.deleteBuild(deleteBuildParams); + + // all methods should return a Promise + expectToBePromise(deleteBuildResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/builds/{name}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteBuildTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteBuildTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteBuildTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteBuildParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteBuild(deleteBuildParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteBuild({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteBuild(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('updateBuild', () => { + describe('positive tests', () => { + function __updateBuildTest() { + // Construct the params object for operation updateBuild + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const ifMatch = 'testString'; + const outputImage = 'private.de.icr.io/icr_namespace/image-name'; + const outputSecret = 'ce-auto-icr-private-eu-de'; + const sourceContextDir = 'some/subfolder'; + const sourceRevision = 'main'; + const sourceSecret = 'testString'; + const sourceType = 'git'; + const sourceUrl = 'https://github.com/IBM/CodeEngine'; + const strategySize = 'medium'; + const strategySpecFile = 'Dockerfile'; + const strategyType = 'dockerfile'; + const timeout = 600; + const updateBuildParams = { + projectId, + name, + ifMatch, + outputImage, + outputSecret, + sourceContextDir, + sourceRevision, + sourceSecret, + sourceType, + sourceUrl, + strategySize, + strategySpecFile, + strategyType, + timeout, + }; + + const updateBuildResult = codeEngineService.updateBuild(updateBuildParams); + + // all methods should return a Promise + expectToBePromise(updateBuildResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/builds/{name}', 'PATCH'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/merge-patch+json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + expect(mockRequestOptions.body.output_image).toEqual(outputImage); + expect(mockRequestOptions.body.output_secret).toEqual(outputSecret); + expect(mockRequestOptions.body.source_context_dir).toEqual(sourceContextDir); + expect(mockRequestOptions.body.source_revision).toEqual(sourceRevision); + expect(mockRequestOptions.body.source_secret).toEqual(sourceSecret); + expect(mockRequestOptions.body.source_type).toEqual(sourceType); + expect(mockRequestOptions.body.source_url).toEqual(sourceUrl); + expect(mockRequestOptions.body.strategy_size).toEqual(strategySize); + expect(mockRequestOptions.body.strategy_spec_file).toEqual(strategySpecFile); + expect(mockRequestOptions.body.strategy_type).toEqual(strategyType); + expect(mockRequestOptions.body.timeout).toEqual(timeout); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __updateBuildTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __updateBuildTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __updateBuildTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build'; + const ifMatch = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const updateBuildParams = { + projectId, + name, + ifMatch, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.updateBuild(updateBuildParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.updateBuild({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.updateBuild(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listBuildRuns', () => { + describe('positive tests', () => { + function __listBuildRunsTest() { + // Construct the params object for operation listBuildRuns + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const buildName = 'my-build'; + const limit = 100; + const start = 'testString'; + const listBuildRunsParams = { + projectId, + buildName, + limit, + start, + }; + + const listBuildRunsResult = codeEngineService.listBuildRuns(listBuildRunsParams); + + // all methods should return a Promise + expectToBePromise(listBuildRunsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/build_runs', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.build_name).toEqual(buildName); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listBuildRunsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listBuildRunsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listBuildRunsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listBuildRunsParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listBuildRuns(listBuildRunsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listBuildRuns({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listBuildRuns(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('BuildRunsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/build_runs'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"total_count":2,"limit":1,"build_runs":[{"build_name":"build_name","created_at":"2022-09-13T11:41:35+02:00","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/build_runs/my-build-run","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-build-run","output_image":"private.de.icr.io/icr_namespace/image-name","output_secret":"ce-auto-icr-private-eu-de","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"build_run_v2","service_account":"default","source_context_dir":"some/subfolder","source_revision":"main","source_secret":"source_secret","source_type":"git","source_url":"https://github.com/IBM/CodeEngine","status":"succeeded","status_details":{"completion_time":"2022-09-22T17:40:00Z","output_digest":"sha256:9a3d845c629d2b4a6b271b1d526dfafc1e7d9511f8863b43b5bb0483ef626384","reason":"succeeded","start_time":"2022-09-22T17:34:00Z"},"strategy_size":"medium","strategy_spec_file":"Dockerfile","strategy_type":"dockerfile","timeout":600}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"build_runs":[{"build_name":"build_name","created_at":"2022-09-13T11:41:35+02:00","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/build_runs/my-build-run","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-build-run","output_image":"private.de.icr.io/icr_namespace/image-name","output_secret":"ce-auto-icr-private-eu-de","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"build_run_v2","service_account":"default","source_context_dir":"some/subfolder","source_revision":"main","source_secret":"source_secret","source_type":"git","source_url":"https://github.com/IBM/CodeEngine","status":"succeeded","status_details":{"completion_time":"2022-09-22T17:40:00Z","output_digest":"sha256:9a3d845c629d2b4a6b271b1d526dfafc1e7d9511f8863b43b5bb0483ef626384","reason":"succeeded","start_time":"2022-09-22T17:34:00Z"},"strategy_size":"medium","strategy_spec_file":"Dockerfile","strategy_type":"dockerfile","timeout":600}]}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + buildName: 'my-build', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.BuildRunsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + buildName: 'my-build', + limit: 100, + }; + const pager = new CodeEngineV2.BuildRunsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createBuildRun', () => { + describe('positive tests', () => { + function __createBuildRunTest() { + // Construct the params object for operation createBuildRun + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const buildName = 'testString'; + const name = 'testString'; + const outputImage = 'private.de.icr.io/icr_namespace/image-name'; + const outputSecret = 'ce-auto-icr-private-eu-de'; + const serviceAccount = 'default'; + const sourceContextDir = 'some/subfolder'; + const sourceRevision = 'main'; + const sourceSecret = 'testString'; + const sourceType = 'git'; + const sourceUrl = 'https://github.com/IBM/CodeEngine'; + const strategySize = 'medium'; + const strategySpecFile = 'Dockerfile'; + const strategyType = 'dockerfile'; + const timeout = 600; + const createBuildRunParams = { + projectId, + buildName, + name, + outputImage, + outputSecret, + serviceAccount, + sourceContextDir, + sourceRevision, + sourceSecret, + sourceType, + sourceUrl, + strategySize, + strategySpecFile, + strategyType, + timeout, + }; + + const createBuildRunResult = codeEngineService.createBuildRun(createBuildRunParams); + + // all methods should return a Promise + expectToBePromise(createBuildRunResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/build_runs', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.build_name).toEqual(buildName); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.output_image).toEqual(outputImage); + expect(mockRequestOptions.body.output_secret).toEqual(outputSecret); + expect(mockRequestOptions.body.service_account).toEqual(serviceAccount); + expect(mockRequestOptions.body.source_context_dir).toEqual(sourceContextDir); + expect(mockRequestOptions.body.source_revision).toEqual(sourceRevision); + expect(mockRequestOptions.body.source_secret).toEqual(sourceSecret); + expect(mockRequestOptions.body.source_type).toEqual(sourceType); + expect(mockRequestOptions.body.source_url).toEqual(sourceUrl); + expect(mockRequestOptions.body.strategy_size).toEqual(strategySize); + expect(mockRequestOptions.body.strategy_spec_file).toEqual(strategySpecFile); + expect(mockRequestOptions.body.strategy_type).toEqual(strategyType); + expect(mockRequestOptions.body.timeout).toEqual(timeout); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createBuildRunTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createBuildRunTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createBuildRunTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createBuildRunParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createBuildRun(createBuildRunParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createBuildRun({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createBuildRun(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getBuildRun', () => { + describe('positive tests', () => { + function __getBuildRunTest() { + // Construct the params object for operation getBuildRun + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build-run'; + const getBuildRunParams = { + projectId, + name, + }; + + const getBuildRunResult = codeEngineService.getBuildRun(getBuildRunParams); + + // all methods should return a Promise + expectToBePromise(getBuildRunResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/build_runs/{name}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getBuildRunTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getBuildRunTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getBuildRunTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build-run'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getBuildRunParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getBuildRun(getBuildRunParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getBuildRun({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getBuildRun(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteBuildRun', () => { + describe('positive tests', () => { + function __deleteBuildRunTest() { + // Construct the params object for operation deleteBuildRun + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build-run'; + const deleteBuildRunParams = { + projectId, + name, + }; + + const deleteBuildRunResult = codeEngineService.deleteBuildRun(deleteBuildRunParams); + + // all methods should return a Promise + expectToBePromise(deleteBuildRunResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/build_runs/{name}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteBuildRunTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteBuildRunTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteBuildRunTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-build-run'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteBuildRunParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteBuildRun(deleteBuildRunParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteBuildRun({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteBuildRun(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listConfigMaps', () => { + describe('positive tests', () => { + function __listConfigMapsTest() { + // Construct the params object for operation listConfigMaps + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const limit = 100; + const start = 'testString'; + const listConfigMapsParams = { + projectId, + limit, + start, + }; + + const listConfigMapsResult = codeEngineService.listConfigMaps(listConfigMapsParams); + + // all methods should return a Promise + expectToBePromise(listConfigMapsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/config_maps', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listConfigMapsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listConfigMapsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listConfigMapsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listConfigMapsParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listConfigMaps(listConfigMapsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listConfigMaps({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listConfigMaps(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('ConfigMapsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/config_maps'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"config_maps":[{"created_at":"2022-09-13T11:41:35+02:00","data":{"mapKey":"inner"},"entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/config_maps/my-config-map","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-config-map","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"config_map_v2"}],"total_count":2,"limit":1}'; + const mockPagerResponse2 = + '{"config_maps":[{"created_at":"2022-09-13T11:41:35+02:00","data":{"mapKey":"inner"},"entity_tag":"2385407409","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/config_maps/my-config-map","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-config-map","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"config_map_v2"}],"total_count":2,"limit":1}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.ConfigMapsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const pager = new CodeEngineV2.ConfigMapsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createConfigMap', () => { + describe('positive tests', () => { + function __createConfigMapTest() { + // Construct the params object for operation createConfigMap + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-configmap'; + const data = { 'key1': 'testString' }; + const createConfigMapParams = { + projectId, + name, + data, + }; + + const createConfigMapResult = codeEngineService.createConfigMap(createConfigMapParams); + + // all methods should return a Promise + expectToBePromise(createConfigMapResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/config_maps', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.data).toEqual(data); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createConfigMapTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createConfigMapTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createConfigMapTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-configmap'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createConfigMapParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createConfigMap(createConfigMapParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createConfigMap({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createConfigMap(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getConfigMap', () => { + describe('positive tests', () => { + function __getConfigMapTest() { + // Construct the params object for operation getConfigMap + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-config-map'; + const getConfigMapParams = { + projectId, + name, + }; + + const getConfigMapResult = codeEngineService.getConfigMap(getConfigMapParams); + + // all methods should return a Promise + expectToBePromise(getConfigMapResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/config_maps/{name}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getConfigMapTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getConfigMapTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getConfigMapTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-config-map'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getConfigMapParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getConfigMap(getConfigMapParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getConfigMap({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getConfigMap(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('replaceConfigMap', () => { + describe('positive tests', () => { + function __replaceConfigMapTest() { + // Construct the params object for operation replaceConfigMap + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-config-map'; + const ifMatch = 'testString'; + const data = { 'key1': 'testString' }; + const replaceConfigMapParams = { + projectId, + name, + ifMatch, + data, + }; + + const replaceConfigMapResult = codeEngineService.replaceConfigMap(replaceConfigMapParams); + + // all methods should return a Promise + expectToBePromise(replaceConfigMapResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/config_maps/{name}', 'PUT'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + expect(mockRequestOptions.body.data).toEqual(data); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __replaceConfigMapTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __replaceConfigMapTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __replaceConfigMapTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-config-map'; + const ifMatch = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const replaceConfigMapParams = { + projectId, + name, + ifMatch, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.replaceConfigMap(replaceConfigMapParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.replaceConfigMap({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.replaceConfigMap(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteConfigMap', () => { + describe('positive tests', () => { + function __deleteConfigMapTest() { + // Construct the params object for operation deleteConfigMap + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-config-map'; + const deleteConfigMapParams = { + projectId, + name, + }; + + const deleteConfigMapResult = codeEngineService.deleteConfigMap(deleteConfigMapParams); + + // all methods should return a Promise + expectToBePromise(deleteConfigMapResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod( + mockRequestOptions, + '/projects/{project_id}/config_maps/{name}', + 'DELETE' + ); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteConfigMapTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteConfigMapTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteConfigMapTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-config-map'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteConfigMapParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteConfigMap(deleteConfigMapParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteConfigMap({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteConfigMap(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('listSecrets', () => { + describe('positive tests', () => { + function __listSecretsTest() { + // Construct the params object for operation listSecrets + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const limit = 100; + const start = 'testString'; + const listSecretsParams = { + projectId, + limit, + start, + }; + + const listSecretsResult = codeEngineService.listSecrets(listSecretsParams); + + // all methods should return a Promise + expectToBePromise(listSecretsResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/secrets', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.qs.limit).toEqual(limit); + expect(mockRequestOptions.qs.start).toEqual(start); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listSecretsTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __listSecretsTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __listSecretsTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listSecretsParams = { + projectId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.listSecrets(listSecretsParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.listSecrets({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.listSecrets(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + + describe('SecretsPager tests', () => { + const serviceUrl = codeEngineServiceOptions.url; + const path = '/projects/15314cc3-85b4-4338-903f-c28cdee6d005/secrets'; + const mockPagerResponse1 = + '{"next":{"start":"1"},"total_count":2,"limit":1,"secrets":[{"created_at":"2022-09-13T11:41:35+02:00","data":{"mapKey":"inner"},"entity_tag":"2385407409","format":"generic","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/secrets/my-secret","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-secret","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"resource_type"}]}'; + const mockPagerResponse2 = + '{"total_count":2,"limit":1,"secrets":[{"created_at":"2022-09-13T11:41:35+02:00","data":{"mapKey":"inner"},"entity_tag":"2385407409","format":"generic","href":"https://api.eu-de.codeengine.cloud.ibm.com/v2/projects/4e49b3e0-27a8-48d2-a784-c7ee48bb863b/secrets/my-secret","id":"e33b1cv7-7390-4437-a5c2-130d5ccdddc3","name":"my-secret","project_id":"4e49b3e0-27a8-48d2-a784-c7ee48bb863b","resource_type":"resource_type"}]}'; + + 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const allResults = []; + const pager = new CodeEngineV2.SecretsPager(codeEngineService, 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 = { + projectId: '15314cc3-85b4-4338-903f-c28cdee6d005', + limit: 100, + }; + const pager = new CodeEngineV2.SecretsPager(codeEngineService, params); + const allResults = await pager.getAll(); + expect(allResults).not.toBeNull(); + expect(allResults).toHaveLength(2); + }); + }); + }); + + describe('createSecret', () => { + describe('positive tests', () => { + function __createSecretTest() { + // Construct the params object for operation createSecret + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const format = 'generic'; + const name = 'my-secret'; + const data = { 'key1': 'testString' }; + const createSecretParams = { + projectId, + format, + name, + data, + }; + + const createSecretResult = codeEngineService.createSecret(createSecretParams); + + // all methods should return a Promise + expectToBePromise(createSecretResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/secrets', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.body.format).toEqual(format); + expect(mockRequestOptions.body.name).toEqual(name); + expect(mockRequestOptions.body.data).toEqual(data); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createSecretTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __createSecretTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __createSecretTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const format = 'generic'; + const name = 'my-secret'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createSecretParams = { + projectId, + format, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.createSecret(createSecretParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.createSecret({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.createSecret(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getSecret', () => { + describe('positive tests', () => { + function __getSecretTest() { + // Construct the params object for operation getSecret + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-secret'; + const getSecretParams = { + projectId, + name, + }; + + const getSecretResult = codeEngineService.getSecret(getSecretParams); + + // all methods should return a Promise + expectToBePromise(getSecretResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/secrets/{name}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getSecretTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __getSecretTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __getSecretTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-secret'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getSecretParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.getSecret(getSecretParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.getSecret({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.getSecret(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('replaceSecret', () => { + describe('positive tests', () => { + function __replaceSecretTest() { + // Construct the params object for operation replaceSecret + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-secret'; + const ifMatch = 'testString'; + const data = { 'key1': 'testString' }; + const format = 'generic'; + const replaceSecretParams = { + projectId, + name, + ifMatch, + data, + format, + }; + + const replaceSecretResult = codeEngineService.replaceSecret(replaceSecretParams); + + // all methods should return a Promise + expectToBePromise(replaceSecretResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/secrets/{name}', 'PUT'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + expect(mockRequestOptions.body.data).toEqual(data); + expect(mockRequestOptions.body.format).toEqual(format); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __replaceSecretTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __replaceSecretTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __replaceSecretTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-secret'; + const ifMatch = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const replaceSecretParams = { + projectId, + name, + ifMatch, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.replaceSecret(replaceSecretParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.replaceSecret({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.replaceSecret(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteSecret', () => { + describe('positive tests', () => { + function __deleteSecretTest() { + // Construct the params object for operation deleteSecret + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-secret'; + const deleteSecretParams = { + projectId, + name, + }; + + const deleteSecretResult = codeEngineService.deleteSecret(deleteSecretParams); + + // all methods should return a Promise + expectToBePromise(deleteSecretResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/projects/{project_id}/secrets/{name}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.project_id).toEqual(projectId); + expect(mockRequestOptions.path.name).toEqual(name); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteSecretTest(); + + // enable retries and test again + createRequestMock.mockClear(); + codeEngineService.enableRetries(); + __deleteSecretTest(); + + // disable retries and test again + createRequestMock.mockClear(); + codeEngineService.disableRetries(); + __deleteSecretTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const projectId = '15314cc3-85b4-4338-903f-c28cdee6d005'; + const name = 'my-secret'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteSecretParams = { + projectId, + name, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + codeEngineService.deleteSecret(deleteSecretParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await codeEngineService.deleteSecret({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await codeEngineService.deleteSecret(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); +}); diff --git a/test/unit/common.test.js b/test/unit/common.test.js index 2eb8d76..c360d15 100644 --- a/test/unit/common.test.js +++ b/test/unit/common.test.js @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; const common = require('../../dist/lib/common'); + const { getSdkHeaders } = common; describe('Tests of Common Library', () => { describe('getSdkHeaders', () => { test('should return correct User-Agent header', () => { const headers = getSdkHeaders('service1', 'v1', 'operation1'); - expect(headers).not.toEqual(null); + expect(headers).not.toBeNull(); expect(headers['User-Agent']).toMatch(/^code-engine-node-sdk\/.*/); }); }); diff --git a/test/unit/ibm-cloud-code-engine.v1.test.js b/test/unit/ibm-cloud-code-engine.v1.test.js index 2d6ffc8..5f2bfe9 100644 --- a/test/unit/ibm-cloud-code-engine.v1.test.js +++ b/test/unit/ibm-cloud-code-engine.v1.test.js @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2021. + * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +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 IbmCloudCodeEngineV1 = require('../../dist/ibm-cloud-code-engine/v1'); -const { - getOptions, - checkUrlAndMethod, - checkMediaHeaders, - expectToBePromise, - checkUserHeader, -} = unitTestUtils; +const { getOptions, checkUrlAndMethod, checkMediaHeaders, expectToBePromise, checkUserHeader } = + unitTestUtils; const service = { authenticator: new NoAuthAuthenticator(), @@ -105,11 +100,11 @@ describe('IbmCloudCodeEngineV1', () => { // Construct the params object for operation listKubeconfig const refreshToken = 'testString'; const id = 'testString'; - const accept = 'text/plain'; + const accept = 'application/json'; const params = { - refreshToken: refreshToken, - id: id, - accept: accept, + refreshToken, + id, + accept, }; const listKubeconfigResult = ibmCloudCodeEngineService.listKubeconfig(params); @@ -128,7 +123,7 @@ describe('IbmCloudCodeEngineV1', () => { checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'Refresh-Token', refreshToken); checkUserHeader(createRequestMock, 'Accept', accept); - expect(options.path['id']).toEqual(id); + expect(options.path.id).toEqual(id); }); test('should prioritize user-given headers', () => { @@ -152,7 +147,7 @@ describe('IbmCloudCodeEngineV1', () => { }); describe('negative tests', () => { - test('should enforce required parameters', async done => { + test('should enforce required parameters', async () => { let err; try { await ibmCloudCodeEngineService.listKubeconfig({}); @@ -161,90 +156,13 @@ describe('IbmCloudCodeEngineV1', () => { } expect(err.message).toMatch(/Missing required parameters/); - done(); }); - test('should reject promise when required params are not given', done => { + test('should reject promise when required params are not given', (done) => { const listKubeconfigPromise = ibmCloudCodeEngineService.listKubeconfig(); expectToBePromise(listKubeconfigPromise); - listKubeconfigPromise.catch(err => { - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); - }); - }); - }); - describe('getKubeconfig', () => { - describe('positive tests', () => { - test('should pass the right params to createRequest', () => { - // Construct the params object for operation getKubeconfig - const xDelegatedRefreshToken = 'testString'; - const id = 'testString'; - const accept = 'text/plain'; - const params = { - xDelegatedRefreshToken: xDelegatedRefreshToken, - id: id, - accept: accept, - }; - - const getKubeconfigResult = ibmCloudCodeEngineService.getKubeconfig(params); - - // all methods should return a Promise - expectToBePromise(getKubeconfigResult); - - // assert that create request was called - expect(createRequestMock).toHaveBeenCalledTimes(1); - - const options = getOptions(createRequestMock); - - checkUrlAndMethod(options, '/project/{id}/config', 'GET'); - const expectedAccept = accept; - const expectedContentType = undefined; - checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); - checkUserHeader(createRequestMock, 'X-Delegated-Refresh-Token', xDelegatedRefreshToken); - checkUserHeader(createRequestMock, 'Accept', accept); - expect(options.path['id']).toEqual(id); - }); - - test('should prioritize user-given headers', () => { - // parameters - const xDelegatedRefreshToken = 'testString'; - const id = 'testString'; - const userAccept = 'fake/accept'; - const userContentType = 'fake/contentType'; - const params = { - xDelegatedRefreshToken, - id, - headers: { - Accept: userAccept, - 'Content-Type': userContentType, - }, - }; - - ibmCloudCodeEngineService.getKubeconfig(params); - checkMediaHeaders(createRequestMock, userAccept, userContentType); - }); - }); - - describe('negative tests', () => { - test('should enforce required parameters', async done => { - let err; - try { - await ibmCloudCodeEngineService.getKubeconfig({}); - } catch (e) { - err = e; - } - - expect(err.message).toMatch(/Missing required parameters/); - done(); - }); - - test('should reject promise when required params are not given', done => { - const getKubeconfigPromise = ibmCloudCodeEngineService.getKubeconfig(); - expectToBePromise(getKubeconfigPromise); - - getKubeconfigPromise.catch(err => { + listKubeconfigPromise.catch((err) => { expect(err.message).toMatch(/Missing required parameters/); done(); }); diff --git a/tsconfig.json b/tsconfig.json index 0bd1425..8122ee8 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,27 +1,26 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + "resolveJsonModule": true, "lib": [ "es5", "es2015", "dom", "scripthost" ], - /* Build source files into a folder called `dist` to maintain clean directories, free of ts-generated files */ "outDir": "./dist", - /* Specify library files to be included in the compilation: */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - + "declaration": true, /* Generates corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ /* Strict Type-Checking Options */ - "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - + "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Module Resolution Options */ - "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - "types": ["node"] /* Type declaration files to be included in compilation. */ + "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + "types": [ + "node" + ], /* Type declaration files to be included in compilation. */ } -} +} \ No newline at end of file diff --git a/tslint.json b/tslint.json deleted file mode 100644 index 92a8781..0000000 --- a/tslint.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "extends": ["tslint:recommended", "tslint-eslint-rules", "tslint-config-prettier"], - "rules": { - "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"], - "interface-name": [true, "never-prefix"], - "no-string-literal": false, - "no-empty-interface":false, - "object-literal-sort-keys": false, - "interface-over-type-literal": false, - "ban-types": [false, ["Object", "Use {} instead."]], - "no-namespace": false, - "no-reference": { - "severity": "warning" - }, - "no-shadowed-variable": { - "severity": "warning" - }, - "member-access":false, - "no-console": { - "severity": "warning", - "options": ["debug", "info", "log", "time", "timeEnd", "trace"] - } - }, - "cliOptions": { - "exclude": ["jsdoc", "doc", "coverage", "dist", "node_modules", "jsdoc"] - } -}