api: add unit tests for rest utils

This commit is contained in:
Dmitriy Pleshevskiy 2022-05-15 16:12:03 +03:00
parent 284ad260a4
commit b9fdcb96d7
2 changed files with 96 additions and 0 deletions

View File

@ -32,3 +32,56 @@ impl From<Context> for domain::Context {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_create_default_context() {
let query_params = vec![];
let rest_ctx = Context::from(&query_params);
assert_eq!(rest_ctx.lang, None);
}
#[test]
fn should_get_lang_from_query_params() {
let query_params = vec![("lang", "rus")];
let rest_ctx = Context::from(&query_params);
assert_eq!(rest_ctx.lang, Some(String::from("rus")));
}
#[test]
fn should_create_domain_context_from_rest() {
let rest_ctx = Context {
lang: Some(String::from("rus")),
};
let ctx = domain::Context::from(rest_ctx);
assert_eq!(ctx.lang, domain::Lang::Rus);
let rest_ctx = Context {
lang: Some(String::from("eng")),
};
let ctx = domain::Context::from(rest_ctx);
assert_eq!(ctx.lang, domain::Lang::Eng);
}
#[test]
fn should_fallback_lang_to_default_if_lang_unsupported_or_missed() {
let rest_ctx = Context::default();
let ctx = domain::Context::from(rest_ctx);
assert_eq!(ctx.lang, domain::Lang::Rus);
let rest_ctx = Context {
lang: Some(String::from("unsupported")),
};
let ctx = domain::Context::from(rest_ctx);
assert_eq!(ctx.lang, domain::Lang::Rus);
}
}

View File

@ -50,3 +50,46 @@ fn extract_query_params(query: Option<&str>) -> Vec<QueryParam> {
})
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_extract_path_segments() {
let path = "/hello/world";
let segments = extract_path_segments(path);
assert_eq!(segments, ["hello", "world"]);
}
#[test]
fn should_extract_tralling_slash_as_empty_segment() {
let path = "/hello/world/";
let segments = extract_path_segments(path);
assert_eq!(segments, ["hello", "world", ""]);
}
#[test]
fn should_extract_query_params() {
let query_params = Some("lang=rus&keys=apple&keys=banana");
let params = extract_query_params(query_params);
assert_eq!(
params[..],
[("lang", "rus"), ("keys", "apple"), ("keys", "banana")]
);
}
#[test]
fn should_parse_whole_url() {
let url = Url::parse("/api/ingredients?lang=rus&keys=apple&keys=banana");
assert_eq!(url.path_segments(), ["api", "ingredients"]);
assert_eq!(
url.query_params()[..],
[("lang", "rus"), ("keys", "apple"), ("keys", "banana")]
)
}
}