Debian Codegraph @

third_party/rust/unic-langid-impl/tests/fixtures.rs

raw
1 use std::convert::TryInto;
2 use std::error::Error;
3 use std::fs::File;
4 use std::path::Path;
5
6 use unic_langid_impl::LanguageIdentifier;
7
8 use serde::{Deserialize, Serialize};
9
10 #[derive(Serialize, Deserialize)]
11 struct LangIdTestInputData {
12 string: String,
13 }
14
15 #[derive(Serialize, Deserialize, Debug)]
16 struct LangIdTestOutputObject {
17 language: Option<String>,
18 script: Option<String>,
19 region: Option<String>,
20 #[serde(default)]
21 variants: Vec<String>,
22 }
23
24 #[derive(Serialize, Deserialize, Debug)]
25 #[serde(untagged)]
26 enum LangIdTestOutput {
27 String(String),
28 Object(LangIdTestOutputObject),
29 }
30
31 #[derive(Serialize, Deserialize)]
32 struct LangIdTestSet {
33 input: LangIdTestInputData,
34 output: LangIdTestOutput,
35 }
36
37 fn read_langid_testsets<P: AsRef<Path>>(path: P) -> Result<Vec<LangIdTestSet>, Box<dyn Error>> {
38 let file = File::open(path)?;
39 let sets = serde_json::from_reader(file)?;
40 Ok(sets)
41 }
42
43 fn test_langid_fixtures(path: &str) {
44 let tests = read_langid_testsets(path).unwrap();
45
46 for test in tests {
47 let s = test.input.string;
48
49 let langid: LanguageIdentifier = s.parse().expect("Parsing failed.");
50
51 match test.output {
52 LangIdTestOutput::Object(o) => {
53 let expected = LanguageIdentifier::from_parts(
54 o.language.try_into().unwrap(),
55 o.script.as_ref().map(|s| s.parse().unwrap()),
56 o.region.as_ref().map(|r| r.parse().unwrap()),
57 o.variants
58 .iter()
59 .map(|s| s.parse().unwrap())
60 .collect::<Vec<_>>()
61 .as_ref(),
62 );
63 assert_eq!(langid, expected);
64 }
65 LangIdTestOutput::String(s) => {
66 assert_eq!(langid.to_string(), s);
67 }
68 }
69 }
70 }
71
72 #[test]
73 fn parse() {
74 test_langid_fixtures("./tests/fixtures/parsing.json");
75 }