diff --git a/.eslintrc b/.eslintrc index 63f2a269..2b7c8abe 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,6 +5,8 @@ "n": "readonly", "r": "readonly", "assertDependencies": "readonly", - "assertNodeEngines": "readonly" + "assertNodeEngines": "readonly", + "fixtureFile": "readonly", + "fixtureJson": "readonly" } } diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 967f5c2a..c7ce1db2 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -11,4 +11,5 @@ on: jobs: build: - uses: adobe/aio-reusable-workflows/.github/workflows/node.js.yml@main \ No newline at end of file + uses: adobe/aio-reusable-workflows/.github/workflows/node.js.yml@main + secrets: inherit diff --git a/generators/add-vscode-config/VsCodeConfiguration.js b/generators/add-vscode-config/VsCodeConfiguration.js deleted file mode 100644 index 4c6f4255..00000000 --- a/generators/add-vscode-config/VsCodeConfiguration.js +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2021 Adobe. All rights reserved. -This file is licensed to you 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 REPRESENTATIONS -OF ANY KIND, either express or implied. See the License for the specific language -governing permissions and limitations under the License. -*/ - -const path = require('path') - -/** - * Create a VS Code launch compound. - * - * @param {Object} params the parameters - * @param {String} params.name the compound name - * @param {Array} params.configurations an array of launch configuration names - */ -function createLaunchCompound (params) { - const { name, configurations = [] } = params - return { - name, - configurations - } -} - -/** - * Create a VS Code basic launch configuration. - * - * @param {Object} params the parameters - * @param {String} params.type the launch configuration type - * @param {String} params.name the launch configuration name - * @param {String} params.request the launch configuration request - */ -function createLaunchConfiguration (params) { - const { type, name, request } = params - return { - type, - name, - request - } -} - -/** - * Create a VS Code Google Chrome launch configuration. - * - * This configuration needs the Chrome Debugging extension for VS Code (created by Microsoft) to be installed. - * - * @param {Object} params the parameters - * @param {String} params.url the frontend URL - * @param {String} params.webRoot the path to the web root - * @param {String} params.webDistDev the path to the web dist-dev folder - */ -function createChromeLaunchConfiguration (params) { - const { url, webRoot } = params - return { - ...createLaunchConfiguration({ type: 'chrome', name: 'Web', request: 'launch' }), - url, - webRoot, - breakOnLoad: true, - sourceMapPathOverrides: { - '/__parcel_source_root/*': '${workspaceFolder}/*' // eslint-disable-line no-template-curly-in-string - } - } -} - -/** - * Create a VS Code Node launch configuration. - * - * @param {Object} params the parameters - * @param {String} params.packageName the Openwhisk package name - * @param {String} params.actionName the Openwhisk action name - * @param {String} params.actionFileRelativePath the relative path to the action file - * @param {String} params.envFileRelativePath the relative path to the env file - * @param {String} params.remoteRoot the remote root path - */ -function createPwaNodeLaunchConfiguration (params) { - const { packageName, actionName, actionFileRelativePath, envFileRelativePath, remoteRoot } = params - const configurationName = `Action:${packageName}/${actionName}` - - return { - ...createLaunchConfiguration({ type: 'pwa-node', name: configurationName, request: 'launch' }), - runtimeExecutable: '${workspaceFolder}/node_modules/.bin/wskdebug', // eslint-disable-line no-template-curly-in-string - envFile: path.join('${workspaceFolder}', envFileRelativePath), // eslint-disable-line no-template-curly-in-string - timeout: 30000, - killBehavior: 'polite', - localRoot: '${workspaceFolder}', // eslint-disable-line no-template-curly-in-string - remoteRoot, - outputCapture: 'std', - attachSimplePort: 0, - runtimeArgs: [ - `${packageName}/${actionName}`, - path.join('${workspaceFolder}', actionFileRelativePath), // eslint-disable-line no-template-curly-in-string - '-v', - '--disable-concurrency' - ] - } -} - -/** - * Create a VS Code configuration. - * - * @param {Object} params the parameters - * @param {Array} params.configurations an array of VS Code launch configurations - * @param {Array} params.compunds an array of VS Code launch compounds - */ -function createVsCodeConfiguration (params = {}) { - const { configurations = [], compounds = [] } = params - return { - configurations, - compounds - } -} - -module.exports = { - createVsCodeConfiguration, - createLaunchCompound, - createChromeLaunchConfiguration, - createPwaNodeLaunchConfiguration -} diff --git a/generators/add-vscode-config/index.js b/generators/add-vscode-config/index.js index 381acae7..745ea87d 100644 --- a/generators/add-vscode-config/index.js +++ b/generators/add-vscode-config/index.js @@ -1,5 +1,5 @@ /* -Copyright 2021 Adobe. All rights reserved. +Copyright 2024 Adobe. All rights reserved. This file is licensed to you 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 @@ -10,17 +10,7 @@ governing permissions and limitations under the License. */ const Generator = require('yeoman-generator') -const path = require('path') const fs = require('fs-extra') -const { absApp, objGetValue } = require('./utils') -const cloneDeep = require('lodash.clonedeep') - -const { - createVsCodeConfiguration, - createLaunchCompound, - createChromeLaunchConfiguration, - createPwaNodeLaunchConfiguration -} = require('./VsCodeConfiguration') /* 'initializing', @@ -35,16 +25,11 @@ const { const Default = { DESTINATION_FILE: '.vscode/launch.json', - REMOTE_ROOT: '/code', SKIP_PROMPT: false } const Option = { DESTINATION_FILE: 'destination-file', - FRONTEND_URL: 'frontend-url', - REMOTE_ROOT: 'remote-root', - APP_CONFIG: 'app-config', - ENV_FILE: 'env-file', SKIP_PROMPT: 'skip-prompt' } @@ -53,199 +38,40 @@ class AddVsCodeConfig extends Generator { super(args, opts) // options are inputs from CLI or yeoman parent generator - this.option(Option.APP_CONFIG, { type: Object }) - this.option(Option.FRONTEND_URL, { type: String }) - this.option(Option.REMOTE_ROOT, { type: String, default: Default.REMOTE_ROOT }) this.option(Option.DESTINATION_FILE, { type: String, default: Default.DESTINATION_FILE }) - this.option(Option.ENV_FILE, { type: String }) this.option(Option.SKIP_PROMPT, { type: Boolean, default: Default.SKIP_PROMPT }) } - _verifyConfig () { - function getMissingKeys (config, keys) { - const missingKeys = [] - keys.forEach(key => { - if (objGetValue(appConfig, key) === undefined) { - missingKeys.push(key) - } - }) - return missingKeys - } - - const appConfig = this.options[Option.APP_CONFIG] - const verifyKeysCommon = [ - 'app.hasFrontend', - 'app.hasBackend', - 'root' - ] - - const verifyKeysFrontend = [ - 'web.src', - 'web.distDev' - ] - - const verifyKeysBackend = [ - 'ow.package', - 'ow.apihost', - 'manifest.packagePlaceholder', - 'manifest.full.packages' - ] - - const missingKeys = getMissingKeys(appConfig, verifyKeysCommon) - if (appConfig.app.hasFrontend) { - missingKeys.push(...getMissingKeys(appConfig, verifyKeysFrontend)) - } - if (appConfig.app.hasBackend) { - missingKeys.push(...getMissingKeys(appConfig, verifyKeysBackend)) - } - if (missingKeys.length > 0) { - throw new Error(`App config missing keys: ${missingKeys.join(', ')}`) - } - - const envFile = this.options[Option.ENV_FILE] - if (!envFile) { - throw new Error(`Missing option for generator: ${Option.ENV_FILE}`) - } - } - - _getActionEntryFile (pkgJson) { - const pkgJsonContent = fs.readJsonSync(pkgJson) - if (pkgJsonContent.main) { - return pkgJsonContent.main - } - return 'index.js' - } - - _processRuntimeArgsForActionEntryFile (action, runtimeArgs) { - const appConfig = this.options[Option.APP_CONFIG] - const actionPath = absApp(appConfig.root, action.function) - - const actionFileStats = fs.lstatSync(actionPath) - if (actionFileStats.isDirectory()) { - // take package.json main or 'index.js' - const zipMain = this._getActionEntryFile(path.join(actionPath, 'package.json')) - // index 1 is the action file path - runtimeArgs[1] = path.join(runtimeArgs[1], zipMain) - } - - return runtimeArgs - } - - _processAction (packageName, actionName, action) { - const appConfig = this.options[Option.APP_CONFIG] - const nodeVersion = this.options[Option.NODE_VERSION] - const remoteRoot = this.options[Option.REMOTE_ROOT] - const envFile = this.options[Option.ENV_FILE] - - // make sure the action path is a relative path, using appConfig.root - let actionFileRelativePath = action.function - if (path.isAbsolute(actionFileRelativePath)) { - actionFileRelativePath = path.relative(appConfig.root, actionFileRelativePath) - } - - // make sure the envFile path is a relative path, using appConfig.root - let envFileRelativePath = envFile - if (path.isAbsolute(envFileRelativePath)) { - envFileRelativePath = path.relative(appConfig.root, envFileRelativePath) - } - - const launchConfig = createPwaNodeLaunchConfiguration({ - packageName, - actionName, - actionFileRelativePath, - envFileRelativePath, - remoteRoot, - nodeVersion - }) - - launchConfig.runtimeArgs = this._processRuntimeArgsForActionEntryFile(action, launchConfig.runtimeArgs) - - if ( - action.annotations && - action.annotations['require-adobe-auth'] && - appConfig.ow.apihost === 'https://adobeioruntime.net' - ) { - // NOTE: The require-adobe-auth annotation is a feature implemented in the - // runtime plugin. The current implementation replaces the action by a sequence - // and renames the action to __secured_. The annotation will soon be - // natively supported in Adobe I/O Runtime, at which point this condition won't - // be needed anymore. - /* instanbul ignore next */ - launchConfig.runtimeArgs[0] = `${packageName}/__secured_${actionName}` - } - - if (action.runtime) { - launchConfig.runtimeArgs.push('--kind') - launchConfig.runtimeArgs.push(action.runtime) - } - - return launchConfig - } - - _processForBackend () { - const appConfig = this.options[Option.APP_CONFIG] - - const modifiedConfig = cloneDeep(appConfig) - const packages = modifiedConfig.manifest.full.packages - const packagePlaceholder = modifiedConfig.manifest.packagePlaceholder - if (packages[packagePlaceholder]) { - packages[modifiedConfig.ow.package] = packages[packagePlaceholder] - delete packages[packagePlaceholder] + initializing () { + this.vsCodeConfig = { + version: '0.2.0', + configurations: [] } - Object.keys(packages).forEach(packageName => { - const pkg = packages[packageName] - - Object.keys(pkg.actions).forEach(actionName => { - const action = pkg.actions[actionName] - const launchConfig = this._processAction(packageName, actionName, action) - this.vsCodeConfig.configurations.push(launchConfig) - }) + this.vsCodeConfig.configurations.push({ + name: 'App Builder: debug actions', + type: 'node-terminal', + request: 'launch', + command: 'aio app dev' }) - this.vsCodeConfig.compounds.push({ - name: 'Actions', - configurations: this.vsCodeConfig.configurations.map(config => config.name) + this.vsCodeConfig.configurations.push({ + name: 'App Builder: debug full stack', + type: 'node-terminal', + request: 'launch', + command: 'aio app dev', + sourceMapPathOverrides: { + '/__parcel_source_root/*': '${webRoot}/*' // eslint-disable-line no-template-curly-in-string + }, + serverReadyAction: { + pattern: 'server running on port : ([0-9]+)', + uriFormat: 'https://localhost:%s', + action: 'debugWithChrome', + webRoot: '${workspaceFolder}' // eslint-disable-line no-template-curly-in-string + } }) } - _processForFrontend () { - const appConfig = this.options[Option.APP_CONFIG] - const frontEndUrl = this.options[Option.FRONTEND_URL] - - if (!frontEndUrl) { - throw new Error(`Missing option for generator: ${Option.FRONTEND_URL}`) - } - - const webConfig = createChromeLaunchConfiguration({ - url: frontEndUrl, - webRoot: appConfig.web.src, - webDistDev: appConfig.web.distDev - }) - - this.vsCodeConfig.configurations.push(webConfig) - - this.vsCodeConfig.compounds.push(createLaunchCompound({ - name: 'WebAndActions', - configurations: this.vsCodeConfig.configurations.map(config => config.name) - })) - } - - initializing () { - this._verifyConfig() - this.vsCodeConfig = createVsCodeConfiguration() - - const appConfig = this.options[Option.APP_CONFIG] - - if (appConfig.app.hasBackend) { - this._processForBackend() - } - - if (appConfig.app.hasFrontend) { - this._processForFrontend() - } - } - async writing () { const destFile = this.options[Option.DESTINATION_FILE] const skipPrompt = this.options[Option.SKIP_PROMPT] diff --git a/generators/add-vscode-config/utils.js b/generators/add-vscode-config/utils.js deleted file mode 100644 index 76215232..00000000 --- a/generators/add-vscode-config/utils.js +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright 2021 Adobe. All rights reserved. -This file is licensed to you 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 REPRESENTATIONS -OF ANY KIND, either express or implied. See the License for the specific language -governing permissions and limitations under the License. -*/ - -const path = require('path') - -function absApp (root, p) { - if (path.isAbsolute(p)) return p - return path.join(root, path.normalize(p)) -} - -function objGetProp (obj, key) { - return obj[Object.keys(obj).find(k => k.toLowerCase() === key.toLowerCase())] -} - -function objGetValue (obj, key) { - const keys = (key || '').toString().split('.') - return keys.filter(o => o.trim()).reduce((o, i) => o && objGetProp(o, i), obj) -} - -module.exports = { - absApp, - objGetValue -} diff --git a/test/__fixtures__/add-vscode-config/launch.json b/test/__fixtures__/add-vscode-config/launch.json new file mode 100644 index 00000000..717b0ce5 --- /dev/null +++ b/test/__fixtures__/add-vscode-config/launch.json @@ -0,0 +1,26 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "App Builder: debug actions", + "type": "node-terminal", + "request": "launch", + "command": "aio app dev" + }, + { + "name": "App Builder: debug full stack", + "type": "node-terminal", + "request": "launch", + "command": "aio app dev", + "sourceMapPathOverrides": { + "/__parcel_source_root/*": "${webRoot}/*" + }, + "serverReadyAction": { + "pattern": "server running on port : ([0-9]+)", + "uriFormat": "https://localhost:%s", + "action": "debugWithChrome", + "webRoot": "${workspaceFolder}" + } + } + ] +} diff --git a/test/generators/add-vscode-config/VsCodeConfiguration.test.js b/test/generators/add-vscode-config/VsCodeConfiguration.test.js deleted file mode 100644 index 619b5673..00000000 --- a/test/generators/add-vscode-config/VsCodeConfiguration.test.js +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright 2021 Adobe. All rights reserved. -This file is licensed to you 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 REPRESENTATIONS -OF ANY KIND, either express or implied. See the License for the specific language -governing permissions and limitations under the License. -*/ -const { - createVsCodeConfiguration, - createLaunchCompound, - createChromeLaunchConfiguration, - createPwaNodeLaunchConfiguration -} = require('../../../generators/add-vscode-config/VsCodeConfiguration') - -const path = require('path') - -test('exports', () => { - expect(typeof createVsCodeConfiguration).toEqual('function') - expect(typeof createLaunchCompound).toEqual('function') - expect(typeof createChromeLaunchConfiguration).toEqual('function') - expect(typeof createPwaNodeLaunchConfiguration).toEqual('function') -}) - -test('createVsCodeConfiguration', () => { - const launchConfig = createVsCodeConfiguration() - - expect(typeof launchConfig).toEqual('object') - expect(Array.isArray(launchConfig.configurations)).toBeTruthy() - expect(Array.isArray(launchConfig.compounds)).toBeTruthy() -}) - -test('createLaunchCompound', () => { - const compoundName = 'compound-name' - const launchCompound = createLaunchCompound({ name: compoundName }) - - expect(typeof launchCompound).toEqual('object') - expect(launchCompound.name).toEqual(compoundName) - expect(Array.isArray(launchCompound.configurations)).toBeTruthy() -}) - -test('createChromeLaunchConfiguration', () => { - const params = { - url: 'my-url', - webRoot: 'my-web-root', - webDistDev: 'dist-dev' - } - const launchConfig = createChromeLaunchConfiguration(params) - - expect(typeof launchConfig).toEqual('object') - expect(launchConfig.type).toEqual('chrome') - expect(launchConfig.name).toEqual('Web') - expect(launchConfig.request).toEqual('launch') - - expect(launchConfig).toStrictEqual({ - type: 'chrome', - name: 'Web', - request: 'launch', - url: params.url, - webRoot: params.webRoot, - breakOnLoad: true, - sourceMapPathOverrides: { - '/__parcel_source_root/*': '${workspaceFolder}/*' // eslint-disable-line no-template-curly-in-string - } - }) -}) - -test('createPwaNodeLaunchConfiguration', () => { - const params = { - packageName: 'my-package', - actionName: 'my-action-name', - actionFileRelativePath: 'action-relative-path', - envFileRelativePath: 'env-file-relative-path', - remoteRoot: 'remote-root', - nodeVersion: 14 - } - const launchConfig = createPwaNodeLaunchConfiguration(params) - - expect(launchConfig).toStrictEqual({ - type: 'pwa-node', - name: `Action:${params.packageName}/${params.actionName}`, - request: 'launch', - killBehavior: 'polite', - runtimeExecutable: '${workspaceFolder}/node_modules/.bin/wskdebug', // eslint-disable-line no-template-curly-in-string - envFile: path.join('${workspaceFolder}', params.envFileRelativePath), // eslint-disable-line no-template-curly-in-string - timeout: 30000, - localRoot: '${workspaceFolder}', // eslint-disable-line no-template-curly-in-string - remoteRoot: params.remoteRoot, - outputCapture: 'std', - attachSimplePort: 0, - runtimeArgs: [ - `${params.packageName}/${params.actionName}`, - path.join('${workspaceFolder}', params.actionFileRelativePath), // eslint-disable-line no-template-curly-in-string - '-v', - '--disable-concurrency' - ] - }) -}) diff --git a/test/generators/add-vscode-config/index.test.js b/test/generators/add-vscode-config/index.test.js index 2d3d44c3..12bf0ab4 100644 --- a/test/generators/add-vscode-config/index.test.js +++ b/test/generators/add-vscode-config/index.test.js @@ -1,5 +1,5 @@ /* -Copyright 2021 Adobe. All rights reserved. +Copyright 2024 Adobe. All rights reserved. This file is licensed to you 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 @@ -8,9 +8,9 @@ the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTA OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ + const assert = require('yeoman-assert') const fs = require('fs-extra') -const path = require('path') jest.mock('fs-extra') @@ -21,119 +21,6 @@ beforeAll(async () => { const theGeneratorPath = require.resolve('../../../generators/add-vscode-config') const Generator = require('yeoman-generator') -const { constants } = require('@adobe/generator-app-common-lib') - -const createOptions = ({ actionPathIsAbsolute = false, envFilePathIsAbsolute = false } = {}) => { - const root = '/root' - let actionPath = path.join('src', 'actions', 'action-1') - let envFilePath = path.join('my', '.env') - - if (actionPathIsAbsolute) { - actionPath = path.join(root, actionPath) - } - - if (envFilePathIsAbsolute) { - envFilePath = path.join(root, envFilePath) - } - - return { - 'app-config': { - app: { - hasBackend: true, - hasFrontend: true - }, - ow: { - package: 'my-package', - apihost: 'https://my-api.host' - }, - manifest: { - packagePlaceholder: '__APP_PACKAGE__', - full: { - packages: { - __APP_PACKAGE__: { - actions: { - 'action-1': { - function: actionPath - } - } - } - } - } - }, - web: { - src: 'html', - distDev: 'dist-dev' - }, - root - }, - 'frontend-url': 'https://localhost:9080', - 'env-file': envFilePath - } -} - -const createTestLaunchConfiguration = ( - packageName, - requireAdobeAuth = false, - mainFile = null -) => { - const actionName = `${packageName}/${requireAdobeAuth ? '__secured_' : ''}action-1` - let actionJs = path.join('${workspaceFolder}', 'src', 'actions', 'action-1') // eslint-disable-line no-template-curly-in-string - if (mainFile) { - actionJs = path.join(actionJs, mainFile) - } - - return { - configurations: [ - { - type: 'pwa-node', - name: `Action:${packageName}/action-1`, - request: 'launch', - killBehavior: 'polite', - runtimeExecutable: '${workspaceFolder}/node_modules/.bin/wskdebug', // eslint-disable-line no-template-curly-in-string - envFile: path.join('${workspaceFolder}', 'my', '.env'), // eslint-disable-line no-template-curly-in-string - timeout: 30000, - localRoot: '${workspaceFolder}', // eslint-disable-line no-template-curly-in-string - remoteRoot: '/code', - outputCapture: 'std', - attachSimplePort: 0, - runtimeArgs: [ - actionName, - actionJs, - '-v', - '--disable-concurrency', - '--kind', - constants.defaultRuntimeKind - ] - }, - { - type: 'chrome', - name: 'Web', - request: 'launch', - url: 'https://localhost:9080', - webRoot: 'html', - breakOnLoad: true, - sourceMapPathOverrides: { - '/__parcel_source_root/*': '${workspaceFolder}/*' // eslint-disable-line no-template-curly-in-string - } - } - ], - compounds: [ - { - name: 'Actions', - configurations: [ - `Action:${packageName}/action-1` - ] - }, - { - name: 'WebAndActions', - configurations: [ - `Action:${packageName}/action-1`, - 'Web' - ] - } - ] - } -} beforeEach(() => { fs.lstatSync.mockReset() @@ -144,227 +31,22 @@ test('exports a yeoman generator', () => { expect(require(theGeneratorPath).prototype).toBeInstanceOf(Generator) }) -test('option app-config incomplete', async () => { - const options = { - 'app-config': { - app: { - } - } - } - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - - await expect(result).rejects.toEqual(new Error( - 'App config missing keys: app.hasFrontend, app.hasBackend, root')) -}) - -test('option backend keys missing', async () => { - const options = createOptions() - options['app-config'].app.hasBackend = true - options['app-config'].app.hasFrontend = false - delete options['app-config'].manifest - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).rejects.toEqual(new Error('App config missing keys: manifest.packagePlaceholder, manifest.full.packages')) -}) - -test('option frontend-url missing', async () => { - const options = createOptions() - options['app-config'].app.hasBackend = false - options['app-config'].app.hasFrontend = true - options['frontend-url'] = undefined - options['env-file'] = 'env-file' - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).rejects.toEqual(new Error('Missing option for generator: frontend-url')) -}) - -test('option env-file missing', async () => { - const options = createOptions() - options['app-config'].app.hasBackend = true - options['app-config'].app.hasFrontend = true - options['frontend-url'] = 'https://localhost:9999' - delete options['env-file'] - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).rejects.toEqual(new Error('Missing option for generator: env-file')) -}) - -test('no missing options -- coverage (no frontend or backend, runtime not specified)', async () => { - const options = createOptions() - options['app-config'].app.hasBackend = false - options['app-config'].app.hasFrontend = false - - fs.lstatSync.mockReturnValue({ - isDirectory: () => false - }) - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() -}) - -test('no missing options (action is a file)', async () => { - const options = createOptions() - options['destination-file'] = 'foo/bar.json' - const pkg = options['app-config'].manifest.full.packages.__APP_PACKAGE__ - pkg.actions['action-1'].runtime = constants.defaultRuntimeKind - +test('no missing options (defaults))', async () => { fs.lstatSync.mockReturnValue({ isDirectory: () => false }) - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() - - assert.file(options['destination-file']) // destination file is written - assert.JSONFileContent(options['destination-file'], - createTestLaunchConfiguration(options['app-config'].ow.package)) -}) - -test('no missing options (action is a folder)', async () => { - const destFile = 'foo/bar.json' - const options = createOptions() - options['destination-file'] = destFile - const pkg = options['app-config'].manifest.full.packages.__APP_PACKAGE__ - pkg.actions['action-1'].runtime = constants.defaultRuntimeKind - - let result - - fs.lstatSync.mockReturnValue({ - isDirectory: () => true - }) - - fs.readJsonSync.mockReturnValue({}) // no main property in package.json - result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() - - assert.file(destFile) // destination file is written - assert.JSONFileContent(destFile, - createTestLaunchConfiguration( - options['app-config'].ow.package, - false, - 'index.js' - ) - ) - - fs.readJsonSync.mockReturnValue({ main: 'main.js' }) // has main property in package.json - result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) + const result = yeomanTestHelpers.run(theGeneratorPath) await expect(result).resolves.not.toThrow() - assert.file(destFile) // destination file is written - assert.JSONFileContent(destFile, - createTestLaunchConfiguration( - options['app-config'].ow.package, - false, - 'main.js' - ) - ) + assert.file('.vscode/launch.json') // destination file is written + assert.JSONFileContent('.vscode/launch.json', fixtureJson('add-vscode-config/launch.json')) }) -test('no missing options (coverage: action has a runtime specifier)', async () => { - const options = createOptions() - const pkg = options['app-config'].manifest.full.packages.__APP_PACKAGE__ - pkg.actions['action-1'].runtime = constants.defaultRuntimeKind - - fs.lstatSync.mockReturnValue({ - isDirectory: () => false - }) - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() -}) - -test('no missing options (coverage: action has annotations)', async () => { - const options = createOptions() - options['app-config'].ow.apihost = 'https://adobeioruntime.net' - const pkg = options['app-config'].manifest.full.packages.__APP_PACKAGE__ - pkg.actions['action-1'].annotations = { 'require-adobe-auth': true } - - fs.lstatSync.mockReturnValue({ - isDirectory: () => false - }) - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() -}) - -test('output check', async () => { - const options = createOptions() - const pkg = options['app-config'].manifest.full.packages.__APP_PACKAGE__ - pkg.actions['action-1'].runtime = constants.defaultRuntimeKind - pkg.actions['action-1'].annotations = { - 'require-adobe-auth': true - } - options['app-config'].ow.apihost = 'https://adobeioruntime.net' - options['destination-file'] = 'foo/bar.json' - - fs.lstatSync.mockReturnValue({ - isDirectory: () => false - }) - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() - - const destFile = options['destination-file'] - assert.file(destFile) // destination file is written - assert.JSONFileContent(destFile, createTestLaunchConfiguration(options['app-config'].ow.package, true)) -}) - -test('output check (action path is absolute)', async () => { - const options = createOptions({ actionPathIsAbsolute: true }) - const pkg = options['app-config'].manifest.full.packages.__APP_PACKAGE__ - pkg.actions['action-1'].runtime = constants.defaultRuntimeKind - pkg.actions['action-1'].annotations = { - 'require-adobe-auth': true - } - options['app-config'].ow.apihost = 'https://adobeioruntime.net' - options['destination-file'] = 'foo/bar.json' - - fs.lstatSync.mockReturnValue({ - isDirectory: () => false - }) - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() - - const destFile = options['destination-file'] - assert.file(destFile) // destination file is written - assert.JSONFileContent(destFile, createTestLaunchConfiguration(options['app-config'].ow.package, true)) -}) - -test('output check (envFile path is absolute)', async () => { - const options = createOptions({ envFilePathIsAbsolute: true }) - const pkg = options['app-config'].manifest.full.packages.__APP_PACKAGE__ - pkg.actions['action-1'].runtime = constants.defaultRuntimeKind - pkg.actions['action-1'].annotations = { - 'require-adobe-auth': true - } - options['app-config'].ow.apihost = 'https://adobeioruntime.net' - options['destination-file'] = 'foo/bar.json' - - fs.lstatSync.mockReturnValue({ - isDirectory: () => false - }) - - const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) - await expect(result).resolves.not.toThrow() - - const destFile = options['destination-file'] - assert.file(destFile) // destination file is written - assert.JSONFileContent(destFile, createTestLaunchConfiguration(options['app-config'].ow.package, true)) -}) - -test('output check (custom package)', async () => { - const customPackage = 'my-custom-package' - const options = createOptions() - const packages = options['app-config'].manifest.full.packages - packages[customPackage] = Object.assign({}, packages.__APP_PACKAGE__) - delete packages.__APP_PACKAGE__ - packages[customPackage].actions['action-1'].runtime = constants.defaultRuntimeKind - packages[customPackage].actions['action-1'].annotations = { - 'require-adobe-auth': true +test('option destination-file is set', async () => { + const options = { + 'destination-file': 'foo/bar.json' } - options['app-config'].ow.apihost = 'https://adobeioruntime.net' - options['destination-file'] = 'foo/bar.json' fs.lstatSync.mockReturnValue({ isDirectory: () => false @@ -373,14 +55,14 @@ test('output check (custom package)', async () => { const result = yeomanTestHelpers.run(theGeneratorPath).withOptions(options) await expect(result).resolves.not.toThrow() - const destFile = options['destination-file'] - assert.file(destFile) // destination file is written - assert.JSONFileContent(destFile, createTestLaunchConfiguration(customPackage, true)) + assert.file(options['destination-file']) // destination file is written + assert.JSONFileContent(options['destination-file'], fixtureJson('add-vscode-config/launch.json')) }) test('vscode launch configuration exists', async () => { - const options = createOptions() - options['destination-file'] = 'foo/bar.json' + const options = { + 'destination-file': 'foo/bar.json' + } fs.lstatSync.mockReturnValue({ isDirectory: () => false diff --git a/test/generators/add-vscode-config/utils.test.js b/test/generators/add-vscode-config/utils.test.js deleted file mode 100644 index 5d003f7d..00000000 --- a/test/generators/add-vscode-config/utils.test.js +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2021 Adobe. All rights reserved. -This file is licensed to you 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 REPRESENTATIONS -OF ANY KIND, either express or implied. See the License for the specific language -governing permissions and limitations under the License. -*/ - -const { - absApp, - objGetValue -} = require('../../../generators/add-vscode-config/utils') -const path = require('path') - -test('exports', () => { - expect(typeof absApp).toEqual('function') - expect(typeof objGetValue).toEqual('function') -}) - -test('absApp', () => { - const root = '/foo' - expect(() => absApp(undefined, undefined)).toThrow() - expect(() => absApp(undefined, 'bar')).toThrow() - expect(() => absApp(root, undefined)).toThrow() - - expect(absApp(root, 'bar')).toEqual(path.join(root, 'bar')) - expect(absApp(root, path.join(root, 'bar'))).toEqual(path.join(root, 'bar')) -}) - -test('objGetValue', () => { - const obj = { - foo: { - bar: 'baz' - } - } - - expect(objGetValue(undefined, undefined)).toEqual(undefined) - expect(objGetValue(undefined, 'foo')).toEqual(undefined) - expect(objGetValue(obj, undefined)).toEqual(obj) - expect(objGetValue(obj, 'foo')).toEqual({ bar: 'baz' }) - expect(objGetValue(obj, 'foo.bar')).toEqual('baz') -}) diff --git a/test/jest.setup.js b/test/jest.setup.js index ea9a8fc4..8fa959d0 100644 --- a/test/jest.setup.js +++ b/test/jest.setup.js @@ -9,7 +9,8 @@ OF ANY KIND, either express or implied. See the License for the specific languag governing permissions and limitations under the License. */ -const path = require('path') +const path = require('node:path') +const fs = require('node:fs') const { stdout, stderr } = require('stdout-stderr') jest.setTimeout(30000) @@ -43,3 +44,18 @@ global.basicGeneratorOptions = { 'config-path': 'ext.config.yaml', 'full-key-to-manifest': 'runtimeManifest' } + +const fixturesFolder = path.join(__dirname, '__fixtures__') + +global.fixturePath = (file) => { + return `${fixturesFolder}/${file}` +} +// helper for fixtures +global.fixtureFile = (output) => { + return fs.readFileSync(global.fixturePath(output)).toString() +} + +// helper for fixtures +global.fixtureJson = (output) => { + return JSON.parse(global.fixtureFile(output)) +}