1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod autotest_generated {
5
    use super::*;
6

            
7
    // ------------------------------------------------------------------
8
    // BiometricKind::is_available  (predicate)
9
    // ------------------------------------------------------------------
10

            
11
    /// basic_true_false: one known-false (`NotAvailable`) and the three
12
    /// known-true sensor variants return the documented bool.
13
    #[test]
14
    fn is_available_known_true_false() {
15
        assert!(!BiometricKind::NotAvailable.is_available());
16
        assert!(BiometricKind::Fingerprint.is_available());
17
        assert!(BiometricKind::Face.is_available());
18
        assert!(BiometricKind::Iris.is_available());
19
    }
20

            
21
    /// edge_inputs: `Default::default()` is `NotAvailable`, so the default
22
    /// gate must report "no biometric offered" — never panics.
23
    #[test]
24
    fn is_available_default_is_unavailable() {
25
        assert_eq!(BiometricKind::default(), BiometricKind::NotAvailable);
26
        assert!(!BiometricKind::default().is_available());
27
    }
28

            
29
    /// invariant: `is_available()` is exactly "not the NotAvailable
30
    /// variant" for every variant — catches a mis-mapped `matches!`.
31
    #[test]
32
    fn is_available_iff_not_notavailable() {
33
        let all = [
34
            BiometricKind::NotAvailable,
35
            BiometricKind::Fingerprint,
36
            BiometricKind::Face,
37
            BiometricKind::Iris,
38
        ];
39
        for k in all {
40
            assert_eq!(k.is_available(), k != BiometricKind::NotAvailable);
41
        }
42
        // Exactly one variant is unavailable.
43
        let unavailable = all.iter().filter(|k| !k.is_available()).count();
44
        assert_eq!(unavailable, 1);
45
    }
46

            
47
    /// The `const fn` really is usable in a const context (compile-time
48
    /// evaluation) — a regression guard against dropping `const`.
49
    #[test]
50
    fn is_available_const_evaluable() {
51
        const NONE: BiometricKind = BiometricKind::NotAvailable;
52
        const FACE: BiometricKind = BiometricKind::Face;
53
        const NONE_AVAIL: bool = NONE.is_available();
54
        const FACE_AVAIL: bool = FACE.is_available();
55
        const _: () = assert!(!NONE_AVAIL && FACE_AVAIL);
56
    }
57

            
58
    // ------------------------------------------------------------------
59
    // BiometricResult::is_success  (predicate)
60
    // ------------------------------------------------------------------
61

            
62
    /// basic_true_false + full variant sweep: only `Authenticated` and
63
    /// `FellBackToPasscode` count as success. In particular `Failed`
64
    /// (biometric mismatch) and `Cancelled` must NOT unlock the vault.
65
    #[test]
66
    fn is_success_per_variant() {
67
        assert!(BiometricResult::Authenticated.is_success());
68
        assert!(BiometricResult::FellBackToPasscode.is_success());
69

            
70
        assert!(!BiometricResult::Failed.is_success());
71
        assert!(!BiometricResult::Cancelled.is_success());
72
        assert!(!BiometricResult::Unavailable.is_success());
73
        assert!(!BiometricResult::Error.is_success());
74
    }
75

            
76
    /// invariant: exactly two of the six variants are successes — a naive
77
    /// impl that treated `FellBackToPasscode` as failure, or `Failed` as
78
    /// success, would break this count.
79
    #[test]
80
    fn is_success_exactly_two_successes() {
81
        let all = [
82
            BiometricResult::Authenticated,
83
            BiometricResult::Failed,
84
            BiometricResult::Cancelled,
85
            BiometricResult::FellBackToPasscode,
86
            BiometricResult::Unavailable,
87
            BiometricResult::Error,
88
        ];
89
        let successes = all.iter().filter(|r| r.is_success()).count();
90
        assert_eq!(successes, 2);
91
        // Every non-success variant is deterministically false.
92
        for r in all {
93
            let expect = matches!(
94
                r,
95
                BiometricResult::Authenticated | BiometricResult::FellBackToPasscode
96
            );
97
            assert_eq!(r.is_success(), expect);
98
        }
99
    }
100

            
101
    /// The `const fn` is const-evaluable — regression guard.
102
    #[test]
103
    fn is_success_const_evaluable() {
104
        const OK: BiometricResult = BiometricResult::Authenticated;
105
        const BAD: BiometricResult = BiometricResult::Failed;
106
        const OK_S: bool = OK.is_success();
107
        const BAD_S: bool = BAD.is_success();
108
        const _: () = assert!(OK_S && !BAD_S);
109
    }
110

            
111
    // ------------------------------------------------------------------
112
    // BiometricPrompt::new  (constructor)
113
    // ------------------------------------------------------------------
114

            
115
    /// invariants_hold: `new` copies `reason` verbatim and applies the
116
    /// documented defaults (empty cancel label, no device-credential
117
    /// fallback). Uses AzString content-equality.
118
    #[test]
119
    fn new_sets_reason_and_defaults() {
120
        let reason = AzString::from("Unlock your vault");
121
        let prompt = BiometricPrompt::new(reason.clone());
122
        assert_eq!(prompt.reason, reason);
123
        assert_eq!(prompt.reason.as_str(), "Unlock your vault");
124
        assert!(prompt.cancel_label.is_empty());
125
        assert!(!prompt.allow_device_credential);
126
    }
127

            
128
    /// `new("")` must be indistinguishable from `Default::default()`.
129
    #[test]
130
    fn new_empty_equals_default() {
131
        let from_new = BiometricPrompt::new(AzString::from(""));
132
        assert_eq!(from_new, BiometricPrompt::default());
133
        assert!(from_new.reason.is_empty());
134
    }
135

            
136
    /// no_panic: a multi-megabyte ASCII reason is stored without
137
    /// truncation or panic.
138
    #[test]
139
    fn new_huge_ascii_reason_no_panic() {
140
        let big = "x".repeat(1_000_000);
141
        let prompt = BiometricPrompt::new(AzString::from(big.as_str()));
142
        assert_eq!(prompt.reason.as_str().len(), 1_000_000);
143
        assert_eq!(prompt.reason.as_str(), big.as_str());
144
        // Defaults still hold for the extreme input.
145
        assert!(prompt.cancel_label.is_empty());
146
        assert!(!prompt.allow_device_credential);
147
    }
148

            
149
    /// no_panic + unicode: emoji, combining marks, CJK and RTL text
150
    /// survive byte-for-byte through the constructor.
151
    #[test]
152
    fn new_unicode_reason_roundtrips() {
153
        let weird = "Fingerprint 🔒 verificação — 指紋 مرحبا e\u{0301}";
154
        let prompt = BiometricPrompt::new(AzString::from(weird));
155
        assert_eq!(prompt.reason.as_str(), weird);
156
        assert_eq!(prompt.reason.as_bytes(), weird.as_bytes());
157
        assert_eq!(
158
            prompt.reason.as_str().chars().count(),
159
            weird.chars().count()
160
        );
161
    }
162

            
163
    /// A multibyte reason repeated to ~1 MB: char count and byte count
164
    /// stay consistent (no UTF-8 boundary corruption).
165
    #[test]
166
    fn new_huge_multibyte_reason() {
167
        let big = "λ".repeat(500_000); // 2 bytes each
168
        let prompt = BiometricPrompt::new(AzString::from(big.as_str()));
169
        assert_eq!(prompt.reason.as_str().chars().count(), 500_000);
170
        assert_eq!(prompt.reason.as_bytes().len(), 1_000_000);
171
    }
172

            
173
    /// A reason containing embedded NUL / control bytes must NOT be
174
    /// truncated at the NUL (guards against C-string-style handling).
175
    #[test]
176
    fn new_embedded_nul_and_control_preserved() {
177
        let s = String::from("before\0mid\tline\nafter\r\u{7}end");
178
        let prompt = BiometricPrompt::new(AzString::from(s.clone()));
179
        assert_eq!(prompt.reason.as_str(), s.as_str());
180
        assert_eq!(prompt.reason.as_bytes().len(), s.len());
181
        // The NUL is retained, not used as a terminator.
182
        assert!(prompt.reason.as_bytes().contains(&0));
183
    }
184

            
185
    /// Boundary reason lengths around common allocation/size thresholds
186
    /// all round-trip their length exactly.
187
    #[test]
188
    fn new_boundary_lengths() {
189
        for len in [0usize, 1, 2, 15, 16, 17, 255, 256, 4096] {
190
            let s = "a".repeat(len);
191
            let prompt = BiometricPrompt::new(AzString::from(s.as_str()));
192
            assert_eq!(prompt.reason.as_str().len(), len, "len {len} mismatch");
193
            assert!(!prompt.allow_device_credential);
194
        }
195
    }
196

            
197
    /// `new` equals a hand-built struct with the same reason and the
198
    /// documented default fields — pins the field wiring.
199
    #[test]
200
    fn new_matches_manual_construction() {
201
        let reason = AzString::from("Confirm identity");
202
        let via_new = BiometricPrompt::new(reason.clone());
203
        let manual = BiometricPrompt {
204
            reason,
205
            cancel_label: AzString::from(""),
206
            allow_device_credential: false,
207
        };
208
        assert_eq!(via_new, manual);
209
    }
210

            
211
    /// `new` never enables the device-credential fallback, whatever the
212
    /// reason — it is documented as biometric-only.
213
    #[test]
214
    fn new_is_always_biometric_only() {
215
        let reasons = [
216
            String::new(),
217
            "ok".to_string(),
218
            "🔒".to_string(),
219
            "z".repeat(10_000),
220
        ];
221
        for reason in &reasons {
222
            let prompt = BiometricPrompt::new(AzString::from(reason.as_str()));
223
            assert!(!prompt.allow_device_credential);
224
            assert!(prompt.cancel_label.is_empty());
225
        }
226
    }
227

            
228
    /// Clone of a constructed prompt compares equal (Clone/PartialEq
229
    /// consistency with the deep AzString buffer).
230
    #[test]
231
    fn new_clone_is_equal() {
232
        let prompt = BiometricPrompt::new(AzString::from("clone me"));
233
        assert_eq!(prompt.clone(), prompt);
234
    }
235

            
236
    // ------------------------------------------------------------------
237
    // OptionBiometricResult round-trip (encode == decode)
238
    // ------------------------------------------------------------------
239

            
240
    /// `Option<BiometricResult>` <-> `OptionBiometricResult` round-trips
241
    /// losslessly for every variant and for `None`.
242
    #[test]
243
    fn option_result_roundtrips() {
244
        let cases = [
245
            None,
246
            Some(BiometricResult::Authenticated),
247
            Some(BiometricResult::Failed),
248
            Some(BiometricResult::Cancelled),
249
            Some(BiometricResult::FellBackToPasscode),
250
            Some(BiometricResult::Unavailable),
251
            Some(BiometricResult::Error),
252
        ];
253
        for original in cases {
254
            let wrapped: OptionBiometricResult = original.into();
255
            assert_eq!(wrapped.is_some(), original.is_some());
256
            assert_eq!(wrapped.is_none(), original.is_none());
257
            assert_eq!(wrapped.as_option(), original.as_ref());
258
            let back: Option<BiometricResult> = wrapped.into();
259
            assert_eq!(back, original);
260
        }
261
    }
262

            
263
    // ------------------------------------------------------------------
264
    // FFI discriminant stability (`#[repr(C)]` ABI contract)
265
    //
266
    // Both enums cross the FFI boundary as C enums; the platform backends
267
    // (iOS/Android/Windows/Linux) map their native codes onto these
268
    // discriminants. Re-ordering or inserting a variant silently
269
    // re-numbers them, which would turn a `Cancelled` into a `Failed` —
270
    // or worse, an `Error` into an `Authenticated` — for any already
271
    // compiled shell. These pin the numbering.
272
    // ------------------------------------------------------------------
273

            
274
    /// `BiometricKind` discriminants are 0..=3 in declaration order, with
275
    /// `NotAvailable == 0` (so a zeroed C struct means "no sensor").
276
    #[test]
277
    fn kind_discriminants_are_stable() {
278
        assert_eq!(BiometricKind::NotAvailable as u32, 0);
279
        assert_eq!(BiometricKind::Fingerprint as u32, 1);
280
        assert_eq!(BiometricKind::Face as u32, 2);
281
        assert_eq!(BiometricKind::Iris as u32, 3);
282
        // The zero value is the safe/default one.
283
        assert_eq!(BiometricKind::default() as u32, 0);
284
    }
285

            
286
    /// `BiometricResult` discriminants are 0..=5 in declaration order.
287
    /// Note `Authenticated == 0`: a zeroed result is a *success*, so the
288
    /// backends must never hand out a default-initialised result.
289
    #[test]
290
    fn result_discriminants_are_stable() {
291
        assert_eq!(BiometricResult::Authenticated as u32, 0);
292
        assert_eq!(BiometricResult::Failed as u32, 1);
293
        assert_eq!(BiometricResult::Cancelled as u32, 2);
294
        assert_eq!(BiometricResult::FellBackToPasscode as u32, 3);
295
        assert_eq!(BiometricResult::Unavailable as u32, 4);
296
        assert_eq!(BiometricResult::Error as u32, 5);
297
    }
298

            
299
    /// encode == decode: variant -> discriminant -> variant is the
300
    /// identity for every variant, and out-of-range codes (the boundary /
301
    /// overflow cases a native backend could hand us) decode to `None`
302
    /// rather than being reinterpreted as a valid variant.
303
    #[test]
304
    fn discriminant_roundtrip_and_out_of_range() {
305
        fn kind_from_u32(d: u32) -> Option<BiometricKind> {
306
            match d {
307
                0 => Some(BiometricKind::NotAvailable),
308
                1 => Some(BiometricKind::Fingerprint),
309
                2 => Some(BiometricKind::Face),
310
                3 => Some(BiometricKind::Iris),
311
                _ => None,
312
            }
313
        }
314
        fn result_from_u32(d: u32) -> Option<BiometricResult> {
315
            match d {
316
                0 => Some(BiometricResult::Authenticated),
317
                1 => Some(BiometricResult::Failed),
318
                2 => Some(BiometricResult::Cancelled),
319
                3 => Some(BiometricResult::FellBackToPasscode),
320
                4 => Some(BiometricResult::Unavailable),
321
                5 => Some(BiometricResult::Error),
322
                _ => None,
323
            }
324
        }
325

            
326
        for k in [
327
            BiometricKind::NotAvailable,
328
            BiometricKind::Fingerprint,
329
            BiometricKind::Face,
330
            BiometricKind::Iris,
331
        ] {
332
            assert_eq!(kind_from_u32(k as u32), Some(k));
333
        }
334
        for r in [
335
            BiometricResult::Authenticated,
336
            BiometricResult::Failed,
337
            BiometricResult::Cancelled,
338
            BiometricResult::FellBackToPasscode,
339
            BiometricResult::Unavailable,
340
            BiometricResult::Error,
341
        ] {
342
            assert_eq!(result_from_u32(r as u32), Some(r));
343
        }
344

            
345
        // Boundary / bogus native codes.
346
        assert_eq!(kind_from_u32(4), None);
347
        assert_eq!(kind_from_u32(u32::MAX), None);
348
        assert_eq!(result_from_u32(6), None);
349
        assert_eq!(result_from_u32(u32::MAX), None);
350
    }
351

            
352
    /// Both C enums share one underlying repr, and the FFI Option wrapper
353
    /// is at least as large as its payload (no niche-packing surprise that
354
    /// would break the `#[repr(C, u8)]` layout the shells rely on).
355
    #[test]
356
    fn repr_layout_invariants() {
357
        use core::mem::size_of;
358
        assert_eq!(size_of::<BiometricKind>(), size_of::<BiometricResult>());
359
        assert!(size_of::<OptionBiometricResult>() >= size_of::<BiometricResult>());
360
        assert!(size_of::<BiometricKind>() > 0);
361
    }
362

            
363
    // ------------------------------------------------------------------
364
    // Ord / Hash / Copy derive invariants
365
    // ------------------------------------------------------------------
366

            
367
    /// The derived total order follows declaration order (it is the same
368
    /// order the discriminants encode), and sorting is stable against it.
369
    #[test]
370
    fn ord_matches_declaration_order() {
371
        assert!(BiometricKind::NotAvailable < BiometricKind::Fingerprint);
372
        assert!(BiometricKind::Fingerprint < BiometricKind::Face);
373
        assert!(BiometricKind::Face < BiometricKind::Iris);
374

            
375
        let mut kinds = [
376
            BiometricKind::Iris,
377
            BiometricKind::NotAvailable,
378
            BiometricKind::Face,
379
            BiometricKind::Fingerprint,
380
        ];
381
        kinds.sort_unstable();
382
        assert_eq!(
383
            kinds,
384
            [
385
                BiometricKind::NotAvailable,
386
                BiometricKind::Fingerprint,
387
                BiometricKind::Face,
388
                BiometricKind::Iris,
389
            ]
390
        );
391
        // The one unavailable kind sorts first — `kinds[1..]` are all real
392
        // sensors.
393
        assert!(!kinds[0].is_available());
394
        assert!(kinds[1..].iter().all(BiometricKind::is_available));
395

            
396
        let mut results = [
397
            BiometricResult::Error,
398
            BiometricResult::Authenticated,
399
            BiometricResult::Cancelled,
400
        ];
401
        results.sort_unstable();
402
        assert_eq!(
403
            results,
404
            [
405
                BiometricResult::Authenticated,
406
                BiometricResult::Cancelled,
407
                BiometricResult::Error,
408
            ]
409
        );
410
    }
411

            
412
    /// Hash is variant-distinguishing (no two variants collide in a set)
413
    /// and equal values hash equal — the manager keys cached results by
414
    /// these types.
415
    #[test]
416
    fn hash_is_consistent_and_distinct() {
417
        use std::{
418
            collections::{hash_map::DefaultHasher, HashSet},
419
            hash::{Hash, Hasher},
420
        };
421

            
422
        fn hash_of<T: Hash>(t: &T) -> u64 {
423
            let mut h = DefaultHasher::new();
424
            t.hash(&mut h);
425
            h.finish()
426
        }
427

            
428
        let kinds = [
429
            BiometricKind::NotAvailable,
430
            BiometricKind::Fingerprint,
431
            BiometricKind::Face,
432
            BiometricKind::Iris,
433
        ];
434
        let results = [
435
            BiometricResult::Authenticated,
436
            BiometricResult::Failed,
437
            BiometricResult::Cancelled,
438
            BiometricResult::FellBackToPasscode,
439
            BiometricResult::Unavailable,
440
            BiometricResult::Error,
441
        ];
442

            
443
        assert_eq!(kinds.iter().collect::<HashSet<_>>().len(), 4);
444
        assert_eq!(results.iter().collect::<HashSet<_>>().len(), 6);
445

            
446
        // Eq => equal hashes (the Hash/Eq contract).
447
        for k in kinds {
448
            let copy = k;
449
            assert_eq!(k, copy);
450
            assert_eq!(hash_of(&k), hash_of(&copy));
451
        }
452
        for r in results {
453
            let copy = r;
454
            assert_eq!(r, copy);
455
            assert_eq!(hash_of(&r), hash_of(&copy));
456
        }
457
    }
458

            
459
    /// Both enums are `Copy`: reading a result does not consume it, so a
460
    /// manager can hand the same value to several callbacks.
461
    #[test]
462
    fn enums_are_copy() {
463
        let r = BiometricResult::FellBackToPasscode;
464
        let moved = r;
465
        // `r` is still usable — this only compiles/behaves if `Copy`.
466
        assert!(r.is_success());
467
        assert!(moved.is_success());
468
        assert_eq!(r, moved);
469

            
470
        let k = BiometricKind::Face;
471
        let moved_k = k;
472
        assert!(k.is_available());
473
        assert_eq!(k, moved_k);
474
    }
475

            
476
    // ------------------------------------------------------------------
477
    // Documented cross-type pairing
478
    // ------------------------------------------------------------------
479

            
480
    /// `BiometricResult::Unavailable` is documented to pair with
481
    /// `BiometricKind::NotAvailable`: neither may unlock anything.
482
    #[test]
483
    fn unavailable_pairs_with_not_available() {
484
        assert!(!BiometricResult::Unavailable.is_success());
485
        assert!(!BiometricKind::NotAvailable.is_available());
486
        // Every non-success result must not accidentally be readable as an
487
        // available sensor kind through the shared discriminant space.
488
        assert_ne!(
489
            BiometricResult::Authenticated as u32,
490
            BiometricResult::Unavailable as u32
491
        );
492
    }
493

            
494
    // ------------------------------------------------------------------
495
    // OptionBiometricResult — the FFI accessor's "no request yet" state
496
    // ------------------------------------------------------------------
497

            
498
    /// The wrapper defaults to `None` ("no request has completed yet") —
499
    /// crucially NOT to `Some(Authenticated)`, which discriminant 0 of the
500
    /// payload would be.
501
    #[test]
502
    fn option_result_default_is_none() {
503
        let d = OptionBiometricResult::default();
504
        assert!(d.is_none());
505
        assert!(!d.is_some());
506
        assert_eq!(d.as_option(), None);
507
        assert_eq!(Option::<BiometricResult>::from(d), None);
508
        // A defaulted accessor must never read as a successful unlock.
509
        assert!(!d.as_option().is_some_and(BiometricResult::is_success));
510
    }
511

            
512
    /// `replace` has `mem::replace` semantics: it returns the *previous*
513
    /// value and installs the new one. A vault gate that mis-read the
514
    /// return value would act on the stale result.
515
    #[test]
516
    fn option_result_replace_returns_previous() {
517
        let mut slot = OptionBiometricResult::None;
518
        let prev = slot.replace(BiometricResult::Failed);
519
        assert!(prev.is_none());
520
        assert_eq!(slot, OptionBiometricResult::Some(BiometricResult::Failed));
521

            
522
        let prev = slot.replace(BiometricResult::Authenticated);
523
        assert_eq!(prev, OptionBiometricResult::Some(BiometricResult::Failed));
524
        assert_eq!(
525
            slot,
526
            OptionBiometricResult::Some(BiometricResult::Authenticated)
527
        );
528
        assert!(slot.as_option().is_some_and(BiometricResult::is_success));
529
        // The previous (failed) attempt is not a success.
530
        assert!(!prev.as_option().is_some_and(BiometricResult::is_success));
531
    }
532

            
533
    /// `map` / `and_then` / `as_ref` / `as_mut` / `into_option` behave
534
    /// exactly like the std `Option` equivalents for every variant.
535
    #[test]
536
    fn option_result_combinators_match_std_option() {
537
        for original in [
538
            None,
539
            Some(BiometricResult::Authenticated),
540
            Some(BiometricResult::Failed),
541
            Some(BiometricResult::Cancelled),
542
            Some(BiometricResult::FellBackToPasscode),
543
            Some(BiometricResult::Unavailable),
544
            Some(BiometricResult::Error),
545
        ] {
546
            let wrapped: OptionBiometricResult = original.into();
547

            
548
            assert_eq!(wrapped.into_option(), original);
549
            assert_eq!(wrapped.as_ref(), original.as_ref());
550
            assert_eq!(
551
                wrapped.map(|r| r.is_success()),
552
                original.map(|r| r.is_success())
553
            );
554
            assert_eq!(
555
                wrapped.and_then(|r| r.is_success().then_some(r)),
556
                original.and_then(|r| r.is_success().then_some(r))
557
            );
558

            
559
            // as_mut writes through to the wrapper (and is `None` exactly
560
            // when the source Option was `None` — it must not conjure a
561
            // slot out of the `None` variant).
562
            let mut target = wrapped;
563
            let wrote = target.as_mut().map(|slot| *slot = BiometricResult::Error);
564
            assert_eq!(wrote.is_some(), original.is_some());
565
            if original.is_some() {
566
                assert_eq!(target, OptionBiometricResult::Some(BiometricResult::Error));
567
            } else {
568
                assert_eq!(target, OptionBiometricResult::None);
569
            }
570
        }
571
    }
572

            
573
    /// The wrapper's derived order puts `None` before every `Some(_)`, and
574
    /// `Some(_)` follows the payload order — pins the `#[repr(C, u8)]`
575
    /// tag ordering that codegen mirrors.
576
    #[test]
577
    fn option_result_ord_none_first() {
578
        assert!(
579
            OptionBiometricResult::None
580
                < OptionBiometricResult::Some(BiometricResult::Authenticated)
581
        );
582
        assert!(
583
            OptionBiometricResult::Some(BiometricResult::Authenticated)
584
                < OptionBiometricResult::Some(BiometricResult::Error)
585
        );
586
    }
587

            
588
    // ------------------------------------------------------------------
589
    // BiometricPrompt — equality / field wiring / string invariants
590
    // ------------------------------------------------------------------
591

            
592
    /// `PartialEq` is sensitive to *every* field: two prompts that differ
593
    /// only in the cancel label, only in the reason, or only in the
594
    /// device-credential flag must not compare equal. A derive that
595
    /// dropped a field would let a biometric-only prompt compare equal to
596
    /// a passcode-fallback one.
597
    #[test]
598
    fn prompt_eq_is_field_sensitive() {
599
        let base = BiometricPrompt {
600
            reason: AzString::from("Unlock"),
601
            cancel_label: AzString::from("Nope"),
602
            allow_device_credential: true,
603
        };
604

            
605
        let mut other_reason = base.clone();
606
        other_reason.reason = AzString::from("Unlock!");
607
        assert_ne!(base, other_reason);
608

            
609
        let mut other_cancel = base.clone();
610
        other_cancel.cancel_label = AzString::from("nope");
611
        assert_ne!(base, other_cancel);
612

            
613
        let mut other_flag = base.clone();
614
        other_flag.allow_device_credential = false;
615
        assert_ne!(base, other_flag);
616

            
617
        // …and an identical rebuild does compare equal (deep AzString eq).
618
        let same = BiometricPrompt {
619
            reason: AzString::from("Unlock"),
620
            cancel_label: AzString::from("Nope"),
621
            allow_device_credential: true,
622
        };
623
        assert_eq!(base, same);
624
    }
625

            
626
    /// Post-construction length invariants: `len()`, `as_str().len()` and
627
    /// `as_bytes().len()` agree for ASCII, multibyte, embedded-NUL and
628
    /// empty reasons — no off-by-one or capacity/len confusion.
629
    #[test]
630
    fn prompt_string_len_invariants() {
631
        let cases = [
632
            String::new(),
633
            "a".to_string(),
634
            "λ🔒指".to_string(),
635
            String::from("nul\0inside"),
636
            "z".repeat(70_000),
637
        ];
638
        for s in &cases {
639
            let prompt = BiometricPrompt::new(AzString::from(s.as_str()));
640
            assert_eq!(prompt.reason.len(), s.len());
641
            assert_eq!(prompt.reason.as_str().len(), s.len());
642
            assert_eq!(prompt.reason.as_bytes().len(), s.len());
643
            assert_eq!(prompt.reason.is_empty(), s.is_empty());
644
            // The untouched field keeps its documented default.
645
            assert_eq!(prompt.cancel_label.len(), 0);
646
            assert!(prompt.cancel_label.is_empty());
647
        }
648
    }
649

            
650
    /// No Unicode normalization happens: an NFC "é" and an NFD "e" + U+0301
651
    /// stay distinct byte sequences (a normalizing string type would make
652
    /// these two prompts compare equal and silently change what the OS
653
    /// modal displays).
654
    #[test]
655
    fn prompt_does_not_normalize_unicode() {
656
        let nfc = BiometricPrompt::new(AzString::from("caf\u{e9}"));
657
        let nfd = BiometricPrompt::new(AzString::from("cafe\u{301}"));
658
        assert_ne!(nfc, nfd);
659
        assert_eq!(nfc.reason.as_bytes().len(), 5);
660
        assert_eq!(nfd.reason.as_bytes().len(), 6);
661
        assert_eq!(nfc.reason.as_str().chars().count(), 4);
662
        assert_eq!(nfd.reason.as_str().chars().count(), 5);
663
    }
664

            
665
    /// The constructor does not trim, collapse or otherwise rewrite the
666
    /// reason — leading/trailing whitespace survives verbatim.
667
    #[test]
668
    fn prompt_preserves_whitespace_verbatim() {
669
        let raw = "  \t Unlock the vault \n ";
670
        let prompt = BiometricPrompt::new(AzString::from(raw));
671
        assert_eq!(prompt.reason.as_str(), raw);
672
        assert_ne!(prompt.reason.as_str(), raw.trim());
673
    }
674

            
675
    /// `AzString` round-trips out of a constructed prompt unchanged
676
    /// (`into_library_owned_string` gives back exactly what went in),
677
    /// including for a multibyte reason.
678
    #[test]
679
    fn prompt_reason_string_roundtrip() {
680
        for original in [String::new(), "Unlock".to_string(), "🔒λ指紋".to_string()] {
681
            let prompt = BiometricPrompt::new(AzString::from(original.clone()));
682
            let back = prompt.reason.clone().into_library_owned_string();
683
            assert_eq!(back, original);
684
        }
685
    }
686

            
687
    /// A prompt whose *both* strings are ~1 MB clones deeply and compares
688
    /// equal — exercises the deep-copy path for the non-defaulted field
689
    /// too (the constructor never sets it, so it is built by hand).
690
    #[test]
691
    fn prompt_huge_both_strings_clone_deeply() {
692
        let big_reason = "r".repeat(1_000_000);
693
        let big_cancel = "c".repeat(1_000_000);
694
        let prompt = BiometricPrompt {
695
            reason: AzString::from(big_reason.as_str()),
696
            cancel_label: AzString::from(big_cancel.as_str()),
697
            allow_device_credential: true,
698
        };
699
        let cloned = prompt.clone();
700
        assert_eq!(cloned, prompt);
701
        assert_eq!(cloned.reason.as_str(), big_reason.as_str());
702
        assert_eq!(cloned.cancel_label.as_str(), big_cancel.as_str());
703
        assert!(cloned.allow_device_credential);
704
        // The two buffers did not get aliased/swapped by the clone.
705
        assert_ne!(cloned.reason, cloned.cancel_label);
706
    }
707

            
708
    /// `Default::default()` is idempotent and fully empty — two defaults
709
    /// compare equal and neither enables the passcode fallback.
710
    #[test]
711
    fn prompt_default_is_empty_and_stable() {
712
        let a = BiometricPrompt::default();
713
        let b = BiometricPrompt::default();
714
        assert_eq!(a, b);
715
        assert!(a.reason.is_empty());
716
        assert!(a.cancel_label.is_empty());
717
        assert!(!a.allow_device_credential);
718
        // An empty reason is accepted (documented as "discouraged", not
719
        // rejected) — the constructor must not panic on it.
720
        assert_eq!(BiometricPrompt::new(AzString::from_const_str("")), a);
721
    }
722

            
723
    /// `Debug` renders the reason (used in backend logs); it must not lose
724
    /// the field or print a placeholder.
725
    #[test]
726
    fn prompt_debug_contains_fields() {
727
        let prompt = BiometricPrompt {
728
            reason: AzString::from("Unlock vault"),
729
            cancel_label: AzString::from("Abort"),
730
            allow_device_credential: true,
731
        };
732
        let dbg = format!("{prompt:?}");
733
        assert!(dbg.contains("BiometricPrompt"), "{dbg}");
734
        assert!(dbg.contains("Unlock vault"), "{dbg}");
735
        assert!(dbg.contains("Abort"), "{dbg}");
736
        assert!(dbg.contains("true"), "{dbg}");
737
    }
738
}