Cotton code
222 lines · 7.9 KB · RustRaw
//! The capture, and every decision in it.//!//! The shell is `/bin/sh` and the agent is a two-line script this test writes://! no login file on the machine running this is read, and no real agent is//! ever run.use super::*;use std::os::unix::fs::PermissionsExt as _;/// A directory holding an executable script called `name`.fn fake_program(dir: &Path, name: &str, prints: &str) {    let path = dir.join(name);    std::fs::write(&path, format!("#!/bin/sh\n{prints}\n")).expect("the script is written");    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))        .expect("the script is executable");}#[test]fn env_0_is_parsed_nul_by_nul_so_a_value_with_a_newline_survives() {    let printed = b"PATH=/usr/bin:/bin\0HOME=/Users/me\0GREETING=one\ntwo\0";    let vars = parse_env0(printed);    assert_eq!(vars.get("PATH").map(String::as_str), Some("/usr/bin:/bin"));    assert_eq!(vars.get("HOME").map(String::as_str), Some("/Users/me"));    assert_eq!(        vars.get("GREETING").map(String::as_str),        Some("one\ntwo"),        "a line-based read would have made two half-variables out of this"    );}#[test]fn an_entry_that_is_not_a_variable_is_skipped_never_half_parsed() {    let vars = parse_env0(b"PATH=/bin\0nonsense\0=novalue\0\0EMPTY=\0");    assert_eq!(vars.len(), 2, "got {vars:?}");    assert_eq!(vars.get("PATH").map(String::as_str), Some("/bin"));    assert_eq!(        vars.get("EMPTY").map(String::as_str),        Some(""),        "a variable set to nothing IS set — that is not the same as unset"    );}#[test]fn a_value_that_is_not_utf8_is_skipped_rather_than_mangled() {    let mut printed = b"PATH=/bin\0BROKEN=".to_vec();    printed.extend_from_slice(&[0xff, 0xfe]);    printed.push(0);    let vars = parse_env0(&printed);    assert_eq!(vars.keys().collect::<Vec<_>>(), vec!["PATH"]);}#[test]fn a_hosted_terminal_always_has_a_term_and_the_person_s_own_wins() {    let none = build(BTreeMap::new(), "/Users/me");    assert_eq!(none.get("TERM"), Some(FALLBACK_TERM));    let theirs = build(        BTreeMap::from([("TERM".to_string(), "screen-256color".to_string())]),        "/Users/me",    );    assert_eq!(theirs.get("TERM"), Some("screen-256color"));}#[test]fn the_shell_var_is_asked_first_then_the_login_record_then_zsh() {    assert_eq!(choose_shell(Some("/bin/bash"), Some("/bin/zsh")), "/bin/bash");    assert_eq!(        choose_shell(None, Some("/opt/homebrew/bin/fish")),        "/opt/homebrew/bin/fish",        "under launchd SHELL is not set at all — the login record is what answers"    );    assert_eq!(choose_shell(None, None), FALLBACK_SHELL);    assert_eq!(        choose_shell(Some("zsh"), None),        FALLBACK_SHELL,        "a shell that is not an absolute path is not one this host will exec"    );}#[test]fn an_agent_is_found_on_the_captured_path_and_the_answer_names_where() {    let dir = tempfile::tempdir().expect("a scratch directory");    let bin = dir.path().join("bin");    std::fs::create_dir_all(&bin).expect("the directory is made");    fake_program(&bin, "claude", "echo '9.9.9 (Claude Code)'");    std::fs::create_dir_all(bin.join("codex")).expect("a directory that shares the name");    let env = LoginEnv::from_vars(BTreeMap::from([(        "PATH".to_string(),        format!("/usr/bin:{}", bin.display()),    )]));    assert_eq!(        env.program_path("claude"),        bin.join("claude").display().to_string(),        "the answer is the path it found, not the bare name"    );    assert_eq!(        env.program_path("codex"),        "codex",        "a directory called `codex` is not a program — the bare name is left for the caller's own PATH to refuse"    );}#[test]fn nothing_captured_resolves_by_bare_name_and_adds_nothing() {    let env = LoginEnv::default();    assert!(env.is_empty());    assert_eq!(env.path(), "");    assert_eq!(env.program_path("claude"), "claude");    assert_eq!(        env.merged(BTreeMap::from([("A".to_string(), "1".to_string())])),        BTreeMap::from([("A".to_string(), "1".to_string())]),        "an empty capture adds nothing to a child"    );}#[test]fn what_the_caller_asked_for_wins_over_what_the_login_shell_said() {    let env = LoginEnv::from_vars(BTreeMap::from([        ("PATH".to_string(), "/usr/bin".to_string()),        ("LANG".to_string(), "en_GB.UTF-8".to_string()),    ]));    let merged = env.merged(BTreeMap::from([("PATH".to_string(), "/opt/test".to_string())]));    assert_eq!(merged.get("PATH").map(String::as_str), Some("/opt/test"));    assert_eq!(merged.get("LANG").map(String::as_str), Some("en_GB.UTF-8"));}#[test]fn a_real_login_shell_is_captured_and_the_answer_is_what_it_exported() {    let dir = tempfile::tempdir().expect("a scratch directory");    fake_program(dir.path(), "shell", "env -0");    let env = capture(        &dir.path().join("shell").display().to_string(),        "/Users/me",        BTreeMap::from([("MARK".to_string(), "fallback".to_string())]),        CAPTURE_TIMEOUT,    );    // The script is `#!/bin/sh env -0`, so what comes back is THIS process's    // environment — which is not the fallback map, and holds a PATH.    assert!(!env.path().is_empty());    assert_eq!(        env.get("MARK"),        None,        "the shell answered, so the fallback was not used"    );}#[test]fn a_shell_that_will_not_run_leaves_the_host_with_the_process_environment() {    let env = capture(        "/nowhere/no-such-shell",        "/Users/me",        BTreeMap::from([            ("PATH".to_string(), "/usr/bin:/bin".to_string()),            ("LANG".to_string(), "en_IN.UTF-8".to_string()),        ]),        CAPTURE_TIMEOUT,    );    assert_eq!(env.get("LANG"), Some("en_IN.UTF-8"));    assert!(        env.path().contains("/opt/homebrew/bin"),        "even the fallback gains the well-known agent directories — got {}",        env.path()    );}#[test]fn a_shell_that_prints_nothing_is_the_same_as_one_that_would_not_run() {    let dir = tempfile::tempdir().expect("a scratch directory");    fake_program(dir.path(), "silent", "exit 1");    let env = capture(        &dir.path().join("silent").display().to_string(),        "",        BTreeMap::from([("MARK".to_string(), "fallback".to_string())]),        CAPTURE_TIMEOUT,    );    assert_eq!(env.get("MARK"), Some("fallback"));}#[test]fn the_log_line_names_the_shell_and_the_path_and_nothing_else() {    let env = LoginEnv::from_vars(BTreeMap::from([        ("SHELL".to_string(), "/bin/zsh".to_string()),        ("PATH".to_string(), "/Users/me/.local/bin:/usr/bin".to_string()),        ("ANTHROPIC_API_KEY".to_string(), "sk-secret".to_string()),        ("AWS_SECRET_ACCESS_KEY".to_string(), "hunter2".to_string()),    ]));    let said = env.summary();    assert!(said.contains("SHELL=/bin/zsh"), "{said}");    assert!(said.contains("PATH=/Users/me/.local/bin:/usr/bin"), "{said}");    for secret in ["sk-secret", "hunter2", "ANTHROPIC_API_KEY", "AWS_SECRET_ACCESS_KEY"] {        assert!(            !said.contains(secret),            "a variable that is not on LOGGABLE reached the log — {said}"        );    }    assert!(LoginEnv::default().summary().contains("no login environment"));}#[test]fn the_capturing_shell_s_own_bookkeeping_does_not_follow_a_session_into_a_repository() {    let env = build(        BTreeMap::from([            ("PATH".to_string(), "/usr/bin".to_string()),            ("PWD".to_string(), "/Users/me".to_string()),            ("OLDPWD".to_string(), "/".to_string()),            ("SHLVL".to_string(), "1".to_string()),            ("_".to_string(), "/usr/bin/env".to_string()),            ("LANG".to_string(), "en_IN.UTF-8".to_string()),        ]),        "/Users/me",    );    for name in SHELL_BOOKKEEPING {        assert_eq!(            env.get(name),            None,            "{name} describes the shell that answered, not the session that follows"        );    }    assert_eq!(env.get("LANG"), Some("en_IN.UTF-8"));}