1From d7a5ccfa9ef25f476deb4e5dac58d164e3c4e0fb Mon Sep 17 00:00:00 2001
2From: Martin Geisler <[email protected]>
3Date: Wed, 17 Apr 2024 13:02:31 +0200
4Subject: [PATCH] fix: use random temporary directory in test
5
6While trying to enable the unit tests in Android (see
7https://r.android.com/3044134), I noticed test failures saying:
8
9    thread 'errno::tests::test_errno' panicked at
10    external/rust/crates/vmm-sys-util/src/errno.rs:156:14:
11    called `Result::unwrap()` on an `Err` value: Os { code: 21, kind:
12    IsADirectory, message: "Is a directory" }
13
14I believe this is because of the hard-coded name for the temporary
15file in the `test_errno` unit test.
16
17Using a randomized path should fix this.
18
19Signed-off-by: Martin Geisler <[email protected]>
20---
21 src/errno.rs | 12 ++++++++----
22 1 file changed, 8 insertions(+), 4 deletions(-)
23
24diff --git a/src/errno.rs b/src/errno.rs
25index 27b9bcf..3478b7c 100644
26--- a/src/errno.rs
27+++ b/src/errno.rs
28@@ -132,7 +132,7 @@ pub fn errno_result<T>() -> Result<T> {
29 #[cfg(test)]
30 mod tests {
31     use super::*;
32-    use std::env::temp_dir;
33+    use crate::tempfile::TempFile;
34     use std::error::Error as _;
35     use std::fs::OpenOptions;
36     use std::io::{self, Read};
37@@ -145,14 +145,16 @@ mod tests {
38         let expected_errno = libc::EIO;
39
40         // try to read from a file without read permissions
41-        let mut path = temp_dir();
42-        path.push("test");
43+        let temp_file = TempFile::new().unwrap();
44+        let path = temp_file.as_path().to_owned();
45+        // Drop temp_file so we can cleanly reuse path below.
46+        std::mem::drop(temp_file);
47         let mut file = OpenOptions::new()
48             .read(false)
49             .write(true)
50             .create(true)
51             .truncate(true)
52-            .open(path)
53+            .open(&path)
54             .unwrap();
55         let mut buf: Vec<u8> = Vec::new();
56         assert!(file.read_to_end(&mut buf).is_err());
57@@ -174,6 +176,8 @@ mod tests {
58         let last_err: io::Error = last_err.into();
59         // Test creating a `std::io::Error` from an `Error`
60         assert_eq!(io::Error::last_os_error().kind(), last_err.kind());
61+
62+        assert!(std::fs::remove_file(&path).is_ok());
63     }
64
65     #[test]
66