@codifycli/plugin-test 1.0.0-beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,83 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { ChildProcess } from 'node:child_process';
3
+ import { Readable } from 'stream';
4
+ import { TestUtils } from './test-utils.js';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+ import { MessageStatus } from '@codifycli/schemas';
7
+ import { nanoid } from 'nanoid';
8
+
9
+ describe('Test Utils tests', async () => {
10
+
11
+ const mockChildProcess = () => {
12
+ const process = new ChildProcess();
13
+ process.stdout = new EventEmitter() as Readable;
14
+ process.stderr = new EventEmitter() as Readable
15
+ process.send = () => true;
16
+
17
+ return process;
18
+ }
19
+
20
+ it('Sends the message that was passed in', async () => {
21
+ const process = mockChildProcess();
22
+ const sendMock = vi.spyOn(process, 'send');
23
+ const requestId = nanoid(6);
24
+
25
+ TestUtils.sendMessageAndAwaitResponse(process, { cmd: 'message', data: 'data', requestId })
26
+
27
+ expect(sendMock.mock.calls.length).to.eq(1);
28
+ expect(sendMock.mock.calls[0][0]).to.deep.eq({ cmd: 'message', data: 'data', requestId });
29
+ })
30
+
31
+ it('Send a message and receives a response from a plugin (success)', async () => {
32
+ const process = mockChildProcess();
33
+ const requestId = nanoid(6);
34
+
35
+ const result = await Promise.all([
36
+ (async () => {
37
+ await sleep(30);
38
+ // Note that the response must end in _Response. In accordance to the message schema rules.
39
+ process.emit('message', { cmd: 'message_Response', status: MessageStatus.SUCCESS, data: 'data', requestId })
40
+ })(),
41
+ TestUtils.sendMessageAndAwaitResponse(process, { cmd: 'message', data: 'data', requestId }),
42
+ ]);
43
+
44
+ expect(result[1]).to.eq('data')
45
+ });
46
+
47
+ it('Send a message and can handle errors', async () => {
48
+ const process = mockChildProcess();
49
+ const requestId = nanoid(6);
50
+
51
+ expect(async () => Promise.all([
52
+ (async () => {
53
+ await sleep(30);
54
+ // Note that the response must end in _Response. In accordance to the message schema rules.
55
+ process.emit('message', { cmd: 'message_Response', status: MessageStatus.ERROR, data: 'error message', requestId })
56
+ })(),
57
+ TestUtils.sendMessageAndAwaitResponse(process, { cmd: 'message', data: 'data', requestId }),
58
+ ])).rejects.toThrowError(new Error('error message'))
59
+ });
60
+
61
+ it('Ignores other IPC messages', async () => {
62
+ const process = mockChildProcess();
63
+
64
+ const requestId = nanoid(6);
65
+
66
+ const result = await Promise.all([
67
+ (async () => {
68
+ await sleep(30);
69
+ process.emit('message', { cmd: 'randomMessage1', status: MessageStatus.SUCCESS, data: 'message1', requestId: nanoid(6) })
70
+ process.emit('message', { cmd: 'randomMessage2', status: MessageStatus.SUCCESS, data: 'message2', requestId: nanoid(6) })
71
+ process.emit('message', { cmd: 'message_Response', status: MessageStatus.SUCCESS, data: 'data', requestId })
72
+ })(),
73
+ TestUtils.sendMessageAndAwaitResponse(process, { cmd: 'message', data: 'data', requestId }),
74
+ ]);
75
+
76
+ // Only the final _Response message should be returned.
77
+ expect(result[1]).to.eq('data')
78
+ });
79
+ });
80
+
81
+ async function sleep(ms: number) {
82
+ return new Promise((resolve, reject) => setTimeout(resolve, ms))
83
+ }
@@ -0,0 +1,147 @@
1
+ import Ajv from 'ajv';
2
+ import { IpcMessageSchema, IpcMessageV2, MessageStatus, ResourceOs, SpawnStatus } from '@codifycli/schemas';
3
+ import { ChildProcess } from 'node:child_process';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ import { PluginTester } from './plugin-tester.js';
8
+ import { testSpawn } from './spawn.js';
9
+
10
+ const ajv = new Ajv.default({
11
+ strict: true
12
+ });
13
+ const ipcMessageValidator = ajv.compile(IpcMessageSchema);
14
+
15
+ export const TestUtils = {
16
+ sendMessageAndAwaitResponse(process: ChildProcess, message: IpcMessageV2): Promise<any> {
17
+ return new Promise((resolve, reject) => {
18
+ process.on('message', (response: IpcMessageV2) => {
19
+ if (!ipcMessageValidator(response)) {
20
+ throw new Error(`Invalid message from plugin. ${JSON.stringify(message, null, 2)}`);
21
+ }
22
+
23
+ // Wait for the message response. Other messages such as sudoRequest may be sent before the response returns
24
+ if (response.requestId === message.requestId) {
25
+ if (response.status === MessageStatus.SUCCESS) {
26
+ resolve(response.data)
27
+ } else {
28
+ reject(new Error(String(response.data)))
29
+ }
30
+ }
31
+ });
32
+
33
+ // Send message last to ensure listeners are all registered
34
+ process.send(message);
35
+ });
36
+ },
37
+
38
+ async ensureHomebrewInstalledOnMacOs(pluginPath: string) {
39
+ const homebrewQuery = await testSpawn('which brew');
40
+ if (homebrewQuery.status !== SpawnStatus.SUCCESS) {
41
+ await PluginTester.install(pluginPath, [{ type: 'homebrew', os: [ResourceOs.MACOS] }])
42
+ }
43
+ },
44
+
45
+ async ensureXcodeInstalledOnMacOs(pluginPath: string) {
46
+ const xcodeQuery = await testSpawn('xcode-select -p');
47
+ if (xcodeQuery.status !== SpawnStatus.SUCCESS) {
48
+ await PluginTester.install(pluginPath, [{ type: 'xcode-tools', os: [ResourceOs.MACOS] }])
49
+ }
50
+ },
51
+
52
+
53
+ getShell(): 'bash' | 'zsh' {
54
+ const shell = process.env.SHELL || '';
55
+
56
+ if (shell.includes('bash')) {
57
+ return 'bash';
58
+ }
59
+
60
+ if (shell.includes('zsh')) {
61
+ return 'zsh';
62
+ }
63
+
64
+ // Default to bash for tests
65
+ return 'bash';
66
+ },
67
+
68
+ /**
69
+ * Get the primary shell rc file path
70
+ */
71
+ getPrimaryShellRc(): string {
72
+ const shell = TestUtils.getShell();
73
+ const homeDir = os.homedir();
74
+
75
+ if (shell === 'bash') {
76
+ return path.join(homeDir, '.bashrc')
77
+ }
78
+
79
+ if (shell === 'zsh') {
80
+ return path.join(homeDir, '.zshrc');
81
+ }
82
+
83
+ throw new Error('Unsupported shell')
84
+ },
85
+
86
+ /**
87
+ * Get the source command for the shell rc file
88
+ * Usage: execSync(TestUtils.getSourceCommand())
89
+ */
90
+ getSourceCommand(): string {
91
+ return `source ${TestUtils.getPrimaryShellRc()}`;
92
+ },
93
+
94
+ /**
95
+ * Get shell-specific command to run with sourced environment
96
+ * Usage: execSync(TestUtils.getShellCommand('which brew'))
97
+ */
98
+ getShellCommand(command: string): string {
99
+ return `${TestUtils.getSourceCommand()}; ${command}`;
100
+ },
101
+
102
+ /**
103
+ * Get shell name for execSync shell option
104
+ */
105
+ getShellName(): string {
106
+ return TestUtils.getShell();
107
+ },
108
+
109
+ /**
110
+ * Get interactive shell command
111
+ * Usage: execSync(TestUtils.getInteractiveCommand('my-alias'))
112
+ */
113
+ getInteractiveCommand(command: string): string {
114
+ const shell = TestUtils.getShell();
115
+
116
+ return shell === 'bash'
117
+ ? `bash -i -c "${command}"`
118
+ : `zsh -i -c "${command}"`;
119
+ },
120
+
121
+ /**
122
+ * Get which command output format based on shell
123
+ */
124
+ getAliasWhichCommand(aliasName: string): string {
125
+ const shell = TestUtils.getShell();
126
+
127
+ // zsh outputs: "alias_name: aliased to command"
128
+ // bash outputs: "alias alias_name='command'"
129
+ return shell === 'bash'
130
+ ? `${TestUtils.getShellCommand(`alias ${aliasName}`)}`
131
+ : `${TestUtils.getShellCommand(`which ${aliasName}`)}`;
132
+ },
133
+
134
+ /**
135
+ * Check if running on macOS
136
+ */
137
+ isMacOS(): boolean {
138
+ return os.platform() === 'darwin';
139
+ },
140
+
141
+ /**
142
+ * Check if running on Linux
143
+ */
144
+ isLinux(): boolean {
145
+ return os.platform() === 'linux';
146
+ },
147
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { ResourceConfig, ResourceOs, StringIndexedObject } from '@codifycli/schemas';
2
+ import os from 'node:os';
3
+
4
+ export function splitUserConfig<T extends StringIndexedObject>(
5
+ config: ResourceConfig & T
6
+ ): { parameters: T; coreParameters: ResourceConfig } {
7
+ const coreParameters = {
8
+ type: config.type,
9
+ ...(config.name ? { name: config.name } : {}),
10
+ ...(config.dependsOn ? { dependsOn: config.dependsOn } : {}),
11
+ ...(config.os ? { os: config.os } : {}),
12
+ };
13
+
14
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
15
+ const { type, name, dependsOn, os, ...parameters } = config;
16
+
17
+ return {
18
+ parameters: parameters as T,
19
+ coreParameters,
20
+ };
21
+ }
22
+
23
+ export function getPlatformOs(): ResourceOs{
24
+ const currOs = os.platform();
25
+ switch (currOs) {
26
+ case 'darwin': {
27
+ return ResourceOs.MACOS;
28
+ }
29
+
30
+ case 'linux': {
31
+ return ResourceOs.LINUX;
32
+ }
33
+
34
+ case 'win32': {
35
+ return ResourceOs.WINDOWS;
36
+ }
37
+
38
+ default: {
39
+ throw new Error(`Unsupported OS: ${currOs}`);
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,350 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { PluginTester } from '../src/index.js';
3
+ import path from 'node:path';
4
+ import { ResourceOperation } from '@codifycli/schemas';
5
+ import deepMatches from 'lodash.matches';
6
+ import differenceWith from 'lodash.differencewith';
7
+ import { PluginProcess } from '../src/plugin-process';
8
+ import * as fs from 'node:fs';
9
+ import { ResourceOs } from '@codifycli/schemas';
10
+
11
+ const pluginPath = path.join(__dirname, './test-plugin.ts');
12
+
13
+ describe('Plugin tester integration tests', () => {
14
+ let plugin: PluginProcess;
15
+ beforeEach(() => {
16
+ plugin = new PluginProcess(path.join(__dirname, './test-plugin.ts'));
17
+ })
18
+
19
+ afterEach(() => {
20
+ plugin.kill();
21
+ })
22
+
23
+ it('Can instantiate a plugin', async () => {
24
+ expect(plugin.childProcess.pid).to.not.be.undefined;
25
+ expect(plugin.childProcess.stdout).to.not.be.undefined;
26
+ expect(plugin.childProcess.stderr).to.not.be.undefined;
27
+ expect(plugin.childProcess.channel).to.not.be.undefined;
28
+
29
+ const result = await plugin.initialize();
30
+ expect(result).toMatchObject({
31
+ resourceDefinitions: expect.arrayContaining([
32
+ expect.objectContaining({ dependencies: [], type: 'test' }),
33
+ expect.objectContaining({ dependencies: [], type: 'test2' }),
34
+ expect.objectContaining({ dependencies: [], type: 'test-uninstall' }),
35
+ expect.objectContaining({ dependencies: [], type: 'test-modify' }),
36
+ expect.objectContaining({ dependencies: [], type: 'test-destroy' }),
37
+ expect.objectContaining({ dependencies: [], type: 'test-destroy-2' }),
38
+ ])
39
+ })
40
+ })
41
+
42
+ it('Can validate a config', async () => {
43
+ const result = await plugin.validate({
44
+ configs: [{
45
+ core: {
46
+ type: 'test',
47
+ },
48
+ parameters: {
49
+ propA: 'a',
50
+ propB: 2,
51
+ propC: 'c',
52
+ }
53
+ }]
54
+ })
55
+
56
+ expect(result.resourceValidations).toMatchObject([{
57
+ isValid: true,
58
+ }])
59
+ })
60
+
61
+ it('Can generate a plan', async () => {
62
+ const result = await plugin.plan({
63
+ core: {
64
+ type: 'test',
65
+ },
66
+ desired: {
67
+ propA: 'a',
68
+ propB: 10,
69
+ propC: 'c',
70
+ },
71
+ state: undefined,
72
+ isStateful: false,
73
+ })
74
+
75
+ expect(result).toMatchObject({
76
+ planId: expect.any(String),
77
+ operation: ResourceOperation.NOOP,
78
+ resourceType: 'test',
79
+ })
80
+ })
81
+
82
+ it('Can generate a plan', async () => {
83
+ const result = await plugin.plan({
84
+ core: {
85
+ type: 'test',
86
+ },
87
+ desired: {
88
+ propA: 'a',
89
+ propB: 10,
90
+ propC: 'c',
91
+ },
92
+ state: undefined,
93
+ isStateful: false,
94
+ })
95
+
96
+ expect(result).toMatchObject({
97
+ planId: expect.any(String),
98
+ operation: ResourceOperation.NOOP,
99
+ resourceType: 'test',
100
+ })
101
+ })
102
+
103
+ it('Can apply a plan', async () => {
104
+ const plan = await plugin.plan({
105
+ core: {
106
+ type: 'test',
107
+ },
108
+ desired: {
109
+ propA: 'a',
110
+ propB: 10,
111
+ propC: 'c',
112
+ },
113
+ state: undefined,
114
+ isStateful: false,
115
+ })
116
+
117
+ // No expect needed here. This passes if it doesn't throw.
118
+ await plugin.apply({ planId: plan.planId })
119
+ })
120
+
121
+ it('Handles errors that are thrown', async () => {
122
+ expect(async () => plugin.plan({
123
+ core: {
124
+ type: 'test',
125
+ },
126
+ desired: {
127
+ propA: 'a',
128
+ propB: 10,
129
+ propC: 'c',
130
+ propD: 'any'
131
+ },
132
+ state: undefined,
133
+ isStateful: false,
134
+ })).rejects.toThrowError(new Error('Prop D is included'));
135
+ })
136
+
137
+ it('Has helpers that can test a resource', async () => {
138
+ // No expect needed here. This passes if it doesn't throw.
139
+ await PluginTester.fullTest(pluginPath, [{
140
+ type: 'test',
141
+ propA: 'a',
142
+ propB: 10,
143
+ propC: 'c',
144
+ }, {
145
+ type: 'test',
146
+ propA: 'a',
147
+ propB: 10,
148
+ propC: 'c',
149
+ }], {
150
+ skipUninstall: true,
151
+ });
152
+ })
153
+
154
+ it('Full test supports plan assertions to ensure the generated plan is correct', async () => {
155
+ // No expect needed here. This passes if it doesn't throw.
156
+ await PluginTester.fullTest(pluginPath, [{
157
+ type: 'test',
158
+ propA: 'a',
159
+ propB: 10,
160
+ propC: 'c',
161
+ }, {
162
+ type: 'test',
163
+ propA: 'a',
164
+ propB: 10,
165
+ propC: 'c',
166
+ }], {
167
+ skipUninstall: true,
168
+ validatePlan: (plans) => {
169
+ expect(plans[0]).toMatchObject({
170
+ planId: expect.any(String),
171
+ operation: ResourceOperation.NOOP,
172
+ resourceType: 'test',
173
+ });
174
+
175
+ expect(plans[1]).toMatchObject({
176
+ planId: expect.any(String),
177
+ operation: ResourceOperation.NOOP,
178
+ resourceType: 'test',
179
+ });
180
+ }
181
+ })
182
+ })
183
+
184
+ it('Full test supports plan assertions to ensure the generated plan is correct (2)', async () => {
185
+ // No expect needed here. This passes if it doesn't throw.
186
+ await PluginTester.fullTest(pluginPath, [{
187
+ type: 'test',
188
+ propA: 'a',
189
+ propB: 10,
190
+ }], {
191
+ skipUninstall: true,
192
+ validatePlan: (plans) => {
193
+ expect(plans[0]).toMatchObject({
194
+ planId: expect.any(String),
195
+ operation: ResourceOperation.NOOP,
196
+ resourceType: 'test',
197
+ });
198
+ }
199
+ })
200
+ })
201
+
202
+ it('Full test supports plan assertions to ensure the generated plan is correct (3)', async () => {
203
+ console.log(differenceWith(['b', 'a'], ['a', 'b', 'c'], (a, b) => deepMatches(a)(b)).length === 0);
204
+
205
+ // No expect needed here. This passes if it doesn't throw.
206
+ await PluginTester.fullTest(pluginPath, [{
207
+ type: 'test2',
208
+ propB: ['second', 'first'],
209
+ propA: 'a',
210
+ }], {
211
+ skipUninstall: true,
212
+ })
213
+ })
214
+
215
+ it('Has helpers that can uninstall a resource', async () => {
216
+ // No expect needed here. This passes if it doesn't throw.
217
+ await PluginTester.uninstall(pluginPath, [{
218
+ type: 'test-uninstall',
219
+ propA: 'a',
220
+ propB: 10,
221
+ propC: 'c',
222
+ }]);
223
+ })
224
+
225
+ it('Has helpers that can uninstall a resource (errors out when unsuccessful)', async () => {
226
+ // No expect needed here. This passes if it doesn't throw.
227
+ await expect(async () => PluginTester.uninstall(pluginPath, [{
228
+ type: 'test',
229
+ propA: 'a',
230
+ propB: 10,
231
+ propC: 'c',
232
+ }])).rejects.toThrowError();
233
+ })
234
+
235
+
236
+ it('Can test modify', { timeout: 50000000 }, async () => {
237
+ await expect(() => PluginTester.fullTest(pluginPath, [{
238
+ type: 'test-modify',
239
+ propA: 'a',
240
+ propB: 10,
241
+ }], {
242
+ skipUninstall: true,
243
+ testModify: {
244
+ modifiedConfigs: [{
245
+ type: 'test-modify',
246
+ propA: 'Modify',
247
+ propB: 10,
248
+ }]
249
+ }
250
+ })).rejects.toThrowError();
251
+ })
252
+
253
+ // it('Will call destory with the correct parameters (modify)', { timeout: 50000000 }, async () => {
254
+ // await expect(async () => await PluginTester.fullTest(pluginPath, [{
255
+ // type: 'test-modify',
256
+ // propA: 'a',
257
+ // propB: 10,
258
+ // }], {
259
+ // skipUninstall: true,
260
+ // testModify: {
261
+ // modifiedConfigs: [{
262
+ // type: 'test-modify',
263
+ // propA: 'Modify',
264
+ // propB: 10,
265
+ // }]
266
+ // }
267
+ // })).rejects.toThrow(
268
+ // `
269
+ // "parameters": [
270
+ // {
271
+ // "name": "propA",
272
+ // "previousValue": "Modify__",
273
+ // "newValue": "Modify",
274
+ // "operation": "modify"
275
+ // },
276
+ // {
277
+ // "name": "propB",
278
+ // "previousValue": "10",
279
+ // "newValue": "10",
280
+ // "operation": "noop"
281
+ // }
282
+ // ]
283
+ // }
284
+ // `
285
+ // )
286
+ // })
287
+
288
+ it('Works when uninstalling two resources', { timeout: 300000 }, async () => {
289
+ try {
290
+ await PluginTester.fullTest(pluginPath, [{
291
+ type: 'test-destroy',
292
+ propA: 'a',
293
+ propB: 10,
294
+ }, {
295
+ type: 'test-destroy-2',
296
+ propA: 'a',
297
+ propB: 20,
298
+ }], {
299
+ validateDestroy(plan) {
300
+ expect(plan.length).to.eq(2);
301
+ expect(plan[0]).toMatchObject({
302
+ operation: 'destroy',
303
+ resourceType: 'test-destroy-2',
304
+ })
305
+ expect(plan[1]).toMatchObject({
306
+ operation: 'destroy',
307
+ resourceType: 'test-destroy',
308
+ })
309
+ }
310
+ });
311
+ } finally {
312
+ try { fs.rmSync('test-destroy'); } catch (e) {}
313
+ try { fs.rmSync('test-destroy-2') } catch (e) {}
314
+ }
315
+ })
316
+
317
+ it('Can filter out unsupported configs based on OS', { timeout: 300000 }, async () => {
318
+ await PluginTester.fullTest(pluginPath, [{
319
+ type: 'windows-only',
320
+ os: [ResourceOs.Windows],
321
+ }], {
322
+ validatePlan(plan) {
323
+ expect(plan.length).to.eq(0);
324
+ }
325
+ });
326
+ });
327
+
328
+ // it('Can uninstall two resources with the same type', async () => {
329
+ // await plugin.fullTest([{
330
+ // type: 'test-destroy',
331
+ // propA: 'a',
332
+ // propB: 10,
333
+ // }, {
334
+ // type: 'test-destroy',
335
+ // propA: 'a',
336
+ // propB: 20,
337
+ // }], {
338
+ // validateDestroy(plan) {
339
+ // expect(plan.length).to.eq(2);
340
+ // expect(plan[0]).toMatchObject({
341
+ // operation: 'destroy',
342
+ // resourceType: 'test-destroy',
343
+ // })
344
+ // expect(plan[1]).toMatchObject({
345
+ // operation: 'destroy',
346
+ // resourceType: 'test-destroy',
347
+ // })
348
+ // }
349
+ // });
350
+ })