Skip to content

Commit e4f5d29

Browse files
committed
fix: add test-only LockFile::read_pid for cross-platform testing
Fixes an issue encountered in the CI overhaul PR #253. Open lock file with read+write access and add test-only `read_pid` function that reads from the same file handle. This works on Windows where exclusive locks prevent reading through another file handle: ``` thread 'storage::lockfile::tests::test_lock_file_contains_pid' (8952) panicked at dash-spv\src\storage\lockfile.rs:72:59: Should read lock file: Os { code: 33, kind: Uncategorized, message: "The process cannot access the file because another process has locked a portion of the file." } ```
1 parent 3884314 commit e4f5d29

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

dash-spv/src/storage/lockfile.rs

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Lock file implementation and related unit tests.
22
3-
use std::fs::File;
3+
use std::fs::{File, OpenOptions};
44
use std::io::Write;
55
use std::path::PathBuf;
66

@@ -14,7 +14,12 @@ pub(super) struct LockFile {
1414

1515
impl LockFile {
1616
pub(super) fn new(path: PathBuf) -> StorageResult<Self> {
17-
let mut file = File::create(&path)
17+
let mut file = OpenOptions::new()
18+
.read(true)
19+
.write(true)
20+
.create(true)
21+
.truncate(true)
22+
.open(&path)
1823
.map_err(|e| StorageError::WriteFailed(format!("Failed to create lock file: {}", e)))?;
1924

2025
file.try_lock().map_err(|e| match e {
@@ -49,8 +54,22 @@ impl Drop for LockFile {
4954
#[cfg(test)]
5055
mod tests {
5156
use super::*;
57+
use std::io::{Read, Seek, SeekFrom};
5258
use tempfile::TempDir;
5359

60+
impl LockFile {
61+
/// Reads the PID from the lock file.
62+
fn read_pid(&mut self) -> std::io::Result<u32> {
63+
self._file.seek(SeekFrom::Start(0))?;
64+
let mut content = String::new();
65+
self._file.read_to_string(&mut content)?;
66+
content
67+
.trim()
68+
.parse()
69+
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
70+
}
71+
}
72+
5473
#[test]
5574
fn test_lock_file_creation() {
5675
let temp_dir = TempDir::new().expect("Failed to create temp directory");
@@ -67,11 +86,8 @@ mod tests {
6786
let temp_dir = TempDir::new().expect("Failed to create temp directory");
6887
let lock_path = temp_dir.path().join(".lock");
6988

70-
let _lock = LockFile::new(lock_path.clone()).unwrap();
71-
72-
let content = std::fs::read_to_string(&lock_path).expect("Should read lock file");
73-
let pid: u32 = content.trim().parse().expect("Lock file should contain valid PID");
74-
assert_eq!(pid, std::process::id());
89+
let mut lock = LockFile::new(lock_path.clone()).unwrap();
90+
assert_eq!(lock.read_pid().unwrap(), std::process::id());
7591
}
7692

7793
#[test]

0 commit comments

Comments
 (0)