laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
//! Tools for testing an application without starting a server.
//!
//! Most application tests send a request to the application and check its response. Write
//! tests with [`#[laravel::test]`](crate::test). A test that takes an [`Application`] gets a
//! fresh application of its own and runs inside it. Import [`prelude`] to bring in the traits
//! that give the application its test methods:
//!
//! - [`MakesHttpRequests`] sends requests through middleware, routing, and error handling
//!   without opening a socket, and returns a [`TestResponse`] with assertions.
//! - [`MakesConsoleRequests`] runs console commands and captures their output.
//! - [`RunsJobs`] runs one attempt of a queued job, or one method of a batch callback.
//! - [`RunsWorkflows`] runs a workflow until it finishes or suspends, and lets the test resume it.
//! - [`InteractsWithDatabase`] asserts what a test left in the database.
//!
//! [`Application`] also has methods of its own for tests. [`travel`](Application::travel) and
//! the other time-travel methods move the application's clock, [`swap`](Application::swap)
//! replaces a service with a fake, and [`listener`](Application::listener) runs one event
//! listener.
//!
//! ```no_run
//! use laravel::testing::prelude::*;
//!
//! # mod users { pub async fn show() {} }
//! # async fn test(app: Application) {
//! app.get("/").await.assert_ok().assert_see("Welcome");
//!
//! app.post("/users")
//!     .json(serde_json::json!({ "name": "Taylor" }))
//!     .await
//!     .assert_redirect_to_route(users::show, 1);
//! # }
//! ```
//!
//! To learn how to configure tests, refresh the database between them, and use fakes, check
//! out the [testing guide](https://github.com/laravel/rust-framework/blob/0.x/docs/testing.md).

mod console;
#[cfg(feature = "database")]
mod database;
use laravel_core::testing::fake_stack;
mod json;
pub mod prelude;
mod queue;
mod request;
mod response;
mod workflow;

pub use self::console::{MakesConsoleRequests, TestCommand, TestCommandResult};
#[cfg(feature = "database")]
pub use self::database::{DatabaseAssertion, InteractsWithDatabase};
pub(crate) use self::fake_stack::{FakeGuard, FakeStack};
pub use self::json::AssertableJson;
pub use self::queue::{RunsJobs, TestCallback, TestJob, TestJobResult};
pub use self::request::{MakesHttpRequests, TestRequest};
pub use self::response::TestResponse;
pub use self::workflow::{RunsWorkflows, TestRun, TestWorkflow};

use std::future::Future;
use std::sync::Arc;

use crate::Error;
use crate::event::{Event, Listener};
use crate::foundation::Application;

/// Find the error of type `E` in `error`, whether `error` is that error, wraps it in context, or
/// keeps it as a `#[source]`.
fn find_error<E: std::error::Error + Send + Sync + 'static>(error: &Error) -> Option<&E> {
    error
        .downcast_ref::<E>()
        .or_else(|| error.chain().find_map(|cause| cause.downcast_ref::<E>()))
}

/// Run the future that [`crate::test`] generates, on a new single-threaded runtime.
#[doc(hidden)]
pub fn __run<F: Future>(future: F) -> F::Output {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("the test runtime couldn't be created")
        .block_on(future)
}

/// Seed the test application's factory faker from the test's name unless already seeded.
#[doc(hidden)]
pub fn __seed_test(app: &Application, name: &str) {
    #[cfg(feature = "database")]
    app.seed_faker_default(name);
    #[cfg(not(feature = "database"))]
    let _ = (app, name);
}

/// Methods that move the application's clock, so a test can check what happens later without
/// waiting, such as a signed URL or a session expiring.
///
/// ```no_run
/// use laravel::testing::MakesHttpRequests;
/// use laravel::time::ToSpan;
///
/// # async fn test(app: laravel::Application, url: &str) {
/// app.travel(31.minutes());
///
/// app.get(url).await.assert_forbidden();
/// # }
/// ```
///
/// After any of these methods, the time that [`laravel::now`](crate::now) returns stays where it
/// stopped until you call [`travel_back`](Application::travel_back). Each application has its
/// own clock, so tests that run at the same time don't move each other's clocks.
impl Application {
    /// Move the application's time forward by `amount`, and stop it there.
    ///
    /// The amount is a [`Span`](crate::time::Span), such as `5.minutes()` with
    /// [`ToSpan`](crate::time::ToSpan) in scope, or a `std::time::Duration`. A span may use
    /// calendar units such as `1.month()`, which the clock counts in UTC.
    ///
    /// # Panics
    ///
    /// Panics when the new time is before 1970 or after 2554.
    #[track_caller]
    pub fn travel(&self, amount: impl Into<jiff::ZonedDateTimeArithmetic>) -> &Self {
        let Ok(time) = crate::clock::utc(self.clock().now()).checked_add(amount) else {
            panic!("tests can only travel to times between 1970 and 2554");
        };

        self.travel_to(time)
    }

    /// Move the application's time to `time`, and stop it there.
    ///
    /// The time is a [`ZonedDateTime`](crate::time::ZonedDateTime), such as one from
    /// [`laravel::now`](crate::now), or a [`Timestamp`](crate::time::Timestamp). The clock keeps a
    /// `ZonedDateTime`'s instant but not its time zone, so `laravel::now()` still returns UTC.
    ///
    /// # Panics
    ///
    /// Panics when the time is before 1970 or after 2554.
    #[track_caller]
    pub fn travel_to(&self, time: impl Into<jiff::Timestamp>) -> &Self {
        self.clock().stop_at(Some(time.into()));

        self
    }

    /// Stop the application's time where it is.
    pub fn freeze_time(&self) -> &Self {
        self.travel_to(crate::clock::utc(self.clock().now()))
    }

    /// Stop the application's time at the start of the current second.
    ///
    /// Some databases store timestamps in whole seconds. Freezing at a whole second lets a test
    /// compare the application's times with the stored ones exactly.
    #[expect(
        clippy::missing_panics_doc,
        reason = "the start of a second of the clock's own time is always a valid timestamp"
    )]
    pub fn freeze_second(&self) -> &Self {
        let second = crate::clock::utc(self.clock().now()).timestamp().as_second();

        self.travel_to(jiff::Timestamp::from_second(second).expect("a whole second of a valid time is valid"))
    }

    /// Return the application's time to the present, so it follows the system clock again.
    pub fn travel_back(&self) -> &Self {
        self.clock().stop_at(None);

        self
    }
}

/// Methods that replace a service with a fake, such as a payment client that records charges
/// instead of making them.
///
/// ```no_run
/// use std::sync::Arc;
/// use laravel::testing::MakesHttpRequests;
/// # trait Billing: Send + Sync {}
/// # #[derive(Default)] struct FakeBilling;
/// # impl FakeBilling { fn assert_charged(&self, cents: u64) {} }
/// # impl Billing for FakeBilling {}
///
/// # async fn test(app: laravel::Application) {
/// let billing = Arc::new(FakeBilling::default());
/// app.swap_as(Arc::clone(&billing) as Arc<dyn Billing>);
///
/// app.post("/checkout").await.assert_redirect();
/// billing.assert_charged(2_000);
/// # }
/// ```
///
/// After a swap, everything that resolves the service receives the replacement, including
/// handlers, middleware, commands, and factories. Services that were already built with the
/// original keep the original, so swap a service before you send the requests that use it.
impl Application {
    /// Register `service` in place of the application's `T`, and return a shared handle to it.
    ///
    /// Keep the handle to make assertions on the fake, as in `let stripe = app.swap(Stripe::fake())`.
    pub fn swap<T: Send + Sync + 'static>(&self, service: T) -> Arc<T> {
        let service = Arc::new(service);
        self.services().insert(Arc::clone(&service));

        service
    }

    /// Register a shared service in place of the application's `T`.
    ///
    /// `T` may be a trait object, as in `app.swap_as(fake as Arc<dyn Billing>)`. Keep your own
    /// clone of the `Arc` to make assertions on the fake.
    pub fn swap_as<T: ?Sized + Send + Sync + 'static>(&self, service: Arc<T>) -> &Self {
        self.services().insert(service);

        self
    }
}

/// A method that runs one event listener, so a test can check it apart from the event's other
/// listeners.
///
/// ```
/// use std::sync::Mutex;
/// use laravel::container::Inject;
/// use laravel::event::Event;
///
/// struct OrderPlaced { order_id: u64 }
///
/// #[derive(Default)]
/// struct AuditLog(Mutex<Vec<u64>>);
///
/// async fn record_order(event: Event<OrderPlaced>, audit: Inject<AuditLog>) {
///     audit.0.lock().unwrap().push(event.order_id);
/// }
///
/// let app = laravel::Application::configure()
///     .replace_env(laravel::config::Env::default())
///     .create();
/// laravel::testing::__run(async {
///     let audit = app.swap(AuditLog::default());
///
///     app.listener(record_order, OrderPlaced { order_id: 42 }).await.unwrap();
///
///     assert_eq!(*audit.0.lock().unwrap(), [42]);
/// });
/// ```
impl Application {
    /// Run `listener` with `event` in a fresh context of the application.
    ///
    /// The listener resolves its services as it would during a dispatch, and the event's other
    /// listeners don't run. A queued listener pushes its job as a dispatch would. In the
    /// `testing` environment, every job goes to the default connection, even when the listener
    /// names another one. That connection is `sync` unless the test sets `QUEUE_CONNECTION`, so
    /// the job runs before this method returns.
    ///
    /// # Errors
    ///
    /// Returns the listener's error or an error resolving its services. For a queued listener,
    /// also returns the queue's error.
    pub async fn listener<E, Args>(&self, listener: impl Listener<E, Args>, event: E) -> crate::Result<()>
    where
        E: Send + Sync + 'static,
    {
        self.scope(async || listener.call(Event::__new(Arc::new(event))).await)
            .await
    }
}