dictutils 0.1.2

Dictionary utilities for Mdict and other formats
Documentation
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Error handling and edge case tests
//!
//! This module tests error conditions, edge cases, and recovery scenarios
//! for all dictionary operations.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::*;
    use crate::util::test_utils::*;
    use std::io;

    /// Test dictionary operation errors
    mod dict_error_tests {
        use super::*;

        #[test]
        fn test_file_not_found_error() {
            let loader = DictLoader::new();
            let non_existent_path = std::path::Path::new("nonexistent.mdict");

            let result = loader.load(non_existent_path);
            assert!(result.is_err());

            if let Err(error) = result {
                assert!(matches!(error, DictError::FileNotFound(_)));
            }
        }

        #[test]
        fn test_invalid_format_error() {
            let temp_dir = temp_dir().unwrap();
            let invalid_file = temp_dir.path().join("invalid.mdict");

            // Create an invalid dictionary file
            std::fs::write(&invalid_file, "This is not a valid dictionary").unwrap();

            let loader = DictLoader::new();
            let result = loader.load(&invalid_file);

            // Should either fail to load or detect invalid format
            if result.is_err() {
                if let Err(error) = result {
                    assert!(matches!(error, DictError::InvalidFormat(_)));
                }
            }
        }

        #[test]
        fn test_unsupported_operation_error() {
            // Test unsupported operations
            let error = DictError::UnsupportedOperation("test operation".to_string());
            assert!(matches!(error, DictError::UnsupportedOperation(_)));

            let error_str = error.to_string();
            assert!(error_str.contains("test operation"));
            assert!(error_str.contains("Unsupported operation"));
        }

        #[test]
        fn test_io_error_handling() {
            let error = DictError::IoError("I/O test error".to_string());
            assert!(matches!(error, DictError::IoError(_)));

            let error_str = error.to_string();
            assert!(error_str.contains("I/O test error"));
            assert!(error_str.contains("I/O error"));
        }

        #[test]
        fn test_index_error_handling() {
            let error = DictError::IndexError("Index test error".to_string());
            assert!(matches!(error, DictError::IndexError(_)));

            let error_str = error.to_string();
            assert!(error_str.contains("Index test error"));
            assert!(error_str.contains("Index error"));
        }

        #[test]
        fn test_decompression_error_handling() {
            let error = DictError::DecompressionError("Decompression test error".to_string());
            assert!(matches!(error, DictError::DecompressionError(_)));

            let error_str = error.to_string();
            assert!(error_str.contains("Decompression test error"));
            assert!(error_str.contains("Decompression error"));
        }

        #[test]
        fn test_internal_error_handling() {
            let error = DictError::Internal("Internal test error".to_string());
            assert!(matches!(error, DictError::Internal(_)));

            let error_str = error.to_string();
            assert!(error_str.contains("Internal test error"));
            assert!(error_str.contains("Internal error"));
        }
    }

    /// Test file I/O error scenarios
    mod io_error_tests {
        use super::*;
        use std::fs;

        #[test]
        fn test_permission_denied_error() {
            // This test simulates permission errors
            // In a real test, you might create a file with restricted permissions

            // Test that the library handles permission issues gracefully
            let temp_dir = temp_dir().unwrap();
            let restricted_file = temp_dir.path().join("restricted.txt");

            // Create a file first
            std::fs::write(&restricted_file, "test content").unwrap();

            // Check that readable utility works
            assert!(crate::dict::utils::is_readable(&restricted_file));
        }

        #[test]
        fn test_disk_full_simulation() {
            // Simulate disk full scenarios
            // In practice, this would be difficult to test reliably

            let temp_dir = temp_dir().unwrap();
            let test_file = temp_dir.path().join("test_file");

            // Test basic file operations
            let result = std::fs::write(&test_file, "test content");
            assert!(result.is_ok());

            // Clean up
            let _ = std::fs::remove_file(&test_file);
        }

        #[test]
        fn test_concurrent_file_access_errors() {
            // Test concurrent access scenarios
            let temp_dir = temp_dir().unwrap();
            let test_file = temp_dir.path().join("concurrent_test.txt");

            // Create initial file
            std::fs::write(&test_file, "initial content").unwrap();

            // Test that file exists and is readable
            assert!(test_file.exists());
            assert!(crate::dict::utils::is_readable(&test_file));

            // Clean up
            let _ = std::fs::remove_file(&test_file);
        }
    }

    /// Test format-specific error conditions
    mod format_error_tests {
        use super::*;

        #[test]
        fn test_mdict_format_errors() {
            let temp_dir = temp_dir().unwrap();
            let mdict_file = temp_dir.path().join("test.mdict");

            // Test various invalid MDict files
            let invalid_contents = vec![
                "",  // Empty file
                "InvalidHeader",  // Wrong magic header
                "MDictInvalidVersion",  // Wrong version
                "MDictVersion 1.0.0\x00\x00\x00\x00",  // Incomplete header
            ];

            for content in invalid_contents {
                std::fs::write(&mdict_file, content).unwrap();

                let loader = DictLoader::new();
                let result = loader.load(&mdict_file);

                // Should fail gracefully
                if result.is_err() {
                    if let Err(error) = result {
                        assert!(matches!(error, DictError::InvalidFormat(_) |
                                        DictError::IoError(_) |
                                        DictError::UnsupportedOperation(_)));
                    }
                }
            }
        }

        #[test]
        fn test_stardict_format_errors() {
            let temp_dir = temp_dir().unwrap();
            let dict_file = temp_dir.path().join("test.dict");

            let invalid_contents = vec![
                "",  // Empty file
                "InvalidMagic",  // Wrong magic
                "StarDict's dictInvalidVersion\x00",  // Invalid version
            ];

            for content in invalid_contents {
                std::fs::write(&dict_file, content).unwrap();

                let loader = DictLoader::new();
                let result = loader.load(&dict_file);

                // Should handle gracefully
                if result.is_err() {
                    if let Err(error) = result {
                        assert!(matches!(error, DictError::InvalidFormat(_) |
                                        DictError::IoError(_)));
                    }
                }
            }
        }

        #[test]
        fn test_zim_format_errors() {
            let temp_dir = temp_dir().unwrap();
            let zim_file = temp_dir.path().join("test.zim");

            let invalid_contents = vec![
                "",  // Empty file
                "ZIM\x00",  // Wrong version
                "ZIM\x01Invalid",  // Invalid header
            ];

            for content in invalid_contents {
                std::fs::write(&zim_file, content).unwrap();

                let loader = DictLoader::new();
                let result = loader.load(&zim_file);

                // Should handle gracefully
                if result.is_err() {
                    if let Err(error) = result {
                        assert!(matches!(error, DictError::InvalidFormat(_) |
                                        DictError::IoError(_)));
                    }
                }
            }
        }
    }

    /// Test edge case scenarios
    mod edge_case_tests {
        use super::*;

        #[test]
        fn test_empty_dictionary_handling() {
            let temp_dir = temp_dir().unwrap();
            let empty_dict = temp_dir.path().join("empty.mdict");

            // Create an empty dictionary
            std::fs::write(&empty_dict, "").unwrap();

            let loader = DictLoader::new();

            // Format detection might succeed but loading should fail gracefully
            let format_result = loader.detect_format(&empty_dict);
            // Empty files should be handled gracefully

            let load_result = loader.load(&empty_dict);
            if load_result.is_err() {
                if let Err(error) = load_result {
                    assert!(matches!(error, DictError::InvalidFormat(_) |
                                    DictError::IoError(_)));
                }
            }
        }

        #[test]
        fn test_extremely_long_keys() {
            let temp_dir = temp_dir().unwrap();
            let long_key_dict = temp_dir.path().join("long_key.mdict");

            // Test with very long keys (within reasonable limits)
            let long_key = "a".repeat(4096); // 4KB key
            let content = "This is content for a very long key";

            std::fs::write(&long_key_dict, format!("{}\n{}", long_key, content)).unwrap();

            // Should handle long keys gracefully
            assert!(long_key_dict.exists());
        }

        #[test]
        fn test_very_large_entries() {
            let temp_dir = temp_dir().unwrap();
            let large_entry_dict = temp_dir.path().join("large_entry.mdict");

            // Create entry with large content
            let large_content = "x".repeat(1024 * 1024); // 1MB content
            let entry = format!("large_key\n{}", large_content);

            std::fs::write(&large_entry_dict, entry).unwrap();

            assert!(large_entry_dict.exists());
            assert!(large_entry_dict.metadata().unwrap().len() > 1024 * 1024);
        }

        #[test]
        fn test_invalid_utf8_content() {
            let temp_dir = temp_dir().unwrap();
            let invalid_utf8_dict = temp_dir.path().join("invalid_utf8.mdict");

            // Create content with invalid UTF-8 sequences
            let invalid_content = vec![0xFF, 0xFE, 0x00, 0x01];
            std::fs::write(&invalid_utf8_dict, &invalid_content).unwrap();

            // Should handle invalid UTF-8 gracefully
            assert!(invalid_utf8_dict.exists());

            let loader = DictLoader::new();
            let result = loader.load(&invalid_utf8_dict);

            // Should either handle gracefully or fail with appropriate error
            if result.is_err() {
                if let Err(error) = result {
                    assert!(matches!(error, DictError::InvalidFormat(_) |
                                    DictError::IoError(_)));
                }
            }
        }

        #[test]
        fn test_maximum_file_size_handling() {
            // Test with very large files
            let temp_dir = temp_dir().unwrap();
            let large_file = temp_dir.path().join("large_file.mdict");

            // Create a file approaching system limits
            let large_content = "data".repeat(1024 * 1024 * 10); // ~40MB
            let write_result = std::fs::write(&large_file, large_content);

            // Should either succeed or fail gracefully
            if write_result.is_err() {
                if let Err(error) = write_result {
                    assert!(matches!(error, io::ErrorKind::DiskFull |
                                    io::ErrorKind::FileTooLarge |
                                    io::ErrorKind::PermissionDenied));
                }
            } else {
                assert!(large_file.exists());
                let size = large_file.metadata().unwrap().len();
                assert!(size > 10 * 1024 * 1024);
            }
        }
    }

    /// Test recovery and retry mechanisms
    mod recovery_tests {
        use super::*;

        #[test]
        fn test_format_detection_retry() {
            let temp_dir = temp_dir().unwrap();
            let ambiguous_file = temp_dir.path().join("ambiguous");

            // Create file without extension - format detection should try multiple methods
            std::fs::write(&ambiguous_file, "MDict version").unwrap();

            let loader = DictLoader::new();

            // Test that format detection attempts different methods
            // Note: actual format detection might need content-based analysis
            let result = loader.detect_format(&ambiguous_file);

            // Should either succeed or fail with appropriate error
            if result.is_err() {
                if let Err(error) = result {
                    assert!(matches!(error, DictError::UnsupportedOperation(_)));
                }
            }
        }

        #[test]
        fn test_partial_file_recovery() {
            let temp_dir = temp_dir().unwrap();
            let partial_file = temp_dir.path().join("partial.mdict");

            // Create a partially written file
            let partial_content = "MDict version 1.0.0";
            std::fs::write(&partial_file, partial_content).unwrap();

            let loader = DictLoader::new();
            let result = loader.load(&partial_file);

            // Should fail gracefully for incomplete files
            if result.is_err() {
                if let Err(error) = result {
                    assert!(matches!(error, DictError::InvalidFormat(_) |
                                    DictError::IoError(_)));
                }
            }
        }

        #[test]
        fn test_concurrent_access_recovery() {
            let temp_dir = temp_dir().unwrap();
            let shared_file = temp_dir.path().join("shared.mdict");

            // Create a file that might be accessed concurrently
            let content = "MDict version 1.0.0\n1\n0\n0\n0\n";
            std::fs::write(&shared_file, content).unwrap();

            // Test that basic operations work
            assert!(shared_file.exists());
            assert!(crate::dict::utils::is_readable(&shared_file));

            // Test format detection still works
            let loader = DictLoader::new();
            let format = loader.detect_format(&shared_file);

            if let Ok(format_type) = format {
                assert_eq!(format_type, "mdict");
            }
        }
    }

    /// Test memory and resource limits
    mod resource_limit_tests {
        use super::*;

        #[test]
        fn test_memory_limit_handling() {
            // Test handling of memory constraints
            let temp_dir = temp_dir().unwrap();

            // Create multiple files to test memory usage
            for i in 0..10 {
                let file_path = temp_dir.path().join(format!("memory_test_{}.mdict", i));
                let content = format!("MDict version 1.0.0\n{}", i);
                std::fs::write(&file_path, content).unwrap();
            }

            // Test directory scanning
            let loader = DictLoader::new();
            let dict_files = loader.scan_directory(&temp_dir).unwrap();

            assert_eq!(dict_files.len(), 10);
        }

        #[test]
        fn test_cache_limit_handling() {
            // Test cache behavior with limited size
            let limited_config = DictConfig {
                cache_size: 5, // Very small cache
                batch_size: 10,
                ..Default::default()
            };

            let loader = DictLoader::with_config(limited_config);
            assert_eq!(loader.default_config().cache_size, 5);
        }

        #[test]
        fn test_concurrent_resource_usage() {
            let temp_dir = temp_dir().unwrap();

            // Create multiple dictionary files for concurrent testing
            for i in 0..5 {
                let file_path = temp_dir.path().join(format!("concurrent_{}.mdict", i));
                let content = format!("MDict version 1.0.0\n{}", i);
                std::fs::write(&file_path, content).unwrap();
            }

            // Test multiple file operations
            let loader = DictLoader::new();

            for i in 0..5 {
                let file_path = temp_dir.path().join(format!("concurrent_{}.mdict", i));
                assert!(loader.is_dictionary_file(&file_path));
            }
        }
    }
}