rust-use 0.3.0

A library of behaviors for agents to build and drive the next generation of user interfaces.
//! Drive agent-visible components in tests and inspect their screen and change events.
//!
//! ```toml
//! [dev-dependencies]
//! rust-use = { version = "0.3", features = ["testing"] }
//! ```
//!
//! ```
//! use rust_use::prelude::*;
//! use rust_use::testing::*;
//!
//! #[derive(Default)]
//! struct Mute(Toggle);
//!
//! impl Behavior for Mute {
//!     fn describe(&self, out: &mut Describe) {
//!         self.0.describe(out);
//!     }
//!     fn actions(&self) -> Vec<ActionSpec> {
//!         self.0.actions()
//!     }
//!     fn invoke(&mut self, action: &str, args: &Args) -> Option<Result<Value, ActionError>> {
//!         self.0.invoke(action, args)
//!     }
//! }
//!
//! impl Primitive for Mute {
//!     const NAME: &'static str = "toggle";
//! }
//!
//! let harness = Harness::new();
//! harness.mount(Mute::default(), "Mute");
//! let changes = harness.recorder();
//! harness.act_ok("Mute toggle");
//! assert_line!(harness, "Mute", r#"@1 toggle "Mute" =true !toggle !set(on:bool)"#);
//! assert_eq!(changes.sources(), [ChangeSource::Agent]);
//!
//! changes.clear();
//! harness.user("Mute", "set", (false,));
//! assert_eq!(changes.sources(), [ChangeSource::User]);
//! ```

use crate::{
    ActOutcome, Agent, Args, ChangeEvent, ChangeSource, Handle, Primitive, SnapshotOptions,
    Subscription, Ui, Value,
};
use std::sync::{Arc, Mutex, PoisonError};

/// A UI and an agent session with assertions that include the whole screen on failure.
pub struct Harness {
    /// Registry for mounting components and inspecting or updating their state.
    pub ui: Ui,
    agent: Agent,
}

impl Default for Harness {
    fn default() -> Self {
        Self::new()
    }
}

// Panics in these test assertions report failures at the call site.
#[allow(clippy::panic)]
impl Harness {
    /// Start with an empty UI and a fresh agent session.
    pub fn new() -> Self {
        let ui = Ui::new();
        let agent = Agent::new(&ui);
        Self { ui, agent }
    }

    /// Mount a primitive with the given label.
    pub fn mount<P: Primitive>(&self, p: P, label: &str) -> Handle<P> {
        self.ui.mount(p).label(label)
    }

    /// Run a script as the agent and return its outcome.
    ///
    /// # Panics
    /// Panics with the full error reply and current snapshot if the script fails.
    #[track_caller]
    pub fn act_ok(&self, script: &str) -> ActOutcome {
        match self.agent.act(script) {
            Ok(outcome) => outcome,
            Err(error) => panic!(
                "agent script {script:?} failed\n{}\n\n{}",
                error.to_reply(),
                self.snapshot()
            ),
        }
    }

    /// Run a script as the agent and return its error reply.
    ///
    /// # Panics
    /// Panics with the outcome and current snapshot if the script succeeds.
    #[track_caller]
    pub fn act_err(&self, script: &str) -> String {
        match self.agent.act(script) {
            Ok(outcome) => panic!(
                "agent script {script:?} succeeded\n{outcome}\n\n{}",
                self.snapshot()
            ),
            Err(error) => error.to_reply(),
        }
    }

    /// Invoke an action as a person ([`ChangeSource::User`]).
    ///
    /// # Panics
    /// Panics with the invocation error and current snapshot on failure.
    #[track_caller]
    pub fn user(&self, target: &str, action: &str, args: impl Into<Args>) -> Value {
        match self.ui.invoke(target, action, args, ChangeSource::User) {
            Ok(value) => value,
            Err(error) => panic!(
                "user action {action:?} on {target:?} failed\n{error}\n\n{}",
                self.snapshot()
            ),
        }
    }

    /// Return the compact snapshot line for one agent-visible component.
    ///
    /// # Panics
    /// Panics with the current snapshot if the target is missing or ambiguous.
    #[track_caller]
    pub fn line(&self, target: &str) -> String {
        let id = match self.ui.resolve_for(target, ChangeSource::Agent) {
            Ok(id) => id,
            Err(error) => panic!(
                "could not find snapshot line for {target:?}\n{error}\n\n{}",
                self.snapshot()
            ),
        };
        let snapshot = self.agent.snapshot_with(SnapshotOptions {
            from: Some(id),
            limit: 1,
            docs: false,
        });
        if snapshot
            .components
            .first()
            .is_some_and(|component| component.id == id)
            && let Some(line) = snapshot.to_string().lines().nth(1)
        {
            return line.to_owned();
        }
        panic!(
            "component {target:?} ({id}) disappeared from the snapshot\n\n{}",
            self.snapshot()
        );
    }

    /// Return the full compact snapshot, including the revision and all visible components.
    pub fn snapshot(&self) -> String {
        self.agent
            .snapshot_with(SnapshotOptions {
                limit: usize::MAX,
                ..SnapshotOptions::default()
            })
            .to_string()
    }

    /// Start recording changes on this UI.
    pub fn recorder(&self) -> Recorder {
        let events = Arc::new(Mutex::new(Vec::new()));
        let recorded = Arc::clone(&events);
        let subscription = self.ui.subscribe(move |event| {
            recorded
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .push(event.clone());
        });
        Recorder {
            _subscription: subscription,
            events,
        }
    }
}

/// Records committed change events until dropped.
pub struct Recorder {
    _subscription: Subscription,
    events: Arc<Mutex<Vec<ChangeEvent>>>,
}

impl Recorder {
    /// Return the events received since recording began or was last cleared.
    pub fn events(&self) -> Vec<ChangeEvent> {
        self.events
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Return the source of each recorded event.
    pub fn sources(&self) -> Vec<ChangeSource> {
        self.events
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .iter()
            .map(|event| event.source)
            .collect()
    }

    /// Discard the events recorded so far and continue recording.
    pub fn clear(&self) {
        self.events
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
    }
}

/// Assert a component's snapshot line and show the full snapshot on mismatch.
#[macro_export]
macro_rules! assert_line {
    ($harness:expr, $target:expr, $expected:expr $(,)?) => {{
        let harness = &$harness;
        ::std::assert_eq!(
            harness.line($target),
            $expected,
            "snapshot\n{}",
            harness.snapshot()
        );
    }};
}

#[doc(inline)]
pub use crate::assert_line;