ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

RecipesServe static filesCompress responsesSecurity headers and CSRFSessions with tower-sessionsCookies with tower-cookiesRequest IDsAccess logError reporting with SentryLocalised responses with FluentA client as a providerA MongoDB ODM over the injected clientExplicit transactions with SQLxA mailer over lettreObject storage over the AWS SDKA CLI command with clapMocks with mockallFeature flags with OpenFeatureAuthorization with CedarMoving from axum or actix-web

Operating

Reference

Recipes

Mocks with mockall

Register a mockall mock in place of a trait binding with TestApp::override_value and have its expectations checked when the app closes.

A handler that depends on Dep<dyn Mailer> should be tested without sending mail, and a test often needs to assert how the dependency was called. mockall generates the mock and its expectations, and TestApp::override_value::<dyn Mailer> binds it where the real implementation was bound.

This recipe builds on examples/13-testing. It compiled and ran against mockall 0.15.0 with ulo 0.1.0-alpha.3.

[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
ulo-http-hyper = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
ulo-transport = "=0.1.0-alpha.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

[dev-dependencies]
mockall = "0.15"

The code under test

use ulo::{App, AppBuilder, Dep, controller, handlers, injectable, module};

pub trait Mailer: Send + Sync {
    fn send(&self, to: &str) -> String;
}

#[injectable]
pub struct SmtpMailer;

impl Mailer for SmtpMailer {
    fn send(&self, to: &str) -> String {
        format!("smtp to {to}")
    }
}

#[controller]
pub struct SignupController {
    mailer: Dep<dyn Mailer>,
}

#[handlers]
impl SignupController {
    #[ulo_http::get("/signup")]
    fn signup(&self) -> String {
        self.mailer.send("ada")
    }
}

#[module(providers = [SmtpMailer as dyn Mailer], controllers = [SignupController])]
pub struct AppModule;

pub fn builder() -> AppBuilder {
    App::builder(AppModule)
}

The trait carries no mockall attribute. An integration test under tests/ compiles the library without cfg(test), so an automock guarded by cfg_attr(test, ..) is absent from it, and an unguarded one puts mockall in the library's dependencies. mock! in the test file generates the mock where it is used.

The tests

The test file starts the app on port 0 through the example support crate in the repository (ex_support::listen and get): any HTTP client does the same.

use std::sync::Arc;

use ex_support::{get, listen};
use r3::mocks::{AppModule, Mailer};
use ulo::{StartupError, TestApp, WiringError};
use ulo_runtime_tokio::Tokio;

mockall::mock! {
    pub FakeMailer {}

    impl Mailer for FakeMailer {
        fn send(&self, to: &str) -> String;
    }
}

#[tokio::test]
async fn the_mock_answers_and_its_expectation_holds() {
    let mut mailer = MockFakeMailer::new();
    mailer.expect_send().withf(|to| to == "ada").times(1).returning(|to| format!("mock to {to}"));
    let app = TestApp::of(AppModule)
        .runtime(Tokio::current())
        .override_value::<dyn Mailer>(Arc::new(mailer))
        .connect()
        .await
        .unwrap();
    let server = listen(app).await;
    assert_eq!(get(server.addr, "/signup").await.body, "mock to ada");
    server.stop().await.unwrap();
}

#[tokio::test]
async fn an_override_of_a_type_nothing_binds_fails_wiring() {
    let Err(StartupError::Wiring(errors)) = TestApp::of(AppModule)
        .runtime(Tokio::current())
        .override_value::<MockFakeMailer>(Arc::new(MockFakeMailer::new()))
        .wire()
    else {
        panic!("a stale override should fail wiring");
    };
    assert!(matches!(errors.iter().next(), Some(WiringError::OverrideUnmatched { .. })));
    assert!(errors.to_string().contains("override of `MockFakeMailer` matches no binding"), "{errors}");
}

#[tokio::test]
#[should_panic(expected = "called 0 time(s) which is fewer than expected 1")]
async fn an_unmet_expectation_panics_once_the_app_has_dropped_the_mock() {
    let mut mailer = MockFakeMailer::new();
    mailer.expect_send().times(1).returning(|to| format!("mock to {to}"));
    let app = TestApp::of(AppModule)
        .runtime(Tokio::current())
        .override_value::<dyn Mailer>(Arc::new(mailer))
        .connect()
        .await
        .unwrap();
    app.close(ulo::Signal::new("test")).await.unwrap();
}

What each seam does

  • mock! writes MockFakeMailer with an expect_send() method for send. The struct is named FakeMailer inside the macro because Mailer is the trait's name.
  • override_value::<dyn Mailer>(Arc::new(mailer)) replaces the binding of dyn Mailer. The key is the trait object, the same key SmtpMailer as dyn Mailer registered, so Dep<dyn Mailer> in SignupController receives the mock.
  • withf and times(1) set what the mock accepts and how often. returning supplies the answer.
  • connect() on the TestApp gives an App<Connected>, and listen binds it to an HTTP server on port 0.

Failure modes

  • An override whose key nothing binds fails wire() with WiringError::OverrideUnmatched. Overriding MockFakeMailer as a concrete type is the common slip, since the binding is dyn Mailer. The message reads: override of MockFakeMailer matches no binding.
  • Expectations are checked when the mock drops, and the container holds the only Arc. The third test closes the app and the times(1) that no call satisfied panics with "called 0 time(s) which is fewer than expected 1". A test that never closes or drops the app never checks its expectations, so end each such test with server.stop() or app.close(..).
  • Two modules binding the same key make an unscoped override ambiguous. Scope it with .in_module::<M>(); the testing page lists the forms.

Reference

  • TestApp: override_value, override_factory, module scoping and replacement.
  • Providers: binding a type as a trait.
  • Traits and qualifiers: dyn bindings and what keys them.

A CLI command with clap

Run a one-shot command with the application's providers and no server: clap parses, App::execute runs.

Feature flags with OpenFeature

Install an OpenFeature provider at startup, inject a flag client, and hide a route behind a flag with a guard that reads the flag name from #[meta].

On this page

The code under testThe testsWhat each seam doesFailure modesReference