mod common;
use std::cmp::Ordering;
use common::*;
use flow_types::{Constructor, EnumShape, Payload, RecordShape};
use flow_value::{
DataError, HostToken, Native, Record, TaskId, Tuple, Value, Variant, compare, equal,
};
fn outcome_shape() -> std::sync::Arc<EnumShape> {
EnumShape::new(
"Outcome",
[
Constructor::new("Done", Payload::Positional(1)),
Constructor::new("Pair", Payload::Positional(2)),
Constructor::new("StepFailed", Payload::named(["step", "last"])),
Constructor::new("TimedOut", Payload::None),
],
)
}
fn outcome(index: usize, payload: Vec<Value>) -> Value {
Value::Variant(Variant::new(outcome_shape(), index, payload).expect("a valid payload"))
}
#[test]
fn unit_equals_itself() {
assert_eq!(order(&Value::Unit, &Value::Unit), Ordering::Equal);
}
#[test]
fn false_orders_before_true() {
assert_eq!(
order(&Value::Bool(false), &Value::Bool(true)),
Ordering::Less
);
assert_eq!(
order(&Value::Bool(true), &Value::Bool(true)),
Ordering::Equal
);
}
#[test]
fn enum_values_order_by_declaration_order_then_payload() {
let ascending = [
outcome(0, vec![Value::int(5)]),
outcome(0, vec![Value::int(6)]),
outcome(1, vec![Value::int(0), Value::int(9)]),
outcome(1, vec![Value::int(1), Value::int(0)]),
outcome(2, vec![Value::int(1), Value::text("z")]),
outcome(3, vec![]),
];
for (at, left) in ascending.iter().enumerate() {
for (other, right) in ascending.iter().enumerate() {
assert_eq!(order(left, right), at.cmp(&other), "{at} against {other}");
}
}
}
#[test]
fn none_orders_below_every_some() {
assert!(order(&none(), &some(Value::int(-1000))).is_lt());
assert!(order(&some(Value::int(1)), &some(Value::int(2))).is_lt());
assert!(same(&some(Value::int(1)), &some(Value::int(1))));
}
#[test]
fn records_compare_field_by_field_in_declaration_order() {
let row = |rounds: i64, latest: &str| {
record(
"State",
&[
("rounds", Value::int(rounds)),
("latest", Value::text(latest)),
],
)
};
assert!(same(&row(1, "a"), &row(1, "a")));
assert!(!same(&row(1, "a"), &row(1, "b")));
assert!(
order(&row(1, "z"), &row(2, "a")).is_lt(),
"the first declared field decides"
);
assert!(order(&row(2, "a"), &row(2, "b")).is_lt());
}
#[test]
fn tuples_compare_part_by_part() {
let pair = |a: i64, b: &str| Value::tuple([Value::int(a), Value::text(b)]);
assert!(order(&pair(1, "b"), &pair(2, "a")).is_lt());
assert!(order(&pair(1, "a"), &pair(1, "b")).is_lt());
assert!(same(&pair(1, "a"), &pair(1, "a")));
}
#[test]
fn equality_holds_exactly_when_the_order_is_equal() {
let values = [Value::int(1), Value::int(2)];
for left in &values {
for right in &values {
assert_eq!(
equal(left, right).unwrap(),
compare(left, right).unwrap() == Ordering::Equal
);
}
}
}
#[test]
fn a_record_has_exactly_one_value_per_declared_field() {
let shape = RecordShape::new("Row", ["id", "quantity"]);
assert_eq!(shape.name(), "Row");
assert_eq!(shape.fields().collect::<Vec<_>>(), ["id", "quantity"]);
assert!(Record::new(std::sync::Arc::clone(&shape), vec![Value::Unit]).is_none());
assert!(Record::new(std::sync::Arc::clone(&shape), vec![Value::Unit; 3]).is_none());
let row = Record::new(
std::sync::Arc::clone(&shape),
vec![Value::text("a"), Value::int(3)],
)
.unwrap();
assert!(std::sync::Arc::ptr_eq(row.shape(), &shape));
assert_eq!(row.fields().len(), 2);
assert_eq!(flow_value::text_form(row.field(1).unwrap()).unwrap(), "3");
assert!(row.field(2).is_none());
}
#[test]
fn a_constructor_value_carries_exactly_the_payload_it_declares() {
let shape = outcome_shape();
assert_eq!(shape.name(), "Outcome");
assert!(
Variant::new(std::sync::Arc::clone(&shape), 4, vec![]).is_none(),
"no fifth constructor"
);
assert!(Variant::new(std::sync::Arc::clone(&shape), 0, vec![]).is_none());
assert!(Variant::new(std::sync::Arc::clone(&shape), 1, vec![Value::Unit]).is_none());
assert!(Variant::new(std::sync::Arc::clone(&shape), 2, vec![Value::Unit; 2]).is_some());
assert!(Variant::new(std::sync::Arc::clone(&shape), 3, vec![Value::Unit]).is_none());
let done = Variant::new(std::sync::Arc::clone(&shape), 0, vec![Value::int(1)]).unwrap();
assert_eq!(done.index(), 0);
assert_eq!(done.constructor().name(), "Done");
assert_eq!(done.constructor().payload(), &Payload::Positional(1));
assert_eq!(done.payload().len(), 1);
assert!(std::sync::Arc::ptr_eq(done.shape(), &shape));
assert_eq!(Payload::None.arity(), 0);
assert_eq!(Payload::Positional(3).arity(), 3);
assert_eq!(Payload::named(["a", "b"]).arity(), 2);
assert_eq!(shape.constructor(3).unwrap().name(), "TimedOut");
assert!(shape.constructor(4).is_none());
}
#[test]
fn a_tuple_holds_its_parts_in_order() {
let tuple = Tuple::new([Value::int(1), Value::text("a")]);
assert_eq!(tuple.parts().len(), 2);
assert_eq!(flow_value::text_form(&tuple.parts()[1]).unwrap(), "\"a\"");
}
#[test]
fn functions_tasks_and_host_tokens_have_no_equality_or_order() {
let not_data = [
native(1),
Value::Task(TaskId::FIRST),
Value::Host(HostToken::new("page-1")),
];
for value in ¬_data {
assert_eq!(compare(value, value), Err(DataError::NotData));
assert_eq!(compare(value, &Value::Unit), Err(DataError::NotData));
assert_eq!(compare(&Value::Unit, value), Err(DataError::NotData));
assert_eq!(equal(value, value), Err(DataError::NotData));
assert_eq!(flow_value::text_form(value), Err(DataError::NotData));
assert_eq!(
flow_value::interpolate(value).map(|_| ()),
Err(DataError::NotData)
);
}
}
#[test]
fn an_aggregate_holding_a_non_data_value_is_refused_where_it_is_reached() {
let task = Value::Task(TaskId::FIRST);
let in_list = Value::list([Value::int(1), task.clone()]);
let in_record = record("Step", &[("name", Value::text("a")), ("run", task.clone())]);
let in_variant = some(task.clone());
let in_tuple = Value::tuple([task.clone(), Value::Unit]);
for value in [&in_list, &in_record, &in_variant, &in_tuple] {
assert_eq!(compare(value, value), Err(DataError::NotData));
assert_eq!(flow_value::text_form(value), Err(DataError::NotData));
}
let in_dict = flow_value::Dict::from_entries([(Value::int(1), task)]).unwrap();
let in_dict = Value::Dict(in_dict);
assert_eq!(compare(&in_dict, &in_dict), Err(DataError::NotData));
assert_eq!(flow_value::text_form(&in_dict), Err(DataError::NotData));
}
#[test]
fn values_of_different_types_are_refused_rather_than_ordered() {
let values = [
Value::Unit,
Value::Bool(true),
Value::int(1),
decimal_value("1"),
Value::text("1"),
Value::Bytes(flow_value::Bytes::new(b"1")),
Value::list([]),
Value::Dict(flow_value::Dict::new()),
Value::Set(flow_value::Set::from_items([]).unwrap()),
Value::tuple([Value::Unit, Value::Unit]),
record("R", &[]),
none(),
Value::Duration(flow_value::Duration::from_millis(&flow_value::Int::from(1))),
Value::Instant(flow_value::Instant::from_unix_seconds(dec("1"))),
];
for (at, left) in values.iter().enumerate() {
for (other, right) in values.iter().enumerate() {
if at == other {
assert_eq!(compare(left, right), Ok(Ordering::Equal), "{left:?}");
} else {
assert_eq!(
compare(left, right),
Err(DataError::Mismatch),
"{left:?} {right:?}"
);
}
}
}
}
#[test]
fn values_of_two_declarations_are_refused_rather_than_compared_by_their_parts() {
let point = record("Point", &[("x", Value::int(1))]);
let size = record("Size", &[("w", Value::int(1))]);
assert_eq!(compare(&point, &size), Err(DataError::Mismatch));
assert_eq!(equal(&point, &size), Err(DataError::Mismatch));
assert!(!point.same(&size));
let one = |name: &str, ctor: &str| {
let shape = EnumShape::new(name, [Constructor::new(ctor, Payload::None)]);
Value::Variant(Variant::new(shape, 0, Vec::new()).expect("no payload"))
};
assert_eq!(
compare(&one("A", "X"), &one("B", "Y")),
Err(DataError::Mismatch)
);
assert_eq!(compare(&one("A", "X"), &one("A", "X")), Ok(Ordering::Equal));
assert_eq!(
compare(&point, &record("Point", &[("x", Value::int(2))])),
Ok(Ordering::Less)
);
}
#[test]
fn values_are_the_same_as_history_tells_them_apart() {
let host = |token: &str| Value::Host(HostToken::new(token));
assert!(host("page-1").same(&host("page-1")));
assert!(!host("page-1").same(&host("page-2")));
let one = TaskId::FIRST;
let other = one.next();
assert!(Value::Task(one).same(&Value::Task(one)));
assert!(!Value::Task(one).same(&Value::Task(other)));
let listed = Value::list([host("a"), Value::Task(one)]);
assert!(listed.same(&Value::list([host("a"), Value::Task(one)])));
assert!(!listed.same(&Value::list([host("a")])));
let made = native(1);
assert!(made.same(&made.clone()));
assert!(!made.same(&native(1)));
assert!(!Value::int(1).same(&Value::text("1")));
}
#[test]
fn a_native_value_is_recovered_only_as_its_own_type() {
let native = Native::new(Made(41));
assert_eq!(native.downcast::<Made>(), Some(&Made(41)));
assert_eq!(native.downcast::<i64>(), None);
assert_eq!(format!("{native:?}"), "<native>");
assert_eq!(HostToken::new("tok").as_str(), "tok");
}
#[test]
fn data_errors_describe_themselves() {
assert_eq!(DataError::NotData.to_string(), "the value is not data");
assert_eq!(
DataError::Mismatch.to_string(),
"the values are not of one type"
);
}