[pdm-devel] [PATCH proxmox-datacenter-manager 02/15] test support: add NamedTempFile helper

Lukas Wagner l.wagner at proxmox.com
Tue Jan 28 13:25:07 CET 2025


This one is useful when writing tests, it automatically removes the
temporary file when dropped. The name was chosen because of the similar
NamedTempFile struct in the popular tempfile crate.

Signed-off-by: Lukas Wagner <l.wagner at proxmox.com>
---
 server/src/lib.rs               |  2 +-
 server/src/test_support/mod.rs  |  4 ++++
 server/src/test_support/temp.rs | 33 +++++++++++++++++++++++++++++++++
 3 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 server/src/test_support/temp.rs

diff --git a/server/src/lib.rs b/server/src/lib.rs
index 12dc912..143ee32 100644
--- a/server/src/lib.rs
+++ b/server/src/lib.rs
@@ -13,7 +13,7 @@ pub mod task_utils;
 pub mod connection;
 pub mod pbs_client;
 
-#[cfg(remote_config = "faked")]
+#[cfg(any(remote_config = "faked", test))]
 pub mod test_support;
 
 use anyhow::Error;
diff --git a/server/src/test_support/mod.rs b/server/src/test_support/mod.rs
index e54cd72..f026011 100644
--- a/server/src/test_support/mod.rs
+++ b/server/src/test_support/mod.rs
@@ -1 +1,5 @@
+#[cfg(remote_config = "faked")]
 pub mod fake_remote;
+
+#[cfg(test)]
+pub mod temp;
diff --git a/server/src/test_support/temp.rs b/server/src/test_support/temp.rs
new file mode 100644
index 0000000..a3a6d59
--- /dev/null
+++ b/server/src/test_support/temp.rs
@@ -0,0 +1,33 @@
+use std::path::{Path, PathBuf};
+
+use anyhow::Error;
+
+use proxmox_sys::fs::CreateOptions;
+
+/// Temporary file that be cleaned up when dropped.
+pub struct NamedTempFile {
+    path: PathBuf,
+}
+
+impl NamedTempFile {
+    /// Create a new temporary file.
+    ///
+    /// The file will be created with the passed [`CreateOptions`].
+    pub fn new(options: CreateOptions) -> Result<Self, Error> {
+        let base = std::env::temp_dir().join("test");
+        let (_, path) = proxmox_sys::fs::make_tmp_file(base, options)?;
+
+        Ok(Self { path })
+    }
+
+    /// Return the [`Path`] to the temporary file.
+    pub fn path(&self) -> &Path {
+        &self.path
+    }
+}
+
+impl Drop for NamedTempFile {
+    fn drop(&mut self) {
+        let _ = std::fs::remove_file(&self.path);
+    }
+}
-- 
2.39.5





More information about the pdm-devel mailing list