Add a convenience function to preserve a test's state.

- Add `Sq::preserve` to prevent the files created by an `Sq`
    instance from being deleted when the `Sq` instance is dropped.

  - Preserving the state makes it easier to debug a test that is
    failing.
This commit is contained in:
Neal H. Walfield 2024-08-24 12:49:55 +02:00
parent 7d6040b5ad
commit 910edc96f6
No known key found for this signature in database
GPG Key ID: 6863C9AD5B4D22D3

View File

@ -156,6 +156,10 @@ impl FileOrKeyHandle {
pub struct Sq {
base: TempDir,
// Whether to preserve the directory on exit. Normally we clean
// it up, but preserving it can simplify debugging when a test
// fails.
preserve: bool,
home: PathBuf,
policy: PathBuf,
certd: PathBuf,
@ -163,6 +167,26 @@ pub struct Sq {
scratch: AtomicUsize,
}
impl Drop for Sq {
fn drop(&mut self) {
if self.preserve {
self.preserve = false;
match TempDir::new() {
Ok(tmp) => {
let base = std::mem::replace(&mut self.base, tmp);
let path = base.into_path();
eprintln!("Preserving state in {}", path.display());
}
Err(err) => {
eprintln!("Error preserving state in {}: {}",
self.base.path().display(), err);
}
}
}
}
}
impl Sq {
/// Creates a new Sq context in a new, emphemeral home directory.
/// The clock is set to the specified time.
@ -181,6 +205,7 @@ impl Sq {
Sq {
base,
preserve: false,
home,
policy,
certd,
@ -200,6 +225,16 @@ impl Sq {
Self::at(now)
}
/// Preserves the files on exit.
///
/// Normally we clean delete all files and directories. This
/// suppresses that behavior. Preserving the state can facilitate
/// debugging. Normally, you'll only enable this to debug a test,
/// and then disable it again.
pub fn preserve(&mut self) {
self.preserve = true;
}
/// Returns the base directory.
///
/// The sequoia home directory is under the `home` subdirectory.