diff --git a/api/src/rest/context.rs b/api/src/rest/context.rs index aaafb1c..09c8e67 100644 --- a/api/src/rest/context.rs +++ b/api/src/rest/context.rs @@ -32,3 +32,56 @@ impl From 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); + } +} diff --git a/api/src/rest/types.rs b/api/src/rest/types.rs index 95f5b04..1978d27 100644 --- a/api/src/rest/types.rs +++ b/api/src/rest/types.rs @@ -50,3 +50,46 @@ fn extract_query_params(query: Option<&str>) -> Vec { }) .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")] + ) + } +}