Debian Codegraph @

third_party/rust/tempfile/tests/namedtempfile.rs

raw
1 #![deny(rust_2018_idioms)]
2
3 use std::ffi::{OsStr, OsString};
4 use std::fs::File;
5 use std::io::{Read, Seek, SeekFrom, Write};
6 use std::path::{Path, PathBuf};
7 use tempfile::{env, tempdir, Builder, NamedTempFile, TempPath};
8
9 fn exists<P: AsRef<Path>>(path: P) -> bool {
10 std::fs::metadata(path.as_ref()).is_ok()
11 }
12
13 #[test]
14 fn test_prefix() {
15 let tmpfile = NamedTempFile::with_prefix("prefix").unwrap();
16 let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
17 assert!(name.starts_with("prefix"));
18 }
19
20 #[test]
21 fn test_suffix() {
22 let tmpfile = NamedTempFile::with_suffix("suffix").unwrap();
23 let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
24 assert!(name.ends_with("suffix"));
25 }
26
27 #[test]
28 fn test_basic() {
29 let mut tmpfile = NamedTempFile::new().unwrap();
30 write!(tmpfile, "abcde").unwrap();
31 tmpfile.seek(SeekFrom::Start(0)).unwrap();
32 let mut buf = String::new();
33 tmpfile.read_to_string(&mut buf).unwrap();
34 assert_eq!("abcde", buf);
35 }
36
37 #[test]
38 fn test_deleted() {
39 let tmpfile = NamedTempFile::new().unwrap();
40 let path = tmpfile.path().to_path_buf();
41 assert!(exists(&path));
42 drop(tmpfile);
43 assert!(!exists(&path));
44 }
45
46 #[test]
47 fn test_persist() {
48 let mut tmpfile = NamedTempFile::new().unwrap();
49 let old_path = tmpfile.path().to_path_buf();
50 let persist_path = env::temp_dir().join("persisted_temporary_file");
51 write!(tmpfile, "abcde").unwrap();
52 {
53 assert!(exists(&old_path));
54 let mut f = tmpfile.persist(&persist_path).unwrap();
55 assert!(!exists(&old_path));
56
57 // Check original file
58 f.seek(SeekFrom::Start(0)).unwrap();
59 let mut buf = String::new();
60 f.read_to_string(&mut buf).unwrap();
61 assert_eq!("abcde", buf);
62 }
63
64 {
65 // Try opening it at the new path.
66 let mut f = File::open(&persist_path).unwrap();
67 f.seek(SeekFrom::Start(0)).unwrap();
68 let mut buf = String::new();
69 f.read_to_string(&mut buf).unwrap();
70 assert_eq!("abcde", buf);
71 }
72 std::fs::remove_file(&persist_path).unwrap();
73 }
74
75 #[test]
76 fn test_persist_noclobber() {
77 let mut tmpfile = NamedTempFile::new().unwrap();
78 let old_path = tmpfile.path().to_path_buf();
79 let persist_target = NamedTempFile::new().unwrap();
80 let persist_path = persist_target.path().to_path_buf();
81 write!(tmpfile, "abcde").unwrap();
82 assert!(exists(&old_path));
83 {
84 tmpfile = tmpfile.persist_noclobber(&persist_path).unwrap_err().into();
85 assert!(exists(&old_path));
86 std::fs::remove_file(&persist_path).unwrap();
87 drop(persist_target);
88 }
89 tmpfile.persist_noclobber(&persist_path).unwrap();
90 // Try opening it at the new path.
91 let mut f = File::open(&persist_path).unwrap();
92 f.seek(SeekFrom::Start(0)).unwrap();
93 let mut buf = String::new();
94 f.read_to_string(&mut buf).unwrap();
95 assert_eq!("abcde", buf);
96 std::fs::remove_file(&persist_path).unwrap();
97 }
98
99 #[test]
100 fn test_customnamed() {
101 let tmpfile = Builder::new()
102 .prefix("tmp")
103 .suffix(&".rs")
104 .rand_bytes(12)
105 .tempfile()
106 .unwrap();
107 let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
108 assert!(name.starts_with("tmp"));
109 assert!(name.ends_with(".rs"));
110 assert_eq!(name.len(), 18);
111 }
112
113 #[test]
114 fn test_append() {
115 let mut tmpfile = Builder::new().append(true).tempfile().unwrap();
116 tmpfile.write_all(b"a").unwrap();
117 tmpfile.seek(SeekFrom::Start(0)).unwrap();
118 tmpfile.write_all(b"b").unwrap();
119
120 tmpfile.seek(SeekFrom::Start(0)).unwrap();
121 let mut buf = vec![0u8; 1];
122 tmpfile.read_exact(&mut buf).unwrap();
123 assert_eq!(buf, b"a");
124 }
125
126 #[test]
127 fn test_reopen() {
128 let source = NamedTempFile::new().unwrap();
129 let mut first = source.reopen().unwrap();
130 let mut second = source.reopen().unwrap();
131 drop(source);
132
133 write!(first, "abcde").expect("write failed");
134 let mut buf = String::new();
135 second.read_to_string(&mut buf).unwrap();
136 assert_eq!("abcde", buf);
137 }
138
139 #[test]
140 fn test_into_file() {
141 let mut file = NamedTempFile::new().unwrap();
142 let path = file.path().to_owned();
143 write!(file, "abcde").expect("write failed");
144
145 assert!(path.exists());
146 let mut file = file.into_file();
147 assert!(!path.exists());
148
149 file.seek(SeekFrom::Start(0)).unwrap();
150 let mut buf = String::new();
151 file.read_to_string(&mut buf).unwrap();
152 assert_eq!("abcde", buf);
153 }
154
155 #[test]
156 fn test_immut() {
157 let tmpfile = NamedTempFile::new().unwrap();
158 (&tmpfile).write_all(b"abcde").unwrap();
159 (&tmpfile).seek(SeekFrom::Start(0)).unwrap();
160 let mut buf = String::new();
161 (&tmpfile).read_to_string(&mut buf).unwrap();
162 assert_eq!("abcde", buf);
163 }
164
165 #[test]
166 fn test_temppath() {
167 let mut tmpfile = NamedTempFile::new().unwrap();
168 write!(tmpfile, "abcde").unwrap();
169
170 let path = tmpfile.into_temp_path();
171 assert!(path.is_file());
172 }
173
174 #[test]
175 fn test_temppath_persist() {
176 let mut tmpfile = NamedTempFile::new().unwrap();
177 write!(tmpfile, "abcde").unwrap();
178
179 let tmppath = tmpfile.into_temp_path();
180
181 let old_path = tmppath.to_path_buf();
182 let persist_path = env::temp_dir().join("persisted_temppath_file");
183
184 {
185 assert!(exists(&old_path));
186 tmppath.persist(&persist_path).unwrap();
187 assert!(!exists(&old_path));
188 }
189
190 {
191 // Try opening it at the new path.
192 let mut f = File::open(&persist_path).unwrap();
193 f.seek(SeekFrom::Start(0)).unwrap();
194 let mut buf = String::new();
195 f.read_to_string(&mut buf).unwrap();
196 assert_eq!("abcde", buf);
197 }
198
199 std::fs::remove_file(&persist_path).unwrap();
200 }
201
202 #[test]
203 fn test_temppath_persist_noclobber() {
204 let mut tmpfile = NamedTempFile::new().unwrap();
205 write!(tmpfile, "abcde").unwrap();
206
207 let mut tmppath = tmpfile.into_temp_path();
208
209 let old_path = tmppath.to_path_buf();
210 let persist_target = NamedTempFile::new().unwrap();
211 let persist_path = persist_target.path().to_path_buf();
212
213 assert!(exists(&old_path));
214
215 {
216 tmppath = tmppath.persist_noclobber(&persist_path).unwrap_err().into();
217 assert!(exists(&old_path));
218 std::fs::remove_file(&persist_path).unwrap();
219 drop(persist_target);
220 }
221
222 tmppath.persist_noclobber(&persist_path).unwrap();
223
224 // Try opening it at the new path.
225 let mut f = File::open(&persist_path).unwrap();
226 f.seek(SeekFrom::Start(0)).unwrap();
227 let mut buf = String::new();
228 f.read_to_string(&mut buf).unwrap();
229 assert_eq!("abcde", buf);
230 std::fs::remove_file(&persist_path).unwrap();
231 }
232
233 #[test]
234 fn temp_path_from_existing() {
235 let tmp_dir = tempdir().unwrap();
236 let tmp_file_path_1 = tmp_dir.path().join("testfile1");
237 let tmp_file_path_2 = tmp_dir.path().join("testfile2");
238
239 File::create(&tmp_file_path_1).unwrap();
240 assert!(tmp_file_path_1.exists(), "Test file 1 hasn't been created");
241
242 File::create(&tmp_file_path_2).unwrap();
243 assert!(tmp_file_path_2.exists(), "Test file 2 hasn't been created");
244
245 let tmp_path = TempPath::from_path(&tmp_file_path_1);
246 assert!(
247 tmp_file_path_1.exists(),
248 "Test file has been deleted before dropping TempPath"
249 );
250
251 drop(tmp_path);
252 assert!(
253 !tmp_file_path_1.exists(),
254 "Test file exists after dropping TempPath"
255 );
256 assert!(
257 tmp_file_path_2.exists(),
258 "Test file 2 has been deleted before dropping TempDir"
259 );
260 }
261
262 #[test]
263 #[allow(unreachable_code)]
264 fn temp_path_from_argument_types() {
265 // This just has to compile
266 return;
267
268 TempPath::from_path("");
269 TempPath::from_path(String::new());
270 TempPath::from_path(OsStr::new(""));
271 TempPath::from_path(OsString::new());
272 TempPath::from_path(Path::new(""));
273 TempPath::from_path(PathBuf::new());
274 TempPath::from_path(PathBuf::new().into_boxed_path());
275 }
276
277 #[test]
278 fn test_write_after_close() {
279 let path = NamedTempFile::new().unwrap().into_temp_path();
280 File::create(path).unwrap().write_all(b"test").unwrap();
281 }
282
283 #[test]
284 fn test_change_dir() {
285 std::env::set_current_dir(env::temp_dir()).unwrap();
286 let tmpfile = NamedTempFile::new_in(".").unwrap();
287 let path = std::env::current_dir().unwrap().join(tmpfile.path());
288 std::env::set_current_dir("/").unwrap();
289 drop(tmpfile);
290 assert!(!exists(path))
291 }
292
293 #[test]
294 fn test_into_parts() {
295 let mut file = NamedTempFile::new().unwrap();
296 write!(file, "abcd").expect("write failed");
297
298 let (mut file, temp_path) = file.into_parts();
299
300 let path = temp_path.to_path_buf();
301
302 assert!(path.exists());
303 drop(temp_path);
304 assert!(!path.exists());
305
306 write!(file, "efgh").expect("write failed");
307
308 file.seek(SeekFrom::Start(0)).unwrap();
309 let mut buf = String::new();
310 file.read_to_string(&mut buf).unwrap();
311 assert_eq!("abcdefgh", buf);
312 }
313
314 #[test]
315 fn test_from_parts() {
316 let mut file = NamedTempFile::new().unwrap();
317 write!(file, "abcd").expect("write failed");
318
319 let (file, temp_path) = file.into_parts();
320
321 let file = NamedTempFile::from_parts(file, temp_path);
322
323 assert!(file.path().exists());
324 }
325
326 #[test]
327 fn test_keep() {
328 let mut tmpfile = NamedTempFile::new().unwrap();
329 write!(tmpfile, "abcde").unwrap();
330 let (mut f, temp_path) = tmpfile.into_parts();
331 let path;
332 {
333 assert!(exists(&temp_path));
334 path = temp_path.keep().unwrap();
335 assert!(exists(&path));
336
337 // Check original file
338 f.seek(SeekFrom::Start(0)).unwrap();
339 let mut buf = String::new();
340 f.read_to_string(&mut buf).unwrap();
341 assert_eq!("abcde", buf);
342 }
343
344 {
345 // Try opening it again.
346 let mut f = File::open(&path).unwrap();
347 f.seek(SeekFrom::Start(0)).unwrap();
348 let mut buf = String::new();
349 f.read_to_string(&mut buf).unwrap();
350 assert_eq!("abcde", buf);
351 }
352 std::fs::remove_file(&path).unwrap();
353 }
354
355 #[test]
356 fn test_builder_keep() {
357 let mut tmpfile = Builder::new().keep(true).tempfile().unwrap();
358 write!(tmpfile, "abcde").unwrap();
359 let path = tmpfile.path().to_owned();
360 drop(tmpfile);
361
362 {
363 // Try opening it again.
364 let mut f = File::open(&path).unwrap();
365 let mut buf = String::new();
366 f.read_to_string(&mut buf).unwrap();
367 assert_eq!("abcde", buf);
368 }
369 std::fs::remove_file(&path).unwrap();
370 }
371
372 #[test]
373 fn test_make() {
374 let tmpfile = Builder::new().make(|path| File::create(path)).unwrap();
375
376 assert!(tmpfile.path().is_file());
377 }
378
379 #[test]
380 fn test_make_in() {
381 let tmp_dir = tempdir().unwrap();
382
383 let tmpfile = Builder::new()
384 .make_in(tmp_dir.path(), |path| File::create(path))
385 .unwrap();
386
387 assert!(tmpfile.path().is_file());
388 assert_eq!(tmpfile.path().parent(), Some(tmp_dir.path()));
389 }
390
391 #[test]
392 fn test_make_fnmut() {
393 let mut count = 0;
394
395 // Show that an FnMut can be used.
396 let tmpfile = Builder::new()
397 .make(|path| {
398 count += 1;
399 File::create(path)
400 })
401 .unwrap();
402
403 assert!(tmpfile.path().is_file());
404 }
405
406 #[cfg(unix)]
407 #[test]
408 fn test_make_uds() {
409 use std::os::unix::net::UnixListener;
410
411 let temp_sock = Builder::new()
412 .prefix("tmp")
413 .suffix(".sock")
414 .rand_bytes(12)
415 .make(|path| UnixListener::bind(path))
416 .unwrap();
417
418 assert!(temp_sock.path().exists());
419 }
420
421 #[cfg(unix)]
422 #[test]
423 fn test_make_uds_conflict() {
424 use std::io::ErrorKind;
425 use std::os::unix::net::UnixListener;
426
427 let sockets = std::iter::repeat_with(|| {
428 Builder::new()
429 .prefix("tmp")
430 .suffix(".sock")
431 .rand_bytes(1)
432 .make(|path| UnixListener::bind(path))
433 })
434 .take_while(|r| match r {
435 Ok(_) => true,
436 Err(e) if matches!(e.kind(), ErrorKind::AddrInUse | ErrorKind::AlreadyExists) => false,
437 Err(e) => panic!("unexpected error {e}"),
438 })
439 .collect::<Result<Vec<_>, _>>()
440 .unwrap();
441
442 // Number of sockets we can create. Depends on whether or not the filesystem is case sensitive.
443
444 #[cfg(target_os = "macos")]
445 const NUM_FILES: usize = 36;
446 #[cfg(not(target_os = "macos"))]
447 const NUM_FILES: usize = 62;
448
449 assert_eq!(sockets.len(), NUM_FILES);
450
451 for socket in sockets {
452 assert!(socket.path().exists());
453 }
454 }
455
456 /// Make sure we re-seed with system randomness if we run into a conflict.
457 #[test]
458 fn test_reseed() {
459 // Deterministic seed.
460 fastrand::seed(42);
461
462 let mut attempts = 0;
463 let _files: Vec<_> = std::iter::repeat_with(|| {
464 Builder::new()
465 .make(|path| {
466 attempts += 1;
467 File::options().write(true).create_new(true).open(path)
468 })
469 .unwrap()
470 })
471 .take(5)
472 .collect();
473
474 assert_eq!(5, attempts);
475 attempts = 0;
476
477 // Re-seed to cause a conflict.
478 fastrand::seed(42);
479
480 let _f = Builder::new()
481 .make(|path| {
482 attempts += 1;
483 File::options().write(true).create_new(true).open(path)
484 })
485 .unwrap();
486
487 // We expect exactly three conflict before we re-seed with system randomness.
488 assert_eq!(4, attempts);
489 }
490
491 // Issue #224.
492 #[test]
493 fn test_overly_generic_bounds() {
494 pub struct Foo<T>(T);
495
496 impl<T> Foo<T>
497 where
498 T: Sync + Send + 'static,
499 for<'a> &'a T: Write + Read,
500 {
501 pub fn new(foo: T) -> Self {
502 Self(foo)
503 }
504 }
505
506 // Don't really need to run this. Only care if it compiles.
507 if let Ok(file) = File::open("i_do_not_exist") {
508 let mut f;
509 let _x = {
510 f = Foo::new(file);
511 &mut f
512 };
513 }
514 }