mockstream-0.0.3/.gitignore00006440000000000000000000000232132000136560014026 0ustar0000000000000000# Compiled files *.o *.so *.rlib *.dll # Executables *.exe # Generated by Cargo /target/ # Libraries should ignore Cargo.lock Cargo.lock mockstream-0.0.3/Cargo.toml.orig00006440000000000000000000000646132000136140014730 0ustar0000000000000000[package] name = "mockstream" version = "0.0.3" authors = ["Alex Bogma "] license = "MIT" description = "Stream (Read+Write traits) implementations to be used to mock real streams in tests." repository = "https://github.com/lazy-bitfield/rust-mockstream" readme = "README.md" keywords = ["test", "stream", "io", "mock"] [lib] name = "mockstream" path = "src/lib.rs" test = true mockstream-0.0.3/Cargo.toml0000644000000016400010217 0ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "mockstream" version = "0.0.3" authors = ["Alex Bogma "] description = "Stream (Read+Write traits) implementations to be used to mock real streams in tests." readme = "README.md" keywords = ["test", "stream", "io", "mock"] license = "MIT" repository = "https://github.com/lazy-bitfield/rust-mockstream" [lib] name = "mockstream" path = "src/lib.rs" test = true mockstream-0.0.3/LICENSE00006440000000000000000000002120132000072770013043 0ustar0000000000000000The MIT License (MIT) Copyright (c) 2015 Alexandr Bogma Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mockstream-0.0.3/README.md00006440000000000000000000005154132000072770013327 0ustar0000000000000000# rust-mockstream Stream (Read+Write traits) implementations to be used to mock real streams in tests. ## Install Just use Cargo. ## Usage scenario Wrap the stream you use into ADT and provide Read and Write traits implementation. ``` enum NetStream { Mocked(SharedMockStream), Tcp(TcpStream) } impl io::Read for NetStream { fn read(&mut self, buf: &mut [u8]) -> io::Result { match *self { NetStream::Mocked(ref mut s) => s.read(buf), NetStream::Tcp(ref mut s) => s.read(buf), } } } impl io::Write for NetStream { fn write(&mut self, buf: &[u8]) -> io::Result { match *self { NetStream::Mocked(ref mut s) => s.write(buf), NetStream::Tcp(ref mut s) => s.write(buf), } } fn flush(&mut self) -> io::Result<()> { match *self { NetStream::Mocked(ref mut s) => s.flush(), NetStream::Tcp(ref mut s) => s.flush(), } } } ``` Then use this ADT instead of stream everywhere. ``` fn reverse4(s: &mut NetStream) -> io::Result { use std::io::{Read, Write}; // read 4 bytes into v let mut v = [0; 4]; let count = try![s.read(v.as_mut_slice())]; assert_eq!(count, 4); // reverse them v.reverse(); // write them back to network s.write(v.as_slice()) } ``` In tests, provide data to mock and verify the results after performing operations. ``` let mut s = SharedMockStream::new(); let mut e = NetStream::Mocked(s.clone()); // provide data to mock s.push_bytes_to_read([1, 2, 3, 4].as_slice()); // check if io succeeded assert_eq!(reverse4(&mut e), Ok(4)); // verify the data returned assert_eq!(s.pop_bytes_written().as_slice(), [4, 3, 2, 1]); ``` ## I/O failures A mock simulating I/O errors is provided too. Combined with a Chain, this allows to simulate errors between reading data. See the following example where read_data performs 3 retries on I/O errors. This is verified in the test function below. ``` struct CountIo {} impl CountIo { fn read_data(&self, r: &mut Read) -> usize { let mut count: usize = 0; let mut retries = 3; loop { let mut buffer = [0; 5]; match r.read(&mut buffer) { Err(_) => { if retries == 0 { break; } retries -= 1; }, Ok(0) => break, Ok(n) => count += n, } } count } } #[test] fn test_io_retries() { let mut c = Cursor::new(&b"1234"[..]) .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3)) .chain(Cursor::new(&b"5678"[..])); let sut = CountIo {}; // this will fail unless read_data performs at least 3 retries on I/O errors assert_eq!(8, sut.read_data(&mut c)); } ``` mockstream-0.0.3/src/lib.rs00006440000000000000000000012644132000072770013755 0ustar0000000000000000#![crate_name="mockstream"] #![crate_type="lib"] //! A reader/writer streams to mock real streams in tests. use std::rc::{Rc}; use std::cell::{RefCell}; use std::io::{Cursor, Read, Write, Result, Error, ErrorKind}; use std::mem::swap; use std::sync::{Arc, Mutex}; #[cfg(test)] mod tests; /// MockStream is Read+Write stream that stores the data written and provides the data to be read. #[derive(Clone)] pub struct MockStream { reader: Cursor>, writer: Cursor>, } impl Default for MockStream { fn default() -> Self { MockStream::new() } } fn new_cursor() -> Cursor> { Cursor::new(Vec::new()) } impl MockStream { /// Create new empty stream pub fn new() -> MockStream { MockStream { reader: new_cursor(), writer: new_cursor(), } } /// Extract all bytes written by Write trait calls. pub fn pop_bytes_written(&mut self) -> Vec { let mut result = Vec::new(); swap(&mut result, self.writer.get_mut()); self.writer.set_position(0); result } /// Provide data to be read by Read trait calls. pub fn push_bytes_to_read(&mut self, bytes: &[u8]) { let avail = self.reader.get_ref().len(); if self.reader.position() == avail as u64 { self.reader = new_cursor(); } self.reader.get_mut().extend(bytes.iter().map(|c| *c)); } } impl Read for MockStream { fn read(&mut self, buf: &mut [u8]) -> Result { self.reader.read(buf) } } impl Write for MockStream { fn write<'a>(&mut self, buf: &'a [u8]) -> Result { self.writer.write(buf) } fn flush(&mut self) -> Result<()> { self.writer.flush() } } /// Reference-counted stream. #[derive(Clone, Default)] pub struct SharedMockStream { pimpl: Rc> } impl SharedMockStream { /// Create empty stream pub fn new() -> SharedMockStream { SharedMockStream::default() } /// Extract all bytes written by Write trait calls. pub fn push_bytes_to_read(&mut self, bytes: &[u8]) { self.pimpl.borrow_mut().push_bytes_to_read(bytes) } /// Provide data to be read by Read trait calls. pub fn pop_bytes_written(&mut self) -> Vec { self.pimpl.borrow_mut().pop_bytes_written() } } impl Read for SharedMockStream { fn read(&mut self, buf: &mut [u8]) -> Result { self.pimpl.borrow_mut().read(buf) } } impl Write for SharedMockStream { fn write(&mut self, buf: &[u8]) -> Result { self.pimpl.borrow_mut().write(buf) } fn flush(&mut self) -> Result<()> { self.pimpl.borrow_mut().flush() } } /// Thread-safe stream. #[derive(Clone, Default)] pub struct SyncMockStream { pimpl: Arc> } impl SyncMockStream { /// Create empty stream pub fn new() -> SyncMockStream { SyncMockStream::default() } /// Extract all bytes written by Write trait calls. pub fn push_bytes_to_read(&mut self, bytes: &[u8]) { self.pimpl.lock().unwrap().push_bytes_to_read(bytes) } /// Provide data to be read by Read trait calls. pub fn pop_bytes_written(&mut self) -> Vec { self.pimpl.lock().unwrap().pop_bytes_written() } } impl Read for SyncMockStream { fn read(&mut self, buf: &mut [u8]) -> Result { self.pimpl.lock().unwrap().read(buf) } } impl Write for SyncMockStream { fn write(&mut self, buf: &[u8]) -> Result { self.pimpl.lock().unwrap().write(buf) } fn flush(&mut self) -> Result<()> { self.pimpl.lock().unwrap().flush() } } /// `FailingMockStream` mocks a stream which will fail upon read or write /// /// # Examples /// /// ``` /// use std::io::{Cursor, Read}; /// /// struct CountIo {} /// /// impl CountIo { /// fn read_data(&self, r: &mut Read) -> usize { /// let mut count: usize = 0; /// let mut retries = 3; /// /// loop { /// let mut buffer = [0; 5]; /// match r.read(&mut buffer) { /// Err(_) => { /// if retries == 0 { break; } /// retries -= 1; /// }, /// Ok(0) => break, /// Ok(n) => count += n, /// } /// } /// count /// } /// } /// /// #[test] /// fn test_io_retries() { /// let mut c = Cursor::new(&b"1234"[..]) /// .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3)) /// .chain(Cursor::new(&b"5678"[..])); /// /// let sut = CountIo {}; /// // this will fail unless read_data performs at least 3 retries on I/O errors /// assert_eq!(8, sut.read_data(&mut c)); /// } /// ``` #[derive(Clone)] pub struct FailingMockStream { kind: ErrorKind, message: &'static str, repeat_count: i32, } impl FailingMockStream { /// Creates a FailingMockStream /// /// When `read` or `write` is called, it will return an error `repeat_count` times. /// `kind` and `message` can be specified to define the exact error. pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream { FailingMockStream { kind: kind, message: message, repeat_count: repeat_count, } } fn error(&mut self) -> Result { if self.repeat_count == 0 { return Ok(0) } else { if self.repeat_count > 0 { self.repeat_count -= 1; } Err(Error::new(self.kind, self.message)) } } } impl Read for FailingMockStream { fn read(&mut self, _: &mut [u8]) -> Result { self.error() } } impl Write for FailingMockStream { fn write(&mut self, _: &[u8]) -> Result { self.error() } fn flush(&mut self) -> Result<()> { Ok(()) } } mockstream-0.0.3/src/tests.rs00006440000000000000000000011705132000072770014346 0ustar0000000000000000use super::{MockStream, SharedMockStream, SyncMockStream, FailingMockStream}; use std::io::{Cursor, Read, Write, Result, ErrorKind}; use std::error::Error; #[test] fn test_mock_stream_read() { let mut s = MockStream::new(); s.push_bytes_to_read("abcd".as_bytes()); let mut v = [11; 6]; assert_eq!(s.read(v.as_mut()).unwrap(), 4); assert_eq!(v, [97, 98, 99, 100, 11, 11]); } #[test] fn test_mock_stream_pop_again() { let mut s = MockStream::new(); s.write_all(b"abcd").unwrap(); assert_eq!(s.pop_bytes_written(), b"abcd"); s.write_all(b"efgh").unwrap(); assert_eq!(s.pop_bytes_written(), b"efgh"); } #[test] fn test_mock_stream_empty_and_fill() { let mut s = MockStream::new(); let mut v = [11; 6]; assert_eq!(s.read(v.as_mut()).unwrap(), 0); s.push_bytes_to_read("abcd".as_bytes()); assert_eq!(s.read(v.as_mut()).unwrap(), 4); assert_eq!(s.read(v.as_mut()).unwrap(), 0); } #[test] fn test_mock_stream_read_lines() { let mut s = MockStream::new(); s.push_bytes_to_read("abcd\r\ndcba\r\n".as_bytes()); let first_line = s.bytes().map(|c| c.unwrap()).take_while(|&c| c != b'\n').collect::>(); assert_eq!(first_line, (vec![97, 98, 99, 100, 13])); } #[test] fn test_failing_mock_stream_read() { let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the ethernet cable", 1); let mut v = [0; 4]; let error = s.read(v.as_mut()).unwrap_err(); assert_eq!(error.kind(), ErrorKind::BrokenPipe); assert_eq!(error.description(), "The dog ate the ethernet cable"); // after a single error, it will return Ok(0) assert_eq!(s.read(v.as_mut()).unwrap(), 0); } #[test] fn test_failing_mock_stream_chain() { let mut s1 = MockStream::new(); s1.push_bytes_to_read("abcd".as_bytes()); let s2 = FailingMockStream::new(ErrorKind::Other, "Failing", -1); let mut c = s1.chain(s2); let mut v = [0; 8]; assert_eq!(c.read(v.as_mut()).unwrap(), 4); assert_eq!(c.read(v.as_mut()).unwrap_err().kind(), ErrorKind::Other); assert_eq!(c.read(v.as_mut()).unwrap_err().kind(), ErrorKind::Other); } #[test] fn test_failing_mock_stream_chain_interrupted() { let mut c = Cursor::new(&b"abcd"[..]) .chain(FailingMockStream::new(ErrorKind::Interrupted, "Interrupted", 5)) .chain(Cursor::new(&b"ABCD"[..])); let mut v = [0; 8]; c.read_exact(v.as_mut()).unwrap(); assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41, 0x42, 0x43, 0x44]); assert_eq!(c.read(v.as_mut()).unwrap(), 0); } #[test] fn test_mock_stream_write() { let mut s = MockStream::new(); assert_eq!(s.write("abcd".as_bytes()).unwrap(), 4); assert_eq!(s.pop_bytes_written().as_ref(), [97, 98, 99, 100]); assert!(s.pop_bytes_written().is_empty()); } #[test] fn test_failing_mock_stream_write() { let mut s = FailingMockStream::new(ErrorKind::PermissionDenied, "Access denied", -1); let error = s.write("abcd".as_bytes()).unwrap_err(); assert_eq!(error.kind(), ErrorKind::PermissionDenied); assert_eq!(error.description(), "Access denied"); // it will keep failing s.write("abcd".as_bytes()).unwrap_err(); } // *** Real-world example *** /// ADT that represents some network stream enum NetStream { Mocked(SharedMockStream), //Tcp(TcpStream) } impl Read for NetStream { fn read(&mut self, buf: &mut [u8]) -> Result { match *self { NetStream::Mocked(ref mut s) => s.read(buf), //NetStream::Tcp(ref mut s) => s.read(buf), } } } impl Write for NetStream { fn write(&mut self, buf: &[u8]) -> Result { match *self { NetStream::Mocked(ref mut s) => s.write(buf), //NetStream::Tcp(ref mut s) => s.write(buf), } } fn flush(&mut self) -> Result<()> { match *self { NetStream::Mocked(ref mut s) => s.flush(), //NetStream::Tcp(ref mut s) => s.flush(), } } } /// read 4 bytes from network, reverse them and write back fn reverse4(s: &mut NetStream) -> Result { let mut v = [0; 4]; let count = try![s.read(v.as_mut())]; assert_eq!(count, 4); v.reverse(); s.write(v.as_ref()) } #[test] fn test_shared_mock_stream() { let mut s = SharedMockStream::new(); let mut e = NetStream::Mocked(s.clone()); // provide data to mock s.push_bytes_to_read([1, 2, 3, 4].as_ref()); // check if io succeeded assert_eq!(reverse4(&mut e).unwrap(), 4); // verify the data returned assert_eq!(s.pop_bytes_written().as_ref(), [4, 3, 2, 1]); // ensure no more bytes in stream assert_eq!(e.read(&mut [0; 4]).unwrap(), 0); } #[test] fn test_sync_mock_stream() { use std::thread; let mut s = SyncMockStream::new(); let mut s2 = s.clone(); // thread will write some bytes, and then read some bytes s.push_bytes_to_read(&[5, 6, 7, 8]); let read = thread::spawn(move || { s2.write_all(&[1, 2, 3, 4]).unwrap(); let mut buf = Vec::new(); s2.read_to_end(&mut buf).unwrap(); buf }).join().unwrap(); assert_eq!(s.pop_bytes_written(), &[1, 2, 3, 4]); assert_eq!(read, &[5, 6, 7, 8]); }