qubit-argument 0.4.1

Structured, ownership-preserving argument validation for Rust applications
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Tests for ownership-preserving string argument validation.

use qubit_argument::{
    ArgumentError,
    ArgumentErrorKind,
    LengthConstraint,
    LengthMetric,
    StringArgument,
};

#[cfg(feature = "regex")]
use qubit_argument::PatternExpectation;
#[cfg(feature = "regex")]
use regex::Regex;

/// Asserts that an error has the requested path and structured kind.
fn assert_structured_error(
    error: ArgumentError,
    expected_path: &str,
    expected_kind: ArgumentErrorKind,
) {
    assert_eq!(error.path().as_str(), expected_path);
    assert_eq!(error.kind(), &expected_kind);
}

/// Verifies that non-blank validation returns an owned string unchanged.
#[test]
fn test_require_non_blank_preserves_owned_string() {
    let value = String::from("qubit");
    let validated: String =
        value.require_non_blank("name").expect("name is non-blank");
    assert_eq!(validated, "qubit");
}

/// Verifies that non-blank validation preserves a borrowed string.
#[test]
fn test_require_non_blank_preserves_borrowed_str() {
    let value: &str = "qubit";
    let validated: &str =
        value.require_non_blank("name").expect("name is non-blank");
    assert_eq!(validated, value);
}

/// Verifies that empty and Unicode-whitespace strings are blank.
#[test]
fn test_require_non_blank_rejects_unicode_whitespace() {
    for value in ["", "\u{2003}\u{3000}", " \t\n"] {
        let error = value
            .require_non_blank("name")
            .expect_err("whitespace-only input must be blank");
        assert_structured_error(error, "name", ArgumentErrorKind::Blank);
    }
}

/// Verifies that byte length and Unicode scalar count are distinct.
#[test]
fn test_byte_len_and_char_count_have_distinct_semantics() {
    let value = "汉😀";
    assert!(value.require_byte_len("value", 7).is_ok());
    assert!(value.require_char_count("value", 2).is_ok());
}

/// Verifies the exact byte-length constraint and its structured error.
#[test]
fn test_require_byte_len_returns_exact_length_error() {
    assert_eq!(
        "abc"
            .require_byte_len("value", 3)
            .expect("three ASCII bytes satisfy the constraint"),
        "abc",
    );
    let error = "ab"
        .require_byte_len("value", 3)
        .expect_err("two bytes do not satisfy an exact length of three");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::Length {
            actual: 2,
            constraint: LengthConstraint::Exact(3),
            metric: LengthMetric::Bytes,
        },
    );
}

/// Verifies the minimum byte-length constraint and its structured error.
#[test]
fn test_require_byte_len_at_least_returns_minimum_length_error() {
    assert_eq!(
        "abc"
            .require_byte_len_at_least("value", 3)
            .expect("three bytes satisfy a minimum of three"),
        "abc",
    );
    let error = "ab"
        .require_byte_len_at_least("value", 3)
        .expect_err("two bytes are below the minimum");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::Length {
            actual: 2,
            constraint: LengthConstraint::AtLeast(3),
            metric: LengthMetric::Bytes,
        },
    );
}

/// Verifies the maximum byte-length constraint and its structured error.
#[test]
fn test_require_byte_len_at_most_returns_maximum_length_error() {
    assert_eq!(
        "abc"
            .require_byte_len_at_most("value", 3)
            .expect("three bytes satisfy a maximum of three"),
        "abc",
    );
    let error = "abcd"
        .require_byte_len_at_most("value", 3)
        .expect_err("four bytes exceed the maximum");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::Length {
            actual: 4,
            constraint: LengthConstraint::AtMost(3),
            metric: LengthMetric::Bytes,
        },
    );
}

/// Verifies both inclusive limits of a byte-length range.
#[test]
fn test_require_byte_len_in_returns_range_length_errors() {
    assert_eq!(
        "abc"
            .require_byte_len_in("value", 3, 4)
            .expect("three bytes lie on the inclusive lower boundary"),
        "abc",
    );
    for value in ["ab", "abcde"] {
        let error = value
            .require_byte_len_in("value", 3, 4)
            .expect_err("byte length lies outside the range");
        assert_structured_error(
            error,
            "value",
            ArgumentErrorKind::Length {
                actual: value.len(),
                constraint: LengthConstraint::InRange { min: 3, max: 4 },
                metric: LengthMetric::Bytes,
            },
        );
    }
}

/// Verifies that a reversed byte-length range fails before value validation.
#[test]
fn test_require_byte_len_in_rejects_invalid_constraint_first() {
    let error = "x"
        .require_byte_len_in("value", 3, 1)
        .expect_err("a reversed byte-length range is invalid");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::InvalidLengthConstraint {
            constraint: LengthConstraint::InRange { min: 3, max: 1 },
            metric: LengthMetric::Bytes,
        },
    );
}

/// Verifies the exact Unicode scalar-count constraint and its error.
#[test]
fn test_require_char_count_returns_exact_length_error() {
    assert_eq!(
        "汉😀"
            .require_char_count("value", 2)
            .expect("the input has two Unicode scalar values"),
        "汉😀",
    );
    let error = "汉😀"
        .require_char_count("value", 3)
        .expect_err("two scalar values do not satisfy a count of three");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::Length {
            actual: 2,
            constraint: LengthConstraint::Exact(3),
            metric: LengthMetric::UnicodeScalars,
        },
    );
}

/// Verifies the minimum Unicode scalar-count constraint and its error.
#[test]
fn test_require_char_count_at_least_returns_minimum_length_error() {
    assert_eq!(
        "汉😀"
            .require_char_count_at_least("value", 2)
            .expect("two scalar values satisfy a minimum of two"),
        "汉😀",
    );
    let error = ""
        .require_char_count_at_least("value", 2)
        .expect_err("one scalar value is below the minimum");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::Length {
            actual: 1,
            constraint: LengthConstraint::AtLeast(2),
            metric: LengthMetric::UnicodeScalars,
        },
    );
}

/// Verifies the maximum Unicode scalar-count constraint and its error.
#[test]
fn test_require_char_count_at_most_returns_maximum_length_error() {
    assert_eq!(
        "汉😀"
            .require_char_count_at_most("value", 2)
            .expect("two scalar values satisfy a maximum of two"),
        "汉😀",
    );
    let error = "汉😀x"
        .require_char_count_at_most("value", 2)
        .expect_err("three scalar values exceed the maximum");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::Length {
            actual: 3,
            constraint: LengthConstraint::AtMost(2),
            metric: LengthMetric::UnicodeScalars,
        },
    );
}

/// Verifies both inclusive limits of a Unicode scalar-count range.
#[test]
fn test_require_char_count_in_returns_range_length_errors() {
    assert_eq!(
        "汉😀"
            .require_char_count_in("value", 1, 2)
            .expect("two scalar values lie on the inclusive upper boundary"),
        "汉😀",
    );
    for value in ["", "汉😀x"] {
        let error = value
            .require_char_count_in("value", 1, 2)
            .expect_err("scalar count lies outside the range");
        assert_structured_error(
            error,
            "value",
            ArgumentErrorKind::Length {
                actual: value.chars().count(),
                constraint: LengthConstraint::InRange { min: 1, max: 2 },
                metric: LengthMetric::UnicodeScalars,
            },
        );
    }
}

/// Verifies that a reversed scalar-count range fails before value validation.
#[test]
fn test_require_char_count_in_rejects_invalid_constraint_first() {
    let error = "x"
        .require_char_count_in("value", 3, 1)
        .expect_err("a reversed scalar-count range is invalid");
    assert_structured_error(
        error,
        "value",
        ArgumentErrorKind::InvalidLengthConstraint {
            constraint: LengthConstraint::InRange { min: 3, max: 1 },
            metric: LengthMetric::UnicodeScalars,
        },
    );
}

/// Verifies that empty strings have zero byte and scalar lengths.
#[test]
fn test_length_methods_accept_empty_string_at_zero() {
    assert_eq!(
        "".require_byte_len("value", 0)
            .expect("the empty string has zero bytes"),
        "",
    );
    assert_eq!(
        "".require_char_count("value", 0)
            .expect("the empty string has zero scalar values"),
        "",
    );
}

/// Verifies that all core validators can return the same owned string.
#[test]
fn test_core_string_validation_chain_preserves_ownership() {
    let validated: String = String::from("汉😀")
        .require_non_blank("value")
        .and_then(|value| value.require_byte_len("value", 7))
        .and_then(|value| value.require_byte_len_at_least("value", 7))
        .and_then(|value| value.require_byte_len_at_most("value", 7))
        .and_then(|value| value.require_byte_len_in("value", 7, 7))
        .and_then(|value| value.require_char_count("value", 2))
        .and_then(|value| value.require_char_count_at_least("value", 2))
        .and_then(|value| value.require_char_count_at_most("value", 2))
        .and_then(|value| value.require_char_count_in("value", 2, 2))
        .expect("every constraint accepts the owned value");
    assert_eq!(validated, "汉😀");
}

/// Verifies that string errors do not expose the validated input.
#[test]
fn test_string_error_does_not_expose_input() {
    let secret = "secret-token-value";
    let error = secret
        .require_byte_len_at_most("token", 4)
        .expect_err("secret is too long");
    assert!(!format!("{error:?}").contains(secret));
    assert!(!error.to_string().contains(secret));
}

/// Verifies the pattern error emitted when a match is required.
#[cfg(feature = "regex")]
#[test]
fn test_require_match_returns_pattern_error_without_input() {
    let pattern = Regex::new("^[a-z]+$").expect("test pattern is valid");
    let secret = "123-secret-token";
    let error = secret
        .require_match("name", &pattern)
        .expect_err("digits and punctuation must fail");
    assert_structured_error(
        error.clone(),
        "name",
        ArgumentErrorKind::Pattern {
            pattern: String::from("^[a-z]+$"),
            expectation: PatternExpectation::Match,
        },
    );
    assert!(!format!("{error:?}").contains(secret));
    assert!(!error.to_string().contains(secret));
}

/// Verifies the pattern error emitted when a non-match is required.
#[cfg(feature = "regex")]
#[test]
fn test_require_not_match_returns_pattern_error() {
    let pattern = Regex::new("^[0-9]+$").expect("test pattern is valid");
    let error = "123"
        .require_not_match("identifier", &pattern)
        .expect_err("digits match the forbidden pattern");
    assert_structured_error(
        error,
        "identifier",
        ArgumentErrorKind::Pattern {
            pattern: String::from("^[0-9]+$"),
            expectation: PatternExpectation::NoMatch,
        },
    );
}

/// Verifies that regex validation preserves an owned string on success.
#[cfg(feature = "regex")]
#[test]
fn test_require_match_preserves_owned_string() {
    let pattern = Regex::new("^[a-z]+$").expect("test pattern is valid");
    let validated: String = String::from("qubit")
        .require_match("name", &pattern)
        .and_then(|value| {
            value.require_not_match(
                "name",
                &Regex::new("^[0-9]+$").expect("test pattern is valid"),
            )
        })
        .expect("the owned string satisfies both pattern constraints");
    assert_eq!(validated, "qubit");
}

/// Verifies that regex validation preserves a borrowed string on success.
#[cfg(feature = "regex")]
#[test]
fn test_pattern_methods_preserve_borrowed_str() {
    let value: &str = "qubit";
    let validated = value
        .require_match(
            "name",
            &Regex::new("^[a-z]+$").expect("test pattern is valid"),
        )
        .and_then(|matched| {
            matched.require_not_match(
                "name",
                &Regex::new("^[0-9]+$").expect("test pattern is valid"),
            )
        })
        .expect("the borrowed string satisfies both pattern constraints");
    assert!(std::ptr::eq(validated, value));
}