Testing
Three layers of tests, each responsible for one thing:
| Test | Where | Proves |
|---|---|---|
| PHP parity | crates/cg-component/tests/php_parity.rs | Rust components output the same HTML as the PHP snapshots |
| Template functions | crates/cg-component/tests/templates.rs | cg_* functions match the builders' output; escaping; error messages |
| Runtime protocol | tests/runtime.rs | Endpoints, tokens, Linker state and rev match what the PHP JS expects |
Plus unit tests inside the crate (#[cfg(test)] in runtime/mod.rs and linker/mod.rs). Run them all together:
cargo test --workspaceFor the tests that need a database (tests/), in-memory SQLite is the easiest choice in CI:
DB_CONNECTION=sqlite DATABASE_URL='sqlite::memory:' cargo test --workspacePHP parity
#[test]
fn an_icon_button_matches_the_php_fields_snapshot() {
let rust = Button::new("儲存設定").icon("check").render();
assert_same_structure(&php_component("fields", "button", "儲存設定"), rust.as_str());
}php_component(page, component, label): finds, intests/fixtures/php/<page>.html, the element withdata-component="<component>"whose text containslabel(the snapshots are in Chinese, so labels are too).assert_same_structure: parses both sides withscraperand compares the element trees, ignoring indentation whitespace and attribute order; tags, attribute names and values, class strings and text must all match.the_comparison_catches_differences: makes sure the comparison really catches differences (a missing class, say). Don't delete it.the_fixtures_are_the_snapshots_the_manifest_describes: the fixtures match the sha256 inmanifest.json, so nobody edits a snapshot by hand.
The fixtures are copied by the sync script from PHP's tests/Snapshots/ComponentShowcase; don't edit them by hand. PHP's HTML changes → sync again → the parity tests fail → fix the Rust builder.
Currently covered: Badge (combinations on overview, the default on catalog) and Button (the icon button on fields, the state button and icon-only button on interactions). Icon is covered indirectly through Badge and Button.
Template functions
use laravel::view::minijinja::Environment;
fn render(template: &str) -> String {
let mut environment = Environment::new();
environment.set_auto_escape_callback(|_| laravel::view::minijinja::AutoEscape::Html);
cg_component::jinja::add_functions(&mut environment);
environment.render_str(template, ()).expect("template renders")
}
#[test]
fn template_labels_are_escaped_unless_marked_safe() {
assert!(render(r#"{{ cg_badge("<b>x</b>") }}"#).contains("<b>x</b>"));
}When you add a template function, test at least: the same output as the builder, an error on unknown parameters, and the message for an invalid option value.
Runtime protocol
tests/runtime.rs hits the real routes with Laravel for Rust's test tools:
use app::models::User;
use cg_component::runtime::endpoints;
use laravel::model::create;
use laravel::testing::prelude::*;
#[laravel::test]
async fn a_stateful_linker_keeps_its_state_and_revision(app: Application) -> laravel::Result<()> {
let user = create!(User { name: "Taylor", email: "taylor@laravel.com", password: "password" }).await?;
let page = app.get("/runtime").acting_as(&user).await;
let instance = attribute(&page.text(), r#"data-linker="counter""#, "data-linker-instance");
app.post(endpoints::linker_url())
.acting_as(&user)
.json(json!({ "component": "counter", "instance": instance, "rev": 0, "method": "increment", "args": {} }))
.await
.assert_ok()
.assert_json(json!({ "ok": true, "data": { "count": 1 }, "instance": instance, "rev": 1 }));
Ok(())
}#[laravel::test]gives you a testApplication(with a database that has run the migrations), so you cancreate!data directly.attribute(html, marker, name)is a small helper in the file: it finds the first tag containingmarkerand returns the value ofname="…". That's how you get the instance uuid from the page.endpoints::linker_url(),render_url()andrender_token_url()give you the right prefixed paths.- The render endpoint needs a token: put one in the session with
.with_session(json!({ "cg_render_before": ["first"] })), then send"key": "first".
Covered: meta tags, one-time tokens and their replacement, request validation, the token endpoint, 404 for other prefixes, Stateful state and rev (including conflict, validation failures not advancing rev, unexposed methods), other users' instances returning expired, logged-out calls and field formats, Stateless signed URL renewal.
Testing your own Linker components
Write an integration test for each component, modeled on tests/runtime.rs. Cover at least three paths:
#[laravel::test]
async fn customer_list(app: Application) -> laravel::Result<()> {
let owner = user("a@x.test").await?;
let other = user("b@x.test").await?;
let mine = create!(Customer { user_id: owner.id, name: "Acme <b>", email: "a@acme.test" }).await?;
let theirs = create!(Customer { user_id: other.id, name: "Other", email: "o@x.test" }).await?;
let page = app.get("/customers").acting_as(&owner).await;
page.assert_ok()
.assert_see_html(r#"data-linker-ref-seed="customers">[{"id":"#)
.assert_dont_see_html("Acme <b>"); // the seed is escaped
let instance = attribute(&page.text(), r#"data-linker="customerList""#, "data-linker-instance");
let call = |rev: u64, method: &str, args: serde_json::Value| {
json!({ "component": "customerList", "instance": instance, "rev": rev, "method": method, "args": args })
};
// success
app.post(endpoints::linker_url()).acting_as(&owner).json(call(0, "search", json!({ "keyword": "acme" }))).await
.assert_json(json!({ "ok": true, "data": { "matchCount": 1 }, "rev": 1 }));
// no permission: someone else's data
app.post(endpoints::linker_url()).acting_as(&owner).json(call(1, "delete", json!({ "id": theirs.id }))).await
.assert_json(json!({ "ok": false, "kind": "policy" }));
// validation failure doesn't advance rev
app.post(endpoints::linker_url()).acting_as(&owner).json(call(1, "delete", json!({}))).await
.assert_json(json!({ "ok": false, "kind": "validation", "rev": 1 }));
let _ = mine;
Ok(())
}This is taken from the test used to verify the searchable list tutorial. assert_json compares only the fields you give (a partial match), so you don't have to write out the whole response.
Testing flow guards
For flows like wizards, test at least that skipping steps is blocked:
post(call(0, "submit", json!({}))).await.assert_json(json!({ "ok": false, "kind": "policy" }));Testing the pipeline
.assert_json(json!({
"pipeline": [{ "fn": "ui.toast", "args": { "level": "info", "message": "已歸零" }, "on": "then" }],
}));Testing fragments
Fragment functions are ordinary async functions you can call directly:
#[laravel::test]
async fn the_orders_fragment_ignores_unknown_modes(_app: Application) -> laravel::Result<()> {
let mut params = std::collections::BTreeMap::new();
params.insert("mode".to_owned(), "<script>".to_owned());
let input = RenderInput { method: RenderMethod::Components, params, target: None, url: None };
let html = orders::render(input).await?;
assert!(!html.as_str().contains("<script>"));
Ok(())
}The browser side
The JS is the PHP project's own files, and its tests live in the PHP project (Vitest). This repo is only responsible for "the server returns the same shapes as PHP", which the protocol tests above guarantee. To check by hand, open the /runtime example page and watch the linker and render requests in DevTools' Network tab.