Use tempfile for file_store tests

This commit is contained in:
LLFourn 2023-03-02 16:44:18 +11:00 committed by Daniela Brozzoni
parent c069b0fb41
commit 2e82cd8c04
No known key found for this signature in database
GPG Key ID: 7DE4F1FDCED0AB87
2 changed files with 12 additions and 55 deletions

View 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> {

View 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
};