rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Request data extraction and response body templating.
//!
//! This module provides Mountebank-compatible template substitution for response bodies.
//! It supports extracting values from the request and inserting them into responses.
//!
//! # Supported Template Variables
//!
//! - `${request.path}` - The request path
//! - `${request.method}` - The HTTP method
//! - `${request.query.<name>}` - Query parameter value
//! - `${request.headers.<name>}` - Header value (case-insensitive)
//! - `${request.pathParams.<name>}` - Path parameter from route pattern
//! - `${request.body}` - The raw request body
//!
//! # Example
//!
//! ```yaml
//! fault:
//!   error:
//!     status: 200
//!     body: '{"echo": "${request.query.message}", "path": "${request.path}"}'
//! ```

use crate::util::FastMap;
use crate::util::{comma_joined, parse_query_string};
use regex::Regex;
use std::sync::OnceLock;

/// Regex for matching template variables: ${request.path}, ${request.query.name}, etc.
static TEMPLATE_REGEX: OnceLock<Regex> = OnceLock::new();

fn get_template_regex() -> &'static Regex {
    TEMPLATE_REGEX.get_or_init(|| {
        Regex::new(r"\$\{request\.([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_-]*)?)\}")
            .unwrap()
    })
}

/// Parsed request data for template substitution
#[derive(Debug, Clone, Default)]
pub struct RequestData {
    /// HTTP method (GET, POST, etc.)
    pub method: String,
    /// Request path (without query string)
    pub path: String,
    /// Query parameters parsed from the URL, by the same parser predicates use (issue #1153), a
    /// repeated key's values comma-joined in order (`docs/mountebank/responses.md`; predicates
    /// match each value, issue #1553). Request-scoped — `FastMap` (issue #704).
    pub query: crate::util::OrderedMap<String, String>,
    /// Request headers (keys lowercased). Request-scoped — `FastMap` (issue #704).
    pub headers: FastMap<String, String>,
    /// Path parameters extracted from route patterns (e.g., /users/:id). Request-scoped —
    /// `FastMap` (issue #704).
    pub path_params: FastMap<String, String>,
    /// Raw request body
    pub body: String,
}

impl RequestData {
    /// Create RequestData from request components.
    ///
    /// `headers` is `collect_request_headers`' map for this request, not the raw `HeaderMap`
    /// (issue #1040). Templating used to re-derive its own view with `to_str().ok()` — an
    /// unattributed drop, and last-wins on a repeated header. On the served path the collector had
    /// already warned about that value, so the drop was not wholly undiagnosed; what it lacked was
    /// any guarantee of it, since an embedder calling this `pub` constructor with a hand-built
    /// `HeaderMap` bypassed the collector entirely. Taking the collected map closes that by
    /// construction, and makes `${request.headers.x}` resolve to the same value a predicate on `x`
    /// matched.
    pub fn new<SH: std::hash::BuildHasher>(
        method: &str,
        path: &str,
        query_string: Option<&str>,
        headers: &indexmap::IndexMap<String, Vec<String>, SH>,
        body: Option<&str>,
    ) -> Self {
        let query = comma_joined(&parse_query_string(query_string.unwrap_or("")));
        // Lowercased because that is this map's lookup contract (`${request.headers.x-id}` is
        // matched case-insensitively by lowercasing the token). The collector hands over
        // Title-Case names, which lowercase to exactly the names hyper produced before.
        let headers_map: FastMap<String, String> = headers
            .iter()
            .filter_map(|(k, values)| {
                values
                    .first()
                    .map(|first| (k.to_lowercase(), first.clone()))
            })
            .collect();

        Self {
            method: method.to_string(),
            path: path.to_string(),
            query,
            headers: headers_map,
            path_params: FastMap::default(),
            body: body.unwrap_or("").to_string(),
        }
    }

    /// Populate `path_params` by matching the request path against a route `pattern` (issue #433),
    /// e.g. `/users/:id`. A `None` pattern — or one whose shape doesn't match the path — leaves the
    /// map empty (the unchanged default), so callers can pass a stub's optional pattern directly.
    #[must_use]
    pub fn with_route_pattern(mut self, pattern: Option<&str>) -> Self {
        if let Some(pattern) = pattern {
            self.path_params = extract_path_params(pattern, &self.path);
        }
        self
    }

    /// Get a value by dotted path (e.g., "query.name", "headers.content-type")
    pub fn get(&self, path: &str) -> Option<String> {
        let parts: Vec<&str> = path.splitn(2, '.').collect();

        match parts.as_slice() {
            ["path"] => Some(self.path.clone()),
            ["method"] => Some(self.method.clone()),
            ["body"] => Some(self.body.clone()),
            ["query", name] => self.query.get(*name).cloned(),
            ["headers", name] => self.headers.get(&name.to_lowercase()).cloned(),
            ["pathParams", name] | ["path_params", name] => self.path_params.get(*name).cloned(),
            _ => None,
        }
    }
}

/// Extract path parameters from a route `pattern` (`:name` segments) and the actual request
/// `path`. Returns an empty map when the segment counts differ or a literal segment doesn't match.
/// Request-scoped — `FastMap` (issue #704).
pub(crate) fn extract_path_params(pattern: &str, path: &str) -> FastMap<String, String> {
    let mut params = FastMap::default();

    let pattern_parts: Vec<&str> = pattern.split('/').collect();
    let path_parts: Vec<&str> = path.split('/').collect();

    if pattern_parts.len() != path_parts.len() {
        return params;
    }

    for (pattern_part, path_part) in pattern_parts.iter().zip(path_parts.iter()) {
        if let Some(param_name) = pattern_part.strip_prefix(':') {
            params.insert(param_name.to_string(), path_part.to_string());
        } else if pattern_part != path_part {
            // Pattern doesn't match
            return FastMap::default();
        }
    }

    params
}

/// Process a template string, substituting variables with request data
///
/// # Arguments
/// * `template` - The template string containing `${request.*}` variables
/// * `request_data` - The request data to use for substitution
///
/// # Returns
/// The processed string with all variables substituted
pub fn process_template(template: &str, request_data: &RequestData) -> String {
    process_template_mapped(template, request_data, |value| value)
}

/// [`process_template`], with every substituted value passed through `map` before it is spliced in.
///
/// Header values need the *substituted* text repaired and the literal text around it left alone
/// (issue #1067): the substitution carries request data, which can hold a byte a header value
/// cannot, while a control character the author typed into the header itself is an authoring bug
/// that must still fail the response. Bodies use [`process_template`] and substitute verbatim.
pub(crate) fn process_template_mapped<F>(
    template: &str,
    request_data: &RequestData,
    map: F,
) -> String
where
    F: Fn(String) -> String,
{
    let mut spliced = crate::behaviors::Spliced::authored(template.to_string());
    process_template_spliced(&mut spliced, request_data, map);
    spliced.into_text()
}

/// [`process_template_mapped`] over text that remembers what earlier passes inserted (issue
/// #1203): a `${request.*}` lying wholly inside text a `{{ }}` pass substituted from the request is
/// served as written, so a client cannot name a request header for the engine to reflect.
pub(crate) fn process_template_spliced<F>(
    template: &mut crate::behaviors::Spliced,
    request_data: &RequestData,
    map: F,
) where
    F: Fn(String) -> String,
{
    template.replace_regex(get_template_regex(), |caps| {
        map(request_data.get(&caps[1]).unwrap_or_default())
    });
}

/// Check if a string contains template variables
pub fn has_template_variables(s: &str) -> bool {
    get_template_regex().is_match(s)
}

static DAYS_REGEX: OnceLock<Regex> = OnceLock::new();
static MONTHS_REGEX: OnceLock<Regex> = OnceLock::new();
static NOW_REGEX: OnceLock<Regex> = OnceLock::new();

fn days_regex() -> &'static Regex {
    DAYS_REGEX.get_or_init(|| Regex::new(r"\{\{DAYS([+-])(\d+)\}\}").unwrap())
}
fn months_regex() -> &'static Regex {
    MONTHS_REGEX.get_or_init(|| Regex::new(r"\{\{MONTHS([+-])(\d+)\}\}").unwrap())
}
fn now_regex() -> &'static Regex {
    NOW_REGEX.get_or_init(|| Regex::new(r"\{\{NOW\}\}").unwrap())
}

/// True if `body` contains any serve-time date token that [`apply_date_templates`] would expand
/// (`{{NOW}}` / `{{DAYS±N}}` / `{{MONTHS±N}}`). Shares the exact regexes with the applier so the
/// two cannot drift — the prepared-response fast path (issue #703) uses this at construction to
/// decide whether a body needs the per-request date pass. The leading `{{` check is a cheap reject
/// that skips the three regex scans for the overwhelmingly common token-free body.
#[must_use]
pub fn contains_date_templates(body: &str) -> bool {
    DOUBLE_BRACE_FINDER.find(body.as_bytes()).is_some()
        && (days_regex().is_match(body)
            || months_regex().is_match(body)
            || now_regex().is_match(body))
}

/// Prebuilt SIMD substring searcher for the `{{` marker probed on every candidate response body
/// (issue #706). Building the `Finder` once amortizes its setup; `str::contains` rebuilds its search
/// state on each call.
static DOUBLE_BRACE_FINDER: std::sync::LazyLock<memchr::memmem::Finder<'static>> =
    std::sync::LazyLock::new(|| memchr::memmem::Finder::new(b"{{"));

/// Expand legacy-recorder relative-date templates in a response body (issue #195):
/// `{{DAYS+N}}` / `{{DAYS-N}}` / `{{MONTHS+N}}` / `{{MONTHS-N}}` → an RFC3339 timestamp `N`
/// days/months in the future (`+`) or past (`-`, issue #270) from now, and `{{NOW}}` → the current
/// UTC timestamp. A token whose offset overflows the representable date range is left unchanged
/// rather than panicking. These are a legacy extension, not standard Mountebank/WireMock.
pub fn apply_date_templates(body: &str) -> String {
    // The imposter's clock, or the request's X-Rift-Now (issue #1756).
    let now = crate::scripting::env::now_utc();
    let days_re = days_regex();
    let months_re = months_regex();
    let now_re = now_regex();

    let with_days = days_re.replace_all(body, |caps: &regex::Captures| {
        match caps[2].parse::<i64>() {
            // `Duration::days` panics on overflow, so go through the fallible `try_days` and let an
            // out-of-range offset flow into the leave-token-unchanged fallback below.
            Ok(n) => {
                let signed = if &caps[1] == "-" { -n } else { n };
                chrono::Duration::try_days(signed)
                    .and_then(|d| now.checked_add_signed(d))
                    .map(|d| d.to_rfc3339())
                    .unwrap_or_else(|| caps[0].to_string())
            }
            Err(_) => caps[0].to_string(),
        }
    });
    let with_months = months_re.replace_all(&with_days, |caps: &regex::Captures| {
        match caps[2].parse::<u32>() {
            Ok(n) => {
                let months = chrono::Months::new(n);
                let shifted = if &caps[1] == "-" {
                    now.checked_sub_months(months)
                } else {
                    now.checked_add_months(months)
                };
                shifted
                    .map(|d| d.to_rfc3339())
                    .unwrap_or_else(|| caps[0].to_string())
            }
            Err(_) => caps[0].to_string(),
        }
    });
    now_re
        .replace_all(&with_months, |_: &regex::Captures| now.to_rfc3339())
        .into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The shape `collect_request_headers` hands `RequestData::new` (issue #1040): Title-Case
    /// names, every value the client sent.
    fn hdrs(pairs: &[(&str, &[&str])]) -> crate::util::OrderedMap<String, Vec<String>> {
        pairs
            .iter()
            .map(|(k, vs)| {
                (
                    (*k).to_string(),
                    vs.iter().map(|v| (*v).to_string()).collect(),
                )
            })
            .collect()
    }

    fn create_test_request_data() -> RequestData {
        let headers = hdrs(&[
            ("Content-Type", &["application/json"]),
            ("X-Request-Id", &["req-12345"]),
        ]);

        let mut data = RequestData::new(
            "POST",
            "/users/123",
            Some("name=John&age=30"),
            &headers,
            Some(r#"{"action": "test"}"#),
        );

        data.path_params.insert("id".to_string(), "123".to_string());
        data
    }

    #[test]
    fn test_parse_query_string() {
        let params = parse_query_string("name=John&age=30&city=New%20York");
        assert_eq!(params.get("name"), Some(&vec!["John".to_string()]));
        assert_eq!(params.get("age"), Some(&vec!["30".to_string()]));
        assert_eq!(params.get("city"), Some(&vec!["New York".to_string()]));
    }

    // Issue #1153: templates parsed a repeated query key with the orphaned `crate::predicate`
    // parser, which keeps the *last* value. One parser now; a template renders a repeated key's
    // values comma-joined in order, while predicates match each value (issue #1553).
    #[test]
    fn a_repeated_query_key_renders_comma_joined() {
        let headers: crate::imposter::Headers = crate::imposter::Headers::new();
        let data = RequestData::new("GET", "/p", Some("color=red&color=green"), &headers, None);
        assert_eq!(
            process_template("${request.query.color}", &data),
            "red,green"
        );
    }

    #[test]
    fn test_parse_query_string_empty() {
        let params = parse_query_string("");
        assert!(params.is_empty());
    }

    #[test]
    fn test_extract_path_params() {
        let params = extract_path_params("/users/:id/posts/:post_id", "/users/123/posts/456");
        assert_eq!(params.get("id"), Some(&"123".to_string()));
        assert_eq!(params.get("post_id"), Some(&"456".to_string()));
    }

    #[test]
    fn test_extract_path_params_no_match() {
        let params = extract_path_params("/users/:id", "/posts/123");
        assert!(params.is_empty());
    }

    #[test]
    fn test_with_route_pattern_builder() {
        let headers = hdrs(&[]);
        // A matching pattern populates path_params from the request path.
        let data = RequestData::new("GET", "/users/42", None, &headers, None)
            .with_route_pattern(Some("/users/:id"));
        assert_eq!(data.get("pathParams.id"), Some("42".to_string()));
        // No pattern (and a non-matching pattern) leave the map empty.
        let none =
            RequestData::new("GET", "/users/42", None, &headers, None).with_route_pattern(None);
        assert!(none.path_params.is_empty());
        let mismatch = RequestData::new("GET", "/orders/42", None, &headers, None)
            .with_route_pattern(Some("/users/:id"));
        assert!(mismatch.path_params.is_empty());
    }

    // Issue #1040: the same first-value rule as `RequestContext`, pinned on this projection too.
    // Only the integration test covered it before, so flipping `.first()` to `.last()` here alone
    // would have left every unit test green.
    #[test]
    fn request_data_takes_the_first_value_of_a_repeated_header() {
        let data = RequestData::new(
            "GET",
            "/x",
            None,
            &hdrs(&[("X-Id", &["a", "b"]), ("X-Empty", &[])]),
            None,
        );
        assert_eq!(data.get("headers.x-id"), Some("a".to_string()));
        assert_eq!(
            data.get("headers.x-empty"),
            None,
            "a name with no values is absent, not present as an empty string"
        );
    }

    #[test]
    fn test_request_data_get() {
        let data = create_test_request_data();

        assert_eq!(data.get("path"), Some("/users/123".to_string()));
        assert_eq!(data.get("method"), Some("POST".to_string()));
        assert_eq!(data.get("query.name"), Some("John".to_string()));
        assert_eq!(data.get("query.age"), Some("30".to_string()));
        assert_eq!(
            data.get("headers.content-type"),
            Some("application/json".to_string())
        );
        assert_eq!(
            data.get("headers.x-request-id"),
            Some("req-12345".to_string())
        );
        assert_eq!(data.get("pathParams.id"), Some("123".to_string()));
        assert_eq!(data.get("body"), Some(r#"{"action": "test"}"#.to_string()));
    }

    #[test]
    fn test_process_template_path() {
        let data = create_test_request_data();
        let template = r#"{"path": "${request.path}"}"#;
        let result = process_template(template, &data);
        assert_eq!(result, r#"{"path": "/users/123"}"#);
    }

    #[test]
    fn test_process_template_query() {
        let data = create_test_request_data();
        let template = r#"{"name": "${request.query.name}", "age": "${request.query.age}"}"#;
        let result = process_template(template, &data);
        assert_eq!(result, r#"{"name": "John", "age": "30"}"#);
    }

    #[test]
    fn test_process_template_headers() {
        let data = create_test_request_data();
        let template = r#"{"requestId": "${request.headers.x-request-id}"}"#;
        let result = process_template(template, &data);
        assert_eq!(result, r#"{"requestId": "req-12345"}"#);
    }

    #[test]
    fn test_process_template_path_params() {
        let data = create_test_request_data();
        let template = r#"{"userId": "${request.pathParams.id}"}"#;
        let result = process_template(template, &data);
        assert_eq!(result, r#"{"userId": "123"}"#);
    }

    #[test]
    fn test_process_template_multiple() {
        let data = create_test_request_data();
        let template = r#"{"method": "${request.method}", "path": "${request.path}", "name": "${request.query.name}"}"#;
        let result = process_template(template, &data);
        assert_eq!(
            result,
            r#"{"method": "POST", "path": "/users/123", "name": "John"}"#
        );
    }

    #[test]
    fn test_process_template_missing_variable() {
        let data = create_test_request_data();
        let template = r#"{"missing": "${request.query.nonexistent}"}"#;
        let result = process_template(template, &data);
        assert_eq!(result, r#"{"missing": ""}"#);
    }

    #[test]
    fn test_process_template_no_variables() {
        let data = create_test_request_data();
        let template = r#"{"static": "value"}"#;
        let result = process_template(template, &data);
        assert_eq!(result, r#"{"static": "value"}"#);
    }

    #[test]
    fn test_has_template_variables() {
        assert!(has_template_variables("${request.path}"));
        assert!(has_template_variables(
            "prefix ${request.query.name} suffix"
        ));
        assert!(!has_template_variables("no variables here"));
        assert!(!has_template_variables("${invalid}"));
    }

    #[test]
    fn contains_date_templates_agrees_with_applier() {
        // Detector fires exactly for the tokens the applier rewrites (issue #703) — otherwise a body
        // the applier would change could be wrongly fast-pathed, or vice versa.
        for tok in [
            "{{NOW}}",
            "x {{DAYS+7}} y",
            "{{DAYS-3}}",
            "{{MONTHS+2}}",
            "{{MONTHS-1}}",
        ] {
            assert!(contains_date_templates(tok), "should detect {tok}");
            assert_ne!(
                apply_date_templates(tok),
                tok,
                "applier should rewrite {tok}"
            );
        }
        // No date token: detector is quiet and the applier is identity — including a literal `{{` and
        // handlebars-style tokens that are not date tokens.
        for s in [
            "no tokens",
            "a literal {{ brace",
            "{{ helper arg }}",
            "${request.path}",
            "{{DAYS}}",
        ] {
            assert!(!contains_date_templates(s), "should not detect {s}");
            assert_eq!(
                apply_date_templates(s),
                s,
                "applier should leave {s} unchanged"
            );
        }
    }

    // Issue #195: relative-date template expansion.
    use chrono::{DateTime, Months, Utc};

    fn parse_rfc3339(s: &str) -> DateTime<Utc> {
        DateTime::parse_from_rfc3339(s)
            .expect("date template must produce valid RFC3339")
            .with_timezone(&Utc)
    }

    #[test]
    fn date_tpl_days_zero_is_today() {
        let out = apply_date_templates("{{DAYS+0}}");
        assert_eq!(parse_rfc3339(&out).date_naive(), Utc::now().date_naive());
    }

    #[test]
    fn date_tpl_days_plus_offsets_by_days() {
        let out = apply_date_templates("{{DAYS+5}}");
        let expected = (Utc::now() + chrono::Duration::days(5)).date_naive();
        assert_eq!(parse_rfc3339(&out).date_naive(), expected);
    }

    #[test]
    fn date_tpl_months_plus_offsets_by_months() {
        let out = apply_date_templates("{{MONTHS+1}}");
        let expected = (Utc::now() + Months::new(1)).date_naive();
        assert_eq!(parse_rfc3339(&out).date_naive(), expected);
    }

    #[test]
    fn date_tpl_now_is_parseable() {
        let out = apply_date_templates("{{NOW}}");
        // Within a second of now.
        let delta = (Utc::now() - parse_rfc3339(&out)).num_seconds().abs();
        assert!(delta <= 2, "{{NOW}} should be ~now, delta={delta}s");
    }

    #[test]
    fn date_tpl_no_tokens_unchanged() {
        let body = r#"{"plain":"value","n":42}"#;
        assert_eq!(apply_date_templates(body), body);
    }

    #[test]
    fn date_tpl_mixed_resolves_dates_leaves_request_vars() {
        let body = r#"{"exp":"{{DAYS+5}}","who":"${request.path}"}"#;
        let out = apply_date_templates(body);
        assert!(!out.contains("{{DAYS+5}}"), "date token must be expanded");
        assert!(
            out.contains("${request.path}"),
            "only date tokens are expanded; other content (e.g. ${{...}}) is left untouched"
        );
    }

    #[test]
    fn date_tpl_multiple_tokens_in_one_body() {
        let out = apply_date_templates(r#"{"a":"{{DAYS+1}}","b":"{{MONTHS+2}}","c":"{{NOW}}"}"#);
        assert!(!out.contains("{{"), "all date tokens expanded: {out}");
    }

    #[test]
    fn date_tpl_days_overflow_leaves_token_unchanged() {
        // Parses as i64 but overflows the date range — must not panic (issue #195 no-panic contract).
        let body = "{{DAYS+9999999999999}}";
        assert_eq!(apply_date_templates(body), body);
    }

    #[test]
    fn date_tpl_months_overflow_leaves_token_unchanged() {
        let body = "{{MONTHS+4000000000}}";
        assert_eq!(apply_date_templates(body), body);
    }

    // Issue #270: past offsets.
    #[test]
    fn date_tpl_days_minus_offsets_into_past() {
        let out = apply_date_templates("{{DAYS-5}}");
        let expected = (Utc::now() - chrono::Duration::days(5)).date_naive();
        assert_eq!(parse_rfc3339(&out).date_naive(), expected);
    }

    #[test]
    fn date_tpl_months_minus_offsets_into_past() {
        let out = apply_date_templates("{{MONTHS-1}}");
        let expected = Utc::now()
            .checked_sub_months(Months::new(1))
            .expect("1 month ago is representable")
            .date_naive();
        assert_eq!(parse_rfc3339(&out).date_naive(), expected);
    }

    #[test]
    fn date_tpl_days_minus_zero_is_today() {
        let out = apply_date_templates("{{DAYS-0}}");
        assert_eq!(parse_rfc3339(&out).date_naive(), Utc::now().date_naive());
    }

    #[test]
    fn date_tpl_days_minus_overflow_leaves_token_unchanged() {
        let body = "{{DAYS-9999999999999}}";
        assert_eq!(apply_date_templates(body), body);
    }

    #[test]
    fn date_tpl_months_minus_underflow_leaves_token_unchanged() {
        // Subtractive `checked_sub_months` underflow must leave the token literal (no panic).
        let body = "{{MONTHS-4000000000}}";
        assert_eq!(apply_date_templates(body), body);
    }

    #[test]
    fn date_tpl_mixed_signs_resolve_per_occurrence() {
        let out = apply_date_templates("{{DAYS-5}}|{{DAYS+5}}");
        let parts: Vec<&str> = out.split('|').collect();
        assert_eq!(parts.len(), 2, "both tokens expand: {out}");
        assert_eq!(
            parse_rfc3339(parts[0]).date_naive(),
            (Utc::now() - chrono::Duration::days(5)).date_naive()
        );
        assert_eq!(
            parse_rfc3339(parts[1]).date_naive(),
            (Utc::now() + chrono::Duration::days(5)).date_naive()
        );
    }
}