ignite-core 0.7.3

Core types for Ignite, the admin panel for Rocket.rs: resources, fields, forms and runtime resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Runtime resources: owned field and column definitions, the registry, and the validation
//! of a submitted form against the definitions. No database is needed: the data source of
//! these resources is never called.
//!
//! The registry is shared by the whole test binary and the tests run in parallel, so each
//! test uses slugs of its own.

use std::collections::HashMap;

use ignite_core::{
    ActionAbility, BulkAction, Column, ColumnDef, Database, Field, FieldDef, FieldKind,
    FieldKindDef, FormInput, ListQuery, Page, Registries, Row, RuntimeData, RuntimeError,
    RuntimeFuture, RuntimeResource,
};
use serde_json::{json, Value};

/// A data source that is never called: these tests only register and validate.
struct NoData;

impl RuntimeData for NoData {
    fn list<'a>(&'a self, _: &'a Database, _: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>> {
        unreachable!()
    }
    fn find<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, Option<Row>> {
        unreachable!()
    }
    fn create<'a>(&'a self, _: &'a Database, _: Row) -> RuntimeFuture<'a, Row> {
        unreachable!()
    }
    fn update<'a>(&'a self, _: &'a Database, _: i64, _: Row) -> RuntimeFuture<'a, Row> {
        unreachable!()
    }
    fn delete<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, u64> {
        unreachable!()
    }
}

fn text(name: &str, label: &str, required: bool) -> FieldDef {
    FieldDef {
        name: name.to_string(),
        label: label.to_string(),
        kind: FieldKindDef::Text,
        required,
    }
}

fn resource(slug: &str) -> RuntimeResource {
    RuntimeResource::new(slug, "Books", "Book", NoData)
        .field(text("title", "Title", true))
        .column(ColumnDef {
            key: "title".to_string(),
            label: "Title".to_string(),
            sortable: true,
            searchable: true,
        })
}

fn form(pairs: &[(&str, &str)]) -> FormInput {
    FormInput::new(
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect::<HashMap<_, _>>(),
    )
}

#[test]
fn a_static_field_converts_to_an_owned_definition() {
    const STATUS: Field = Field {
        name: "status",
        label: "Status",
        kind: FieldKind::Select(&[("draft", "Draft"), ("live", "Live")]),
        required: true,
    };
    let def = FieldDef::from(STATUS);
    assert_eq!(def.name, "status");
    assert_eq!(def.label, "Status");
    assert!(def.required);
    assert_eq!(
        def.kind,
        FieldKindDef::Select(vec![
            ("draft".to_string(), "Draft".to_string()),
            ("live".to_string(), "Live".to_string()),
        ])
    );
    assert_eq!(
        FieldKindDef::from(FieldKind::Decimal("0.01")),
        FieldKindDef::Decimal("0.01".to_string())
    );
    for (kind, def) in [
        (FieldKind::Text, FieldKindDef::Text),
        (FieldKind::Textarea, FieldKindDef::Textarea),
        (FieldKind::Password, FieldKindDef::Password),
        (FieldKind::Number, FieldKindDef::Number),
        (FieldKind::Checkbox, FieldKindDef::Checkbox),
        (FieldKind::Lookup, FieldKindDef::Lookup),
        (FieldKind::Date, FieldKindDef::Date),
        (FieldKind::DateTime, FieldKindDef::DateTime),
    ] {
        assert_eq!(FieldKindDef::from(kind), def);
    }
}

#[test]
fn a_static_column_converts_to_an_owned_definition() {
    let column = Column {
        key: "name",
        label: "Name",
        sortable: true,
        searchable: false,
    };
    assert_eq!(
        ColumnDef::from(column),
        ColumnDef {
            key: "name".to_string(),
            label: "Name".to_string(),
            sortable: true,
            searchable: false,
        }
    );
}

#[test]
fn a_registered_resource_is_listed_until_it_is_unregistered() {
    let registries = Registries::new();
    registries
        .register_runtime(resource("rt-listed"))
        .expect("register");

    let found = registries
        .runtime_resource("rt-listed")
        .expect("registered");
    assert_eq!(found.slug(), "rt-listed");
    assert_eq!(found.title(), "Books");
    assert_eq!(found.singular(), "Book");
    assert_eq!(found.fields()[0].name, "title");
    assert_eq!(found.fields()[0].kind, FieldKindDef::Text);
    assert_eq!(found.columns()[0].key, "title");
    assert!(registries
        .runtime_resources()
        .iter()
        .any(|r| r.slug() == "rt-listed"));

    registries
        .unregister_runtime("rt-listed")
        .expect("unregister");
    assert!(registries.runtime_resource("rt-listed").is_none());
    assert!(!registries
        .runtime_resources()
        .iter()
        .any(|r| r.slug() == "rt-listed"));
}

#[test]
fn unregistering_an_unknown_slug_is_an_error() {
    let registries = Registries::new();
    let error = registries.unregister_runtime("rt-never").unwrap_err();
    assert_eq!(error, RuntimeError::NotRegistered("rt-never".to_string()));
}

#[test]
fn a_second_resource_with_the_same_slug_is_refused() {
    let registries = Registries::new();
    registries
        .register_runtime(resource("rt-twice"))
        .expect("register");

    let error = registries
        .register_runtime(resource("rt-twice"))
        .unwrap_err();
    assert_eq!(error, RuntimeError::SlugTaken("rt-twice".to_string()));
    assert_eq!(
        error.to_string(),
        "the slug `rt-twice` is already used by another Ignite resource"
    );
    registries
        .unregister_runtime("rt-twice")
        .expect("unregister");
}

#[test]
fn a_reserved_slug_is_refused_and_a_registered_slug_cannot_be_reserved() {
    let registries = Registries::new();
    registries.reserve_slugs(&["rt-static"]).expect("reserve");
    assert_eq!(
        registries
            .register_runtime(resource("rt-static"))
            .unwrap_err(),
        RuntimeError::SlugTaken("rt-static".to_string())
    );

    registries
        .register_runtime(resource("rt-first"))
        .expect("register");
    assert_eq!(
        registries.reserve_slugs(&["rt-first"]).unwrap_err(),
        RuntimeError::SlugTaken("rt-first".to_string())
    );
    registries
        .unregister_runtime("rt-first")
        .expect("unregister");
    // Reserving the same slug twice is fine: a panel may be built more than once.
    registries
        .reserve_slugs(&["rt-static"])
        .expect("reserve again");
}

#[test]
fn a_slug_that_is_not_one_url_segment_is_refused() {
    let registries = Registries::new();
    for slug in ["", "two/parts", "with space", "new?x", "Caps"] {
        assert_eq!(
            registries.register_runtime(resource(slug)).unwrap_err(),
            RuntimeError::InvalidSlug(slug.to_string()),
            "{slug:?}"
        );
    }
}

#[test]
fn two_fields_with_the_same_name_are_refused() {
    let registries = Registries::new();
    let twice = resource("rt-dup-field").field(text("title", "Again", false));
    assert_eq!(
        registries.register_runtime(twice).unwrap_err(),
        RuntimeError::DuplicateField {
            slug: "rt-dup-field".to_string(),
            field: "title".to_string(),
        }
    );
}

/// A resource with one field of each kind that validation reads, registered at `slug`.
fn every_kind(slug: &str) -> std::sync::Arc<ignite_core::RegisteredResource> {
    let registries = Registries::new();
    registries
        .register_runtime(every_kind_definition(slug))
        .expect("register");
    registries.runtime_resource(slug).expect("registered")
}

fn every_kind_definition(slug: &str) -> RuntimeResource {
    let def = |name: &str, label: &str, kind: FieldKindDef, required: bool| FieldDef {
        name: name.to_string(),
        label: label.to_string(),
        kind,
        required,
    };
    RuntimeResource::new(slug, "Events", "Event", NoData)
        .field(def("title", "Title", FieldKindDef::Text, true))
        .field(def("body", "Body", FieldKindDef::Textarea, false))
        .field(def("seats", "Seats", FieldKindDef::Number, true))
        .field(def(
            "price",
            "Price",
            FieldKindDef::Decimal("0.01".into()),
            false,
        ))
        .field(def("public", "Public", FieldKindDef::Checkbox, false))
        .field(def(
            "status",
            "Status",
            FieldKindDef::Select(vec![
                ("draft".into(), "Draft".into()),
                ("live".into(), "Live".into()),
            ]),
            true,
        ))
        .field(def("day", "Day", FieldKindDef::Date, false))
        .field(def("starts", "Starts", FieldKindDef::DateTime, false))
        .field(def("secret", "Secret", FieldKindDef::Password, true))
}

#[test]
fn a_valid_form_becomes_a_row_of_typed_values() {
    let row = every_kind("rt-kinds-valid")
        .validate(&form(&[
            ("title", "  Launch  "),
            ("seats", "40"),
            ("price", "9.50"),
            ("public", "on"),
            ("status", "live"),
            ("day", "2026-11-14"),
            ("starts", "2026-11-14T18:30"),
            ("secret", "hunter2"),
        ]))
        .expect("valid");

    assert_eq!(row["title"], json!("Launch"));
    assert_eq!(row["body"], Value::Null, "a blank optional field is null");
    assert_eq!(row["seats"], json!(40));
    assert_eq!(row["price"], json!(9.5));
    assert_eq!(row["public"], json!(true));
    assert_eq!(row["status"], json!("live"));
    assert_eq!(row["day"], json!("2026-11-14"));
    assert_eq!(row["starts"], json!("2026-11-14 18:30:00"));
    let hash = row["secret"].as_str().expect("a hash");
    assert!(ignite_core::verify_password(hash, "hunter2"));
}

#[test]
fn an_invalid_form_returns_the_messages_of_the_static_checks() {
    let errors = every_kind("rt-kinds-invalid")
        .validate(&form(&[
            ("seats", "many"),
            ("price", "cheap"),
            ("status", "archived"),
            ("day", "14/11/2026"),
            ("starts", "soon"),
        ]))
        .unwrap_err();

    let message = |name: &str| errors.get(name).map(String::as_str);
    assert_eq!(message("title"), Some("Title is required."));
    assert_eq!(message("seats"), Some("Seats must be a whole number."));
    assert_eq!(message("price"), Some("Price must be a number."));
    assert_eq!(message("status"), Some("Choose one of the options."));
    assert_eq!(message("day"), Some("Day must be a date, as YYYY-MM-DD."));
    assert_eq!(
        message("starts"),
        Some("Starts must be a date and time, as YYYY-MM-DD HH:MM.")
    );
    assert_eq!(message("secret"), Some("Secret is required."));
    assert_eq!(message("public"), None, "a checkbox is never blank");
}

#[test]
fn on_an_edit_a_field_not_sent_is_kept_and_one_sent_blank_is_null() {
    let row = every_kind("rt-kinds-absent")
        .validate_update(&form(&[
            ("title", "Launch"),
            ("seats", "40"),
            ("status", "draft"),
            ("body", ""),
            ("day", "  "),
        ]))
        .expect("valid");
    assert_eq!(row["body"], Value::Null, "sent blank: cleared");
    assert_eq!(row["day"], Value::Null, "sent as spaces: cleared");
    assert!(!row.contains_key("price"), "not sent: kept");
    assert!(!row.contains_key("starts"), "not sent: kept");
    assert_eq!(
        row["public"],
        json!(false),
        "a checkbox not sent is unticked, so false"
    );

    // On create, a field not sent is null, as before.
    let row = every_kind("rt-kinds-absent-create")
        .validate(&form(&[
            ("title", "Launch"),
            ("seats", "40"),
            ("status", "draft"),
            ("secret", "hunter2"),
        ]))
        .expect("valid");
    assert_eq!(row["price"], Value::Null);
    assert_eq!(row["starts"], Value::Null);
}

#[test]
fn a_blank_password_on_an_edit_keeps_the_stored_one() {
    let row = every_kind("rt-kinds-edit")
        .validate_update(&form(&[
            ("title", "Launch"),
            ("seats", "40"),
            ("status", "draft"),
        ]))
        .expect("valid without a password");
    assert!(!row.contains_key("secret"), "the stored password is kept");
    assert_eq!(row["public"], json!(false));
}

#[test]
fn a_field_name_that_is_not_a_lowercase_identifier_is_refused() {
    let registries = Registries::new();
    for name in [
        "Title",
        "two words",
        "1st",
        "_hidden",
        "naïve",
        "dash-ed",
        "",
    ] {
        let resource = resource("rt-bad-name").field(text(name, "Label", false));
        assert_eq!(
            registries.register_runtime(resource).unwrap_err(),
            RuntimeError::InvalidFieldName {
                slug: "rt-bad-name".to_string(),
                field: name.to_string(),
            },
            "{name:?}"
        );
    }
    let error = registries
        .register_runtime(resource("rt-bad-name").field(text("Bad", "Bad", false)))
        .unwrap_err()
        .to_string();
    assert_eq!(
        error,
        "the field `Bad` of the resource `rt-bad-name` is not valid: use lowercase letters, \
         digits and `_`, starting with a letter, at most 64 bytes"
    );
}

#[test]
fn a_field_name_may_be_64_bytes_but_not_65() {
    let registries = Registries::new();
    let long = format!("a{}", "b".repeat(63));
    assert_eq!(long.len(), 64);
    registries
        .register_runtime(resource("rt-long-name").field(text(&long, "Long", false)))
        .expect("64 bytes is accepted");
    registries
        .unregister_runtime("rt-long-name")
        .expect("unregister");

    let too_long = format!("{long}c");
    assert_eq!(
        registries
            .register_runtime(resource("rt-too-long").field(text(&too_long, "Long", false)))
            .unwrap_err(),
        RuntimeError::InvalidFieldName {
            slug: "rt-too-long".to_string(),
            field: too_long,
        }
    );
}

#[test]
fn a_registered_resource_keeps_its_bulk_actions_in_order() {
    let registries = Registries::new();
    let slug = "rt-bulk";
    assert!(resource(slug).bulk_actions.is_empty(), "none by default");
    registries
        .register_runtime(
            resource(slug)
                .bulk_action(BulkAction::make("trash").label("Move to Trash"))
                .bulk_action(
                    BulkAction::make("delete")
                        .authorize(ActionAbility::Delete)
                        .success_notification_title("Deleted :count posts."),
                ),
        )
        .expect("register");
    let registered = registries.runtime_resource(slug).expect("registered");
    registries.unregister_runtime(slug).expect("unregister");
    let actions = registered.bulk_actions();
    assert_eq!(actions.len(), 2);
    assert_eq!(actions[0].get_label(), "Move to Trash");
    assert_eq!(actions[0].ability(), ActionAbility::Update);
    assert_eq!(actions[1].ability(), ActionAbility::Delete);
    assert_eq!(
        actions[1].success_message(2).as_deref(),
        Some("Deleted 2 posts.")
    );
}