switchy_async 0.3.0

Switchy Async runtime package
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Simulated process spawning and management.
//!
//! Provides fully deterministic mock implementations for testing.
//! No real processes are spawned - all behavior is controlled via the [`ProcessRegistry`].
//!
//! # Example
//!
//! ```ignore
//! use switchy_async::process::{Command, MockResponse, ProcessRegistry, set_registry};
//!
//! // Set up mock responses
//! let registry = ProcessRegistry::new();
//! registry.register(
//!     MockResponse::success()
//!         .for_program("rustfmt")
//!         .with_stdout(b"Formatted successfully")
//! );
//! set_registry(registry);
//!
//! // Now Command will return the mocked response
//! let output = Command::new("rustfmt").output().await.unwrap();
//! assert!(output.status.success());
//! ```

use std::collections::VecDeque;
use std::ffi::OsStr;
use std::io::{self, Cursor};
use std::path::Path;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use tokio::io::{AsyncRead, ReadBuf};

/// Simulated exit status.
///
/// Unlike `std::process::ExitStatus`, this is fully controlled by tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExitStatus {
    code: Option<i32>,
}

impl ExitStatus {
    /// Creates a successful exit status (code 0).
    #[must_use]
    pub const fn from_success() -> Self {
        Self { code: Some(0) }
    }

    /// Creates an exit status with the given code.
    #[must_use]
    pub const fn from_code(code: i32) -> Self {
        Self { code: Some(code) }
    }

    /// Creates an exit status representing termination by signal (no code).
    #[must_use]
    pub const fn from_signal() -> Self {
        Self { code: None }
    }

    /// Returns true if the process exited successfully (code 0).
    #[must_use]
    pub const fn success(&self) -> bool {
        matches!(self.code, Some(0))
    }

    /// Returns the exit code, if any.
    #[must_use]
    pub const fn code(&self) -> Option<i32> {
        self.code
    }
}

impl Default for ExitStatus {
    fn default() -> Self {
        Self::from_success()
    }
}

/// Simulated process output.
///
/// Contains the exit status and captured stdout/stderr.
#[derive(Debug, Clone, Default)]
pub struct Output {
    /// The exit status of the process.
    pub status: ExitStatus,
    /// The data that the process wrote to stdout.
    pub stdout: Vec<u8>,
    /// The data that the process wrote to stderr.
    pub stderr: Vec<u8>,
}

/// Configuration for standard I/O streams.
///
/// Mirrors `std::process::Stdio` but is fully simulated.
#[derive(Debug, Clone, Copy, Default)]
pub enum Stdio {
    /// Inherit the parent's stdio.
    #[default]
    Inherit,
    /// Capture the stdio as a pipe.
    Piped,
    /// Discard the stdio (like /dev/null).
    Null,
}

impl From<std::process::Stdio> for Stdio {
    fn from(stdio: std::process::Stdio) -> Self {
        // We can't inspect std::process::Stdio, so default to Inherit
        // In practice, tests should use our Stdio directly
        let _ = stdio;
        Self::Inherit
    }
}

/// A mock response for a simulated command.
///
/// Use the builder methods to configure the response.
#[derive(Debug, Clone)]
pub struct MockResponse {
    /// Program name matcher (None = match any)
    pub program: Option<String>,
    /// Arguments matcher (None = match any)
    pub args: Option<Vec<String>>,
    /// Simulated stdout
    pub stdout: Vec<u8>,
    /// Simulated stderr
    pub stderr: Vec<u8>,
    /// Simulated exit code
    pub exit_code: i32,
    /// Optional delay before returning (for timing tests)
    #[cfg(feature = "time")]
    pub delay: Option<std::time::Duration>,
    /// If true, simulate spawn failure instead of returning output
    pub fail_to_spawn: bool,
    /// Error message if `fail_to_spawn` is true
    pub spawn_error: Option<String>,
}

impl Default for MockResponse {
    fn default() -> Self {
        Self::success()
    }
}

impl MockResponse {
    /// Creates a successful response with no output.
    #[must_use]
    pub const fn success() -> Self {
        Self {
            program: None,
            args: None,
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 0,
            #[cfg(feature = "time")]
            delay: None,
            fail_to_spawn: false,
            spawn_error: None,
        }
    }

    /// Creates a failed response with the given exit code.
    #[must_use]
    pub const fn failure(exit_code: i32) -> Self {
        Self {
            program: None,
            args: None,
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code,
            #[cfg(feature = "time")]
            delay: None,
            fail_to_spawn: false,
            spawn_error: None,
        }
    }

    /// Sets the program name to match.
    #[must_use]
    pub fn for_program(mut self, program: impl Into<String>) -> Self {
        self.program = Some(program.into());
        self
    }

    /// Sets the arguments to match.
    #[must_use]
    pub fn for_args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args = Some(args.into_iter().map(Into::into).collect());
        self
    }

    /// Sets stdout content.
    #[must_use]
    pub fn with_stdout(mut self, stdout: impl Into<Vec<u8>>) -> Self {
        self.stdout = stdout.into();
        self
    }

    /// Sets stderr content.
    #[must_use]
    pub fn with_stderr(mut self, stderr: impl Into<Vec<u8>>) -> Self {
        self.stderr = stderr.into();
        self
    }

    /// Sets the exit code.
    #[must_use]
    pub const fn with_exit_code(mut self, code: i32) -> Self {
        self.exit_code = code;
        self
    }

    /// Sets a simulated delay before the command completes.
    ///
    /// Requires the `time` feature.
    #[cfg(feature = "time")]
    #[must_use]
    pub const fn with_delay(mut self, delay: std::time::Duration) -> Self {
        self.delay = Some(delay);
        self
    }

    /// Makes the command fail to spawn with the given error message.
    #[must_use]
    pub fn fail_spawn(mut self, message: impl Into<String>) -> Self {
        self.fail_to_spawn = true;
        self.spawn_error = Some(message.into());
        self
    }

    /// Checks if this response matches the given program and args.
    fn matches(&self, program: &str, args: &[String]) -> bool {
        if let Some(ref expected_program) = self.program
            && expected_program != program
        {
            return false;
        }
        if let Some(ref expected_args) = self.args
            && expected_args != args
        {
            return false;
        }
        true
    }
}

/// Registry for mock process responses.
///
/// Tests register expected responses, and [`Command`] consumes them in order.
#[derive(Debug, Default, Clone)]
pub struct ProcessRegistry {
    responses: Arc<Mutex<VecDeque<MockResponse>>>,
    default_response: Arc<Mutex<Option<MockResponse>>>,
}

impl ProcessRegistry {
    /// Creates a new empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a mock response (FIFO order).
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    pub fn register(&self, response: MockResponse) {
        self.responses.lock().unwrap().push_back(response);
    }

    /// Registers multiple mock responses.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    pub fn register_all<I>(&self, responses: I)
    where
        I: IntoIterator<Item = MockResponse>,
    {
        let mut queue = self.responses.lock().unwrap();
        for response in responses {
            queue.push_back(response);
        }
    }

    /// Sets a default response for unmatched commands.
    ///
    /// This is returned when no registered response matches.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    pub fn set_default(&self, response: MockResponse) {
        *self.default_response.lock().unwrap() = Some(response);
    }

    /// Returns the number of registered responses remaining.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    #[must_use]
    pub fn remaining(&self) -> usize {
        self.responses.lock().unwrap().len()
    }

    /// Clears all registered responses.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    pub fn clear(&self) {
        self.responses.lock().unwrap().clear();
        *self.default_response.lock().unwrap() = None;
    }

    /// Takes the next matching response.
    fn take_response(&self, program: &str, args: &[String]) -> Option<MockResponse> {
        let mut responses = self.responses.lock().unwrap();

        // Find first matching response
        if let Some(idx) = responses.iter().position(|r| r.matches(program, args)) {
            return responses.remove(idx);
        }

        drop(responses);

        // Fall back to default
        self.default_response.lock().unwrap().clone()
    }
}

thread_local! {
    static PROCESS_REGISTRY: std::cell::RefCell<Option<ProcessRegistry>> =
        const { std::cell::RefCell::new(None) };
}

/// Sets the process registry for the current thread/simulation.
///
/// # Example
///
/// ```ignore
/// let registry = ProcessRegistry::new();
/// registry.register(MockResponse::success().for_program("ls"));
/// set_registry(registry);
/// ```
pub fn set_registry(registry: ProcessRegistry) {
    PROCESS_REGISTRY.with(|r| {
        *r.borrow_mut() = Some(registry);
    });
}

/// Clears the process registry for the current thread.
pub fn clear_registry() {
    PROCESS_REGISTRY.with(|r| {
        *r.borrow_mut() = None;
    });
}

/// Gets the current process registry, if set.
#[must_use]
pub fn get_registry() -> Option<ProcessRegistry> {
    PROCESS_REGISTRY.with(|r| r.borrow().clone())
}

/// Simulated async command builder.
///
/// Mirrors `tokio::process::Command` but returns mocked responses
/// from the [`ProcessRegistry`].
#[derive(Debug)]
pub struct Command {
    program: String,
    args: Vec<String>,
    current_dir: Option<std::path::PathBuf>,
    stdin: Stdio,
    stdout: Stdio,
    stderr: Stdio,
}

impl Command {
    /// Creates a new `Command` for the given program.
    #[must_use]
    pub fn new<S: AsRef<OsStr>>(program: S) -> Self {
        Self {
            program: program.as_ref().to_string_lossy().to_string(),
            args: Vec::new(),
            current_dir: None,
            stdin: Stdio::default(),
            stdout: Stdio::default(),
            stderr: Stdio::default(),
        }
    }

    /// Adds an argument.
    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
        self.args.push(arg.as_ref().to_string_lossy().to_string());
        self
    }

    /// Adds multiple arguments.
    pub fn args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        for arg in args {
            self.arg(arg);
        }
        self
    }

    /// Sets the working directory.
    pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
        self.current_dir = Some(dir.as_ref().to_path_buf());
        self
    }

    /// Sets the stdin configuration.
    pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
        self.stdin = cfg.into();
        self
    }

    /// Sets the stdout configuration.
    pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
        self.stdout = cfg.into();
        self
    }

    /// Sets the stderr configuration.
    pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
        self.stderr = cfg.into();
        self
    }

    /// Executes the command and collects output.
    ///
    /// Returns the mocked response from the registry, or a default success
    /// if no response is registered.
    ///
    /// # Errors
    ///
    /// Returns an error if the mock is configured to fail spawn.
    pub async fn output(&mut self) -> io::Result<Output> {
        let response = get_registry()
            .and_then(|r| r.take_response(&self.program, &self.args))
            .unwrap_or_default();

        if response.fail_to_spawn {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                response
                    .spawn_error
                    .unwrap_or_else(|| "command not found".to_string()),
            ));
        }

        // Simulate delay if configured
        #[cfg(feature = "time")]
        if let Some(delay) = response.delay {
            crate::time::sleep(delay).await;
        }

        Ok(Output {
            status: ExitStatus::from_code(response.exit_code),
            stdout: response.stdout,
            stderr: response.stderr,
        })
    }

    /// Spawns the command as a child process.
    ///
    /// # Errors
    ///
    /// Returns an error if the mock is configured to fail.
    pub fn spawn(&mut self) -> io::Result<Child> {
        let response = get_registry()
            .and_then(|r| r.take_response(&self.program, &self.args))
            .unwrap_or_default();

        if response.fail_to_spawn {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                response
                    .spawn_error
                    .unwrap_or_else(|| "command not found".to_string()),
            ));
        }

        // Create stdout/stderr handles based on Stdio configuration
        let stdout = if matches!(self.stdout, Stdio::Piped) {
            Some(ChildStdout::new(response.stdout.clone()))
        } else {
            None
        };

        let stderr = if matches!(self.stderr, Stdio::Piped) {
            Some(ChildStderr::new(response.stderr.clone()))
        } else {
            None
        };

        Ok(Child {
            response,
            stdout,
            stderr,
        })
    }
}

/// Simulated child process handle.
///
/// Created by [`Command::spawn`].
#[derive(Debug)]
pub struct Child {
    response: MockResponse,
    /// Handle to the child's standard output.
    ///
    /// This is `Some` if stdout was set to `Stdio::piped()` on the command.
    /// Use `.take()` to take ownership of the handle.
    pub stdout: Option<ChildStdout>,
    /// Handle to the child's standard error.
    ///
    /// This is `Some` if stderr was set to `Stdio::piped()` on the command.
    /// Use `.take()` to take ownership of the handle.
    pub stderr: Option<ChildStderr>,
}

impl Child {
    /// Waits for the child to exit.
    ///
    /// # Errors
    ///
    /// This simulated version never fails.
    pub async fn wait(&mut self) -> io::Result<ExitStatus> {
        #[cfg(feature = "time")]
        if let Some(delay) = self.response.delay {
            crate::time::sleep(delay).await;
        }
        Ok(ExitStatus::from_code(self.response.exit_code))
    }

    /// Waits for the child to exit and collects output.
    ///
    /// # Errors
    ///
    /// This simulated version never fails.
    pub async fn wait_with_output(self) -> io::Result<Output> {
        #[cfg(feature = "time")]
        if let Some(delay) = self.response.delay {
            crate::time::sleep(delay).await;
        }
        Ok(Output {
            status: ExitStatus::from_code(self.response.exit_code),
            stdout: self.response.stdout.clone(),
            stderr: self.response.stderr.clone(),
        })
    }

    /// Forces the child process to exit.
    ///
    /// In the simulator, this is a no-op since there's no real process to kill.
    /// The method exists for API compatibility with `tokio::process::Child`.
    ///
    /// # Errors
    ///
    /// This simulated version never fails.
    #[allow(clippy::unused_async)] // Keep async for API compatibility with tokio::process::Child
    pub async fn kill(&mut self) -> io::Result<()> {
        // No-op in simulator - there's no real process to kill
        Ok(())
    }
}

/// A handle to a child process's standard input.
///
/// In the simulator, this is a no-op sink that discards all written data.
#[derive(Debug)]
pub struct ChildStdin;

/// A handle to a child process's standard output.
///
/// In the simulator, this reads from the mocked stdout data.
#[derive(Debug)]
pub struct ChildStdout {
    data: Cursor<Vec<u8>>,
}

impl ChildStdout {
    /// Creates a new `ChildStdout` with the given data.
    pub(crate) const fn new(data: Vec<u8>) -> Self {
        Self {
            data: Cursor::new(data),
        }
    }
}

impl AsyncRead for ChildStdout {
    fn poll_read(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let data = self.data.get_ref();
        #[allow(clippy::cast_possible_truncation)]
        // Position can never exceed Vec length (which is usize)
        let pos = self.data.position() as usize;
        let remaining = &data[pos..];

        let to_read = std::cmp::min(remaining.len(), buf.remaining());
        buf.put_slice(&remaining[..to_read]);
        self.data.set_position((pos + to_read) as u64);

        Poll::Ready(Ok(()))
    }
}

/// A handle to a child process's standard error.
///
/// In the simulator, this reads from the mocked stderr data.
#[derive(Debug)]
pub struct ChildStderr {
    data: Cursor<Vec<u8>>,
}

impl ChildStderr {
    /// Creates a new `ChildStderr` with the given data.
    pub(crate) const fn new(data: Vec<u8>) -> Self {
        Self {
            data: Cursor::new(data),
        }
    }
}

impl AsyncRead for ChildStderr {
    fn poll_read(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let data = self.data.get_ref();
        #[allow(clippy::cast_possible_truncation)]
        // Position can never exceed Vec length (which is usize)
        let pos = self.data.position() as usize;
        let remaining = &data[pos..];

        let to_read = std::cmp::min(remaining.len(), buf.remaining());
        buf.put_slice(&remaining[..to_read]);
        self.data.set_position((pos + to_read) as u64);

        Poll::Ready(Ok(()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test_log::test]
    fn exit_status_success() {
        let status = ExitStatus::from_success();
        assert!(status.success());
        assert_eq!(status.code(), Some(0));
    }

    #[test_log::test]
    fn exit_status_failure() {
        let status = ExitStatus::from_code(1);
        assert!(!status.success());
        assert_eq!(status.code(), Some(1));
    }

    #[test_log::test]
    fn exit_status_signal() {
        let status = ExitStatus::from_signal();
        assert!(!status.success());
        assert_eq!(status.code(), None);
    }

    #[test_log::test]
    fn mock_response_builder() {
        let response = MockResponse::success()
            .for_program("test")
            .with_stdout(b"hello".to_vec())
            .with_stderr(b"error".to_vec())
            .with_exit_code(42);

        assert_eq!(response.program, Some("test".to_string()));
        assert_eq!(response.stdout, b"hello");
        assert_eq!(response.stderr, b"error");
        assert_eq!(response.exit_code, 42);
    }

    #[test_log::test]
    fn mock_response_matches() {
        let response = MockResponse::success().for_program("cargo");

        assert!(response.matches("cargo", &[]));
        assert!(!response.matches("rustc", &[]));

        let response_any = MockResponse::success();
        assert!(response_any.matches("anything", &[]));
    }

    #[test_log::test]
    fn registry_fifo_order() {
        let registry = ProcessRegistry::new();
        registry.register(MockResponse::success().for_program("first"));
        registry.register(MockResponse::success().for_program("second"));

        let first = registry.take_response("first", &[]);
        assert!(first.is_some());
        assert_eq!(first.unwrap().program, Some("first".to_string()));

        let second = registry.take_response("second", &[]);
        assert!(second.is_some());
        assert_eq!(second.unwrap().program, Some("second".to_string()));

        assert!(registry.take_response("third", &[]).is_none());
    }

    #[test_log::test]
    fn registry_default_response() {
        let registry = ProcessRegistry::new();
        registry.set_default(MockResponse::failure(99));

        let response = registry.take_response("unknown", &[]);
        assert!(response.is_some());
        assert_eq!(response.unwrap().exit_code, 99);
    }
}