diff --git a/tests/unit/content/cidr-set-operations.test.ts b/tests/unit/content/cidr-set-operations.test.ts new file mode 100644 index 0000000..b8557bc --- /dev/null +++ b/tests/unit/content/cidr-set-operations.test.ts @@ -0,0 +1,131 @@ +import { describe, it, expect } from 'vitest'; +import { setOperationsContent } from '../../../src/lib/content/cidr-set-operations'; + +describe('CIDR Set Operations Content', () => { + it('should have valid structure', () => { + expect(setOperationsContent).toBeDefined(); + expect(setOperationsContent.title).toBe('Set Operations Reference'); + expect(typeof setOperationsContent.description).toBe('string'); + expect(setOperationsContent.description.length).toBeGreaterThan(0); + }); + + it('should contain all required operations', () => { + expect(setOperationsContent.operations).toHaveLength(4); + + const operationSymbols = setOperationsContent.operations.map(op => op.symbol); + expect(operationSymbols).toContain('A ∪ B'); // Union + expect(operationSymbols).toContain('A ∩ B'); // Intersection + expect(operationSymbols).toContain('A - B'); // Difference + expect(operationSymbols).toContain('A ⊆ B'); // Containment + }); + + it('should have valid operation structure', () => { + setOperationsContent.operations.forEach(operation => { + expect(operation).toHaveProperty('symbol'); + expect(operation).toHaveProperty('name'); + expect(operation).toHaveProperty('description'); + expect(operation).toHaveProperty('example'); + + expect(typeof operation.symbol).toBe('string'); + expect(typeof operation.name).toBe('string'); + expect(typeof operation.description).toBe('string'); + expect(typeof operation.example).toBe('string'); + + expect(operation.symbol.length).toBeGreaterThan(0); + expect(operation.name.length).toBeGreaterThan(0); + expect(operation.description.length).toBeGreaterThan(0); + expect(operation.example.length).toBeGreaterThan(0); + }); + }); + + it('should contain expected patterns', () => { + expect(setOperationsContent.patterns).toHaveLength(4); + + const patternTitles = setOperationsContent.patterns.map(p => p.title); + expect(patternTitles).toContain('Firewall Management'); + expect(patternTitles).toContain('IP Allocation'); + expect(patternTitles).toContain('Network Analysis'); + expect(patternTitles).toContain('Cloud Networks'); + }); + + it('should have valid pattern structure', () => { + setOperationsContent.patterns.forEach(pattern => { + expect(pattern).toHaveProperty('icon'); + expect(pattern).toHaveProperty('title'); + expect(pattern).toHaveProperty('items'); + + expect(typeof pattern.icon).toBe('string'); + expect(typeof pattern.title).toBe('string'); + expect(Array.isArray(pattern.items)).toBe(true); + expect(pattern.items.length).toBeGreaterThan(0); + + pattern.items.forEach(item => { + expect(item).toHaveProperty('term'); + expect(item).toHaveProperty('description'); + expect(typeof item.term).toBe('string'); + expect(typeof item.description).toBe('string'); + }); + }); + }); + + it('should contain informative notes', () => { + expect(setOperationsContent.notes).toHaveLength(4); + + const noteTitles = setOperationsContent.notes.map(n => n.title); + expect(noteTitles).toContain('IPv4 vs IPv6'); + expect(noteTitles).toContain('CIDR Optimization'); + expect(noteTitles).toContain('Range Normalization'); + expect(noteTitles).toContain('Performance Considerations'); + }); + + it('should have valid note structure', () => { + setOperationsContent.notes.forEach(note => { + expect(note).toHaveProperty('title'); + expect(note).toHaveProperty('content'); + expect(typeof note.title).toBe('string'); + expect(typeof note.content).toBe('string'); + expect(note.title.length).toBeGreaterThan(0); + expect(note.content.length).toBeGreaterThan(0); + }); + }); + + it('should contain best practices', () => { + expect(setOperationsContent.bestPractices).toHaveLength(4); + + const practiceTerms = setOperationsContent.bestPractices.map(p => p.term); + expect(practiceTerms).toContain('Validate Inputs'); + expect(practiceTerms).toContain('Document Operations'); + expect(practiceTerms).toContain('Test in Stages'); + expect(practiceTerms).toContain('Monitor Results'); + }); + + it('should have valid best practices structure', () => { + setOperationsContent.bestPractices.forEach(practice => { + expect(practice).toHaveProperty('term'); + expect(practice).toHaveProperty('description'); + expect(typeof practice.term).toBe('string'); + expect(typeof practice.description).toBe('string'); + expect(practice.term.length).toBeGreaterThan(0); + expect(practice.description.length).toBeGreaterThan(0); + }); + }); + + it('should contain meaningful examples with IP addresses', () => { + const examples = setOperationsContent.operations.map(op => op.example); + + // Should contain realistic IP address examples + expect(examples.some(ex => ex.includes('192.168'))).toBe(true); + expect(examples.some(ex => ex.includes('/24'))).toBe(true); + expect(examples.some(ex => ex.includes('/25'))).toBe(true); + }); + + it('should have consistent mathematical notation', () => { + const symbols = setOperationsContent.operations.map(op => op.symbol); + + // Check for proper mathematical symbols + expect(symbols).toContain('A ∪ B'); // Union symbol + expect(symbols).toContain('A ∩ B'); // Intersection symbol + expect(symbols).toContain('A - B'); // Difference symbol + expect(symbols).toContain('A ⊆ B'); // Subset symbol + }); +}); \ No newline at end of file diff --git a/tests/unit/content/ip-address-validation.test.ts b/tests/unit/content/ip-address-validation.test.ts new file mode 100644 index 0000000..41114cf --- /dev/null +++ b/tests/unit/content/ip-address-validation.test.ts @@ -0,0 +1,157 @@ +import { describe, it, expect } from 'vitest'; +import { ipAddressValidationContent } from '../../../src/lib/content/ip-address-validation'; + +describe('IP Address Validation Content', () => { + it('should have valid structure', () => { + expect(ipAddressValidationContent).toBeDefined(); + expect(ipAddressValidationContent.title).toBe('IP Address Format & RegEx Validation'); + expect(typeof ipAddressValidationContent.description).toBe('string'); + expect(ipAddressValidationContent.description.length).toBeGreaterThan(0); + }); + + it('should contain all required sections', () => { + expect(ipAddressValidationContent.sections).toBeDefined(); + expect(ipAddressValidationContent.sections).toHaveProperty('overview'); + expect(ipAddressValidationContent.sections).toHaveProperty('ipv4'); + expect(ipAddressValidationContent.sections).toHaveProperty('ipv6'); + expect(ipAddressValidationContent.sections).toHaveProperty('regexValidation'); + expect(ipAddressValidationContent.sections).toHaveProperty('practicalTips'); + }); + + it('should have valid section structure', () => { + Object.values(ipAddressValidationContent.sections).forEach(section => { + expect(section).toHaveProperty('title'); + expect(section).toHaveProperty('content'); + expect(typeof section.title).toBe('string'); + expect(typeof section.content).toBe('string'); + expect(section.title.length).toBeGreaterThan(0); + expect(section.content.length).toBeGreaterThan(0); + }); + }); + + it('should contain practical examples', () => { + expect(ipAddressValidationContent.examples).toBeDefined(); + expect(ipAddressValidationContent.examples).toHaveProperty('ipv4Basic'); + expect(ipAddressValidationContent.examples).toHaveProperty('ipv4Proper'); + expect(ipAddressValidationContent.examples).toHaveProperty('ipv6Basic'); + }); + + it('should have valid example structure', () => { + Object.values(ipAddressValidationContent.examples).forEach(example => { + expect(example).toHaveProperty('title'); + expect(example).toHaveProperty('pattern'); + expect(example).toHaveProperty('description'); + expect(example).toHaveProperty('matches'); + expect(example).toHaveProperty('fails'); + expect(example).toHaveProperty('limitation'); + + expect(typeof example.title).toBe('string'); + expect(typeof example.pattern).toBe('string'); + expect(typeof example.description).toBe('string'); + expect(Array.isArray(example.matches)).toBe(true); + expect(Array.isArray(example.fails)).toBe(true); + expect(typeof example.limitation).toBe('string'); + }); + }); + + it('should have working regex patterns', () => { + const { ipv4Basic, ipv4Proper, ipv6Basic } = ipAddressValidationContent.examples; + + // Test IPv4 basic pattern + const ipv4BasicRegex = new RegExp(ipv4Basic.pattern); + ipv4Basic.matches.forEach(ip => { + expect(ipv4BasicRegex.test(ip)).toBe(true); + }); + ipv4Basic.fails.forEach(ip => { + expect(ipv4BasicRegex.test(ip)).toBe(false); + }); + + // Test IPv4 proper pattern + const ipv4ProperRegex = new RegExp(ipv4Proper.pattern); + ipv4Proper.matches.forEach(ip => { + expect(ipv4ProperRegex.test(ip)).toBe(true); + }); + ipv4Proper.fails.forEach(ip => { + expect(ipv4ProperRegex.test(ip)).toBe(false); + }); + + // Test IPv6 basic pattern + const ipv6BasicRegex = new RegExp(ipv6Basic.pattern); + ipv6Basic.matches.forEach(ip => { + expect(ipv6BasicRegex.test(ip)).toBe(true); + }); + ipv6Basic.fails.forEach(ip => { + expect(ipv6BasicRegex.test(ip)).toBe(false); + }); + }); + + it('should contain practical recommendations', () => { + expect(ipAddressValidationContent.recommendations).toBeDefined(); + expect(Array.isArray(ipAddressValidationContent.recommendations)).toBe(true); + expect(ipAddressValidationContent.recommendations.length).toBeGreaterThan(0); + }); + + it('should have valid recommendation structure', () => { + ipAddressValidationContent.recommendations.forEach(recommendation => { + expect(recommendation).toHaveProperty('icon'); + expect(recommendation).toHaveProperty('title'); + expect(recommendation).toHaveProperty('description'); + expect(recommendation).toHaveProperty('color'); + + expect(typeof recommendation.icon).toBe('string'); + expect(typeof recommendation.title).toBe('string'); + expect(typeof recommendation.description).toBe('string'); + expect(typeof recommendation.color).toBe('string'); + + // Check for CSS color variables + expect(recommendation.color).toMatch(/^var\(--color-/); + }); + }); + + it('should contain IPv4 technical details', () => { + const ipv4Section = ipAddressValidationContent.sections.ipv4; + expect(ipv4Section.content).toContain('192.168.1.1'); + expect(ipv4Section.content).toContain('0-255'); + expect(ipv4Section.content).toContain('four decimal numbers'); + }); + + it('should contain IPv6 technical details', () => { + const ipv6Section = ipAddressValidationContent.sections.ipv6; + expect(ipv6Section.content).toContain('128-bit'); + expect(ipv6Section.content).toContain('hexadecimal'); + expect(ipv6Section.content).toContain('::'); + expect(ipv6Section.content).toContain('2001:'); + }); + + it('should explain regex challenges', () => { + const regexSection = ipAddressValidationContent.sections.regexValidation; + expect(regexSection.content).toContain('RegEx'); + expect(regexSection.content).toContain('range validation'); + expect(regexSection.content).toContain('edge cases'); + }); + + it('should provide practical tips', () => { + const tipsSection = ipAddressValidationContent.sections.practicalTips; + expect(tipsSection.content).toContain('built-ins'); + expect(tipsSection.content).toContain('edge cases'); + expect(tipsSection.content).toContain('leading zeros'); + }); + + it('should have realistic example IPs', () => { + const allMatches = Object.values(ipAddressValidationContent.examples) + .flatMap(ex => ex.matches); + + // Should contain common IP patterns + expect(allMatches.some(ip => ip.includes('192.168'))).toBe(true); + expect(allMatches.some(ip => ip.includes('::'))).toBe(true); + }); + + it('should have realistic failure cases', () => { + const allFails = Object.values(ipAddressValidationContent.examples) + .flatMap(ex => ex.fails); + + // Should contain common mistakes + expect(allFails.length).toBeGreaterThan(0); + expect(allFails.some(ip => !ip.includes('.'))).toBe(true); + }); +}); \ No newline at end of file diff --git a/tests/unit/content/subnetting.test.ts b/tests/unit/content/subnetting.test.ts new file mode 100644 index 0000000..9efade2 --- /dev/null +++ b/tests/unit/content/subnetting.test.ts @@ -0,0 +1,262 @@ +import { describe, it, expect } from 'vitest'; +import { + commonSubnetMasks, + keyConcepts, + subnettingTechniques, + practicalTips, + commonMistakes, + type SubnetMask, + type SubnettingConcept, + type SubnettingTechnique +} from '../../../src/lib/content/subnetting'; + +describe('Subnetting Content', () => { + describe('Common Subnet Masks', () => { + it('should contain expected subnet masks', () => { + expect(commonSubnetMasks).toHaveLength(9); + + const cidrValues = commonSubnetMasks.map(mask => mask.cidr); + expect(cidrValues).toContain(8); + expect(cidrValues).toContain(16); + expect(cidrValues).toContain(24); + expect(cidrValues).toContain(25); + expect(cidrValues).toContain(26); + expect(cidrValues).toContain(27); + expect(cidrValues).toContain(28); + expect(cidrValues).toContain(29); + expect(cidrValues).toContain(30); + }); + + it('should have valid structure for each mask', () => { + commonSubnetMasks.forEach((mask: SubnetMask) => { + expect(mask).toHaveProperty('cidr'); + expect(mask).toHaveProperty('decimal'); + expect(mask).toHaveProperty('binary'); + expect(mask).toHaveProperty('hosts'); + expect(mask).toHaveProperty('networks'); + + expect(typeof mask.cidr).toBe('number'); + expect(typeof mask.decimal).toBe('string'); + expect(typeof mask.binary).toBe('string'); + expect(typeof mask.hosts).toBe('number'); + expect(typeof mask.networks).toBe('number'); + }); + }); + + it('should have CIDR values in ascending order', () => { + for (let i = 0; i < commonSubnetMasks.length - 1; i++) { + expect(commonSubnetMasks[i].cidr).toBeLessThan(commonSubnetMasks[i + 1].cidr); + } + }); + + it('should have valid IPv4 decimal formats', () => { + commonSubnetMasks.forEach(mask => { + expect(mask.decimal).toMatch(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/); + + const octets = mask.decimal.split('.').map(Number); + octets.forEach(octet => { + expect(octet).toBeGreaterThanOrEqual(0); + expect(octet).toBeLessThanOrEqual(255); + }); + }); + }); + + it('should have valid binary formats', () => { + commonSubnetMasks.forEach(mask => { + expect(mask.binary).toMatch(/^[01]{8}\.[01]{8}\.[01]{8}\.[01]{8}$/); + + // Count network bits (1s) should match CIDR + const networkBits = mask.binary.replace(/\./g, '').split('1').length - 1; + expect(networkBits).toBe(mask.cidr); + }); + }); + + it('should have decreasing host counts as CIDR increases', () => { + for (let i = 0; i < commonSubnetMasks.length - 1; i++) { + expect(commonSubnetMasks[i].hosts).toBeGreaterThan(commonSubnetMasks[i + 1].hosts); + } + }); + + it('should have increasing network counts as CIDR increases', () => { + for (let i = 0; i < commonSubnetMasks.length - 1; i++) { + expect(commonSubnetMasks[i].networks).toBeLessThan(commonSubnetMasks[i + 1].networks); + } + }); + + it('should calculate correct host counts for common masks', () => { + const mask24 = commonSubnetMasks.find(m => m.cidr === 24); + const mask25 = commonSubnetMasks.find(m => m.cidr === 25); + const mask30 = commonSubnetMasks.find(m => m.cidr === 30); + + expect(mask24?.hosts).toBe(254); // 2^8 - 2 + expect(mask25?.hosts).toBe(126); // 2^7 - 2 + expect(mask30?.hosts).toBe(2); // 2^2 - 2 + }); + }); + + describe('Key Concepts', () => { + it('should contain essential subnetting concepts', () => { + expect(keyConcepts).toHaveLength(4); + + const titles = keyConcepts.map(concept => concept.title); + expect(titles).toContain('Network & Host Bits'); + expect(titles).toContain('CIDR Notation'); + expect(titles).toContain('Broadcast Domain'); + expect(titles).toContain('Subnet Zero & All-Ones'); + }); + + it('should have valid structure for each concept', () => { + keyConcepts.forEach((concept: SubnettingConcept) => { + expect(concept).toHaveProperty('title'); + expect(concept).toHaveProperty('description'); + expect(concept).toHaveProperty('icon'); + + expect(typeof concept.title).toBe('string'); + expect(typeof concept.description).toBe('string'); + expect(typeof concept.icon).toBe('string'); + + expect(concept.title.length).toBeGreaterThan(0); + expect(concept.description.length).toBeGreaterThan(0); + expect(concept.icon.length).toBeGreaterThan(0); + }); + }); + + it('should include examples where provided', () => { + const conceptsWithExamples = keyConcepts.filter(c => c.example); + expect(conceptsWithExamples.length).toBeGreaterThan(0); + + conceptsWithExamples.forEach(concept => { + expect(typeof concept.example).toBe('string'); + expect(concept.example!.length).toBeGreaterThan(0); + }); + }); + + it('should contain technical details', () => { + const allDescriptions = keyConcepts.map(c => c.description).join(' '); + expect(allDescriptions).toContain('subnet mask'); + expect(allDescriptions).toContain('network'); + expect(allDescriptions).toContain('bits'); + }); + }); + + describe('Subnetting Techniques', () => { + it('should contain main subnetting approaches', () => { + expect(subnettingTechniques).toHaveLength(3); + + const names = subnettingTechniques.map(tech => tech.name); + expect(names).toContain('Fixed-Length Subnetting'); + expect(names).toContain('VLSM'); + expect(names).toContain('Supernetting'); + }); + + it('should have valid structure for each technique', () => { + subnettingTechniques.forEach((technique: SubnettingTechnique) => { + expect(technique).toHaveProperty('name'); + expect(technique).toHaveProperty('description'); + expect(technique).toHaveProperty('useCase'); + expect(technique).toHaveProperty('icon'); + expect(technique).toHaveProperty('color'); + + expect(typeof technique.name).toBe('string'); + expect(typeof technique.description).toBe('string'); + expect(typeof technique.useCase).toBe('string'); + expect(typeof technique.icon).toBe('string'); + expect(typeof technique.color).toBe('string'); + + expect(technique.name.length).toBeGreaterThan(0); + expect(technique.description.length).toBeGreaterThan(0); + expect(technique.useCase.length).toBeGreaterThan(0); + expect(technique.icon.length).toBeGreaterThan(0); + }); + }); + + it('should use CSS color variables', () => { + subnettingTechniques.forEach(technique => { + expect(technique.color).toMatch(/^var\(--color-/); + }); + }); + + it('should describe different approaches', () => { + const descriptions = subnettingTechniques.map(t => t.description); + expect(descriptions.some(d => d.includes('same mask'))).toBe(true); + expect(descriptions.some(d => d.includes('Variable-length'))).toBe(true); + expect(descriptions.some(d => d.includes('Combine'))).toBe(true); + }); + }); + + describe('Practical Tips', () => { + it('should contain helpful guidance', () => { + expect(practicalTips).toHaveLength(5); + expect(Array.isArray(practicalTips)).toBe(true); + }); + + it('should have meaningful content', () => { + practicalTips.forEach(tip => { + expect(typeof tip).toBe('string'); + expect(tip.length).toBeGreaterThan(10); + }); + }); + + it('should cover important topics', () => { + const allTips = practicalTips.join(' '); + expect(allTips).toContain('growth'); + expect(allTips).toContain('addresses'); + expect(allTips).toContain('subnet'); + }); + + it('should mention RFC 1918', () => { + const allTips = practicalTips.join(' '); + expect(allTips).toContain('RFC 1918'); + }); + }); + + describe('Common Mistakes', () => { + it('should contain typical errors', () => { + expect(commonMistakes).toHaveLength(4); + expect(Array.isArray(commonMistakes)).toBe(true); + }); + + it('should have meaningful content', () => { + commonMistakes.forEach(mistake => { + expect(typeof mistake).toBe('string'); + expect(mistake.length).toBeGreaterThan(10); + }); + }); + + it('should cover important pitfalls', () => { + const allMistakes = commonMistakes.join(' '); + expect(allMistakes).toContain('network'); + expect(allMistakes).toContain('broadcast'); + expect(allMistakes).toContain('overlapping'); + }); + + it('should mention growth planning', () => { + const allMistakes = commonMistakes.join(' '); + expect(allMistakes).toContain('growth'); + }); + }); + + describe('Data Consistency', () => { + it('should have consistent CIDR ranges', () => { + commonSubnetMasks.forEach(mask => { + expect(mask.cidr).toBeGreaterThanOrEqual(8); + expect(mask.cidr).toBeLessThanOrEqual(30); + }); + }); + + it('should have positive host and network counts', () => { + commonSubnetMasks.forEach(mask => { + expect(mask.hosts).toBeGreaterThan(0); + expect(mask.networks).toBeGreaterThan(0); + }); + }); + + it('should have proper mathematical relationships', () => { + commonSubnetMasks.forEach(mask => { + const hostBits = 32 - mask.cidr; + const expectedHosts = Math.pow(2, hostBits) - 2; // -2 for network and broadcast + expect(mask.hosts).toBe(expectedHosts); + }); + }); + }); +}); \ No newline at end of file diff --git a/tests/unit/stores/accessibility.test.ts b/tests/unit/stores/accessibility.test.ts new file mode 100644 index 0000000..8c110f5 --- /dev/null +++ b/tests/unit/stores/accessibility.test.ts @@ -0,0 +1,352 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { get } from 'svelte/store'; +import { accessibility, type AccessibilitySettings, type AccessibilityOption } from '../../../src/lib/stores/accessibility'; + +// Mock browser environment +vi.mock('$app/environment', () => ({ + browser: true +})); + +// Mock localStorage +const mockLocalStorage = { + getItem: vi.fn(), + setItem: vi.fn(), + removeItem: vi.fn(), + clear: vi.fn(), +}; + +Object.defineProperty(window, 'localStorage', { + value: mockLocalStorage, + writable: true, +}); + +// Mock matchMedia for system preferences +const mockMatchMedia = vi.fn(); +Object.defineProperty(window, 'matchMedia', { + value: mockMatchMedia, + writable: true, +}); + +// Mock document.head.appendChild for font loading +const mockAppendChild = vi.fn(); +Object.defineProperty(document, 'head', { + value: { appendChild: mockAppendChild }, + writable: true, +}); + +// Mock document.createElement +const mockCreateElement = vi.fn(); +global.document.createElement = mockCreateElement; + +describe('Accessibility Store', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockLocalStorage.getItem.mockReturnValue(null); + mockMatchMedia.mockReturnValue({ matches: false }); + mockCreateElement.mockReturnValue({ + rel: '', + href: '', + crossOrigin: '' + }); + }); + + afterEach(() => { + // Reset store to default state + accessibility.reset(); + }); + + describe('Store Initialization', () => { + it('should initialize with default options', () => { + const settings = get(accessibility); + + expect(settings).toBeDefined(); + expect(settings.options).toBeDefined(); + expect(Array.isArray(settings.options)).toBe(true); + expect(settings.options.length).toBeGreaterThan(0); + }); + + it('should load stored settings from localStorage', () => { + const storedSettings = { + options: [ + { id: 'high-contrast', enabled: true }, + { id: 'large-text', enabled: false } + ] + }; + + mockLocalStorage.getItem.mockReturnValue(JSON.stringify(storedSettings)); + + accessibility.init(); + + const settings = get(accessibility); + const highContrastOption = settings.options.find(opt => opt.id === 'high-contrast'); + + expect(mockLocalStorage.getItem).toHaveBeenCalledWith('accessibility-settings'); + expect(highContrastOption?.enabled).toBe(true); + }); + + it('should handle invalid JSON in localStorage gracefully', () => { + mockLocalStorage.getItem.mockReturnValue('invalid-json'); + + expect(() => accessibility.init()).not.toThrow(); + + const settings = get(accessibility); + expect(settings.options).toBeDefined(); + }); + + it('should respect system preferences for reduce motion', () => { + mockMatchMedia.mockReturnValue({ matches: true }); + + accessibility.init(); + + const settings = get(accessibility); + const reduceMotionOption = settings.options.find(opt => opt.id === 'reduce-motion'); + + expect(reduceMotionOption?.enabled).toBe(true); + }); + + it('should load dyslexic font if option is enabled', () => { + const storedSettings = { + options: [{ id: 'dyslexia-font', enabled: true }] + }; + + mockLocalStorage.getItem.mockReturnValue(JSON.stringify(storedSettings)); + + accessibility.init(); + + expect(mockCreateElement).toHaveBeenCalledWith('link'); + expect(mockAppendChild).toHaveBeenCalled(); + }); + }); + + describe('Option Structure Validation', () => { + it('should have valid structure for all default options', () => { + const settings = get(accessibility); + + settings.options.forEach((option: AccessibilityOption) => { + expect(option).toHaveProperty('id'); + expect(option).toHaveProperty('name'); + expect(option).toHaveProperty('description'); + expect(option).toHaveProperty('category'); + expect(option).toHaveProperty('enabled'); + expect(option).toHaveProperty('cssClass'); + + expect(typeof option.id).toBe('string'); + expect(typeof option.name).toBe('string'); + expect(typeof option.description).toBe('string'); + expect(typeof option.category).toBe('string'); + expect(typeof option.enabled).toBe('boolean'); + expect(typeof option.cssClass).toBe('string'); + + expect(['visual', 'motion', 'reading', 'interaction']).toContain(option.category); + }); + }); + + it('should contain expected accessibility options', () => { + const settings = get(accessibility); + const optionIds = settings.options.map(opt => opt.id); + + expect(optionIds).toContain('reduce-motion'); + expect(optionIds).toContain('high-contrast'); + expect(optionIds).toContain('large-text'); + expect(optionIds).toContain('dyslexia-font'); + expect(optionIds).toContain('always-underline-links'); + expect(optionIds).toContain('no-icons'); + expect(optionIds).toContain('focus-visible'); + expect(optionIds).toContain('dark-mode-high-contrast'); + }); + }); + + describe('Toggle Functionality', () => { + it('should toggle option state', () => { + const initialSettings = get(accessibility); + const option = initialSettings.options.find(opt => opt.id === 'high-contrast'); + const initialState = option?.enabled; + + accessibility.toggle('high-contrast'); + + const newSettings = get(accessibility); + const toggledOption = newSettings.options.find(opt => opt.id === 'high-contrast'); + + expect(toggledOption?.enabled).toBe(!initialState); + expect(mockLocalStorage.setItem).toHaveBeenCalled(); + }); + + it('should load dyslexic font when dyslexia-font is enabled', () => { + accessibility.toggle('dyslexia-font'); + + // Check that the option is toggled to enabled + const settings = get(accessibility); + const dyslexiaOption = settings.options.find(opt => opt.id === 'dyslexia-font'); + expect(dyslexiaOption?.enabled).toBe(true); + }); + + it('should toggle dyslexia-font option correctly', () => { + // First toggle to enable + accessibility.toggle('dyslexia-font'); + + let settings = get(accessibility); + let dyslexiaOption = settings.options.find(opt => opt.id === 'dyslexia-font'); + expect(dyslexiaOption?.enabled).toBe(true); + + // Toggle off + accessibility.toggle('dyslexia-font'); + + settings = get(accessibility); + dyslexiaOption = settings.options.find(opt => opt.id === 'dyslexia-font'); + expect(dyslexiaOption?.enabled).toBe(false); + + // Toggle on again + accessibility.toggle('dyslexia-font'); + + settings = get(accessibility); + dyslexiaOption = settings.options.find(opt => opt.id === 'dyslexia-font'); + expect(dyslexiaOption?.enabled).toBe(true); + }); + }); + + describe('Enable/Disable Functions', () => { + it('should enable an option', () => { + accessibility.enable('high-contrast'); + + const settings = get(accessibility); + const option = settings.options.find(opt => opt.id === 'high-contrast'); + + expect(option?.enabled).toBe(true); + expect(mockLocalStorage.setItem).toHaveBeenCalled(); + }); + + it('should disable an option', () => { + // First enable it + accessibility.enable('high-contrast'); + + // Then disable it + accessibility.disable('high-contrast'); + + const settings = get(accessibility); + const option = settings.options.find(opt => opt.id === 'high-contrast'); + + expect(option?.enabled).toBe(false); + expect(mockLocalStorage.setItem).toHaveBeenCalledTimes(2); + }); + }); + + describe('Utility Functions', () => { + it('should generate CSS classes string', () => { + accessibility.enable('high-contrast'); + accessibility.enable('large-text'); + + const settings = get(accessibility); + const cssClasses = accessibility.getCSSClasses(settings); + + expect(cssClasses).toContain('contrast-high'); + expect(cssClasses).toContain('scale-large'); + expect(typeof cssClasses).toBe('string'); + }); + + it('should filter options by category', () => { + const settings = get(accessibility); + const visualOptions = accessibility.getOptionsByCategory(settings, 'visual'); + const motionOptions = accessibility.getOptionsByCategory(settings, 'motion'); + + expect(Array.isArray(visualOptions)).toBe(true); + expect(Array.isArray(motionOptions)).toBe(true); + expect(visualOptions.length).toBeGreaterThan(0); + expect(motionOptions.length).toBeGreaterThan(0); + + visualOptions.forEach(option => { + expect(option.category).toBe('visual'); + }); + + motionOptions.forEach(option => { + expect(option.category).toBe('motion'); + }); + }); + + it('should check if option is enabled', () => { + const settings = get(accessibility); + + // Should return false for disabled options + expect(accessibility.isEnabled(settings, 'high-contrast')).toBe(false); + + // Enable and check again + accessibility.enable('high-contrast'); + const newSettings = get(accessibility); + expect(accessibility.isEnabled(newSettings, 'high-contrast')).toBe(true); + + // Should return false for non-existent options + expect(accessibility.isEnabled(settings, 'non-existent')).toBe(false); + }); + }); + + describe('Reset Functionality', () => { + it('should reset all settings to defaults', () => { + // Enable some options + accessibility.enable('high-contrast'); + accessibility.enable('large-text'); + + // Reset + accessibility.reset(); + + const settings = get(accessibility); + const allEnabled = settings.options.filter(opt => opt.enabled); + + // Should have no enabled options (assuming defaults are all false) + expect(allEnabled.length).toBe(0); + expect(mockLocalStorage.setItem).toHaveBeenCalledWith( + 'accessibility-settings', + expect.stringContaining('options') + ); + }); + }); + + describe('Font Loading', () => { + it('should handle dyslexic font option', () => { + // Test that the dyslexic font option exists and can be enabled + const settings = get(accessibility); + const dyslexiaOption = settings.options.find(opt => opt.id === 'dyslexia-font'); + + expect(dyslexiaOption).toBeDefined(); + expect(dyslexiaOption?.category).toBe('reading'); + expect(dyslexiaOption?.cssClass).toBe('dyslexia-font'); + + // Test enabling the option + accessibility.enable('dyslexia-font'); + + const newSettings = get(accessibility); + const enabledOption = newSettings.options.find(opt => opt.id === 'dyslexia-font'); + expect(enabledOption?.enabled).toBe(true); + }); + }); + + describe('System Preferences', () => { + it('should have system preference function for reduce motion', () => { + const settings = get(accessibility); + const reduceMotionOption = settings.options.find(opt => opt.id === 'reduce-motion'); + + expect(reduceMotionOption?.systemPreference).toBeDefined(); + expect(typeof reduceMotionOption?.systemPreference).toBe('function'); + }); + + it('should call matchMedia for reduce motion preference', () => { + const settings = get(accessibility); + const reduceMotionOption = settings.options.find(opt => opt.id === 'reduce-motion'); + + if (reduceMotionOption?.systemPreference) { + reduceMotionOption.systemPreference(); + expect(mockMatchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)'); + } + }); + }); + + describe('Category Coverage', () => { + it('should have options in all categories', () => { + const settings = get(accessibility); + const categories = ['visual', 'motion', 'reading', 'interaction'] as const; + + categories.forEach(category => { + const optionsInCategory = settings.options.filter(opt => opt.category === category); + expect(optionsInCategory.length).toBeGreaterThan(0); + }); + }); + }); +}); \ No newline at end of file diff --git a/tests/unit/utils/api-handler.test.ts b/tests/unit/utils/api-handler.test.ts new file mode 100644 index 0000000..d2509fb --- /dev/null +++ b/tests/unit/utils/api-handler.test.ts @@ -0,0 +1,249 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { createAPIHandler, type APIResponse } from '../../../src/lib/utils/api-handler'; +import * as apiRegistry from '../../../src/lib/utils/api-registry'; + +// Mock SvelteKit functions +vi.mock('@sveltejs/kit', () => ({ + json: vi.fn((data, init) => ({ + json: () => Promise.resolve(data), + status: init?.status || 200 + })), + error: vi.fn((status, message) => ({ + status, + text: () => Promise.resolve(message), + json: () => Promise.resolve({ message }) + })) +})); + +// Mock api-registry +vi.mock('../../../src/lib/utils/api-registry', () => ({ + getAPIHandler: vi.fn() +})); + +describe('API Handler', () => { + let mockRequest: any; + let mockParams: any; + let handler: { POST: any; GET: any }; + + beforeEach(() => { + vi.clearAllMocks(); + + mockRequest = { + json: vi.fn().mockResolvedValue({ input: 'test' }) + }; + + mockParams = { + tool: 'test-tool' + }; + + handler = createAPIHandler('test-category'); + }); + + describe('createAPIHandler', () => { + it('should return POST and GET handlers', () => { + expect(handler).toHaveProperty('POST'); + expect(handler).toHaveProperty('GET'); + expect(typeof handler.POST).toBe('function'); + expect(typeof handler.GET).toBe('function'); + }); + }); + + describe('POST Handler', () => { + it('should handle successful requests', async () => { + const mockEndpoint = { + handler: vi.fn().mockResolvedValue({ output: 'success' }), + description: 'Test endpoint', + category: 'test-category' + }; + + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(mockEndpoint); + + const result = await handler.POST({ params: mockParams, request: mockRequest }); + + expect(apiRegistry.getAPIHandler).toHaveBeenCalledWith('test-category', 'test-tool'); + expect(mockRequest.json).toHaveBeenCalled(); + expect(mockEndpoint.handler).toHaveBeenCalledWith({ input: 'test' }); + + const data = await result.json(); + expect(data).toEqual({ + success: true, + tool: 'test-tool', + result: { output: 'success' } + }); + }); + + it('should handle missing tool parameter', async () => { + const mockParamsNoTool = {}; + + const result = await handler.POST({ params: mockParamsNoTool, request: mockRequest }); + + expect(result.status).toBe(400); + const message = await result.text(); + expect(message).toBe('Tool parameter is required'); + }); + + it('should handle tool not found', async () => { + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(null); + + const result = await handler.POST({ params: mockParams, request: mockRequest }); + + expect(result.status).toBe(404); + const message = await result.text(); + expect(message).toBe("Tool 'test-tool' not found in test-category category"); + }); + + it('should handle endpoint handler errors', async () => { + const mockEndpoint = { + handler: vi.fn().mockRejectedValue(new Error('Handler error')), + description: 'Test endpoint', + category: 'test-category' + }; + + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(mockEndpoint); + + const result = await handler.POST({ params: mockParams, request: mockRequest }); + const data = await result.json(); + + expect(data).toEqual({ + success: false, + error: 'Handler error', + tool: 'test-tool' + }); + expect(result.status).toBe(500); + }); + + it('should handle non-Error exceptions', async () => { + const mockEndpoint = { + handler: vi.fn().mockRejectedValue('String error'), + description: 'Test endpoint', + category: 'test-category' + }; + + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(mockEndpoint); + + const result = await handler.POST({ params: mockParams, request: mockRequest }); + const data = await result.json(); + + expect(data).toEqual({ + success: false, + error: 'An error occurred', + tool: 'test-tool' + }); + }); + + it('should handle JSON parsing errors', async () => { + mockRequest.json.mockRejectedValue(new Error('Invalid JSON')); + + const mockEndpoint = { + handler: vi.fn(), + description: 'Test endpoint', + category: 'test-category' + }; + + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(mockEndpoint); + + const result = await handler.POST({ params: mockParams, request: mockRequest }); + const data = await result.json(); + + expect(data).toEqual({ + success: false, + error: 'Invalid JSON', + tool: 'test-tool' + }); + expect(mockEndpoint.handler).not.toHaveBeenCalled(); + }); + }); + + describe('GET Handler', () => { + it('should return endpoint information', async () => { + const mockEndpoint = { + handler: vi.fn(), + description: 'Test endpoint description', + category: 'test-category' + }; + + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(mockEndpoint); + + const result = await handler.GET({ params: mockParams }); + const data = await result.json(); + + expect(data).toEqual({ + tool: 'test-tool', + category: 'test-category', + description: 'Test endpoint description', + method: 'POST', + message: 'Send a POST request with parameters in the body' + }); + }); + + it('should handle missing tool parameter', async () => { + const mockParamsNoTool = {}; + + const result = await handler.GET({ params: mockParamsNoTool }); + + expect(result.status).toBe(400); + const message = await result.text(); + expect(message).toBe('Tool parameter is required'); + }); + + it('should handle tool not found', async () => { + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(null); + + const result = await handler.GET({ params: mockParams }); + + expect(result.status).toBe(404); + const message = await result.text(); + expect(message).toBe("Tool 'test-tool' not found in test-category category"); + }); + }); + + describe('Error Handling', () => { + it('should log errors to console', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + + const mockEndpoint = { + handler: vi.fn().mockRejectedValue(new Error('Test error')), + description: 'Test endpoint', + category: 'test-category' + }; + + vi.mocked(apiRegistry.getAPIHandler).mockReturnValue(mockEndpoint); + + await handler.POST({ params: mockParams, request: mockRequest }); + + expect(consoleSpy).toHaveBeenCalledWith( + 'API Error in test-category/test-tool:', + expect.any(Error) + ); + + consoleSpy.mockRestore(); + }); + }); + + describe('Type Safety', () => { + it('should maintain type safety for APIResponse', () => { + // This test ensures the APIResponse interface is properly exported and typed + const response: APIResponse<{ test: string }> = { + success: true, + tool: 'test', + result: { test: 'value' } + }; + + expect(response.success).toBe(true); + expect(response.tool).toBe('test'); + expect(response.result?.test).toBe('value'); + }); + + it('should handle error responses', () => { + const errorResponse: APIResponse = { + success: false, + tool: 'test', + error: 'Test error' + }; + + expect(errorResponse.success).toBe(false); + expect(errorResponse.error).toBe('Test error'); + expect(errorResponse.result).toBeUndefined(); + }); + }); +}); \ No newline at end of file diff --git a/tests/unit/utils/api-registry.test.ts b/tests/unit/utils/api-registry.test.ts new file mode 100644 index 0000000..16e7551 --- /dev/null +++ b/tests/unit/utils/api-registry.test.ts @@ -0,0 +1,260 @@ +import { describe, it, expect } from 'vitest'; +import { apiRegistry, getAPIHandler, listCategoryEndpoints } from '../../../src/lib/utils/api-registry'; + +describe('API Registry', () => { + describe('Registry Structure', () => { + it('should have apiRegistry defined', () => { + expect(apiRegistry).toBeDefined(); + expect(typeof apiRegistry).toBe('object'); + }); + + it('should have endpoints with correct structure', () => { + Object.entries(apiRegistry).forEach(([key, endpoint]) => { + expect(endpoint).toHaveProperty('handler'); + expect(endpoint).toHaveProperty('category'); + expect(endpoint).toHaveProperty('description'); + + expect(typeof endpoint.handler).toBe('function'); + expect(typeof endpoint.category).toBe('string'); + expect(typeof endpoint.description).toBe('string'); + + expect(key.length).toBeGreaterThan(0); + expect(endpoint.category.length).toBeGreaterThan(0); + expect(endpoint.description.length).toBeGreaterThan(0); + }); + }); + + it('should have expected categories', () => { + const categories = [...new Set(Object.values(apiRegistry).map(e => e.category))]; + + expect(categories).toContain('subnetting'); + expect(categories).toContain('cidr'); + expect(categories).toContain('ip-address-convertor'); + expect(categories).toContain('dns'); + }); + + it('should have expected endpoint counts', () => { + const endpointCount = Object.keys(apiRegistry).length; + expect(endpointCount).toBeGreaterThan(50); // Registry has many endpoints + }); + }); + + describe('Category Validation', () => { + it('should have valid subnetting endpoints', () => { + const subnettingEndpoints = Object.entries(apiRegistry) + .filter(([_, endpoint]) => endpoint.category === 'subnetting'); + + expect(subnettingEndpoints.length).toBeGreaterThan(0); + + const endpointNames = subnettingEndpoints.map(([key]) => key); + expect(endpointNames).toContain('ipv4-subnet-calculator'); + expect(endpointNames).toContain('ipv6-subnet-calculator'); + }); + + it('should have valid CIDR endpoints', () => { + const cidrEndpoints = Object.entries(apiRegistry) + .filter(([_, endpoint]) => endpoint.category === 'cidr'); + + expect(cidrEndpoints.length).toBeGreaterThan(0); + + const endpointNames = cidrEndpoints.map(([key]) => key); + expect(endpointNames).toContain('summarize'); + expect(endpointNames).toContain('split'); + }); + + it('should have valid IP conversion endpoints', () => { + const ipEndpoints = Object.entries(apiRegistry) + .filter(([_, endpoint]) => endpoint.category === 'ip-address-convertor'); + + expect(ipEndpoints.length).toBeGreaterThan(0); + + const endpointNames = ipEndpoints.map(([key]) => key); + expect(endpointNames).toContain('validator'); + expect(endpointNames).toContain('normalize'); + }); + + it('should have valid DNS endpoints', () => { + const dnsEndpoints = Object.entries(apiRegistry) + .filter(([_, endpoint]) => endpoint.category === 'dns'); + + expect(dnsEndpoints.length).toBeGreaterThan(0); + + const endpointNames = dnsEndpoints.map(([key]) => key); + expect(endpointNames).toContain('ptr-generator'); + expect(endpointNames).toContain('validate-domain'); + }); + }); + + describe('getAPIHandler Function', () => { + it('should find handlers by direct key match', () => { + const handler = getAPIHandler('subnetting', 'ipv4-subnet-calculator'); + + expect(handler).toBeDefined(); + expect(handler?.category).toBe('subnetting'); + expect(typeof handler?.handler).toBe('function'); + }); + + it('should find handlers by removing category prefix', () => { + const handler = getAPIHandler('dns', 'validate-domain'); + + expect(handler).toBeDefined(); + expect(handler?.category).toBe('dns'); + }); + + it('should return null for non-existent handlers', () => { + const handler = getAPIHandler('invalid-category', 'non-existent-tool'); + + expect(handler).toBeNull(); + }); + + it('should respect category filtering', () => { + const handler = getAPIHandler('cidr', 'ipv4-subnet-calculator'); + + expect(handler).toBeNull(); // Wrong category + }); + + it('should handle category prefix removal correctly', () => { + const handler = getAPIHandler('ip-address-convertor', 'ip-address-convertor-validator'); + + expect(handler).toBeDefined(); + expect(handler?.category).toBe('ip-address-convertor'); + }); + }); + + describe('listCategoryEndpoints Function', () => { + it('should list all endpoints for a category', () => { + const subnettingEndpoints = listCategoryEndpoints('subnetting'); + + expect(Array.isArray(subnettingEndpoints)).toBe(true); + expect(subnettingEndpoints.length).toBeGreaterThan(0); + expect(subnettingEndpoints).toContain('ipv4-subnet-calculator'); + }); + + it('should return empty array for non-existent category', () => { + const endpoints = listCategoryEndpoints('non-existent'); + + expect(Array.isArray(endpoints)).toBe(true); + expect(endpoints.length).toBe(0); + }); + + it('should list correct number of DNS endpoints', () => { + const dnsEndpoints = listCategoryEndpoints('dns'); + + expect(dnsEndpoints.length).toBeGreaterThan(10); // DNS has many endpoints + }); + + it('should not include duplicates', () => { + const cidrEndpoints = listCategoryEndpoints('cidr'); + const uniqueEndpoints = [...new Set(cidrEndpoints)]; + + expect(cidrEndpoints.length).toBe(uniqueEndpoints.length); + }); + }); + + describe('Handler Execution Tests', () => { + it('should execute IPv4 subnet calculator', () => { + const handler = getAPIHandler('subnetting', 'ipv4-subnet-calculator'); + + expect(() => { + const result = handler?.handler({ cidr: '192.168.1.0/24' }); + expect(result).toBeDefined(); + }).not.toThrow(); + }); + + it('should handle invalid CIDR format', () => { + const handler = getAPIHandler('subnetting', 'ipv4-subnet-calculator'); + + expect(() => { + handler?.handler({ cidr: 'invalid' }); + }).toThrow('Invalid CIDR format'); + }); + + it('should execute CIDR summarization', () => { + const handler = getAPIHandler('cidr', 'summarize'); + + expect(() => { + const result = handler?.handler({ input: '192.168.1.0/24\n192.168.2.0/24', mode: 'summarize' }); + expect(result).toBeDefined(); + }).not.toThrow(); + }); + + it('should execute IP validation', () => { + const handler = getAPIHandler('ip-address-convertor', 'validator'); + + expect(() => { + const result = handler?.handler({ ip: '192.168.1.1' }); + expect(result).toBeDefined(); + expect(result.ipv4).toBeDefined(); + }).not.toThrow(); + }); + + it('should handle missing required parameters', () => { + const handler = getAPIHandler('dns', 'validate-domain'); + + expect(() => { + handler?.handler({}); + }).toThrow('domain parameter is required'); + }); + }); + + describe('Error Handling', () => { + it('should throw errors for missing parameters in IPv6 calculator', () => { + const handler = getAPIHandler('subnetting', 'ipv6-subnet-calculator'); + + expect(() => { + handler?.handler({ cidr: '2001:db8::/invalid' }); + }).toThrow('Prefix length must be a valid number'); + }); + + it('should throw errors for missing input in random IP generator', () => { + const handler = getAPIHandler('ip-address-convertor', 'random'); + + expect(() => { + handler?.handler({}); + }).toThrow('input parameter is required'); + }); + + it('should validate required DNS parameters', () => { + const handler = getAPIHandler('dns', 'validate-srv-record'); + + expect(() => { + handler?.handler({ service: 'http' }); + }).toThrow('service, protocol, priority, weight, port, and target parameters are required'); + }); + }); + + describe('Parameter Handling', () => { + it('should handle array inputs for CIDR operations', () => { + const handler = getAPIHandler('cidr', 'diff'); + + expect(() => { + const result = handler?.handler({ + setA: ['192.168.1.0/24'], + setB: ['192.168.2.0/24'] + }); + expect(result).toBeDefined(); + }).not.toThrow(); + }); + + it('should handle string inputs for CIDR operations', () => { + const handler = getAPIHandler('cidr', 'overlap'); + + expect(() => { + const result = handler?.handler({ + setA: '192.168.1.0/24', + setB: '192.168.2.0/24' + }); + expect(result).toBeDefined(); + }).not.toThrow(); + }); + + it('should handle default values', () => { + const handler = getAPIHandler('ip-address-convertor', 'random'); + + expect(() => { + const result = handler?.handler({ input: '192.168.1.0/24' }); + expect(result).toBeDefined(); + }).not.toThrow(); + }); + }); +}); \ No newline at end of file diff --git a/tests/unit/utils/cidr-compare.test.ts b/tests/unit/utils/cidr-compare.test.ts new file mode 100644 index 0000000..f44932f --- /dev/null +++ b/tests/unit/utils/cidr-compare.test.ts @@ -0,0 +1,349 @@ +import { describe, it, expect } from 'vitest'; +import { cidrCompare, type CompareInput } from '../../../src/lib/utils/cidr-compare'; + +describe('CIDR Compare Utility', () => { + describe('Basic Comparison', () => { + it('should identify identical lists', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n10.0.0.0/16', + listB: '192.168.1.0/24\n10.0.0.0/16' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + expect(result.unchanged).toHaveLength(2); + expect(result.summary.totalA).toBe(2); + expect(result.summary.totalB).toBe(2); + }); + + it('should identify added entries', () => { + const input: CompareInput = { + listA: '192.168.1.0/24', + listB: '192.168.1.0/24\n10.0.0.0/16' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.added).toContain('10.0.0.0/16'); + expect(result.removed).toHaveLength(0); + expect(result.unchanged).toContain('192.168.1.0/24'); + expect(result.summary.addedCount).toBe(1); + }); + + it('should identify removed entries', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n10.0.0.0/16', + listB: '192.168.1.0/24' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.added).toHaveLength(0); + expect(result.removed).toContain('10.0.0.0/16'); + expect(result.unchanged).toContain('192.168.1.0/24'); + expect(result.summary.removedCount).toBe(1); + }); + + it('should handle completely different lists', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n10.0.0.0/16', + listB: '172.16.0.0/12\n203.0.113.0/24' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.added).toHaveLength(2); + expect(result.removed).toHaveLength(2); + expect(result.unchanged).toHaveLength(0); + expect(result.summary.unchangedCount).toBe(0); + }); + }); + + describe('Normalization', () => { + it('should normalize single IPs to /32', () => { + const input: CompareInput = { + listA: '192.168.1.1', + listB: '192.168.1.1/32' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.unchanged).toHaveLength(1); + expect(result.normalizedA).toContain('192.168.1.1/32'); + expect(result.normalizedB).toContain('192.168.1.1/32'); + }); + + it('should normalize CIDR to network address', () => { + const input: CompareInput = { + listA: '192.168.1.100/24', + listB: '192.168.1.0/24' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.unchanged).toHaveLength(1); + expect(result.normalizedA).toContain('192.168.1.0/24'); + expect(result.normalizedB).toContain('192.168.1.0/24'); + }); + + it('should handle empty inputs', () => { + const input: CompareInput = { + listA: '', + listB: '192.168.1.0/24' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.added).toContain('192.168.1.0/24'); + expect(result.removed).toHaveLength(0); + expect(result.summary.totalA).toBe(0); + expect(result.summary.totalB).toBe(1); + }); + + it('should ignore empty lines and whitespace', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n\n \n10.0.0.0/16', + listB: '192.168.1.0/24\n10.0.0.0/16' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.unchanged).toHaveLength(2); + expect(result.summary.totalA).toBe(2); + expect(result.summary.totalB).toBe(2); + }); + }); + + describe('IP Range Handling', () => { + it('should convert IP ranges to CIDR blocks', () => { + const input: CompareInput = { + listA: '192.168.1.0-192.168.1.3', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.removed.length).toBeGreaterThan(0); + expect(result.normalizedA.length).toBeGreaterThan(0); + }); + + it('should handle single IP ranges', () => { + const input: CompareInput = { + listA: '192.168.1.1-192.168.1.1', + listB: '192.168.1.1/32' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.unchanged).toHaveLength(1); + }); + + it('should reject invalid ranges', () => { + const input: CompareInput = { + listA: '192.168.1.10-192.168.1.5', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(false); + expect(result.error).toContain('start IP is greater than end IP'); + }); + }); + + describe('Sorting', () => { + it('should sort results by network address', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n10.0.0.0/16\n172.16.0.0/12', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.normalizedA[0]).toBe('10.0.0.0/16'); + expect(result.normalizedA[1]).toBe('172.16.0.0/12'); + expect(result.normalizedA[2]).toBe('192.168.1.0/24'); + }); + + it('should sort by prefix length for same network', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n192.168.1.0/25', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.normalizedA[0]).toBe('192.168.1.0/25'); // More specific first + expect(result.normalizedA[1]).toBe('192.168.1.0/24'); + }); + }); + + describe('Error Handling', () => { + it('should handle invalid CIDR format', () => { + const input: CompareInput = { + listA: 'not.an.ip.address', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(false); + expect(result.error).toContain('Error processing'); + }); + + it('should handle invalid prefix length', () => { + const input: CompareInput = { + listA: '192.168.1.0/33', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(false); + expect(result.error).toContain('Invalid prefix length'); + }); + + it('should handle malformed IP addresses', () => { + const input: CompareInput = { + listA: 'abc.def.ghi.jkl/24', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(false); + expect(result.error).toBeDefined(); + }); + + it('should handle malformed ranges', () => { + const input: CompareInput = { + listA: '192.168.1.1-invalid', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(false); + expect(result.error).toBeDefined(); + }); + }); + + describe('Deduplication', () => { + it('should deduplicate identical entries', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n192.168.1.0/24\n192.168.1.100/24', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.normalizedA).toHaveLength(1); + expect(result.normalizedA[0]).toBe('192.168.1.0/24'); + }); + + it('should handle complex deduplication', () => { + const input: CompareInput = { + listA: '192.168.1.1\n192.168.1.1/32\n192.168.1.100/24', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.normalizedA).toContain('192.168.1.1/32'); + expect(result.normalizedA).toContain('192.168.1.0/24'); + }); + }); + + describe('Summary Statistics', () => { + it('should provide accurate summary counts', () => { + const input: CompareInput = { + listA: '192.168.1.0/24\n10.0.0.0/16\n172.16.0.0/12', + listB: '192.168.1.0/24\n203.0.113.0/24' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.summary.totalA).toBe(3); + expect(result.summary.totalB).toBe(2); + expect(result.summary.addedCount).toBe(1); + expect(result.summary.removedCount).toBe(2); + expect(result.summary.unchangedCount).toBe(1); + + // Verify totals add up + expect(result.summary.addedCount + result.summary.unchangedCount).toBe(result.summary.totalB); + expect(result.summary.removedCount + result.summary.unchangedCount).toBe(result.summary.totalA); + }); + }); + + describe('Edge Cases', () => { + it('should handle both lists empty', () => { + const input: CompareInput = { + listA: '', + listB: '' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.summary.totalA).toBe(0); + expect(result.summary.totalB).toBe(0); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + expect(result.unchanged).toHaveLength(0); + }); + + it('should handle whitespace-only inputs', () => { + const input: CompareInput = { + listA: ' \n \n ', + listB: '\t\n ' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.summary.totalA).toBe(0); + expect(result.summary.totalB).toBe(0); + }); + + it('should handle /0 prefix', () => { + const input: CompareInput = { + listA: '0.0.0.0/0', + listB: '0.0.0.0/0' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.unchanged).toContain('0.0.0.0/0'); + }); + + it('should handle /32 prefix', () => { + const input: CompareInput = { + listA: '192.168.1.1/32', + listB: '192.168.1.1/32' + }; + + const result = cidrCompare(input); + + expect(result.success).toBe(true); + expect(result.unchanged).toContain('192.168.1.1/32'); + }); + }); +}); \ No newline at end of file diff --git a/tests/unit/utils/json-serialization.test.ts b/tests/unit/utils/json-serialization.test.ts new file mode 100644 index 0000000..d7d4226 --- /dev/null +++ b/tests/unit/utils/json-serialization.test.ts @@ -0,0 +1,181 @@ +import { describe, it, expect } from 'vitest'; +import { serializeBigInt } from '../../../src/lib/utils/json-serialization'; + +describe('JSON Serialization Utilities', () => { + describe('serializeBigInt', () => { + it('should convert BigInt to string', () => { + const bigIntValue = BigInt('12345678901234567890'); + const result = serializeBigInt(bigIntValue); + + expect(result).toBe('12345678901234567890'); + expect(typeof result).toBe('string'); + }); + + it('should handle arrays with BigInt values', () => { + const input = [BigInt('123'), BigInt('456'), 'normal string', 42]; + const result = serializeBigInt(input); + + expect(result).toEqual(['123', '456', 'normal string', 42]); + expect(Array.isArray(result)).toBe(true); + }); + + it('should handle nested arrays', () => { + const input = [BigInt('123'), [BigInt('456'), BigInt('789')]]; + const result = serializeBigInt(input); + + expect(result).toEqual(['123', ['456', '789']]); + }); + + it('should handle objects with BigInt values', () => { + const input = { + count: BigInt('12345'), + name: 'test', + value: 42 + }; + const result = serializeBigInt(input); + + expect(result).toEqual({ + count: '12345', + name: 'test', + value: 42 + }); + }); + + it('should handle nested objects', () => { + const input = { + outer: { + inner: BigInt('999'), + other: 'string' + }, + number: 123 + }; + const result = serializeBigInt(input); + + expect(result).toEqual({ + outer: { + inner: '999', + other: 'string' + }, + number: 123 + }); + }); + + it('should handle complex nested structures', () => { + const input = { + array: [BigInt('111'), { nested: BigInt('222') }], + object: { + value: BigInt('333'), + subArray: [BigInt('444'), 'text'] + } + }; + const result = serializeBigInt(input); + + expect(result).toEqual({ + array: ['111', { nested: '222' }], + object: { + value: '333', + subArray: ['444', 'text'] + } + }); + }); + + it('should handle primitive values', () => { + expect(serializeBigInt('string')).toBe('string'); + expect(serializeBigInt(42)).toBe(42); + expect(serializeBigInt(true)).toBe(true); + expect(serializeBigInt(false)).toBe(false); + expect(serializeBigInt(null)).toBe(null); + expect(serializeBigInt(undefined)).toBe(undefined); + }); + + it('should handle empty arrays and objects', () => { + expect(serializeBigInt([])).toEqual([]); + expect(serializeBigInt({})).toEqual({}); + }); + + it('should handle arrays with mixed types', () => { + const input = [ + BigInt('123'), + 'string', + 42, + true, + null, + undefined, + { key: BigInt('456') }, + [BigInt('789')] + ]; + const result = serializeBigInt(input); + + expect(result).toEqual([ + '123', + 'string', + 42, + true, + null, + undefined, + { key: '456' }, + ['789'] + ]); + }); + + it('should preserve object property ownership', () => { + const parent = { inherited: BigInt('999') }; + const child = Object.create(parent); + child.own = BigInt('123'); + + const result = serializeBigInt(child); + + expect(result).toEqual({ own: '123' }); + expect(result.hasOwnProperty('inherited')).toBe(false); + }); + + it('should handle very large BigInt values', () => { + const largeValue = BigInt('12345678901234567890123456789012345678901234567890'); + const result = serializeBigInt(largeValue); + + expect(result).toBe('12345678901234567890123456789012345678901234567890'); + }); + + it('should handle zero BigInt', () => { + const result = serializeBigInt(BigInt(0)); + expect(result).toBe('0'); + }); + + it('should handle negative BigInt values', () => { + const result = serializeBigInt(BigInt(-123)); + expect(result).toBe('-123'); + }); + + it('should handle Date objects (converts to empty object)', () => { + const date = new Date('2023-01-01'); + const result = serializeBigInt(date); + + expect(result).toEqual({}); + expect(typeof result).toBe('object'); + }); + + it('should handle RegExp objects (converts to empty object)', () => { + const regex = /test/g; + const result = serializeBigInt(regex); + + expect(result).toEqual({}); + expect(typeof result).toBe('object'); + }); + + it('should handle functions (pass through)', () => { + const fn = () => 'test'; + const result = serializeBigInt(fn); + + expect(result).toBe(fn); + expect(typeof result).toBe('function'); + }); + + it('should handle symbols (pass through)', () => { + const sym = Symbol('test'); + const result = serializeBigInt(sym); + + expect(result).toBe(sym); + expect(typeof result).toBe('symbol'); + }); + }); +}); \ No newline at end of file