umbral-core 0.0.4

umbral internals: ORM, migrations, routing, DB backends, the Plugin trait. Do not depend on this directly; use the `umbral` facade.
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
//! Integration coverage for `#[derive(Form)]`. The macro emits an
//! `impl Form` against the primitives in `umbral::forms` (Field,
//! ValidationErrors, validators). Each test pins a different
//! lowering shape: per-attr validators, Option<T> -> optional,
//! type dispatch over String / i64 / f64 / bool, the email and
//! password attribute hooks, and the default render_html walk.
//!
//! Pure compile-time + sync — no DB, no async runtime needed.

#![allow(dead_code)]

use std::collections::HashMap;

// `Form` is now the axum extractor (gaps2 #19). The `validate()`
// method comes from the `FormValidate` trait the derive emits an
// impl of. Imports keep the test surface short.
use umbral::forms::{FormValidate, ValidationErrors};

fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
    pairs
        .iter()
        .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
        .collect()
}

// --------------------------------------------------------------------- //
// 1. Minimum-viable form: String field, no attributes. The derive       //
// picks Field::text and Required-by-default, so an empty input fails.   //
// --------------------------------------------------------------------- //

#[derive(Debug, umbral::forms::Form)]
struct MinimalForm {
    title: String,
}

#[tokio::test]
async fn minimal_string_form_round_trips_a_valid_input() {
    let form = MinimalForm::validate(&data(&[("title", "hello")]))
        .await
        .expect("should validate");
    assert_eq!(form.title, "hello");
}

#[tokio::test]
async fn minimal_string_form_rejects_empty_input() {
    let err = MinimalForm::validate(&data(&[("title", "")]))
        .await
        .expect_err("empty fails");
    assert!(err.fields.contains_key("title"));
    assert!(err.fields["title"][0].contains("required"));
}

// --------------------------------------------------------------------- //
// 2. The full attr set: min_length, max_length, email, password,        //
// optional. The macro lowers each to the matching Field builder method. //
// --------------------------------------------------------------------- //

#[derive(Debug, umbral::forms::Form)]
struct SignupForm {
    #[form(min_length = 3, max_length = 150)]
    username: String,

    #[form(email)]
    email: String,

    #[form(password, min_length = 8)]
    password: String,

    #[form(optional, max_length = 280)]
    bio: Option<String>,

    is_admin: bool,
}

#[tokio::test]
async fn signup_form_happy_path_returns_the_typed_struct() {
    let form = SignupForm::validate(&data(&[
        ("username", "alice"),
        ("email", "alice@example.com"),
        ("password", "hunter2-stronger"),
        ("bio", "loves rust"),
        ("is_admin", "true"),
    ]))
    .await
    .expect("happy path");
    assert_eq!(form.username, "alice");
    assert_eq!(form.email, "alice@example.com");
    assert_eq!(form.password, "hunter2-stronger");
    assert_eq!(form.bio.as_deref(), Some("loves rust"));
    assert!(form.is_admin);
}

#[tokio::test]
async fn signup_form_collects_every_field_error_at_once() {
    let err = SignupForm::validate(&data(&[
        ("username", "ab"),
        ("email", "not-an-email"),
        ("password", "short"),
        ("bio", ""),
        ("is_admin", ""),
    ]))
    .await
    .expect_err("multi-field failure");
    assert!(err.fields.contains_key("username"), "username missing");
    assert!(err.fields.contains_key("email"), "email missing");
    assert!(err.fields.contains_key("password"), "password missing");
    assert!(
        !err.fields.contains_key("bio"),
        "optional empty bio shouldn't error"
    );
    assert!(
        !err.fields.contains_key("is_admin"),
        "boolean missing-key is valid (form omits unchecked boxes)"
    );

    assert!(err.fields["username"][0].contains("at least 3"));
    assert!(
        err.fields["email"][0].contains("@") || err.fields["email"][0].contains("`@`"),
        "email diagnostic should mention @ symbol: {:?}",
        err.fields["email"]
    );
    assert!(err.fields["password"][0].contains("at least 8"));
}

#[tokio::test]
async fn signup_form_optional_bio_handles_both_some_and_none() {
    let with_bio = SignupForm::validate(&data(&[
        ("username", "alice"),
        ("email", "alice@example.com"),
        ("password", "hunter2-stronger"),
        ("bio", "wrote a book"),
        ("is_admin", "false"),
    ]))
    .await
    .expect("with bio");
    assert_eq!(with_bio.bio.as_deref(), Some("wrote a book"));

    let without_bio = SignupForm::validate(&data(&[
        ("username", "bob"),
        ("email", "bob@example.com"),
        ("password", "hunter2-stronger"),
    ]))
    .await
    .expect("without bio");
    assert_eq!(without_bio.bio, None);
}

#[tokio::test]
async fn signup_form_checkbox_is_false_when_key_is_absent() {
    let form = SignupForm::validate(&data(&[
        ("username", "alice"),
        ("email", "alice@example.com"),
        ("password", "hunter2-stronger"),
    ]))
    .await
    .expect("happy path with no is_admin");
    assert!(
        !form.is_admin,
        "an unchecked HTML checkbox sends no key; the form should default to false"
    );
}

// --------------------------------------------------------------------- //
// 3. Numeric types. The derive dispatches i64 -> Field::integer and     //
// emits parse::<i64>() for the value path. Validation fails when the    //
// input doesn't parse, and the error message names the field.          //
// --------------------------------------------------------------------- //

#[derive(Debug, umbral::forms::Form)]
struct ProductForm {
    name: String,

    price_cents: i64,

    weight_kg: f64,

    #[form(optional)]
    stock_count: Option<i64>,
}

#[tokio::test]
async fn numeric_form_parses_integers_and_floats() {
    let form = ProductForm::validate(&data(&[
        ("name", "widget"),
        ("price_cents", "1299"),
        ("weight_kg", "0.42"),
        ("stock_count", "100"),
    ]))
    .await
    .expect("happy");
    assert_eq!(form.price_cents, 1299);
    assert!((form.weight_kg - 0.42).abs() < 1e-9);
    assert_eq!(form.stock_count, Some(100));
}

#[tokio::test]
async fn numeric_form_rejects_non_numeric_input() {
    let err = ProductForm::validate(&data(&[
        ("name", "widget"),
        ("price_cents", "free"),
        ("weight_kg", "light"),
        ("stock_count", ""),
    ]))
    .await
    .expect_err("two parse failures");
    assert!(
        err.fields["price_cents"][0].contains("whole number"),
        "integer parse error: {:?}",
        err.fields["price_cents"]
    );
    assert!(
        err.fields["weight_kg"][0].contains("number"),
        "float parse error: {:?}",
        err.fields["weight_kg"]
    );
    assert_eq!(form_field_count(&err), 2);
}

#[tokio::test]
async fn numeric_form_optional_int_with_empty_input_is_none() {
    let form = ProductForm::validate(&data(&[
        ("name", "widget"),
        ("price_cents", "100"),
        ("weight_kg", "1.0"),
    ]))
    .await
    .expect("happy without stock");
    assert_eq!(form.stock_count, None);
}

// --------------------------------------------------------------------- //
// 4. fields() + render_html(). The macro emits a fields() that returns //
// one Field per struct field; the trait's default render_html walks it. //
// --------------------------------------------------------------------- //

#[test]
fn fields_returns_one_entry_per_struct_field_in_order() {
    let fields = SignupForm::fields();
    let names: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(
        names,
        vec!["username", "email", "password", "bio", "is_admin"]
    );
}

#[tokio::test]
async fn render_html_emits_one_input_per_field_with_correct_types() {
    let prefill = data(&[("username", "alice")]);
    let html = SignupForm::render_html(&prefill).await;

    assert!(html.contains("name=\"username\""), "username field missing");
    assert!(html.contains("name=\"email\""), "email field missing");
    assert!(html.contains("name=\"password\""), "password field missing");
    assert!(html.contains("name=\"bio\""), "bio field missing");
    assert!(html.contains("name=\"is_admin\""), "is_admin field missing");

    // Per-attr input type dispatch.
    assert!(
        html.contains("type=\"email\""),
        "email should render type=email"
    );
    assert!(
        html.contains("type=\"password\""),
        "password should render type=password"
    );
    assert!(
        html.contains("type=\"checkbox\""),
        "boolean should render type=checkbox"
    );

    // Prefill round-trips.
    assert!(html.contains("value=\"alice\""), "prefill missing: {html}");
}

#[tokio::test]
async fn render_html_escapes_xss_in_prefill_values() {
    // MinimalForm's field is `title`, so the prefill key has to
    // match. An XSS payload in the prefill value must round-trip
    // through `html_escape` and emerge as `&lt;script&gt;`.
    let prefill = data(&[("title", "<script>alert(1)</script>")]);
    let html = MinimalForm::render_html(&prefill).await;
    assert!(!html.contains("<script>alert"), "raw XSS leaked: {html}");
    assert!(html.contains("&lt;script&gt;"), "escape missing: {html}");
}

fn form_field_count(err: &ValidationErrors) -> usize {
    err.fields.len()
}

// --------------------------------------------------------------------- //
// Task 1 — FormValidate is async. The minimal form must be awaitable.   //
// --------------------------------------------------------------------- //

#[tokio::test]
async fn async_validate_minimal_form_round_trips() {
    let form = MinimalForm::validate(&data(&[("title", "hello")]))
        .await
        .expect("should validate");
    assert_eq!(form.title, "hello");
}

// --------------------------------------------------------------------- //
// Task 2 — reverse relations are back-pointers; the Form derive skips   //
// them WITHOUT requiring #[umbral(noform)] and they're absent from       //
// fields().                                                             //
// --------------------------------------------------------------------- //

#[derive(Debug, Clone, sqlx::FromRow, serde::Serialize, serde::Deserialize, umbral::orm::Model)]
#[umbral(table = "fd_skip_child")]
struct SkipChild {
    pub id: i64,
    pub title: String,
    pub parent: umbral::orm::ForeignKey<SkipParent>,
}

#[derive(
    Debug,
    Clone,
    Default,
    sqlx::FromRow,
    serde::Serialize,
    serde::Deserialize,
    umbral::orm::Model,
    umbral::forms::Form,
)]
#[umbral(table = "fd_skip_parent")]
struct SkipParent {
    pub id: i64,
    pub name: String,
    // Reverse FK collection — NO #[umbral(noform)].
    #[sqlx(skip)]
    #[serde(skip)]
    #[umbral(reverse_fk = "parent")]
    pub child_set: umbral::orm::ReverseSet<SkipChild>,
    // Reverse OneToOne back-pointer — NO #[umbral(noform)].
    #[sqlx(skip)]
    #[serde(skip)]
    pub profile: umbral::orm::OneToOne<SkipChild>,
}

#[test]
fn reverse_relations_absent_from_fields() {
    let names: Vec<String> = SkipParent::fields().into_iter().map(|f| f.name).collect();
    assert!(names.contains(&"name".to_string()), "scalar field present");
    assert!(
        !names.contains(&"child_set".to_string()),
        "ReverseSet skipped"
    );
    assert!(
        !names.contains(&"profile".to_string()),
        "reverse OneToOne skipped"
    );
}

// --------------------------------------------------------------------- //
// Task 3 — #[umbral(choices)] enum fields become a Select. Membership    //
// checked at validate time (no DB); out-of-set is a field error.        //
// --------------------------------------------------------------------- //

#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Default,
    umbral::orm::Choices,
    serde::Serialize,
    serde::Deserialize,
)]
#[choices(rename_all = "lowercase")]
enum Mood {
    #[default]
    Happy,
    Sad,
    Neutral,
}

#[derive(
    Debug,
    Default,
    sqlx::FromRow,
    serde::Serialize,
    serde::Deserialize,
    umbral::orm::Model,
    umbral::forms::Form,
)]
#[umbral(table = "fd_choice_form")]
struct ChoiceForm {
    pub id: i64,
    pub body: String,
    #[umbral(choices)]
    pub mood: Mood,
}

#[tokio::test]
async fn choices_field_round_trips_every_variant() {
    for (raw, expected) in [
        ("happy", Mood::Happy),
        ("sad", Mood::Sad),
        ("neutral", Mood::Neutral),
    ] {
        let form = ChoiceForm::validate(&data(&[("body", "x"), ("mood", raw)]))
            .await
            .expect("valid variant");
        assert_eq!(form.mood, expected, "decoded back as the enum");
    }
}

#[tokio::test]
async fn choices_field_rejects_out_of_set_value() {
    let err = ChoiceForm::validate(&data(&[("body", "x"), ("mood", "ecstatic")]))
        .await
        .expect_err("out-of-set rejected");
    assert!(err.fields.contains_key("mood"), "error keyed to the field");
}

#[test]
fn choices_field_renders_a_select_with_all_options() {
    let names: Vec<String> = ChoiceForm::fields().into_iter().map(|f| f.name).collect();
    assert!(names.contains(&"mood".to_string()));
}