๐Ÿ“ฆ leog / ldx

๐Ÿ“„ ldx.test.js ยท 373 lines
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
373import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";
import mock from "mock-require";

// Mock the config file at the top level
mock("./ldx.config.js", {
  "Test match 1": "โœ… Test match 1 processed",
  "Test match 3": "๐Ÿณ Test match 3 processed",
});

describe("config file check", () => {
  let errorSpy;
  let exitSpy;

  beforeEach(() => {
    vi.resetModules();
    errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
    exitSpy = vi.spyOn(process, "exit").mockImplementation(() => {});
  });

  test("logs an error and exits when no config file is found", async () => {
    mock.stopAll();
    await import("./ldx.js");
    expect(errorSpy).toHaveBeenCalledWith("Oops, no ldx.config.js file found!");
    expect(exitSpy).toHaveBeenCalledWith(1);
  });
});

describe("processOutput", () => {
  let warnSpy;

  beforeEach(() => {
    // Reset the module cache before each test
    vi.resetModules();
    // Create a spy on console.warn
    warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  });

  afterEach(() => {
    // Restore the original console.warn
    warnSpy.mockRestore();
  });

  test("returns correct message for static string matches", async () => {
    mock("./ldx.config.js", {
      "Test match 1": "โœ… Test match 1 processed",
    });
    const { processOutput } = await import("./ldx.js");
    const line = "Test match 1";
    const result = processOutput(line);
    expect(result).toBe("โœ… Test match 1 processed");
    expect(warnSpy).not.toHaveBeenCalled();
  });

  test("handles function values correctly", async () => {
    mock("./ldx.config.js", {
      "Function match": (line) => `Processed: ${line}`,
    });
    const { processOutput } = await import("./ldx.js");
    const line = "Function match test line";
    const result = processOutput(line);
    expect(result).toBe(`Processed: ${line}`);
    expect(warnSpy).not.toHaveBeenCalled();
  });

  test("handles function errors gracefully and returns original line", async () => {
    const errorFn = vi.fn(() => {
      throw new Error("Test error");
    });
    mock("./ldx.config.js", {
      "Error match": errorFn,
    });
    const { processOutput } = await import("./ldx.js");
    const line = "Error match with extra text";
    const result = processOutput(line);
    expect(result).toBe(line); // Returns original line on error
    expect(errorFn).toHaveBeenCalled();
    expect(warnSpy).toHaveBeenCalledWith(
      "LDX: provided function errored: ",
      "Test error"
    );
  });

  test("returns undefined for no match", async () => {
    mock("./ldx.config.js", { Something: "not used" });
    const { processOutput } = await import("./ldx.js");
    const line = "Some random line";
    const result = processOutput(line);
    expect(result).toBeUndefined();
    expect(warnSpy).not.toHaveBeenCalled();
  });

  test("warns for invalid configuration type", async () => {
    mock("./ldx.config.js", {
      "Invalid match": 12345, // Invalid type (number)
    });
    const { processOutput } = await import("./ldx.js");
    const line = "Invalid match";
    const result = processOutput(line);
    expect(result).toBeUndefined();
    expect(warnSpy).toHaveBeenCalledWith(
      "Invalid configuration for key: Invalid match. Expected string or function."
    );
  });
});

describe("executeAndProcessCommand", () => {
  let logSpy;

  beforeEach(() => {
    vi.clearAllMocks();
    mock.stopAll();
    logSpy = vi.spyOn(console, "log").mockImplementation(() => {});

    // Reset the module cache to ensure fresh imports
    vi.resetModules();
  });

  afterEach(() => {
    logSpy.mockRestore();
  });

  test("rejects when no command is provided", async () => {
    const { executeAndProcessCommand } = await import("./ldx.js");
    await expect(executeAndProcessCommand()).rejects.toThrow(
      "No command provided."
    );
  });

  test("resolves when command executes successfully", async () => {
    vi.spyOn(process, "argv", "get").mockReturnValue([
      "node",
      "ldx.js",
      "echo",
      "hello",
    ]);

    const mockSpawn = vi.fn(() => ({
      stdout: { on: vi.fn() },
      stderr: { on: vi.fn() },
      on: vi.fn((event, callback) => {
        if (event === "close") callback(0);
      }),
    }));
    vi.spyOn(require("child_process"), "spawn").mockImplementation(mockSpawn);
    const { executeAndProcessCommand } = await import("./ldx.js");
    await expect(executeAndProcessCommand()).resolves.toBeUndefined();
  });

  test("rejects when command fails", async () => {
    vi.spyOn(process, "argv", "get").mockReturnValue([
      "node",
      "ldx.js",
      "false",
    ]);

    const mockSpawn = vi.fn(() => ({
      stdout: { on: vi.fn() },
      stderr: { on: vi.fn() },
      on: vi.fn((event, callback) => {
        if (event === "close") callback(1);
      }),
    }));
    vi.spyOn(require("child_process"), "spawn").mockImplementation(mockSpawn);
    const { executeAndProcessCommand } = await import("./ldx.js");
    await expect(executeAndProcessCommand()).rejects.toThrow(
      "Command failed with exit code 1"
    );
  });

  test("processes static strings correctly when command executes", async () => {
    // Setup config mock FIRST
    mock("./ldx.config.js", {
      "Test output": "โœ… Processed output",
    });

    vi.spyOn(process, "argv", "get").mockReturnValue([
      "node",
      "ldx.js",
      "echo",
      "Test output",
    ]);

    // Mock spawn to simulate command output
    const mockSpawn = vi.fn(() => ({
      stdout: {
        on: vi.fn((event, callback) => {
          if (event === "data") {
            // Simulate actual command output
            callback(Buffer.from("Test output\n"));
          }
        }),
      },
      stderr: { on: vi.fn() },
      on: vi.fn((event, callback) => {
        if (event === "close") callback(0);
      }),
    }));
    vi.spyOn(require("child_process"), "spawn").mockImplementation(mockSpawn);

    // Import AFTER all mocks are set up
    const { executeAndProcessCommand } = await import("./ldx.js");
    await executeAndProcessCommand();

    expect(logSpy).toHaveBeenCalledWith("โœ… Processed output");
  });

  test("processes stderr output correctly", async () => {
    mock("./ldx.config.js", {
      "Error:": "Transformed error message",
    });

    vi.spyOn(process, "argv", "get").mockReturnValue([
      "node",
      "ldx.js",
      "somecommand",
    ]);

    const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});

    const mockSpawn = vi.fn(() => ({
      stdout: { on: vi.fn() },
      stderr: {
        on: vi.fn((event, callback) => {
          if (event === "data") {
            callback(Buffer.from("Error: something went wrong\n"));
          }
        }),
      },
      on: vi.fn((event, callback) => {
        if (event === "close") callback(0);
      }),
    }));
    vi.spyOn(require("child_process"), "spawn").mockImplementation(mockSpawn);

    const { executeAndProcessCommand } = await import("./ldx.js");
    await executeAndProcessCommand();

    expect(errorSpy).toHaveBeenCalledWith("Transformed error message");
    errorSpy.mockRestore();
  });

  test("passes through unmatched stderr lines", async () => {
    mock("./ldx.config.js", {
      "Something else": "Not this",
    });

    vi.spyOn(process, "argv", "get").mockReturnValue([
      "node",
      "ldx.js",
      "somecommand",
    ]);

    const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});

    const mockSpawn = vi.fn(() => ({
      stdout: { on: vi.fn() },
      stderr: {
        on: vi.fn((event, callback) => {
          if (event === "data") {
            callback(Buffer.from("Unmatched error line\n"));
          }
        }),
      },
      on: vi.fn((event, callback) => {
        if (event === "close") callback(0);
      }),
    }));
    vi.spyOn(require("child_process"), "spawn").mockImplementation(mockSpawn);

    const { executeAndProcessCommand } = await import("./ldx.js");
    await executeAndProcessCommand();

    expect(errorSpy).toHaveBeenCalledWith("Unmatched error line");
    errorSpy.mockRestore();
  });

  test("rejects when spawn fails with error event", async () => {
    vi.spyOn(process, "argv", "get").mockReturnValue([
      "node",
      "ldx.js",
      "nonexistentcommand",
    ]);

    const mockSpawn = vi.fn(() => {
      const emitter = {
        stdout: { on: vi.fn() },
        stderr: { on: vi.fn() },
        on: vi.fn((event, callback) => {
          if (event === "error") {
            setTimeout(() => callback(new Error("spawn nonexistentcommand ENOENT")), 0);
          }
        }),
      };
      return emitter;
    });
    vi.spyOn(require("child_process"), "spawn").mockImplementation(mockSpawn);

    const { executeAndProcessCommand } = await import("./ldx.js");
    await expect(executeAndProcessCommand()).rejects.toThrow(
      "Failed to start command: spawn nonexistentcommand ENOENT"
    );
  });
});

describe("validateConfig", () => {
  beforeEach(() => {
    vi.resetModules();
    mock.stopAll();
  });

  test("returns valid for correct configuration", async () => {
    mock("./ldx.config.js", {
      "key1": "value1",
      "key2": (line) => line,
    });
    const { validateConfig } = await import("./ldx.js");
    const result = validateConfig({
      "key1": "value1",
      "key2": (line) => line,
    });
    expect(result.valid).toBe(true);
  });

  test("returns invalid for null configuration", async () => {
    mock("./ldx.config.js", { "key": "value" });
    const { validateConfig } = await import("./ldx.js");
    const result = validateConfig(null);
    expect(result.valid).toBe(false);
    expect(result.error).toBe("Configuration must be a non-null object.");
  });

  test("returns invalid for array configuration", async () => {
    mock("./ldx.config.js", { "key": "value" });
    const { validateConfig } = await import("./ldx.js");
    const result = validateConfig(["item1", "item2"]);
    expect(result.valid).toBe(false);
    expect(result.error).toBe("Configuration must be a non-null object.");
  });

  test("returns invalid for empty configuration", async () => {
    mock("./ldx.config.js", { "key": "value" });
    const { validateConfig } = await import("./ldx.js");
    const result = validateConfig({});
    expect(result.valid).toBe(false);
    expect(result.error).toBe("Configuration cannot be empty.");
  });

  test("returns invalid for configuration with invalid value type", async () => {
    mock("./ldx.config.js", { "key": "value" });
    const { validateConfig } = await import("./ldx.js");
    const result = validateConfig({
      "validKey": "validValue",
      "invalidKey": 12345,
    });
    expect(result.valid).toBe(false);
    expect(result.error).toBe(
      'Invalid value type for key "invalidKey". Expected string or function, got number.'
    );
  });

  test("returns invalid for configuration with object value", async () => {
    mock("./ldx.config.js", { "key": "value" });
    const { validateConfig } = await import("./ldx.js");
    const result = validateConfig({
      "key": { nested: "object" },
    });
    expect(result.valid).toBe(false);
    expect(result.error).toBe(
      'Invalid value type for key "key". Expected string or function, got object.'
    );
  });
});