Debian Codegraph @

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