io_test_util/
error_reader.rs

1use std::io::{self, ErrorKind};
2
3/// An implementation of `std::io::Read` that fails on the first call to `read` and throws
4/// an `std::io::Error` with the given ErrorKind.
5#[derive(Debug, PartialEq)]
6pub struct ErrReader {
7	/// The ErrorKind to put into the `std::io::Error`.
8	pub kind: ErrorKind,
9}
10
11impl ErrReader {
12	/// Construct a new ErrReader.
13	pub fn new(kind: ErrorKind) -> Self {
14		Self {
15			kind,
16		}
17	}
18}
19
20impl io::Read for ErrReader {
21	fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
22		Err(io::Error::new(self.kind, ""))
23	}
24}
25
26#[cfg(test)]
27mod test {
28	use super::*;
29	use std::io::Read;
30
31	#[test]
32	fn should_throw_correct_error() {
33		let mut reader = ErrReader::new(ErrorKind::BrokenPipe);
34		let res = reader.read(&mut [0; 3]);
35
36		assert!(res.is_err());
37		if let Err(err) = res {
38			assert_eq!(io::ErrorKind::BrokenPipe, err.kind());
39		}
40	}
41}