fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! Test helpers, as the PHP package's `InteractsWithApi`, `ApiTestResponse` and
//! `TransformsVersionChanges`: request headers for versions, keys and idempotency, assertions
//! for JSON:API documents, errors, replays, deprecation and shapes, and helpers that run one
//! version change on its own.
//!
//! ```no_run
//! use fusion_stack::testing::{ApiRequest, ApiResponse};
//! use laravel::testing::prelude::*;
//! # fn create() -> Application { Application::configure().create() }
//!
//! #[laravel::test(app = create)]
//! async fn old_clients_see_the_old_name(app: Application) {
//!     app.get("/v1/customers/1")
//!         .api_version("2026-06-01")
//!         .await
//!         .assert_json_api_resource(Some("customers"), Some("1"))
//!         .assert_deprecated(Some("2027-06-01"))
//!         .assert_shape(json!({ "data": { "type": "string", "id": "string",
//!             "attributes": { "name": "string" } } }));
//! }
//! ```

use laravel::testing::{TestRequest, TestResponse};
use serde_json::{Map, Value, json};

use crate::errors::ErrorCode;
use crate::versioning::VersionChange;

const JSON_API: &str = "application/vnd.api+json";

/// Fusion Stack's request headers on a test request.
pub trait ApiRequest: Sized {
    /// Pins the request to a version with the `Api-Version` header.
    #[must_use]
    fn api_version(self, version: &str) -> Self;

    /// Authenticates with an API key, as a bearer token.
    #[must_use]
    fn api_key(self, key: &str) -> Self;

    /// Sends an `Idempotency-Key`, so a retry with the same key is replayed.
    #[must_use]
    fn idempotency_key(self, key: &str) -> Self;
}

impl ApiRequest for TestRequest {
    fn api_version(self, version: &str) -> Self {
        self.header("Api-Version", version)
    }

    fn api_key(self, key: &str) -> Self {
        self.token(key)
    }

    fn idempotency_key(self, key: &str) -> Self {
        self.header("Idempotency-Key", key)
    }
}

/// The error an [`ApiResponse::assert_api_error`] expects: a code such as `"not_found"`, which
/// checks no status, or an [`ErrorCode`], which also checks the code's own status.
pub trait ExpectedError {
    /// The code, such as `not_found`.
    fn expected_code(&self) -> String;
    /// The status the response must have, if any.
    fn expected_status(&self) -> Option<u16>;
}

impl ExpectedError for &str {
    fn expected_code(&self) -> String {
        (*self).to_owned()
    }

    fn expected_status(&self) -> Option<u16> {
        None
    }
}

impl<T: ErrorCode> ExpectedError for T {
    fn expected_code(&self) -> String {
        self.code().to_owned()
    }

    fn expected_status(&self) -> Option<u16> {
        Some(self.status())
    }
}

/// Fusion Stack's assertions on a test response. Each returns the response, so they chain.
pub trait ApiResponse {
    /// A successful JSON:API document whose `data` is one resource, of `kind` and `id` when given.
    fn assert_json_api_resource(&self, kind: Option<&str>, id: Option<&str>) -> &Self;

    /// A successful JSON:API document whose `data` is a list of resources, each of `kind` and
    /// `count` of them when given.
    fn assert_json_api_collection(&self, kind: Option<&str>, count: Option<usize>) -> &Self;

    /// A JSON:API error document with an error of `code`. An [`ErrorCode`] also checks its status.
    fn assert_api_error(&self, code: impl ExpectedError) -> &Self;

    /// The response was replayed from an earlier request with the same `Idempotency-Key`.
    fn assert_idempotent_replay(&self) -> &Self;

    /// The request ran: it was not replayed.
    fn assert_not_idempotent_replay(&self) -> &Self;

    /// The version the response was served in is deprecated, sunsetting on `sunset`
    /// (`YYYY-MM-DD`) when given.
    fn assert_deprecated(&self, sunset: Option<&str>) -> &Self;

    /// The version the response was served in is not deprecated.
    fn assert_not_deprecated(&self) -> &Self;

    /// The body's [`shape`]. Key order does not matter.
    fn assert_shape(&self, expected: Value) -> &Self;
}

fn assert_json_api(response: &TestResponse, what: &str) {
    let content_type = response.header("content-type").unwrap_or_default();
    assert!(
        content_type.starts_with(JSON_API),
        "Expected a JSON:API {what}; the Content-Type is [{content_type}]."
    );
}

fn data(response: &TestResponse) -> Value {
    response.assert_successful();
    assert_json_api(response, "document");
    let data = response.json().get("data").cloned();
    assert!(
        data.as_ref()
            .is_some_and(|data| data.is_object() || data.is_array()),
        "Expected a `data` member."
    );
    data.unwrap_or_default()
}

fn assert_resource_object(resource: &Value, kind: Option<&str>) {
    let actual = resource.get("type").and_then(Value::as_str);
    assert!(actual.is_some(), "A resource object needs a string `type`.");
    assert!(
        resource.get("id").is_some_and(Value::is_string),
        "A resource object needs a string `id`."
    );
    if let Some(kind) = kind {
        assert_eq!(actual, Some(kind), "The resource has a different type.");
    }
}

impl ApiResponse for TestResponse {
    fn assert_json_api_resource(&self, kind: Option<&str>, id: Option<&str>) -> &Self {
        let data = data(self);
        assert!(
            data.is_object(),
            "Expected `data` to be one resource, not a list."
        );
        assert_resource_object(&data, kind);
        if let Some(id) = id {
            assert_eq!(
                data.get("id").and_then(Value::as_str),
                Some(id),
                "The resource has a different id."
            );
        }
        self
    }

    fn assert_json_api_collection(&self, kind: Option<&str>, count: Option<usize>) -> &Self {
        let data = data(self);
        let Value::Array(resources) = &data else {
            panic!("Expected `data` to be a list of resources.");
        };
        for resource in resources {
            assert_resource_object(resource, kind);
        }
        if let Some(count) = count {
            assert_eq!(
                resources.len(),
                count,
                "Expected {count} resources in `data`."
            );
        }
        self
    }

    fn assert_api_error(&self, code: impl ExpectedError) -> &Self {
        let expected = code.expected_code();
        assert_json_api(self, "error document");
        let body = self.json();
        let Some(errors) = body.get("errors").and_then(Value::as_array) else {
            panic!("Expected an `errors` list.");
        };
        let codes: Vec<&str> = errors
            .iter()
            .filter_map(|error| error.get("code").and_then(Value::as_str))
            .collect();
        assert!(
            codes.contains(&expected.as_str()),
            "Expected an error [{expected}]; got [{}].",
            codes.join(", ")
        );
        if let Some(status) = code.expected_status() {
            self.assert_status(status);
        }
        self
    }

    fn assert_idempotent_replay(&self) -> &Self {
        assert_eq!(
            self.header("idempotent-replayed"),
            Some("true"),
            "Expected a replayed response (Idempotent-Replayed: true)."
        );
        self
    }

    fn assert_not_idempotent_replay(&self) -> &Self {
        assert!(
            self.header("idempotent-replayed").is_none(),
            "Expected the request to run, not be replayed."
        );
        self
    }

    fn assert_deprecated(&self, sunset: Option<&str>) -> &Self {
        assert!(
            self.headers().contains_key("deprecation"),
            "Expected a Deprecation header."
        );
        if let Some(sunset) = sunset {
            let header = self.header("sunset");
            assert!(header.is_some(), "Expected a Sunset header.");
            let header = header.unwrap_or_default();
            assert_eq!(
                http_date(header).as_deref().unwrap_or(header),
                sunset,
                "The Sunset header has a different date."
            );
        }
        self
    }

    fn assert_not_deprecated(&self) -> &Self {
        assert!(
            !self.headers().contains_key("deprecation"),
            "Expected no Deprecation header."
        );
        self
    }

    fn assert_shape(&self, expected: Value) -> &Self {
        assert_eq!(
            shape(&self.json()),
            expected,
            "The response has a different shape."
        );
        self
    }
}

/// `Mon, 01 Jun 2027 00:00:00 GMT` as `2027-06-01`.
fn http_date(header: &str) -> Option<String> {
    const MONTHS: [&str; 12] = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    let mut parts = header.split_whitespace().skip(1);
    let (day, month, year) = (parts.next()?, parts.next()?, parts.next()?);
    let month = MONTHS.iter().position(|known| *known == month)? + 1;
    Some(format!("{year}-{month:02}-{day:0>2}"))
}

/// A value's shape: its keys, with each value replaced by its JSON type (`string`, `integer`,
/// `number`, `boolean` or `null`) and each list by the shape of its first item.
#[must_use]
pub fn shape(value: &Value) -> Value {
    match value {
        Value::Array(items) => Value::Array(items.first().map(shape).into_iter().collect()),
        Value::Object(map) => Value::Object(
            map.iter()
                .map(|(key, value)| (key.clone(), shape(value)))
                .collect(),
        ),
        Value::String(_) => json!("string"),
        Value::Number(number) if number.is_f64() => json!("number"),
        Value::Number(_) => json!("integer"),
        Value::Bool(_) => json!("boolean"),
        Value::Null => json!("null"),
    }
}

/// An older client's request body, migrated to the shape after the change.
#[must_use]
pub fn upgrade_request(change: &dyn VersionChange, payload: &Value) -> Value {
    let mut map: Map<String, Value> = payload.as_object().cloned().unwrap_or_default();
    change.transform_request(&mut map);
    Value::Object(map)
}

/// A latest-shape response document, migrated back to the shape before the change.
#[must_use]
pub fn downgrade_response(change: &dyn VersionChange, document: &Value) -> Value {
    let mut document = document.clone();
    change.transform_response(&mut document);
    document
}

/// Downgrading `document` and upgrading the result gives `document` back, so old clients can
/// send what they receive. Not for changes that drop data, such as a removed attribute. Returns
/// the downgraded document, for further assertions.
///
/// # Panics
///
/// When upgrading the downgraded document does not give it back.
pub fn assert_round_trip(change: &dyn VersionChange, document: &Value) -> Value {
    let old = downgrade_response(change, document);
    assert_eq!(
        &upgrade_request(change, &old),
        document,
        "Upgrading the downgraded document does not give it back."
    );
    old
}

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

    #[test]
    fn shapes_use_the_first_item_of_each_list() {
        assert_eq!(
            shape(
                &json!({ "data": [{ "id": "1", "n": 2, "f": 1.5, "b": true, "z": null }, { "x": 1 }], "e": [] })
            ),
            json!({ "data": [{ "id": "string", "n": "integer", "f": "number", "b": "boolean", "z": "null" }], "e": [] })
        );
    }

    #[test]
    fn reads_sunset_dates() {
        assert_eq!(
            http_date("Tue, 01 Jun 2027 00:00:00 GMT").as_deref(),
            Some("2027-06-01")
        );
    }
}