api: add lang and inmemory tests

This commit is contained in:
Dmitriy Pleshevskiy 2022-05-10 00:09:47 +03:00
parent 39808b8bda
commit 830ea2b9de
4 changed files with 92 additions and 7 deletions

View File

@ -1,6 +1,30 @@
use super::types;
use crate::repo::ingredient::IngredientRepo;
pub fn execute(repo: impl IngredientRepo) -> Vec<types::Ingredient> {
pub fn execute(repo: &impl IngredientRepo) -> Vec<types::Ingredient> {
repo.get_ingredients()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::ingredient::types::Lang;
#[test]
fn should_return_all_ingredients() {
let repo = crate::repo::ingredient::InMemoryIngredientRepo::new();
let res = execute(&repo);
match res.as_slice() {
[first, second] => {
assert_eq!(first.key, String::from("apple"));
assert_eq!(first.lang, Lang::Rus);
assert_eq!(first.name, String::from("Яблоко"));
assert_eq!(second.key, String::from("salt"));
assert_eq!(second.lang, Lang::Rus);
assert_eq!(second.name, String::from("Соль"));
}
_ => unimplemented!(),
}
}
}

View File

@ -1,12 +1,32 @@
#[derive(Debug, Serialize)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize)]
pub enum Lang {
Rus,
#[allow(dead_code)]
Eng,
}
#[derive(Debug, Clone, Serialize)]
pub struct Ingredient {
key: String,
pub key: String,
pub lang: Lang,
pub name: String,
}
impl From<&db::data::Ingredient> for Ingredient {
fn from(db: &db::data::Ingredient) -> Self {
Self {
key: db.key.to_string(),
}
Self::from((db, Lang::Rus))
}
}
impl From<(&db::data::Ingredient, Lang)> for Ingredient {
fn from((db, lang): (&db::data::Ingredient, Lang)) -> Self {
let key = db.key.to_string();
let name = match lang {
Lang::Rus => db.translates.ru.to_string(),
Lang::Eng => db.translates.en.unwrap().to_string(),
};
Self { key, lang, name }
}
}

View File

@ -11,3 +11,44 @@ impl IngredientRepo for StaticIngredientRepo {
db::INGREDIENTS.iter().map(From::from).collect::<Vec<_>>()
}
}
#[cfg(test)]
pub struct InMemoryIngredientRepo {
pub ingredients: Vec<db::data::Ingredient>,
}
#[cfg(test)]
impl InMemoryIngredientRepo {
pub fn new() -> Self {
Self {
ingredients: vec![
db::data::Ingredient {
key: "apple",
translates: db::data::IngredientTranslate {
ru: "Яблоко",
en: Some("Apple"),
},
},
db::data::Ingredient {
key: "salt",
translates: db::data::IngredientTranslate {
ru: "Соль",
en: Some("Salt"),
},
},
],
}
}
}
#[cfg(test)]
impl IngredientRepo for InMemoryIngredientRepo {
fn get_ingredients(&self) -> Vec<types::Ingredient> {
let langs = [types::Lang::Rus].repeat(self.ingredients.len());
self.ingredients
.iter()
.zip(langs)
.map(From::from)
.collect::<Vec<_>>()
}
}

View File

@ -16,7 +16,7 @@ pub fn start() {
handles.push(thread::spawn(move || {
for rq in server.incoming_requests() {
let repo = StaticIngredientRepo {};
let ingredients = domain::ingredient::fetch_list::execute(repo);
let ingredients = domain::ingredient::fetch_list::execute(&repo);
let data = serde_json::to_string(&ingredients).unwrap();
let response = tiny_http::Response::from_string(data);