Debian Codegraph @

debian/rust-vendor/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::{self, Read, Seek, SeekFrom, Write};
6 use std::path::{Path, PathBuf};
7 use tempfile::{env, tempdir, Builder, NamedTempFile, TempPath};
8
9 struct CWDGuard {
10 #[allow(unused)]
11 guard: std::sync::MutexGuard<'static, ()>,
12 old_cwd: PathBuf,
13 }
14
15 impl Drop for CWDGuard {
16 fn drop(&mut self) {
17 let _ = std::env::set_current_dir(&self.old_cwd);
18 }
19 }
20
21 static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
22
23 fn cwd_lock() -> CWDGuard {
24 let guard = CWD_LOCK.lock().unwrap();
25 let old_cwd = std::env::current_dir().unwrap();
26 CWDGuard { guard, old_cwd }
27 }
28
29 fn exists<P: AsRef<Path>>(path: P) -> bool {
30 std::fs::metadata(path.as_ref()).is_ok()
31 }
32
33 /// For the wasi platforms, `std::env::temp_dir` will panic. For those targets, configure the /tmp
34 /// directory instead as the base directory for temp files.
35 fn configure_wasi_temp_dir() {
36 if cfg!(target_os = "wasi") {
37 let _ = tempfile::env::override_temp_dir(Path::new("/tmp"));
38 }
39 }
40
41 #[test]
42 fn test_prefix() {
43 configure_wasi_temp_dir();
44
45 let tmpfile = NamedTempFile::with_prefix("prefix").unwrap();
46 let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
47 assert!(name.starts_with("prefix"));
48 }
49
50 #[test]
51 fn test_suffix() {
52 configure_wasi_temp_dir();
53
54 let tmpfile = NamedTempFile::with_suffix("suffix").unwrap();
55 let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
56 assert!(name.ends_with("suffix"));
57 }
58
59 #[test]
60 fn test_basic() {
61 configure_wasi_temp_dir();
62
63 let mut tmpfile = NamedTempFile::new().unwrap();
64 write!(tmpfile, "abcde").unwrap();
65 tmpfile.seek(SeekFrom::Start(0)).unwrap();
66 let mut buf = String::new();
67 tmpfile.read_to_string(&mut buf).unwrap();
68 assert_eq!("abcde", buf);
69 }
70
71 #[test]
72 fn test_deleted() {
73 configure_wasi_temp_dir();
74
75 let tmpfile = NamedTempFile::new().unwrap();
76 let path = tmpfile.path().to_path_buf();
77 assert!(exists(&path));
78 drop(tmpfile);
79 assert!(!exists(&path));
80 }
81
82 #[test]
83 fn test_persist() {
84 configure_wasi_temp_dir();
85
86 let mut tmpfile = NamedTempFile::new().unwrap();
87 let old_path = tmpfile.path().to_path_buf();
88 let persist_path = env::temp_dir().join("persisted_temporary_file");
89 write!(tmpfile, "abcde").unwrap();
90 {
91 assert!(exists(&old_path));
92 let mut f = tmpfile.persist(&persist_path).unwrap();
93 assert!(!exists(&old_path));
94
95 // Check original file
96 f.seek(SeekFrom::Start(0)).unwrap();
97 let mut buf = String::new();
98 f.read_to_string(&mut buf).unwrap();
99 assert_eq!("abcde", buf);
100 }
101
102 {
103 // Try opening it at the new path.
104 let mut f = File::open(&persist_path).unwrap();
105 f.seek(SeekFrom::Start(0)).unwrap();
106 let mut buf = String::new();
107 f.read_to_string(&mut buf).unwrap();
108 assert_eq!("abcde", buf);
109 }
110 std::fs::remove_file(&persist_path).unwrap();
111 }
112
113 #[test]
114 fn test_persist_noclobber() {
115 configure_wasi_temp_dir();
116
117 let mut tmpfile = NamedTempFile::new().unwrap();
118 let old_path = tmpfile.path().to_path_buf();
119 let persist_target = NamedTempFile::new().unwrap();
120 let persist_path = persist_target.path().to_path_buf();
121 write!(tmpfile, "abcde").unwrap();
122 assert!(exists(&old_path));
123 {
124 tmpfile = tmpfile.persist_noclobber(&persist_path).unwrap_err().into();
125 assert!(exists(&old_path));
126 std::fs::remove_file(&persist_path).unwrap();
127 drop(persist_target);
128 }
129 tmpfile.persist_noclobber(&persist_path).unwrap();
130 // Try opening it at the new path.
131 let mut f = File::open(&persist_path).unwrap();
132 f.seek(SeekFrom::Start(0)).unwrap();
133 let mut buf = String::new();
134 f.read_to_string(&mut buf).unwrap();
135 assert_eq!("abcde", buf);
136 std::fs::remove_file(&persist_path).unwrap();
137 }
138
139 #[test]
140 fn test_customnamed() {
141 configure_wasi_temp_dir();
142
143 let tmpfile = Builder::new()
144 .prefix("tmp")
145 .suffix(&".rs")
146 .rand_bytes(12)
147 .tempfile()
148 .unwrap();
149 let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
150 assert!(name.starts_with("tmp"));
151 assert!(name.ends_with(".rs"));
152 assert_eq!(name.len(), 18);
153 }
154
155 #[test]
156 fn test_append() {
157 configure_wasi_temp_dir();
158
159 let mut tmpfile = Builder::new().append(true).tempfile().unwrap();
160 tmpfile.write_all(b"a").unwrap();
161 tmpfile.seek(SeekFrom::Start(0)).unwrap();
162 tmpfile.write_all(b"b").unwrap();
163
164 tmpfile.seek(SeekFrom::Start(0)).unwrap();
165 let mut buf = vec![0u8; 1];
166 tmpfile.read_exact(&mut buf).unwrap();
167 assert_eq!(buf, b"a");
168 }
169
170 #[test]
171 fn test_reopen() {
172 configure_wasi_temp_dir();
173
174 let source = NamedTempFile::new().unwrap();
175 let mut first = source.reopen().unwrap();
176 let mut second = source.reopen().unwrap();
177 drop(source);
178
179 write!(first, "abcde").expect("write failed");
180 let mut buf = String::new();
181 second.read_to_string(&mut buf).unwrap();
182 assert_eq!("abcde", buf);
183 }
184
185 #[test]
186 fn test_into_file() {
187 configure_wasi_temp_dir();
188
189 let mut file = NamedTempFile::new().unwrap();
190 let path = file.path().to_owned();
191 write!(file, "abcde").expect("write failed");
192
193 assert!(path.exists());
194 let mut file = file.into_file();
195 assert!(!path.exists());
196
197 file.seek(SeekFrom::Start(0)).unwrap();
198 let mut buf = String::new();
199 file.read_to_string(&mut buf).unwrap();
200 assert_eq!("abcde", buf);
201 }
202
203 #[test]
204 fn test_immut() {
205 configure_wasi_temp_dir();
206
207 let tmpfile = NamedTempFile::new().unwrap();
208 (&tmpfile).write_all(b"abcde").unwrap();
209 (&tmpfile).seek(SeekFrom::Start(0)).unwrap();
210 let mut buf = String::new();
211 (&tmpfile).read_to_string(&mut buf).unwrap();
212 assert_eq!("abcde", buf);
213 }
214
215 #[test]
216 fn test_temppath() {
217 configure_wasi_temp_dir();
218
219 let mut tmpfile = NamedTempFile::new().unwrap();
220 write!(tmpfile, "abcde").unwrap();
221
222 let path = tmpfile.into_temp_path();
223 assert!(path.is_file());
224 }
225
226 #[test]
227 fn test_temppath_persist() {
228 configure_wasi_temp_dir();
229
230 let mut tmpfile = NamedTempFile::new().unwrap();
231 write!(tmpfile, "abcde").unwrap();
232
233 let tmppath = tmpfile.into_temp_path();
234
235 let old_path = tmppath.to_path_buf();
236 let persist_path = env::temp_dir().join("persisted_temppath_file");
237
238 {
239 assert!(exists(&old_path));
240 tmppath.persist(&persist_path).unwrap();
241 assert!(!exists(&old_path));
242 }
243
244 {
245 // Try opening it at the new path.
246 let mut f = File::open(&persist_path).unwrap();
247 f.seek(SeekFrom::Start(0)).unwrap();
248 let mut buf = String::new();
249 f.read_to_string(&mut buf).unwrap();
250 assert_eq!("abcde", buf);
251 }
252
253 std::fs::remove_file(&persist_path).unwrap();
254 }
255
256 #[test]
257 fn test_temppath_persist_noclobber() {
258 configure_wasi_temp_dir();
259
260 let mut tmpfile = NamedTempFile::new().unwrap();
261 write!(tmpfile, "abcde").unwrap();
262
263 let mut tmppath = tmpfile.into_temp_path();
264
265 let old_path = tmppath.to_path_buf();
266 let persist_target = NamedTempFile::new().unwrap();
267 let persist_path = persist_target.path().to_path_buf();
268
269 assert!(exists(&old_path));
270
271 {
272 tmppath = tmppath.persist_noclobber(&persist_path).unwrap_err().into();
273 assert!(exists(&old_path));
274 std::fs::remove_file(&persist_path).unwrap();
275 drop(persist_target);
276 }
277
278 tmppath.persist_noclobber(&persist_path).unwrap();
279
280 // Try opening it at the new path.
281 let mut f = File::open(&persist_path).unwrap();
282 f.seek(SeekFrom::Start(0)).unwrap();
283 let mut buf = String::new();
284 f.read_to_string(&mut buf).unwrap();
285 assert_eq!("abcde", buf);
286 std::fs::remove_file(&persist_path).unwrap();
287 }
288
289 #[test]
290 fn temp_path_from_existing() {
291 configure_wasi_temp_dir();
292
293 let tmp_dir = tempdir().unwrap();
294 let tmp_file_path_1 = tmp_dir.path().join("testfile1");
295 let tmp_file_path_2 = tmp_dir.path().join("testfile2");
296
297 File::create(&tmp_file_path_1).unwrap();
298 assert!(tmp_file_path_1.exists(), "Test file 1 hasn't been created");
299
300 File::create(&tmp_file_path_2).unwrap();
301 assert!(tmp_file_path_2.exists(), "Test file 2 hasn't been created");
302
303 let tmp_path = TempPath::try_from_path(&tmp_file_path_1).unwrap();
304 assert!(
305 tmp_file_path_1.exists(),
306 "Test file has been deleted before dropping TempPath"
307 );
308
309 drop(tmp_path);
310 assert!(
311 !tmp_file_path_1.exists(),
312 "Test file exists after dropping TempPath"
313 );
314 assert!(
315 tmp_file_path_2.exists(),
316 "Test file 2 has been deleted before dropping TempDir"
317 );
318 }
319
320 #[test]
321 #[allow(unreachable_code)]
322 fn temp_path_from_argument_types() {
323 // This just has to compile
324 return;
325
326 TempPath::try_from_path("").unwrap();
327 TempPath::try_from_path(String::new()).unwrap();
328 TempPath::try_from_path(OsStr::new("")).unwrap();
329 TempPath::try_from_path(OsString::new()).unwrap();
330 TempPath::try_from_path(Path::new("")).unwrap();
331 TempPath::try_from_path(PathBuf::new()).unwrap();
332 TempPath::try_from_path(PathBuf::new().into_boxed_path()).unwrap();
333 }
334
335 // This test only works on platforms where we can safely delete the current
336 // working directory.
337 #[test]
338 #[cfg(not(any(target_os = "redox", target_os = "wasi", windows)))]
339 fn test_temp_path_resolve_missing_cwd() {
340 configure_wasi_temp_dir();
341 let _guard = cwd_lock();
342
343 // Intentionally delete the current working directory
344 let tmpdir = tempdir().unwrap();
345 std::env::set_current_dir(&tmpdir).expect("failed to change to the temporary directory");
346 tmpdir.close().unwrap();
347
348 #[allow(deprecated)]
349 let path = TempPath::from_path("foo");
350 assert_eq!(&*path, Path::new("foo"));
351
352 TempPath::try_from_path("foo").expect_err("should have failed to make path absolute file");
353 }
354
355 #[test]
356 fn test_temp_path_resolve_existing_cwd() {
357 configure_wasi_temp_dir();
358 let _guard = cwd_lock();
359
360 let tmpdir = tempdir().unwrap();
361 std::env::set_current_dir(&tmpdir).expect("failed to change to directory");
362
363 let cwd = if cfg!(target_os = "macos") {
364 // MacOS has absolute paths and ABSOLUTE paths. `cd /var/tmp/...` actually changes to
365 // /private/var/tmp...
366 std::env::current_dir().expect("failed to get the current directory")
367 } else {
368 tmpdir.path().to_owned()
369 };
370
371 #[allow(deprecated)]
372 let path = TempPath::from_path("foo");
373 assert_eq!(&*path, cwd.join("foo"));
374
375 #[allow(deprecated)]
376 let path = TempPath::from_path("");
377 assert_eq!(&*path, Path::new(""));
378
379 TempPath::try_from_path("").expect_err("empty paths should fail");
380 }
381
382 #[test]
383 fn test_write_after_close() {
384 configure_wasi_temp_dir();
385
386 let path = NamedTempFile::new().unwrap().into_temp_path();
387 File::create(path).unwrap().write_all(b"test").unwrap();
388 }
389
390 #[test]
391 fn test_change_dir() {
392 configure_wasi_temp_dir();
393 let _guard = cwd_lock();
394
395 let dir_a = tempdir().unwrap();
396 let dir_b = tempdir().unwrap();
397
398 std::env::set_current_dir(&dir_a).expect("failed to change to directory A");
399 let tmpfile = NamedTempFile::new_in(".").unwrap();
400 let path = std::env::current_dir().unwrap().join(tmpfile.path());
401 std::env::set_current_dir(&dir_b).expect("failed to change to directory B");
402 drop(tmpfile);
403 assert!(!exists(path));
404
405 drop(dir_a);
406 drop(dir_b);
407 }
408
409 #[test]
410 fn test_change_dir_make() {
411 configure_wasi_temp_dir();
412 let _guard = cwd_lock();
413
414 let dir_a = tempdir().unwrap();
415 let dir_b = tempdir().unwrap();
416
417 std::env::set_current_dir(&dir_a).expect("failed to change to directory A");
418 let tmpfile = Builder::new().make_in(".", |p| File::create(p)).unwrap();
419 let path = std::env::current_dir().unwrap().join(tmpfile.path());
420 std::env::set_current_dir(&dir_b).expect("failed to change to directory B");
421 drop(tmpfile);
422 assert!(!exists(path));
423
424 drop(dir_a);
425 drop(dir_b);
426 }
427
428 #[test]
429 fn test_into_parts() {
430 configure_wasi_temp_dir();
431
432 let mut file = NamedTempFile::new().unwrap();
433 write!(file, "abcd").expect("write failed");
434
435 let (mut file, temp_path) = file.into_parts();
436
437 let path = temp_path.to_path_buf();
438
439 assert!(path.exists());
440 drop(temp_path);
441 assert!(!path.exists());
442
443 write!(file, "efgh").expect("write failed");
444
445 file.seek(SeekFrom::Start(0)).unwrap();
446 let mut buf = String::new();
447 file.read_to_string(&mut buf).unwrap();
448 assert_eq!("abcdefgh", buf);
449 }
450
451 #[test]
452 fn test_from_parts() {
453 configure_wasi_temp_dir();
454
455 let mut file = NamedTempFile::new().unwrap();
456 write!(file, "abcd").expect("write failed");
457
458 let (file, temp_path) = file.into_parts();
459
460 let file = NamedTempFile::from_parts(file, temp_path);
461
462 assert!(file.path().exists());
463 }
464
465 #[test]
466 fn test_keep() {
467 configure_wasi_temp_dir();
468
469 let mut tmpfile = NamedTempFile::new().unwrap();
470 write!(tmpfile, "abcde").unwrap();
471 let (mut f, temp_path) = tmpfile.into_parts();
472 let path;
473 {
474 assert!(exists(&temp_path));
475 path = temp_path.keep().unwrap();
476 assert!(exists(&path));
477
478 // Check original file
479 f.seek(SeekFrom::Start(0)).unwrap();
480 let mut buf = String::new();
481 f.read_to_string(&mut buf).unwrap();
482 assert_eq!("abcde", buf);
483 }
484
485 {
486 // Try opening it again.
487 let mut f = File::open(&path).unwrap();
488 f.seek(SeekFrom::Start(0)).unwrap();
489 let mut buf = String::new();
490 f.read_to_string(&mut buf).unwrap();
491 assert_eq!("abcde", buf);
492 }
493 std::fs::remove_file(&path).unwrap();
494 }
495
496 #[test]
497 fn test_disable_cleanup() {
498 configure_wasi_temp_dir();
499
500 // Case 0: never mark as "disable cleanup"
501 // Case 1: enable "disable cleanup" in the builder, don't touch it after.
502 // Case 2: enable "disable cleanup" in the builder, turn it off after.
503 // Case 3: don't enable disable cleanup in the builder, turn it on after.
504
505 for case in 0..4 {
506 let in_builder = case & 1 > 0;
507 let toggle = case & 2 > 0;
508 let mut tmpfile = Builder::new()
509 .disable_cleanup(in_builder)
510 .tempfile()
511 .unwrap();
512 write!(tmpfile, "abcde").unwrap();
513 if toggle {
514 tmpfile.disable_cleanup(!in_builder);
515 }
516
517 let path = tmpfile.path().to_owned();
518 drop(tmpfile);
519
520 if in_builder ^ toggle {
521 // Try opening it again.
522 let mut f = File::open(&path).unwrap();
523 let mut buf = String::new();
524 f.read_to_string(&mut buf).unwrap();
525 assert_eq!("abcde", buf);
526 std::fs::remove_file(&path).unwrap();
527 } else {
528 assert!(!path.exists(), "tempfile wasn't deleted");
529 }
530 }
531 }
532
533 #[test]
534 fn test_make() {
535 configure_wasi_temp_dir();
536
537 let tmpfile = Builder::new().make(|path| File::create(path)).unwrap();
538
539 assert!(tmpfile.path().is_file());
540 }
541
542 #[test]
543 fn test_make_in() {
544 configure_wasi_temp_dir();
545
546 let tmp_dir = tempdir().unwrap();
547
548 let tmpfile = Builder::new()
549 .make_in(tmp_dir.path(), |path| File::create(path))
550 .unwrap();
551
552 assert!(tmpfile.path().is_file());
553 assert_eq!(tmpfile.path().parent(), Some(tmp_dir.path()));
554 }
555
556 #[test]
557 fn test_make_fnmut() {
558 configure_wasi_temp_dir();
559
560 let mut count = 0;
561
562 // Show that an FnMut can be used.
563 let tmpfile = Builder::new()
564 .make(|path| {
565 count += 1;
566 File::create(path)
567 })
568 .unwrap();
569
570 assert!(tmpfile.path().is_file());
571 }
572
573 #[cfg(unix)]
574 #[test]
575 fn test_make_uds() {
576 use std::os::unix::net::UnixListener;
577
578 let temp_sock = Builder::new()
579 .prefix("tmp")
580 .suffix(".sock")
581 .rand_bytes(12)
582 .make(|path| UnixListener::bind(path))
583 .unwrap();
584
585 assert!(temp_sock.path().exists());
586 }
587
588 // This works(ish) on redox, but it's really slow.
589 #[cfg(all(unix, not(target_os = "redox")))]
590 #[test]
591 fn test_make_uds_conflict() {
592 use std::io::ErrorKind;
593 use std::os::unix::net::UnixListener;
594
595 let sockets = std::iter::repeat_with(|| {
596 Builder::new()
597 .prefix("tmp")
598 .suffix(".sock")
599 .rand_bytes(1)
600 .make(|path| UnixListener::bind(path))
601 })
602 .take_while(|r| match r {
603 Ok(_) => true,
604 Err(e) if matches!(e.kind(), ErrorKind::AddrInUse | ErrorKind::AlreadyExists) => false,
605 Err(e) => panic!("unexpected error {e}"),
606 })
607 .collect::<Result<Vec<_>, _>>()
608 .unwrap();
609
610 // Number of sockets we can create. Depends on whether or not the filesystem is case sensitive.
611
612 #[cfg(target_os = "macos")]
613 const NUM_FILES: usize = 36;
614 #[cfg(not(target_os = "macos"))]
615 const NUM_FILES: usize = 62;
616
617 assert_eq!(sockets.len(), NUM_FILES);
618
619 for socket in sockets {
620 assert!(socket.path().exists());
621 }
622 }
623
624 /// Make sure we re-seed with system randomness if we run into a conflict.
625 #[test]
626 fn test_reseed() {
627 configure_wasi_temp_dir();
628
629 // Deterministic seed.
630 fastrand::seed(42);
631
632 // I need to create 5 conflicts but I can't just make 5 temporary files because we fork the RNG
633 // each time we create a file.
634 let mut attempts = 0;
635 let mut files: Vec<_> = Vec::new();
636 let _ = Builder::new().make(|path| -> io::Result<File> {
637 if attempts == 5 {
638 return Err(io::Error::new(io::ErrorKind::Other, "stop!"));
639 }
640 attempts += 1;
641 let f = File::options()
642 .write(true)
643 .create_new(true)
644 .open(path)
645 .unwrap();
646
647 files.push(NamedTempFile::from_parts(
648 f,
649 TempPath::try_from_path(path).unwrap(),
650 ));
651 Err(io::Error::new(io::ErrorKind::AlreadyExists, "fake!"))
652 });
653
654 assert_eq!(5, attempts);
655 attempts = 0;
656
657 // Re-seed to cause a conflict.
658 fastrand::seed(42);
659
660 let _f = Builder::new()
661 .make(|path| {
662 attempts += 1;
663 File::options().write(true).create_new(true).open(path)
664 })
665 .unwrap();
666
667 // We expect exactly three conflict before we re-seed with system randomness.
668 assert_eq!(4, attempts);
669 }
670
671 // Issue #224.
672 #[test]
673 fn test_overly_generic_bounds() {
674 pub struct Foo<T>(T);
675
676 impl<T> Foo<T>
677 where
678 T: Sync + Send + 'static,
679 for<'a> &'a T: Write + Read,
680 {
681 pub fn new(foo: T) -> Self {
682 Self(foo)
683 }
684 }
685
686 // Don't really need to run this. Only care if it compiles.
687 if let Ok(file) = File::open("i_do_not_exist") {
688 let mut f;
689 let _x = {
690 f = Foo::new(file);
691 &mut f
692 };
693 }
694 }