agplatform 0.4.0

Platform providing env, fs, request and process infrastructure for production and testing
Documentation
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::panic::Location;
use std::path::Path;
use std::path::PathBuf;

/// Enabled by the `testing` feature flag.
///
/// A real directory for tests and benchmarks, created empty and removed
/// with its content when dropped.
///
/// The name is derived from the source location of the caller, e.g.
/// `agplatform_src_fs.rs.42.21.testdir`, so that it is unique per call
/// site and any leftover points back to the code that created it. A
/// call site executed repeatedly (in a loop or through a helper function
/// without `#[track_caller]`) reuses the same directory.
///
/// When dropped during a panic (e.g. a failing assertion) the directory
/// is kept for inspection. It is removed by the next run of the same
/// code.
///
/// # Examples
///
/// ```rust
/// use agplatform::TestDir;
///
/// let dir = TestDir::new();
/// std::fs::write(dir.path().join("file.txt"), "content").unwrap();
/// let path = dir.path().to_path_buf();
/// drop(dir);
///
/// assert!(!path.exists());
/// ```
pub struct TestDir {
    path: PathBuf,
}

impl TestDir {
    /// Creates an empty directory in the current directory. Any existing
    /// directory of the same name is removed first.
    ///
    /// # Panics
    ///
    /// Panics if the current directory cannot be determined or the
    /// directory cannot be created.
    #[track_caller]
    pub fn new() -> Self {
        Self::create(caller_path(&current_dir(), "testdir"))
    }

    /// Creates an empty directory in [`std::env::temp_dir()`] (on Unix
    /// overridable with `TMPDIR`, e.g. `TMPDIR=/dev/shm`). Any existing
    /// directory of the same name is removed first.
    ///
    /// # Panics
    ///
    /// Panics if the directory cannot be created.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::TestDir;
    ///
    /// let dir = TestDir::temp();
    ///
    /// assert!(dir.path().starts_with(std::env::temp_dir()));
    /// ```
    #[track_caller]
    pub fn temp() -> Self {
        Self::create(caller_path(&std::env::temp_dir(), "testdir"))
    }

    /// Returns the path of the directory.
    pub fn path(&self) -> &Path {
        &self.path
    }

    fn create(path: PathBuf) -> Self {
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).unwrap_or_else(|e| {
            panic!(
                "Test directory could not be created: {}: {e}",
                path.display()
            )
        });

        Self { path }
    }
}

impl Default for TestDir {
    /// Same as [`Self::new`].
    #[track_caller]
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for TestDir {
    fn drop(&mut self) {
        if !std::thread::panicking() {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }
}

/// Enabled by the `testing` feature flag.
///
/// A path to a real file for tests and benchmarks. The file is not
/// created, only removed if it exists, both on creation and when
/// dropped.
///
/// It is named and kept on panic the same way as [`TestDir`], with the
/// `testfile` extension. Prefer [`TestDir`] when a test needs more than
/// one file.
///
/// # Examples
///
/// ```rust
/// use agplatform::TestFile;
///
/// let file = TestFile::new();
/// std::fs::write(file.path(), "content").unwrap();
/// let path = file.path().to_path_buf();
/// drop(file);
///
/// assert!(!path.exists());
/// ```
pub struct TestFile {
    path: PathBuf,
}

impl TestFile {
    /// Creates a path to a file in the current directory, removing the
    /// file if it exists.
    ///
    /// # Panics
    ///
    /// Panics if the current directory cannot be determined.
    #[track_caller]
    pub fn new() -> Self {
        Self::create(caller_path(&current_dir(), "testfile"))
    }

    /// Creates a path to a file in [`std::env::temp_dir()`] (on Unix
    /// overridable with `TMPDIR`, e.g. `TMPDIR=/dev/shm`), removing the
    /// file if it exists.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::TestFile;
    ///
    /// let file = TestFile::temp();
    ///
    /// assert!(file.path().starts_with(std::env::temp_dir()));
    /// ```
    #[track_caller]
    pub fn temp() -> Self {
        Self::create(caller_path(&std::env::temp_dir(), "testfile"))
    }

    /// Returns the path of the file.
    pub fn path(&self) -> &Path {
        &self.path
    }

    fn create(path: PathBuf) -> Self {
        let _ = std::fs::remove_file(&path);
        Self { path }
    }
}

impl Default for TestFile {
    /// Same as [`Self::new`].
    #[track_caller]
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for TestFile {
    fn drop(&mut self) {
        if !std::thread::panicking() {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

fn current_dir() -> PathBuf {
    std::env::current_dir().expect("current directory should be accessible")
}

/// Returns `parent` joined with a name unique to the caller's source
/// location: its file path with separators replaced by `_`, line, column
/// and `extension`.
#[track_caller]
fn caller_path(parent: &Path, extension: &str) -> PathBuf {
    let caller = Location::caller();

    parent.join(format!(
        "{}.{}.{}.{extension}",
        caller.file().replace(['/', '\\', ':'], "_"),
        caller.line(),
        caller.column()
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Runs `f` and unwinds without invoking the panic hook while holding
    /// the guard it returns, returning the path it returns.
    fn unwind_holding<T>(f: impl FnOnce() -> (T, PathBuf)) -> PathBuf {
        let mut path = PathBuf::new();
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let (_guard, guarded_path) = f();
            path = guarded_path;
            std::panic::resume_unwind(Box::new(()));
        }));
        path
    }

    /// Returns the sanitized source file part of a name created by
    /// [`caller_path`].
    fn caller_file(path: &Path) -> &str {
        let name = path.file_name().unwrap().to_str().unwrap();
        name.split_once(".rs.").unwrap().0
    }

    mod test_dir {
        use super::*;

        mod new {
            use super::*;

            #[test]
            fn new_should_create_empty_dir_named_after_caller_in_current_dir() {
                let dir = TestDir::new();

                assert_eq!(dir.path().parent().unwrap(), current_dir());
                assert_eq!(caller_file(dir.path()), "agplatform_src_testing");
                assert!(dir.path().is_dir());
                assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
            }

            #[test]
            fn new_should_replace_existing_dir() {
                // GIVEN a leftover directory with content
                fn create() -> TestDir {
                    TestDir::new()
                }
                let path = unwind_holding(|| {
                    let dir = create();
                    std::fs::write(dir.path().join("leftover.txt"), "").unwrap();
                    let path = dir.path().to_path_buf();
                    (dir, path)
                });

                // WHEN created again at the same call site
                let dir = create();

                // THEN the directory is empty
                assert_eq!(dir.path(), path);
                assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
            }

            #[test]
            fn new_at_different_call_sites_should_create_different_dirs() {
                let a = TestDir::new();
                let b = TestDir::new();

                assert_ne!(a.path(), b.path());
            }
        }

        mod temp {
            use super::*;

            #[test]
            fn temp_should_create_dir_named_after_caller_in_temp_dir() {
                let dir = TestDir::temp();

                assert_eq!(dir.path().parent().unwrap(), std::env::temp_dir());
                assert_eq!(caller_file(dir.path()), "agplatform_src_testing");
                assert!(dir.path().is_dir());
            }
        }

        mod create {
            use super::*;

            #[test]
            fn create_under_file_should_panic() {
                // GIVEN a parent that is a file
                let file = TestFile::new();
                std::fs::write(file.path(), "").unwrap();

                // WHEN creating a directory in it
                let result = std::panic::catch_unwind(|| TestDir::create(file.path().join("dir")));

                // THEN it panics
                assert!(result.is_err());
            }
        }

        mod default {
            use super::*;

            #[test]
            fn default_should_create_dir_named_after_caller() {
                let dir = TestDir::default();

                assert_eq!(caller_file(dir.path()), "agplatform_src_testing");
                assert!(dir.path().is_dir());
            }
        }

        mod drop {
            use super::*;

            #[test]
            fn drop_should_remove_dir_with_content() {
                let dir = TestDir::new();
                std::fs::create_dir(dir.path().join("sub")).unwrap();
                std::fs::write(dir.path().join("sub").join("a.txt"), "").unwrap();
                let path = dir.path().to_path_buf();

                drop(dir);

                assert!(!path.exists());
            }

            #[test]
            fn drop_while_panicking_should_keep_dir() {
                let path = unwind_holding(|| {
                    let dir = TestDir::new();
                    let path = dir.path().to_path_buf();
                    (dir, path)
                });

                assert!(path.is_dir());
                std::fs::remove_dir_all(path).unwrap();
            }
        }
    }

    mod test_file {
        use super::*;

        mod new {
            use super::*;

            #[test]
            fn new_should_name_file_after_caller_in_current_dir_without_creating_it() {
                let file = TestFile::new();

                assert_eq!(file.path().parent().unwrap(), current_dir());
                assert_eq!(caller_file(file.path()), "agplatform_src_testing");
                assert_eq!(file.path().extension().unwrap(), "testfile");
                assert!(!file.path().exists());
            }

            #[test]
            fn new_should_remove_existing_file() {
                // GIVEN a leftover file
                fn create() -> TestFile {
                    TestFile::new()
                }
                let path = unwind_holding(|| {
                    let file = create();
                    std::fs::write(file.path(), "leftover").unwrap();
                    let path = file.path().to_path_buf();
                    (file, path)
                });

                // WHEN created again at the same call site
                let file = create();

                // THEN the file does not exist
                assert_eq!(file.path(), path);
                assert!(!file.path().exists());
            }
        }

        mod temp {
            use super::*;

            #[test]
            fn temp_should_name_file_after_caller_in_temp_dir_without_creating_it() {
                let file = TestFile::temp();

                assert_eq!(file.path().parent().unwrap(), std::env::temp_dir());
                assert_eq!(caller_file(file.path()), "agplatform_src_testing");
                assert!(!file.path().exists());
            }
        }

        mod default {
            use super::*;

            #[test]
            fn default_should_name_file_after_caller() {
                let file = TestFile::default();

                assert_eq!(caller_file(file.path()), "agplatform_src_testing");
            }
        }

        mod drop {
            use super::*;

            #[test]
            fn drop_should_remove_file() {
                let file = TestFile::new();
                std::fs::write(file.path(), "").unwrap();
                let path = file.path().to_path_buf();

                drop(file);

                assert!(!path.exists());
            }

            #[test]
            fn drop_while_panicking_should_keep_file() {
                let path = unwind_holding(|| {
                    let file = TestFile::new();
                    std::fs::write(file.path(), "").unwrap();
                    let path = file.path().to_path_buf();
                    (file, path)
                });

                assert!(path.is_file());
                std::fs::remove_file(path).unwrap();
            }
        }
    }
}