Skip to content

Commit

Permalink
feat: parking orbit (core3, jsforce2)
Browse files Browse the repository at this point in the history
  • Loading branch information
mshanemc committed May 31, 2022
1 parent 5ac6096 commit 4575f9c
Show file tree
Hide file tree
Showing 15 changed files with 519 additions and 476 deletions.
1 change: 1 addition & 0 deletions .mocharc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"require": "test/init.js, ts-node/register, source-map-support/register",
"watch-extensions": "ts",
"watch-files": ["test/**/*.ts", "src/**/*.ts"],
"recursive": true,
"reporter": "spec",
"timeout": 5000
Expand Down
7 changes: 2 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@salesforce/cli-plugins-testkit",
"description": "Provides test utilities to assist Salesforce CLI plug-in authors with writing non-unit tests (NUT).",
"version": "1.5.35",
"version": "2.0.0",
"author": "Salesforce",
"license": "BSD-3-Clause",
"main": "lib/index.js",
Expand Down Expand Up @@ -42,7 +42,7 @@
"!lib/**/*.map"
],
"dependencies": {
"@salesforce/core": "^2.24.0",
"@salesforce/core": "^3.19.1",
"@salesforce/kit": "^1.5.13",
"@salesforce/ts-types": "^1.5.17",
"archiver": "^5.2.0",
Expand All @@ -58,9 +58,6 @@
"@salesforce/ts-sinon": "^1.3.18",
"@types/archiver": "^5.1.0",
"@types/debug": "^4.1.5",
"@types/graceful-fs": "^4.1.5",
"@types/jsforce": "^1.9.29",
"@types/mkdirp": "^1.0.1",
"@types/shelljs": "^0.8.8",
"@typescript-eslint/eslint-plugin": "^4.26.0",
"@typescript-eslint/parser": "^4.26.0",
Expand Down
9 changes: 4 additions & 5 deletions samples/generateSamplesDoc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as path from 'path';
import * as os from 'os';
import { fs as fsCore } from '@salesforce/core';

import * as fs from 'fs';
// The structure of topic content in topics.json.
type SamplesContent = {
header: string;
Expand Down Expand Up @@ -48,7 +47,7 @@ function replaceImports(nut: string): string {

// Reads topics.json for configuration and doc structure. Writes SAMPLES.md.
(function generateSamples() {
const topics = fsCore.readJsonSync(path.join(__dirname, 'topics.json')) as SamplesTopic[];
const topics = JSON.parse(fs.readFileSync(path.join(__dirname, 'topics.json'), 'utf8')) as SamplesTopic[];

const fileModificationWarning = `<!--${os.EOL}WARNING: THIS IS A GENERATED FILE. DO NOT MODIFY DIRECTLY. USE topics.json${os.EOL}-->${os.EOL}`;

Expand All @@ -72,7 +71,7 @@ function replaceImports(nut: string): string {

if (samplesContent.file) {
sampleContents.push(`\`\`\`${topic.type}${os.EOL}`);
const nut = fsCore.readFileSync(path.join(__dirname, samplesContent.file)).toString();
const nut = fs.readFileSync(path.join(__dirname, samplesContent.file)).toString();
const replacedNut = replaceImports(nut);
sampleContents.push(`${replacedNut}${os.EOL}`);
sampleContents.push(`\`\`\`${os.EOL}${os.EOL}`);
Expand Down Expand Up @@ -100,5 +99,5 @@ function replaceImports(nut: string): string {

const samplesFileContent = [...tableOfContents, ...sampleContents];
const samplesFilePath = path.join(process.cwd(), 'SAMPLES.md');
fsCore.writeFileSync(samplesFilePath, samplesFileContent.join(''));
fs.writeFileSync(samplesFilePath, samplesFileContent.join(''));
})();
13 changes: 7 additions & 6 deletions src/execCmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
* 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
*/
import * as fs from 'fs';

import { join as pathJoin, resolve as pathResolve } from 'path';
import { inspect } from 'util';
import { fs, SfdxError } from '@salesforce/core';
import { SfError } from '@salesforce/core';
import { Duration, env, parseJson } from '@salesforce/kit';
import { AnyJson, isNumber } from '@salesforce/ts-types';
import Debug from 'debug';
Expand Down Expand Up @@ -64,14 +65,14 @@ export interface SfdxExecCmdResult<T = Collection> extends ExecCmdResult {
/**
* Command output parsed as JSON, if `--json` param present.
*/
jsonOutput?: { status: number; result: T } & Partial<ExcludeMethods<SfdxError>>;
jsonOutput?: { status: number; result: T } & Partial<ExcludeMethods<SfError>>;
}

export interface SfExecCmdResult<T = Collection> extends ExecCmdResult {
/**
* Command output parsed as JSON, if `--json` param present.
*/
jsonOutput?: { status: number; result: T } & Partial<ExcludeMethods<SfdxError>>;
jsonOutput?: { status: number; result: T } & Partial<ExcludeMethods<SfError>>;
}

const DEFAULT_EXEC_OPTIONS: ExecCmdOptions = {
Expand Down Expand Up @@ -120,22 +121,22 @@ const getExitCodeError = (cmd: string, expectedCode: number, output: ShellString
*
* The executable preference order is:
* 2. TESTKIT_EXECUTABLE_PATH env var
* 3. `bin/run` (default)
* 3. `bin/dev` (default)
*
* @param cmdArgs The command name, args, and param as a string. E.g., `"force:user:create -a testuser1"`
* @returns The command string with CLI executable. E.g., `"node_modules/bin/sfdx force:user:create -a testuser1"`
*/
const buildCmd = (cmdArgs: string, options?: ExecCmdOptions): string => {
const debug = Debug('testkit:buildCmd');

const bin = env.getString('TESTKIT_EXECUTABLE_PATH') || pathJoin('bin', 'run');
const bin = env.getString('TESTKIT_EXECUTABLE_PATH') ?? pathJoin('bin', 'dev');
const which = shelljs.which(bin);
let resolvedPath = pathResolve(bin);

// If which finds the path in the system path, use that.
if (which) {
resolvedPath = which;
} else if (!fs.fileExistsSync(bin)) {
} else if (!fs.existsSync(bin)) {
throw new Error(`Cannot find specified executable path: ${bin}`);
}

Expand Down
6 changes: 3 additions & 3 deletions src/hubAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
*/
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
import * as shell from 'shelljs';
import { debug } from 'debug';

import { AuthFields, fs } from '@salesforce/core';
import { AuthFields } from '@salesforce/core';
import { env } from '@salesforce/kit';

// this seems to be a known eslint error for enums
Expand Down Expand Up @@ -163,7 +163,7 @@ export const transferExistingAuthToEnv = (authStrategy: AuthStrategy = getAuthSt
logger(`reading ${devhub}.json`);
const authFileName = `${devhub}.json`;
const hubAuthFileSource = path.join(env.getString('HOME') || os.homedir(), '.sfdx', authFileName);
const authFileContents = fs.readJsonSync(hubAuthFileSource) as AuthFields;
const authFileContents = JSON.parse(fs.readFileSync(hubAuthFileSource, 'utf-8')) as AuthFields;
if (authFileContents.privateKey) {
logger('copying variables to env from AuthFile for JWT');
// this is jwt. set the appropriate env vars
Expand Down
5 changes: 2 additions & 3 deletions src/testProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
* 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
*/

import * as fs from 'fs';
import * as path from 'path';
import { tmpdir } from 'os';
import { inspect } from 'util';
import { debug, Debugger } from 'debug';
import * as shell from 'shelljs';
import { fs as fsCore } from '@salesforce/core';
import { env } from '@salesforce/kit';
import { genUniqueString } from './genUniqueString';
import { zipDir, ZipDirConfig } from './zip';
Expand Down Expand Up @@ -75,7 +74,7 @@ export class TestProject {
}
// the git clone will fail if the destination dir is not empty, so after
// a successful clone the only contents should be the cloned repo dir.
const cloneDirName = fsCore.readdirSync(destDir)[0];
const cloneDirName = fs.readdirSync(destDir)[0];
this.dir = path.join(destDir, cloneDirName);
}
// Create a new project using the command.
Expand Down
36 changes: 12 additions & 24 deletions src/testSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
* 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
*/
import * as fs from 'fs';
import * as path from 'path';
import { retry, RetryConfig, RetryError } from 'ts-retry-promise';
import { RetryConfig } from 'ts-retry-promise';
import { debug, Debugger } from 'debug';
import { fs as fsCore } from '@salesforce/core';
import { AsyncOptionalCreatable, Duration, env, parseJson, sleep } from '@salesforce/kit';
import { AnyJson, getString, Optional } from '@salesforce/ts-types';
import { createSandbox, SinonStub } from 'sinon';
Expand Down Expand Up @@ -116,7 +116,7 @@ export class TestSession extends AsyncOptionalCreatable<TestSessionOptions> {
// Create the test session directory
this.overriddenDir = env.getString('TESTKIT_SESSION_DIR') || this.options.sessionDir;
this.dir = this.overriddenDir || path.join(process.cwd(), `test_session_${this.id}`);
fsCore.mkdirpSync(this.dir);
fs.mkdirSync(this.dir, { recursive: true });

// Setup a test project and stub process.cwd to be the project dir
if (this.options.project) {
Expand All @@ -131,16 +131,20 @@ export class TestSession extends AsyncOptionalCreatable<TestSessionOptions> {
// TESTKIT_EXECUTABLE_PATH env var is not being used, then set it
// to use the bin/run from the cwd now.
if (!env.getString('TESTKIT_EXECUTABLE_PATH')) {
env.setString('TESTKIT_EXECUTABLE_PATH', path.join(process.cwd(), 'bin', 'run'));
const binDev = path.join(process.cwd(), 'bin', 'dev');
env.setString(
'TESTKIT_EXECUTABLE_PATH',
fs.existsSync(binDev) ? binDev : path.join(process.cwd(), 'bin', 'run')
);
}

this.stubCwd(projectDir);
}

// Write the test session options used to create this session
fsCore.writeJsonSync(
fs.writeFileSync(
path.join(this.dir, 'testSessionOptions.json'),
JSON.parse(JSON.stringify(this.options)) as AnyJson
JSON.stringify(JSON.parse(JSON.stringify(this.options)))
);

const authStrategy = this.options.authStrategy ? AuthStrategy[this.options.authStrategy] : undefined;
Expand Down Expand Up @@ -253,24 +257,8 @@ export class TestSession extends AsyncOptionalCreatable<TestSessionOptions> {
if (this.overriddenDir) {
return;
}
// this is wrapped in a promise because shelljs isn't async/await
return await retry(
() =>
new Promise<void>((resolve, reject) => {
this.debug(`Deleting test session dir: ${this.dir}`);
const rv = shell.rm('-rf', this.dir);
if (rv.code !== 0) {
reject(`Deleting the test session failed due to: ${rv.stderr}`);
}
resolve();
}),
this.rmRetryConfig
).catch((err) => {
if (err instanceof RetryError) {
throw err.lastError;
}
throw err;
});
this.debug(`Deleting test session dir: ${this.dir}`);
return fs.promises.rm(this.dir, { recursive: true, force: true });
}

// Executes commands and keeps track of any orgs created.
Expand Down
5 changes: 2 additions & 3 deletions src/zip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@
* 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
*/

import * as fs from 'fs';
import * as path from 'path';
import { create as createArchive } from 'archiver';
import Debug from 'debug';
import { fs as fsCore } from '@salesforce/core';

export interface ZipDirConfig {
/**
Expand Down Expand Up @@ -39,7 +38,7 @@ export const zipDir = async (config: ZipDirConfig): Promise<string> => {
const { sourceDir, destDir, name } = config;
const zip = createArchive('zip', { zlib: { level: 3 } });
const zipFilePath = path.join(destDir, name);
const output = fsCore.createWriteStream(zipFilePath);
const output = fs.createWriteStream(zipFilePath);
debug(`Zipping contents of ${sourceDir} to ${zipFilePath}`);

return new Promise((resolve, reject) => {
Expand Down
Loading

0 comments on commit 4575f9c

Please sign in to comment.