Skip to main content

file_system/operations/
file_system.rs

1use crate::{
2    Attributes, Context, DirectoryOperations, FileOperations, Flags, MountOperations, Path, Result,
3};
4
5pub trait FileSystemOperations: FileOperations + DirectoryOperations + MountOperations {
6    /// Return whether this backend enforces confined, non-following namespace
7    /// semantics for operations beneath a directory root.
8    ///
9    /// In-process storage backends with no native symlink traversal and
10    /// backends that implement [`Self::supports_directory_entry_operations`]
11    /// satisfy this contract. Backends using the default (`false`) are rejected
12    /// before dispatch during confined lookups.
13    fn supports_confined_namespace(&self) -> bool {
14        self.supports_directory_entry_operations()
15    }
16
17    /// Return whether this backend operates on single normal entry names
18    /// relative to an already-opened directory [`Context`].
19    ///
20    /// When `true`, the virtual file system traverses components using opened
21    /// directory handles and never asks the backend to re-resolve multi-component
22    /// parent paths after checks.
23    fn supports_directory_entry_operations(&self) -> bool {
24        false
25    }
26
27    /// Open a child directory entry `name` inside the opened `parent`
28    /// directory into `context`, without following symbolic links.
29    ///
30    /// `name` must be a single normal entry name without separators or dot
31    /// segments.
32    fn lookup_directory_entry(
33        &self,
34        _parent: &Context,
35        _name: &str,
36        _context: &mut Context,
37    ) -> Result<()> {
38        Err(crate::IoErrorKind::Unsupported)
39    }
40
41    /// Open a child regular file `name` inside the opened `parent` directory
42    /// into `context`, without following symbolic links.
43    fn lookup_file_entry(
44        &self,
45        _parent: &Context,
46        _name: &str,
47        _context: &mut Context,
48        _flags: Flags,
49    ) -> Result<()> {
50        Err(crate::IoErrorKind::Unsupported)
51    }
52
53    /// Create a child directory `name` inside the opened `parent` directory,
54    /// persisting `attributes` with the new entry where the backend can.
55    fn create_directory_entry(
56        &self,
57        _parent: &Context,
58        _name: &str,
59        _attributes: &Attributes,
60    ) -> Result<()> {
61        Err(crate::IoErrorKind::Unsupported)
62    }
63
64    /// Create a child regular file `name` inside the opened `parent` directory,
65    /// persisting `attributes` with the new entry where the backend can.
66    fn create_file_entry(
67        &self,
68        _parent: &Context,
69        _name: &str,
70        _attributes: &Attributes,
71    ) -> Result<()> {
72        Err(crate::IoErrorKind::Unsupported)
73    }
74
75    /// Remove a child entry `name` inside the opened `parent` directory
76    /// without following symbolic links.
77    fn remove_entry(&self, _parent: &Context, _name: &str) -> Result<()> {
78        Err(crate::IoErrorKind::Unsupported)
79    }
80
81    /// Rename `source_name` inside `source_parent` to `destination_name` inside
82    /// `destination_parent` without following symbolic links.
83    fn rename_entry(
84        &self,
85        _source_parent: &Context,
86        _source_name: &str,
87        _destination_parent: &Context,
88        _destination_name: &str,
89    ) -> Result<()> {
90        Err(crate::IoErrorKind::Unsupported)
91    }
92
93    /// Create `new_name` inside `new_parent` as a hard link to `existing_name`
94    /// inside `existing_parent` without following symbolic links.
95    fn link_entry(
96        &self,
97        _existing_parent: &Context,
98        _existing_name: &str,
99        _new_parent: &Context,
100        _new_name: &str,
101    ) -> Result<()> {
102        Err(crate::IoErrorKind::Unsupported)
103    }
104
105    /// Create a symbolic link named `name` inside the opened `parent`
106    /// directory pointing to `target`, persisting `attributes` with the new
107    /// entry where the backend can.
108    fn create_symlink_entry(
109        &self,
110        _target: &Path,
111        _parent: &Context,
112        _name: &str,
113        _attributes: &Attributes,
114    ) -> Result<()> {
115        Err(crate::IoErrorKind::Unsupported)
116    }
117
118    /// Read the target of symbolic link `name` inside the opened `parent`
119    /// directory into `buffer` without following it.
120    fn read_symlink_entry(
121        &self,
122        _parent: &Context,
123        _name: &str,
124        _buffer: &mut [u8],
125    ) -> Result<usize> {
126        Err(crate::IoErrorKind::Unsupported)
127    }
128
129    /// Populate `attributes` for child entry `name` inside the opened `parent`
130    /// directory without following symbolic links.
131    fn get_entry_attributes(
132        &self,
133        _parent: &Context,
134        _name: &str,
135        _attributes: &mut Attributes,
136    ) -> Result<()> {
137        Err(crate::IoErrorKind::Unsupported)
138    }
139
140    /// Update `attributes` for child entry `name` inside the opened `parent`
141    /// directory without following symbolic links.
142    fn set_entry_attributes(
143        &self,
144        _parent: &Context,
145        _name: &str,
146        _attributes: &Attributes,
147    ) -> Result<()> {
148        Err(crate::IoErrorKind::Unsupported)
149    }
150
151    /// Create a symbolic link without resolving its target, persisting
152    /// `attributes` with the new entry where the backend can. Backends that do
153    /// not support native links or a durable Xila link representation may keep
154    /// the default implementation.
155    fn create_symlink(&self, _target: &Path, _link: &Path, _attributes: &Attributes) -> Result<()> {
156        Err(crate::IoErrorKind::Unsupported)
157    }
158
159    /// Create `new` as an additional directory entry for the existing,
160    /// non-directory object at `existing`, sharing its data. Backends without
161    /// hard links (including LittleFS) keep the default implementation, which
162    /// reports [`crate::IoErrorKind::Unsupported`].
163    fn link(&self, _existing: &Path, _new: &Path) -> Result<()> {
164        Err(crate::IoErrorKind::Unsupported)
165    }
166
167    /// Copy the stored target of a symbolic link into a caller-owned buffer.
168    /// This operation must inspect the final directory entry without following it.
169    fn read_symlink(&self, _link: &Path, _buffer: &mut [u8]) -> Result<usize> {
170        Err(crate::IoErrorKind::Unsupported)
171    }
172
173    /// Return the fields this backend can accept through `set_attributes`.
174    ///
175    /// This is a capability hint for VFS-managed default metadata during file
176    /// creation and open. Explicit attribute mutations still call
177    /// `set_attributes` and receive the backend's normal errors. Existing
178    /// implementations default to the historical all-fields behavior.
179    fn writable_attributes(&self) -> crate::AttributeFlags {
180        crate::AttributeFlags::all()
181    }
182
183    /// Return the fields that are stored durably by this filesystem.
184    ///
185    /// The VFS uses this to select representations that rely on metadata
186    /// surviving an unmount and remount. A writable field is not necessarily
187    /// persistent (for example, a synthesized host attribute).
188    fn persistent_attributes(&self) -> crate::AttributeFlags {
189        crate::AttributeFlags::empty()
190    }
191
192    fn lookup_directory(&self, context: &mut Context, path: &Path) -> Result<()>;
193
194    fn lookup_file(&self, context: &mut Context, path: &Path, flags: Flags) -> Result<()>;
195
196    /// Create a directory at `path`, persisting `attributes` with the new
197    /// entry in the same commit as the entry creation where the backend can.
198    ///
199    /// `attributes.get_mask()` selects the fields to persist; callers pass the
200    /// mask already intersected with [`Self::writable_attributes`]. The backend
201    /// must apply or ignore the full mask at creation: the caller no longer
202    /// rewrites fields afterwards. An empty mask persists the backend defaults.
203    ///
204    /// LittleFS costs two commits for a directory: the entry commit, then the
205    /// attributes commit (`lfs_mkdir` has no attribute configuration).
206    fn create_directory(&self, path: &Path, attributes: &Attributes) -> Result<()>;
207
208    /// Create a regular file at `path`, persisting `attributes` with the new
209    /// entry in the same commit as the entry creation where the backend can.
210    ///
211    /// LittleFS costs two commits for a file: the entry commit, then the
212    /// struct+attributes commit, which carries the custom attributes
213    /// atomically with the file through `lfs_file_config.attrs`. See
214    /// [`Self::create_directory`] for the mask contract.
215    fn create_file(&self, path: &Path, attributes: &Attributes) -> Result<()>;
216
217    /// Remove a file or directory from the file system.
218    ///
219    /// Permanently deletes the specified file or directory. For directories,
220    /// they must be empty before they can be removed.
221    ///
222    /// # Arguments
223    ///
224    /// * `context` - File system context
225    /// * `path` - Path to the file or directory to remove
226    ///
227    /// # Returns
228    ///
229    /// * `Ok(())` - File or directory successfully removed
230    /// * `Err(IoErrorKind)` - Error during removal
231    ///
232    /// # Errors
233    ///
234    /// * [`crate::IoErrorKind::NotFound`] - File or directory doesn't exist
235    /// * [`crate::IoErrorKind::PermissionDenied`] - Insufficient permissions
236    /// * [`crate::IoErrorKind::DirectoryNotEmpty`] - Directory contains files
237    /// * [`crate::IoErrorKind::ResourceBusy`] - File is currently in use
238    fn remove(&self, path: &Path) -> Result<()>;
239
240    /// Rename or move a file or directory.
241    ///
242    /// Changes the name or location of a file or directory. This can be used
243    /// for both renaming within the same directory and moving between directories.
244    ///
245    /// # Arguments
246    ///
247    /// * `context` - File system context
248    /// * `source` - Current path of the file or directory
249    /// * `destination` - New path for the file or directory
250    ///
251    /// # Returns
252    ///
253    /// * `Ok(())` - File or directory successfully renamed/moved
254    /// * `Err(IoErrorKind)` - Error during rename operation
255    ///
256    /// # Errors
257    ///
258    /// * [`crate::IoErrorKind::NotFound`] - Source file doesn't exist
259    /// * [`crate::IoErrorKind::AlreadyExists`] - Destination already exists
260    /// * [`crate::IoErrorKind::PermissionDenied`] - Insufficient permissions
261    fn rename(&self, source: &Path, destination: &Path) -> Result<()>;
262
263    // - Directory
264
265    // - Statistics
266
267    /// Populate the requested attributes for a path.
268    ///
269    /// On entry, `attributes.get_mask()` selects the fields requested by the
270    /// caller. On success, the mask must contain only fields that were both
271    /// requested and populated with meaningful values. Backends may omit
272    /// unavailable fields; they must not fabricate values to satisfy a request.
273    /// An empty mask is a successful no-op.
274    fn get_attributes(&self, path: &Path, attributes: &mut Attributes) -> Result<()>;
275
276    /// Change the fields selected by `attributes.get_mask()` for a path.
277    ///
278    /// An empty mask is a successful no-op. If any requested field is
279    /// unsupported, the operation must return [`crate::IoErrorKind::Unsupported`]
280    /// before changing any supported field. A later backend I/O or permission
281    /// failure may occur after an earlier supported field was changed; this
282    /// operation does not promise rollback for such failures.
283    fn set_attributes(&self, path: &Path, attributes: &Attributes) -> Result<()>;
284}
285
286pub mod tests {
287    //! Generic test suite for file system operations.
288    //!
289    //! This module provides comprehensive tests for any implementation of the
290    //! `FileSystemOperations` trait. It includes tests for:
291    //!
292    //! - File operations (create, lookup, remove)
293    //! - Directory operations (create, lookup, remove, nested)
294    //! - Rename and move operations
295    //! - Attribute get/set operations
296    //! - Error handling and edge cases
297    //! - File system consistency
298    //! - Special cases (root directory, long names, special characters)
299    //!
300    //! # Usage
301    //!
302    //! ## Using the Macro (Recommended)
303    //!
304    //! The easiest way to test your file system implementation is to use the
305    //! `implement_file_system_tests!` macro, which generates individual test
306    //! functions for each test category:
307    //!
308    //! ```rust,ignore
309    //! use file_system::implement_file_system_tests;
310    //!
311    //! mod tests {
312    //!     use super::*;
313    //!     
314    //!     implement_file_system_tests! {
315    //!         instance: MyFileSystem::new()
316    //!     }
317    //! }
318    //! ```
319    //!
320    //! This will generate 32+ individual `#[test]` functions, each testing a specific
321    //! aspect of your file system implementation.
322    //!
323    //! ## Using Individual Test Functions
324    //!
325    //! You can also call individual test functions directly:
326    //!
327    //! ```rust,ignore
328    //! use file_system::operations::file_system::tests;
329    //!
330    //! #[test]
331    //! fn test_my_file_system() {
332    //!     let fs = MyFileSystem::new();
333    //!     
334    //!     // Run all tests
335    //!     tests::run_all_tests(&fs);
336    //!     
337    //!     // Or run individual test categories
338    //!     tests::test_file_operations(&fs);
339    //!     tests::test_directory_operations(&fs);
340    //!     tests::test_rename_operations(&fs);
341    //! }
342    //! ```
343    //!
344    //! # Test Categories
345    //!
346    //! ## File System Structure Tests
347    //! - `test_file_operations` - Basic file CRUD operations
348    //! - `test_directory_operations` - Basic directory operations
349    //! - `test_nested_directories` - Nested directory hierarchy
350    //! - `test_rename_operations` - File/directory rename and move
351    //! - `test_attribute_operations` - Metadata get/set operations
352    //!
353    //! ## File I/O Tests
354    //! - `test_file_read_operations` - Reading data from files
355    //! - `test_file_write_operations` - Writing data to files
356    //! - `test_file_write_pattern` - Pattern-based writing
357    //! - `test_file_write_vectored` - Vectored (scatter-gather) I/O
358    //! - `test_file_position_operations` - Position-based read/write
359    //! - `test_file_read_until` - Reading until delimiter
360    //! - `test_file_flush` - Flushing buffered data
361    //! - `test_large_file_operations` - Large file handling
362    //!
363    //! ## Directory I/O Tests
364    //! - `test_directory_read_operations` - Reading directory entries
365    //! - `test_directory_position_operations` - Directory position management
366    //! - `test_directory_rewind` - Rewinding directory stream
367    //! - `test_empty_directory_read` - Reading empty directories
368    //!
369    //! ## Error Handling & Edge Cases
370    //! - `test_error_handling` - Error case validation
371    //! - `test_file_system_consistency` - Consistency checks
372    //! - `test_root_directory_operations` - Root directory special cases
373    //! - `test_invalid_paths` - Invalid path handling
374    //!
375    //! ## Test Execution
376    //! - `implement_file_system_tests!` - Macro to generate all test functions (recommended)
377    //! - `run_all_tests` - Function to execute all test categories sequentially
378
379    use super::*;
380    use crate::{
381        AccessFlags, AttributeFlags, Attributes, BaseOperations, Context, IoErrorKind, Kind,
382        Permissions, Size, Time,
383    };
384    use users::{GroupIdentifier, UserIdentifier};
385
386    /// Attribute capabilities used by the generic test suite.
387    ///
388    /// This is test configuration only; it is not a runtime query on
389    /// [`FileSystemOperations`].
390    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
391    pub struct FileSystemTestCapabilities {
392        pub readable: AttributeFlags,
393        pub writable: AttributeFlags,
394    }
395
396    impl Default for FileSystemTestCapabilities {
397        fn default() -> Self {
398            Self {
399                readable: AttributeFlags::all(),
400                writable: AttributeFlags::all(),
401            }
402        }
403    }
404
405    /// Generic test suite for file system operations.
406    ///
407    /// This provides a comprehensive set of tests that can be used to verify
408    /// any implementation of the `FileSystemOperations` trait.
409    pub fn test_file_system_operations<F>(fs: &F)
410    where
411        F: FileSystemOperations,
412    {
413        test_file_operations(fs);
414        test_directory_operations(fs);
415        test_attribute_operations(fs);
416        test_error_handling(fs);
417    }
418
419    /// Test basic file operations: create, lookup, remove
420    pub fn test_file_operations<F>(fs: &F)
421    where
422        F: FileSystemOperations,
423    {
424        let test_file = Path::new("/test_file.txt");
425        let mut context = Context::new_empty();
426
427        // Test file creation
428        fs.create_file(test_file, &Attributes::new()).unwrap();
429
430        // Test file lookup
431        fs.lookup_file(&mut context, test_file, AccessFlags::Read.into())
432            .unwrap();
433
434        // Test file removal
435        fs.remove(test_file).unwrap();
436
437        // Test lookup after removal should fail
438        fs.lookup_file(&mut context, test_file, AccessFlags::Read.into())
439            .unwrap_err();
440    }
441
442    /// Test file creation with various edge cases
443    pub fn test_file_creation_edge_cases<F>(fs: &F)
444    where
445        F: FileSystemOperations,
446    {
447        // Test creating file that already exists
448        let test_file = Path::new("/duplicate.txt");
449        fs.create_file(test_file, &Attributes::new()).unwrap();
450
451        let result = fs.create_file(test_file, &Attributes::new());
452        assert!(
453            matches!(result, Err(IoErrorKind::AlreadyExists)),
454            "Creating duplicate file should return AlreadyExists error"
455        );
456
457        // Cleanup
458        fs.remove(test_file).unwrap();
459    }
460
461    /// Test directory operations: create, lookup, remove
462    pub fn test_directory_operations<F>(fs: &F)
463    where
464        F: FileSystemOperations,
465    {
466        let test_dir = Path::new("/test_directory");
467        let mut context = Context::new_empty();
468
469        // Test directory creation
470        fs.create_directory(test_dir, &Attributes::new()).unwrap();
471
472        // Test directory lookup
473        fs.lookup_directory(&mut context, test_dir).unwrap();
474
475        DirectoryOperations::close(fs, &mut context).unwrap();
476
477        // Test directory removal
478        fs.remove(test_dir).unwrap();
479
480        let mut context = Context::new_empty();
481
482        // Test lookup after removal should fail
483        fs.lookup_directory(&mut context, test_dir).unwrap_err();
484    }
485
486    /// Test nested directory operations
487    pub fn test_nested_directories<F>(fs: &F)
488    where
489        F: FileSystemOperations,
490    {
491        let parent_dir = Path::new("/parent");
492        let child_dir = Path::new("/parent/child");
493
494        // Create parent directory
495        fs.create_directory(parent_dir, &Attributes::new()).unwrap();
496
497        // Create child directory
498        fs.create_directory(child_dir, &Attributes::new()).unwrap();
499
500        // Try to remove parent with child (should fail)
501        let result = fs.remove(parent_dir);
502        assert!(
503            matches!(result, Err(IoErrorKind::DirectoryNotEmpty)),
504            "Removing non-empty directory should fail with DirectoryNotEmpty"
505        );
506
507        // Remove child first
508        fs.remove(child_dir).unwrap();
509
510        // Now parent removal should succeed
511        fs.remove(parent_dir).unwrap();
512    }
513
514    /// Test rename/move operations
515    pub fn test_rename_operations<F>(fs: &F)
516    where
517        F: FileSystemOperations,
518    {
519        let source = Path::new("/source_file.txt");
520        let destination = Path::new("/destination_file.txt");
521        let mut context = Context::new_empty();
522
523        // Create source file
524        fs.create_file(source, &Attributes::new()).unwrap();
525
526        // Test rename
527        fs.rename(source, destination).unwrap();
528
529        // Verify source no longer exists
530        fs.lookup_file(&mut context, source, AccessFlags::Read.into())
531            .unwrap_err();
532
533        // Verify destination exists
534        assert!(
535            fs.lookup_file(&mut context, destination, AccessFlags::Read.into())
536                .is_ok(),
537            "Destination file should exist after rename"
538        );
539
540        // Cleanup
541        fs.remove(destination).unwrap();
542    }
543
544    /// Test rename edge cases
545    pub fn test_rename_edge_cases<F>(fs: &F)
546    where
547        F: FileSystemOperations,
548    {
549        let source = Path::new("/rename_source.txt");
550        let destination = Path::new("/rename_dest.txt");
551
552        // Test renaming non-existent file
553        let result = fs.rename(source, destination);
554        assert_eq!(result, Err(IoErrorKind::NotFound),);
555
556        // Create both files
557        fs.create_file(source, &Attributes::new()).unwrap();
558        fs.create_file(destination, &Attributes::new()).unwrap();
559
560        // Test renaming to existing file
561        //let _ = fs.rename(source, destination);
562        //assert_eq!(
563        //    result,
564        //    Err(IoErrorKind::AlreadyExists),
565        //);
566
567        // Cleanup
568        fs.remove(source).unwrap();
569        fs.remove(destination).unwrap();
570    }
571
572    /// Test moving files between directories
573    pub fn test_move_between_directories<F>(fs: &F)
574    where
575        F: FileSystemOperations,
576    {
577        let dir1 = Path::new("/dir1");
578        let dir2 = Path::new("/dir2");
579        let file_in_dir1 = Path::new("/dir1/file.txt");
580        let file_in_dir2 = Path::new("/dir2/file.txt");
581
582        // Create directories
583        fs.create_directory(dir1, &Attributes::new()).unwrap();
584        fs.create_directory(dir2, &Attributes::new()).unwrap();
585
586        // Create file in dir1
587        fs.create_file(file_in_dir1, &Attributes::new()).unwrap();
588
589        // Move file to dir2
590        fs.rename(file_in_dir1, file_in_dir2).unwrap();
591
592        // Verify file is in dir2
593        let mut context = Context::new_empty();
594        fs.lookup_file(&mut context, file_in_dir2, AccessFlags::Read.into())
595            .unwrap();
596
597        // Cleanup
598        fs.remove(file_in_dir2).unwrap();
599        fs.remove(dir2).unwrap();
600        fs.remove(dir1).unwrap();
601    }
602
603    /// Test attribute get/set operations
604    pub fn test_attribute_operations<F>(fs: &F)
605    where
606        F: FileSystemOperations,
607    {
608        test_attribute_operations_with_capabilities(fs, FileSystemTestCapabilities::default());
609    }
610
611    /// Test attribute operations for a backend with explicitly configured
612    /// readable and writable fields.
613    pub fn test_attribute_operations_with_capabilities<F>(
614        fs: &F,
615        capabilities: FileSystemTestCapabilities,
616    ) where
617        F: FileSystemOperations,
618    {
619        let test_file = Path::new("/attr_test.txt");
620        fs.create_file(test_file, &Attributes::new()).unwrap();
621
622        let writable = capabilities.writable.intersection(AttributeFlags::all());
623        let readable = capabilities.readable.intersection(AttributeFlags::all());
624        let expected = Attributes::new()
625            .set_size(0)
626            .set_permissions(Permissions::ALL_READ_WRITE)
627            .set_kind(Kind::File)
628            .set_user(UserIdentifier::new(42))
629            .set_group(GroupIdentifier::new(43))
630            .set_inode(42)
631            .set_creation(Time::new(1))
632            .set_modification(Time::new(2))
633            .set_access(Time::new(3))
634            .set_status(Time::new(4));
635
636        let mut requested_write = expected.clone().set_mask(writable);
637        FileSystemOperations::set_attributes(fs, test_file, &requested_write).unwrap();
638
639        // Empty masks are no-ops.
640        requested_write = requested_write.set_mask(AttributeFlags::empty());
641        FileSystemOperations::set_attributes(fs, test_file, &requested_write).unwrap();
642
643        let mut actual = Attributes::new().set_mask(readable);
644        FileSystemOperations::get_attributes(fs, test_file, &mut actual).unwrap();
645        assert_eq!(
646            actual.get_mask(),
647            readable,
648            "backend returned an inaccurate attribute mask"
649        );
650        assert_attribute_values(&expected, &actual, readable.intersection(writable));
651        if readable.contains(AttributeFlags::Size) {
652            assert_eq!(
653                actual.get_size(),
654                Some(&0),
655                "new file should have size zero"
656            );
657        }
658
659        let subset = readable.intersection(AttributeFlags::Kind | AttributeFlags::Size);
660        if !subset.is_empty() {
661            let mut subset_result = Attributes::new().set_mask(subset);
662            FileSystemOperations::get_attributes(fs, test_file, &mut subset_result).unwrap();
663            assert_eq!(
664                subset_result.get_mask(),
665                subset,
666                "backend ignored the requested read mask"
667            );
668            if subset.contains(AttributeFlags::Kind) {
669                assert_eq!(subset_result.get_kind(), Some(&Kind::File));
670            }
671            if subset.contains(AttributeFlags::Size) {
672                assert_eq!(subset_result.get_size(), Some(&0));
673            }
674        }
675
676        let unsupported = AttributeFlags::all().difference(writable);
677        if !unsupported.is_empty() {
678            let changed = Attributes::new()
679                .set_permissions(Permissions::NONE)
680                .set_kind(Kind::Directory)
681                .set_user(UserIdentifier::ROOT)
682                .set_group(GroupIdentifier::ROOT)
683                .set_inode(99)
684                .set_creation(Time::new(11))
685                .set_modification(Time::new(12))
686                .set_access(Time::new(13))
687                .set_status(Time::new(14))
688                .set_mask(AttributeFlags::all());
689            assert!(matches!(
690                FileSystemOperations::set_attributes(fs, test_file, &changed),
691                Err(IoErrorKind::Unsupported)
692            ));
693
694            let mut after_rejection = Attributes::new().set_mask(readable);
695            FileSystemOperations::get_attributes(fs, test_file, &mut after_rejection).unwrap();
696            assert_eq!(after_rejection.get_mask(), readable);
697            assert_attribute_values(&expected, &after_rejection, readable.intersection(writable));
698        }
699
700        fs.remove(test_file).unwrap();
701    }
702
703    fn assert_attribute_values(expected: &Attributes, actual: &Attributes, mask: AttributeFlags) {
704        macro_rules! assert_field {
705            ($flag:expr, $getter:ident) => {
706                if mask.contains($flag) {
707                    assert_eq!(actual.$getter(), expected.$getter());
708                }
709            };
710        }
711
712        assert_field!(AttributeFlags::Inode, get_inode);
713        assert_field!(AttributeFlags::Kind, get_kind);
714        assert_field!(AttributeFlags::Size, get_size);
715        assert_field!(AttributeFlags::Links, get_links);
716        assert_field!(AttributeFlags::CreationTime, get_creation);
717        assert_field!(AttributeFlags::ModificationTime, get_modification);
718        assert_field!(AttributeFlags::AccessTime, get_access);
719        assert_field!(AttributeFlags::StatusTime, get_status);
720        assert_field!(AttributeFlags::Permissions, get_permissions);
721        assert_field!(AttributeFlags::User, get_user);
722        assert_field!(AttributeFlags::Group, get_group);
723    }
724
725    /// Test attribute operations on directories
726    pub fn test_directory_attributes<F>(fs: &F)
727    where
728        F: FileSystemOperations,
729    {
730        let test_dir = Path::new("/attr_dir");
731
732        // Create test directory
733        fs.create_directory(test_dir, &Attributes::new()).unwrap();
734
735        // Get directory attributes
736        let mut attrs = Attributes::new().set_mask(AttributeFlags::Kind);
737        FileSystemOperations::get_attributes(fs, test_dir, &mut attrs).unwrap();
738
739        // Verify it's a directory
740        if let Some(kind) = attrs.get_kind() {
741            assert_eq!(*kind, Kind::Directory, "Should be a directory type");
742        }
743
744        // Cleanup
745        fs.remove(test_dir).unwrap();
746    }
747
748    /// Test error handling for various scenarios
749    pub fn test_error_handling<F>(fs: &F)
750    where
751        F: FileSystemOperations,
752    {
753        let mut context = Context::new_empty();
754
755        // Test NotFound errors
756        let nonexistent = Path::new("/nonexistent.txt");
757        fs.lookup_file(&mut context, nonexistent, AccessFlags::Read.into())
758            .unwrap_err();
759
760        assert!(
761            fs.remove(nonexistent).is_err(),
762            "Should return error when removing non-existent file"
763        );
764
765        // Test getting attributes of non-existent file
766        let mut attrs = Attributes::new().set_mask(AttributeFlags::all());
767        FileSystemOperations::get_attributes(fs, nonexistent, &mut attrs).unwrap_err();
768    }
769
770    /// Test invalid path handling
771    pub fn test_invalid_paths<F>(fs: &F)
772    where
773        F: FileSystemOperations,
774    {
775        // Note: Path validation typically happens at Path::new(),
776        // but we test file system behavior with edge cases
777
778        // Test empty filename (directory operations might handle this differently)
779        let path = Path::new("/.txt");
780        // If path is valid, file system should handle it appropriately
781        let file_result = fs.create_file(path, &Attributes::new());
782        // Result depends on implementation - may succeed or fail
783        if file_result.is_ok() {
784            fs.remove(path).unwrap();
785        }
786    }
787
788    /// Test concurrent operations (if file system supports it)
789    pub fn test_multiple_operations<F>(fs: &F)
790    where
791        F: FileSystemOperations,
792    {
793        // Create multiple files
794        let files = [
795            "/multi_test_1.txt",
796            "/multi_test_2.txt",
797            "/multi_test_3.txt",
798        ];
799
800        for file_path in &files {
801            let path = Path::new(file_path);
802            fs.create_file(path, &Attributes::new()).unwrap();
803        }
804
805        // Verify all files exist
806        for file_path in &files {
807            let path = Path::new(file_path);
808            let mut context = Context::new_empty();
809            fs.lookup_file(&mut context, path, AccessFlags::Read.into())
810                .unwrap();
811            BaseOperations::close(fs, &mut context).unwrap();
812        }
813
814        // Remove all files
815        for file_path in &files {
816            let path = Path::new(file_path);
817            fs.remove(path).unwrap();
818        }
819    }
820
821    /// Test file system consistency
822    pub fn test_file_system_consistency<F>(fs: &F)
823    where
824        F: FileSystemOperations,
825    {
826        let dir = Path::new("/consistency_test");
827        let file = Path::new("/consistency_test/file.txt");
828
829        // Create directory and file
830        fs.create_directory(dir, &Attributes::new()).unwrap();
831        fs.create_file(file, &Attributes::new()).unwrap();
832
833        // Attempt to create file with same name as directory should fail
834        let result = fs.create_file(dir, &Attributes::new());
835        result.unwrap_err();
836
837        // Attempt to create directory with same name as file should fail
838        let result = fs.create_directory(file, &Attributes::new());
839        result.unwrap_err();
840
841        // Cleanup
842        fs.remove(file).unwrap();
843        fs.remove(dir).unwrap();
844    }
845
846    /// Test file lookup with different flags
847    pub fn test_lookup_with_flags<F>(fs: &F)
848    where
849        F: FileSystemOperations,
850    {
851        let test_file = Path::new("/flags_test.txt");
852        let mut context = Context::new_empty();
853
854        fs.create_file(test_file, &Attributes::new()).unwrap();
855
856        // Test with different flag combinations
857        fs.lookup_file(&mut context, test_file, AccessFlags::Read.into())
858            .unwrap();
859        let mut context = Context::new_empty();
860
861        fs.lookup_file(&mut context, test_file, AccessFlags::Write.into())
862            .unwrap();
863        let mut context = Context::new_empty();
864
865        fs.lookup_file(&mut context, test_file, AccessFlags::READ_WRITE.into())
866            .unwrap();
867
868        // Cleanup
869        fs.remove(test_file).unwrap();
870    }
871
872    /// Test operations on root directory
873    pub fn test_root_directory_operations<F>(fs: &F)
874    where
875        F: FileSystemOperations,
876    {
877        let root = Path::new("/");
878        let mut context = Context::new_empty();
879
880        // Root should always exist
881        fs.lookup_directory(&mut context, root).unwrap();
882
883        // Should not be able to remove root
884        let result = fs.remove(root);
885        result.unwrap_err();
886
887        // Should be able to get root attributes
888        let mut attrs = Attributes::new().set_mask(AttributeFlags::all());
889        FileSystemOperations::get_attributes(fs, root, &mut attrs).unwrap();
890    }
891
892    /// Test long file names
893    pub fn test_long_filenames<F>(fs: &F)
894    where
895        F: FileSystemOperations,
896    {
897        // Create a reasonably long filename
898        let long_name = "/this_is_a_very_long_filename_that_tests_the_limits.txt";
899        let path = Path::new(long_name);
900
901        let result = fs.create_file(path, &Attributes::new());
902        // May succeed or fail depending on file system limits
903        if result.is_ok() {
904            fs.remove(path).unwrap();
905        }
906    }
907
908    /// Test special characters in filenames
909    pub fn test_special_characters_in_names<F>(fs: &F)
910    where
911        F: FileSystemOperations,
912    {
913        let special_chars = [
914            "/file-with-dash.txt",
915            "/file_with_underscore.txt",
916            "/file.multiple.dots.txt",
917        ];
918
919        for name in &special_chars {
920            let path = Path::new(name);
921            let result = fs.create_file(path, &Attributes::new());
922            if result.is_ok() {
923                fs.remove(path).unwrap();
924            }
925        }
926    }
927
928    /// Test file read operations (when FileOperations::read is available)
929    pub fn test_file_read_operations<F>(fs: &F)
930    where
931        F: FileSystemOperations,
932    {
933        use crate::BaseOperations;
934
935        let test_file = Path::new("/read_test.txt");
936        let mut context = Context::new_empty();
937
938        // Create and open file for writing
939        fs.create_file(test_file, &Attributes::new()).unwrap();
940        fs.lookup_file(&mut context, test_file, AccessFlags::Write.into())
941            .unwrap();
942
943        // Write test data
944        let test_data = b"Hello, File System!";
945        let write_result = fs.write_sync(&mut context, test_data, 0);
946        write_result.as_ref().unwrap();
947        assert_eq!(
948            write_result.unwrap(),
949            test_data.len(),
950            "Should write all bytes"
951        );
952
953        // Close and reopen for reading
954        BaseOperations::close(fs, &mut context).unwrap();
955        fs.lookup_file(&mut context, test_file, AccessFlags::Read.into())
956            .unwrap();
957
958        // Read data back
959        let mut buffer = alloc::vec![0u8; test_data.len()];
960        let read_result = BaseOperations::read_sync(fs, &mut context, &mut buffer, 0);
961        read_result.as_ref().unwrap();
962        assert_eq!(
963            read_result.unwrap(),
964            test_data.len(),
965            "Should read all bytes"
966        );
967        assert_eq!(
968            &buffer[..],
969            test_data,
970            "Read data should match written data"
971        );
972
973        // Cleanup
974        BaseOperations::close(fs, &mut context).unwrap();
975        fs.remove(test_file).unwrap();
976    }
977
978    /// Test file write operations with various patterns
979    pub fn test_file_write_operations<F>(fs: &F)
980    where
981        F: FileSystemOperations,
982    {
983        use crate::BaseOperations;
984
985        let test_file = Path::new("/write_test.txt");
986        let mut context = Context::new_empty();
987
988        fs.create_file(test_file, &Attributes::new()).unwrap();
989        fs.lookup_file(&mut context, test_file, AccessFlags::Write.into())
990            .unwrap();
991
992        // Test single write
993        let data1 = b"First write. ";
994        let result = BaseOperations::write_sync(fs, &mut context, data1, 0);
995        result.unwrap();
996
997        // Test sequential write
998        let data2 = b"Second write.";
999        let result = BaseOperations::write_sync(fs, &mut context, data2, data1.len() as Size);
1000        result.unwrap();
1001
1002        // Test overwrite
1003        let overwrite_data = b"OVERWRITE";
1004        let result = BaseOperations::write_sync(fs, &mut context, overwrite_data, 0);
1005        result.unwrap();
1006
1007        // Cleanup
1008        BaseOperations::close(fs, &mut context).unwrap();
1009        fs.remove(test_file).unwrap();
1010    }
1011
1012    /// Test file write pattern operations
1013    pub fn test_file_write_pattern<F>(fs: &F)
1014    where
1015        F: FileSystemOperations,
1016    {
1017        use crate::BaseOperations;
1018
1019        let test_file = Path::new("/pattern_test.txt");
1020        let mut context = Context::new_empty();
1021
1022        fs.create_file(test_file, &Attributes::new()).unwrap();
1023        fs.lookup_file(&mut context, test_file, AccessFlags::Write.into())
1024            .unwrap();
1025
1026        // Write a pattern multiple times
1027        let pattern = b"ABC";
1028        let count = 5;
1029        let result = BaseOperations::write_pattern_sync(fs, &mut context, pattern, count, 0);
1030
1031        if let Ok(bytes_written) = result {
1032            assert!(
1033                bytes_written <= pattern.len() * count,
1034                "Should not write more than requested"
1035            );
1036
1037            // Read back and verify pattern
1038            BaseOperations::close(fs, &mut context).unwrap();
1039            fs.lookup_file(&mut context, test_file, AccessFlags::Read.into())
1040                .unwrap();
1041
1042            let mut buffer = alloc::vec![0u8; bytes_written];
1043            let read_result = BaseOperations::read_sync(fs, &mut context, &mut buffer, 0);
1044            read_result.unwrap();
1045        }
1046
1047        // Cleanup
1048        BaseOperations::close(fs, &mut context).unwrap();
1049        fs.remove(test_file).unwrap();
1050    }
1051
1052    /// Test file write vectored operations
1053    pub fn test_file_write_vectored<F>(fs: &F)
1054    where
1055        F: FileSystemOperations,
1056    {
1057        use crate::BaseOperations;
1058
1059        let test_file = Path::new("/vectored_test.txt");
1060        let mut context = Context::new_empty();
1061
1062        fs.create_file(test_file, &Attributes::new()).unwrap();
1063        fs.lookup_file(&mut context, test_file, AccessFlags::Write.into())
1064            .unwrap();
1065
1066        // Write multiple buffers at once
1067        let buf1 = b"First ";
1068        let buf2 = b"Second ";
1069        let buf3 = b"Third";
1070        let buffers = [buf1.as_slice(), buf2.as_slice(), buf3.as_slice()];
1071
1072        let result = BaseOperations::write_vectored_sync(fs, &mut context, &buffers, 0);
1073        if let Ok(total_written) = result {
1074            let expected_total = buf1.len() + buf2.len() + buf3.len();
1075            assert!(
1076                total_written <= expected_total,
1077                "Should write all buffers or partial"
1078            );
1079
1080            // Read back and verify
1081            BaseOperations::close(fs, &mut context).unwrap();
1082            fs.lookup_file(&mut context, test_file, AccessFlags::Read.into())
1083                .unwrap();
1084
1085            let mut buffer = alloc::vec![0u8; total_written];
1086            let read_result = BaseOperations::read_sync(fs, &mut context, &mut buffer, 0);
1087            read_result.unwrap();
1088        }
1089
1090        // Cleanup
1091        BaseOperations::close(fs, &mut context).unwrap();
1092        fs.remove(test_file).unwrap();
1093    }
1094
1095    /// Test file read/write at specific positions
1096    pub fn test_file_position_operations<F>(fs: &F)
1097    where
1098        F: FileSystemOperations,
1099    {
1100        use crate::BaseOperations;
1101
1102        let test_file = Path::new("/position_test.txt");
1103        let mut context = Context::new_empty();
1104
1105        fs.create_file(test_file, &Attributes::new()).unwrap();
1106        fs.lookup_file(&mut context, test_file, AccessFlags::READ_WRITE.into())
1107            .unwrap();
1108
1109        // Write data at different positions
1110        let data1 = b"AAAA";
1111        let data2 = b"BBBB";
1112        let data3 = b"CCCC";
1113
1114        BaseOperations::write_sync(fs, &mut context, data1, 0).unwrap();
1115        BaseOperations::write_sync(fs, &mut context, data2, 4).unwrap();
1116        BaseOperations::write_sync(fs, &mut context, data3, 8).unwrap();
1117
1118        // Read from specific positions
1119        let mut buffer = alloc::vec![0u8; 4];
1120
1121        let result = BaseOperations::read_sync(fs, &mut context, &mut buffer, 0);
1122        result.unwrap();
1123        assert_eq!(&buffer[..], b"AAAA", "Should read first chunk");
1124
1125        let result = BaseOperations::read_sync(fs, &mut context, &mut buffer, 4);
1126        result.unwrap();
1127        assert_eq!(&buffer[..], b"BBBB", "Should read second chunk");
1128
1129        let result = BaseOperations::read_sync(fs, &mut context, &mut buffer, 8);
1130        result.unwrap();
1131        assert_eq!(&buffer[..], b"CCCC", "Should read third chunk");
1132
1133        // Cleanup
1134        BaseOperations::close(fs, &mut context).unwrap();
1135        fs.remove(test_file).unwrap();
1136    }
1137
1138    /// Test file read until delimiter
1139    pub fn test_file_read_until<F>(fs: &F)
1140    where
1141        F: FileSystemOperations,
1142    {
1143        use crate::BaseOperations;
1144
1145        let test_file = Path::new("/read_until_test.txt");
1146        let mut context = Context::new_empty();
1147
1148        fs.create_file(test_file, &Attributes::new()).unwrap();
1149        fs.lookup_file(&mut context, test_file, AccessFlags::READ_WRITE.into())
1150            .unwrap();
1151
1152        // Write data with delimiter
1153        let test_data = b"Line 1\nLine 2\nLine 3\n";
1154        BaseOperations::write_sync(fs, &mut context, test_data, 0).unwrap();
1155
1156        // Read until newline
1157        let mut buffer = alloc::vec![0u8; 100];
1158        let result = BaseOperations::read_until_sync(fs, &mut context, &mut buffer, 0, b"\n");
1159
1160        if let Ok(bytes_read) = result {
1161            assert!(bytes_read > 0, "Should read some bytes");
1162            assert!(bytes_read <= 7, "Should stop at first newline");
1163        }
1164
1165        // Cleanup
1166        BaseOperations::close(fs, &mut context).unwrap();
1167        fs.remove(test_file).unwrap();
1168    }
1169
1170    /// Test file flush operation
1171    pub fn test_file_flush<F>(fs: &F)
1172    where
1173        F: FileSystemOperations,
1174    {
1175        use crate::BaseOperations;
1176
1177        let test_file = Path::new("/flush_test.txt");
1178        let mut context = Context::new_empty();
1179
1180        fs.create_file(test_file, &Attributes::new()).unwrap();
1181        fs.lookup_file(&mut context, test_file, AccessFlags::Write.into())
1182            .unwrap();
1183
1184        // Write data
1185        let data = b"Data to flush";
1186        BaseOperations::write_sync(fs, &mut context, data, 0).unwrap();
1187
1188        // Flush should succeed or be unsupported
1189        let result = BaseOperations::flush_sync(fs, &mut context);
1190        assert!(
1191            result.is_ok() || matches!(result, Err(IoErrorKind::Unsupported)),
1192            "Flush should succeed or be unsupported"
1193        );
1194
1195        // Cleanup
1196        BaseOperations::close(fs, &mut context).unwrap();
1197        fs.remove(test_file).unwrap();
1198    }
1199
1200    /// Test empty file operations
1201    pub fn test_empty_file_operations<F>(fs: &F)
1202    where
1203        F: FileSystemOperations,
1204    {
1205        use crate::BaseOperations;
1206
1207        let test_file = Path::new("/empty_test.txt");
1208        let mut context = Context::new_empty();
1209
1210        fs.create_file(test_file, &Attributes::new()).unwrap();
1211        fs.lookup_file(&mut context, test_file, AccessFlags::Read.into())
1212            .unwrap();
1213
1214        // Try to read from empty file
1215        let mut buffer = alloc::vec![0u8; 100];
1216        let result = BaseOperations::read_sync(fs, &mut context, &mut buffer, 0);
1217
1218        // Should either read 0 bytes or return an error
1219        if let Ok(bytes_read) = result {
1220            assert_eq!(bytes_read, 0, "Should read 0 bytes from empty file");
1221        }
1222
1223        // Cleanup
1224        BaseOperations::close(fs, &mut context).unwrap();
1225        fs.remove(test_file).unwrap();
1226    }
1227
1228    /// Test large file operations
1229    pub fn test_large_file_operations<F>(fs: &F)
1230    where
1231        F: FileSystemOperations,
1232    {
1233        use crate::BaseOperations;
1234
1235        let test_file = Path::new("/large_test.txt");
1236        let mut context = Context::new_empty();
1237
1238        fs.create_file(test_file, &Attributes::new()).unwrap();
1239        fs.lookup_file(&mut context, test_file, AccessFlags::READ_WRITE.into())
1240            .unwrap();
1241
1242        // Write a larger amount of data
1243        let large_data = alloc::vec![0xABu8; 4096];
1244        let write_result = BaseOperations::write_sync(fs, &mut context, &large_data, 0);
1245
1246        if let Ok(bytes_written) = write_result {
1247            // Read back the data
1248            let mut read_buffer = alloc::vec![0u8; bytes_written];
1249            let read_result = BaseOperations::read_sync(fs, &mut context, &mut read_buffer, 0);
1250
1251            if let Ok(bytes_read) = read_result {
1252                assert_eq!(
1253                    bytes_read, bytes_written,
1254                    "Should read back same amount written"
1255                );
1256                assert_eq!(
1257                    &read_buffer[..bytes_read],
1258                    &large_data[..bytes_written],
1259                    "Read data should match written data"
1260                );
1261            }
1262        }
1263
1264        // Cleanup
1265        BaseOperations::close(fs, &mut context).unwrap();
1266        fs.remove(test_file).unwrap();
1267    }
1268
1269    /// Test directory read operations
1270    pub fn test_directory_read_operations<F>(fs: &F)
1271    where
1272        F: FileSystemOperations,
1273    {
1274        let test_dir = Path::new("/read_dir_test");
1275        let file1 = Path::new("/read_dir_test/file1.txt");
1276        let file2 = Path::new("/read_dir_test/file2.txt");
1277        let file3 = Path::new("/read_dir_test/file3.txt");
1278        let mut context = Context::new_empty();
1279
1280        // Create directory and files
1281        fs.create_directory(test_dir, &Attributes::new()).unwrap();
1282        fs.create_file(file1, &Attributes::new()).unwrap();
1283        fs.create_file(file2, &Attributes::new()).unwrap();
1284        fs.create_file(file3, &Attributes::new()).unwrap();
1285
1286        // Open directory for reading
1287        fs.lookup_directory(&mut context, test_dir).unwrap();
1288
1289        // Read directory entries
1290        let mut entry_count = 0;
1291        let mut found_files = alloc::vec::Vec::new();
1292
1293        loop {
1294            let result = DirectoryOperations::read(fs, &mut context);
1295            match result {
1296                Ok(Some(entry)) => {
1297                    entry_count += 1;
1298                    found_files.push(entry.name.clone());
1299                }
1300                Ok(None) => break, // End of directory
1301                Err(_) => break,   // Error reading
1302            }
1303
1304            // Safety limit to prevent infinite loops
1305            if entry_count > 100 {
1306                break;
1307            }
1308        }
1309
1310        // Should find at least the files we created (may also include . and ..)
1311        assert!(entry_count >= 3, "Should find at least the 3 created files");
1312
1313        // Cleanup
1314        DirectoryOperations::close(fs, &mut context).unwrap();
1315        fs.remove(file1).unwrap();
1316        fs.remove(file2).unwrap();
1317        fs.remove(file3).unwrap();
1318        fs.remove(test_dir).unwrap();
1319    }
1320
1321    /// Test directory position operations
1322    pub fn test_directory_position_operations<F>(fs: &F)
1323    where
1324        F: FileSystemOperations,
1325    {
1326        let test_dir = Path::new("/pos_dir_test");
1327        let file1 = Path::new("/pos_dir_test/a.txt");
1328        let file2 = Path::new("/pos_dir_test/b.txt");
1329        let mut context = Context::new_empty();
1330
1331        // Create directory and files
1332        fs.create_directory(test_dir, &Attributes::new()).unwrap();
1333        fs.create_file(file1, &Attributes::new()).unwrap();
1334        fs.create_file(file2, &Attributes::new()).unwrap();
1335
1336        // Open directory
1337        fs.lookup_directory(&mut context, test_dir).unwrap();
1338
1339        // Read first entry
1340        let first_result = DirectoryOperations::read(fs, &mut context);
1341        first_result.unwrap();
1342
1343        // Get position
1344        let pos_result = fs.get_position(&mut context);
1345        if pos_result.is_ok() {
1346            // Set position back to start
1347            let set_result = DirectoryOperations::set_position(fs, &mut context, 0);
1348            assert!(
1349                set_result.is_ok() || matches!(set_result, Err(IoErrorKind::Unsupported)),
1350                "Should set position or be unsupported"
1351            );
1352        }
1353
1354        // Test rewind
1355        let rewind_result = fs.rewind(&mut context);
1356        assert!(
1357            rewind_result.is_ok() || matches!(rewind_result, Err(IoErrorKind::Unsupported)),
1358            "Should rewind or be unsupported"
1359        );
1360
1361        // Cleanup
1362        DirectoryOperations::close(fs, &mut context).unwrap();
1363        fs.remove(file1).unwrap();
1364        fs.remove(file2).unwrap();
1365        fs.remove(test_dir).unwrap();
1366    }
1367
1368    /// Test directory rewind and re-read
1369    pub fn test_directory_rewind<F>(fs: &F)
1370    where
1371        F: FileSystemOperations,
1372    {
1373        let test_dir = Path::new("/rewind_test");
1374        let file = Path::new("/rewind_test/file.txt");
1375        let mut context = Context::new_empty();
1376
1377        // Create directory and file
1378        fs.create_directory(test_dir, &Attributes::new()).unwrap();
1379        fs.create_file(file, &Attributes::new()).unwrap();
1380
1381        // Open directory
1382        fs.lookup_directory(&mut context, test_dir).unwrap();
1383
1384        // Read all entries
1385        let mut first_pass_count = 0;
1386        while let Ok(Some(_)) = DirectoryOperations::read(fs, &mut context) {
1387            first_pass_count += 1;
1388            if first_pass_count > 100 {
1389                break;
1390            }
1391        }
1392
1393        // Rewind
1394        if fs.rewind(&mut context).is_ok() {
1395            // Read again
1396            let mut second_pass_count = 0;
1397            while let Ok(Some(_)) = DirectoryOperations::read(fs, &mut context) {
1398                second_pass_count += 1;
1399                if second_pass_count > 100 {
1400                    break;
1401                }
1402            }
1403
1404            assert_eq!(
1405                first_pass_count, second_pass_count,
1406                "Should read same number of entries after rewind"
1407            );
1408        }
1409
1410        // Cleanup
1411        DirectoryOperations::close(fs, &mut context).unwrap();
1412        fs.remove(file).unwrap();
1413        fs.remove(test_dir).unwrap();
1414    }
1415
1416    /// Test reading empty directory
1417    pub fn test_empty_directory_read<F>(fs: &F)
1418    where
1419        F: FileSystemOperations,
1420    {
1421        let test_dir = Path::new("/empty_dir");
1422        let mut context = Context::new_empty();
1423
1424        fs.create_directory(test_dir, &Attributes::new()).unwrap();
1425        fs.lookup_directory(&mut context, test_dir).unwrap();
1426
1427        // Read from empty directory (may have . and .. entries)
1428        let result = DirectoryOperations::read(fs, &mut context);
1429        // Either returns None immediately or returns . and .. entries
1430        assert!(
1431            result.is_ok() || matches!(result, Err(IoErrorKind::NotFound)),
1432            "Reading empty directory should succeed or return not found"
1433        );
1434
1435        // Cleanup
1436        DirectoryOperations::close(fs, &mut context).unwrap();
1437        fs.remove(test_dir).unwrap();
1438    }
1439
1440    /// Test directory entry metadata
1441    pub fn test_directory_entry_metadata<F>(fs: &F)
1442    where
1443        F: FileSystemOperations,
1444    {
1445        let test_dir = Path::new("/metadata_dir");
1446        let test_file = Path::new("/metadata_dir/test.txt");
1447        let test_subdir = Path::new("/metadata_dir/subdir");
1448        let mut context = Context::new_empty();
1449
1450        // Create structures
1451        fs.create_directory(test_dir, &Attributes::new()).unwrap();
1452        fs.create_file(test_file, &Attributes::new()).unwrap();
1453        fs.create_directory(test_subdir, &Attributes::new())
1454            .unwrap();
1455
1456        // Open and read directory
1457        fs.lookup_directory(&mut context, test_dir).unwrap();
1458
1459        let mut found_file = false;
1460        let mut found_dir = false;
1461
1462        for _ in 0..10 {
1463            match DirectoryOperations::read(fs, &mut context) {
1464                Ok(Some(entry)) => {
1465                    // Check entry has valid metadata
1466                    assert!(!entry.name.is_empty(), "Entry should have a name");
1467
1468                    if entry.name.contains("test.txt") {
1469                        found_file = true;
1470                        // Could check that kind is File if available
1471                    }
1472                    if entry.name.contains("subdir") {
1473                        found_dir = true;
1474                        // Could check that kind is Directory if available
1475                    }
1476                }
1477                Ok(None) => break,
1478                Err(_) => break,
1479            }
1480        }
1481
1482        assert!(found_file, "Should find test file in directory");
1483        assert!(found_dir, "Should find subdirectory in directory");
1484
1485        // Cleanup
1486        DirectoryOperations::close(fs, &mut context).unwrap();
1487        fs.remove(test_file).unwrap();
1488        fs.remove(test_subdir).unwrap();
1489        fs.remove(test_dir).unwrap();
1490    }
1491
1492    /// Test open and close operations
1493    pub fn test_open_close_operations<F>(fs: &F)
1494    where
1495        F: FileSystemOperations,
1496    {
1497        let test_file = Path::new("/open_close_test.txt");
1498        let mut context = Context::new_empty();
1499
1500        // Create file
1501        fs.create_file(test_file, &Attributes::new()).unwrap();
1502
1503        // Open file
1504        let open_result = fs.lookup_file(&mut context, test_file, AccessFlags::Read.into());
1505        open_result.unwrap();
1506
1507        // Close file
1508        let close_result = BaseOperations::close(fs, &mut context);
1509        assert!(
1510            close_result.is_ok() || matches!(close_result, Err(IoErrorKind::Unsupported)),
1511            "Should close file or be unsupported"
1512        );
1513
1514        // Open directory
1515        let test_dir = Path::new("/open_close_dir");
1516        fs.create_directory(test_dir, &Attributes::new()).unwrap();
1517
1518        let open_result = fs.lookup_directory(&mut context, test_dir);
1519        open_result.unwrap();
1520
1521        // Close directory
1522        DirectoryOperations::close(fs, &mut context).unwrap();
1523
1524        // Cleanup
1525        fs.remove(test_file).unwrap();
1526        fs.remove(test_dir).unwrap();
1527    }
1528
1529    /// Macro to implement all file system operation tests for a given file system instance.
1530    ///
1531    /// This macro generates individual test functions for each test category, making it easy
1532    /// to integrate comprehensive file system testing into your test suite.
1533    ///
1534    /// # Usage
1535    ///
1536    /// ```rust,ignore
1537    /// use file_system::implement_file_system_tests;
1538    ///
1539    /// mod tests {
1540    ///     use super::*;
1541    ///     
1542    ///     implement_file_system_tests! {
1543    ///         instance: MyFileSystem::new()
1544    ///     }
1545    /// }
1546    /// ```
1547    ///
1548    /// This will generate individual `#[test]` functions for each test category.
1549    #[macro_export]
1550    macro_rules! implement_file_system_tests {
1551        ($fs:expr) => {
1552            $crate::implement_file_system_tests!(@impl $fs, None);
1553        };
1554        ($fs:expr, $attribute_capabilities:expr) => {
1555            $crate::implement_file_system_tests!(@impl $fs, Some($attribute_capabilities));
1556        };
1557        (@impl $fs:expr, $attribute_capabilities:expr) => {
1558            // Basic file system structure tests
1559            #[test]
1560            fn test_file_operations() {
1561                let fs = $fs;
1562                $crate::file_system::tests::test_file_operations(&fs);
1563            }
1564
1565            #[test]
1566            fn test_file_creation_edge_cases() {
1567                let fs = $fs;
1568                $crate::file_system::tests::test_file_creation_edge_cases(&fs);
1569            }
1570
1571            #[test]
1572            fn test_directory_operations() {
1573                let fs = $fs;
1574                $crate::file_system::tests::test_directory_operations(&fs);
1575            }
1576
1577            #[test]
1578            fn test_nested_directories() {
1579                let fs = $fs;
1580                $crate::file_system::tests::test_nested_directories(&fs);
1581            }
1582
1583            #[test]
1584            fn test_rename_operations() {
1585                let fs = $fs;
1586                $crate::file_system::tests::test_rename_operations(&fs);
1587            }
1588
1589            #[test]
1590            fn test_rename_edge_cases() {
1591                let fs = $fs;
1592                $crate::file_system::tests::test_rename_edge_cases(&fs);
1593            }
1594
1595            #[test]
1596            fn test_move_between_directories() {
1597                let fs = $fs;
1598                $crate::file_system::tests::test_move_between_directories(&fs);
1599            }
1600
1601            // Attribute operations
1602            #[test]
1603            fn test_attribute_operations() {
1604                let fs = $fs;
1605                match $attribute_capabilities {
1606                    Some(capabilities) => $crate::file_system::tests::test_attribute_operations_with_capabilities(&fs, capabilities),
1607                    None => $crate::file_system::tests::test_attribute_operations(&fs),
1608                }
1609            }
1610
1611            #[test]
1612            fn test_directory_attributes() {
1613                let fs = $fs;
1614                $crate::file_system::tests::test_directory_attributes(&fs);
1615            }
1616
1617            // File I/O operations
1618            #[test]
1619            fn test_file_read_operations() {
1620                let fs = $fs;
1621                $crate::file_system::tests::test_file_read_operations(&fs);
1622            }
1623
1624            #[test]
1625            fn test_file_write_operations() {
1626                let fs = $fs;
1627                $crate::file_system::tests::test_file_write_operations(&fs);
1628            }
1629
1630            #[test]
1631            fn test_file_write_pattern() {
1632                let fs = $fs;
1633                $crate::file_system::tests::test_file_write_pattern(&fs);
1634            }
1635
1636            #[test]
1637            fn test_file_write_vectored() {
1638                let fs = $fs;
1639                $crate::file_system::tests::test_file_write_vectored(&fs);
1640            }
1641
1642            #[test]
1643            fn test_file_position_operations() {
1644                let fs = $fs;
1645                $crate::file_system::tests::test_file_position_operations(&fs);
1646            }
1647
1648            #[test]
1649            fn test_file_read_until() {
1650                let fs = $fs;
1651                $crate::file_system::tests::test_file_read_until(&fs);
1652            }
1653
1654            #[test]
1655            fn test_file_flush() {
1656                let fs = $fs;
1657                $crate::file_system::tests::test_file_flush(&fs);
1658            }
1659
1660            #[test]
1661            fn test_empty_file_operations() {
1662                let fs = $fs;
1663                $crate::file_system::tests::test_empty_file_operations(&fs);
1664            }
1665
1666            #[test]
1667            fn test_large_file_operations() {
1668                let fs = $fs;
1669                $crate::file_system::tests::test_large_file_operations(&fs);
1670            }
1671
1672            // Directory I/O operations
1673            #[test]
1674            fn test_directory_read_operations() {
1675                let fs = $fs;
1676                $crate::file_system::tests::test_directory_read_operations(&fs);
1677            }
1678
1679            #[test]
1680            fn test_directory_position_operations() {
1681                let fs = $fs;
1682                $crate::file_system::tests::test_directory_position_operations(&fs);
1683            }
1684
1685            #[test]
1686            fn test_directory_rewind() {
1687                let fs = $fs;
1688                $crate::file_system::tests::test_directory_rewind(&fs);
1689            }
1690
1691            #[test]
1692            fn test_empty_directory_read() {
1693                let fs = $fs;
1694                $crate::file_system::tests::test_empty_directory_read(&fs);
1695            }
1696
1697            #[test]
1698            fn test_directory_entry_metadata() {
1699                let fs = $fs;
1700                $crate::file_system::tests::test_directory_entry_metadata(&fs);
1701            }
1702
1703            #[test]
1704            fn test_open_close_operations() {
1705                let fs = $fs;
1706                $crate::file_system::tests::test_open_close_operations(&fs);
1707            }
1708
1709            // Error handling and edge cases
1710            #[test]
1711            fn test_error_handling() {
1712                let fs = $fs;
1713                $crate::file_system::tests::test_error_handling(&fs);
1714            }
1715
1716            #[test]
1717            fn test_invalid_paths() {
1718                let fs = $fs;
1719                $crate::file_system::tests::test_invalid_paths(&fs);
1720            }
1721
1722            #[test]
1723            fn test_multiple_operations() {
1724                let fs = $fs;
1725                $crate::file_system::tests::test_multiple_operations(&fs);
1726            }
1727
1728            #[test]
1729            fn test_file_system_consistency() {
1730                let fs = $fs;
1731                $crate::file_system::tests::test_file_system_consistency(&fs);
1732            }
1733
1734            #[test]
1735            fn test_lookup_with_flags() {
1736                let fs = $fs;
1737                $crate::file_system::tests::test_lookup_with_flags(&fs);
1738            }
1739
1740            #[test]
1741            fn test_root_directory_operations() {
1742                let fs = $fs;
1743                $crate::file_system::tests::test_root_directory_operations(&fs);
1744            }
1745
1746            #[test]
1747            fn test_long_filenames() {
1748                let fs = $fs;
1749                $crate::file_system::tests::test_long_filenames(&fs);
1750            }
1751
1752            #[test]
1753            fn test_special_characters_in_names() {
1754                let fs = $fs;
1755                $crate::file_system::tests::test_special_characters_in_names(&fs);
1756            }
1757        };
1758    }
1759    pub use implement_file_system_tests;
1760}