use flow_abi_testing::catalog as common;
use common::*;
use flow_abi::{
DecodeErrorKind, INPUT, Json, Limits, Mode, REBUILD, REPLY, decodable, decode, decode_text,
parse,
};
use flow_testing::on_a_small_stack;
use flow_types::Type;
use flow_value::Value;
fn problem(catalog: &flow_abi::Catalog, ty: &Type, text: &str) -> String {
refusal(catalog, ty, text).1
}
fn plan_text(steps: &str) -> String {
format!(r#"{{"steps": {steps}, "title": "t"}}"#)
}
fn first(catalog: &flow_abi::Catalog, ty: &Type, text: &str) -> (String, DecodeErrorKind) {
match decode_text(catalog, ty, text, Mode::Reply, &Limits::LANGUAGE) {
Ok(_) => panic!("{text} decodes"),
Err(error) => (error.path.to_string(), error.kind),
}
}
#[test]
fn each_refusal_is_one_problem_and_the_first_one_found_is_reported() {
use DecodeErrorKind::{Duplicate, Mismatch, Missing, Syntax, Unknown};
let catalog = catalog();
let dict = Type::dict(Type::Int, Type::Text);
let cases: &[(&Type, &str, (&str, DecodeErrorKind))] = &[
(&named(PLAN), r#"{"steps": 7"#, ("", Syntax { at: 11 })),
(
&named(PLAN),
r#"{"title": 1, "steps": [}"#,
(r#"["steps"][0]"#, Syntax { at: 23 }),
),
(
&named(PLAN),
r#"{"title": 1, "title": 2}"#,
(r#"["title"]"#, Duplicate),
),
(
&named(PLAN),
r#"{"steps": [{"a": 1, "a": 2}]}"#,
(r#"["steps"][0]["a"]"#, Duplicate),
),
(&named(PLAN), r#"{"title": 1}"#, ("steps", Missing)),
(
&named(PLAN),
r#"{"title": 1, "steps": []}"#,
("title", Mismatch),
),
(
&named(PLAN),
r#"{"steps": [], "title": null}"#,
("title", Mismatch),
),
(
&named(PLAN),
r#"{"steps": [{"owner": 1}, {"done": true}], "title": 1}"#,
("steps[0].owner", Mismatch),
),
(&Type::option(Type::Int), r#""Nada""#, ("", Unknown)),
(&dict, r#"[[1, "a"], [1, "b"]]"#, ("", Duplicate)),
(&dict, r#"[[1, 2], [1, "b"]]"#, ("[0][1]", Mismatch)),
];
for (ty, text, (path, kind)) in cases {
assert_eq!(
first(&catalog, ty, text),
((*path).to_owned(), *kind),
"{text}"
);
}
}
#[test]
fn a_missing_field_fails_to_decode_unless_it_is_an_option() {
let catalog = catalog();
assert_eq!(
refusal(&catalog, &named(PLAN), r#"{"steps": []}"#),
("title".into(), "is missing".into())
);
assert_eq!(
reread(&catalog, &named(PLAN), r#"{"steps": [], "title": "t"}"#),
r#"{"steps":[],"title":"t"}"#
);
let plan = dec_reply(&catalog, &named(PLAN), &plan_text("[]")).expect("decodes");
assert!(same(
&catalog,
&named(PLAN),
&plan,
&rec(&catalog, PLAN, vec![Value::list([]), none(), text("t")])
));
}
#[test]
fn null_is_none_for_an_option_field_and_refused_anywhere_else() {
let catalog = catalog();
assert_eq!(
reread(
&catalog,
&named(PLAN),
r#"{"steps": [], "owner": null, "title": "t"}"#
),
r#"{"steps":[],"title":"t"}"#
);
assert_eq!(
refusal(&catalog, &named(PLAN), r#"{"steps": [], "title": null}"#),
(
"title".into(),
"is null, which only an Option field may be".into()
)
);
assert_eq!(
refusal(&catalog, &Type::list(Type::option(Type::Int)), "[null]"),
(
"[0]".into(),
"is null, which only an Option field may be".into()
)
);
assert_eq!(
problem(&catalog, &Type::Int, "null"),
"should be an integer, not null"
);
}
#[test]
fn a_field_the_type_does_not_declare_is_ignored_in_a_reply_and_refused_in_input() {
let catalog = catalog();
let text = r#"{"steps": [], "title": "t", "extra": {"deep": [1, 2]}}"#;
assert_eq!(
reread(&catalog, &named(PLAN), text),
r#"{"steps":[],"title":"t"}"#
);
assert_eq!(
dec_input(&catalog, &named(PLAN), text).expect_err("refused"),
(
"extra".into(),
"is not a field of github.com/acme/plans@v1.2.0/plans.Plan".into()
)
);
let arrived = r#"{"Arrived": {"index": 1, "late": true}}"#;
assert_eq!(
reread(&catalog, &named(STATUS), arrived),
r#"{"Arrived":{"index":1}}"#
);
assert_eq!(
dec_input(&catalog, &named(STATUS), arrived)
.expect_err("refused")
.0,
"Arrived.late"
);
assert!(dec_input(&catalog, &named(PLAN), &plan_text("[]")).is_ok());
}
#[test]
fn any_json_number_syntax_is_read_exactly() {
let catalog = catalog();
assert_eq!(reread(&catalog, &Type::Decimal, "1.50"), "1.5");
assert_eq!(reread(&catalog, &Type::Decimal, "-2.5E-3"), "-0.0025");
assert_eq!(
reread(
&catalog,
&Type::Decimal,
"0.1000000000000000000000000000000000000001"
),
"0.1000000000000000000000000000000000000001"
);
assert_eq!(
reread(
&catalog,
&Type::Int,
"123456789012345678901234567890123456789"
),
"123456789012345678901234567890123456789"
);
}
#[test]
fn an_int_needs_a_whole_value_in_any_spelling() {
let catalog = catalog();
assert_eq!(reread(&catalog, &Type::Int, "1.0"), "1");
assert_eq!(reread(&catalog, &Type::Int, "1e2"), "100");
assert_eq!(reread(&catalog, &Type::Int, "1500e-2"), "15");
assert_eq!(reread(&catalog, &Type::Int, "-0"), "0");
assert_eq!(
problem(&catalog, &Type::Int, "1.5"),
"should be a whole number"
);
assert_eq!(
problem(&catalog, &Type::Int, "1e-1"),
"should be a whole number"
);
}
#[test]
fn an_int_past_the_size_limit_is_refused_without_being_built() {
let catalog = catalog();
let limit = format!("{}", flow_value::BigInt::from(2).pow(4096) - 1);
assert_eq!(reread(&catalog, &Type::Int, &limit), limit);
assert_eq!(
reread(&catalog, &Type::Int, &format!("-{limit}")),
format!("-{limit}")
);
let past = format!("{}", flow_value::BigInt::from(2).pow(4096));
assert_eq!(
problem(&catalog, &Type::Int, &past),
"is a number whose digits make an integer larger than 4096 bits (at byte 1234)"
);
assert_eq!(reread(&catalog, &Type::Int, "1e1233").len(), 1234);
assert_eq!(
problem(&catalog, &Type::Int, "1e1234"),
"is an integer larger than 4096 bits"
);
assert_eq!(
problem(&catalog, &Type::Int, "1e9000000000000000000"),
"is a number too large for this host (at byte 21)"
);
}
#[test]
fn a_number_whose_plain_notation_passes_the_text_limit_is_refused() {
let catalog = catalog();
let limits = Limits {
text_bytes: 10,
..Limits::LANGUAGE
};
let read = |text: &str| decode_text(&catalog, &Type::Decimal, text, Mode::Reply, &limits);
assert!(read("1e9").is_ok());
let four = Limits {
text_bytes: 4,
..Limits::LANGUAGE
};
let short = |text: &str| decode_text(&catalog, &Type::Decimal, text, Mode::Reply, &four);
assert!(short("0.12").is_ok());
assert_eq!(kind_of(short("0.123")), DecodeErrorKind::TooLarge);
assert!(short("1.23").is_ok());
assert_eq!(kind_of(read("-123456789.1")), DecodeErrorKind::TooLarge);
assert!(read("1e-8").is_ok(), "0.00000001 is ten characters");
assert_eq!(kind_of(read("1e-9")), DecodeErrorKind::TooLarge);
assert!(read("12345678.9").is_ok());
assert_eq!(kind_of(read("123456789.1")), DecodeErrorKind::TooLarge);
assert_eq!(kind_of(read("1e10")), DecodeErrorKind::TooLarge);
}
#[test]
fn text_must_be_valid_json() {
let catalog = catalog();
assert_eq!(
dec_reply(
&catalog,
&Type::Text,
r#""a\"\\\/\b\f\n\r\t\u00e9\uD83D\uDE00""#
)
.map(|value| text_of(&value).to_owned()),
Ok("a\"\\/\u{8}\u{c}\n\r\t\u{e9}😀".to_owned())
);
assert_eq!(
problem(&catalog, &Type::Text, "\"a\u{1}b\""),
"has an unescaped control character (at byte 2)"
);
assert_eq!(
problem(&catalog, &Type::Text, r#""\x""#),
"has an invalid escape (at byte 2)"
);
assert_eq!(
problem(&catalog, &Type::Text, r#""\u12G4""#),
"has an invalid `\\u` escape (at byte 3)"
);
assert_eq!(
problem(&catalog, &Type::Text, r#""\u12"#),
"has an invalid `\\u` escape (at byte 3)"
);
assert_eq!(
problem(&catalog, &Type::Text, r#""abc"#),
"ends inside a string (at byte 4)"
);
assert_eq!(
problem(&catalog, &Type::Text, r#""\"#),
"has an invalid escape (at byte 2)"
);
}
#[test]
fn an_escape_naming_a_lone_surrogate_is_refused() {
let catalog = catalog();
let lone = "has an escape naming a lone surrogate";
assert_eq!(
problem(&catalog, &Type::Text, r#""\uDC00\uDC00""#),
"has an escape naming a lone surrogate (at byte 7)"
);
for text in [
r#""\uD800""#,
r#""\uDBFF x""#,
r#""\uDC00""#,
r#""\uDFFF""#,
r#""\uD800\u0041""#,
r#""\uD800\uD800""#,
r#""\uD800\uE000""#,
] {
let found = problem(&catalog, &Type::Text, text);
assert!(found.starts_with(lone), "{text}: {found}");
}
assert_eq!(
dec_reply(&catalog, &Type::Text, r#""\uDBFF\uDFFF\uD7FF\uE000""#)
.map(|value| text_of(&value).to_owned()),
Ok("\u{10FFFF}\u{D7FF}\u{E000}".to_owned())
);
assert_eq!(
dec_reply(&catalog, &Type::Text, r#""\uD800\uDC00""#)
.map(|value| text_of(&value).to_owned()),
Ok("\u{10000}".to_owned())
);
assert_eq!(
dec_reply(&catalog, &Type::Text, r#""\u0041\ud83d\ude00\u0000""#)
.map(|value| text_of(&value).to_owned()),
Ok("A\u{1F600}\u{0}".to_owned()),
"hex digits of either case"
);
}
#[test]
fn duplicate_object_keys_are_refused() {
let catalog = catalog();
assert_eq!(
refusal(
&catalog,
&named(PLAN),
r#"{"steps": [], "title": "a", "title": "b"}"#
),
(
r#"["title"]"#.into(),
"is a key its object already has (at byte 35)".into()
)
);
assert_eq!(
refusal(
&catalog,
&Type::list(Type::Json),
r#"[1, {"x": {"y": 1, "y": 2}}]"#
)
.0,
"[1][\"x\"][\"y\"]"
);
}
#[test]
fn a_dict_with_two_equal_keys_is_refused() {
let catalog = catalog();
assert_eq!(
refusal(
&catalog,
&Type::dict(Type::Decimal, Type::Text),
r#"[[1.0, "a"], [1, "b"]]"#
),
(String::new(), "has two equal keys".into())
);
assert_eq!(
reread(
&catalog,
&Type::dict(Type::Int, Type::Text),
r#"[[2, "b"], [1, "a"]]"#
),
r#"[[1,"a"],[2,"b"]]"#
);
}
#[test]
fn a_set_with_repeated_elements_is_refused() {
let catalog = catalog();
assert_eq!(reread(&catalog, &Type::set(Type::Int), "[3, 1]"), "[1,3]");
assert_eq!(
refusal(&catalog, &Type::set(Type::Int), "[3, 1, 3]"),
(String::new(), "has two equal elements".to_owned())
);
assert_eq!(
refusal(&catalog, &Type::set(Type::Decimal), "[1, 1.0]").1,
"has two equal elements"
);
let kind = decode_text(
&catalog,
&Type::set(Type::Int),
"[3, 1, 3]",
Mode::Input,
&Limits::LANGUAGE,
)
.expect_err("refused")
.kind;
assert_eq!(kind, DecodeErrorKind::Duplicate);
}
#[test]
fn an_unknown_constructor_name_is_refused() {
let catalog = catalog();
assert_eq!(
refusal(&catalog, &named(STATUS), r#""Finished""#),
(
String::new(),
"names \"Finished\", which is not a constructor of github.com/acme/plans@v1.2.0/plans.Status".into()
)
);
assert_eq!(
problem(&catalog, &named(STATUS), r#"{"notrun": 1}"#),
"names \"notrun\", which is not a constructor of github.com/acme/plans@v1.2.0/plans.Status"
);
assert_eq!(
problem(&catalog, &Type::option(Type::Int), r#""Some""#),
"names \"Some\", which is not a constructor of Option"
);
}
#[test]
fn decoding_never_coerces_between_types() {
let catalog = catalog();
let cases: &[(Type, &str, &str)] = &[
(Type::Int, r#""1""#, "should be an integer, not a string"),
(Type::Decimal, "true", "should be a number, not a boolean"),
(Type::Bool, "1", "should be a boolean, not a number"),
(Type::Text, "1", "should be a string, not a number"),
(Type::Bytes, "[]", "should be a base64 string, not an array"),
(
Type::Duration,
"90",
"should be an ISO 8601 duration, not a number",
),
(
Type::Instant,
"0",
"should be an ISO 8601 date and time, not a number",
),
(Type::Unit, "null", "should be `[]`, not null"),
(Type::Unit, "[1]", "should be `[]`, not an array"),
(
Type::list(Type::Int),
"{}",
"should be an array, not an object",
),
(
Type::set(Type::Int),
"1",
"should be an array, not a number",
),
(
Type::dict(Type::Text, Type::Int),
"[]",
"should be an object, not an array",
),
(
Type::dict(Type::Int, Type::Int),
"{}",
"should be an array of `[key, value]` pairs, not an object",
),
(
Type::Tuple(vec![Type::Int, Type::Int]),
"[1]",
"should be an array of 2 elements, not an array",
),
(
Type::Tuple(vec![Type::Int, Type::Int]),
"{}",
"should be an array of 2 elements, not an object",
),
(named(STEP), "[]", "should be an object, not an array"),
(
named(PAGE),
"1",
"should be a host token string, not a number",
),
(
named(STATUS),
"[]",
"should be a constructor's name or an object with one member, not an array",
),
(
named(STATUS),
r#"{"NotRun": 1, "Failed": "x"}"#,
"should be a constructor's name or an object with one member, not an object",
),
(
Type::option(Type::Int),
r#"{"Some": 1, "None": 1}"#,
"should be `\"None\"` or `{\"Some\": ...}`, not an object",
),
(
Type::option(Type::Int),
r#"{"Nome": 1}"#,
"names \"Nome\", which is not a constructor of Option",
),
(
Type::option(Type::Int),
r#""none""#,
"names \"none\", which is not a constructor of Option",
),
];
for (ty, text, expected) in cases {
assert_eq!(problem(&catalog, ty, text), *expected, "{ty:?} from {text}");
}
}
#[test]
fn each_constructor_is_read_in_the_form_its_payload_is_written_in() {
let catalog = catalog();
let status = named(STATUS);
assert_eq!(reread(&catalog, &status, r#""NotRun""#), r#""NotRun""#);
assert_eq!(
reread(&catalog, &status, r#"{"Failed": "x"}"#),
r#"{"Failed":"x"}"#
);
assert_eq!(
reread(&catalog, &status, r#"{"Pair": [1, "a"]}"#),
r#"{"Pair":[1,"a"]}"#
);
assert_eq!(
reread(
&catalog,
&status,
r#"{"Arrived": {"index": 1, "reply": null}}"#
),
r#"{"Arrived":{"index":1}}"#
);
}
#[test]
fn a_constructor_in_the_wrong_form_for_its_payload_is_refused() {
let catalog = catalog();
let status = named(STATUS);
assert_eq!(
refusal(&catalog, &status, r#"{"NotRun": []}"#),
("NotRun".into(), "carries no payload".into())
);
assert_eq!(
refusal(&catalog, &status, r#""Failed""#),
(
"Failed".into(),
"carries a payload, so it is written as an object".into()
)
);
assert_eq!(
refusal(&catalog, &status, r#"{"Pair": [1]}"#),
(
"Pair".into(),
"should be an array of 2 elements, not an array".into()
)
);
assert_eq!(
refusal(&catalog, &status, r#"{"Pair": {"a": 1}}"#),
(
"Pair".into(),
"should be an array of 2 elements, not an object".into()
)
);
assert_eq!(
refusal(&catalog, &status, r#"{"Pair": [1, 2]}"#),
("Pair[1]".into(), "should be a string, not a number".into())
);
assert_eq!(
refusal(&catalog, &status, r#"{"Arrived": [1]}"#),
("Arrived".into(), "should be an object, not an array".into())
);
assert_eq!(
refusal(&catalog, &status, r#"{"Arrived": {}}"#),
("Arrived.index".into(), "is missing".into())
);
assert_eq!(
refusal(&catalog, &status, r#"{"Failed": 1}"#),
("Failed".into(), "should be a string, not a number".into())
);
}
#[test]
fn an_option_outside_a_field_is_none_or_some() {
let catalog = catalog();
let ty = Type::option(Type::Int);
assert_eq!(reread(&catalog, &ty, r#""None""#), r#""None""#);
assert_eq!(reread(&catalog, &ty, r#"{"Some": 1}"#), r#"{"Some":1}"#);
assert_eq!(
refusal(&catalog, &ty, r#"{"Some": "x"}"#),
("Some".into(), "should be an integer, not a string".into())
);
}
#[test]
fn a_generic_declaration_decodes_at_its_arguments() {
let catalog = catalog();
assert_eq!(
refusal(
&catalog,
&tree(Type::Int),
r#"{"Node": [{"Leaf": 1}, {"Leaf": "x"}]}"#
),
(
"Node[1].Leaf".into(),
"should be an integer, not a string".into()
)
);
assert_eq!(
reread(
&catalog,
&result(Type::Unit, Type::Text),
r#"{"Err": "no"}"#
),
r#"{"Err":"no"}"#
);
}
#[test]
fn a_failure_names_its_place_as_a_path() {
let catalog = catalog();
let steps = r#"[{"owner": "a", "done": true}, {"owner": "b", "done": true}, {"owner": 7, "done": true}]"#;
assert_eq!(
refusal(&catalog, &named(PLAN), &plan_text(steps)),
(
"steps[2].owner".into(),
"should be a string, not a number".into()
)
);
assert_eq!(
refusal(
&catalog,
&Type::dict(Type::Text, named(STEP)),
r#"{"first \"one\"": {"owner": "a"}}"#
),
(r#"["first \"one\""].done"#.into(), "is missing".into())
);
assert_eq!(
refusal(
&catalog,
&Type::dict(Type::Int, Type::Text),
r#"[[1, "a"], [2, 3]]"#
),
("[1][1]".into(), "should be a string, not a number".into())
);
assert_eq!(
refusal(
&catalog,
&Type::dict(Type::Int, Type::Text),
r#"[[1, "a"], ["2", "b"]]"#
),
("[1][0]".into(), "should be an integer, not a string".into())
);
assert_eq!(
refusal(
&catalog,
&Type::dict(Type::Int, Type::Text),
r#"[[1, "a"], [2]]"#
),
(
"[1]".into(),
"should be a `[key, value]` pair, not an array".into()
)
);
assert_eq!(
refusal(
&catalog,
&Type::Tuple(vec![Type::Int, Type::Text]),
r"[1, 2]"
),
("[1]".into(), "should be a string, not a number".into())
);
assert_eq!(
refusal(&catalog, &Type::set(Type::Int), r#"[1, "x"]"#),
("[1]".into(), "should be an integer, not a string".into())
);
assert_eq!(
refusal(&catalog, &Type::Json, r#"{"a": [1, {"b": [true, 01]}]}"#).0,
r#"["a"][1]["b"][1]"#
);
}
#[test]
fn a_decode_error_reads_as_its_place_and_problem() {
let catalog = catalog();
let error = decode_text(
&catalog,
&Type::list(Type::Int),
"[1, true]",
Mode::Reply,
&Limits::LANGUAGE,
)
.expect_err("refused");
assert_eq!(
error.to_string(),
"`[1]` should be an integer, not a boolean"
);
let error = decode_text(&catalog, &Type::Int, "true", Mode::Reply, &Limits::LANGUAGE)
.expect_err("refused");
assert_eq!(
error.to_string(),
"the value should be an integer, not a boolean"
);
}
#[test]
fn decoding_cant_build_an_opaque_type_even_where_none_is_present() {
let catalog = catalog();
let opaque = "has the type github.com/acme/plans@v1.2.0/review.Approved, which is opaque, so it can't be decoded";
assert_eq!(
refusal(&catalog, &named(GUARDED), "{}"),
(String::new(), opaque.into())
);
assert_eq!(problem(&catalog, &named(APPROVED), "{}"), opaque);
assert_eq!(
problem(
&catalog,
&Type::list(Type::Named(BOXED, vec![named(APPROVED)])),
"[]"
),
opaque
);
assert_eq!(
problem(
&catalog,
&Type::dict(Type::Text, Type::option(named(GUARDED))),
"{}"
),
opaque
);
assert_eq!(
problem(
&catalog,
&Type::Tuple(vec![Type::Int, named(GUARDED)]),
"[1, {}]"
),
opaque
);
assert_eq!(
problem(&catalog, &result(Type::Int, named(GUARDED)), r#"{"Ok": 1}"#),
opaque
);
assert_eq!(problem(&catalog, &Type::set(named(APPROVED)), "[]"), opaque);
assert_eq!(problem(&catalog, &named(APPROVED), "not json"), opaque);
assert!(decodable(&catalog, &named(PLAN), INPUT).is_ok());
}
fn rebuild(catalog: &flow_abi::Catalog, ty: &Type, text: &str) -> Result<Value, (String, String)> {
decode_text(catalog, ty, text, Mode::Rebuild, &Limits::LANGUAGE)
.map_err(|error| (error.path.to_string(), error.problem))
}
#[test]
fn rebuilding_a_value_the_program_made_builds_opaque_types_and_host_tokens() {
let catalog = catalog();
let plan = r#"{"plan": {"steps": [], "title": "t"}}"#;
let approved = rebuild(&catalog, &named(APPROVED), plan).expect("rebuilt");
assert_eq!(
enc(&catalog, &named(APPROVED), &approved),
r#"{"plan":{"steps":[],"title":"t"}}"#
);
let guarded = rebuild(
&catalog,
&named(GUARDED),
&format!(r#"{{"approval": {plan}}}"#),
);
assert!(guarded.is_ok());
let page = rebuild(&catalog, &named(PAGE), r#""p1""#).expect("rebuilt");
assert_eq!(enc(&catalog, &named(PAGE), &page), r#""p1""#);
}
#[test]
fn rebuilding_refuses_a_field_the_type_does_not_declare() {
let catalog = catalog();
assert_eq!(
rebuild(
&catalog,
&named(STEP),
r#"{"owner": "a", "done": true, "late": 1}"#
)
.expect_err("refused"),
(
"late".into(),
"is not a field of github.com/acme/plans@v1.2.0/plans.Step".into()
)
);
}
#[test]
fn rebuilding_rebuilds_a_type_with_a_part_with_no_encoding_where_it_holds_no_value() {
let catalog = catalog();
let functions = Type::list(Type::NotData);
assert!(decodable(&catalog, &functions, REBUILD).is_ok());
assert!(decodable(&catalog, &named(CALLBACK), REBUILD).is_ok());
let empty = rebuild(&catalog, &functions, "[]").expect("rebuilt");
assert_eq!(enc(&catalog, &functions, &empty), "[]");
let none = rebuild(&catalog, &Type::option(Type::NotData), r#""None""#).expect("rebuilt");
assert_eq!(
enc(&catalog, &Type::option(Type::NotData), &none),
r#""None""#
);
assert_eq!(
rebuild(&catalog, &functions, "[{}]").expect_err("refused"),
(
"[0]".into(),
"has a type with no encoding, so it holds no value".into()
)
);
assert_eq!(
rebuild(&catalog, &named(CALLBACK), r#"{"run": "f"}"#)
.expect_err("refused")
.1,
"has a type with no encoding, so it holds no value"
);
assert_eq!(
rebuild(&catalog, &Type::Param(0), "1")
.expect_err("refused")
.1,
"has a type with no encoding"
);
}
#[test]
fn a_type_with_no_encoding_is_refused_before_reading() {
let catalog = catalog();
assert_eq!(
problem(&catalog, &named(CALLBACK), "{}"),
"has a type with no encoding"
);
assert_eq!(
problem(&catalog, &Type::Param(0), "1"),
"has a type with no encoding"
);
assert_eq!(
problem(&catalog, &Type::list(Type::NotData), "[]"),
"has a type with no encoding"
);
}
#[test]
fn never_has_no_values_to_decode() {
let catalog = catalog();
assert_eq!(
problem(&catalog, &Type::Never, "[]"),
"has a type with no values to decode"
);
assert_eq!(
reread(&catalog, &result(Type::Int, Type::Never), r#"{"Ok": 1}"#),
r#"{"Ok":1}"#
);
assert_eq!(
refusal(&catalog, &result(Type::Int, Type::Never), r#"{"Err": 1}"#),
("Err".into(), "has a type with no values to decode".into())
);
}
#[test]
fn a_host_value_decodes_as_its_token_in_a_reply_but_never_in_input() {
let catalog = catalog();
let ty = Type::list(named(PAGE));
let pages = dec_reply(&catalog, &ty, r#"["p1", "p2"]"#).expect("decodes");
match &pages {
Value::List(items) => {
let tokens: Vec<&str> = items
.iter()
.map(|item| match item {
Value::Host(token) => token.as_str(),
_ => panic!("a host token"),
})
.collect();
assert_eq!(tokens, ["p1", "p2"]);
}
_ => panic!("a list"),
}
assert_eq!(
dec_input(&catalog, &ty, r#"["p1"]"#).expect_err("not input"),
(
String::new(),
"has the host type github.com/acme/plans@v1.2.0/browser.Page, which a run's input can't carry".into()
)
);
}
#[test]
fn what_a_declaration_holds_is_found_through_a_chain_declared_in_any_order() {
let link = |name: &str, field: Type| flow_types::Decl {
lexical_ordinal: 1,
identity: local(name),
doc: None,
members: vec![],
params: vec![],
opaque: false,
body: flow_types::Body::Record(flow_types::RecordShape::new(name, ["next"]), vec![field]),
};
let next = |index| Type::Named(flow_types::DeclId(index), vec![]);
let decls = vec![
link("A", next(1)),
link("B", next(2)),
link("C", next(3)),
flow_types::Decl {
lexical_ordinal: 1,
identity: local("Page"),
doc: None,
members: vec![],
params: vec![],
opaque: false,
body: flow_types::Body::Host,
},
];
let catalog = flow_abi::Catalog::new(decls, option_shape(), None).expect("std's shapes");
let text = r#"{"next": {"next": {"next": "p"}}}"#;
assert_eq!(
dec_input(&catalog, &next(0), text)
.expect_err("not input")
.1,
"has the host type main.Page, which a run's input can't carry"
);
assert!(dec_reply(&catalog, &next(0), text).is_ok());
}
#[test]
fn a_host_type_a_declaration_holds_is_refused_in_input_however_deep() {
let catalog = catalog();
let refusal = "has the host type github.com/acme/plans@v1.2.0/browser.Page, which a run's input can't carry";
let visit = r#"{"session": {"page": "p"}}"#;
assert_eq!(
dec_input(&catalog, &named(VISIT), visit)
.expect_err("not input")
.1,
refusal
);
assert_eq!(
dec_input(&catalog, &named(SESSION), r#"{"page": "p"}"#)
.expect_err("not input")
.1,
refusal
);
assert!(dec_reply(&catalog, &named(VISIT), visit).is_ok());
assert!(rebuild(&catalog, &named(VISIT), visit).is_ok());
}
#[test]
fn building_a_catalog_holding_nest_is_refused() {
assert_eq!(
flow_abi::Catalog::new(vec![nest()], option_shape(), Some(json_shape()))
.expect_err("Nest is not regular")
.problem,
"recursive arguments must be bare owner parameters"
);
}
#[test]
fn a_declaration_holding_what_cant_be_decoded_refuses_whatever_its_arguments() {
let catalog = catalog();
let boxed = |item| Type::Named(BOXED, vec![item]);
assert_eq!(
problem(&catalog, &boxed(named(CALLBACK)), "{}"),
"has a type with no encoding"
);
assert_eq!(
problem(&catalog, &tree(boxed(named(GUARDED))), r#"{"Leaf": {}}"#),
"has the type github.com/acme/plans@v1.2.0/review.Approved, which is opaque, so it can't be decoded"
);
assert_eq!(
dec_input(&catalog, &boxed(named(PAGE)), r#"{"value": "p"}"#)
.expect_err("not input")
.1,
"has the host type github.com/acme/plans@v1.2.0/browser.Page, which a run's input can't carry"
);
assert!(dec_reply(&catalog, &boxed(named(PAGE)), r#"{"value": "p"}"#).is_ok());
}
#[test]
fn a_recursive_type_is_judged_once_per_instance() {
let catalog = catalog();
let deep = r#"{"Node": [{"Node": [{"Leaf": 1}]}, {"Leaf": 2}]}"#;
assert_eq!(
reread(&catalog, &tree(Type::Int), deep),
deep.replace(' ', "")
);
}
#[test]
fn bytes_are_read_from_strict_standard_base64() {
let catalog = catalog();
let read = |text: &str| dec_reply(&catalog, &Type::Bytes, &format!("\"{text}\""));
for (text, contents) in [
("", &b""[..]),
("YQ==", b"a"),
("YWI=", b"ab"),
("YWJj", b"abc"),
("AAEC/w==", &[0, 1, 2, 255]),
("+/+/", &[0xfb, 0xff, 0xbf]),
] {
let decoded = read(text).expect("valid base64");
assert!(
same(&catalog, &Type::Bytes, &decoded, &bytes(contents)),
"{text}"
);
}
for text in [
"YQ", "YQ=", "Y===", "YQ==YQ==", "YW=I", "YQ=a", "Y Q==", "YQ-_", "YR==", "YWJ=", "=YWI",
"====",
] {
assert_eq!(
read(text).expect_err("refused").1,
"should be standard base64 with padding",
"{text}"
);
}
}
#[test]
fn bytes_past_the_size_limit_are_refused() {
let catalog = catalog();
let limits = Limits {
text_bytes: 3,
..Limits::LANGUAGE
};
let read = |text: &str| decode_text(&catalog, &Type::Bytes, text, Mode::Reply, &limits);
assert!(read(r#""YWJj""#).is_ok());
assert_eq!(
read(r#""YWJjZA==""#).expect_err("refused").problem,
"is longer than 3 bytes"
);
}
#[test]
fn text_past_the_size_limit_is_refused_wherever_it_stands() {
let catalog = catalog();
let limits = Limits {
text_bytes: 3,
..Limits::LANGUAGE
};
let read = |ty: &Type, text: &str| decode_text(&catalog, ty, text, Mode::Reply, &limits);
assert!(read(&Type::Text, r#""abc""#).is_ok());
assert_eq!(
read(&Type::Text, r#""abcd""#).expect_err("refused").problem,
"is longer than 3 bytes"
);
assert!(read(&Type::Text, r#""é""#).is_ok(), "two bytes");
assert_eq!(
kind_of(read(&Type::Text, r#""éé""#)),
DecodeErrorKind::TooLarge,
"four bytes"
);
let keyed = read(&Type::dict(Type::Text, Type::Int), r#"{"abcd": 1}"#).expect_err("refused");
assert_eq!(
(keyed.path.to_string().as_str(), keyed.problem.as_str()),
(r#"["abcd"]"#, "is longer than 3 bytes")
);
assert_eq!(
kind_of(read(&Type::Json, r#""abcd""#)),
DecodeErrorKind::TooLarge
);
assert_eq!(
kind_of(read(&Type::Json, r#"{"abcd": 1}"#)),
DecodeErrorKind::TooLarge
);
}
#[test]
fn an_instant_is_read_from_iso_8601_with_z_or_an_offset() {
let catalog = catalog();
let at = |text: &str| reread(&catalog, &Type::Instant, &format!("\"{text}\""));
assert_eq!(at("2026-03-21T09:30:00Z"), "\"2026-03-21T09:30:00Z\"");
assert_eq!(
at("2026-03-21T09:30:00.250Z"),
"\"2026-03-21T09:30:00.25Z\""
);
assert_eq!(at("2026-03-21T11:30:00+02:00"), "\"2026-03-21T09:30:00Z\"");
assert_eq!(at("2026-03-21T04:00:00-05:30"), "\"2026-03-21T09:30:00Z\"");
assert_eq!(
at("2026-03-21T09:30:00.5-00:00"),
"\"2026-03-21T09:30:00.5Z\""
);
assert_eq!(at("1970-01-01T00:00:00Z"), "\"1970-01-01T00:00:00Z\"");
assert_eq!(
at("1969-12-31T23:59:59.999Z"),
"\"1969-12-31T23:59:59.999Z\""
);
assert_eq!(at("0000-01-01T00:00:00Z"), "\"0000-01-01T00:00:00Z\"");
assert_eq!(at("-0001-12-31T00:00:00Z"), "\"-0001-12-31T00:00:00Z\"");
assert_eq!(at("+10000-01-01T00:00:00Z"), "\"+10000-01-01T00:00:00Z\"");
assert_eq!(at("+2026-01-01T00:00:00Z"), "\"2026-01-01T00:00:00Z\"");
assert_eq!(at("-123456-03-01T23:59:59Z"), "\"-123456-03-01T23:59:59Z\"");
assert_eq!(at("9999-12-31T23:59:59Z"), "\"9999-12-31T23:59:59Z\"");
}
#[test]
fn an_instant_may_write_its_t_and_z_in_lowercase() {
let catalog = catalog();
let at = |text: &str| reread(&catalog, &Type::Instant, &format!("\"{text}\""));
assert_eq!(at("2026-03-21t09:30:00Z"), "\"2026-03-21T09:30:00Z\"");
assert_eq!(at("2026-03-21T09:30:00z"), "\"2026-03-21T09:30:00Z\"");
assert_eq!(at("2026-03-21t18:30:00+09:00"), "\"2026-03-21T09:30:00Z\"");
}
#[test]
fn an_instant_on_a_leap_day_exists_only_in_a_leap_year() {
let catalog = catalog();
let read = |text: &str| {
decode_text(
&catalog,
&Type::Instant,
&format!("\"{text}\""),
Mode::Reply,
&Limits::LANGUAGE,
)
};
for leap in [
"2024-02-29",
"2000-02-29",
"0000-02-29",
"-0004-02-29",
"2400-02-29",
] {
assert!(read(&format!("{leap}T00:00:00Z")).is_ok(), "{leap}");
}
for common in [
"2023-02-29",
"1900-02-29",
"2100-02-29",
"-0001-02-29",
"2024-02-30",
] {
assert_eq!(
kind_of(read(&format!("{common}T00:00:00Z"))),
DecodeErrorKind::Mismatch,
"{common}"
);
}
for (month, days) in [
(1, 31),
(3, 31),
(4, 30),
(5, 31),
(6, 30),
(7, 31),
(8, 31),
(9, 30),
(10, 31),
(11, 30),
(12, 31),
] {
assert!(read(&format!("2023-{month:02}-{days:02}T00:00:00Z")).is_ok());
assert_eq!(
kind_of(read(&format!("2023-{month:02}-{:02}T00:00:00Z", days + 1))),
DecodeErrorKind::Mismatch
);
}
}
#[test]
fn an_instant_in_any_other_form_is_refused() {
let catalog = catalog();
for text in [
"",
"2026-03-21",
"2026-03-21T09:30Z",
"2026-03-21T09:30:00",
"2026-03-21 09:30:00Z",
"2026-3-21T09:30:00Z",
"26-03-21T09:30:00Z",
"12026-03-21T09:30:00Z",
"2026-00-21T09:30:00Z",
"2026-13-21T09:30:00Z",
"2026-03-00T09:30:00Z",
"2026-03-32T09:30:00Z",
"2026-03-21T24:00:00Z",
"2026-03-21T09:60:00Z",
"2026-03-21T09:30:60Z",
"2026-03-21T09:30:00.Z",
"2026-03-21T09:30:00+0200",
"2026-03-21T09:30:00+24:00",
"2026-03-21T09:30:00+02:60",
"2026-03-21T09:30:00Z ",
"2026/03/21T09:30:00Z",
"2026-03-21T09-30-00Z",
"2026-03-21T09:30:00",
"2026-03-21T0a:30:00Z",
"x2026-03-21T09:30:00Z",
] {
assert_eq!(
refusal(&catalog, &Type::Instant, &format!("\"{text}\"")).1,
"should be an ISO 8601 date and time",
"{text}"
);
}
}
#[test]
fn a_duration_is_read_from_weeks_days_hours_minutes_and_seconds() {
let catalog = catalog();
let span = |text: &str| reread(&catalog, &Type::Duration, &format!("\"{text}\""));
assert_eq!(span("PT90S"), "\"PT90S\"");
assert_eq!(span("PT0.25S"), "\"PT0.25S\"");
assert_eq!(span("PT-5S"), "\"PT-5S\"");
assert_eq!(span("PT1M30S"), "\"PT90S\"");
assert_eq!(span("PT1H"), "\"PT3600S\"");
assert_eq!(span("PT1H1M1.5S"), "\"PT3661.5S\"");
assert_eq!(span("P1D"), "\"PT86400S\"");
assert_eq!(span("P2DT3H"), "\"PT183600S\"");
assert_eq!(span("P1DT-1H"), "\"PT82800S\"");
assert_eq!(span("P-1DT1H"), "\"PT-82800S\"");
assert_eq!(span("PT0S"), "\"PT0S\"");
}
#[test]
fn a_week_is_seven_days_of_86400_seconds() {
let catalog = catalog();
let span = |text: &str| reread(&catalog, &Type::Duration, &format!("\"{text}\""));
assert_eq!(span("P1W"), "\"PT604800S\"");
assert_eq!(span("P-2W"), "\"PT-1209600S\"");
assert_eq!(span("P1W1D"), "\"PT691200S\"");
assert_eq!(span("P1WT1S"), "\"PT604801S\"");
}
#[test]
fn a_duration_in_calendar_units_or_any_other_form_is_refused() {
let catalog = catalog();
for text in [
"",
"P",
"PT",
"P1DT",
"P1Y",
"P1M",
"P1.5W",
"P1D1W",
"-PT5S",
"-P1D",
"PT1.5H",
"PT1.5M",
"P1.5D",
"PT1.S",
"PT.5S",
"PT5",
"T5S",
"PT5S ",
"pt5s",
"PT5SX",
"P--1D",
"PT1S1M",
"+PT5S",
"PTS",
"PT-0.5M10S",
] {
assert_eq!(
refusal(&catalog, &Type::Duration, &format!("\"{text}\"")).1,
"should be an ISO 8601 duration",
"{text}"
);
}
}
#[test]
fn a_value_nested_to_the_depth_limit_decodes_and_one_deeper_is_refused() {
let catalog = catalog();
let limits = Limits {
depth: 3,
..Limits::LANGUAGE
};
let ty = Type::list(Type::list(Type::list(Type::Int)));
let read = |ty: &Type, text: &str| decode_text(&catalog, ty, text, Mode::Reply, &limits);
assert!(read(&ty, "[[[1]]]").is_ok());
let deeper = Type::list(ty);
let error = read(&deeper, "[[[[1]]]]").expect_err("too deep");
assert_eq!(
(error.path.to_string().as_str(), error.problem.as_str()),
("[0][0][0]", "nests deeper than 3 levels")
);
assert!(read(&deeper, "[[[]]]").is_ok());
assert_eq!(
kind_of(read(&deeper, "[[[[]]]]")),
DecodeErrorKind::TooLarge
);
}
#[test]
fn a_value_as_deep_as_the_limit_decodes_without_a_native_frame_per_level() {
let catalog = catalog();
let (ty, text) = deepest_trees();
let deepest = parse(&text, &Limits::LANGUAGE).expect("within the limits");
let deeper = parse(&format!("[{text}]"), &Limits::LANGUAGE).expect("within the limits");
let deeper_ty = Type::list(ty.clone());
on_a_small_stack(|| {
assert!(decode(&catalog, &ty, &deepest, Mode::Reply, &Limits::LANGUAGE).is_ok());
let error = decode(
&catalog,
&deeper_ty,
&deeper,
Mode::Reply,
&Limits::LANGUAGE,
)
.expect_err("one level too deep");
assert_eq!(error.problem, "nests deeper than 256 levels");
});
}
#[test]
fn every_aggregate_counts_one_level_of_depth() {
let catalog = catalog();
let limits = Limits {
depth: 1,
..Limits::LANGUAGE
};
let read = |ty: &Type, text: &str| decode_text(&catalog, ty, text, Mode::Reply, &limits);
let one_level: &[(Type, &str)] = &[
(Type::list(Type::Int), "[1]"),
(Type::set(Type::Int), "[1]"),
(Type::dict(Type::Text, Type::Int), r#"{"a": 1}"#),
(Type::dict(Type::Int, Type::Int), "[[1, 2]]"),
(Type::Tuple(vec![Type::Int, Type::Int]), "[1, 2]"),
(Type::option(Type::Int), r#"{"Some": 1}"#),
(named(STEP), r#"{"owner": "a", "done": true}"#),
(named(STATUS), r#""NotRun""#),
(named(STATUS), r#"{"Pair": [1, "a"]}"#),
(Type::Json, "1"),
(Type::Int, "1"),
(Type::Unit, "[]"),
];
for (ty, text) in one_level {
assert!(read(ty, text).is_ok(), "{ty:?} {text}");
}
let two_levels: &[(Type, &str)] = &[
(Type::list(Type::list(Type::Int)), "[[]]"),
(Type::set(Type::option(Type::Int)), r#"["None"]"#),
(
Type::dict(Type::Text, Type::list(Type::Int)),
r#"{"a": []}"#,
),
(Type::dict(Type::list(Type::Int), Type::Int), "[[[], 1]]"),
(Type::dict(Type::Int, Type::list(Type::Int)), "[[1, []]]"),
(
Type::Tuple(vec![Type::Int, Type::list(Type::Int)]),
"[1, []]",
),
(Type::option(Type::list(Type::Int)), r#"{"Some": []}"#),
(named(PLAN), r#"{"steps": [], "title": "t"}"#),
(
Type::Named(BOXED, vec![Type::option(Type::Int)]),
r#"{"value": 1}"#,
),
(Type::Named(BOXED, vec![Type::option(Type::Int)]), "{}"),
(named(STATUS), r#"{"Arrived": {"index": 1, "reply": "r"}}"#),
(Type::list(named(STATUS)), r#"["NotRun"]"#),
(Type::Json, "[]"),
(Type::Json, "{}"),
];
for (ty, text) in two_levels {
assert_eq!(
read(ty, text).expect_err("two levels").problem,
"nests deeper than 1 levels",
"{ty:?} {text}"
);
}
}
#[test]
fn an_option_field_holding_none_is_one_level_and_some_wraps_its_payload() {
let catalog = catalog();
let at = |depth| Limits {
depth,
..Limits::LANGUAGE
};
let read =
|depth, text: &str| decode_text(&catalog, &named(STATUS), text, Mode::Reply, &at(depth));
assert!(read(2, r#"{"Arrived": {"index": 1}}"#).is_ok());
assert!(read(2, r#"{"Arrived": {"index": 1, "reply": "r"}}"#).is_ok());
assert_eq!(
kind_of(read(1, r#"{"Arrived": {"index": 1}}"#)),
DecodeErrorKind::TooLarge
);
let boxed = Type::Named(BOXED, vec![Type::option(Type::list(Type::Int))]);
let read = |depth, text: &str| decode_text(&catalog, &boxed, text, Mode::Reply, &at(depth));
assert!(read(3, r#"{"value": [1]}"#).is_ok());
assert_eq!(
kind_of(read(2, r#"{"value": [1]}"#)),
DecodeErrorKind::TooLarge
);
assert!(read(2, r"{}").is_ok());
}
#[test]
fn a_json_value_counts_its_constructor_and_its_collection() {
let catalog = catalog();
let read = |depth, text: &str| {
decode_text(
&catalog,
&Type::Json,
text,
Mode::Reply,
&Limits {
depth,
..Limits::LANGUAGE
},
)
};
assert!(read(5, "[[1]]").is_ok());
assert_eq!(kind_of(read(4, "[[1]]")), DecodeErrorKind::TooLarge);
assert!(read(4, r#"{"a": {}}"#).is_ok());
assert_eq!(kind_of(read(3, r#"{"a": {}}"#)), DecodeErrorKind::TooLarge);
}
#[test]
fn json_nested_past_twice_the_depth_limit_is_refused_unread() {
let limits = Limits {
depth: 2,
..Limits::LANGUAGE
};
assert!(parse("[[[[[1]]]]]", &limits).is_ok(), "five levels");
let error = parse("[[[[[[1]]]]]]", &limits).expect_err("six levels");
assert_eq!(error.problem, "nests deeper than 5 levels (at byte 5)");
assert_eq!(error.path, "[0][0][0][0][0]");
let error = parse(r#"{"a":{"b":{"c":{"d":{"e":{}}}}}}"#, &limits).expect_err("six levels");
assert_eq!(error.path, r#"["a"]["b"]["c"]["d"]["e"]"#);
let deep = "[".repeat(1_000_000);
assert_eq!(
kind_of(parse(&deep, &Limits::LANGUAGE)),
DecodeErrorKind::TooLarge
);
}
#[test]
fn json_as_deep_as_the_parser_admits_is_read_without_a_native_frame_per_level() {
let pairs = Limits::LANGUAGE.depth;
let deepest = format!("{}[]{}", "{\"a\": [".repeat(pairs), "]}".repeat(pairs));
let deeper = format!("[{deepest}]");
on_a_small_stack(|| {
assert!(parse(&deepest, &Limits::LANGUAGE).is_ok());
let error = parse(&deeper, &Limits::LANGUAGE).expect_err("one level too deep");
assert_eq!(
error.problem,
format!("nests deeper than 513 levels (at byte {})", 1 + 7 * pairs)
);
});
}
#[test]
fn the_minimum_limits_are_the_specifications() {
assert_eq!(
Limits::LANGUAGE,
Limits {
depth: 256,
int_bits: 4096,
text_bytes: 16 * 1024 * 1024,
}
);
assert_eq!(Limits::default(), Limits::LANGUAGE);
}
#[test]
fn text_that_is_not_one_json_value_is_refused_with_where() {
let limits = Limits::LANGUAGE;
let cases = [
("", "ends before a JSON value (at byte 0)"),
(" ", "ends before a JSON value (at byte 3)"),
("nul", "is not valid JSON (at byte 0)"),
("tru", "is not valid JSON (at byte 0)"),
("fals", "is not valid JSON (at byte 0)"),
("x", "is not valid JSON (at byte 0)"),
("1 2", "has text after the JSON value (at byte 2)"),
("[1,]", "is not valid JSON (at byte 3)"),
(
"[1 2]",
"is not valid JSON: expected `,` or `]` (at byte 3)",
),
("[1", "is not valid JSON: expected `,` or `]` (at byte 2)"),
("{1: 2}", "is not valid JSON: expected a key (at byte 1)"),
("{\"a\" 2}", "is not valid JSON: expected `:` (at byte 5)"),
(
"{\"a\": 2 \"b\"}",
"is not valid JSON: expected `,` or `}` (at byte 8)",
),
(
"{\"a\": 2,}",
"is not valid JSON: expected a key (at byte 8)",
),
("01", "is not a valid JSON number (at byte 2)"),
("-", "is not a valid JSON number (at byte 1)"),
("-a", "is not a valid JSON number (at byte 1)"),
("1.", "is not a valid JSON number (at byte 2)"),
("1.e1", "is not a valid JSON number (at byte 2)"),
("1e", "is not a valid JSON number (at byte 2)"),
("1e+", "is not a valid JSON number (at byte 3)"),
("+1", "is not valid JSON (at byte 0)"),
(".5", "is not valid JSON (at byte 0)"),
("[\u{a0}1]", "is not valid JSON (at byte 1)"),
];
for (text, problem) in cases {
let error = parse(text, &limits).expect_err(text);
assert_eq!(error.problem, problem, "{text:?}");
}
}
#[test]
fn json_whitespace_is_space_tab_newline_and_return_only() {
let limits = Limits::LANGUAGE;
assert_eq!(
parse(" \t\n\r[ \t\n\r1 \t\n\r, 2 ] \t\n\r", &limits).map(|json| json.canonical()),
Ok("[1,2]".to_owned())
);
assert_eq!(
kind_of(parse("\u{c}1", &limits)),
DecodeErrorKind::Syntax { at: 0 }
);
assert_eq!(
kind_of(parse("1\u{b}", &limits)),
DecodeErrorKind::Syntax { at: 1 }
);
}
#[test]
fn json_literals_and_empty_aggregates_parse() {
let limits = Limits::LANGUAGE;
assert_eq!(parse("null", &limits), Ok(Json::Null));
assert_eq!(parse("true", &limits), Ok(Json::Bool(true)));
assert_eq!(parse("false", &limits), Ok(Json::Bool(false)));
assert_eq!(parse("[ ]", &limits), Ok(Json::Array(vec![])));
assert_eq!(parse("{ }", &limits), Ok(Json::Object(vec![])));
assert_eq!(parse("\"\"", &limits), Ok(Json::String(String::new())));
assert_eq!(
parse("0", &limits).map(|json| json.canonical()),
Ok("0".to_owned())
);
assert_eq!(
parse("-0.0", &limits).map(|json| json.canonical()),
Ok("0".to_owned())
);
assert_eq!(
parse("1e0005", &limits).map(|json| json.canonical()),
Ok("100000".to_owned())
);
assert_eq!(
parse("1e-0000000000000000000000002", &limits).map(|json| json.canonical()),
Ok("0.01".to_owned())
);
assert_eq!(
parse("5e0000000000000000000000000", &limits).map(|json| json.canonical()),
Ok("5".to_owned())
);
}
#[test]
fn an_exponent_beyond_sixty_four_bits_is_refused_as_too_large() {
let limits = Limits::LANGUAGE;
assert_eq!(
parse("1e-99999999999999999999", &limits)
.expect_err("refused")
.problem,
"is a number too large for this host (at byte 23)"
);
assert_eq!(
parse("0.1e-9223372036854775808", &limits)
.expect_err("refused")
.problem,
"is a number too large for this host (at byte 24)"
);
}
#[test]
fn a_member_value_failing_names_its_key_in_the_path() {
let error = parse(r#"{"a": [1, tru]}"#, &Limits::LANGUAGE).expect_err("refused");
assert_eq!(
(error.path.to_string().as_str(), error.problem.as_str()),
(r#"["a"][1]"#, "is not valid JSON (at byte 10)")
);
}
#[test]
fn a_task_is_written_as_the_id_of_its_call_and_never_decoded() {
use flow_abi::{encode, encode_naming_tasks};
use flow_value::TaskId;
let catalog = catalog();
let ty = Type::list(Type::Task(Box::new(Type::Text)));
let ids: Vec<TaskId> = std::iter::successors(Some(TaskId::FIRST), |id| Some(id.next()))
.take(10)
.collect();
let (named, unnamed) = (ids[4], ids[9]);
let tasks = Value::list([Value::Task(named), Value::Task(unnamed)]);
let mut met = Vec::new();
let json = encode_naming_tasks(&catalog, &ty, &tasks, &mut |task, result| {
met.push((task, result.clone()));
(task == named).then(|| "root/1#1".to_owned())
});
assert!(json.is_err(), "a task with no call is refused");
assert_eq!(met, [(named, Type::Text), (unnamed, Type::Text)]);
let json = encode_naming_tasks(&catalog, &ty, &tasks, &mut |task, _| {
Some(format!("root/{task}#1"))
})
.expect("every task is parked");
assert_eq!(json.canonical(), r#"["root/4#1","root/9#1"]"#);
assert!(
encode(&catalog, &ty, &tasks).is_err(),
"a task has no encoding outside a view"
);
assert!(decodable(&catalog, &ty, REBUILD).is_ok());
assert_eq!(
kind_of(decodable(&catalog, &ty, REPLY)),
DecodeErrorKind::Mismatch
);
let outside = flow_abi::decode(&catalog, &ty, &json, Mode::Rebuild, &Limits::default())
.expect_err("a task has no values to decode");
assert!(
outside
.to_string()
.contains("has a type with no values to decode"),
"{outside}"
);
assert_eq!(catalog.name(&ty), "List<task.Task<Text>>");
assert_eq!(
Type::Task(Box::new(Type::Param(0))).subst(&[Type::Int]),
Type::Task(Box::new(Type::Int))
);
assert!(flow_abi::schema(&catalog, &ty).is_err());
}
#[test]
fn full_function_and_nominal_nondata_rebuild_only_where_no_value_is_held() {
let catalog = phantom_catalog();
let function = Type::Function {
params: vec![Type::Int],
result: Box::new(Type::Text),
};
for actual in [function, Type::Named(flow_types::DeclId(0), vec![])] {
assert_eq!(
kind_of(decodable(&catalog, &actual, REPLY)),
DecodeErrorKind::Mismatch
);
assert!(rebuild(&catalog, &actual, "[]").is_err());
let empty = Type::list(actual.clone());
assert!(rebuild(&catalog, &empty, "[]").is_ok());
assert_eq!(
kind_of(decodable(&catalog, &empty, REPLY)),
DecodeErrorKind::Mismatch
);
let phantom = Type::Named(flow_types::DeclId(1), vec![actual]);
assert!(decodable(&catalog, &phantom, INPUT).is_ok());
let value = rebuild(&catalog, &phantom, r#"{"n":7}"#).expect("actual Int field");
assert_eq!(enc(&catalog, &phantom, &value), r#"{"n":7}"#);
}
}
#[test]
fn resource_refusals_keep_their_kind_for_parser_and_preparsed_values() {
use flow_abi::DecodeErrorKind;
let catalog = catalog();
let small = Limits {
depth: 0,
int_bits: 8,
text_bytes: 2,
};
for (ty, input) in [
(Type::Int, "256"),
(Type::Decimal, "256"),
(Type::Text, r#""abc""#),
(Type::Bytes, r#""YWJj""#),
(Type::list(Type::Int), "[]"),
] {
let value = parse(input, &Limits::default()).unwrap();
let error = flow_abi::decode(&catalog, &ty, &value, Mode::Rebuild, &small).unwrap_err();
assert_eq!(error.kind, DecodeErrorKind::TooLarge, "{ty:?}: {error}");
}
for (input, limits) in [
(
"256",
Limits {
int_bits: 8,
..Limits::default()
},
),
(
"[[1]]",
Limits {
depth: 0,
..Limits::default()
},
),
(
"1e9",
Limits {
text_bytes: 2,
..Limits::default()
},
),
(
"[1e9,1e9]",
Limits {
text_bytes: 12,
..Limits::default()
},
),
] {
assert_eq!(
parse(input, &limits).unwrap_err().kind,
DecodeErrorKind::TooLarge,
"{input}"
);
}
for (input, kind) in [
("{", DecodeErrorKind::Syntax { at: 1 }),
("[1,]", DecodeErrorKind::Syntax { at: 3 }),
(r#"{"a":1,"a":2}"#, DecodeErrorKind::Duplicate),
] {
assert_eq!(parse(input, &small).unwrap_err().kind, kind, "{input}");
}
assert_eq!(
flow_abi::decode(
&catalog,
&Type::Int,
&Json::Bool(false),
Mode::Rebuild,
&small
)
.unwrap_err()
.kind,
DecodeErrorKind::Mismatch
);
}
#[test]
fn preparsed_raw_json_numbers_share_decimal_coefficient_limits() {
let catalog = catalog();
let value = parse("256", &Limits::default()).unwrap();
let limits = Limits {
int_bits: 8,
..Limits::default()
};
let error =
flow_abi::decode(&catalog, &Type::Json, &value, Mode::Rebuild, &limits).unwrap_err();
assert_eq!(error.kind, flow_abi::DecodeErrorKind::TooLarge);
assert_eq!(error.problem, "has a coefficient larger than 8 bits");
}
#[test]
fn decimal_coefficient_bit_limits_admit_the_exact_boundary_in_every_decode_mode() {
let catalog = catalog();
let limits = Limits {
int_bits: 8,
..Limits::LANGUAGE
};
for mode in [Mode::Input, Mode::Reply, Mode::Rebuild] {
for (source, admitted) in [
("12.7", true),
("12.8", true),
("25.5", true),
("-12.8", true),
("25.6", false),
] {
let parsed = parse(source, &Limits::default()).unwrap();
for result in [
decode_text(&catalog, &Type::Decimal, source, mode, &limits),
flow_abi::decode(&catalog, &Type::Decimal, &parsed, mode, &limits),
] {
if admitted {
let value = result.unwrap_or_else(|error| panic!("{source}: {error}"));
assert_eq!(enc(&catalog, &Type::Decimal, &value), source);
} else {
assert_eq!(
result.unwrap_err().kind,
flow_abi::DecodeErrorKind::TooLarge
);
}
}
}
let zero = Limits {
int_bits: 0,
..Limits::LANGUAGE
};
let value = decode_text(&catalog, &Type::Decimal, "0", mode, &zero).unwrap();
assert_eq!(enc(&catalog, &Type::Decimal, &value), "0");
}
}
#[test]
fn one_rule_set_decodes_json_a_missing_option_field_is_none_and_a_newtype_its_erasure() {
let catalog = catalog();
let plan = r#"{"steps": [], "title": "t"}"#;
assert_eq!(
reread(&catalog, &named(PLAN), plan),
r#"{"steps":[],"title":"t"}"#
);
assert!(dec_input(&catalog, &named(PLAN), plan).is_ok());
assert_eq!(
refusal(&catalog, &named(PLAN), r#"{"steps": []}"#),
("title".to_owned(), "is missing".to_owned())
);
let newtypes = newtype_catalog();
assert_eq!(reread(&newtypes, &named(USER_ID), r#""u-17""#), r#""u-17""#);
assert_eq!(
refusal(&newtypes, &named(USER_ID), r#"{"UserId": "u-17"}"#),
refusal(&newtypes, &Type::Text, r#"{"UserId": "u-17"}"#)
);
}
#[cfg(unix)]
#[test]
fn an_os_string_reads_back_as_its_bytes_on_unix() {
use flow_abi::wire::Wire as _;
use std::os::unix::ffi::OsStringExt as _;
let written = std::ffi::OsString::from_vec(vec![b'a', 0xff]);
assert_eq!(
std::ffi::OsString::decode(&written.bytes()).ok(),
Some(written),
"bytes that are not UTF-8 read back as they were"
);
}
#[cfg(not(unix))]
#[test]
fn an_os_string_that_is_not_utf8_is_refused_off_unix() {
use flow_abi::wire::Wire as _;
let written = flow_value::Bytes::new(&[b'a', 0xff]).bytes();
assert!(
std::ffi::OsString::decode(&written).is_err(),
"bytes that are not UTF-8 are no OS string here"
);
assert_eq!(
std::ffi::OsString::decode(&std::ffi::OsString::from("a").bytes()).ok(),
Some(std::ffi::OsString::from("a")),
"UTF-8 reads back"
);
}