File size: 2,422 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Mock utilities for testing
 * Provides reusable mocks for common dependencies
 */

import { vi } from 'vitest';
import type { ChildProcess } from 'child_process';
import { EventEmitter } from 'events';
import type { Readable } from 'stream';

/**
 * Mock child_process.spawn for subprocess tests
 */
export function createMockChildProcess(options: {
  stdout?: string[];
  stderr?: string[];
  exitCode?: number | null;
  shouldError?: boolean;
}): ChildProcess {
  const { stdout = [], stderr = [], exitCode = 0, shouldError = false } = options;

  const mockProcess = new EventEmitter() as any;

  // Create mock stdout stream
  mockProcess.stdout = new EventEmitter() as Readable;
  mockProcess.stderr = new EventEmitter() as Readable;

  mockProcess.kill = vi.fn();

  // Simulate async output
  process.nextTick(() => {
    // Emit stdout lines
    for (const line of stdout) {
      mockProcess.stdout.emit('data', Buffer.from(line + '\n'));
    }

    // Emit stderr lines
    for (const line of stderr) {
      mockProcess.stderr.emit('data', Buffer.from(line + '\n'));
    }

    // Emit exit or error
    if (shouldError) {
      mockProcess.emit('error', new Error('Process error'));
    } else {
      mockProcess.emit('exit', exitCode);
    }
  });

  return mockProcess as ChildProcess;
}

/**
 * Mock fs/promises for file system tests
 */
export function createMockFs() {
  return {
    readFile: vi.fn(),
    writeFile: vi.fn(),
    mkdir: vi.fn(),
    access: vi.fn(),
    stat: vi.fn(),
  };
}

/**
 * Mock Express request/response/next for middleware tests
 */
export function createMockExpressContext() {
  const req = {
    headers: {},
    body: {},
    params: {},
    query: {},
  } as any;

  const res = {
    status: vi.fn().mockReturnThis(),
    json: vi.fn().mockReturnThis(),
    send: vi.fn().mockReturnThis(),
  } as any;

  const next = vi.fn();

  return { req, res, next };
}

/**
 * Mock AbortController for async operation tests
 */
export function createMockAbortController() {
  const controller = new AbortController();
  const originalAbort = controller.abort.bind(controller);
  controller.abort = vi.fn(originalAbort);
  return controller;
}

/**
 * Mock Claude SDK query function
 */
export function createMockClaudeQuery(messages: any[] = []) {
  return vi.fn(async function* ({ prompt, options }: any) {
    for (const msg of messages) {
      yield msg;
    }
  });
}