Skip to content

Commit

Permalink
Coded translate_to_english() function.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mintype committed Apr 6, 2024
1 parent 0d942b0 commit 169f104
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
16 changes: 13 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,19 @@ pub async fn translate(text: &str, from: &str, to: &str) -> Result<String, Box<d
Ok(translated_text)
}

pub fn translate_to_english(text: &str) -> String {
// placeholder
text.to_string()
pub async fn translate_to_english(text: &str) -> Result<String, Box<dyn std::error::Error>> {
let from = "auto";
let to = "en";

let url = format!(
"https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}",
from, to, text
);

let response = reqwest::get(&url).await?.text().await?;
let translated_text: String = serde_json::from_str::<Value>(&response)?[0][0][0].as_str().unwrap().to_string();

Ok(translated_text)
}

pub async fn translate_from_english(text: &str, to: &str) -> Result<String, Box<dyn std::error::Error>> {
Expand Down
20 changes: 15 additions & 5 deletions tests/translate_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,26 @@ async fn test_translate() {
}
}

#[test]
fn test_translate_to_english() {
#[tokio::test]
async fn test_translate_to_english() {
// Prepare the input parameters
let text = "Hallo Welt";
let text = "Estoy comiendo queso.";

// Call the function under test
let translated_text = translate_to_english(text);
let translated_text_result = translate_to_english(text).await;

// Check if the result is as expected
assert_eq!(translated_text, "Hello World");
match translated_text_result {
Ok(translated_text) => {
assert_eq!(translated_text, "I'm eating cheese.");
},
Err(err) => {
// Print out the error message
eprintln!("Error: {}", err);
// Fail the test
assert!(false);
}
}
}

#[tokio::test]
Expand Down

0 comments on commit 169f104

Please sign in to comment.