rust-expect 0.5.0

Next-generation Expect-style terminal automation library for Rust
Documentation
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Integration tests for PTY spawning functionality.
//!
//! These tests verify the PTY backend works correctly with the `SessionBuilder`.

#![cfg(unix)] // PTY tests only work on Unix

use std::time::Duration;

use rust_expect::{QuickSession, SessionBuilder};

/// Test `SessionBuilder` creates valid config.
#[test]
fn session_builder_creates_config() {
    let config = SessionBuilder::new()
        .command("/bin/echo")
        .arg("hello world")
        .timeout(Duration::from_secs(5))
        .build();

    assert_eq!(config.command, "/bin/echo");
    assert_eq!(config.args, vec!["hello world"]);
    assert_eq!(config.timeout.default, Duration::from_secs(5));
}

/// Test `SessionBuilder` with environment variables.
#[test]
fn session_builder_with_env() {
    let config = SessionBuilder::new()
        .command("/bin/sh")
        .arg("-c")
        .arg("echo $TEST_VAR")
        .env("TEST_VAR", "test_value")
        .build();

    assert!(config.env.contains_key("TEST_VAR"));
    assert_eq!(config.env.get("TEST_VAR"), Some(&"test_value".to_string()));
}

/// Regression test: env vars set via `SessionBuilder::env()` must actually reach
/// the spawned child process. Before the env-plumbing fix in `backend/pty.rs`,
/// this would fail — the value was dropped between `PtyConfig::from` and
/// `execvp` on Unix.
#[tokio::test]
async fn env_vars_reach_child_process() {
    use rust_expect::Session;

    let config = SessionBuilder::new()
        .command("/bin/sh")
        .arg("-c")
        .arg("printf 'value=%s\\n' \"$RUST_EXPECT_TEST_VAR\"; exit 0")
        .env("RUST_EXPECT_TEST_VAR", "smelt-pinecone-42")
        .timeout(Duration::from_secs(5))
        .build();

    let mut session = Session::spawn_with_config(
        "/bin/sh",
        &[
            "-c",
            "printf 'value=%s\\n' \"$RUST_EXPECT_TEST_VAR\"; exit 0",
        ],
        config,
    )
    .await
    .expect("spawn should succeed");

    // Match the full string in one expect to avoid races on the split
    // between `value=` and the rest of the line.
    let m = session
        .expect_timeout("value=smelt-pinecone-42", Duration::from_secs(3))
        .await
        .expect("expected child to receive RUST_EXPECT_TEST_VAR=smelt-pinecone-42");
    assert!(m.matched.contains("smelt-pinecone-42"));

    session.wait_timeout(Duration::from_secs(2)).await.ok();
}

/// Env-var fix: when no explicit env is set, the child should still inherit
/// the parent's environment (Inherit mode is the default and previously
/// worked; this guards against regressing it).
#[tokio::test]
async fn parent_env_inherited_when_no_overrides() {
    use rust_expect::Session;
    // SAFETY: single-threaded test setup.
    #[allow(unsafe_code)]
    unsafe {
        std::env::set_var("RUST_EXPECT_PARENT_PROBE", "from-parent");
    }

    let config = SessionBuilder::new()
        .command("/bin/sh")
        .arg("-c")
        .arg("printf 'probe=%s\\n' \"$RUST_EXPECT_PARENT_PROBE\"; exit 0")
        .timeout(Duration::from_secs(5))
        .build();

    let mut session = Session::spawn_with_config(
        "/bin/sh",
        &[
            "-c",
            "printf 'probe=%s\\n' \"$RUST_EXPECT_PARENT_PROBE\"; exit 0",
        ],
        config,
    )
    .await
    .expect("spawn should succeed");

    let m = session
        .expect_timeout("probe=from-parent", Duration::from_secs(3))
        .await
        .expect("expected child to inherit RUST_EXPECT_PARENT_PROBE=from-parent");
    assert!(m.matched.contains("from-parent"));

    session.wait_timeout(Duration::from_secs(2)).await.ok();
}

/// cwd fix: `working_directory` must actually `chdir` the child before exec.
/// Before the fix in `backend/pty.rs`, `working_dir` was dropped between
/// `PtyConfig::from` and `execvp` on Unix, so the child ran in the parent's cwd.
#[tokio::test]
async fn working_dir_changes_child_cwd() {
    use rust_expect::Session;

    let dir = std::env::temp_dir();
    let canonical = std::fs::canonicalize(&dir).expect("temp dir should canonicalize");
    let expected = canonical.to_string_lossy().into_owned();

    let config = SessionBuilder::new()
        .command("/bin/sh")
        .arg("-c")
        .arg("pwd -P; exit 0")
        .working_directory(&canonical)
        .timeout(Duration::from_secs(5))
        .build();

    let mut session = Session::spawn_with_config("/bin/sh", &["-c", "pwd -P; exit 0"], config)
        .await
        .expect("spawn should succeed");

    let m = session
        .expect_timeout(expected.as_str(), Duration::from_secs(3))
        .await
        .expect("expected child to run in the configured working directory");
    assert!(m.matched.contains(&expected));

    session.wait_timeout(Duration::from_secs(2)).await.ok();
}

/// cwd fix: a non-existent `working_directory` must fail with a clean
/// `InvalidWorkingDir` spawn error rather than a cryptic child exit.
#[tokio::test]
async fn working_dir_missing_returns_clean_error() {
    use rust_expect::{ExpectError, Session, SpawnError};

    let config = SessionBuilder::new()
        .command("/bin/sh")
        .arg("-c")
        .arg("exit 0")
        .working_directory("/no/such/rust-expect/fixture/dir")
        .build();

    let result = Session::spawn_with_config("/bin/sh", &["-c", "exit 0"], config).await;
    let err = result.expect_err("spawn should fail for a non-existent working directory");
    assert!(
        matches!(
            err,
            ExpectError::Spawn(SpawnError::InvalidWorkingDir { .. })
        ),
        "expected InvalidWorkingDir, got {err:?}"
    );
}

/// env fix: `inherit_env(false)` must clear the parent environment so the child
/// sees only explicit overrides. Before the fix the flag was a silent no-op.
#[tokio::test]
async fn inherit_env_false_clears_parent_env() {
    use rust_expect::Session;
    // SAFETY: single-threaded test setup.
    #[allow(unsafe_code)]
    unsafe {
        std::env::set_var("RUST_EXPECT_CLEAR_PROBE", "should-not-appear");
    }

    let config = SessionBuilder::new()
        .command("/bin/sh")
        .arg("-c")
        .arg("printf 'probe=[%s]\\n' \"$RUST_EXPECT_CLEAR_PROBE\"; exit 0")
        .timeout(Duration::from_secs(5))
        .build()
        .inherit_env(false);

    let mut session = Session::spawn_with_config(
        "/bin/sh",
        &[
            "-c",
            "printf 'probe=[%s]\\n' \"$RUST_EXPECT_CLEAR_PROBE\"; exit 0",
        ],
        config,
    )
    .await
    .expect("spawn should succeed");

    let m = session
        .expect_timeout("probe=[]", Duration::from_secs(3))
        .await
        .expect("expected cleared env so the parent probe var is absent");
    assert!(m.matched.contains("probe=[]"));

    session.wait_timeout(Duration::from_secs(2)).await.ok();
}

/// Test `SessionBuilder` with custom dimensions.
#[test]
fn session_builder_with_dimensions() {
    let config = SessionBuilder::new()
        .command("/bin/sh")
        .dimensions(120, 40)
        .build();

    assert_eq!(config.dimensions, (120, 40));
}

/// Test `QuickSession::bash` creates correct config.
#[test]
fn quick_session_bash_config() {
    let config = QuickSession::bash();

    assert_eq!(config.command, "/bin/bash");
    assert!(config.args.contains(&"--norc".to_string()));
    assert!(config.args.contains(&"--noprofile".to_string()));
}

/// Test `QuickSession::shell` uses SHELL env var or default.
#[test]
fn quick_session_shell_config() {
    let config = QuickSession::shell();

    // Should have a command set
    assert!(!config.command.is_empty());
}

/// Test `QuickSession::ssh` creates correct config.
#[test]
fn quick_session_ssh_config() {
    let config = QuickSession::ssh("example.com");

    assert_eq!(config.command, "ssh");
    assert!(config.args.contains(&"example.com".to_string()));
    assert_eq!(config.timeout.default, Duration::from_secs(30));
}

/// Test `QuickSession::ssh_user` creates correct config.
#[test]
fn quick_session_ssh_user_config() {
    let config = QuickSession::ssh_user("admin", "server.example.com");

    assert_eq!(config.command, "ssh");
    assert!(
        config
            .args
            .contains(&"admin@server.example.com".to_string())
    );
}

/// Test `QuickSession::python` creates correct config.
#[test]
fn quick_session_python_config() {
    let config = QuickSession::python();

    assert_eq!(config.command, "python3");
    assert!(config.args.contains(&"-i".to_string()));
}

/// Test `QuickSession::telnet` creates correct config.
#[test]
fn quick_session_telnet_config() {
    let config = QuickSession::telnet("host.example.com", 23);

    assert_eq!(config.command, "telnet");
    assert!(config.args.contains(&"host.example.com".to_string()));
    assert!(config.args.contains(&"23".to_string()));
}

/// Test `SessionBuilder` working directory.
#[test]
fn session_builder_working_dir() {
    let config = SessionBuilder::new()
        .command("/bin/pwd")
        .working_directory("/tmp")
        .build();

    assert_eq!(config.working_dir, Some("/tmp".into()));
}

/// Test `SessionBuilder` line endings.
#[test]
fn session_builder_line_endings() {
    use rust_expect::LineEnding;

    let config_unix = SessionBuilder::new()
        .command("test")
        .unix_line_endings()
        .build();
    assert!(matches!(config_unix.line_ending, LineEnding::Lf));

    let config_windows = SessionBuilder::new()
        .command("test")
        .windows_line_endings()
        .build();
    assert!(matches!(config_windows.line_ending, LineEnding::CrLf));
}

/// Test `SessionBuilder` buffer configuration.
#[test]
fn session_builder_buffer_size() {
    let config = SessionBuilder::new()
        .command("test")
        .buffer_max_size(1024 * 1024)
        .build();

    assert_eq!(config.buffer.max_size, 1024 * 1024);
}

/// Test `SessionBuilder` logging.
#[test]
fn session_builder_logging() {
    let config = SessionBuilder::new()
        .command("test")
        .log_to_file("/tmp/test.log")
        .build();

    assert_eq!(config.logging.log_file, Some("/tmp/test.log".into()));
}

// =============================================================================
// End-to-end spawn tests (require actual process spawning)
// =============================================================================

use rust_expect::Session;

/// Test spawning a simple command and expecting output.
#[tokio::test]
async fn spawn_echo_command() {
    let mut session = Session::spawn("/bin/echo", &["hello", "world"])
        .await
        .expect("Failed to spawn echo");

    // Read the output
    let m = session.expect("world").await.expect("Expected 'world'");
    assert!(m.matched.contains("world"));
}

/// Test spawning a shell and sending commands.
#[tokio::test]
async fn spawn_shell_send_command() {
    let mut session = Session::spawn("/bin/sh", &[])
        .await
        .expect("Failed to spawn shell");

    // Wait for shell prompt ($ or something similar)
    // Send a command
    session
        .send_line("echo test123")
        .await
        .expect("Failed to send");

    // Expect the output
    let m = session.expect("test123").await.expect("Expected 'test123'");
    assert!(m.matched.contains("test123"));
}

/// Test spawning cat in interactive mode.
#[tokio::test]
async fn spawn_cat_interactive() {
    let mut session = Session::spawn("/bin/cat", &[])
        .await
        .expect("Failed to spawn cat");

    // Cat echoes what we send
    session
        .send_line("hello cat")
        .await
        .expect("Failed to send");

    let m = session
        .expect("hello cat")
        .await
        .expect("Expected 'hello cat'");
    assert!(m.matched.contains("hello cat"));

    // Send EOF to terminate cat (Ctrl+D)
    session
        .send_control(rust_expect::ControlChar::CtrlD)
        .await
        .expect("Failed to send EOF");
}

/// Test process ID is available.
#[tokio::test]
async fn spawn_has_pid() {
    // `/usr/bin/true` exists on both Linux and macOS (macOS has no `/bin/true`).
    // The migrated spawn correctly reports exec failure for a missing program,
    // unlike the old fork path which returned a pid for a doomed child.
    let session = Session::spawn("/usr/bin/true", &[])
        .await
        .expect("Failed to spawn true");

    let pid = session.pid();
    assert!(pid > 0, "Expected valid PID, got {pid}");
}

/// Spawning a non-existent program must surface a spawn error. The old
/// hand-rolled fork path returned `Ok` with a pid for a child that then failed
/// to `exec`; the migrated `tokio::process` path reports the failure.
#[tokio::test]
async fn spawn_reports_missing_program() {
    let result = Session::spawn("/no/such/rust-expect/program", &[]).await;
    assert!(
        result.is_err(),
        "spawning a non-existent program should error, got Ok"
    );
}

/// Test spawn with custom configuration.
#[tokio::test]
async fn spawn_with_custom_config() {
    use rust_expect::SessionConfig;

    let config = SessionConfig {
        dimensions: (100, 30),
        ..SessionConfig::default()
    };

    let session = Session::spawn_with_config("/bin/sh", &[], config)
        .await
        .expect("Failed to spawn with config");

    // Just verify it spawned successfully
    let pid = session.pid();
    assert!(pid > 0);
}

/// Test spawning command that fails.
#[tokio::test]
async fn spawn_nonexistent_command() {
    let result = Session::spawn("/nonexistent/command", &[]).await;
    // The spawn should succeed (fork works), but the exec fails
    // The child process will exit immediately with code 1
    // This is expected behavior for PTY spawning
    // We just verify we don't panic
    assert!(result.is_ok() || result.is_err());
}

/// Test sending control characters.
#[tokio::test]
async fn spawn_send_control_c() {
    let mut session = Session::spawn("/bin/cat", &[])
        .await
        .expect("Failed to spawn cat");

    // Send Ctrl-C to interrupt
    session
        .send_control(rust_expect::ControlChar::CtrlC)
        .await
        .expect("Failed to send Ctrl-C");

    // Cat should terminate after Ctrl-C
    // Wait for EOF with a timeout to prevent hanging if something goes wrong
    let result = session.wait_timeout(Duration::from_secs(5)).await;

    // The process should have exited (EOF detected) or we timed out
    // Either outcome is acceptable for this test - we mainly want to verify
    // that Ctrl-C was sent successfully and the test doesn't hang
    assert!(
        result.is_ok() || result.is_err(),
        "wait_timeout should return a result"
    );
}

/// Test basic expect with multiple patterns.
#[tokio::test]
async fn spawn_expect_multiple() {
    let mut session = Session::spawn("/bin/sh", &[])
        .await
        .expect("Failed to spawn shell");

    session
        .send_line("echo first; echo second")
        .await
        .expect("Failed to send");

    // Expect first
    session.expect("first").await.expect("Expected 'first'");

    // Expect second
    session.expect("second").await.expect("Expected 'second'");
}

/// Test that matched field contains the expected text.
#[tokio::test]
async fn spawn_match_contains_text() {
    let mut session = Session::spawn("/bin/echo", &["hello", "world"])
        .await
        .expect("Failed to spawn echo");

    let m = session.expect("hello").await.expect("Expected 'hello'");

    // The matched field should contain the matched text
    assert!(m.matched.contains("hello"), "Match should contain 'hello'");
}