use flow_abi::description::CallTypes;
use flow_abi::{Catalog, Json};
use flow_toolkit::{Context, Encoded, Int};
use flow_types::{Body, Decl, DeclId, Type};
use crate::test_types::{catalog, local, record, signature, spec};
fn json(text: &str) -> Json {
flow_abi::parse(text, &flow_abi::Limits::default()).unwrap()
}
fn items(json: &Json) -> &[Json] {
let Json::Array(items) = json else {
panic!("not an array: {}", json.canonical())
};
items
}
fn text(json: &Json) -> &str {
let Json::String(text) = json else { panic!() };
text
}
const NOT_ONE: &str = "does not bind exactly one type parameter";
fn declarations(json: &Json) -> (Catalog, Vec<String>) {
let Json::Object(all) = json else { panic!() };
let keys: Vec<String> = all.iter().map(|(key, _)| key.clone()).collect();
let decls = all
.iter()
.map(|(_, declaration)| {
let name = text(declaration.get("name").unwrap());
let doc = match declaration.get("doc") {
Some(Json::String(doc)) => Some(doc.clone()),
_ => None,
};
let built = match text(declaration.get("kind").unwrap()) {
"record" => {
let fields: Vec<(String, Type)> = items(declaration.get("fields").unwrap())
.iter()
.map(|field| {
(
text(field.get("name").unwrap()).to_owned(),
term(field.get("type").unwrap(), &keys),
)
})
.collect();
let fields: Vec<(&str, Type)> = fields
.iter()
.map(|(name, ty)| (name.as_str(), ty.clone()))
.collect();
record(name, &fields, &[])
}
kind => {
assert_eq!(kind, "newtype", "a vector declares a record or a newtype");
Decl {
body: Body::Newtype(term(declaration.get("base").unwrap(), &keys)),
..record(name, &[], &[])
}
}
};
Decl {
doc,
identity: local(name),
..built
}
})
.collect();
(catalog(decls), keys)
}
fn term(named: &Json, keys: &[String]) -> Type {
if let Json::String(name) = named {
if name == "Int" {
return Type::Int;
}
assert_eq!(name, "Text", "a vector names Int or Text");
return Type::Text;
}
let Json::Object(one) = named else { panic!() };
let [(kind, item)] = &one[..] else { panic!() };
match kind.as_str() {
"List" => Type::list(term(item, keys)),
"Option" => Type::option(term(item, keys)),
kind => {
assert_eq!(
kind, "Named",
"a vector's type is a list, an option or a named one"
);
let key = text(item.get("declaration").unwrap());
let at = keys.iter().position(|known| known == key).unwrap();
Type::Named(DeclId(at.try_into().unwrap()), Vec::new())
}
}
}
fn views(generic: &[&str], catalog: &Catalog, bindings: &[Type]) -> CallTypes {
flow_abi::call_views(catalog, &signature(generic, &[], Type::Text), bindings).unwrap()
}
fn context(generic: &[&str], views: &CallTypes) -> Result<Context, flow_toolkit::DecodeError> {
Context::try_new(
"7f3a91c04be2d5e6f708192a3b4c5d6e/root#1"
.parse()
.expect("a call key"),
&spec(&catalog(Vec::new()), generic, &[], Type::Text),
Some(views),
crate::Cancellation::default(),
)
}
fn call(generic: &[&str], catalog: &Catalog, bindings: &[Type]) -> Context {
context(generic, &views(generic, catalog, bindings)).unwrap()
}
#[test]
fn the_schema_is_the_bound_types_for_one_parameter_and_absent_for_more() {
let plain = catalog(Vec::new());
let text = call(&["T"], &plain, &[Type::Text]);
let int = call(&["T"], &plain, &[Type::Int]);
assert!(text.schema().is_some());
assert_ne!(text.schema(), int.schema(), "its binding's schema");
let several = call(&["K", "V"], &plain, &[Type::Text, Type::Int]);
assert_eq!(several.schema(), None);
}
fn decoded(context: &Context, value: &Json) -> Result<String, String> {
context
.decode::<Encoded>(&value.canonical())
.and_then(|value| context.to_json(&value))
.map_err(|error| error.to_string())
}
#[test]
fn a_generic_calls_schema_is_its_bound_types_and_decode_checks_values_against_it() {
let vectors = json(include_str!("../../conformance/context_schema.json"));
let cases = items(vectors.get("cases").unwrap());
assert_eq!(cases.len(), 4);
for case in cases {
let rule = case.get("rule").unwrap().canonical();
let empty = Json::Object(vec![]);
let (catalog, keys) = declarations(case.get("declarations").unwrap_or(&empty));
let bound = term(case.get("binding").unwrap(), &keys);
let c = call(&["T"], &catalog, &[bound]);
assert_eq!(
c.schema().map(str::to_owned),
Some(case.get("schema").unwrap().canonical()),
"{rule}"
);
for pair in items(case.get("accepts").unwrap()) {
let [value, normal] = items(pair) else {
panic!("{rule}: an accepted value and its normal form")
};
assert_eq!(decoded(&c, value), Ok(normal.canonical()), "{rule}");
}
for value in items(case.get("refuses").unwrap()) {
let reason = decoded(&c, value).unwrap_err();
assert!(!reason.is_empty(), "{rule}: {}", value.canonical());
}
}
}
#[test]
fn decode_reads_the_value_as_the_rust_type_the_tool_writes() {
let c = call(&["T"], &catalog(Vec::new()), &[Type::list(Type::Int)]);
let numbers: Vec<Int> = c.decode("[1, 2]").unwrap();
assert_eq!(numbers, vec![Int::from(1), Int::from(2)]);
let carried: Encoded = c.decode("[3, 1]").unwrap();
assert_eq!(c.to_json(&carried).unwrap(), "[3,1]");
assert_eq!(c.to_json(&numbers).unwrap(), "[1,2]");
let refused = c.decode::<Vec<Int>>(r#"[1, "two"]"#).unwrap_err();
assert!(refused.to_string().contains("[1]"), "{refused}");
assert!(
c.decode::<Vec<Int>>("[1,").is_err(),
"text that is not JSON"
);
}
#[test]
fn a_nongeneric_call_has_no_schema_and_decodes_nothing() {
let tested = Context::for_test("7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse().unwrap());
let served = Context::try_new(
"7f3a91c04be2d5e6f708192a3b4c5d6e/root#1"
.parse()
.expect("a call key"),
&spec(&catalog(Vec::new()), &[], &[], Type::Text),
None,
crate::Cancellation::default(),
)
.unwrap();
for c in [tested, served] {
assert_eq!(c.schema(), None);
assert!(decoded(&c, &json("1")).unwrap_err().contains(NOT_ONE));
assert!(
c.to_json(&Int::from(1))
.unwrap_err()
.to_string()
.contains(NOT_ONE)
);
}
}
#[test]
fn a_tool_with_several_type_parameters_names_none_of_them() {
let c = call(&["K", "V"], &catalog(Vec::new()), &[Type::Text, Type::Int]);
assert_eq!(c.schema(), None);
assert!(decoded(&c, &json("1")).unwrap_err().contains(NOT_ONE));
}
#[test]
fn a_binding_that_cannot_cross_still_has_a_schema_but_decodes_nothing() {
let c = call(&["T"], &catalog(Vec::new()), &[Type::option(Type::Json)]);
assert!(c.schema().is_some());
assert!(decoded(&c, &json("1")).is_err());
assert!(decoded(&c, &json("null")).is_err());
}