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
//! Futures MockStream gives you a MockStream for testing your custom AsyncRead, AsyncWrite and
//! Streams implementations.
//!
//! # Examples
//! ```compile_fail
//!# use futures_mockstream::MockStream;
//!let mut ms = MockStream::from(&b"GET /index HTTP/1.1\r\n");
//!smol::run(async {
//!     while let Some(item) = MyConn::new(&mut ms).next().await {
//!         println!("{}", item);
//!     }
//!})
//! ```
use futures_core::Stream;
use futures_io::{AsyncRead, AsyncWrite};
use futures_task::{Context, Poll};
use std::io::{self, Cursor, Read, Write};
use std::pin::Pin;

/// A Mock Stream with implements AsyncRead, AsyncWrite, and Stream from the futures crate.
///
/// # Examples
/// ```
/// # use futures_mockstream::MockStream;
/// let mock_stream = MockStream::from(&b"mock stream buffer"[..]);
/// ```
#[derive(Default, Debug)]
pub struct MockStream {
    buf: Cursor<Vec<u8>>,
    from_index: usize,
}

impl Unpin for MockStream {}

impl MockStream {
    /// Creates a MockStream from a reference of array.
    ///
    /// # Arguments
    /// A reference of array of u8.
    ///
    /// # Examples
    /// ```
    /// # use futures_mockstream::MockStream;
    /// let mockstream = MockStream::from("hello".as_bytes());
    /// ```
    pub fn from(buf: &[u8]) -> Self {
        Self {
            buf: Cursor::new(Vec::from(buf)),
            from_index: 0,
        }
    }
}

impl AsyncRead for MockStream {
    fn poll_read(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let this: &mut Self = Pin::into_inner(self);
        Poll::Ready(this.buf.read(buf))
    }
}

impl AsyncWrite for MockStream {
    fn poll_write(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this: &mut Self = Pin::into_inner(self);
        Poll::Ready(this.buf.write(buf))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }
}

impl Stream for MockStream {
    type Item = Result<Vec<u8>, io::Error>;
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this: &mut Self = Pin::into_inner(self);
        let mut buf = [0u8; 1024];
        match Pin::new(this).poll_read(cx, &mut buf) {
            Poll::Pending => Poll::Ready(None),
            Poll::Ready(Ok(b)) if b == 0 => Poll::Ready(None),
            Poll::Ready(Ok(b)) => Poll::Ready(Some(Ok(Vec::from(&buf[..b])))),
            Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))),
        }
    }
}

impl AsRef<[u8]> for MockStream {
    fn as_ref(&self) -> &[u8] {
        self.buf.get_ref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures_util::stream::StreamExt;
    use futures_util::{AsyncReadExt, AsyncWriteExt};

    #[test]
    fn async_read() {
        let mut ms = MockStream::default();
        let mut buf = [0u8; 1024];
        smol::run(async {
            let readed = ms.read(&mut buf).await.expect("failed to read");
            assert_eq!(readed, 0);
        })
    }

    #[test]
    fn async_read_sized() {
        let packet = b"ciao mondo";
        let mut ms = MockStream::from(packet);
        smol::run(async {
            let mut buf = [0u8; 1024];
            let readed = ms.read(&mut buf).await.expect("failed to read");
            assert_eq!(readed, 10);
            assert_eq!(&b"ciao mondo"[..], &buf[..readed]);
            dbg!(ms);
        })
    }

    #[test]
    fn async_write() {
        let buf = &[];
        let mut ms = MockStream::default();
        smol::run(async {
            let written = ms.write(buf).await.expect("failed to write");
            assert_eq!(written, 0);
        })
    }

    #[test]
    fn async_write_sized() {
        let buf = b"this is the packet";
        let mut ms = MockStream::default();
        smol::run(async {
            let written = ms.write(buf).await.expect("failed to write");
            assert_ne!(written, 0);
            assert_eq!(&buf[..], ms.as_ref());
        })
    }

    #[test]
    fn async_stream_none() {
        let buf: &[u8] = &[];
        let mut ms = MockStream::from(&buf);
        smol::run(async {
            while let Some(v) = ms.next().await {
                match v {
                    Ok(b) => assert_eq!(b.len(), 0),
                    Err(e) => panic!("{}", e),
                }
            }
        })
    }

    #[test]
    fn async_stream_sized() {
        let buf = b"this is my packet";
        let mut ms = MockStream::from(buf);
        smol::run(async {
            while let Some(v) = ms.next().await {
                match v {
                    Ok(b) => {
                        assert_eq!(b.len(), buf.len());
                        assert_eq!(&buf[..], buf.as_ref());
                    }
                    Err(e) => panic!("{}", e),
                }
            }
        })
    }
}