Debian Codegraph @

debian/missing-sources/tempfile/tests/tempfile.rs

raw
1 #![deny(rust_2018_idioms)]
2
3 use std::fs;
4 use std::io::{Read, Seek, SeekFrom, Write};
5 #[cfg(target_os = "linux")]
6 use std::{
7 sync::mpsc::{sync_channel, TryRecvError},
8 thread,
9 };
10
11 #[test]
12 fn test_basic() {
13 // For the wasi platforms, `std::env::temp_dir` will panic. For those targets, configure the /tmp
14 // directory instead as the base directory for temp files.
15 #[cfg(target_os = "wasi")]
16 let _ = tempfile::env::override_temp_dir(std::path::Path::new("/tmp"));
17
18 let mut tmpfile = tempfile::tempfile().unwrap();
19 write!(tmpfile, "abcde").unwrap();
20 tmpfile.seek(SeekFrom::Start(0)).unwrap();
21 let mut buf = String::new();
22 tmpfile.read_to_string(&mut buf).unwrap();
23 assert_eq!("abcde", buf);
24 }
25
26 #[test]
27 fn test_cleanup() {
28 // For the wasi platforms, `std::env::temp_dir` will panic. For those targets, configure the /tmp
29 // directory instead as the base directory for temp files.
30 #[cfg(target_os = "wasi")]
31 let _ = tempfile::env::override_temp_dir(std::path::Path::new("/tmp"));
32
33 let tmpdir = tempfile::tempdir().unwrap();
34 {
35 let mut tmpfile = tempfile::tempfile_in(&tmpdir).unwrap();
36 write!(tmpfile, "abcde").unwrap();
37 }
38 let num_files = fs::read_dir(&tmpdir).unwrap().count();
39 assert!(num_files == 0);
40 }
41
42 // Only run this test on Linux. MacOS doesn't like us creating so many files, apparently.
43 #[cfg(target_os = "linux")]
44 #[test]
45 fn test_pathological_cleaner() {
46 let tmpdir = tempfile::tempdir().unwrap();
47 let (tx, rx) = sync_channel(0);
48 let cleaner_thread = thread::spawn(move || {
49 let tmp_path = rx.recv().unwrap();
50 while rx.try_recv() == Err(TryRecvError::Empty) {
51 let files = fs::read_dir(&tmp_path).unwrap();
52 for f in files {
53 // skip errors
54 if f.is_err() {
55 continue;
56 }
57 let f = f.unwrap();
58 let _ = fs::remove_file(f.path());
59 }
60 }
61 });
62
63 // block until cleaner_thread makes progress
64 tx.send(tmpdir.path().to_owned()).unwrap();
65 // need 40-400 iterations to encounter race with cleaner on original system
66 for _ in 0..10000 {
67 let mut tmpfile = tempfile::tempfile_in(&tmpdir).unwrap();
68 write!(tmpfile, "abcde").unwrap();
69 tmpfile.seek(SeekFrom::Start(0)).unwrap();
70 let mut buf = String::new();
71 tmpfile.read_to_string(&mut buf).unwrap();
72 assert_eq!("abcde", buf);
73 }
74
75 // close the channel to make cleaner_thread exit
76 drop(tx);
77 cleaner_thread.join().expect("The cleaner thread failed");
78 }