@codifycli/plugin-test 1.1.0-beta7 → 2.0.0

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.
package/src/utils.ts CHANGED
@@ -1,6 +1,25 @@
1
- import { ResourceConfig, ResourceOs, StringIndexedObject } from '@codifycli/schemas';
1
+ import { LinuxDistro, ResourceConfig, ResourceOs, StringIndexedObject } from '@codifycli/schemas';
2
+ import fs from 'node:fs';
2
3
  import os from 'node:os';
3
4
 
5
+ const DEBIAN_BASED_DISTROS: LinuxDistro[] = [
6
+ LinuxDistro.DEBIAN,
7
+ LinuxDistro.UBUNTU,
8
+ LinuxDistro.MINT,
9
+ LinuxDistro.POP_OS,
10
+ LinuxDistro.ELEMENTARY_OS,
11
+ LinuxDistro.KALI,
12
+ ];
13
+
14
+ const RPM_BASED_DISTROS: LinuxDistro[] = [
15
+ LinuxDistro.FEDORA,
16
+ LinuxDistro.CENTOS,
17
+ LinuxDistro.RHEL,
18
+ LinuxDistro.AMAZON_LINUX,
19
+ LinuxDistro.OPENSUSE,
20
+ LinuxDistro.SUSE,
21
+ ];
22
+
4
23
  export function splitUserConfig<T extends StringIndexedObject>(
5
24
  config: ResourceConfig & T
6
25
  ): { parameters: T; coreParameters: ResourceConfig } {
@@ -21,6 +40,56 @@ export function splitUserConfig<T extends StringIndexedObject>(
21
40
  };
22
41
  }
23
42
 
43
+ /**
44
+ * Whether a config applies to this machine, like the CLI's os and distro filters: `os` must include the current OS,
45
+ * and on Linux `distro` must match the current distribution (`debian-based` / `rpm-based` match their families).
46
+ * `distro` is ignored on other OSes and when the distribution is unknown.
47
+ */
48
+ export function appliesToCurrentPlatform(config: Pick<ResourceConfig, 'distro' | 'os'>): boolean {
49
+ if (config.os && config.os.length > 0 && !config.os.includes(getPlatformOs())) {
50
+ return false;
51
+ }
52
+
53
+ if (!config.distro || config.distro.length === 0 || os.platform() !== 'linux') {
54
+ return true;
55
+ }
56
+
57
+ const current = getLinuxDistro();
58
+ return !current || config.distro.some((d) => distroMatches(d, current));
59
+ }
60
+
61
+ export function getLinuxDistro(): LinuxDistro | undefined {
62
+ for (const candidate of ['/etc/os-release', '/usr/lib/os-release']) {
63
+ let osRelease: string;
64
+ try {
65
+ osRelease = fs.readFileSync(candidate, 'utf8');
66
+ } catch {
67
+ continue;
68
+ }
69
+
70
+ for (const line of osRelease.split('\n')) {
71
+ if (line.startsWith('ID=')) {
72
+ const distroId = line.slice(3).trim().replaceAll('"', '');
73
+ return Object.values(LinuxDistro).includes(distroId as LinuxDistro) ? distroId as LinuxDistro : undefined;
74
+ }
75
+ }
76
+ }
77
+
78
+ return undefined;
79
+ }
80
+
81
+ export function distroMatches(filter: LinuxDistro, current: LinuxDistro): boolean {
82
+ if (filter === LinuxDistro.DEBIAN_BASED) {
83
+ return DEBIAN_BASED_DISTROS.includes(current);
84
+ }
85
+
86
+ if (filter === LinuxDistro.RPM_BASED) {
87
+ return RPM_BASED_DISTROS.includes(current);
88
+ }
89
+
90
+ return filter === current;
91
+ }
92
+
24
93
  export function getPlatformOs(): ResourceOs{
25
94
  const currOs = os.platform();
26
95
  switch (currOs) {
@@ -0,0 +1,19 @@
1
+ // A plugin like plugin-core >= 2.3.0: stdout and command events go over IPC, before the response.
2
+ // Older plugins write to the stdout pipe: both are noisy (spinners, progress bars)
3
+ process.on('message', (message) => {
4
+ if (message.cmd !== 'initialize') return;
5
+
6
+ const output = (data) => process.send({ cmd: 'output', data: { data }, requestId: '' });
7
+ process.send({ cmd: 'command_started', data: { id: '1', command: 'npm install', acceptsInput: true, canStop: true }, requestId: '' });
8
+ output('hello from the plugin 🍺\n');
9
+ for (let i = 0; i < 500; i++) output(`\u001B[1G${'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[i % 10]}\u001B[0K`);
10
+ output('\u001B[1G\u001B[0Kadded 12 packages in 2s\n');
11
+ for (let i = 0; i <= 100; i++) output(`\rDownloading [${'#'.repeat(i / 5).padEnd(20)}] ${i}%`);
12
+ process.send({ cmd: 'command_finished', data: { id: '1', exitCode: 0 }, requestId: '' });
13
+
14
+ // An older plugin: through the stdout pipe
15
+ for (let i = 0; i <= 100; i += 2) process.stdout.write(`\rProgress: [${String(i).padStart(3)}%]`);
16
+ process.stdout.write('\r\u001B[KSetting up curl (8.5.0) ...\n', () => {
17
+ process.send({ cmd: 'initialize_Response', status: 'success', data: { resourceDefinitions: [] }, requestId: message.requestId });
18
+ });
19
+ });
@@ -0,0 +1,36 @@
1
+ import path from 'node:path';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import { PluginProcess } from '../src/plugin-process.js';
5
+
6
+ describe('Plugin output', () => {
7
+ let plugin: PluginProcess | undefined;
8
+
9
+ afterEach(() => {
10
+ plugin?.kill();
11
+ vi.restoreAllMocks();
12
+ });
13
+
14
+ it('Prints plugin output as a terminal would end up showing it, without a line per spinner frame', async () => {
15
+ const written: string[] = [];
16
+ vi.spyOn(process.stdout, 'write').mockImplementation((chunk: any) => {
17
+ written.push(String(chunk));
18
+ return true;
19
+ });
20
+ plugin = new PluginProcess(path.join(__dirname, './output-plugin.mjs'));
21
+
22
+ await expect(plugin.initialize()).resolves.toEqual({ resourceDefinitions: [] });
23
+ // The stdout pipe and IPC are separate streams: give the pipe a moment
24
+ await new Promise((resolve) => setTimeout(resolve, 200));
25
+
26
+ const lines = written.join('').split('\n').filter(Boolean);
27
+ expect(lines).toEqual(expect.arrayContaining([
28
+ 'hello from the plugin 🍺',
29
+ 'added 12 packages in 2s',
30
+ 'Downloading [####################] 100%',
31
+ 'Setting up curl (8.5.0) ...',
32
+ ]));
33
+ expect(lines).toHaveLength(4);
34
+ expect(written.join('')).not.toMatch(/[⠀-⣿\r\u001B]/);
35
+ });
36
+ });
@@ -6,7 +6,8 @@ import deepMatches from 'lodash.matches';
6
6
  import differenceWith from 'lodash.differencewith';
7
7
  import { PluginProcess } from '../src/plugin-process';
8
8
  import * as fs from 'node:fs';
9
- import { ResourceOs } from '@codifycli/schemas';
9
+ import { LinuxDistro, ResourceOs } from '@codifycli/schemas';
10
+ import { getLinuxDistro } from '../src/utils.js';
10
11
 
11
12
  const pluginPath = path.join(__dirname, './test-plugin.ts');
12
13
 
@@ -119,7 +120,7 @@ describe('Plugin tester integration tests', () => {
119
120
  })
120
121
 
121
122
  it('Handles errors that are thrown', async () => {
122
- expect(async () => plugin.plan({
123
+ await expect(async () => plugin.plan({
123
124
  core: {
124
125
  type: 'test',
125
126
  },
@@ -131,7 +132,7 @@ describe('Plugin tester integration tests', () => {
131
132
  },
132
133
  state: undefined,
133
134
  isStateful: false,
134
- })).rejects.toThrowError(new Error('Prop D is included'));
135
+ })).rejects.toThrowError('Prop D is included');
135
136
  })
136
137
 
137
138
  it('Has helpers that can test a resource', async () => {
@@ -151,6 +152,15 @@ describe('Plugin tester integration tests', () => {
151
152
  });
152
153
  })
153
154
 
155
+ it('Validates the example configs of the tested types', async () => {
156
+ await expect(PluginTester.fullTest(pluginPath, [{
157
+ type: 'test-invalid-example',
158
+ propA: 'a',
159
+ }], {
160
+ skipUninstall: true,
161
+ })).rejects.toThrow(/exampleConfigs\.example1\[0\] failed validation/);
162
+ })
163
+
154
164
  it('Full test supports plan assertions to ensure the generated plan is correct', async () => {
155
165
  // No expect needed here. This passes if it doesn't throw.
156
166
  await PluginTester.fullTest(pluginPath, [{
@@ -314,6 +324,41 @@ describe('Plugin tester integration tests', () => {
314
324
  }
315
325
  })
316
326
 
327
+ it('Uninstalls when a test fails, and keeps the error of the test', { timeout: 300000 }, async () => {
328
+ const configs = [{ type: 'test-destroy', propA: 'a', propB: 10 }, { type: 'test-destroy', propA: 'b', propB: 10 }];
329
+ try {
330
+ await expect(PluginTester.fullTest(pluginPath, configs.slice(0, 1), {
331
+ validateApply() {
332
+ expect(fs.existsSync('/tmp/test-destroy')).to.be.true;
333
+ throw new Error('Apply assertion failed');
334
+ },
335
+ })).rejects.toThrowError('Apply assertion failed');
336
+
337
+ expect(fs.existsSync('/tmp/test-destroy')).to.be.false;
338
+ } finally {
339
+ try { fs.rmSync('/tmp/test-destroy'); } catch (e) {}
340
+ }
341
+
342
+ // The caller's configs aren't changed (names are only added to copies)
343
+ expect(configs.every((c) => !('name' in c))).to.be.true;
344
+ });
345
+
346
+ it('Can filter out unsupported configs based on distro', { timeout: 300000 }, async () => {
347
+ await PluginTester.fullTest(pluginPath, [{
348
+ type: 'windows-only',
349
+ os: [ResourceOs.LINUX],
350
+ distro: [LinuxDistro.ARCH, LinuxDistro.FEDORA],
351
+ }], {
352
+ skipUninstall: true,
353
+ skipImport: true,
354
+ validatePlan(plan) {
355
+ if (getLinuxDistro() !== LinuxDistro.ARCH && getLinuxDistro() !== LinuxDistro.FEDORA) {
356
+ expect(plan.length).to.eq(0);
357
+ }
358
+ }
359
+ });
360
+ });
361
+
317
362
  it('Can filter out unsupported configs based on OS', { timeout: 300000 }, async () => {
318
363
  await PluginTester.fullTest(pluginPath, [{
319
364
  type: 'windows-only',
@@ -48,10 +48,12 @@ export class TestResource extends Resource<TestConfig> {
48
48
  id: 'test',
49
49
  operatingSystems: [OS.Linux, OS.Darwin],
50
50
  allowMultiple: true,
51
- defaultConfig,
52
- exampleConfigs: {
53
- example1,
54
- example2
51
+ registry: {
52
+ defaultConfig,
53
+ exampleConfigs: {
54
+ example1,
55
+ example2
56
+ }
55
57
  }
56
58
  };
57
59
  }
@@ -83,9 +85,11 @@ export class TestResource2 extends Resource<TestConfig2> {
83
85
  parameterSettings: {
84
86
  propB: { type: 'array' }
85
87
  },
86
- exampleConfigs: {
87
- example1,
88
- example2
88
+ registry: {
89
+ exampleConfigs: {
90
+ example1,
91
+ example2
92
+ }
89
93
  }
90
94
  };
91
95
  }
@@ -234,6 +238,34 @@ export class TestDestroyResource2 extends TestDestroyResource {
234
238
  }
235
239
  }
236
240
 
241
+ // Its example doesn't match its schema: full tests of it must fail
242
+ export class InvalidExampleResource extends Resource<TestConfig> {
243
+ getSettings(): ResourceSettings<TestConfig> {
244
+ return {
245
+ id: 'test-invalid-example',
246
+ operatingSystems: [OS.Linux, OS.Darwin],
247
+ schema: {
248
+ type: 'object',
249
+ properties: { propA: { type: 'string' } },
250
+ additionalProperties: false,
251
+ },
252
+ registry: {
253
+ exampleConfigs: {
254
+ example1: { title: 'Invalid example', configs: [{ type: 'test-invalid-example', propA: 5 }] },
255
+ },
256
+ },
257
+ };
258
+ }
259
+
260
+ async refresh(): Promise<Partial<TestConfig> | null> {
261
+ return { propA: 'a' };
262
+ }
263
+
264
+ async create(): Promise<void> {}
265
+
266
+ async destroy(): Promise<void> {}
267
+ }
268
+
237
269
  runPlugin(Plugin.create(
238
270
  'default',
239
271
  [
@@ -244,5 +276,6 @@ runPlugin(Plugin.create(
244
276
  new TestDestroyResource(),
245
277
  new TestDestroyResource2(),
246
278
  new WindowsOnlyResource(),
279
+ new InvalidExampleResource(),
247
280
  ]
248
281
  ));
@@ -1,5 +0,0 @@
1
- {
2
- "disabledMcpjsonServers": [
3
- "supabase"
4
- ]
5
- }