Skip to content

Commit

Permalink
refactor: switch to nuts
Browse files Browse the repository at this point in the history
  • Loading branch information
mshanemc committed Nov 15, 2021
1 parent 873875a commit 60e64f5
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 195 deletions.
5 changes: 5 additions & 0 deletions command-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,10 @@
"command": "force:user:permset:assign",
"plugin": "@salesforce/plugin-user",
"flags": ["apiversion", "json", "loglevel", "onbehalfof", "permsetname", "targetusername"]
},
{
"command": "force:user:permsetlicense:assign",
"plugin": "@salesforce/plugin-user",
"flags": ["apiversion", "json", "loglevel", "name", "onbehalfof", "targetusername"]
}
]
83 changes: 38 additions & 45 deletions src/commands/force/user/permsetlicense/assign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import * as os from 'os';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { Aliases, Connection, Messages, User, AuthInfo, Org, UserFields, SfdxError } from '@salesforce/core';
import { Aliases, Connection, Messages, User, AuthInfo, Org, UserFields } from '@salesforce/core';

Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-user', 'permsetlicense.assign');
Expand All @@ -22,7 +22,7 @@ type FailureMsg = {
message: string;
};

type Result = {
export type PSLResult = {
successes: SuccessMsg[];
failures: FailureMsg[];
};
Expand All @@ -46,59 +46,52 @@ export class UserPermsetLicenseAssignCommand extends SfdxCommand {
description: messages.getMessage('flags.onBehalfOf'),
}),
};
private usernames: string[];
private readonly successes: SuccessMsg[] = [];
private readonly failures: FailureMsg[] = [];

public async run(): Promise<Result> {
try {
this.usernames = this.flags.onbehalfof ?? [this.org.getUsername()];
public async run(): Promise<PSLResult> {
const usernames = (this.flags.onbehalfof as string[]) ?? [this.org.getUsername()];

for (const username of this.usernames) {
// Convert any aliases to usernames
const aliasOrUsername = (await Aliases.fetch(username)) || username;
const connection: Connection = await Connection.create({
authInfo: await AuthInfo.create({ username }),
for (const username of usernames) {
// Convert any aliases to usernames
const aliasOrUsername = (await Aliases.fetch(username)) || username;
const connection: Connection = await Connection.create({
authInfo: await AuthInfo.create({ username }),
});
const org = await Org.create({ connection });
const user: User = await User.create({ org });
const fields: UserFields = await user.retrieve(username);

const pslName = this.flags.name as string;

const psl = await connection.singleRecordQuery<PermissionSetLicense>(
`select Id from PermissionSetLicense where DeveloperName = '${pslName}' or MasterLabel = '${pslName}'`
);

try {
await connection.sobject('PermissionSetLicenseAssign').create({
AssigneeId: fields.id,
PermissionSetLicenseId: psl.Id,
});
const org = await Org.create({ connection });
const user: User = await User.create({ org });
const fields: UserFields = await user.retrieve(username);

const pslName = this.flags.name as string;

const psl = (
await connection.query(
`select Id from PermissionSetLicense where DeveloperName = '${pslName}' or MasterLabel = '${pslName}'`
)
).records[0] as PermissionSetLicense;

try {
await connection.sobject('PermissionSetLicenseAssign').create({
AssigneeId: fields.id,
PermissionSetLicenseId: psl.Id,
});
this.successes.push({
name: aliasOrUsername,
value: this.flags.name as string,
});
} catch (e) {
// idempotency. If user(s) already have PSL, the API will throw an error about duplicate value.
if (e instanceof Error && e.message.startsWith('duplicate value found')) {
this.ux.warn(messages.getMessage('duplicateValue', [aliasOrUsername, pslName]));
this.successes.push({
name: aliasOrUsername,
value: this.flags.name,
value: pslName,
});
} else {
this.failures.push({
name: aliasOrUsername,
message: e instanceof Error ? e.message : 'error contained no message',
});
} catch (e) {
// idempotency. If user(s) already have PSL, the API will throw an error about duplicate value.
if (e.message.startsWith('duplicate value found')) {
this.ux.warn(messages.getMessage('duplicateValue', [aliasOrUsername, this.flags.name]));
this.successes.push({
name: aliasOrUsername,
value: this.flags.name,
});
} else {
this.failures.push({
name: aliasOrUsername,
message: e.message,
});
}
}
}
} catch (e) {
throw SfdxError.wrap(e);
}

this.print();
Expand Down
78 changes: 0 additions & 78 deletions test/commands/user/display.e2e.ts

This file was deleted.

72 changes: 0 additions & 72 deletions test/commands/user/permsetlicense/assign.e2e.ts

This file was deleted.

64 changes: 64 additions & 0 deletions test/commands/user/permsetlicense/assign.nut.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2020, 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
*/
import * as path from 'path';
import { TestSession, execCmd } from '@salesforce/cli-plugins-testkit';
import { expect } from 'chai';
import { PSLResult } from '../../../../src/commands/force/user/permsetlicense/assign';

type PSLResultWithWarnings = PSLResult & { warnings?: string[] };
describe('PermissionSetLicense tests', () => {
const testPSL = 'WaveEmbeddedApp';
let session: TestSession;

before(async () => {
session = await TestSession.create({
project: {
sourceDir: path.join('test', 'df17AppBuilding'),
},
// create org and push source to get a permset
setupCommands: [
`sfdx force:org:create -d 1 -s -f ${path.join('config', 'project-scratch-def.json')}`,
'sfdx force:source:push',
],
});
});

it('assigns a psl to default user', () => {
const commandResult = execCmd<PSLResultWithWarnings>(`sfdx force:user:permsetlicense:assign -n ${testPSL} --json`, {
ensureExitCode: 0,
}).jsonOutput.result;
expect(commandResult.failures).to.be.an('array').with.length(0);
expect(commandResult.successes).to.deep.equal([{ value: 'WaveEmbeddedApp' }]);
expect(commandResult).to.not.have.property('warnings');
});

it('assigns a psl to default user successfully if already assigned', () => {
const commandResult = execCmd<PSLResultWithWarnings>(`sfdx force:user:permsetlicense:assign -n ${testPSL} --json`, {
ensureExitCode: 0,
}).jsonOutput.result;
expect(commandResult.failures).to.be.an('array').with.length(0);
expect(commandResult.successes).to.deep.equal([{ value: 'WaveEmbeddedApp' }]);
expect(commandResult.warnings).to.be.an('array').with.length(1);
expect(commandResult.warnings[0]).to.include(testPSL);
});

it('fails properly for non-existing psl', () => {
const badPSL = 'badPSL';
const commandResult = execCmd<PSLResultWithWarnings>(`sfdx force:user:permsetlicense:assign -n ${badPSL} --json`, {
ensureExitCode: 1,
}).jsonOutput.result;
expect(commandResult.successes).to.be.an('array').with.length(0);
expect(commandResult.failures).to.be.an('array').with.length.greaterThan(0);
});

it('assigns a psl to multiple users via onBehalfOf', async () => {});

after(async () => {
await session.zip(undefined, 'artifacts');
await session.clean();
});
});

0 comments on commit 60e64f5

Please sign in to comment.