Skip to content

Commit

Permalink
Created translate_from_english()
Browse files Browse the repository at this point in the history
  • Loading branch information
Mintype committed Apr 6, 2024
1 parent b1278e9 commit 4f33630
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
18 changes: 14 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
use reqwest;
use serde_json::Value;

pub fn translate(text: &str, from: &str, to: &str) -> String {
// placeholder
text.to_string()
text.to_string()
}

pub fn translate_to_english(text: &str) -> String {
// placeholder
text.to_string()
}

pub fn translate_from_english(text: &str, to: &str) -> String {
// placeholder
text.to_string()
pub async fn translate_from_english(text: &str, to: &str) -> Result<String, Box<dyn std::error::Error>> {
let url = format!(
"https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl={}&dt=t&q={}",
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)
}
18 changes: 14 additions & 4 deletions tests/translate_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,26 @@ fn test_translate_to_english() {
assert_eq!(translated_text, "Hello World");
}

#[test]
fn test_translate_from_english() {
#[tokio::test]
async fn test_translate_from_english() {
// Prepare the input parameters
let text = "Hello World";
let to = "de";

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

// Check if the result is as expected
assert_eq!(translated_text, "Hallo Welt");
match translated_text_result {
Ok(translated_text) => {
assert_eq!(translated_text, "Hallo Welt");
},
Err(err) => {
// Print out the error message
eprintln!("Error: {}", err);
// Fail the test
assert!(false);
}
}
}

0 comments on commit 4f33630

Please sign in to comment.