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