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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*!
Programmatically test TCP programs using real TCP streams.

# Example

Everything can be done using the [`channel()`] function:

```
use tcp_test::{channel, read_assert};
use std::io::{Read, Write};

#[test]
fn first_test() {
    let sent = b"Hello, reader";

    let (mut reader, mut writer) = channel();

    writer.write_all(sent).unwrap();

    let mut read = Vec::new();
    reader.read_to_end(&mut read).unwrap();

    assert_eq!(read, sent);
}

#[test]
fn second_test() {
    let sent = b"Interesting story";

    let (mut reader, mut writer) = channel();

    writer.write_all(sent).unwrap();

    read_assert!(reader, sent.len(), sent);
}

#[test]
fn third_test() {
    let sent = b"...";

    let (mut reader, mut writer) = channel();

    writer.write_all(sent).unwrap();

    read_assert!(reader, sent.len(), sent);
}
```

# Features

By default, a panic in one of the internal threads causes all tests to exit,
because in most cases the tests will just block indefinitely.
The `only_panic` feature prevents this behaviour if enabled.

[`channel()`]: fn.channel.html
*/

#![deny(unsafe_code)]

extern crate lazy_static;

use lazy_static::lazy_static;

use std::io::{self, Error, ErrorKind};
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener, TcpStream, ToSocketAddrs};
use std::process;
use std::sync::{Arc, Condvar, Mutex, Once};
use std::thread::Builder;

static SPAWN_SERVER: Once = Once::new();

lazy_static! {
    static ref STREAM: Arc<(Mutex<Option<(TcpStream, TcpStream)>>, Condvar)> =
        Arc::new((Mutex::new(None), Condvar::new()));

    /// `127.0.0.1:31398`
    static ref DEFAULT_ADDRESS: SocketAddr =
        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 31398));
}

/// Listen to traffic on a specific address.
///
/// The parsed input address is returned for simplicity reasons.
///
/// # Important:
///
/// The address must be equal in all calls to this function,
/// otherwise only one of the addresses is used!
///
/// If there already is a server listening on *any* address,
/// only the address is returned even though it might not be the address of the listening server.
/// The same holds for `listen()`.
fn listen_on(address: impl ToSocketAddrs) {
    SPAWN_SERVER.call_once(move || {
        let address = address
            .to_socket_addrs()
            .expect("<impl ToSocketAddrs>::to_socket_addrs() at listen_on()")
            .next()
            .expect("ToSocketAddrs::Iter::next() at listen_on()");

        let listener = TcpListener::bind(address).expect("TcpListener::bind() at listen_on()");
        let buf = Arc::new((Mutex::new(None), Condvar::new()));
        let buf2 = buf.clone();

        Builder::new()
            .name(String::from("tcp-test listener thread"))
            .spawn(move || {
                let (ref lock, ref cvar) = &*buf2;

                listener_thread(listener, lock, cvar).map_err(|e| {
                    if cfg!(feature = "only_panic") {
                        panic!("tcp-test internal error: {}", e);
                    } else if cfg!(not(feature = "only_panic")) {
                        eprintln!(
                            "tcp-test internal error: {error}, {file}:{line}:{column}",
                            error = e,
                            file = file!(),
                            line = line!(),
                            column = column!()
                        );
                        process::exit(1);
                    };
                })
            })
            .expect("Builder::spawn() at listen_on()");

        Builder::new()
            .name(String::from("tcp-test channel thread"))
            .spawn(move || {
                let &(ref lock, ref cvar) = &*buf;

                channel_thread(address, lock, cvar).map_err(|e| {
                    if cfg!(feature = "only_panic") {
                        panic!("tcp-test internal error: {}", e);
                    } else if cfg!(not(feature = "only_panic")) {
                        eprintln!(
                            "tcp-test internal error: {error}, {file}:{line}:{column}",
                            error = e,
                            file = file!(),
                            line = line!(),
                            column = column!()
                        );
                        process::exit(1);
                    };
                })
            })
            .expect("Builder::spawn() at listen_on()");
    });
}

fn listener_thread(
    listener: TcpListener,
    lock: &Mutex<Option<TcpStream>>,
    cvar: &Condvar,
) -> io::Result<()> {
    let error = |message| Error::new(ErrorKind::Other, message);

    for i in listener.incoming() {
        let i = i?;

        let mut buf = lock
            .lock()
            .map_err(|_| error(concat!("failed to lock Mutex, ", line!())))?;

        while buf.is_some() {
            buf = cvar
                .wait(buf)
                .map_err(|_| error(concat!("failed to wait for Condvar, ", line!())))?;
        }

        *buf = Some(i);
        cvar.notify_one();
    }

    Ok(())
}

fn channel_thread(
    address: SocketAddr,
    lock: &Mutex<Option<TcpStream>>,
    cvar: &Condvar,
) -> Result<(), Error> {
    let error = |message| Error::new(ErrorKind::Other, message);

    loop {
        let local = TcpStream::connect(address)?;

        let remote = {
            // get the stream from the listener thread
            let mut remote = lock
                .lock()
                .map_err(|_| error(concat!("failed to lock Mutex, ", line!())))?;
            while remote.is_none() {
                remote = cvar
                    .wait(remote)
                    .map_err(|_| error(concat!("failed to wait for Condvar, ", line!())))?;
            }

            mem::replace(&mut *remote, None).unwrap()
        };

        // change the global variable
        let &(ref lock, ref cvar) = &*STREAM.clone();
        let mut stream = lock
            .lock()
            .map_err(|_| error(concat!("failed to lock Mutex, ", line!())))?;
        while stream.is_some() {
            stream = cvar
                .wait(stream)
                .map_err(|_| error(concat!("failed to wait for Condvar, ", line!())))?;
        }

        *stream = Some((local, remote));

        cvar.notify_one();
    }
}

/// Returns two TCP streams pointing at each other.
///
/// The internal TCP listener is bound to `127.0.0.1:31398`.
///
/// # Example
///
/// ```
/// # use tcp_test::channel;
/// use std::io::{Read, Write};
///
/// let data = b"Hello world!";
/// let (mut local, mut remote) = channel();
///
/// let local_addr = local.local_addr().unwrap();
/// let peer_addr = remote.peer_addr().unwrap();
///
/// assert_eq!(local_addr, peer_addr);
///
/// local.write_all(data).unwrap();
///
/// let mut buf = [0; 12];
/// remote.read_exact(&mut buf).unwrap();
///
/// assert_eq!(&buf, data);
/// ```
///
/// Also see the [module level example](index.html#example).
///
/// [`listen()`]: fn.listen.html
#[inline]
pub fn channel() -> (TcpStream, TcpStream) {
    channel_on(*DEFAULT_ADDRESS)
}

/// Returns two TCP streams pointing at each other.
///
/// The internal TCP listener is bound to `address`.
/// Only one listener is used throughout the entire program,
/// so the address should match in all calls to this function,
/// otherwise it is not specified which address is finally used.
///
/// # Example
///
/// ```
/// # use tcp_test::channel_on;
/// use std::io::{Read, Write};
///
/// let data = b"Hello world!";
/// let (mut local, mut remote) = channel_on("127.0.0.1:31398");
///
/// let local_addr = remote.local_addr().unwrap();
/// let peer_addr = local.peer_addr().unwrap();
///
/// assert_eq!(local_addr, peer_addr);
///
/// local.write_all(data).unwrap();
///
/// let mut buf = [0; 12];
/// remote.read_exact(&mut buf).unwrap();
///
/// assert_eq!(&buf, data);
/// ```
///
/// [`listen_on()`]: fn.listen_on.html
pub fn channel_on(address: impl ToSocketAddrs) -> (TcpStream, TcpStream) {
    listen_on(address);

    let &(ref lock, ref cvar) = &*STREAM.clone();
    let mut buf = lock.lock().unwrap();
    while buf.is_none() {
        buf = cvar.wait(buf).unwrap();
    }

    let channel = mem::replace(&mut *buf, None);

    cvar.notify_all();

    channel.unwrap()
}

/// Convenience macro for reading and comparing a specific amount of bytes.
///
/// Reads a `$n` number of bytes from `$resource` and then compares that buffer with `$expected`.
/// Panics if the buffers are not equal.
#[macro_export]
macro_rules! read_assert {
    ($resource:expr, $n:expr, $expected:expr) => {{
        match &$expected {
            expected => {
                use std::io::Read;

                let mut buf = [0; $n];
                $resource
                    .read_exact(&mut buf)
                    .expect("failed to read in read_assert!");

                assert_eq!(
                    &buf[..],
                    &expected[..],
                    "read_assert! buffers are not equal"
                );
            }
        }
    }};
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{self, Read};

    struct Placeholder;

    impl Read for Placeholder {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            Ok(buf.len())
        }
    }

    #[test]
    fn read_assert_ok() {
        read_assert!(Placeholder {}, 9, [0; 9]);
    }

    #[test]
    #[should_panic]
    fn read_assert_panic() {
        read_assert!(Placeholder {}, 1, [0xff]);
    }
}