blob: f164abaf1bad08bbe12bb1a0e8ce86489377d1fe [file] [log] [blame]
Jeff Vander Stoepbf372732021-02-18 09:39:46 +01001#![warn(rust_2018_idioms)]
2
3use std::io;
4use tokio::io::{AsyncReadExt, AsyncWriteExt};
5use tokio_test::io::Builder;
6
7#[tokio::test]
8async fn read() {
9 let mut mock = Builder::new().read(b"hello ").read(b"world!").build();
10
11 let mut buf = [0; 256];
12
13 let n = mock.read(&mut buf).await.expect("read 1");
14 assert_eq!(&buf[..n], b"hello ");
15
16 let n = mock.read(&mut buf).await.expect("read 2");
17 assert_eq!(&buf[..n], b"world!");
18}
19
20#[tokio::test]
21async fn read_error() {
22 let error = io::Error::new(io::ErrorKind::Other, "cruel");
23 let mut mock = Builder::new()
24 .read(b"hello ")
25 .read_error(error)
26 .read(b"world!")
27 .build();
28 let mut buf = [0; 256];
29
30 let n = mock.read(&mut buf).await.expect("read 1");
31 assert_eq!(&buf[..n], b"hello ");
32
33 match mock.read(&mut buf).await {
34 Err(error) => {
35 assert_eq!(error.kind(), io::ErrorKind::Other);
36 assert_eq!("cruel", format!("{}", error));
37 }
38 Ok(_) => panic!("error not received"),
39 }
40
41 let n = mock.read(&mut buf).await.expect("read 1");
42 assert_eq!(&buf[..n], b"world!");
43}
44
45#[tokio::test]
46async fn write() {
47 let mut mock = Builder::new().write(b"hello ").write(b"world!").build();
48
49 mock.write_all(b"hello ").await.expect("write 1");
50 mock.write_all(b"world!").await.expect("write 2");
51}
52
53#[tokio::test]
54async fn write_error() {
55 let error = io::Error::new(io::ErrorKind::Other, "cruel");
56 let mut mock = Builder::new()
57 .write(b"hello ")
58 .write_error(error)
59 .write(b"world!")
60 .build();
61 mock.write_all(b"hello ").await.expect("write 1");
62
63 match mock.write_all(b"whoa").await {
64 Err(error) => {
65 assert_eq!(error.kind(), io::ErrorKind::Other);
66 assert_eq!("cruel", format!("{}", error));
67 }
68 Ok(_) => panic!("error not received"),
69 }
70
71 mock.write_all(b"world!").await.expect("write 2");
72}
73
74#[tokio::test]
75#[should_panic]
76async fn mock_panics_read_data_left() {
77 use tokio_test::io::Builder;
78 Builder::new().read(b"read").build();
79}
80
81#[tokio::test]
82#[should_panic]
83async fn mock_panics_write_data_left() {
84 use tokio_test::io::Builder;
85 Builder::new().write(b"write").build();
86}