CI / Lint & Test (push) Canceled after 0s
- .agent/: контекст, запросы, роадмап, задачи, шаблоны и протоколы - заготовка тестовой инфраструктуры: vitest, eslint, prettier, ci-workflow
280 lines
8.5 KiB
TypeScript
280 lines
8.5 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
|
|
// Mock the Obsidian API surface used by AttachmentCleanPasteModule.
|
|
// vi.mock is hoisted above imports, so the module-under-test resolves to this
|
|
// stub instead of the alias target in __mocks__/obsidian.ts (which only
|
|
// exports `Plugin`).
|
|
vi.mock('obsidian', () => ({
|
|
App: class {},
|
|
Editor: class {},
|
|
MarkdownFileInfo: class {},
|
|
MarkdownView: class {},
|
|
Notice: class {
|
|
constructor(public message: string) {}
|
|
},
|
|
Setting: class {
|
|
constructor(_el: HTMLElement) {}
|
|
setName(_n: string): this {
|
|
return this;
|
|
}
|
|
setDesc(_d: string): this {
|
|
return this;
|
|
}
|
|
addTextArea(_cb: (textarea: unknown) => void): this {
|
|
return this;
|
|
}
|
|
},
|
|
// Minimal normalizePath: collapses backslashes, collapses duplicate slashes,
|
|
// strips leading/trailing slash. Sufficient for the inputs in these tests.
|
|
normalizePath: (p: string): string =>
|
|
p.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/|\/$/g, ''),
|
|
Plugin: class {},
|
|
}));
|
|
|
|
import { AttachmentCleanPasteModule } from '../../src/modules/attachment-clean-paste';
|
|
|
|
// Build a minimal File-like object compatible with the module's usage
|
|
// (only `name` and `arrayBuffer()` are read).
|
|
function createFile(name: string, content: string = 'data'): File {
|
|
return {
|
|
name,
|
|
arrayBuffer: async () =>
|
|
new TextEncoder().encode(content).buffer as ArrayBuffer,
|
|
} as unknown as File;
|
|
}
|
|
|
|
describe('AttachmentCleanPasteModule', () => {
|
|
let module: AttachmentCleanPasteModule;
|
|
let mockPlugin: Record<string, unknown>;
|
|
let mockWorkspace: {
|
|
on: ReturnType<typeof vi.fn>;
|
|
offref: ReturnType<typeof vi.fn>;
|
|
};
|
|
let mockVault: {
|
|
getConfig: ReturnType<typeof vi.fn>;
|
|
adapter: { exists: ReturnType<typeof vi.fn> };
|
|
createFolder: ReturnType<typeof vi.fn>;
|
|
getAvailablePath: ReturnType<typeof vi.fn>;
|
|
createBinary: ReturnType<typeof vi.fn>;
|
|
};
|
|
let pasteHandler:
|
|
| ((evt: ClipboardEvent, editor: unknown, info: unknown) => Promise<void>)
|
|
| null;
|
|
let dropHandler:
|
|
| ((evt: DragEvent, editor: unknown, info: unknown) => Promise<void>)
|
|
| null;
|
|
let settings: { extensions: string };
|
|
|
|
beforeEach(() => {
|
|
pasteHandler = null;
|
|
dropHandler = null;
|
|
|
|
mockWorkspace = {
|
|
on: vi.fn((event: string, handler: unknown) => {
|
|
if (event === 'editor-paste') {
|
|
pasteHandler = handler as typeof pasteHandler;
|
|
} else if (event === 'editor-drop') {
|
|
dropHandler = handler as typeof dropHandler;
|
|
}
|
|
return { event, handler };
|
|
}),
|
|
offref: vi.fn(),
|
|
};
|
|
|
|
const mockAdapter = {
|
|
exists: vi.fn(async () => true),
|
|
};
|
|
|
|
mockVault = {
|
|
getConfig: vi.fn((key: string) =>
|
|
key === 'attachmentFolderPath' ? 'attachments' : '',
|
|
),
|
|
adapter: mockAdapter,
|
|
createFolder: vi.fn(async () => undefined),
|
|
// Mirrors the real Obsidian contract: returns "<basePath>.<ext>".
|
|
getAvailablePath: vi.fn(
|
|
async (basePath: string, ext: string) => `${basePath}.${ext}`,
|
|
),
|
|
createBinary: vi.fn(async () => undefined),
|
|
};
|
|
|
|
mockPlugin = {
|
|
app: {
|
|
workspace: mockWorkspace,
|
|
vault: mockVault,
|
|
},
|
|
};
|
|
|
|
settings = { extensions: 'png, jpg' };
|
|
|
|
module = new AttachmentCleanPasteModule();
|
|
module.onload(
|
|
mockPlugin as unknown as Parameters<
|
|
AttachmentCleanPasteModule['onload']
|
|
>[0],
|
|
settings,
|
|
);
|
|
});
|
|
|
|
describe('shouldProcess', () => {
|
|
// Helper: mustProcess is a private method; reach it via a typed cast.
|
|
const callShouldProcess = (
|
|
filename: string,
|
|
cfg: { extensions: string } = settings,
|
|
): boolean =>
|
|
(
|
|
module as unknown as {
|
|
shouldProcess: (
|
|
f: string,
|
|
s: { extensions: string },
|
|
) => boolean;
|
|
}
|
|
).shouldProcess(filename, cfg);
|
|
|
|
it('возвращает true для расширений из настроек (png, jpg)', () => {
|
|
expect(callShouldProcess('image.png')).toBe(true);
|
|
expect(callShouldProcess('photo.jpg')).toBe(true);
|
|
});
|
|
|
|
it('возвращает false для расширений НЕ из настроек (exe, zip)', () => {
|
|
expect(callShouldProcess('malware.exe')).toBe(false);
|
|
expect(callShouldProcess('archive.zip')).toBe(false);
|
|
});
|
|
|
|
it('возвращает false для файлов без расширения', () => {
|
|
expect(callShouldProcess('README')).toBe(false);
|
|
expect(callShouldProcess('Makefile')).toBe(false);
|
|
});
|
|
|
|
it('корректно обрабатывает запятые и пробелы в extensions ("png, jpg" → png и jpg)', () => {
|
|
const cfg = { extensions: ' png , jpg ' };
|
|
expect(callShouldProcess('image.png', cfg)).toBe(true);
|
|
expect(callShouldProcess('photo.jpg', cfg)).toBe(true);
|
|
// Negative case: gif is not in the list.
|
|
expect(callShouldProcess('anim.gif', cfg)).toBe(false);
|
|
});
|
|
|
|
it('case-insensitive: JPG матчится как jpg', () => {
|
|
expect(callShouldProcess('IMAGE.JPG')).toBe(true);
|
|
expect(callShouldProcess('photo.PNG')).toBe(true);
|
|
expect(callShouldProcess('Mixed.JpG')).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('paste handler (createPasteHandler)', () => {
|
|
it('вызывает preventDefault для файлов с подходящими расширениями', async () => {
|
|
const editor = { replaceSelection: vi.fn() };
|
|
const file = createFile('image.png');
|
|
|
|
const preventDefault = vi.fn();
|
|
const stopPropagation = vi.fn();
|
|
const evt = {
|
|
clipboardData: { files: [file] },
|
|
preventDefault,
|
|
stopPropagation,
|
|
} as unknown as ClipboardEvent;
|
|
|
|
expect(pasteHandler).not.toBeNull();
|
|
await pasteHandler!(evt, editor, {});
|
|
|
|
// Matching extension → processAll took over the event.
|
|
expect(preventDefault).toHaveBeenCalledTimes(1);
|
|
expect(stopPropagation).toHaveBeenCalledTimes(1);
|
|
// The link was inserted into the editor.
|
|
expect(editor.replaceSelection).toHaveBeenCalledTimes(1);
|
|
expect(editor.replaceSelection).toHaveBeenCalledWith(
|
|
'[[attachments/image.png|image]]',
|
|
);
|
|
});
|
|
|
|
it('НЕ вызывает preventDefault, если ни один файл не подходит по расширению', async () => {
|
|
const editor = { replaceSelection: vi.fn() };
|
|
const file = createFile('malware.exe');
|
|
|
|
const preventDefault = vi.fn();
|
|
const stopPropagation = vi.fn();
|
|
const evt = {
|
|
clipboardData: { files: [file] },
|
|
preventDefault,
|
|
stopPropagation,
|
|
} as unknown as ClipboardEvent;
|
|
|
|
expect(pasteHandler).not.toBeNull();
|
|
await pasteHandler!(evt, editor, {});
|
|
|
|
expect(preventDefault).not.toHaveBeenCalled();
|
|
expect(stopPropagation).not.toHaveBeenCalled();
|
|
expect(editor.replaceSelection).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('processFile', () => {
|
|
it('формирует ссылку в формате "[[path|name]]"', async () => {
|
|
const file = createFile('image.png');
|
|
|
|
const result = await (
|
|
module as unknown as {
|
|
processFile: (
|
|
f: File,
|
|
s: { extensions: string },
|
|
) => Promise<string | null>;
|
|
}
|
|
).processFile(file, settings);
|
|
|
|
expect(result).toBe('[[attachments/image.png|image]]');
|
|
expect(mockVault.createBinary).toHaveBeenCalledTimes(1);
|
|
// The binary payload was passed to the vault.
|
|
const [, payload] = (
|
|
mockVault.createBinary.mock.calls[0] as [string, ArrayBuffer]
|
|
);
|
|
expect(payload).toBeInstanceOf(ArrayBuffer);
|
|
});
|
|
|
|
it('использует имя файла без расширения как alias', async () => {
|
|
const file = createFile('my-screenshot.png');
|
|
|
|
const result = await (
|
|
module as unknown as {
|
|
processFile: (
|
|
f: File,
|
|
s: { extensions: string },
|
|
) => Promise<string | null>;
|
|
}
|
|
).processFile(file, settings);
|
|
|
|
expect(result).toBe('[[attachments/my-screenshot.png|my-screenshot]]');
|
|
});
|
|
});
|
|
|
|
describe('defaultSettings', () => {
|
|
it('содержит разумный список расширений по умолчанию', () => {
|
|
expect(module.defaultSettings).toEqual({
|
|
extensions: 'png, jpg, jpeg, gif, svg, webp, bmp, pdf',
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('onload lifecycle', () => {
|
|
it('регистрирует оба обработчика (editor-paste и editor-drop) в workspace', () => {
|
|
expect(mockWorkspace.on).toHaveBeenCalledWith(
|
|
'editor-paste',
|
|
expect.any(Function),
|
|
);
|
|
expect(mockWorkspace.on).toHaveBeenCalledWith(
|
|
'editor-drop',
|
|
expect.any(Function),
|
|
);
|
|
});
|
|
|
|
it('onunload отключает оба зарегистрированных обработчика', () => {
|
|
module.onunload(
|
|
mockPlugin as unknown as Parameters<
|
|
AttachmentCleanPasteModule['onunload']
|
|
>[0],
|
|
);
|
|
|
|
expect(mockWorkspace.offref).toHaveBeenCalledTimes(2);
|
|
});
|
|
});
|
|
});
|