πŸ“¦ LinkLeong / OZSync

πŸ“„ test-sync.mjs Β· 242 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242#!/usr/bin/env node

// Test file synchronization functionality
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';

class SyncFunctionTest {
    constructor() {
        this.testDir = './test-vault';
        this.backupDir = './test-backup';
    }

    async setup() {
        console.log('πŸ”§ Setting up test environment...');
        
        // Create test directories
        await this.ensureDir(this.testDir);
        await this.ensureDir(this.backupDir);
        
        // Create test files
        await this.createTestFiles();
        console.log('βœ… Test environment setup completed');
    }

    async ensureDir(dirPath) {
        try {
            await fs.access(dirPath);
        } catch {
            await fs.mkdir(dirPath, { recursive: true });
        }
    }

    async createTestFiles() {
        const testFiles = [
            {
                path: 'note1.md',
                content: '# Test Note 1\n\nThis is a test note for verifying sync functionality.\n\n- Item 1\n- Item 2\n- Item 3'
            },
            {
                path: 'folder1/note2.md',
                content: '# Subfolder Note\n\nThis is a note located in a subfolder.\n\n```javascript\nconsole.log("Hello World");\n```'
            },
            {
                path: 'daily/2024-01-01.md',
                content: '# 2024-01-01 Daily\n\nToday\'s tasks:\n- [x] Complete Project A\n- [ ] Start Project B\n- [ ] Review notes'
            }
        ];

        for (const file of testFiles) {
            const fullPath = path.join(this.testDir, file.path);
            const dir = path.dirname(fullPath);
            await this.ensureDir(dir);
            await fs.writeFile(fullPath, file.content, 'utf8');
        }
    }

    async testFileEncryption() {
        console.log('πŸ” Testing file encryption functionality...');
        
        const testContent = 'This is a test content for encryption';
        const password = 'test-password-123';
        
        // ζ¨‘ζ‹ŸεŠ ε―†θΏ‡η¨‹
        const encrypted = this.encryptContent(testContent, password);
        console.log(`   Encrypted length: ${encrypted.length} characters`);
        
        // Simulate decryption process
        const decrypted = this.decryptContent(encrypted, password);
        const success = decrypted === testContent;
        
        console.log(`   Decryption result: ${success ? 'βœ… Success' : '❌ Failed'}`);
        return success;
    }

    encryptContent(content, password) {
        const algorithm = 'aes-256-cbc';
        const key = crypto.scryptSync(password, 'salt', 32);
        const iv = crypto.randomBytes(16);
        const cipher = crypto.createCipheriv(algorithm, key, iv);
        
        let encrypted = cipher.update(content, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        
        return iv.toString('hex') + ':' + encrypted;
    }

    decryptContent(encryptedData, password) {
        try {
            const algorithm = 'aes-256-cbc';
            const key = crypto.scryptSync(password, 'salt', 32);
            const [ivHex, encrypted] = encryptedData.split(':');
            const iv = Buffer.from(ivHex, 'hex');
            const decipher = crypto.createDecipheriv(algorithm, key, iv);
            
            let decrypted = decipher.update(encrypted, 'hex', 'utf8');
            decrypted += decipher.final('utf8');
            
            return decrypted;
        } catch (error) {
            return null;
        }
    }

    async testBackupCreation() {
        console.log('πŸ” Testing backup creation functionality...');
        
        try {
            const files = await this.scanDirectory(this.testDir);
            console.log(`   Files found: ${files.length}`);
            
            let backupCount = 0;
            for (const file of files) {
                const content = await fs.readFile(file.fullPath, 'utf8');
                const backupPath = path.join(this.backupDir, file.relativePath);
                const backupDir = path.dirname(backupPath);
                
                await this.ensureDir(backupDir);
                await fs.writeFile(backupPath, content, 'utf8');
                backupCount++;
            }
            
            console.log(`   Backup files created: ${backupCount}`);
            console.log('βœ… Backup creation successful');
            return true;
        } catch (error) {
            console.log(`❌ Backup creation failed: ${error.message}`);
            return false;
        }
    }

    async testFileRestore() {
        console.log('πŸ” Testing file restore functionality...');
        
        try {
            // Delete original files
            await fs.rm(this.testDir, { recursive: true, force: true });
            await this.ensureDir(this.testDir);
            
            // Restore from backup
            const backupFiles = await this.scanDirectory(this.backupDir);
            console.log(`   Files to restore: ${backupFiles.length}`);
            
            let restoredCount = 0;
            for (const file of backupFiles) {
                const content = await fs.readFile(file.fullPath, 'utf8');
                const restorePath = path.join(this.testDir, file.relativePath);
                const restoreDir = path.dirname(restorePath);
                
                await this.ensureDir(restoreDir);
                await fs.writeFile(restorePath, content, 'utf8');
                restoredCount++;
            }
            
            console.log(`   Files restored: ${restoredCount}`);
            console.log('βœ… File restore successful');
            return true;
        } catch (error) {
            console.log(`❌ File restore failed: ${error.message}`);
            return false;
        }
    }

    async scanDirectory(dirPath) {
        const files = [];
        
        async function scan(currentPath, relativePath = '') {
            const items = await fs.readdir(currentPath);
            
            for (const item of items) {
                const fullPath = path.join(currentPath, item);
                const itemRelativePath = path.join(relativePath, item);
                const stat = await fs.stat(fullPath);
                
                if (stat.isDirectory()) {
                    await scan(fullPath, itemRelativePath);
                } else if (stat.isFile() && item.endsWith('.md')) {
                    files.push({
                        fullPath,
                        relativePath: itemRelativePath,
                        size: stat.size,
                        modified: stat.mtime
                    });
                }
            }
        }
        
        await scan(dirPath);
        return files;
    }

    async cleanup() {
        console.log('🧹 Cleaning up test environment...');
        try {
            await fs.rm(this.testDir, { recursive: true, force: true });
            await fs.rm(this.backupDir, { recursive: true, force: true });
            console.log('βœ… Cleanup completed');
        } catch (error) {
            console.log(`⚠️ Cleanup warning: ${error.message}`);
        }
    }

    async runAllTests() {
        console.log('πŸš€ εΌ€ε§‹ζ–‡δ»ΆεŒζ­₯εŠŸθƒ½ζ΅‹θ―•\n');
        
        try {
            await this.setup();
            console.log('');
            
            const encryptionResult = await this.testFileEncryption();
            console.log('');
            
            const backupResult = await this.testBackupCreation();
            console.log('');
            
            const restoreResult = await this.testFileRestore();
            console.log('');
            
            console.log('πŸ“Š ζ΅‹θ―•η»“ζžœζ±‡ζ€»:');
            console.log(`   ζ–‡δ»ΆεŠ ε―†: ${encryptionResult ? 'βœ… 成功' : '❌ ε€±θ΄₯'}`);
            console.log(`   ε€‡δ»½εˆ›ε»Ί: ${backupResult ? 'βœ… 成功' : '❌ ε€±θ΄₯'}`);
            console.log(`   文仢恒倍: ${restoreResult ? 'βœ… 成功' : '❌ ε€±θ΄₯'}`);
            
            const overallSuccess = encryptionResult && backupResult && restoreResult;
            console.log(`   ζ•΄δ½“ηŠΆζ€: ${overallSuccess ? 'βœ… ζ‰€ζœ‰ζ΅‹θ―•ι€šθΏ‡' : '❌ ιƒ¨εˆ†ζ΅‹θ―•ε€±θ΄₯'}`);
            
            return overallSuccess;
        } finally {
            console.log('');
            await this.cleanup();
        }
    }
}

// θΏθ‘Œζ΅‹θ―•
const tester = new SyncFunctionTest();
tester.runAllTests().then(success => {
    process.exit(success ? 0 : 1);
}).catch(error => {
    console.error('ζ΅‹θ―•ζ‰§θ‘Œι”™θ――:', error);
    process.exit(1);
});