1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
//! Create and manage temporary file used for unit tests.
//! File is deleted on Drop

/**
 * File content initializer closure.
 * Initializes TestFile with content.
*/
/*
#![feature(trait_alias)]
pub trait FileInitializer = Fn (&mut TestFile) -> std::io::Result<()>;
*/

use std::mem::ManuallyDrop;

/**
 * TestFile structure.
 * Holds opened File and PathBuf.
 * Files are created in temporary directory with unique names. Deleted on Drop.
 * This structure can be dereferenced to &File and implements
 * AsRef for Path, PathBuf and File.
*/
pub struct TestFile {
      file : ManuallyDrop<std::fs::File>,
      path : std::path::PathBuf
}

/**
  Removes TestFile from disk.
*/
impl Drop for TestFile {
    fn drop(&mut self) {
        unsafe { ManuallyDrop::drop(&mut self.file) };
        let _ = std::fs::remove_file(&self.path);
    }
}

use std::ops::{Deref,DerefMut};
use std::convert::{AsRef,AsMut};

impl AsRef<std::path::Path> for TestFile {
   fn as_ref(&self) -> &std::path::Path {
       &self.path
   }
}

impl AsRef<std::path::PathBuf> for TestFile {
    fn as_ref(&self) -> &std::path::PathBuf {
        &self.path
    }
}

impl AsRef<std::fs::File> for TestFile {
   fn as_ref(&self) -> &std::fs::File {
       &self.file
   }
}

impl AsMut<std::fs::File> for TestFile {
   fn as_mut(&mut self) -> &mut std::fs::File {
       &mut self.file
   }
}

impl AsMut<dyn std::io::Read> for TestFile {
   fn as_mut(&mut self) -> &mut (dyn std::io::Read + 'static) {
        self.file.deref_mut()
   }
}

impl AsMut<dyn std::io::Write> for TestFile {
   fn as_mut(&mut self) -> &mut (dyn std::io::Write + 'static) {
        self.file.deref_mut()
   }
}

impl AsMut<TestFile> for TestFile {
   fn as_mut(&mut self) -> &mut TestFile {
        self
   }
}

impl Deref for TestFile {
   type Target = std::fs::File;
   fn deref(&self) -> &Self::Target { &self.file }
}

impl DerefMut for TestFile {
   fn deref_mut(&mut self) -> &mut Self::Target { &mut self.file }
}

/**
 * Turns file into TestFile
*/
pub fn from_file(path: impl AsRef<std::path::Path>) -> TestFile {
   std::fs::OpenOptions::new().read(true).write(true).create_new(false).open(path.as_ref()).map(
      |f| TestFile{ file:ManuallyDrop::new(f), path:std::path::PathBuf::new() }).map(
      |mut tf| { tf.path.push(path.as_ref());tf})
      .unwrap()
}

/**
 * Create an empty test file
*/
pub fn empty() -> TestFile {
    create(|_unused| Ok(()))
}

/**
  Create a TestFile from string
*/
pub fn from<T: AsRef<str>>(content: T) -> TestFile {
    use std::io::Write;
    create(|tfile| tfile.file.write_all(content.as_ref().as_bytes()))
}

/**
 * Create test file with content supplied by initializer closure
*/
pub fn create<I>(initializer: I) -> TestFile
     where I: Fn (&mut TestFile) -> std::io::Result<()> {
   let mut retries = 6;
   let mut rng = rand::thread_rng();
   use rand::Rng;
   use std::fs::OpenOptions;
   use std::io::{Seek, SeekFrom};

   while retries > 0 {
      retries-=1;
      let mut tmp = std::env::temp_dir();
      tmp.push(format!("TMP{}",rng.gen_range::<_,u32,u32>(0,1000)));
      match OpenOptions::new().read(true).write(true).create_new(true).open(&tmp).map(
      |f| TestFile{ file:ManuallyDrop::new(f), path:tmp }
      ).and_then(|mut tfile:TestFile| -> std::io::Result<TestFile> { match initializer(<TestFile as AsMut<TestFile>>::as_mut(&mut tfile)) { Ok(_) => Ok(tfile), Err(ioerr) => Err(ioerr) }}
      ).and_then(|mut tfile| match tfile.file.seek(SeekFrom::Start(0)) { Ok(_) => Ok(tfile), Err(ioerr) => Err(ioerr) }
      ).and_then(|mut tfile| match <dyn std::io::Write>::flush(<TestFile as AsMut<std::fs::File>>::as_mut(&mut tfile)) { Ok(_) => Ok(tfile), Err(ioerr) => Err(ioerr) }
      ) {
         Ok(tfile) => return tfile,
         Err(_) => continue
      }
   }
   panic!("Can't create temporary file")
}

/**
 * Generate unique tmp file name
 */
pub fn generate_name() -> std::path::PathBuf {
   let mut retries = 10;
   let mut rng = rand::thread_rng();
   use rand::Rng;
   use std::fs::OpenOptions;

   while retries > 0 {
      retries-=1;
      let mut tmp = std::env::temp_dir();
      tmp.push(format!("TMP{}", rng.gen_range::<_,u32,u32>(0,1000)));
      match OpenOptions::new().read(true).write(true).create_new(true).open(&tmp).map(
      |f| { drop(f); let _ignored = std::fs::remove_file(&tmp); () })
      {
         Ok(()) => return tmp,
         Err(_) => continue
      }
   }
   panic!("Can't generate suitable tmp file name");
}

#[cfg(test)]
#[path= "./lib_tests.rs"]
mod tests;