Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Test] Fix state leakage between unit tests #978

Merged
merged 1 commit into from
Feb 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions tests/unit/config/comfyServerConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import fsPromises from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';

import { ComfyServerConfig } from '@/config/comfyServerConfig';

Expand All @@ -16,7 +16,7 @@ vi.mock('electron', () => ({
}));

vi.mock('@/install/resourcePaths', () => ({
getAppResourcesPath: vi.fn().mockReturnValue('/mocked/app_resources'),
getAppResourcesPath: vi.fn(() => '/mocked/app_resources'),
}));

async function createTmpDir() {
Expand All @@ -30,13 +30,17 @@ async function copyFixture(fixturePath: string, targetPath: string) {
}

describe('ComfyServerConfig', () => {
const mockUserDataPath = '/fake/user/data';
let tempDir = '';

beforeAll(async () => {
tempDir = await createTmpDir();
vi.mocked(app.getPath).mockImplementation((name: string) => {
if (name === 'userData') return '/fake/user/data';
throw new Error(`Unexpected getPath key: ${name}`);
});

beforeEach(() => {
vi.mocked(app.getPath).mockImplementation((key: string) => {
if (key === 'userData') return '/fake/user/data';
throw new Error(`Unexpected getPath key: ${key}`);
});
});

Expand All @@ -46,17 +50,13 @@ describe('ComfyServerConfig', () => {

afterEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
});

describe('configPath', () => {
it('should return the correct path', () => {
const mockUserDataPath = '/fake/user/data';
const { getPath } = app;
vi.mocked(getPath).mockImplementation((key: string) => {
if (key === 'userData') {
return mockUserDataPath;
}
if (key === 'userData') return mockUserDataPath;
throw new Error(`Unexpected getPath key: ${key}`);
});

Expand Down
41 changes: 16 additions & 25 deletions tests/unit/desktopApp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ vi.mock('electron', () => ({
exit: vi.fn(() => {
throw new Error('Test exited via app.exit()');
}),
getPath: vi.fn().mockReturnValue('/mock/app/path'),
getAppPath: vi.fn().mockReturnValue('/mock/app/path'),
getPath: vi.fn(() => '/mock/app/path'),
getAppPath: vi.fn(() => '/mock/app/path'),
},
dialog: {
showErrorBox: vi.fn(),
Expand All @@ -41,14 +41,14 @@ vi.mock('electron', () => ({
}));

const mockAppWindow = {
loadPage: vi.fn().mockResolvedValue(undefined),
loadPage: vi.fn(),
send: vi.fn(),
sendServerStartProgress: vi.fn(),
loadComfyUI: vi.fn().mockResolvedValue(undefined),
loadComfyUI: vi.fn(),
};

vi.mock('@/main-process/appWindow', () => ({
AppWindow: vi.fn().mockImplementation(() => mockAppWindow),
AppWindow: vi.fn(() => mockAppWindow),
}));

vi.mock('@/config/comfySettings', () => ({
Expand All @@ -59,18 +59,18 @@ vi.mock('@/config/comfySettings', () => ({
saveSettings: vi.fn(),
}),
},
useComfySettings: vi.fn().mockReturnValue({
get: vi.fn().mockReturnValue('true'),
useComfySettings: vi.fn(() => ({
get: vi.fn(),
set: vi.fn(),
saveSettings: vi.fn(),
}),
})),
}));

vi.mock('@/store/desktopConfig', () => ({
useDesktopConfig: vi.fn().mockReturnValue({
get: vi.fn().mockReturnValue('/mock/path'),
useDesktopConfig: vi.fn(() => ({
get: vi.fn(() => '/mock/path'),
set: vi.fn(),
}),
})),
}));

const mockInstallation: Partial<ComfyInstallation> = {
Expand All @@ -84,7 +84,7 @@ const mockInstallation: Partial<ComfyInstallation> = {
};

const mockInstallationManager = {
ensureInstalled: vi.fn().mockResolvedValue(mockInstallation),
ensureInstalled: vi.fn(() => Promise.resolve(mockInstallation)),
};
vi.mock('@/install/installationManager', () => ({
InstallationManager: Object.assign(
Expand All @@ -94,29 +94,20 @@ vi.mock('@/install/installationManager', () => ({
}));

const mockComfyDesktopApp = {
buildServerArgs: vi.fn().mockResolvedValue({ port: '8188' }),
startComfyServer: vi.fn().mockResolvedValue(undefined),
buildServerArgs: vi.fn(),
startComfyServer: vi.fn(),
};
vi.mock('@/main-process/comfyDesktopApp', () => ({
ComfyDesktopApp: vi.fn().mockImplementation(() => mockComfyDesktopApp),
ComfyDesktopApp: vi.fn(() => mockComfyDesktopApp),
}));

vi.mock('@/services/sentry', () => ({
default: {
setSentryGpuContext: vi.fn().mockResolvedValue(undefined),
setSentryGpuContext: vi.fn(),
getBasePath: vi.fn(),
},
}));

vi.mock('@/services/telemetry', () => ({
getTelemetry: vi.fn().mockReturnValue({
hasConsent: false,
track: vi.fn(),
flush: vi.fn(),
}),
promptMetricsConsent: vi.fn().mockResolvedValue(true),
}));

describe('DesktopApp', () => {
let desktopApp: DesktopApp;
let mockOverrides: Partial<DevOverrides>;
Expand Down
14 changes: 7 additions & 7 deletions tests/unit/handlers/appinfoHandlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ vi.mock('electron', () => ({
app: {
isPackaged: false,
getPath: vi.fn(),
getVersion: vi.fn().mockReturnValue('1.0.0'),
getVersion: vi.fn(() => '1.0.0'),
},
ipcMain: {
on: vi.fn(),
Expand All @@ -21,17 +21,17 @@ vi.mock('electron', () => ({
}));

vi.mock('@/store/desktopConfig', () => ({
useDesktopConfig: vi.fn().mockReturnValue({
get: vi.fn().mockImplementation((key) => {
useDesktopConfig: vi.fn(() => ({
get: vi.fn((key: string) => {
if (key === 'basePath') return MOCK_BASE_PATH;
}),
set: vi.fn().mockReturnValue(true),
getAsync: vi.fn().mockImplementation((key) => {
set: vi.fn(),
getAsync: vi.fn((key: string) => {
if (key === 'windowStyle') return Promise.resolve(MOCK_WINDOW_STYLE);
if (key === 'detectedGpu') return Promise.resolve(MOCK_GPU_NAME);
}),
setAsync: vi.fn().mockReturnValue(Promise.resolve(true)),
}),
setAsync: vi.fn(),
})),
}));

vi.mock('@/config/comfyServerConfig', () => ({
Expand Down
67 changes: 36 additions & 31 deletions tests/unit/install/installationManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,64 +19,67 @@ vi.mock('electron', () => ({
on: vi.fn(),
},
app: {
getPath: vi.fn().mockReturnValue('valid/path'),
getPath: vi.fn(() => 'valid/path'),
},
}));

vi.mock('node:fs/promises', () => ({
default: {
access: vi.fn(),
readFile: vi.fn().mockResolvedValue('{}'),
readFile: vi.fn(() => Promise.resolve('{}')),
},
access: vi.fn(),
readFile: vi.fn().mockResolvedValue('{}'),
readFile: vi.fn(() => Promise.resolve('{}')),
}));

vi.mock('@/store/desktopConfig', () => ({
useDesktopConfig: vi.fn().mockReturnValue({
get: vi.fn().mockImplementation((key: string) => {
if (key === 'installState') return 'installed';
if (key === 'basePath') return 'valid/base';
}),
set: vi.fn().mockImplementation((key: string, value: string) => {
if (key !== 'basePath') throw new Error(`Unexpected key: ${key}`);
if (!value) throw new Error(`Unexpected value: [${value}]`);
}),
const config = {
get: vi.fn((key: string) => {
if (key === 'installState') return 'installed';
if (key === 'basePath') return 'valid/base';
}),
set: vi.fn((key: string, value: string) => {
if (key !== 'basePath') throw new Error(`Unexpected key: ${key}`);
if (!value) throw new Error(`Unexpected value: [${value}]`);
}),
};
vi.mock('@/store/desktopConfig', () => ({
useDesktopConfig: vi.fn(() => config),
}));

vi.mock('@/utils', async () => {
const actual = await vi.importActual<typeof utils>('@/utils');
return {
...actual,
pathAccessible: vi.fn().mockImplementation((path: string) => {
pathAccessible: vi.fn((path: string) => {
const isValid = path.startsWith('valid/') || path.endsWith(`\\System32\\vcruntime140.dll`);
return Promise.resolve(isValid);
}),
canExecute: vi.fn().mockResolvedValue(true),
canExecuteShellCommand: vi.fn().mockResolvedValue(true),
canExecute: vi.fn(() => Promise.resolve(true)),
canExecuteShellCommand: vi.fn(() => Promise.resolve(true)),
};
});

vi.mock('@/config/comfyServerConfig', () => {
return {
ComfyServerConfig: {
configPath: 'valid/extra_models_config.yaml',
exists: vi.fn().mockReturnValue(true),
readBasePathFromConfig: vi.fn().mockResolvedValue({
status: 'success',
path: 'valid/base',
}),
exists: vi.fn(() => Promise.resolve(true)),
readBasePathFromConfig: vi.fn(() =>
Promise.resolve({
status: 'success',
path: 'valid/base',
})
),
},
};
});

// Mock VirtualEnvironment with basic implementation
vi.mock('@/virtualEnvironment', () => {
return {
VirtualEnvironment: vi.fn().mockImplementation(() => ({
exists: vi.fn().mockResolvedValue(true),
hasRequirements: vi.fn().mockResolvedValue(true),
VirtualEnvironment: vi.fn(() => ({
exists: vi.fn(() => Promise.resolve(true)),
hasRequirements: vi.fn(() => Promise.resolve(true)),
pythonInterpreterPath: 'valid/python',
uvPath: 'valid/uv',
venvPath: 'valid/venv',
Expand All @@ -88,16 +91,16 @@ vi.mock('@/virtualEnvironment', () => {

// Mock Telemetry
vi.mock('@/services/telemetry', () => ({
getTelemetry: vi.fn().mockReturnValue({
getTelemetry: vi.fn(() => ({
track: vi.fn(),
}),
})),
trackEvent: () => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => descriptor,
}));

const createMockAppWindow = () => {
const mock = {
send: vi.fn(),
loadPage: vi.fn().mockResolvedValue(null),
loadPage: vi.fn(() => Promise.resolve(null)),
showOpenDialog: vi.fn(),
maximize: vi.fn(),
};
Expand Down Expand Up @@ -147,10 +150,9 @@ describe('InstallationManager', () => {

describe('ensureInstalled', () => {
beforeEach(() => {
// eslint-disable-next-line @typescript-eslint/require-await
vi.spyOn(ComfyInstallation, 'fromConfig').mockImplementation(async () => {
return new ComfyInstallation('installed', 'valid/base', createMockTelemetry());
});
vi.spyOn(ComfyInstallation, 'fromConfig').mockImplementation(() =>
Promise.resolve(new ComfyInstallation('installed', 'valid/base', createMockTelemetry()))
);
});

it('returns existing valid installation', async () => {
Expand All @@ -166,6 +168,9 @@ describe('InstallationManager', () => {
{
scenario: 'detects invalid base path',
mockSetup: () => {
vi.spyOn(ComfyInstallation, 'fromConfig').mockImplementation(() =>
Promise.resolve(new ComfyInstallation('installed', 'invalid/base', createMockTelemetry()))
);
vi.mocked(useDesktopConfig().get).mockImplementation((key: string) => {
if (key === 'installState') return 'installed';
if (key === 'basePath') return 'invalid/base';
Expand Down
10 changes: 5 additions & 5 deletions tests/unit/main-process/appWindow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,19 @@ vi.mock('electron', () => ({
}));

vi.mock('electron-store', () => ({
default: vi.fn().mockImplementation(() => ({
default: vi.fn(() => ({
get: vi.fn(),
set: vi.fn(),
})),
}));

vi.mock('@/store/desktopConfig', () => ({
useDesktopConfig: vi.fn().mockReturnValue({
get: vi.fn().mockImplementation((key) => {
useDesktopConfig: vi.fn(() => ({
get: vi.fn((key: string) => {
if (key === 'installState') return 'installed';
}),
set: vi.fn().mockReturnValue(true),
}),
set: vi.fn(),
})),
}));

describe('AppWindow.isOnPage', () => {
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/main-process/comfyDesktopApp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ import { findAvailablePort, getModelsDirectory } from '@/utils';
// Mock dependencies
vi.mock('@/config/comfySettings', () => {
const mockSettings = {
get: vi.fn().mockReturnValue(true),
get: vi.fn(() => true),
set: vi.fn(),
saveSettings: vi.fn(),
};
return {
ComfySettings: {
load: vi.fn().mockResolvedValue(mockSettings),
load: vi.fn(() => Promise.resolve(mockSettings)),
},
useComfySettings: vi.fn().mockReturnValue(mockSettings),
useComfySettings: vi.fn(() => mockSettings),
};
});

Expand Down Expand Up @@ -63,7 +63,7 @@ const mockTerminal = {
restore: vi.fn(),
};
vi.mock('@/shell/terminal', () => ({
Terminal: vi.fn().mockImplementation(() => mockTerminal),
Terminal: vi.fn(() => mockTerminal),
}));

vi.mock('@/main-process/comfyServer', () => ({
Expand Down
Loading
Loading