All files / backend/test/mocks ssg-dependencies.ts

20.68% Statements 18/87
18.18% Branches 6/33
16.27% Functions 7/43
21.25% Lines 17/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                          200x                                 48x 48x   48x               48x               48x     48x                                                                   200x                 170x 170x   170x   170x       170x                     170x                       170x                                           18x                                           170x                                                                                                                                                                                                                                                                                    
/**
 * SSG Provider Mock Dependencies
 *
 * Mock utilities specifically for testing SSG providers.
 * These mocks simulate PathHelper, EnvironmentInfo, and other SSG-specific dependencies.
 */
 
import { vi } from 'vitest';
import type {
  PathHelper,
  EnvironmentInfo,
} from '../../src/utils/path-helper.js';
import type {
  SSGProviderDependencies,
  DownloadProgress,
} from '../../src/ssg-providers/types.js';
import type {
  OutputConsole,
  WindowAdapter,
  ShellAdapter,
} from '../../src/adapters/types.js';
import type { AppConfig } from '../../src/config/app-config.js';
import type { AppContainer } from '../../src/config/container.js';
import path from 'path';
 
/**
 * Create a mock PathHelper with SSG-specific methods
 */
export function createMockPathHelper(overrides?: Partial<PathHelper>): PathHelper {
  const mockPathHelper = {
    // Basic paths
    getRoot: vi.fn(() => '/mock/quiqr'),
    getTempDir: vi.fn(() => '/mock/quiqr/temp'),
    getSiteRoot: vi.fn((siteKey: string) => `/mock/quiqr/sites/${siteKey}`),
    getSiteRootMountPath: vi.fn(() => undefined),
    getSiteDefaultPublishDir: vi.fn(
      (siteKey: string, publishKey: string) => `/mock/quiqr/sites/${siteKey}/publish/${publishKey}`
    ),
    getPublishReposRoot: vi.fn(() => '/mock/quiqr/sitesRepos'),
 
    // SSG-specific paths
    getSSGBinRoot: vi.fn((ssgType: string) => `/mock/quiqr/tools/${ssgType}bin`),
    getSSGBinDirForVer: vi.fn(
      (ssgType: string, version: string) => `/mock/quiqr/tools/${ssgType}bin/${version}`
    ),
    getSSGBinForVer: vi.fn((ssgType: string, version: string) => {
      const platform = process.platform.toLowerCase();
      const binDir = `/mock/quiqr/tools/${ssgType}bin/${version}`;
 
      Iif (ssgType.toLowerCase() === 'eleventy') {
        const npmBinPath = path.join(binDir, 'node_modules', '.bin', 'eleventy');
        if (platform.startsWith('win')) {
          return npmBinPath + '.cmd';
        }
        return npmBinPath;
      }
 
      Iif (ssgType.toLowerCase() === 'jekyll') {
        if (platform.startsWith('win')) {
          return path.join(binDir, 'jekyll.cmd');
        }
        return path.join(binDir, 'jekyll.sh');
      }
 
      // For standalone binaries like Hugo
      Iif (platform.startsWith('win')) {
        return path.join(binDir, `${ssgType}.exe`);
      } else {
        return path.join(binDir, ssgType);
      }
    }),
 
    // Deprecated methods (still present for compatibility)
    getHugoBinRoot: vi.fn(() => '/mock/quiqr/tools/hugobin'),
    getHugoBinDirForVer: vi.fn((version: string) => `/mock/quiqr/tools/hugobin/${version}`),
    getHugoBinForVer: vi.fn((version: string) => {
      const platform = process.platform.toLowerCase();
      if (platform.startsWith('win')) {
        return `/mock/quiqr/tools/hugobin/${version}/hugo.exe`;
      }
      return `/mock/quiqr/tools/hugobin/${version}/hugo`;
    }),
 
    // Other methods
    getLastBuildDir: vi.fn(() => undefined),
    getBuildDir: vi.fn((dir: string) => dir),
    getThemesDir: vi.fn(() => '/mock/quiqr/tools/hugothemes'),
    getApplicationResourcesDir: vi.fn(() => '/mock/resources'),
    workspaceCacheThumbsPath: vi.fn((workspacePath: string, relativePath: string) =>
      path.join(workspacePath, '.quiqr-cache/thumbs', relativePath)
    ),
    getKnownHosts: vi.fn(() => '/mock/home/.ssh/known_hosts'),
    getSiteMountConfigPath: vi.fn((siteKey: string) => `/mock/quiqr/sites/${siteKey}/config.json`),
    randomPathSafeString: vi.fn((length: number) => 'mock-random-string'.substring(0, length)),
    hugoConfigFilePath: vi.fn((hugoRootDir: string) => {
      // Return first config file found
      return path.join(hugoRootDir, 'config.toml');
    }),
 
    ...overrides,
  } as PathHelper;
 
  return mockPathHelper;
}
 
/**
 * Create a mock EnvironmentInfo
 */
export function createMockEnvironmentInfo(
  overrides?: Partial<EnvironmentInfo>
): EnvironmentInfo {
  const platform = process.platform;
  let mockPlatform: 'macOS' | 'windows' | 'linux' = 'linux';
 
  Iif (platform === 'darwin') {
    mockPlatform = 'macOS';
  I} else if (platform === 'win32') {
    mockPlatform = 'windows';
  }
 
  return {
    platform: mockPlatform,
    isPackaged: false,
    ...overrides,
  };
}
 
/**
 * Create a mock AppConfig for testing
 */
export function createMockAppConfig(): AppConfig {
  return {
    // Add minimal AppConfig mock
    prefs: {},
    getPreference: vi.fn(),
    setPreference: vi.fn(),
  } as any;
}
 
/**
 * Create a mock AppContainer for testing
 */
export function createMockContainer(): AppContainer {
  return {
    logger: {
      infoSite: vi.fn(),
      errorSite: vi.fn(),
      warnSite: vi.fn(),
      debugSite: vi.fn(),
      info: vi.fn(),
      error: vi.fn(),
      warn: vi.fn(),
      debug: vi.fn(),
    },
    state: {
      getCurrentSiteKey: vi.fn(() => 'test-site'),
      getCurrentWorkspaceKey: vi.fn(() => 'main'),
      getCurrentSitePath: vi.fn(() => '/test/site'),
      setCurrentSite: vi.fn(),
      clearCurrentSite: vi.fn(),
    },
    config: {} as any,
    unifiedConfig: {
      getInstanceSetting: vi.fn((path: string) => {
        // Return default values for common settings
        Eif (path === 'hugo.serveDraftMode') return false;
        if (path === 'hugo.disableAutoHugoServe') return false;
        if (path === 'dev.disablePartialCache') return false;
        if (path === 'experimentalFeatures') return false;
        if (path === 'storage.dataFolder') return '~/Quiqr';
        return undefined;
      }),
      getEffectivePreference: vi.fn(),
      setUserPreference: vi.fn(),
      setUserState: vi.fn(),
      getUserState: vi.fn(),
      updateInstanceSettings: vi.fn(),
    } as any,
  } as any;
}
 
/**
 * Create a complete set of SSG provider dependencies
 */
export function createMockSSGProviderDependencies(
  overrides?: Partial<SSGProviderDependencies>
): SSGProviderDependencies {
  return {
    pathHelper: createMockPathHelper(),
    environmentInfo: createMockEnvironmentInfo(),
    outputConsole: {
      appendLine: vi.fn(),
    } as OutputConsole,
    windowAdapter: {
      reloadMainWindow: vi.fn(),
      sendToRenderer: vi.fn(),
      openSiteLibrary: vi.fn().mockResolvedValue(undefined),
      setMenuBarVisibility: vi.fn(),
      appendToOutputConsole: vi.fn(),
    } as WindowAdapter,
    shellAdapter: {
      openExternal: vi.fn().mockResolvedValue(undefined),
      showItemInFolder: vi.fn(),
      openPath: vi.fn().mockResolvedValue(''),
    } as ShellAdapter,
    appConfig: createMockAppConfig(),
    container: createMockContainer(),
    ...overrides,
  };
}
 
/**
 * Mock async generator for download progress
 */
export async function* createMockDownloadStream(
  progressSteps: DownloadProgress[]
): AsyncGenerator<DownloadProgress> {
  for (const progress of progressSteps) {
    yield progress;
  }
}
 
/**
 * Create mock progress steps for testing download functionality
 */
export function createMockProgressSteps(complete: boolean = true): DownloadProgress[] {
  const steps: DownloadProgress[] = [
    { percent: 0, message: 'Starting download...', complete: false },
    { percent: 25, message: 'Downloading... 25%', complete: false },
    { percent: 50, message: 'Downloading... 50%', complete: false },
    { percent: 75, message: 'Downloading... 75%', complete: false },
    { percent: 100, message: 'Download complete', complete: true },
  ];
 
  if (!complete) {
    // Simulate failed download
    return [
      ...steps.slice(0, 3),
      {
        percent: 50,
        message: 'Download failed',
        complete: false,
        error: 'Network error',
      },
    ];
  }
 
  return steps;
}
 
/**
 * Helper to mock child_process.execFile
 * Returns a mock that can be customized for different test scenarios
 */
export function createMockExecFile() {
  return vi.fn((cmd: string, args: string[], opts: unknown, callback: Function) => {
    // Default: successful execution
    callback(null, { stdout: 'success', stderr: '' });
  });
}
 
/**
 * Helper to mock child_process.spawn
 * Returns a mock process object with stdout, stderr, and event handlers
 */
export function createMockSpawn() {
  return vi.fn(() => {
    const mockProcess = {
      stdout: {
        on: vi.fn((event: string, handler: Function) => {
          if (event === 'data') {
            // Simulate some output
            setTimeout(() => handler(Buffer.from('Mock output')), 10);
          }
        }),
        setEncoding: vi.fn(),
      },
      stderr: {
        on: vi.fn((event: string, handler: Function) => {
          // No error output by default
        }),
        setEncoding: vi.fn(),
      },
      on: vi.fn((event: string, handler: Function) => {
        if (event === 'close') {
          // Simulate successful exit
          setTimeout(() => handler(0), 50);
        }
      }),
      kill: vi.fn(),
      pid: 12345,
    };
    return mockProcess;
  });
}
 
/**
 * Setup mock for child_process module
 * Call this in your test file's vi.mock() statement
 */
export function mockChildProcess() {
  return {
    execFile: createMockExecFile(),
    spawn: createMockSpawn(),
  };
}
 
/**
 * Reset all SSG dependency mocks
 */
export function resetSSGDependencyMocks(deps: SSGProviderDependencies): void {
  // Reset PathHelper mocks
  vi.mocked(deps.pathHelper.getRoot).mockReset();
  vi.mocked(deps.pathHelper.getSSGBinForVer).mockReset();
  vi.mocked(deps.pathHelper.getSSGBinDirForVer).mockReset();
 
  // Reset OutputConsole
  vi.mocked(deps.outputConsole.appendLine).mockReset();
 
  // Reset WindowAdapter
  vi.mocked(deps.windowAdapter.sendToRenderer).mockReset();
 
  // Reset ShellAdapter
  vi.mocked(deps.shellAdapter.openExternal).mockReset();
}