#![allow(clippy::unwrap_used)]
use std::path::Path;
use modelith_plugin_protocol::{
HostMessage, PluginManifest, PluginMessage, RegistryEntry, RuleSet, UsageReport,
};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
fn read(name: &str) -> String {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../examples")
.join(name);
std::fs::read_to_string(path).unwrap()
}
#[test]
fn manifests_parse() {
let names = ["manifest.rules.json", "manifest.browser.json"];
let errors: Vec<String> = names
.iter()
.filter_map(|n| {
serde_json::from_str::<PluginManifest>(&read(n))
.err()
.map(|e| format!("{n}: {e}"))
})
.collect();
assert!(errors.is_empty(), "{errors:?}");
}
#[test]
fn registry_entry_parses() {
let json = read("registry-entry.json");
let result = serde_json::from_str::<RegistryEntry>(&json);
assert!(result.is_ok(), "{result:?}");
}
#[test]
fn rule_set_parses() {
let json = read("rule-set.json");
let result = serde_json::from_str::<RuleSet>(&json);
assert!(result.is_ok(), "{result:?}");
}
fn round_trip_errors<T: DeserializeOwned + Serialize>(name: &str) -> Vec<String> {
let messages: Vec<Value> = serde_json::from_str(&read(name)).unwrap();
messages
.into_iter()
.enumerate()
.filter_map(|(i, original)| {
let back = serde_json::from_value::<T>(original.clone())
.and_then(|m| serde_json::to_value(&m));
match back {
Ok(v) if v == original => None,
Ok(v) => Some(format!("{name}[{i}]: round trip changed it to {v}")),
Err(e) => Some(format!("{name}[{i}]: {e}")),
}
})
.collect()
}
#[test]
fn host_messages_round_trip() {
let name = "messages.host.json";
let errors = round_trip_errors::<HostMessage>(name);
assert!(errors.is_empty(), "{errors:?}");
}
#[test]
fn plugin_messages_round_trip() {
let name = "messages.plugin.json";
let errors = round_trip_errors::<PluginMessage>(name);
assert!(errors.is_empty(), "{errors:?}");
}
#[test]
fn usage_reports_round_trip() {
let name = "usage-reports.json";
let errors = round_trip_errors::<UsageReport>(name);
assert!(errors.is_empty(), "{errors:?}");
}