1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! Structure to communicate with some `LanguageTool` server through the API.
#[cfg(feature = "multithreaded")]
use crate::api::check;
use crate::{
api::{
check::{Request, Response},
languages, words,
},
error::{Error, Result},
};
#[cfg(feature = "cli")]
use clap::Args;
#[cfg(feature = "multithreaded")]
use lifetime::IntoStatic;
use reqwest::{
header::{HeaderValue, ACCEPT},
Client,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{io, path::PathBuf, time::Instant};
/// Parse `v` if valid port.
///
/// A valid port is either
/// - an empty string
/// - a 4 chars long string with each char in [0-9]
///
/// # Examples
///
/// ```
/// # use languagetool_rust::api::server::parse_port;
/// assert!(parse_port("8081").is_ok());
///
/// assert!(parse_port("").is_ok()); // No port specified, which is accepted
///
/// assert!(parse_port("abcd").is_err());
/// ```
pub fn parse_port(v: &str) -> Result<String> {
if v.is_empty() || (v.len() == 4 && v.chars().all(char::is_numeric)) {
return Ok(v.to_string());
}
Err(Error::InvalidValue(
"The value should be a 4 characters long string with digits only".to_string(),
))
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
/// A Java property file (one `key = value` entry per line) with values listed
/// below.
pub struct ConfigFile {
/// Maximum text length, longer texts will cause an error (optional).
pub max_text_length: Option<isize>,
/// Maximum text length, applies even to users with a special secret 'token'
/// parameter (optional).
pub max_text_hard_length: Option<isize>,
/// Secret JWT token key, if set by user and valid, maxTextLength can be
/// increased by the user (optional).
pub secret_token_key: Option<isize>,
/// Maximum time in milliseconds allowed per check (optional).
pub max_check_time_millis: Option<isize>,
/// Checking will stop with error if there are more rules matches per word
/// (optional).
pub max_errors_per_word_rate: Option<isize>,
/// Only this many spelling errors will have suggestions for performance
/// reasons (optional, affects Hunspell-based languages only).
pub max_spelling_suggestions: Option<isize>,
/// Maximum number of threads working in parallel (optional).
pub max_check_threads: Option<isize>,
/// Size of internal cache in number of sentences (optional, default: 0).
pub cache_size: Option<isize>,
/// How many seconds sentences are kept in cache (optional, default: 300 if
/// 'cacheSize' is set).
pub cache_ttl_seconds: Option<isize>,
/// Maximum number of requests per requestLimitPeriodInSeconds (optional).
pub request_limit: Option<isize>,
/// Maximum aggregated size of requests per requestLimitPeriodInSeconds
/// (optional).
pub request_limit_in_bytes: Option<isize>,
/// Maximum number of timeout request (optional).
pub timeout_request_limit: Option<isize>,
/// Time period to which requestLimit and timeoutRequestLimit applies
/// (optional).
pub request_limit_period_in_seconds: Option<isize>,
/// A directory with '1grams', '2grams', '3grams' sub directories which
/// contain a Lucene index each with ngram occurrence counts; activates the
/// confusion rule if supported (optional).
pub language_model: Option<PathBuf>,
/// A directory with word2vec data (optional), see <https://github.com/languagetool-org/languagetool/blob/master/languagetool-standalone/CHANGES.md#word2vec>.
pub word2vec_model: Option<PathBuf>,
/// A model file for better language detection (optional), see
/// <https://fasttext.cc/docs/en/language-identification.html>.
pub fasttext_model: Option<PathBuf>,
/// Compiled fasttext executable for language detection (optional), see
/// <https://fasttext.cc/docs/en/support.html>.
pub fasttext_binary: Option<PathBuf>,
/// Reject request if request queue gets larger than this (optional).
pub max_work_queue_size: Option<isize>,
/// A file containing rules configuration, such as .langugagetool.cfg
/// (optional).
pub rules_file: Option<PathBuf>,
/// Set to 'true' to warm up server at start, i.e. run a short check with
/// all languages (optional).
pub warm_up: Option<bool>,
/// A comma-separated list of HTTP referrers (and 'Origin' headers) that are
/// blocked and will not be served (optional).
pub blocked_referrers: Option<Vec<String>>,
/// Activate only the premium rules (optional).
pub premium_only: Option<bool>,
/// A comma-separated list of rule ids that are turned off for this server
/// (optional).
pub disable_rule_ids: Option<Vec<String>>,
/// Set to 'true' to enable caching of internal pipelines to improve
/// performance.
pub pipeline_caching: Option<bool>,
/// Cache size if 'pipelineCaching' is set.
pub max_pipeline_pool_size: Option<isize>,
/// Time after which pipeline cache items expire.
pub pipeline_expire_time_in_seconds: Option<isize>,
/// Set to 'true' to fill pipeline cache on start (can slow down start a
/// lot).
pub pipeline_prewarming: Option<bool>,
/// Spellcheck-only languages: You can add simple spellcheck-only support
/// for languages that LT doesn't support by defining two optional
/// properties:
///
/// * 'lang-xx' - set name of the language, use language code instead of
/// 'xx', e.g. lang-tr=Turkish;
///
/// * 'lang-xx-dictPath' - absolute path to the hunspell .dic file, use
/// language code instead of 'xx', e.g. lang-tr-dictPath=/path/to/tr.dic.
/// Note that the same directory also needs to contain a common_words.txt
/// file with the most common 10,000 words (used for better language
/// detection).
pub spellcheck_only: Option<std::collections::HashMap<String, String>>,
}
impl ConfigFile {
/// Write the config file in a `key = value` format.
pub fn write_to<T: io::Write>(&self, w: &mut T) -> io::Result<()> {
let json = serde_json::to_value(self.clone()).unwrap();
let m = json.as_object().unwrap();
for (key, value) in m.iter() {
match value {
Value::Bool(b) => writeln!(w, "{key}={b}")?,
Value::Number(n) => writeln!(w, "{key}={n}")?,
Value::String(s) => writeln!(w, "{key}=\"{s}\"")?,
Value::Array(a) => {
writeln!(
w,
"{}=\"{}\"",
key,
a.iter()
.map(std::string::ToString::to_string)
.collect::<Vec<String>>()
.join(",")
)?
},
Value::Object(o) => {
for (key, value) in o.iter() {
writeln!(w, "{key}=\"{value}\"")?
}
},
Value::Null => writeln!(w, "# {key}=")?,
}
}
Ok(())
}
}
impl Default for ConfigFile {
fn default() -> Self {
Self {
max_text_length: None,
max_text_hard_length: None,
secret_token_key: None,
max_check_time_millis: None,
max_errors_per_word_rate: None,
max_spelling_suggestions: None,
max_check_threads: None,
cache_size: Some(0),
cache_ttl_seconds: Some(300),
request_limit: None,
request_limit_in_bytes: None,
timeout_request_limit: None,
request_limit_period_in_seconds: None,
language_model: None,
word2vec_model: None,
fasttext_model: None,
fasttext_binary: None,
max_work_queue_size: None,
rules_file: None,
warm_up: None,
blocked_referrers: None,
premium_only: None,
disable_rule_ids: None,
pipeline_caching: None,
max_pipeline_pool_size: None,
pipeline_expire_time_in_seconds: None,
pipeline_prewarming: None,
spellcheck_only: None,
}
}
}
/// Server parameters that are to be used when instantiating a `LanguageTool`
/// server.
#[cfg_attr(feature = "cli", derive(Args))]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[non_exhaustive]
pub struct ServerParameters {
/// A Java property file (one `key = value` entry per line) with values
/// listed in [`ConfigFile`].
#[cfg_attr(feature = "cli", clap(long))]
config: Option<PathBuf>,
/// Port to bind to, defaults to 8081 if not specified.
#[cfg_attr(feature = "cli", clap(short = 'p', long, name = "PRT", default_value = "8081", value_parser = parse_port))]
port: String,
/// Allow this server process to be connected from anywhere; if not set, it
/// can only be connected from the computer it was started on.
#[cfg_attr(feature = "cli", clap(long))]
public: bool,
/// set the Access-Control-Allow-Origin header in the HTTP response, used
/// for direct (non-proxy) JavaScript-based access from browsers. Example: --allow-origin "https://my-website.org".
/// Don't set a parameter for `*`, i.e. access from all websites.
#[cfg_attr(feature = "cli", clap(long, name = "ORIGIN"))]
#[allow(rustdoc::bare_urls)]
allow_origin: Option<String>,
/// In case of exceptions, log the input text (up to 500 characters).
#[cfg_attr(feature = "cli", clap(short = 'v', long))]
verbose: bool,
/// A directory with '1grams', '2grams', '3grams' sub directories (per
/// language) which contain a Lucene index (optional, overwrites
/// 'languageModel' parameter in properties files).
#[cfg_attr(feature = "cli", clap(long))]
#[serde(rename = "languageModel")]
language_model: Option<PathBuf>,
/// A directory with word2vec data (optional), see <https://github.com/languagetool-org/languagetool/blob/master/languagetool-standalone/CHANGES.md#word2vec>.
#[cfg_attr(feature = "cli", clap(long))]
#[serde(rename = "word2vecModel")]
word2vec_model: Option<PathBuf>,
/// Activate the premium rules even when user has no username/password -
/// useful for API servers.
#[cfg_attr(feature = "cli", clap(long))]
#[serde(rename = "premiumAlways")]
premium_always: bool,
}
impl Default for ServerParameters {
fn default() -> Self {
Self {
config: None,
port: "8081".to_string(),
public: false,
allow_origin: None,
verbose: false,
language_model: None,
word2vec_model: None,
premium_always: false,
}
}
}
/// Hostname and (optional) port to connect to a `LanguageTool` server.
///
/// To use your local server instead of online api, set:
/// * `hostname` to "http://localhost"
/// * `port` to "8081"
///
/// if you used the default configuration to start the server.
#[cfg_attr(feature = "cli", derive(Args))]
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub struct ServerCli {
/// Server's hostname.
#[cfg_attr(
feature = "cli",
clap(
long,
default_value = "https://api.languagetoolplus.com",
env = "LANGUAGETOOL_HOSTNAME",
)
)]
pub hostname: String,
/// Server's port number, with the empty string referring to no specific
/// port.
#[cfg_attr(feature = "cli", clap(short = 'p', long, name = "PRT", default_value = "", value_parser = parse_port, env = "LANGUAGETOOL_PORT"))]
pub port: String,
}
impl Default for ServerCli {
fn default() -> Self {
Self {
hostname: "https://api.languagetoolplus.com".to_string(),
port: "".to_string(),
}
}
}
impl ServerCli {
/// Create a new [`ServerCli`] instance from environ variables:
/// - `LANGUAGETOOL_HOSTNAME`
/// - `LANGUAGETOOL_PORT`
///
/// If one or both environ variables are empty, an error is returned.
pub fn from_env() -> Result<Self> {
let hostname = std::env::var("LANGUAGETOOL_HOSTNAME")?;
let port = std::env::var("LANGUAGETOOL_PORT")?;
Ok(Self { hostname, port })
}
/// Create a new [`ServerCli`] instance from environ variables,
/// but defaults to [`ServerCli::default`()] if expected environ
/// variables are not set.
#[must_use]
pub fn from_env_or_default() -> Self {
ServerCli::from_env().unwrap_or_default()
}
}
/// Client to communicate with the `LanguageTool` server using async requests.
#[derive(Clone, Debug)]
pub struct ServerClient {
/// API string: hostname and, optionally, port number (see [`ServerCli`]).
pub api: String,
/// Reqwest client that can send requests to the server.
pub client: Client,
max_suggestions: isize,
}
impl From<ServerCli> for ServerClient {
#[inline]
fn from(cli: ServerCli) -> Self {
Self::new(cli.hostname.as_str(), cli.port.as_str())
}
}
impl ServerClient {
/// Construct a new server client using hostname and (optional) port
///
/// An empty string is accepted as empty port.
/// For port validation, please use [`parse_port`] as this constructor does
/// not check anything.
#[must_use]
pub fn new(hostname: &str, port: &str) -> Self {
let api = if port.is_empty() {
format!("{hostname}/v2")
} else {
format!("{hostname}:{port}/v2")
};
let client = Client::new();
Self {
api,
client,
max_suggestions: -1,
}
}
/// Set the maximum number of suggestions (defaults to -1), a negative
/// number will keep all replacement suggestions.
#[must_use]
pub fn with_max_suggestions(mut self, max_suggestions: isize) -> Self {
self.max_suggestions = max_suggestions;
self
}
/// Convert a [`ServerCli`] into a proper (usable) client.
#[must_use]
pub fn from_cli(cli: ServerCli) -> Self {
cli.into()
}
/// Send a check request to the server and await for the response.
pub async fn check(&self, request: &Request<'_>) -> Result<Response> {
let resp = self
.client
.post(format!("{0}/check", self.api))
.header(ACCEPT, HeaderValue::from_static("application/json"))
.form(request)
.send()
.await
.map_err(Error::Reqwest)?;
match resp.error_for_status_ref() {
Ok(_) => {
resp.json::<Response>()
.await
.map_err(Into::into)
.map(|mut resp| {
if self.max_suggestions > 0 {
let max = self.max_suggestions as usize;
resp.matches.iter_mut().for_each(|m| {
let len = m.replacements.len();
if max < len {
m.replacements[max] =
format!("... ({} not shown)", len - max).into();
m.replacements.truncate(max + 1);
}
});
}
resp
})
},
Err(_) => Err(Error::InvalidRequest(resp.text().await?)),
}
}
/// Send multiple check requests and join them into a single response.
///
/// # Error
///
/// If any of the requests has `self.text` field which is none, or
/// if zero request is provided.
#[cfg(feature = "multithreaded")]
pub async fn check_multiple_and_join<'source>(
&self,
requests: Vec<Request<'source>>,
) -> Result<check::ResponseWithContext<'source>> {
use std::borrow::Cow;
if requests.is_empty() {
return Err(Error::InvalidRequest(
"no request; cannot join zero request".to_string(),
));
}
let tasks = requests
.into_iter()
.map(|r| r.into_static())
.map(|request| {
let server_client = self.clone();
tokio::spawn(async move {
let response = server_client.check(&request).await?;
let text = request.text.ok_or_else(|| {
Error::InvalidRequest(
"missing text field; cannot join requests with data annotations"
.to_string(),
)
})?;
Result::<(Cow<'static, str>, Response)>::Ok((text, response))
})
});
let mut response_with_context: Option<check::ResponseWithContext> = None;
for task in tasks {
let (text, response) = task.await.unwrap()?;
response_with_context = Some(match response_with_context {
Some(resp) => resp.append(check::ResponseWithContext::new(text, response)),
None => check::ResponseWithContext::new(text, response),
})
}
Ok(response_with_context.unwrap())
}
/// Send multiple check requests and join them into a single response,
/// without any context.
///
/// # Error
///
/// If any of the requests has `self.text` or `self.data` field which is
/// [`None`].
#[cfg(feature = "multithreaded")]
pub async fn check_multiple_and_join_without_context(
&self,
requests: Vec<Request<'_>>,
) -> Result<check::Response> {
let mut response: Option<check::Response> = None;
let tasks = requests
.into_iter()
.map(|r| r.into_static())
.map(|request| {
let server_client = self.clone();
tokio::spawn(async move {
let response = server_client.check(&request).await?;
Result::<Response>::Ok(response)
})
});
// Make requests in sequence
for task in tasks {
let resp = task.await.unwrap()?;
response = Some(match response {
Some(r) => r.append(resp),
None => resp,
})
}
Ok(response.unwrap())
}
/// Send a check request to the server, await for the response and annotate
/// it.
#[cfg(feature = "annotate")]
pub async fn annotate_check(
&self,
request: &Request<'_>,
origin: Option<&str>,
color: bool,
) -> Result<String> {
let text = request.get_text();
let resp = self.check(request).await?;
Ok(resp.annotate(text.as_ref(), origin, color))
}
/// Send a languages request to the server and await for the response.
pub async fn languages(&self) -> Result<languages::Response> {
let resp = self
.client
.get(format!("{}/languages", self.api))
.send()
.await
.map_err(Error::Reqwest)?;
match resp.error_for_status_ref() {
Ok(_) => resp.json::<languages::Response>().await.map_err(Into::into),
Err(_) => Err(Error::InvalidRequest(resp.text().await?)),
}
}
/// Send a words request to the server and await for the response.
pub async fn words(&self, request: &words::Request) -> Result<words::Response> {
let resp = self
.client
.get(format!("{}/words", self.api))
.header(ACCEPT, HeaderValue::from_static("application/json"))
.query(request)
.send()
.await
.map_err(Error::Reqwest)?;
match resp.error_for_status_ref() {
Ok(_) => resp.json::<words::Response>().await.map_err(Error::Reqwest),
Err(_) => Err(Error::InvalidRequest(resp.text().await?)),
}
}
/// Send a words/add request to the server and await for the response.
pub async fn words_add(&self, request: &words::add::Request) -> Result<words::add::Response> {
let resp = self
.client
.post(format!("{}/words/add", self.api))
.header(ACCEPT, HeaderValue::from_static("application/json"))
.form(request)
.send()
.await
.map_err(Error::Reqwest)?;
match resp.error_for_status_ref() {
Ok(_) => {
resp.json::<words::add::Response>()
.await
.map_err(Error::Reqwest)
},
Err(_) => Err(Error::InvalidRequest(resp.text().await?)),
}
}
/// Send a words/delete request to the server and await for the response.
pub async fn words_delete(
&self,
request: &words::delete::Request,
) -> Result<words::delete::Response> {
let resp = self
.client
.post(format!("{}/words/delete", self.api))
.header(ACCEPT, HeaderValue::from_static("application/json"))
.form(request)
.send()
.await
.map_err(Error::Reqwest)?;
match resp.error_for_status_ref() {
Ok(_) => {
resp.json::<words::delete::Response>()
.await
.map_err(Error::Reqwest)
},
Err(_) => Err(Error::InvalidRequest(resp.text().await?)),
}
}
/// Ping the server and return the elapsed time in milliseconds if the
/// server responded.
pub async fn ping(&self) -> Result<u128> {
let start = Instant::now();
self.client.get(&self.api).send().await?;
Ok((Instant::now() - start).as_millis())
}
}
impl Default for ServerClient {
fn default() -> Self {
Self::from_cli(ServerCli::default())
}
}
impl ServerClient {
/// Create a new [`ServerClient`] instance from environ variables.
///
/// See [`ServerCli::from_env`] for more details.
pub fn from_env() -> Result<Self> {
Ok(Self::from_cli(ServerCli::from_env()?))
}
/// Create a new [`ServerClient`] instance from environ variables,
/// but defaults to [`ServerClient::default`] if expected environ
/// variables are not set.
#[must_use]
pub fn from_env_or_default() -> Self {
Self::from_cli(ServerCli::from_env_or_default())
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use assert_matches::assert_matches;
use super::ServerClient;
use crate::{api::check::Request, error::Error};
fn get_testing_server_client() -> ServerClient {
ServerClient::new("http://localhost", "8010")
}
#[tokio::test]
async fn test_server_ping() {
let client = get_testing_server_client();
assert!(
client.ping().await.is_ok(),
"\n----------------------------------------------------------------------------------------------\n\
IMPORTANT: Please ensure that there is a local LanguageTool service running on port 8010.\n\
----------------------------------------------------------------------------------------------\n"
);
}
#[tokio::test]
async fn test_server_check_text() {
let client = get_testing_server_client();
let req = Request::default().with_text("je suis une poupee");
assert!(client.check(&req).await.is_ok());
// Too long
let req = Request::default().with_text("Repeat ".repeat(1500));
assert_matches!(client.check(&req).await, Err(Error::InvalidRequest(_)));
}
#[tokio::test]
async fn test_server_check_data() {
let client = get_testing_server_client();
let req = Request::default()
.with_data_str("{\"annotation\":[{\"text\": \"je suis une poupee\"}]}")
.unwrap();
assert!(client.check(&req).await.is_ok());
// Too long
let req = Request::default()
.with_data_str(&format!(
"{{\"annotation\":[{{\"text\": \"{}\"}}]}}",
"repeat".repeat(5000)
))
.unwrap();
assert_matches!(client.check(&req).await, Err(Error::InvalidRequest(_)));
}
#[tokio::test]
async fn test_server_check_multiple_and_join() {
const TEXT: &str = "I am a doll.\nBut what are you?";
let client = get_testing_server_client();
let requests = Request::default()
.with_language("en-US".into())
.with_text(TEXT)
.split(20, "\n");
let resp = client.check_multiple_and_join(requests).await.unwrap();
assert_eq!(resp.text, Cow::from(TEXT));
assert_eq!(resp.text_length, TEXT.len());
#[cfg(feature = "unstable")]
assert!(!resp.response.warnings.as_ref().unwrap().incomplete_results);
assert_eq!(resp.response.iter_matches().next(), None);
assert_eq!(resp.response.language.name, "English (US)");
// Fails when trying to use it without text
let requests = vec![Request::default().with_language("en-US".into())];
assert!(client.check_multiple_and_join(requests).await.is_err());
let requests = vec![Request::default()
.with_language("en-US".into())
.with_data_str("{\"annotation\":[{\"text\": \"je suis une poupee\"}]}")
.unwrap()];
assert!(client.check_multiple_and_join(requests).await.is_err());
}
#[tokio::test]
async fn test_server_check_multiple_and_join_without_context() {
let client = get_testing_server_client();
let requests = vec![Request::default()
.with_language("en-US".into())
.with_data_str("{\"annotation\":[{\"text\": \"I am a doll\"}]}")
.unwrap()];
let resp = client
.check_multiple_and_join_without_context(requests)
.await
.unwrap();
#[cfg(feature = "unstable")]
assert!(!resp.warnings.as_ref().unwrap().incomplete_results);
assert_eq!(resp.iter_matches().next(), None);
assert_eq!(resp.language.name, "English (US)");
let requests = vec![Request::default()
.with_language("en-US".into())
.with_text("I am a doll.")];
let resp = client
.check_multiple_and_join_without_context(requests)
.await
.unwrap();
assert_eq!(resp.iter_matches().next(), None);
// Fails when trying to use it without text or data
let requests = vec![Request::default().with_language("en-US".into())];
assert!(client.check_multiple_and_join(requests).await.is_err());
}
#[cfg(feature = "annotate")]
#[tokio::test]
async fn test_server_annotate() {
let client = get_testing_server_client();
let req = Request::default()
.with_text("Who are you?")
.with_language("en-US".into());
let annotated = client
.annotate_check(&req, Some("origin"), false)
.await
.unwrap();
assert_eq!(
annotated,
"No errors were found in provided text".to_string()
);
let req = Request::default()
.with_text("Who ar you?")
.with_language("en-US".into());
let annotated = client
.annotate_check(&req, Some("origin"), false)
.await
.unwrap();
assert!(
annotated.starts_with("error[MORFOLOGIK_RULE_EN_US]: Possible spelling mistake found.")
);
assert!(annotated.contains("^^ Possible spelling mistake"));
}
#[tokio::test]
async fn test_server_languages() {
let client = get_testing_server_client();
assert!(client.languages().await.is_ok());
}
}