generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathsource.test.ts
More file actions
374 lines (346 loc) · 13.1 KB
/
source.test.ts
File metadata and controls
374 lines (346 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*
* Copyright 2026, Salesforce, Inc.
*
* 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.
*/
import fs from 'node:fs';
import sinon from 'sinon';
import { expect } from 'chai';
import {
ComponentSet,
ComponentSetBuilder,
ComponentSetOptions,
RegistryAccess,
SourceComponent,
} from '@salesforce/source-deploy-retrieve';
import { Lifecycle, SfProject } from '@salesforce/core';
import { fromStub, spyMethod, stubInterface, stubMethod } from '@salesforce/ts-sinon';
import { Config } from '@oclif/core';
import { MockTestOrgData, TestContext } from '@salesforce/core/testSetup';
import { SfCommand } from '@salesforce/sf-plugins-core';
import { ComponentProperties } from '@salesforce/source-deploy-retrieve/lib/src/resolve/sourceComponent.js';
import { Source } from '../../../src/commands/project/delete/source.js';
import { DeployCache } from '../../../src/utils/deployCache.js';
export const exampleSourceComponent: ComponentProperties = {
name: 'GeocodingService',
type: {
id: 'apexclass',
name: 'ApexClass',
suffix: 'cls',
directoryName: 'classes',
inFolder: false,
strictDirectoryName: false,
strategies: {
adapter: 'matchingContentFile',
},
},
xml: '/dreamhouse-lwc/force-app/main/default/classes/GeocodingService.cls-meta.xml',
content: '/dreamhouse-lwc/force-app/main/default/classes/GeocodingService.cls',
};
const registry = new RegistryAccess();
const agentComponents: SourceComponent[] = [
new SourceComponent({
name: 'My_Agent',
type: registry.getTypeByName('Bot'),
xml: '/dreamhouse-lwc/force-app/main/default/bots/My_Agent.bot-meta.xml',
}),
new SourceComponent({
name: 'Test_Planner',
type: registry.getTypeByName('GenAiPlanner'),
xml: '/dreamhouse-lwc/force-app/main/default/genAiPlanners/Test_Planner.genAiPlanner-meta.xml',
}),
new SourceComponent({
name: 'Test_Plugin1',
type: registry.getTypeByName('GenAiPlugin'),
xml: '/dreamhouse-lwc/force-app/main/default/genAiPlugins/Test_Plugin1.genAiPlugin-meta.xml',
}),
new SourceComponent({
name: 'Test_Plugin2',
type: registry.getTypeByName('GenAiPlugin'),
xml: '/dreamhouse-lwc/force-app/main/default/genAiPlugins/Test_Plugin2.genAiPlugin-meta.xml',
}),
];
export const exampleDeleteResponse = {
// required but ignored by the delete UT
getFileResponses: (): void => {},
response: {
canceledBy: '0051h000006BHOq',
canceledByName: 'User User',
checkOnly: false,
completedDate: '2021-04-09T20:23:05.000Z',
createdBy: '0051h000006BHOq',
createdByName: 'User User',
createdDate: '2021-04-09T20:22:58.000Z',
details: {
componentSuccesses: [
{
changed: 'false',
componentType: 'CustomField',
created: 'false',
createdDate: '2021-04-09T20:23:02.000Z',
deleted: 'false',
fileName: 'sdx_sourceDeploy_pkg_1617999776176/objects/Property__c.object',
fullName: 'Property__c.Picture__c',
id: '00N1h00000ApoBMEAZ',
success: 'true',
},
{
changed: 'false',
componentType: 'CustomField',
created: 'false',
createdDate: '2021-04-09T20:23:02.000Z',
deleted: 'false',
fileName: 'sdx_sourceDeploy_pkg_1617999776176/objects/Property__c.object',
fullName: 'Property__c.Baths__c',
id: '00N1h00000ApoAuEAJ',
success: 'true',
},
],
runTestResult: {
numFailures: '0',
numTestsRun: '0',
totalTime: '0.0',
},
},
done: true,
id: '0Af1h00000fCQgsCAG',
ignoreWarnings: false,
lastModifiedDate: '2021-04-09T20:23:05.000Z',
numberComponentErrors: 0,
numberComponentsDeployed: 32,
numberComponentsTotal: 86,
numberTestErrors: 0,
numberTestsCompleted: 5,
numberTestsTotal: 10,
rollbackOnError: true,
runTestsEnabled: false,
startDate: '2021-04-09T20:22:58.000Z',
status: 'Succeeded',
success: true,
},
status: 0,
};
describe('project delete source', () => {
const $$ = new TestContext();
const testOrg = new MockTestOrgData();
testOrg.username = 'delete-test@org.com';
const defaultPackagePath = 'defaultPackagePath';
const confirm = true;
const oclifConfigStub = fromStub(
stubInterface<Config>($$.SANDBOX, { runHook: async () => ({ failures: [], successes: [] }) })
);
// Stubs
let buildComponentSetStub: sinon.SinonStub;
let lifecycleEmitStub: sinon.SinonStub;
let resolveProjectConfigStub: sinon.SinonStub;
let rmStub: sinon.SinonStub;
let compSetFromSourceStub: sinon.SinonStub;
let handlePromptStub: sinon.SinonStub;
class TestDelete extends Source {
public async runIt() {
await this.init();
// oclif would normally populate this, but UT don't have it
this.id ??= 'force:source:delete';
return this.run();
}
}
const runDeleteCmd = async (
params: string[],
options?: {
sourceApiVersion?: string;
inquirerMock?: { checkbox: sinon.SinonStub };
}
) => {
const cmd = new TestDelete(params, oclifConfigStub);
cmd.project = SfProject.getInstance();
$$.SANDBOX.stub(cmd.project, 'getDefaultPackage').returns({ name: '', path: '', fullPath: defaultPackagePath });
$$.SANDBOX.stub(cmd.project, 'getUniquePackageDirectories').returns([
{ fullPath: defaultPackagePath, path: '', name: '' },
]);
$$.SANDBOX.stub(cmd.project, 'getPackageDirectories').returns([
{ fullPath: defaultPackagePath, path: '', name: '' },
]);
$$.SANDBOX.stub(cmd.project, 'resolveProjectConfig').resolves({ sourceApiVersion: options?.sourceApiVersion });
stubMethod($$.SANDBOX, SfCommand.prototype, 'log');
stubMethod($$.SANDBOX, ComponentSet.prototype, 'deploy').resolves({
id: '123',
pollStatus: () => exampleDeleteResponse,
onUpdate: () => {},
onFinish: () => {
exampleDeleteResponse;
},
onCancel: () => {},
onError: () => {},
});
handlePromptStub = stubMethod($$.SANDBOX, cmd, 'handlePrompt').returns(confirm);
if (options?.inquirerMock) {
// @ts-expect-error stubbing private member of the command
cmd.inquirer = options.inquirerMock;
} else {
// @ts-expect-error stubbing private member of the command
cmd.inquirer = { checkbox: $$.SANDBOX.stub().resolves([]) };
}
rmStub = stubMethod($$.SANDBOX, fs.promises, 'rm').resolves();
stubMethod($$.SANDBOX, DeployCache, 'update').resolves();
return cmd.runIt();
};
beforeEach(async () => {
await $$.stubAuths(testOrg);
await $$.stubConfig({ 'target-org': testOrg.username });
resolveProjectConfigStub = $$.SANDBOX.stub();
buildComponentSetStub = stubMethod($$.SANDBOX, ComponentSetBuilder, 'build').resolves({
toArray: () => [new SourceComponent(exampleSourceComponent)],
});
const lifecycle = Lifecycle.getInstance();
lifecycleEmitStub = $$.SANDBOX.stub(lifecycle, 'emit');
compSetFromSourceStub = stubMethod($$.SANDBOX, ComponentSet, 'fromSource').returns({
toArray: () => [new SourceComponent(exampleSourceComponent)],
});
});
afterEach(() => {
$$.restore();
$$.SANDBOX.restore();
});
// Ensure SourceCommand.createComponentSet() args
const ensureCreateComponentSetArgs = (overrides?: Partial<ComponentSetOptions>) => {
const defaultArgs = {
sourcepath: undefined,
metadata: undefined,
apiversion: undefined,
sourceapiversion: undefined,
};
const expectedArgs = { ...defaultArgs, ...overrides };
expect(buildComponentSetStub.calledOnce).to.equal(true);
expect(buildComponentSetStub.firstCall.args[0]).to.deep.include(expectedArgs);
};
// Ensure Lifecycle hooks are called properly
const ensureHookArgs = () => {
const failureMsg = 'Lifecycle.emit() should be called for predeploy and postdeploy';
expect(lifecycleEmitStub.calledTwice, failureMsg).to.equal(true);
expect(lifecycleEmitStub.firstCall.args[0]).to.equal('predeploy');
expect(lifecycleEmitStub.secondCall.args[0]).to.equal('postdeploy');
};
it('should pass along sourcepath', async () => {
const sourcepath = ['somepath'];
await runDeleteCmd(['--sourcepath', sourcepath[0], '--json', '-r']);
ensureCreateComponentSetArgs({ sourcepath });
ensureHookArgs();
// deleting the component and its xml
expect(rmStub.callCount).to.equal(2);
});
it('should warn if everything is forceignored', async () => {
buildComponentSetStub.restore();
const warnSpy = spyMethod($$.SANDBOX, SfCommand.prototype, 'warn');
buildComponentSetStub = stubMethod($$.SANDBOX, ComponentSetBuilder, 'build').resolves({
forceIgnoredPaths: new Set<string>('myPath'),
toArray: () => [],
});
await runDeleteCmd(['--metadata', 'ApexClass:MyClass', '--json', '-r']);
expect(warnSpy.calledOnce).to.be.true;
});
it('should pass along metadata', async () => {
const metadata = ['ApexClass:MyClass'];
await runDeleteCmd(['--metadata', metadata[0], '--json', '-r']);
ensureCreateComponentSetArgs({
metadata: {
metadataEntries: metadata,
directoryPaths: [defaultPackagePath],
},
});
ensureHookArgs();
});
it('should pass along metadata and org for pseudo-type matching with plugins', async () => {
const agentCompSet = new ComponentSet();
const pluginNames = [agentComponents[2].name, agentComponents[3].name];
agentComponents.map((comp) => agentCompSet.add(comp));
compSetFromSourceStub = compSetFromSourceStub.returns(agentCompSet);
const inquirerCheckboxStub = $$.SANDBOX.stub().resolves(pluginNames);
const inquirerMock = { checkbox: inquirerCheckboxStub };
const metadata = ['Agent:My_Agent'];
await runDeleteCmd(['--metadata', metadata[0], '--json'], { inquirerMock });
ensureCreateComponentSetArgs({
metadata: {
metadataEntries: metadata,
directoryPaths: [defaultPackagePath],
},
org: {
username: testOrg.username,
exclude: [],
},
});
ensureHookArgs();
expect(compSetFromSourceStub.calledOnce).to.be.true;
expect(inquirerCheckboxStub.calledOnce).to.be.true;
expect(inquirerCheckboxStub.firstCall.firstArg).has.property('message', 'Select related topics to delete');
expect(inquirerCheckboxStub.firstCall.firstArg).has.deep.property('choices', [
{ name: 'Test_Plugin1', value: 'Test_Plugin1' },
{ name: 'Test_Plugin2', value: 'Test_Plugin2' },
]);
expect(handlePromptStub.calledOnce).to.be.true;
expect(lifecycleEmitStub.firstCall.args[1]).to.deep.equal(agentComponents);
});
it('should pass along metadata and org for pseudo-type matching without plugins', async () => {
const agentCompSet = new ComponentSet();
agentComponents.map((comp) => agentCompSet.add(comp));
compSetFromSourceStub = compSetFromSourceStub.returns(agentCompSet);
const inquirerCheckboxStub = $$.SANDBOX.stub().resolves([]);
const inquirerMock = { checkbox: inquirerCheckboxStub };
const metadata = ['Agent:My_Agent'];
await runDeleteCmd(['--metadata', metadata[0], '--json'], { inquirerMock });
ensureCreateComponentSetArgs({
metadata: {
metadataEntries: metadata,
directoryPaths: [defaultPackagePath],
},
org: {
username: testOrg.username,
exclude: [],
},
});
ensureHookArgs();
expect(compSetFromSourceStub.calledOnce).to.be.true;
expect(inquirerCheckboxStub.calledOnce).to.be.true;
expect(inquirerCheckboxStub.firstCall.firstArg).has.deep.property('choices', [
{ name: 'Test_Plugin1', value: 'Test_Plugin1' },
{ name: 'Test_Plugin2', value: 'Test_Plugin2' },
]);
expect(handlePromptStub.calledOnce).to.be.true;
expect(lifecycleEmitStub.firstCall.args[1]).to.deep.equal([agentComponents[0], agentComponents[1]]);
});
it('should pass along apiversion', async () => {
const metadata = ['ApexClass:MyClass'];
await runDeleteCmd(['--metadata', metadata[0], '--json', '-r', '--apiversion', '52.0']);
ensureCreateComponentSetArgs({
metadata: {
metadataEntries: metadata,
directoryPaths: [defaultPackagePath],
},
apiversion: '52.0',
});
ensureHookArgs();
});
it('should pass along sourceapiversion', async () => {
const sourceApiVersion = '50.0';
const metadata = ['ApexClass:MyClass'];
resolveProjectConfigStub.resolves({ sourceApiVersion });
await runDeleteCmd(['--metadata', metadata[0], '--json', '-r'], { sourceApiVersion });
ensureCreateComponentSetArgs({
sourceapiversion: sourceApiVersion,
metadata: {
metadataEntries: metadata,
directoryPaths: [defaultPackagePath],
},
});
ensureHookArgs();
});
});