]> git.lizzy.rs Git - rust.git/blob - tests/run-pass/fs.rs
b6d460f7a981ca0b7b58e261d04ab7e9efb2de0f
[rust.git] / tests / run-pass / fs.rs
1 // ignore-windows: File handling is not implemented yet
2 // compile-flags: -Zmiri-disable-isolation
3
4 use std::fs::{File, create_dir, read_dir, remove_dir, remove_dir_all, remove_file, rename};
5 use std::io::{Read, Write, ErrorKind, Result, Seek, SeekFrom};
6 use std::path::{PathBuf, Path};
7
8 fn main() {
9     test_file();
10     test_file_clone();
11     test_seek();
12     test_metadata();
13     test_symlink();
14     test_errors();
15     test_rename();
16     test_directory();
17 }
18
19 /// Prepare: compute filename and make sure the file does not exist.
20 fn prepare(filename: &str) -> PathBuf {
21     let tmp = std::env::temp_dir();
22     let path = tmp.join(filename);
23     // Clean the paths for robustness.
24     remove_file(&path).ok();
25     path
26 }
27
28 /// Prepare directory: compute directory name and make sure it does not exist.
29 fn prepare_dir(dirname: &str) -> PathBuf {
30     let tmp = std::env::temp_dir();
31     let path = tmp.join(&dirname);
32     // Clean the directory for robustness.
33     remove_dir_all(&path).ok();
34     path
35 }
36
37 /// Prepare like above, and also write some initial content to the file.
38 fn prepare_with_content(filename: &str, content: &[u8]) -> PathBuf {
39     let path = prepare(filename);
40     let mut file = File::create(&path).unwrap();
41     file.write(content).unwrap();
42     path
43 }
44
45 fn test_file() {
46     let bytes = b"Hello, World!\n";
47     let path = prepare("miri_test_fs_file.txt");
48
49     // Test creating, writing and closing a file (closing is tested when `file` is dropped).
50     let mut file = File::create(&path).unwrap();
51     // Writing 0 bytes should not change the file contents.
52     file.write(&mut []).unwrap();
53     assert_eq!(file.metadata().unwrap().len(), 0);
54
55     file.write(bytes).unwrap();
56     assert_eq!(file.metadata().unwrap().len(), bytes.len() as u64);
57     // Test opening, reading and closing a file.
58     let mut file = File::open(&path).unwrap();
59     let mut contents = Vec::new();
60     // Reading 0 bytes should not move the file pointer.
61     file.read(&mut []).unwrap();
62     // Reading until EOF should get the whole text.
63     file.read_to_end(&mut contents).unwrap();
64     assert_eq!(bytes, contents.as_slice());
65
66     // Removing file should succeed.
67     remove_file(&path).unwrap();
68 }
69
70 fn test_file_clone() {
71     let bytes = b"Hello, World!\n";
72     let path = prepare_with_content("miri_test_fs_file_clone.txt", bytes);
73
74     // Cloning a file should be successful.
75     let file = File::open(&path).unwrap();
76     let mut cloned = file.try_clone().unwrap();
77     // Reading from a cloned file should get the same text.
78     let mut contents = Vec::new();
79     cloned.read_to_end(&mut contents).unwrap();
80     assert_eq!(bytes, contents.as_slice());
81
82     // Removing file should succeed.
83     remove_file(&path).unwrap();
84 }
85
86 fn test_seek() {
87     let bytes = b"Hello, entire World!\n";
88     let path = prepare_with_content("miri_test_fs_seek.txt", bytes);
89
90     let mut file = File::open(&path).unwrap();
91     let mut contents = Vec::new();
92     file.read_to_end(&mut contents).unwrap();
93     assert_eq!(bytes, contents.as_slice());
94     // Test that seeking to the beginning and reading until EOF gets the text again.
95     file.seek(SeekFrom::Start(0)).unwrap();
96     let mut contents = Vec::new();
97     file.read_to_end(&mut contents).unwrap();
98     assert_eq!(bytes, contents.as_slice());
99     // Test seeking relative to the end of the file.
100     file.seek(SeekFrom::End(-1)).unwrap();
101     let mut contents = Vec::new();
102     file.read_to_end(&mut contents).unwrap();
103     assert_eq!(&bytes[bytes.len() - 1..], contents.as_slice());
104     // Test seeking relative to the current position.
105     file.seek(SeekFrom::Start(5)).unwrap();
106     file.seek(SeekFrom::Current(-3)).unwrap();
107     let mut contents = Vec::new();
108     file.read_to_end(&mut contents).unwrap();
109     assert_eq!(&bytes[2..], contents.as_slice());
110
111     // Removing file should succeed.
112     remove_file(&path).unwrap();
113 }
114
115 fn check_metadata(bytes: &[u8], path: &Path) -> Result<()> {
116     // Test that the file metadata is correct.
117     let metadata = path.metadata()?;
118     // `path` should point to a file.
119     assert!(metadata.is_file());
120     // The size of the file must be equal to the number of written bytes.
121     assert_eq!(bytes.len() as u64, metadata.len());
122     Ok(())
123 }
124
125 fn test_metadata() {
126     let bytes = b"Hello, meta-World!\n";
127     let path = prepare_with_content("miri_test_fs_metadata.txt", bytes);
128
129     // Test that metadata of an absolute path is correct.
130     check_metadata(bytes, &path).unwrap();
131     // Test that metadata of a relative path is correct.
132     std::env::set_current_dir(path.parent().unwrap()).unwrap();
133     check_metadata(bytes, Path::new(path.file_name().unwrap())).unwrap();
134
135     // Removing file should succeed.
136     remove_file(&path).unwrap();
137 }
138
139 fn test_symlink() {
140     let bytes = b"Hello, World!\n";
141     let path = prepare_with_content("miri_test_fs_link_target.txt", bytes);
142     let symlink_path = prepare("miri_test_fs_symlink.txt");
143
144     // Creating a symbolic link should succeed.
145     #[cfg(unix)]
146     std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
147     #[cfg(windows)]
148     std::os::windows::fs::symlink_file(&path, &symlink_path).unwrap();
149     // Test that the symbolic link has the same contents as the file.
150     let mut symlink_file = File::open(&symlink_path).unwrap();
151     let mut contents = Vec::new();
152     symlink_file.read_to_end(&mut contents).unwrap();
153     assert_eq!(bytes, contents.as_slice());
154     // Test that metadata of a symbolic link is correct.
155     check_metadata(bytes, &symlink_path).unwrap();
156     // Test that the metadata of a symbolic link is correct when not following it.
157     assert!(symlink_path.symlink_metadata().unwrap().file_type().is_symlink());
158     // Removing symbolic link should succeed.
159     remove_file(&symlink_path).unwrap();
160
161     // Removing file should succeed.
162     remove_file(&path).unwrap();
163 }
164
165 fn test_errors() {
166     let bytes = b"Hello, World!\n";
167     let path = prepare("miri_test_fs_errors.txt");
168
169     // The following tests also check that the `__errno_location()` shim is working properly.
170     // Opening a non-existing file should fail with a "not found" error.
171     assert_eq!(ErrorKind::NotFound, File::open(&path).unwrap_err().kind());
172     // Removing a non-existing file should fail with a "not found" error.
173     assert_eq!(ErrorKind::NotFound, remove_file(&path).unwrap_err().kind());
174     // Reading the metadata of a non-existing file should fail with a "not found" error.
175     assert_eq!(ErrorKind::NotFound, check_metadata(bytes, &path).unwrap_err().kind());
176 }
177
178 fn test_rename() {
179     // Renaming a file should succeed.
180     let path1 = prepare("miri_test_fs_rename_source.txt");
181     let path2 = prepare("miri_test_fs_rename_destination.txt");
182
183     let file = File::create(&path1).unwrap();
184     drop(file);
185
186     // Renaming should succeed
187     rename(&path1, &path2).unwrap();
188     // Check that the old file path isn't present
189     assert_eq!(ErrorKind::NotFound, path1.metadata().unwrap_err().kind());
190     // Check that the file has moved successfully
191     assert!(path2.metadata().unwrap().is_file());
192
193     // Renaming a nonexistent file should fail
194     assert_eq!(ErrorKind::NotFound, rename(&path1, &path2).unwrap_err().kind());
195
196     remove_file(&path2).unwrap();
197 }
198
199 fn test_directory() {
200     let dir_path = prepare_dir("miri_test_fs_dir");
201     // Creating a directory should succeed.
202     create_dir(&dir_path).unwrap();
203     // Test that the metadata of a directory is correct.
204     assert!(dir_path.metadata().unwrap().is_dir());
205     // Creating a directory when it already exists should fail.
206     assert_eq!(ErrorKind::AlreadyExists, create_dir(&dir_path).unwrap_err().kind());
207
208     // Create some files inside the directory
209     let path_1 = dir_path.join("test_file_1");
210     drop(File::create(&path_1).unwrap());
211     let path_2 = dir_path.join("test_file_2");
212     drop(File::create(&path_2).unwrap());
213     // Test that the files are present inside the directory
214     let dir_iter = read_dir(&dir_path).unwrap();
215     let mut file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
216     file_names.sort_unstable();
217     assert_eq!(file_names, vec!["test_file_1", "test_file_2"]);
218     // Clean up the files in the directory
219     remove_file(&path_1).unwrap();
220     remove_file(&path_2).unwrap();
221     // Now there should be nothing left in the directory.
222     let dir_iter = read_dir(&dir_path).unwrap();
223     let file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
224     assert!(file_names.is_empty());
225
226     // Deleting the directory should succeed.
227     remove_dir(&dir_path).unwrap();
228     // Reading the metadata of a non-existent directory should fail with a "not found" error.
229     assert_eq!(ErrorKind::NotFound, check_metadata(&[], &dir_path).unwrap_err().kind());
230 }