I'm trying to figure out how to unit test my Stream's fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {todo!()}
It takes a Context cx which is passed to nested stream. My tested and testing code can do without but I have to provide some to be able to test.
use futures::ready;
use futures::stream::Stream;
use pin_project::pin_project;
use std::collections::VecDeque;
use std::pin::Pin;
use std::task::{Context, Poll}; // 0.4.22
#[pin_project]
pub struct MyStream<T>(#[pin] T);
impl<T: Stream> Stream for MyStream<T> {
type Item = ();
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let _ignored = ready!(self.project().0.poll_next(cx));
Poll::Ready(Some(()))
}
}
#[test]
fn test1() {
let setup = TestStream::from(vec![Poll::Ready(Some(true))]);
let sut = MyStream(setup);
// where do I get a fake Context<>?
assert_eq!(Pin::new(&mut sut).poll_next(cx), Poll::Ready(Some(())))
}
#[pin_project]
struct TestStream<I> {
items: VecDeque<Poll<Option<I>>>,
}
impl<T: IntoIterator<Item = Poll<Option<I>>>, I> From<T> for TestStream<I> {
fn from(from: T) -> Self {
TestStream {
items: from.into_iter().collect(),
}
}
}
impl<I> Stream for TestStream<I> {
type Item = I;
fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Some(item) = self.project().items.pop_front() {
item
} else {
Poll::Ready(None)
}
}
}