# Testing

- [Introduction](#introduction)
- [Testing endpoints](#testing-endpoints)
- [Testing authorization](#testing-authorization)
- [Testing MCP tools](#testing-mcp-tools)
- [Comparing with a PHP app](#comparing-with-a-php-app)
- [Testing on SQLite](#testing-on-sqlite)
- [What to test](#what-to-test)

## Introduction

Restify's endpoints are ordinary routes, so you test them with the framework's HTTP tests, described in its `testing.md` guide. These examples use the `Post` repository from the other guides, behind an API token. The example app runs each one, in [`tests/guide_examples.rs`](https://github.com/BinarCode/laravel-restify-rust/blob/main/example/tests/guide_examples.rs).

## Testing endpoints

Send requests as a user with `acting_as`, and assert on the JSON:

```rust
use app::models::User;
use laravel::testing::prelude::*;

#[laravel::test]
async fn a_post_is_stored_for_the_logged_in_user(app: Application) -> laravel::Result<()> {
    let taylor = User::factory().create().await?;

    app.post("/api/restify/posts")
        .acting_as(&taylor)
        .json(json!({ "title": "Hello", "votes": 3 }))
        .await
        .assert_status(201)
        .assert_json(json!({
            "data": { "type": "posts", "attributes": { "title": "Hello", "votes": 3, "user_id": taylor.id } },
        }));

    app.assert_database_has("posts", json!({ "title": "Hello", "user_id": taylor.id }))
        .await;

    Ok(())
}
```

`assert_json` matches part of the response, so name only the fields the test is about. An `id` in a response is a string: compare it with `post.id.to_string()`.

To test a list, assert the order and the count:

```rust
app.get("/api/restify/posts?sort=-votes&featured=true")
    .acting_as(&taylor)
    .await
    .assert_ok()
    .assert_json_count_at("data", 1)
    .assert_json(json!({ "data": [{ "id": post.id.to_string() }] }));
```

## Testing authorization

Test each rule from both sides: the user who may, and the user who may not.

```rust
app.get("/api/restify/posts").await.assert_unauthorized();
app.get("/api/restify/posts").token("wrong-token").await.assert_unauthorized();

app.patch(format!("/api/restify/posts/{}", post.id))
    .acting_as(&another_user)
    .json(json!({ "votes": 1 }))
    .await
    .assert_forbidden();

app.assert_database_has("posts", json!({ "id": post.id, "votes": 10 })).await;
```

Also assert that a client can't write a column the input doesn't declare:

```rust
app.post("/api/restify/posts")
    .acting_as(&taylor)
    .json(json!({ "title": "Hello", "user_id": another_user.id }))
    .await
    .assert_json_path("data.attributes.user_id", taylor.id);
```

## Testing MCP tools

A tool call is a `POST` to the MCP server with a JSON-RPC message.

The test must send `Accept: application/json, text/event-stream`, as every MCP client does, or the server answers `406`. `.json(..)` sets `Accept` to `application/json` only, so set the header after it. A small helper keeps that in one place.

The server starts in `wrapper` mode, which lists five tools: `global-search` and the four wrapper tools. To call one tool per operation, such as `posts-store-tool`, make the test's app in `direct` mode:

```rust
use app::models::User;
use laravel::testing::TestRequest;
use laravel::testing::prelude::*;
use restify::{McpMode, RestifyConfig};
use serde_json::Value;

pub trait Mcp {
    fn message(self, message: Value) -> TestRequest;
}

impl Mcp for TestRequest {
    fn message(self, message: Value) -> TestRequest {
        self.json(message)
            .header("accept", "application/json, text/event-stream")
    }
}

/// The app with its MCP server in `direct` mode.
pub fn direct_mcp() -> Application {
    app::testing::configure()
        .with_config(|config, _| {
            config.section_mut::<RestifyConfig>().mcp_mode = McpMode::Direct;
        })
        .create()
}

fn call(tool: &str, arguments: Value) -> Value {
    json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": arguments } })
}

#[laravel::test(app = direct_mcp)]
async fn an_agent_creates_a_post(app: Application) -> laravel::Result<()> {
    let taylor = User::factory().create().await?;

    app.post("/mcp/restify")
        .acting_as(&taylor)
        .message(call("posts-store-tool", json!({ "title": "From an agent" })))
        .await
        .assert_ok()
        .assert_json(json!({ "result": { "isError": false, "structuredContent": { "data": {
            "attributes": { "title": "From an agent" },
        } } } }));

    Ok(())
}
```

A refused or invalid call still answers `200`. Assert on `result.isError` and on the text of the result:

```rust
app.post("/mcp/restify")
    .acting_as(&taylor)
    .message(call("posts-store-tool", json!({ "title": "" })))
    .await
    .assert_json_path("result.isError", true)
    .assert_json_path("result.content.0.text", "A post needs a title.");
```

## Comparing with a PHP app

If you are moving an app from Restify for PHP, you can check that the Rust app answers the same requests in the same way. A *cassette* is a JSON file that holds requests and what the PHP app answered to them. `restify::testing::replay` sends those requests to your Rust app and fails the test when any answer is different.

Turn the module on in `Cargo.toml`:

```toml
[dev-dependencies]
laravel-restify = { version = "0.2", features = ["testing"] }
```

Then, in a test, load the rows the recording started from, read the cassette, and replay it:

```rust
use laravel::testing::prelude::*;
use restify::testing::{Cassette, replay, seed};

#[laravel::test]
async fn posts_answer_like_php(app: Application) -> laravel::Result<()> {
    seed(include_str!("../restify-oracle/seeds/blog.json")).await?;
    let cassette = Cassette::from_json(include_str!("../restify-oracle/cassettes/errors.json"))?;

    replay(&app, &cassette, &[]).await;

    Ok(())
}
```

- The paths start from the test file, in `tests/`. `restify:record` writes the cassettes to `restify-oracle/cassettes`.
- `seed` inserts the rows inside the test's transaction, so they are gone after the test. It reads JSON you write, a list of rows per table, as in the repository's [`oracle/seeds/blog.json`](https://github.com/BinarCode/laravel-restify-rust/blob/main/oracle/seeds/blog.json).
- `replay` freezes the clock at the time the cassette was recorded.
- The third argument lists differences you accept on purpose, such as an error message that names a PHP class. Build one with `Divergence::new(scenario, step, pointer, reason)`.

The module has a few more helpers for recordings of a real application:

| Item | Does |
| --- | --- |
| `sanctum_tokens::<User>(&cassette)` | Makes a Sanctum token for each user the cassette's `{{token:..}}` placeholders name (also needs the `sanctum` feature) |
| `cassette.with_tokens(&tokens)` | Puts those tokens in place of the placeholders |
| `cassette.with_files(folder)` | Says where the files are that the cassette's steps upload |
| `replay_mcp(&app, &cassette, recorded_at, served_at, &divergences)` | Replays the steps a PHP MCP server answered against this application's MCP server (also needs the `mcp` feature) |

The test file that `restify:import` writes uses each one its recordings need: see [Migrating from Restify for PHP](migrating-from-php.md#import).

A failing test prints one line per difference, such as `/body/data/0/attributes/title: PHP "A", Rust "B"`, followed by both full answers. The exact comparison rules and the cassette format are in `oracle/README.md` of the [Restify for Rust repository](https://github.com/BinarCode/laravel-restify-rust), where this crate's own copy of the check lives (`example/tests/oracle_*.rs`).

## Testing on SQLite

With `refresh_database()`, each test borrows a copy of the database, a numbered file such as `storage/testing_1.sqlite`, and gives it back when it ends. In `laravel-rust` 0.1.6 and 0.2.0, a test gives its file back a moment before its connection to the file has closed. If the next test takes that file in that moment, it fails before its first line runs, at random and rarely, most often on a busy CI machine:

```text
the application failed to boot: booting `laravel::db::provider::DatabaseServiceProvider` failed: the SQLite database is locked by another connection's write, and the busy timeout passed. [..] (Connection: sqlite, Driver: SQLite, SQL: DELETE FROM refreshed_database WHERE fingerprint = ?)
```

Raising `busy_timeout` doesn't help: SQLite reports this kind of lock at once, without waiting. What helps is to make each new connection ask for the write lock first, with `BEGIN IMMEDIATE`. SQLite does wait for that request, until the previous test's connection has closed.

In a new application, the tests use the database that `.env` names, PostgreSQL by default, or the one in `.env.testing` when that file exists: `for_testing` then reads it instead of `.env`. So without either change below, the tests run on the application's own database. To run them on a SQLite file of their own, with the fix, add three lines to the starter's `src/testing.rs`, and the function `wait_for_the_previous_test` from the example app's file below:

```rust
pub fn configure() -> ApplicationBuilder {
    crate::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_envs([
            ("APP_ENV", "testing"),
            // .. the starter's other settings
        ])
        .with_env("DB_CONNECTION", "sqlite")
        .with_env("DATABASE_URL", "sqlite://storage/testing.sqlite?mode=rwc")
        .with_config(|config, _| wait_for_the_previous_test(config))
        .refresh_database()
}
```

The application needs the `database-sqlite` feature in its `laravel-rust` line for that. The example app's whole `src/testing.rs` does the same, but lets `TEST_DATABASE_URL` pick another database, such as PostgreSQL on CI, and adds the statement only on SQLite, where it belongs:

```rust
use laravel::Application;
use laravel::foundation::ApplicationBuilder;

pub fn create() -> Application {
    configure().create()
}

/// Tests run on SQLite unless `TEST_DATABASE_URL` names another database, such as PostgreSQL.
pub fn configure() -> ApplicationBuilder {
    configure_with(crate::restify())
}

/// [`configure`] with `restify` as the Restify provider, for a test with a repository of its own.
pub fn configure_with(restify: restify::Restify) -> ApplicationBuilder {
    let database =
        std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| "sqlite://storage/testing.sqlite?mode=rwc".to_owned());
    let connection = database.split(':').next().unwrap_or("sqlite").to_owned();

    let sqlite = connection == "sqlite";

    crate::configure_with(restify)
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_envs([("APP_ENV", "testing"), ("APP_DEBUG", "true")])
        .with_env("DB_CONNECTION", connection)
        .with_env("DATABASE_URL", database)
        .with_config(move |config, _| {
            if sqlite {
                wait_for_the_previous_test(config);
            }
        })
        .refresh_database()
}

/// Make each new SQLite connection wait until the test that used the database file before it
/// has really closed its connection.
///
/// Each test borrows a database file, a "slot", and writes in a transaction that never commits.
/// When a test ends, the framework (`laravel-rust` 0.1.6 and 0.2.0) gives the slot back before that
/// connection has closed: SQLx closes it on a thread of its own a moment later. If the next test
/// takes the slot in that moment, its boot reads the slot and then deletes a row from it. SQLite
/// can't make a connection that has already read wait for another connection's write lock, so the
/// delete fails at once with "database is locked", whatever the busy timeout. It happened on CI, on
/// a busy machine.
///
/// `BEGIN IMMEDIATE` asks for the write lock before the connection reads anything, and SQLite
/// waits for that one through the busy timeout (5 seconds by default), until the old connection
/// closes and rolls back. The empty transaction then commits, so the test's own transaction
/// begins as usual. Remove this when the framework closes a slot's connections before giving it
/// back.
fn wait_for_the_previous_test(config: &mut laravel::config::Config) {
    let database = config.section_mut::<laravel::config::database::Database>();
    let name = database.default.clone();
    if let Some(connection) = database.connections.get_mut(&name) {
        connection
            .init_sql
            .push(laravel::db::sqlx::SqlStr::from_static("BEGIN IMMEDIATE; COMMIT"));
    }
}
```

The statement only waits; it changes nothing in the database. You can remove it once the framework closes a test's connection before it gives the file back.

## What to test

A tool and its endpoint run the same code, so you don't need every test twice. A good set for a repository:

- One test per endpoint for the usual case.
- One test per rule in `authorize` and in the policy, from both sides.
- One test that a column the client must not write stays unwritten.
- One test of the tool list, when the input's descriptions matter to you.
- One MCP test of a create, to prove the server is wired up.
