teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter ls`, `new`, `attach` and `kill` with `machine:session` (#79), run
//! as the binary from a logged-in "laptop" against a registered, linked
//! machine; and each error message.
// An allow, not an expect: clippy exempts a #[test] function already, so an expect would go
// unfulfilled where only those use these. `allow_attributes` skips inner attributes.
#![allow(
    clippy::expect_used,
    clippy::too_many_lines,
    clippy::unused_result_ok,
    clippy::unwrap_used,
    reason = "a test reports by panicking; its helpers live as long as the test"
)]

use std::path::{Path, PathBuf};
use std::time::Duration;

#[path = "../../test-support/processes.rs"]
mod processes;

use tokio::time::timeout;

const WAIT: Duration = Duration::from_secs(15);

/// The test's folder, removed (and the session processes ended) when it
/// drops.
struct World {
    dir: PathBuf,
}

impl World {
    fn sockets(&self) -> PathBuf {
        self.dir.join("sockets")
    }

    fn laptop(&self) -> PathBuf {
        self.dir.join("laptop")
    }

    async fn teter(&self, device: &Path, args: &[&str]) -> std::process::Output {
        tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
            .args(args)
            .env("XDG_CONFIG_HOME", device)
            .env("XDG_STATE_HOME", device.join("state"))
            .env("TETER_PASSWORD", "correct horse")
            .env_remove("TETER_RELAY")
            .stdin(std::process::Stdio::null())
            .output()
            .await
            .unwrap()
    }

    /// `teter args` on the laptop: its stdout, after asserting it succeeded.
    async fn ok(&self, args: &[&str]) -> String {
        let out = self.teter(&self.laptop(), args).await;
        assert!(out.status.success(), "{args:?}: {out:?}");
        String::from_utf8(out.stdout).unwrap()
    }

    /// `teter args` on the laptop: its stderr, after asserting it failed.
    async fn fails(&self, args: &[&str]) -> String {
        let out = self.teter(&self.laptop(), args).await;
        assert!(!out.status.success(), "{args:?} succeeded: {out:?}");
        String::from_utf8(out.stderr).unwrap()
    }
}

impl Drop for World {
    fn drop(&mut self) {
        processes::kill_naming(&self.sockets().to_string_lossy());
        std::fs::remove_dir_all(&self.dir).ok();
    }
}

#[tokio::test]
async fn ls_new_attach_and_kill_by_machine_session_and_their_errors() {
    let world = World {
        dir: std::env::temp_dir().join(format!("tremote{}", std::process::id())),
    };
    std::fs::create_dir_all(&world.dir).unwrap();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = teter_relay::Server::new(teter_relay::Config {
        store: Some(world.dir.join("store.db")),
        open_signup: true,
        ..teter_relay::Config::new()
    })
    .unwrap();
    tokio::spawn(server.run(listener));
    let relay = format!("ws://{addr}");
    let machine_dir = world.dir.join("machine");

    world.ok(&["signup", &relay, "--name", "ana"]).await;
    let token = world.ok(&["token", "create"]).await.trim().to_owned();
    let out = world
        .teter(
            &machine_dir,
            &["register", "--token", &token, "--name", "jupiter"],
        )
        .await;
    assert!(out.status.success(), "{out:?}");
    let _link = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .args(["link", "--shell", "/bin/sh", "--sockets"])
        .arg(world.sockets())
        .env("XDG_CONFIG_HOME", &machine_dir)
        .env("XDG_STATE_HOME", machine_dir.join("state"))
        .env_remove("TETER_RELAY")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true)
        .spawn()
        .unwrap();

    // ls, once the machine is connected and the relay holds main's record
    // (which comes after the machine connects: until then, ls has no clients
    // to show).
    let listed = timeout(WAIT, async {
        loop {
            let out = world.teter(&world.laptop(), &["ls", "jupiter"]).await;
            let text = String::from_utf8(out.stdout).unwrap();
            if out.status.success() && !text.contains("main\trunning\t-") {
                return text;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    })
    .await
    .expect("teter ls jupiter never worked");
    assert!(listed.contains("main\trunning"), "{listed:?}");
    // With the frontends attached (none) and its size (#135).
    let main = listed
        .lines()
        .find(|line| line.starts_with("main\t"))
        .unwrap();
    let fields: Vec<&str> = main.split('\t').collect();
    assert_eq!(fields.get(2), Some(&"0 clients"), "{main:?}");
    let size = fields.get(3).expect("no size");
    let (columns, rows) = size.split_once('x').expect("not CxR");
    assert!(
        columns.parse::<u16>().is_ok() && rows.parse::<u16>().is_ok(),
        "{main:?}"
    );

    // new, then ls shows it; a name taken.
    let out = world.ok(&["new", "jupiter:build"]).await;
    assert!(out.contains("created jupiter:build"), "{out:?}");
    let listed = world.ok(&["ls", "jupiter"]).await;
    assert!(listed.contains("build\trunning"), "{listed:?}");
    let err = world.fails(&["new", "jupiter:build"]).await;
    assert!(err.contains("already exists"), "{err:?}");

    // attach to an unknown session suggests ls.
    let err = world.fails(&["attach", "jupiter:nope"]).await;
    assert!(
        err.contains("no session named \"nope\"") && err.contains("teter ls jupiter"),
        "{err:?}"
    );

    // kill, then ls no longer shows it; an unknown session suggests ls.
    let out = world.ok(&["kill", "jupiter:build"]).await;
    assert!(out.contains("ended jupiter:build"), "{out:?}");
    let listed = world.ok(&["ls", "jupiter"]).await;
    assert!(!listed.contains("build"), "{listed:?}");
    let err = world.fails(&["kill", "jupiter:nope"]).await;
    assert!(
        err.contains("no session named \"nope\"") && err.contains("teter ls jupiter"),
        "{err:?}"
    );

    // An unknown machine names those the account has; a target with no
    // session part.
    for args in [
        &["ls", "saturn"][..],
        &["new", "saturn:x"][..],
        &["kill", "saturn:x"][..],
        &["attach", "saturn:x"][..],
    ] {
        let err = world.fails(args).await;
        assert!(
            err.contains("no machine named \"saturn\"") && err.contains("jupiter"),
            "{args:?}: {err:?}"
        );
    }
    let err = world.fails(&["new", "jupiter"]).await;
    assert!(err.contains("is not machine:session"), "{err:?}");
}