]> Untitled Git - bdk/commitdiff
Use tempfile for file_store tests
authorLLFourn <lloyd.fourn@gmail.com>
Thu, 2 Mar 2023 05:44:18 +0000 (16:44 +1100)
committerDaniela Brozzoni <danielabrozzoni@protonmail.com>
Thu, 2 Mar 2023 09:56:37 +0000 (10:56 +0100)
crates/file_store/src/file_store.rs
crates/file_store/tests/test_file_store.rs

index 0d3c0c997bae33858e32964141a6b63165702538..1247e4568e3e7d6321add34f5f5e44ed9e97524d 100644 (file)
@@ -81,7 +81,7 @@ where
     ///
     /// **WARNING**: This method changes the write position in the underlying file. You should
     /// always iterate over all entries until `None` is returned if you want your next write to go
-    /// at the end, otherwise you writing over existing enties.
+    /// at the end, otherwise you will write over existing enties.
     pub fn iter_changesets(
         &mut self,
     ) -> Result<EntryIter<'_, KeychainChangeSet<K, P, T>>, io::Error> {
index 5842c3fd85a2563328f9001fc5499978260a72e2..3baf12adc54c3663371fa4aaa50007a9a9ac9d3d 100644 (file)
@@ -5,53 +5,11 @@ use bdk_chain::{
 };
 use bdk_file_store::{FileError, IterError, KeychainStore, MAGIC_BYTES, MAGIC_BYTES_LEN};
 use serde;
+use tempfile::NamedTempFile;
 use std::{
-    format,
-    fs::{File, OpenOptions},
     io::{Read, Write},
-    path::{Path, PathBuf},
     vec::Vec,
 };
-
-struct TempPath(PathBuf);
-
-impl TempPath {
-    fn new() -> Self {
-        let now = std::time::UNIX_EPOCH
-            .elapsed()
-            .expect("must get epoch")
-            .as_nanos();
-        let mut file_path = std::env::temp_dir();
-        file_path.push(format!("bdk_test_{}", now));
-        Self(file_path)
-    }
-
-    fn open(&self) -> File {
-        OpenOptions::new()
-            .read(true)
-            .write(true)
-            .create(true)
-            .open(self.0.as_path())
-            .expect("must open")
-    }
-}
-
-impl AsRef<Path> for TempPath {
-    fn as_ref(&self) -> &Path {
-        self.0.as_path()
-    }
-}
-
-impl Drop for TempPath {
-    fn drop(&mut self) {
-        if let Err(e) = std::fs::remove_file(self.0.as_path()) {
-            if e.kind() != std::io::ErrorKind::NotFound {
-                panic!("remove file unexpected error: {}", e);
-            }
-        };
-    }
-}
-
 #[derive(
     Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
 )]
@@ -76,12 +34,11 @@ fn magic_bytes() {
 
 #[test]
 fn new_fails_if_file_is_too_short() {
-    let path = TempPath::new();
-    path.open()
-        .write_all(&MAGIC_BYTES[..MAGIC_BYTES_LEN - 1])
+    let mut file = NamedTempFile::new().unwrap();
+    file.write_all(&MAGIC_BYTES[..MAGIC_BYTES_LEN - 1])
         .expect("should write");
 
-    match KeychainStore::<TestKeychain, TxHeight, Transaction>::new(path.open()) {
+    match KeychainStore::<TestKeychain, TxHeight, Transaction>::new(file.reopen().unwrap()) {
         Err(FileError::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof),
         unexpected => panic!("unexpected result: {:?}", unexpected),
     };
@@ -91,12 +48,12 @@ fn new_fails_if_file_is_too_short() {
 fn new_fails_if_magic_bytes_are_invalid() {
     let invalid_magic_bytes = "ldkfs0000000";
 
-    let path = TempPath::new();
-    path.open()
+    let mut file = NamedTempFile::new().unwrap();
+    file
         .write_all(invalid_magic_bytes.as_bytes())
         .expect("should write");
 
-    match KeychainStore::<TestKeychain, TxHeight, Transaction>::new(path.open()) {
+    match KeychainStore::<TestKeychain, TxHeight, Transaction>::new(file.reopen().unwrap()) {
         Err(FileError::InvalidMagicBytes(b)) => {
             assert_eq!(b, invalid_magic_bytes.as_bytes())
         }
@@ -123,10 +80,10 @@ fn append_changeset_truncates_invalid_bytes() {
         chain_graph: Default::default(),
     };
 
-    let path = TempPath::new();
-    path.open().write_all(&data).expect("should write");
+    let mut file = NamedTempFile::new().unwrap();
+    file.write_all(&data).expect("should write");
 
-    let mut store = KeychainStore::<TestKeychain, TxHeight, Transaction>::new(path.open())
+    let mut store = KeychainStore::<TestKeychain, TxHeight, Transaction>::new(file.reopen().unwrap())
         .expect("should open");
     match store.iter_changesets().expect("seek should succeed").next() {
         Some(Err(IterError::Bincode(_))) => {}
@@ -139,7 +96,7 @@ fn append_changeset_truncates_invalid_bytes() {
 
     let got_bytes = {
         let mut buf = Vec::new();
-        path.open().read_to_end(&mut buf).expect("should read");
+        file.reopen().unwrap().read_to_end(&mut buf).expect("should read");
         buf
     };