use crate::util::FastMap;
use crate::util::{comma_joined, parse_query_string};
use regex::Regex;
use std::sync::OnceLock;
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()
})
}
#[derive(Debug, Clone, Default)]
pub struct RequestData {
pub method: String,
pub path: String,
pub query: crate::util::OrderedMap<String, String>,
pub headers: FastMap<String, String>,
pub path_params: FastMap<String, String>,
pub body: String,
}
impl RequestData {
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("")));
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(),
}
}
#[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
}
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,
}
}
}
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 {
return FastMap::default();
}
}
params
}
pub fn process_template(template: &str, request_data: &RequestData) -> String {
process_template_mapped(template, request_data, |value| value)
}
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()
}
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())
});
}
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())
}
#[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))
}
static DOUBLE_BRACE_FINDER: std::sync::LazyLock<memchr::memmem::Finder<'static>> =
std::sync::LazyLock::new(|| memchr::memmem::Finder::new(b"{{"));
pub fn apply_date_templates(body: &str) -> String {
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: ®ex::Captures| {
match caps[2].parse::<i64>() {
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: ®ex::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, |_: ®ex::Captures| now.to_rfc3339())
.into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
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()]));
}
#[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(&[]);
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()));
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());
}
#[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() {
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}"
);
}
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"
);
}
}
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}}");
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() {
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);
}
#[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() {
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()
);
}
}