diff --git a/tests/ModalSettingsHelper.test.ts b/tests/ModalSettingsHelper.test.ts new file mode 100644 index 0000000..fe1319a --- /dev/null +++ b/tests/ModalSettingsHelper.test.ts @@ -0,0 +1,309 @@ +import { describe, it, expect } from 'vitest'; +import { ModalSettingsHelper } from '../src/core/ModalSettingsHelper'; +import { obsidianTypstPDFExportSettings, ExportFormat } from '../src/core/settings'; +import { TFile } from 'obsidian'; + +// Mock TFile +const createMockFile = (path: string, basename: string): TFile => ({ + path, + basename, + extension: 'md', +} as TFile); + +// Create mock settings +const createMockSettings = (overrides?: Partial): obsidianTypstPDFExportSettings => ({ + pandocPath: '/usr/bin/pandoc', + typstPath: '/usr/bin/typst', + outputFolder: 'exports', + executablePaths: { + imagemagickPath: '', + additionalPaths: [], + }, + customEnvironmentVariables: {}, + exportDefaults: { + template: 'default', + format: ExportFormat.Standard, + pageSize: 'a4', + orientation: 'portrait', + marginTop: '2.5cm', + marginBottom: '2.5cm', + marginLeft: '2.5cm', + marginRight: '2.5cm', + bodyFont: 'Georgia', + headingFont: 'Helvetica', + monospaceFont: 'Courier New', + bodyFontSize: '11pt', + }, + typography: { + fonts: { + body: 'Georgia', + heading: 'Helvetica', + monospace: 'Courier New', + }, + fontSizes: { + body: 11, + heading: 16, + small: 9, + }, + }, + pageSetup: { + size: 'a4', + orientation: 'portrait', + margins: { + top: 71, + right: 71, + bottom: 71, + left: 71, + }, + }, + behavior: { + openAfterExport: true, + preserveFolderStructure: false, + exportConcurrency: 3, + debugMode: false, + embedPdfFiles: false, + embedAllFiles: false, + printFrontmatter: false, + }, + ...overrides, +}); + +describe('ModalSettingsHelper', () => { + describe('prepareModalSettings', () => { + it('should prepare settings for single file', () => { + const file = createMockFile('notes/test.md', 'test'); + const templates = ['default', 'modern']; + const settings = createMockSettings(); + + const result = ModalSettingsHelper.prepareModalSettings({ + file, + availableTemplates: templates, + settings, + }); + + expect(result.notePath).toBe('notes/test.md'); + expect(result.noteTitle).toBe('test'); + expect(result.files).toBeUndefined(); + expect(result.template).toBe('default'); + expect(result.format).toBe(ExportFormat.Standard); + expect(result.outputFolder).toBe('exports'); + expect(result.availableTemplates).toEqual(templates); + }); + + it('should prepare settings for multi-file export', () => { + const file1 = createMockFile('notes/test1.md', 'test1'); + const file2 = createMockFile('notes/test2.md', 'test2'); + const file3 = createMockFile('notes/test3.md', 'test3'); + const templates = ['default']; + const settings = createMockSettings(); + + const result = ModalSettingsHelper.prepareModalSettings({ + file: file1, + additionalFiles: [file2, file3], + availableTemplates: templates, + settings, + }); + + expect(result.noteTitle).toBe('3 files'); + expect(result.files).toHaveLength(3); + expect(result.files).toContain(file1); + expect(result.files).toContain(file2); + expect(result.files).toContain(file3); + }); + + it('should include template variables from settings', () => { + const file = createMockFile('notes/test.md', 'test'); + const settings = createMockSettings(); + + const result = ModalSettingsHelper.prepareModalSettings({ + file, + availableTemplates: ['default'], + settings, + }); + + expect(result.templateVariables).toBeDefined(); + expect(result.templateVariables?.pageSize).toBe('a4'); + expect(result.templateVariables?.orientation).toBe('portrait'); + expect(result.templateVariables?.flipped).toBe(false); + expect(result.templateVariables?.marginTop).toBe('71'); + expect(result.templateVariables?.bodyFont).toBe('Georgia'); + expect(result.templateVariables?.headingFont).toBe('Helvetica'); + expect(result.templateVariables?.monospaceFont).toBe('Courier New'); + expect(result.templateVariables?.bodyFontSize).toBe(11); + }); + + it('should set flipped to true for landscape orientation', () => { + const file = createMockFile('notes/test.md', 'test'); + const settings = createMockSettings({ + pageSetup: { + size: 'a4', + orientation: 'landscape', + margins: { top: 71, right: 71, bottom: 71, left: 71 }, + }, + }); + + const result = ModalSettingsHelper.prepareModalSettings({ + file, + availableTemplates: ['default'], + settings, + }); + + expect(result.templateVariables?.orientation).toBe('landscape'); + expect(result.templateVariables?.flipped).toBe(true); + }); + + it('should add width:auto for landscape single-page format', () => { + const file = createMockFile('notes/test.md', 'test'); + const settings = createMockSettings({ + pageSetup: { + size: 'a4', + orientation: 'landscape', + margins: { top: 71, right: 71, bottom: 71, left: 71 }, + }, + exportDefaults: { + template: 'default', + format: ExportFormat.SinglePage, + pageSize: 'a4', + orientation: 'landscape', + marginTop: '2.5cm', + marginBottom: '2.5cm', + marginLeft: '2.5cm', + marginRight: '2.5cm', + bodyFont: 'Georgia', + headingFont: 'Helvetica', + monospaceFont: 'Courier New', + bodyFontSize: '11pt', + }, + }); + + const result = ModalSettingsHelper.prepareModalSettings({ + file, + availableTemplates: ['default'], + settings, + }); + + expect(result.templateVariables?.width).toBe('auto'); + }); + + it('should not add width:auto for portrait or standard format', () => { + const file = createMockFile('notes/test.md', 'test'); + + // Test portrait orientation + const settingsPortrait = createMockSettings(); + const resultPortrait = ModalSettingsHelper.prepareModalSettings({ + file, + availableTemplates: ['default'], + settings: settingsPortrait, + }); + expect(resultPortrait.templateVariables?.width).toBeUndefined(); + + // Test landscape with standard format + const settingsLandscapeStandard = createMockSettings({ + pageSetup: { + size: 'a4', + orientation: 'landscape', + margins: { top: 71, right: 71, bottom: 71, left: 71 }, + }, + exportDefaults: { + template: 'default', + format: ExportFormat.Standard, + pageSize: 'a4', + orientation: 'landscape', + marginTop: '2.5cm', + marginBottom: '2.5cm', + marginLeft: '2.5cm', + marginRight: '2.5cm', + bodyFont: 'Georgia', + headingFont: 'Helvetica', + monospaceFont: 'Courier New', + bodyFontSize: '11pt', + }, + }); + const resultLandscapeStandard = ModalSettingsHelper.prepareModalSettings({ + file, + availableTemplates: ['default'], + settings: settingsLandscapeStandard, + }); + expect(resultLandscapeStandard.templateVariables?.width).toBeUndefined(); + }); + + it('should use settings behavior options', () => { + const file = createMockFile('notes/test.md', 'test'); + const settings = createMockSettings({ + behavior: { + openAfterExport: false, + preserveFolderStructure: true, + exportConcurrency: 3, + debugMode: false, + embedPdfFiles: false, + embedAllFiles: false, + printFrontmatter: false, + }, + }); + + const result = ModalSettingsHelper.prepareModalSettings({ + file, + availableTemplates: ['default'], + settings, + }); + + expect(result.openAfterExport).toBe(false); + expect(result.preserveFolderStructure).toBe(true); + }); + }); + + describe('prepareForSingleFile', () => { + it('should be a convenience wrapper for single file', () => { + const file = createMockFile('notes/test.md', 'test'); + const templates = ['default', 'modern']; + const settings = createMockSettings(); + + const result = ModalSettingsHelper.prepareForSingleFile( + file, + templates, + settings + ); + + expect(result.notePath).toBe('notes/test.md'); + expect(result.noteTitle).toBe('test'); + expect(result.files).toBeUndefined(); + expect(result.availableTemplates).toEqual(templates); + }); + }); + + describe('prepareForMultiFile', () => { + it('should be a convenience wrapper for multiple files', () => { + const files = [ + createMockFile('notes/test1.md', 'test1'), + createMockFile('notes/test2.md', 'test2'), + ]; + const templates = ['default']; + const settings = createMockSettings(); + + const result = ModalSettingsHelper.prepareForMultiFile( + files, + templates, + settings + ); + + expect(result.noteTitle).toBe('2 files'); + expect(result.files).toEqual(files); + expect(result.notePath).toBe('notes/test1.md'); + }); + + it('should handle single file array', () => { + const files = [createMockFile('notes/test.md', 'test')]; + const settings = createMockSettings(); + + const result = ModalSettingsHelper.prepareForMultiFile( + files, + ['default'], + settings + ); + + // Single file should still show as single file + expect(result.noteTitle).toBe('test'); + expect(result.files).toBeUndefined(); + }); + }); +}); diff --git a/tests/SecurityUtils.test.ts b/tests/SecurityUtils.test.ts new file mode 100644 index 0000000..3b73c14 --- /dev/null +++ b/tests/SecurityUtils.test.ts @@ -0,0 +1,216 @@ +import { describe, it, expect } from 'vitest'; +import { SecurityUtils } from '../src/core/SecurityUtils'; + +describe('SecurityUtils', () => { + describe('validateOutputPath', () => { + it('should accept valid relative paths', () => { + expect(SecurityUtils.validateOutputPath('exports')).toBe(true); + expect(SecurityUtils.validateOutputPath('my-exports')).toBe(true); + expect(SecurityUtils.validateOutputPath('exports/pdfs')).toBe(true); + expect(SecurityUtils.validateOutputPath('folder_name')).toBe(true); + }); + + it('should reject empty or invalid input', () => { + expect(SecurityUtils.validateOutputPath('')).toBe(false); + expect(SecurityUtils.validateOutputPath(null as any)).toBe(false); + expect(SecurityUtils.validateOutputPath(undefined as any)).toBe(false); + expect(SecurityUtils.validateOutputPath(123 as any)).toBe(false); + }); + + it('should reject path traversal attempts', () => { + expect(SecurityUtils.validateOutputPath('..')).toBe(false); + expect(SecurityUtils.validateOutputPath('../')).toBe(false); + expect(SecurityUtils.validateOutputPath('../../secret')).toBe(false); + expect(SecurityUtils.validateOutputPath('exports/../../../etc')).toBe(false); + }); + + it('should reject absolute paths', () => { + expect(SecurityUtils.validateOutputPath('/etc/passwd')).toBe(false); + expect(SecurityUtils.validateOutputPath('/usr/local')).toBe(false); + expect(SecurityUtils.validateOutputPath('\\Windows\\System32')).toBe(false); + expect(SecurityUtils.validateOutputPath('\\etc\\hosts')).toBe(false); + }); + + it('should reject null bytes', () => { + expect(SecurityUtils.validateOutputPath('exports\x00malicious')).toBe(false); + expect(SecurityUtils.validateOutputPath('\x00')).toBe(false); + }); + + it('should reject double slashes', () => { + // Note: path.normalize() resolves double slashes in the middle, so we test edge cases + // that remain problematic even after normalization + expect(SecurityUtils.validateOutputPath('//exports')).toBe(false); // Starts with // + }); + + it('should reject invalid filename characters', () => { + expect(SecurityUtils.validateOutputPath('exportstest')).toBe(false); + expect(SecurityUtils.validateOutputPath('exports:test')).toBe(false); + expect(SecurityUtils.validateOutputPath('exports"test')).toBe(false); + expect(SecurityUtils.validateOutputPath('exports|test')).toBe(false); + expect(SecurityUtils.validateOutputPath('exports?test')).toBe(false); + expect(SecurityUtils.validateOutputPath('exports*test')).toBe(false); + }); + + it('should reject Windows reserved names', () => { + expect(SecurityUtils.validateOutputPath('CON')).toBe(false); + expect(SecurityUtils.validateOutputPath('PRN')).toBe(false); + expect(SecurityUtils.validateOutputPath('AUX')).toBe(false); + expect(SecurityUtils.validateOutputPath('NUL')).toBe(false); + expect(SecurityUtils.validateOutputPath('COM1')).toBe(false); + expect(SecurityUtils.validateOutputPath('COM9')).toBe(false); + expect(SecurityUtils.validateOutputPath('LPT1')).toBe(false); + expect(SecurityUtils.validateOutputPath('lpt9')).toBe(false); // Case insensitive + }); + + it('should handle whitespace correctly', () => { + expect(SecurityUtils.validateOutputPath(' exports ')).toBe(true); + expect(SecurityUtils.validateOutputPath(' .. ')).toBe(false); + }); + }); + + describe('validateExecutablePath', () => { + it('should accept empty paths (system PATH)', () => { + expect(SecurityUtils.validateExecutablePath('')).toBe(true); + expect(SecurityUtils.validateExecutablePath(' ')).toBe(true); + }); + + it('should accept valid executable paths', () => { + expect(SecurityUtils.validateExecutablePath('/usr/bin/pandoc')).toBe(true); + expect(SecurityUtils.validateExecutablePath('/opt/typst/typst')).toBe(true); + expect(SecurityUtils.validateExecutablePath('C:\\Program Files\\Pandoc\\pandoc.exe')).toBe(true); + expect(SecurityUtils.validateExecutablePath('pandoc')).toBe(true); + }); + + it('should reject shell metacharacters', () => { + expect(SecurityUtils.validateExecutablePath('pandoc;rm -rf /')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc&whoami')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc|cat /etc/passwd')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc`whoami`')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc$(whoami)')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc{}')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc[]')).toBe(false); + }); + + it('should reject null bytes', () => { + expect(SecurityUtils.validateExecutablePath('pandoc\x00malicious')).toBe(false); + expect(SecurityUtils.validateExecutablePath('\x00')).toBe(false); + }); + + it('should reject newlines', () => { + expect(SecurityUtils.validateExecutablePath('pandoc\nrm -rf /')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc\r\nmalicious')).toBe(false); + }); + + it('should reject command separators with whitespace', () => { + expect(SecurityUtils.validateExecutablePath('pandoc ; whoami')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc & whoami')).toBe(false); + expect(SecurityUtils.validateExecutablePath('pandoc | whoami')).toBe(false); + }); + + it('should reject variable and command substitution', () => { + expect(SecurityUtils.validateExecutablePath('${MALICIOUS}')).toBe(false); + expect(SecurityUtils.validateExecutablePath('`whoami`')).toBe(false); + expect(SecurityUtils.validateExecutablePath('$(malicious)')).toBe(false); + }); + + it('should handle whitespace in paths', () => { + expect(SecurityUtils.validateExecutablePath(' /usr/bin/pandoc ')).toBe(true); + }); + }); + + describe('getPathValidationError', () => { + it('should return appropriate error for empty path', () => { + expect(SecurityUtils.getPathValidationError('')).toBe('Output folder is required'); + expect(SecurityUtils.getPathValidationError(null as any)).toBe('Output folder is required'); + expect(SecurityUtils.getPathValidationError(undefined as any)).toBe('Output folder is required'); + }); + + it('should return appropriate error for path traversal', () => { + const error = SecurityUtils.getPathValidationError('..'); + expect(error).toBe('Path traversal attempts (..) are not allowed'); + }); + + it('should return appropriate error for absolute paths', () => { + const error = SecurityUtils.getPathValidationError('/etc/passwd'); + expect(error).toBe('Absolute paths are not allowed - use relative paths from vault root'); + }); + + it('should return appropriate error for null bytes', () => { + const error = SecurityUtils.getPathValidationError('exports\x00'); + expect(error).toBe('Null bytes are not allowed in paths'); + }); + + it('should return appropriate error for double slashes', () => { + // Test with leading // which should fail the absolute path check + const error = SecurityUtils.getPathValidationError('//exports'); + expect(error).toBe('Absolute paths are not allowed - use relative paths from vault root'); + }); + + it('should return appropriate error for invalid characters', () => { + const error = SecurityUtils.getPathValidationError('exports { + const error = SecurityUtils.getPathValidationError('CON'); + expect(error).toBe('Reserved system names are not allowed as folder names'); + }); + + it('should return generic error for unknown issues', () => { + // For a valid path, it would still return 'Invalid path format' if called + // (though normally you wouldn't call this for valid paths) + const validPath = 'exports'; + // This is a bit contrived since we wouldn't normally call this on valid paths + // but it tests the fallback case + expect(SecurityUtils.getPathValidationError(validPath)).toBe('Invalid path format'); + }); + }); + + describe('getExecutablePathValidationError', () => { + it('should return appropriate error for empty path', () => { + expect(SecurityUtils.getExecutablePathValidationError(null as any)) + .toBe('Executable path is required'); + }); + + it('should return appropriate error for shell metacharacters', () => { + const error = SecurityUtils.getExecutablePathValidationError('pandoc;whoami'); + expect(error).toBe('Shell metacharacters are not allowed in executable paths'); + }); + + it('should return appropriate error for null bytes', () => { + const error = SecurityUtils.getExecutablePathValidationError('pandoc\x00'); + expect(error).toBe('Null bytes are not allowed in paths'); + }); + + it('should return appropriate error for newlines', () => { + const error = SecurityUtils.getExecutablePathValidationError('pandoc\nrm'); + expect(error).toBe('Newlines are not allowed in paths'); + }); + + it('should return appropriate error for command separators', () => { + // The semicolon is caught by shell metacharacters check first + const error = SecurityUtils.getExecutablePathValidationError('pandoc ; whoami'); + expect(error).toBe('Shell metacharacters are not allowed in executable paths'); + }); + + it('should return appropriate error for substitution patterns', () => { + // These contain shell metacharacters, which are checked first + const error = SecurityUtils.getExecutablePathValidationError('${VAR}'); + expect(error).toBe('Shell metacharacters are not allowed in executable paths'); + + const error2 = SecurityUtils.getExecutablePathValidationError('`cmd`'); + expect(error2).toBe('Shell metacharacters are not allowed in executable paths'); + + const error3 = SecurityUtils.getExecutablePathValidationError('$(cmd)'); + expect(error3).toBe('Shell metacharacters are not allowed in executable paths'); + }); + + it('should return generic error for valid paths when forced', () => { + const validPath = '/usr/bin/pandoc'; + // Again, contrived - but tests the fallback + expect(SecurityUtils.getExecutablePathValidationError(validPath)) + .toBe('Invalid executable path format'); + }); + }); +}); diff --git a/tests/TempDirectoryManager.test.ts b/tests/TempDirectoryManager.test.ts new file mode 100644 index 0000000..2515c8e --- /dev/null +++ b/tests/TempDirectoryManager.test.ts @@ -0,0 +1,368 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { TempDirectoryManager } from '../src/core/TempDirectoryManager'; +import type { App } from 'obsidian'; + +describe('TempDirectoryManager', () => { + let mockApp: App; + let mockVaultAdapter: any; + + beforeEach(() => { + // Reset mocks before each test + mockVaultAdapter = { + exists: vi.fn(), + mkdir: vi.fn(), + remove: vi.fn(), + list: vi.fn(), + }; + + mockApp = { + vault: { + adapter: mockVaultAdapter, + }, + } as any; + }); + + describe('constructor and static create', () => { + it('should create an instance with provided options', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'test-plugin', + app: mockApp, + }); + + expect(manager).toBeInstanceOf(TempDirectoryManager); + }); + + it('should use default plugin name if not provided', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + app: mockApp, + }); + + const tempDir = manager.getTempDir('images'); + expect(tempDir).toContain('typst-pdf-export'); + }); + + it('should create instance via static create method', () => { + const manager = TempDirectoryManager.create( + '/vault', + '.obsidian', + 'test-plugin', + mockApp + ); + + expect(manager).toBeInstanceOf(TempDirectoryManager); + }); + }); + + describe('getTempDir', () => { + it('should return correct path for images temp directory', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempDir = manager.getTempDir('images'); + expect(tempDir).toContain('temp-images'); + expect(tempDir).toContain('.obsidian'); + expect(tempDir).toContain('plugins'); + }); + + it('should return correct path for pandoc temp directory', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempDir = manager.getTempDir('pandoc'); + expect(tempDir).toContain('temp-pandoc'); + expect(tempDir).toContain('.obsidian'); + expect(tempDir).toContain('plugins'); + }); + + it('should normalize paths correctly', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempDir = manager.getTempDir('images'); + // Should use forward slashes after normalization + expect(tempDir).not.toContain('\\'); + }); + + it('should handle absolute vault paths on Windows', () => { + const manager = new TempDirectoryManager({ + vaultPath: 'C:/Users/Test/Vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempDir = manager.getTempDir('images'); + expect(tempDir).toContain('C:/Users/Test/Vault'); + }); + }); + + describe('ensureTempDir', () => { + it('should create directory if it does not exist', async () => { + mockVaultAdapter.exists.mockResolvedValue(false); + mockVaultAdapter.mkdir.mockResolvedValue(undefined); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.ensureTempDir('images'); + + expect(mockVaultAdapter.exists).toHaveBeenCalledOnce(); + expect(mockVaultAdapter.mkdir).toHaveBeenCalledOnce(); + expect(result).toContain('temp-images'); + }); + + it('should not create directory if it already exists', async () => { + mockVaultAdapter.exists.mockResolvedValue(true); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.ensureTempDir('images'); + + expect(mockVaultAdapter.exists).toHaveBeenCalledOnce(); + expect(mockVaultAdapter.mkdir).not.toHaveBeenCalled(); + expect(result).toContain('temp-images'); + }); + + it('should handle both images and pandoc directories', async () => { + mockVaultAdapter.exists.mockResolvedValue(false); + mockVaultAdapter.mkdir.mockResolvedValue(undefined); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const imagesDir = await manager.ensureTempDir('images'); + const pandocDir = await manager.ensureTempDir('pandoc'); + + expect(imagesDir).toContain('temp-images'); + expect(pandocDir).toContain('temp-pandoc'); + expect(mockVaultAdapter.mkdir).toHaveBeenCalledTimes(2); + }); + }); + + describe('cleanupTempDir', () => { + it('should remove all files from temp directory', async () => { + mockVaultAdapter.exists.mockResolvedValue(true); + mockVaultAdapter.list.mockResolvedValue({ + files: ['file1.png', 'file2.png', 'file3.typ'], + folders: [], + }); + mockVaultAdapter.remove.mockResolvedValue(undefined); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.cleanupTempDir('images'); + + expect(result).toBe(true); + expect(mockVaultAdapter.remove).toHaveBeenCalledTimes(3); + }); + + it('should return true if directory does not exist', async () => { + mockVaultAdapter.exists.mockResolvedValue(false); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.cleanupTempDir('images'); + + expect(result).toBe(true); + expect(mockVaultAdapter.remove).not.toHaveBeenCalled(); + }); + + it('should return false and log warning on error', async () => { + mockVaultAdapter.exists.mockRejectedValue(new Error('Access denied')); + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.cleanupTempDir('images'); + + expect(result).toBe(false); + expect(consoleWarnSpy).toHaveBeenCalled(); + + consoleWarnSpy.mockRestore(); + }); + + it('should handle errors during file removal', async () => { + mockVaultAdapter.exists.mockResolvedValue(true); + mockVaultAdapter.list.mockResolvedValue({ + files: ['file1.png'], + folders: [], + }); + mockVaultAdapter.remove.mockRejectedValue(new Error('Cannot delete')); + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.cleanupTempDir('images'); + + expect(result).toBe(false); + expect(consoleWarnSpy).toHaveBeenCalled(); + + consoleWarnSpy.mockRestore(); + }); + }); + + describe('cleanupAllTempDirs', () => { + it('should clean up both temp directories', async () => { + mockVaultAdapter.exists.mockResolvedValue(true); + mockVaultAdapter.list.mockResolvedValue({ + files: ['file1.png'], + folders: [], + }); + mockVaultAdapter.remove.mockResolvedValue(undefined); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.cleanupAllTempDirs(); + + expect(result).toEqual({ images: true, pandoc: true }); + expect(mockVaultAdapter.list).toHaveBeenCalledTimes(2); + }); + + it('should return status for each directory independently', async () => { + let callCount = 0; + mockVaultAdapter.exists.mockImplementation(() => { + callCount++; + // First call (images) succeeds, second call (pandoc) fails + if (callCount === 1) return Promise.resolve(true); + return Promise.reject(new Error('Access denied')); + }); + mockVaultAdapter.list.mockResolvedValue({ + files: ['file1.png'], + folders: [], + }); + mockVaultAdapter.remove.mockResolvedValue(undefined); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const result = await manager.cleanupAllTempDirs(); + + expect(result.images).toBe(true); + expect(result.pandoc).toBe(false); + }); + }); + + describe('isPluginTempDir', () => { + it('should return true for images temp directory', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempImagesDir = manager.getTempDir('images'); + expect(manager.isPluginTempDir(tempImagesDir)).toBe(true); + }); + + it('should return true for pandoc temp directory', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempPandocDir = manager.getTempDir('pandoc'); + expect(manager.isPluginTempDir(tempPandocDir)).toBe(true); + }); + + it('should return true for subdirectories within temp directories', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempImagesDir = manager.getTempDir('images'); + const subDir = `${tempImagesDir}/subfolder`; + expect(manager.isPluginTempDir(subDir)).toBe(true); + }); + + it('should return false for non-temp directories', () => { + const manager = new TempDirectoryManager({ + vaultPath: '/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + expect(manager.isPluginTempDir('/vault/some-other-folder')).toBe(false); + expect(manager.isPluginTempDir('/vault/.obsidian/plugins/other-plugin')).toBe(false); + }); + + it('should handle paths with different separators', () => { + const manager = new TempDirectoryManager({ + vaultPath: 'C:/vault', + configDir: '.obsidian', + pluginName: 'typst-pdf-export', + app: mockApp, + }); + + const tempImagesDir = manager.getTempDir('images'); + // Test with backslashes (should be normalized) + const windowsStylePath = tempImagesDir.replace(/\//g, '\\'); + expect(manager.isPluginTempDir(windowsStylePath)).toBe(true); + }); + }); +}); diff --git a/tests/TypstVariableMapper.test.ts b/tests/TypstVariableMapper.test.ts new file mode 100644 index 0000000..78ab0bb --- /dev/null +++ b/tests/TypstVariableMapper.test.ts @@ -0,0 +1,233 @@ +import { describe, it, expect, vi } from 'vitest'; +import { TypstVariableMapper } from '../src/converters/pandoc/TypstVariableMapper'; +import { PandocOptions } from '../src/converters/converterTypes'; +import { ExportFormat, obsidianTypstPDFExportSettings } from '../src/core/settings'; + +const createMockPlugin = (settings: Partial = {}) => ({ + settings: { + pandocPath: '/usr/bin/pandoc', + typstPath: '/usr/bin/typst', + outputFolder: 'exports', + executablePaths: { imagemagickPath: '', additionalPaths: [] }, + customEnvironmentVariables: {}, + exportDefaults: { + template: 'default', + format: ExportFormat.Standard, + pageSize: 'a4', + orientation: 'portrait' as const, + marginTop: '2.5cm', + marginBottom: '2.5cm', + marginLeft: '2.5cm', + marginRight: '2.5cm', + bodyFont: 'Georgia', + headingFont: 'Helvetica', + monospaceFont: 'Courier', + bodyFontSize: '11pt', + }, + typography: { + fonts: { body: 'Georgia', heading: 'Helvetica', monospace: 'Courier' }, + fontSizes: { body: 11, heading: 16, small: 9 }, + }, + pageSetup: { + size: 'a4', + orientation: 'portrait' as const, + margins: { top: 71, right: 71, bottom: 71, left: 71 }, + }, + behavior: { + openAfterExport: true, + preserveFolderStructure: false, + exportConcurrency: 3, + debugMode: false, + embedPdfFiles: false, + embedAllFiles: false, + printFrontmatter: false, + }, + ...settings, + }, +} as any); + +describe('TypstVariableMapper', () => { + describe('transformExportConfigVariable', () => { + it('should map bodyFont to font', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { bodyFont: 'Arial' }, + }; + + const vars = mapper.mapAllVariablesToTypst(options); + const fontVar = vars.find(v => v.name === 'font'); + + expect(fontVar).toBeDefined(); + expect(fontVar?.value).toBe('Arial'); + }); + + it('should map headingFont to heading_font', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { headingFont: 'Helvetica' }, + }; + + const vars = mapper.mapAllVariablesToTypst(options); + const headingVar = vars.find(v => v.name === 'heading_font'); + + expect(headingVar).toBeDefined(); + expect(headingVar?.value).toBe('Helvetica'); + }); + + it('should map bodyFontSize to fontsize with pt unit', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { bodyFontSize: 12 }, + }; + + const vars = mapper.mapAllVariablesToTypst(options); + const sizeVar = vars.find(v => v.name === 'fontsize'); + + expect(sizeVar).toBeDefined(); + expect(sizeVar?.value).toBe('12pt'); + }); + + it('should map pageSize to paper with Typst value', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { pageSize: 'a4' }, + }; + + const vars = mapper.mapAllVariablesToTypst(options); + const paperVar = vars.find(v => v.name === 'paper'); + + expect(paperVar).toBeDefined(); + expect(paperVar?.value).toBe('a4'); + }); + + it('should map margin variables with cm unit', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { + marginTop: 2, + marginBottom: 3, + marginLeft: 2.5, + marginRight: 2.5, + }, + }; + + const vars = mapper.mapAllVariablesToTypst(options); + + expect(vars.find(v => v.name === 'margin_top')?.value).toBe('2cm'); + expect(vars.find(v => v.name === 'margin_bottom')?.value).toBe('3cm'); + expect(vars.find(v => v.name === 'margin_left')?.value).toBe('2.5cm'); + expect(vars.find(v => v.name === 'margin_right')?.value).toBe('2.5cm'); + }); + + it('should preserve unmapped variables', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { + orientation: 'landscape', + flipped: true, + customVar: 'value', + }, + }; + + const vars = mapper.mapAllVariablesToTypst(options); + + expect(vars.find(v => v.name === 'orientation')?.value).toBe('landscape'); + expect(vars.find(v => v.name === 'flipped')?.value).toBe('true'); + expect(vars.find(v => v.name === 'customVar')?.value).toBe('value'); + }); + }); + + describe('mapPluginSettingsVariables', () => { + it('should add typography variables from settings', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { variables: {} }; + + const vars = mapper.mapAllVariablesToTypst(options); + + expect(vars.find(v => v.name === 'font')?.value).toBe('Georgia'); + expect(vars.find(v => v.name === 'heading_font')?.value).toBe('Helvetica'); + expect(vars.find(v => v.name === 'fontsize')?.value).toBe('11pt'); + }); + + it('should not override export config variables', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { bodyFont: 'Arial' }, + }; + + const vars = mapper.mapAllVariablesToTypst(options); + const fontVars = vars.filter(v => v.name === 'font'); + + // Should only have one font variable from export config + expect(fontVars).toHaveLength(1); + expect(fontVars[0].value).toBe('Arial'); + }); + + it('should add page setup variables from settings', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { variables: {} }; + + const vars = mapper.mapAllVariablesToTypst(options); + + expect(vars.find(v => v.name === 'paper')?.value).toBe('a4'); + expect(vars.find(v => v.name === 'orientation')?.value).toBe('portrait'); + }); + }); + + describe('convertVariablesToPandocArgs', () => { + it('should convert variables to pandoc -V arguments', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const variables = [ + { name: 'font', value: 'Arial' }, + { name: 'fontsize', value: '12pt' }, + { name: 'paper', value: 'a4' }, + ]; + + const args = mapper.convertVariablesToPandocArgs(variables); + + expect(args).toEqual([ + '-V', 'font=Arial', + '-V', 'fontsize=12pt', + '-V', 'paper=a4', + ]); + }); + + it('should handle empty variables array', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const args = mapper.convertVariablesToPandocArgs([]); + + expect(args).toEqual([]); + }); + }); + + describe('getExportConfigVariableNames', () => { + it('should return set of variable names including mappings', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { + variables: { + bodyFont: 'Arial', + pageSize: 'a4', + marginTop: 2, + }, + }; + + const names = mapper.getExportConfigVariableNames(options); + + expect(names.has('bodyFont')).toBe(true); + expect(names.has('font')).toBe(true); + expect(names.has('pageSize')).toBe(true); + expect(names.has('paper')).toBe(true); + expect(names.has('marginTop')).toBe(true); + expect(names.has('margin_top')).toBe(true); + }); + + it('should handle empty variables', () => { + const mapper = new TypstVariableMapper(createMockPlugin()); + const options: PandocOptions = { variables: {} }; + + const names = mapper.getExportConfigVariableNames(options); + + expect(names.size).toBe(0); + }); + }); +}); diff --git a/tests/__mocks__/obsidian.ts b/tests/__mocks__/obsidian.ts new file mode 100644 index 0000000..37ab1e5 --- /dev/null +++ b/tests/__mocks__/obsidian.ts @@ -0,0 +1,65 @@ +// Mock Obsidian API for testing +import { vi } from 'vitest'; + +export class Notice { + constructor(message: string) {} +} + +export class Plugin { + app: any; + manifest: any; +} + +export class PluginSettingTab { + constructor(app: any, plugin: any) {} +} + +export class Setting { + constructor(containerEl: HTMLElement) {} + setName(name: string): this { return this; } + setDesc(desc: string): this { return this; } + addText(cb: any): this { return this; } + addToggle(cb: any): this { return this; } + addDropdown(cb: any): this { return this; } +} + +export class Modal { + constructor(app: any) {} + open(): void {} + close(): void {} +} + +export class FuzzySuggestModal { + constructor(app: any) {} +} + +export class TFile { + path = ''; + basename = ''; + extension = ''; +} + +export class TFolder { + path = ''; + name = ''; +} + +export function normalizePath(path: string): string { + return path.replace(/\\/g, '/'); +} + +export const requestUrl = vi.fn(); + +// Type exports for compatibility +export interface App { + vault: { + adapter: { + exists: (path: string) => Promise; + mkdir: (path: string) => Promise; + remove: (path: string) => Promise; + list: (path: string) => Promise<{ files: string[]; folders: string[] }>; + read: (path: string) => Promise; + write: (path: string, data: string) => Promise; + }; + }; +} diff --git a/tests/basicCoverage.test.ts b/tests/basicCoverage.test.ts new file mode 100644 index 0000000..2d1ea7c --- /dev/null +++ b/tests/basicCoverage.test.ts @@ -0,0 +1,74 @@ +/** + * Basic coverage tests for simpler modules + * These tests ensure basic functionality and increase overall coverage + */ +import { describe, it, expect } from 'vitest'; + +// Import type files and constants +import { FALLBACK_FONTS, PLUGIN_DIRS, EXPORT_CONSTANTS, DEPENDENCY_CONSTANTS } from '../src/core/constants'; +import { ExportFormat } from '../src/core/settings'; + +// Import utilities +import { SUPPORTED_PAPER_SIZES, DEFAULT_PAPER_SIZE, mapToTypstPaperSize, isSupportedPaperSize } from '../src/utils/paperSizeMapper'; + +describe('Constants and Types Coverage', () => { + describe('FALLBACK_FONTS', () => { + it('should have defined fallback fonts', () => { + expect(FALLBACK_FONTS.length).toBeGreaterThan(0); + expect(FALLBACK_FONTS).toContain('Times New Roman'); + }); + }); + + describe('PLUGIN_DIRS', () => { + it('should have temp directory names', () => { + expect(PLUGIN_DIRS.TEMP_IMAGES).toBe('temp-images'); + expect(PLUGIN_DIRS.TEMP_PANDOC).toBe('temp-pandoc'); + }); + }); + + describe('EXPORT_CONSTANTS', () => { + it('should have timeout constants', () => { + expect(EXPORT_CONSTANTS.DEFAULT_TIMEOUT).toBe(120000); + expect(EXPORT_CONSTANTS.NOTICE_DURATION.SHORT).toBe(5000); + }); + }); + + describe('DEPENDENCY_CONSTANTS', () => { + it('should have default executables', () => { + expect(DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc).toBe('pandoc'); + expect(DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst).toBe('typst'); + }); + + it('should have common paths', () => { + expect(DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE).toContain('/.local/bin'); + expect(DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE).toContain('/usr/local/bin'); + }); + }); + + describe('ExportFormat enum', () => { + it('should have standard and single-page formats', () => { + expect(ExportFormat.Standard).toBe('standard'); + expect(ExportFormat.SinglePage).toBe('single-page'); + }); + }); + + describe('Paper size utilities', () => { + it('should have multiple paper sizes', () => { + expect(SUPPORTED_PAPER_SIZES.length).toBeGreaterThan(5); + }); + + it('should map known sizes', () => { + expect(mapToTypstPaperSize('a4')).toBe('a4'); + expect(mapToTypstPaperSize('us-letter')).toBe('us-letter'); + }); + + it('should validate paper sizes', () => { + expect(isSupportedPaperSize('a4')).toBe(true); + expect(isSupportedPaperSize('invalid')).toBe(false); + }); + + it('should have a default paper size', () => { + expect(DEFAULT_PAPER_SIZE).toBe('a4'); + }); + }); +}); diff --git a/tests/converterTypes.test.ts b/tests/converterTypes.test.ts new file mode 100644 index 0000000..8997e79 --- /dev/null +++ b/tests/converterTypes.test.ts @@ -0,0 +1,10 @@ +import { describe, it, expect } from 'vitest'; +import { ExportFormat } from '../src/core/settings'; + +// Type definition file - basic import test to ensure types compile +describe('converterTypes', () => { + it('should export ExportFormat enum', () => { + expect(ExportFormat.Standard).toBe('standard'); + expect(ExportFormat.SinglePage).toBe('single-page'); + }); +}); diff --git a/tests/paperSizeMapper.test.ts b/tests/paperSizeMapper.test.ts new file mode 100644 index 0000000..98f6a55 --- /dev/null +++ b/tests/paperSizeMapper.test.ts @@ -0,0 +1,175 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { + SUPPORTED_PAPER_SIZES, + DEFAULT_PAPER_SIZE, + mapToTypstPaperSize, + getValidTypstPaperSizes, + isSupportedPaperSize, +} from '../src/utils/paperSizeMapper'; + +describe('paperSizeMapper', () => { + describe('SUPPORTED_PAPER_SIZES', () => { + it('should have all required paper sizes', () => { + expect(SUPPORTED_PAPER_SIZES).toHaveLength(8); + + const keys = SUPPORTED_PAPER_SIZES.map(size => size.key); + expect(keys).toContain('a3'); + expect(keys).toContain('a4'); + expect(keys).toContain('a5'); + expect(keys).toContain('a6'); + expect(keys).toContain('eu-business-card'); + expect(keys).toContain('us-letter'); + expect(keys).toContain('us-legal'); + expect(keys).toContain('us-business-card'); + }); + + it('should have correct structure for each paper size', () => { + SUPPORTED_PAPER_SIZES.forEach(size => { + expect(size).toHaveProperty('key'); + expect(size).toHaveProperty('displayName'); + expect(size).toHaveProperty('typstValue'); + + expect(typeof size.key).toBe('string'); + expect(typeof size.displayName).toBe('string'); + expect(typeof size.typstValue).toBe('string'); + + expect(size.key.length).toBeGreaterThan(0); + expect(size.displayName.length).toBeGreaterThan(0); + expect(size.typstValue.length).toBeGreaterThan(0); + }); + }); + + it('should have unique keys', () => { + const keys = SUPPORTED_PAPER_SIZES.map(size => size.key); + const uniqueKeys = new Set(keys); + expect(uniqueKeys.size).toBe(keys.length); + }); + + it('should have display names with dimensions', () => { + SUPPORTED_PAPER_SIZES.forEach(size => { + // Display names should contain either 'mm' or 'in' + expect(size.displayName).toMatch(/\d+\s*×\s*\d+\s*(mm|in)/); + }); + }); + }); + + describe('DEFAULT_PAPER_SIZE', () => { + it('should be a4', () => { + expect(DEFAULT_PAPER_SIZE).toBe('a4'); + }); + + it('should be a valid supported paper size', () => { + expect(isSupportedPaperSize(DEFAULT_PAPER_SIZE)).toBe(true); + }); + }); + + describe('mapToTypstPaperSize', () => { + it('should map supported paper sizes correctly', () => { + expect(mapToTypstPaperSize('a3')).toBe('a3'); + expect(mapToTypstPaperSize('a4')).toBe('a4'); + expect(mapToTypstPaperSize('a5')).toBe('a5'); + expect(mapToTypstPaperSize('a6')).toBe('a6'); + expect(mapToTypstPaperSize('us-letter')).toBe('us-letter'); + expect(mapToTypstPaperSize('us-legal')).toBe('us-legal'); + expect(mapToTypstPaperSize('eu-business-card')).toBe('eu-business-card'); + expect(mapToTypstPaperSize('us-business-card')).toBe('us-business-card'); + }); + + it('should return default for unsupported paper sizes', () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + expect(mapToTypstPaperSize('invalid-size')).toBe('a4'); + expect(mapToTypstPaperSize('unknown')).toBe('a4'); + expect(mapToTypstPaperSize('')).toBe('a4'); + + expect(consoleWarnSpy).toHaveBeenCalledTimes(3); + consoleWarnSpy.mockRestore(); + }); + + it('should log warning for unsupported sizes', () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + mapToTypstPaperSize('invalid-size'); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining('Unknown paper size: invalid-size') + ); + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining('Using default: a4') + ); + + consoleWarnSpy.mockRestore(); + }); + + it('should handle case-sensitive keys', () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + // Keys are case-sensitive + expect(mapToTypstPaperSize('A4')).toBe('a4'); // Should fall back to default + expect(consoleWarnSpy).toHaveBeenCalled(); + + consoleWarnSpy.mockRestore(); + }); + }); + + describe('getValidTypstPaperSizes', () => { + it('should return all Typst paper size values', () => { + const validSizes = getValidTypstPaperSizes(); + + expect(validSizes).toHaveLength(8); + expect(validSizes).toContain('a3'); + expect(validSizes).toContain('a4'); + expect(validSizes).toContain('a5'); + expect(validSizes).toContain('a6'); + expect(validSizes).toContain('eu-business-card'); + expect(validSizes).toContain('us-letter'); + expect(validSizes).toContain('us-legal'); + expect(validSizes).toContain('us-business-card'); + }); + + it('should return a new array each time', () => { + const sizes1 = getValidTypstPaperSizes(); + const sizes2 = getValidTypstPaperSizes(); + + // Should return different array instances + expect(sizes1).not.toBe(sizes2); + + // But with same content + expect(sizes1).toEqual(sizes2); + }); + + it('should not include duplicate values', () => { + const validSizes = getValidTypstPaperSizes(); + const uniqueSizes = new Set(validSizes); + + expect(uniqueSizes.size).toBe(validSizes.length); + }); + }); + + describe('isSupportedPaperSize', () => { + it('should return true for supported sizes', () => { + expect(isSupportedPaperSize('a3')).toBe(true); + expect(isSupportedPaperSize('a4')).toBe(true); + expect(isSupportedPaperSize('a5')).toBe(true); + expect(isSupportedPaperSize('a6')).toBe(true); + expect(isSupportedPaperSize('us-letter')).toBe(true); + expect(isSupportedPaperSize('us-legal')).toBe(true); + expect(isSupportedPaperSize('eu-business-card')).toBe(true); + expect(isSupportedPaperSize('us-business-card')).toBe(true); + }); + + it('should return false for unsupported sizes', () => { + expect(isSupportedPaperSize('invalid')).toBe(false); + expect(isSupportedPaperSize('unknown')).toBe(false); + expect(isSupportedPaperSize('')).toBe(false); + expect(isSupportedPaperSize('A4')).toBe(false); // Case-sensitive + expect(isSupportedPaperSize('letter')).toBe(false); // Missing 'us-' prefix + }); + + it('should handle edge cases', () => { + expect(isSupportedPaperSize(null as any)).toBe(false); + expect(isSupportedPaperSize(undefined as any)).toBe(false); + expect(isSupportedPaperSize(123 as any)).toBe(false); + }); + }); +}); diff --git a/tests/setup.ts b/tests/setup.ts new file mode 100644 index 0000000..0b67a4e --- /dev/null +++ b/tests/setup.ts @@ -0,0 +1,5 @@ +// Mock process.platform for cross-platform testing +Object.defineProperty(process, 'platform', { + value: 'darwin', + writable: true, +}); diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..12fc0ea --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,39 @@ +import { defineConfig } from 'vitest/config'; +import path from 'path'; + +export default defineConfig({ + test: { + globals: true, + environment: 'happy-dom', + setupFiles: ['./tests/setup.ts'], + coverage: { + provider: 'v8', + reporter: ['text', 'json', 'html', 'lcov'], + include: ['src/**/*.ts'], + exclude: [ + 'node_modules/**', + 'tests/**', + '*.config.*', + '**/*.d.ts', + '**/*.test.ts', + 'main.ts', // Entry point, tested through integration + 'version-bump.mjs', + 'scripts/**', + ], + all: true, // Include all source files in coverage report + thresholds: { + lines: 80, + functions: 80, + branches: 80, + statements: 80, + }, + }, + include: ['tests/**/*.test.ts'], + }, + resolve: { + alias: { + '@': path.resolve(__dirname, './src'), + 'obsidian': path.resolve(__dirname, './tests/__mocks__/obsidian.ts'), + }, + }, +});