-
Notifications
You must be signed in to change notification settings - Fork 0
/
uncloneable.rs
86 lines (69 loc) · 2.14 KB
/
uncloneable.rs
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
extern crate pseudo;
use std::{fmt, io};
use std::fmt::{Display, Formatter};
use std::error::Error;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use pseudo::Mock;
trait FileSystem: Clone {
fn copy<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to: Q) -> io::Result<()>;
}
fn copy_to_all<FS: FileSystem, P: AsRef<Path>>(fs: &FS, from: P, to: &[P]) -> Vec<io::Result<()>> {
to.iter()
.map(|path| fs.copy(&from, &path))
.collect::<Vec<io::Result<()>>>()
}
#[derive(Debug, Clone)]
struct MockFileSystem<'a> {
pub copy: Mock<(PathBuf, PathBuf), Result<(), CloneableError<'a>>>,
}
impl<'a> FileSystem for MockFileSystem<'a> {
fn copy<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to: Q) -> io::Result<()> {
let args = (from.as_ref().to_path_buf(), to.as_ref().to_path_buf());
self.copy.call(args).map_err(|err| {
let (kind, description) = (err.kind, err.description);
io::Error::new(kind, description)
})
}
}
impl<'a> Default for MockFileSystem<'a> {
fn default() -> Self {
MockFileSystem {
copy: Mock::new(Ok(())),
}
}
}
#[derive(Debug, Clone)]
struct CloneableError<'a> {
pub kind: io::ErrorKind,
pub description: &'a str,
}
impl<'a> Error for CloneableError<'a> {
fn description(&self) -> &str {
self.description
}
}
impl<'a> Display for CloneableError<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
fn main() {
// Initially, the `copy` mock returns `Ok()`
let mock = MockFileSystem::default();
let result = copy_to_all(&mock, "from", &["to"]);
assert!(result.iter().all(|res| res.is_ok()));
assert_eq!(mock.copy.num_calls(), 1);
let expected_args = (
Path::new("from").to_path_buf(),
Path::new("to").to_path_buf(),
);
assert!(mock.copy.called_with(expected_args));
let err = CloneableError {
kind: ErrorKind::NotFound,
description: "test",
};
mock.copy.return_err(err);
let result = copy_to_all(&mock, "from", &["to"]);
assert!(result.iter().all(|res| res.is_err()));
}