@salesforce/salesforcedx-vscode-test-tools
Version:
Test automation framework for Salesforce Extensions for VS Code
177 lines • 9.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDefaultScratchOrgViaCli = void 0;
exports.setUpScratchOrg = setUpScratchOrg;
exports.authorizeDevHub = authorizeDevHub;
exports.verifyAliasAndUserName = verifyAliasAndUserName;
exports.createDefaultScratchOrg = createDefaultScratchOrg;
exports.deleteScratchOrgInfo = deleteScratchOrgInfo;
/*
* Copyright (c) 2024, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
const environmentSettings_1 = require("../../src/environmentSettings");
const miscellaneous_1 = require("../core/miscellaneous");
const statusBar_1 = require("../ui-interaction/statusBar");
const cliCommands_1 = require("../system-operations/cliCommands");
const ui_interaction_1 = require("../ui-interaction");
const retryUtils_1 = require("../retryUtils");
/**
* Sets up a scratch org for testing
* @param testSetup - The test setup configuration
* @param scratchOrgEdition - The edition of the scratch org to create
*/
async function setUpScratchOrg(testSetup) {
await authorizeDevHub(testSetup);
return await (0, exports.createDefaultScratchOrgViaCli)(testSetup);
}
/**
* Authorizes a DevHub for use in tests
* @param testSetup - The test setup configuration
* @throws Error if DevHub alias or username are not set
*/
async function authorizeDevHub(testSetup) {
(0, miscellaneous_1.log)('');
(0, miscellaneous_1.log)(`${testSetup.testSuiteSuffixName} - Starting authorizeDevHub()...`);
// Only need to check this once.
if (!testSetup.aliasAndUserNameWereVerified) {
await verifyAliasAndUserName();
testSetup.aliasAndUserNameWereVerified = true;
}
// This is essentially the "SFDX: Authorize a Dev Hub" command, but using the CLI and an auth file instead of the UI.
if (!testSetup.projectFolderPath) {
throw new Error('Project folder path is not set');
}
// Call org:login:sfdx-url and read in the JSON that was just created.
(0, miscellaneous_1.log)(`${testSetup.testSuiteSuffixName} - calling sf org:login:sfdx-url...`);
await (0, cliCommands_1.orgLoginSfdxUrl)();
(0, miscellaneous_1.log)(`${testSetup.testSuiteSuffixName} - ...finished authorizeDevHub()`);
(0, miscellaneous_1.log)('');
}
/**
* Verifies that the alias and user name are set and match an org in the org list
* @throws Error if DevHub alias or username are not set or can't be found in org list
*/
async function verifyAliasAndUserName() {
const environmentSettings = environmentSettings_1.EnvironmentSettings.getInstance();
const devHubAliasName = environmentSettings.devHubAliasName;
if (!devHubAliasName) {
throw new Error('Error: devHubAliasName was not set.');
}
const devHubUserName = environmentSettings.devHubUserName;
if (!devHubUserName) {
throw new Error('Error: devHubUserName was not set.');
}
const execResult = await (0, cliCommands_1.orgList)();
const sfOrgListResult = JSON.parse(execResult.stdout).result;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nonScratchOrgs = sfOrgListResult.nonScratchOrgs;
for (let i = 0; i < nonScratchOrgs.length; i++) {
const nonScratchOrg = nonScratchOrgs[i];
if (nonScratchOrg.alias === devHubAliasName && nonScratchOrg.username === devHubUserName) {
return;
}
}
throw new Error(`Error: matching devHub alias '${devHubAliasName}' and devHub user name '${devHubUserName}' was not found.\nPlease consult README.md and make sure DEV_HUB_ALIAS_NAME and DEV_HUB_USER_NAME are set correctly.`);
}
const buildAlias = () => {
const currentDate = new Date();
const ticks = currentDate.getTime();
const day = ('0' + currentDate.getDate()).slice(-2);
const month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
const year = currentDate.getFullYear();
const currentOsUserName = (0, miscellaneous_1.transformedUserName)();
return `TempScratchOrg_${year}_${month}_${day}_${currentOsUserName}_${ticks}_OrgAuth`;
};
const createDefaultScratchOrgViaCli = async (testSetup) => {
const scratchOrgAliasName = buildAlias();
testSetup.scratchOrgAliasName = scratchOrgAliasName;
const orgCreateResult = await (0, cliCommands_1.scratchOrgCreate)('developer', 'NONE', testSetup.scratchOrgAliasName, 1);
if (orgCreateResult.exitCode > 0) {
throw new Error(`Error: creating scratch org failed with exit code ${orgCreateResult.exitCode}\n stderr ${orgCreateResult.stderr}`);
}
testSetup.scratchOrgId = JSON.parse(orgCreateResult.stdout).result.id;
return testSetup;
};
exports.createDefaultScratchOrgViaCli = createDefaultScratchOrgViaCli;
/**
* Creates a default scratch org for testing
* @param testSetup - The test setup configuration
* @param edition - The edition of the scratch org to create (defaults to 'developer')
* @throws Error if scratch org creation fails
* @private
*/
async function createDefaultScratchOrg() {
(0, miscellaneous_1.log)('Creating a default scratch org...');
return await (0, retryUtils_1.retryOperation)(async () => {
const prompt = await (0, ui_interaction_1.executeQuickPick)('SFDX: Create a Default Scratch Org...', miscellaneous_1.Duration.seconds(1));
// Select a project scratch definition file (config/project-scratch-def.json)
await prompt.confirm();
// Enter an org alias - yyyy-mm-dd-username-ticks
const currentDate = new Date();
const ticks = currentDate.getTime();
const day = ('0' + currentDate.getDate()).slice(-2);
const month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
const year = currentDate.getFullYear();
const currentOsUserName = (0, miscellaneous_1.transformedUserName)();
const scratchOrgAliasName = `TempScratchOrg_${year}_${month}_${day}_${currentOsUserName}_${ticks}_OrgAuth`;
await prompt.setText(scratchOrgAliasName);
await (0, miscellaneous_1.pause)(miscellaneous_1.Duration.seconds(1));
// Press Enter/Return.
await prompt.confirm();
// Enter the number of days.
await prompt.setText('1');
await (0, miscellaneous_1.pause)(miscellaneous_1.Duration.seconds(1));
// Press Enter/Return.
await prompt.confirm();
const successNotificationWasFound = await (0, retryUtils_1.verifyNotificationWithRetry)(/SFDX: Create a Default Scratch Org\.\.\. successfully ran/);
if (successNotificationWasFound !== true) {
const failureNotificationWasFound = await (0, retryUtils_1.verifyNotificationWithRetry)(/SFDX: Create a Default Scratch Org\.\.\. failed to run/);
if (failureNotificationWasFound === true) {
if (await (0, ui_interaction_1.attemptToFindOutputPanelText)('Salesforce CLI', 'organization has reached its daily scratch org signup limit', 5)) {
// This is a known issue...
(0, miscellaneous_1.log)('Warning - creating the scratch org failed, but the failure was due to the daily signup limit');
}
else if (await (0, ui_interaction_1.attemptToFindOutputPanelText)('Salesforce CLI', 'is enabled as a Dev Hub', 5)) {
// This is a known issue...
(0, miscellaneous_1.log)('Warning - Make sure that the org is enabled as a Dev Hub.');
(0, miscellaneous_1.log)('Warning - To enable it, open the org in your browser, navigate to the Dev Hub page in Setup, and click Enable.');
(0, miscellaneous_1.log)('Warning - If you still see this error after enabling the Dev Hub feature, then re-authenticate to the org.');
}
else {
// The failure notification is showing, but it's not due to maxing out the daily limit. What to do...?
(0, miscellaneous_1.log)('Warning - creating the scratch org failed... not sure why...');
}
}
else {
(0, miscellaneous_1.log)('Warning - creating the scratch org failed... neither the success notification or the failure notification was found.');
}
// Throw error to trigger retry if success notification was not found
throw new Error('Scratch org creation failed - success notification not found');
}
// Look for the org's alias name in the list of status bar items.
const scratchOrgStatusBarItem = await (0, statusBar_1.getStatusBarItemWhichIncludes)(scratchOrgAliasName);
if (!scratchOrgStatusBarItem) {
throw new Error('Scratch org status bar item not found');
}
return scratchOrgAliasName;
}, 3, 'Failed to create default scratch org');
}
/**
* Deletes scratch org information from the DevHub
* @param testSetup - The test setup configuration
* @throws Error if deletion fails
*/
async function deleteScratchOrgInfo(testSetup) {
if (testSetup.scratchOrgId) {
const sfDataDeleteRecord = await (0, cliCommands_1.runCliCommand)('data:delete:record', '--sobject', 'ScratchOrgInfo', '--where', `ScratchOrg=${testSetup.scratchOrgId.slice(0, -3)}`, '--target-org', environmentSettings_1.EnvironmentSettings.getInstance().devHubAliasName);
if (sfDataDeleteRecord.exitCode > 0) {
const message = `data delete record failed with exit code ${sfDataDeleteRecord.exitCode}\n stderr ${sfDataDeleteRecord.stderr}`;
(0, miscellaneous_1.log)(message);
throw new Error(message);
}
}
}
//# sourceMappingURL=authorization.js.map