Add integrated server

This commit is contained in:
2022-12-19 12:20:44 +01:00
parent 55516ba03a
commit d52bdbde8f
5 changed files with 542 additions and 3 deletions

View File

@ -1,6 +1,11 @@
#[cfg(feature = "embedded-server")]
use crate::server::EmbeddedServer;
use std::collections::HashMap;
use std::error::Error;
#[cfg(feature = "embedded-server")]
mod server;
/// Spell check options
#[derive(Hash, Debug, Eq, PartialEq)]
pub enum GramOpt {
@ -255,12 +260,17 @@ pub struct SuggestResult {
pub struct GrammalecteClient {
base_url: String,
#[cfg(feature = "embedded-server")]
_server: Option<EmbeddedServer>,
}
impl Default for GrammalecteClient {
fn default() -> Self {
Self {
base_url: "http://localhost:8080".to_string(),
#[cfg(feature = "embedded-server")]
_server: None,
}
}
}
@ -270,9 +280,24 @@ impl GrammalecteClient {
pub fn new(base_url: &str) -> Self {
Self {
base_url: base_url.to_string(),
#[cfg(feature = "embedded-server")]
_server: None,
}
}
/// Construct a new Grammalecte client, spinning up an associated
/// temporary web server.
///
/// Python 3.7 or higher must is required at runtime
#[cfg(feature = "embedded-server")]
pub fn start_server() -> Result<Self, Box<dyn Error>> {
let server = EmbeddedServer::start()?;
Ok(Self {
base_url: server.base_url(),
_server: Some(server),
})
}
/// Run spell check on text
pub async fn spell_check(&self, text: &str) -> Result<CheckResult, Box<dyn Error>> {
self.spell_check_with_options(text, HashMap::new()).await
@ -327,6 +352,7 @@ impl GrammalecteClient {
}
#[cfg(test)]
#[cfg(feature = "embedded-server")]
mod test {
use crate::{GramOpt, GrammalecteClient};
use std::collections::HashMap;
@ -336,7 +362,11 @@ mod test {
let _ = env_logger::builder().is_test(true).try_init();
let msg = "Les ange sont inssuportables!";
let res = GrammalecteClient::default().spell_check(msg).await.unwrap();
let res = GrammalecteClient::start_server()
.unwrap()
.spell_check(msg)
.await
.unwrap();
println!("RESULT = {:#?}", res);
}
@ -347,7 +377,8 @@ mod test {
let msg = "Bonjour !";
let mut opts = HashMap::new();
opts.insert(GramOpt::EspacesInsecables, false);
let res = GrammalecteClient::default()
let res = GrammalecteClient::start_server()
.unwrap()
.spell_check_with_options(msg, opts)
.await
.unwrap();
@ -359,7 +390,8 @@ mod test {
async fn simple_suggestion() {
let _ = env_logger::builder().is_test(true).try_init();
let res = GrammalecteClient::default()
let res = GrammalecteClient::start_server()
.unwrap()
.suggest("bonjou")
.await
.unwrap();