petitcarnets 0.0.10

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation
//! The libc calls, on bad descriptors and real pipes.

use super::*;

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn a_bad_descriptor_is_not_a_terminal() {
    assert!(!is_tty(-1));
    assert!(get_mode(-1).is_err());
    assert!(window_size(-1).is_err());
}

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn the_opaque_buffer_holds_any_termios() {
    assert!(size_of::<Termios>() >= 72);
    assert_eq!(align_of::<Termios>(), 8);
}

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn a_pipe_carries_bytes_and_wakes_a_wait() {
    let pipe = Pipe::new().unwrap();
    write_all_fd(pipe.write, b"hi").unwrap();
    assert_eq!(wait_readable([pipe.read], None).unwrap(), [true]);
    let mut buf = [0u8; 8];
    assert_eq!(read_fd(pipe.read, &mut buf).unwrap(), 2);
    assert_eq!(&buf[..2], b"hi");
}

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn a_wait_ends_at_its_timeout() {
    let pipe = Pipe::new().unwrap();
    let start = Instant::now();
    let ready = wait_readable([pipe.read], Some(Duration::from_millis(20))).unwrap();
    assert_eq!(ready, [false]);
    assert!(start.elapsed() >= Duration::from_millis(20));
}

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn the_write_end_never_blocks() {
    let pipe = Pipe::new().unwrap();
    let chunk = [0u8; 4096];
    let full = (0..1024).find_map(|_| write_all_fd(pipe.write, &chunk).err());
    let err = full.expect("a pipe fills up long before 4 MiB");
    assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
}

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn a_descriptor_that_cannot_be_watched_is_an_error_not_readable() {
    const F_DUPFD: c_int = 0;
    let pipe = Pipe::new().unwrap();
    // The lowest free descriptor from 500 (below select's 1024), then
    // closed: free now, as nothing else in these tests opens so many.
    // SAFETY: `pipe.read` is open; `F_DUPFD` copies it to a free number.
    let fd = check(unsafe { fcntl(pipe.read, F_DUPFD, 500) }).unwrap();
    let mut closed = fd;
    close_fd(&mut closed);
    let wait = wait_readable([fd], Some(Duration::from_millis(10)));
    assert!(wait.is_err(), "reading it would fail or block: {wait:?}");
}

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn a_pipe_is_not_inherited_by_children() {
    const F_GETFD: c_int = 1;
    let pipe = Pipe::new().unwrap();
    for fd in [pipe.read, pipe.write] {
        // SAFETY: `fd` is open; `F_GETFD` takes no argument.
        let flags = unsafe { fcntl(fd, F_GETFD) };
        assert_eq!(flags & 1, 1, "FD_CLOEXEC on {fd}");
    }
}