use std::sync::{Arc, Mutex};
use serde_json::{json, Value};
use xmachines_runtime::step::async_logic;
use xmachines_runtime::work::{ApplyError, Failure, Outcome, Work};
use xmachines_runtime::*;
fn load(def: Value, registry: &Registry<Value, Value>) -> Arc<Machine<Value, Value>> {
Arc::new(Machine::from_json(&def, registry).unwrap())
}
fn hosting(names: &[&str]) -> Registry<Value, Value> {
let mut r = Registry::new();
r.host_actions(HostActions::Named(names.iter().map(|n| n.to_string()).collect()));
r
}
fn auditing() -> Value {
json!({
"id": "order",
"initial": "open",
"states": {
"open": {
"on": { "pay": { "target": "paid", "actions": [{ "type": "audit", "params": { "what": "paid" } }] } }
},
"paid": { "entry": [{ "type": "audit" }] }
}
})
}
#[test]
fn a_host_action_waits_for_the_host_and_is_done_by_a_work_input() {
let mut actor = Actor::start(load(auditing(), &hosting(&["audit"])), 0).unwrap();
let step = actor.apply(&[json!({ "type": "pay" })]).unwrap();
assert_eq!(step.root.value, json!("paid"));
let work = serde_json::to_value(&step.work).unwrap();
assert_eq!(
work,
json!([
{ "kind": "action", "id": "system:0", "actor": "order", "type": "audit", "params": { "what": "paid" } },
{ "kind": "action", "id": "system:1", "actor": "order", "type": "audit" }
])
);
let mut actor = Actor::restore(actor.machine().clone(), &actor.persist()).unwrap();
assert_eq!(actor.work().len(), 2);
let step = actor.apply(&[json!({ "kind": "work", "id": "system:0", "outcome": "done" })]).unwrap();
assert_eq!(step.work.iter().map(Work::id).collect::<Vec<_>>(), ["system:1"]);
}
#[test]
fn a_named_host_action_runs_no_implementation_of_the_registry() {
let ran = Arc::new(Mutex::new(0));
let mut r = hosting(&["audit"]);
let counter = ran.clone();
r.action("audit", move || *counter.lock().unwrap() += 1);
let mut actor = Actor::start(load(auditing(), &r), 0).unwrap();
actor.apply(&[json!({ "type": "pay" })]).unwrap();
assert_eq!(*ran.lock().unwrap(), 0);
assert_eq!(actor.work().len(), 2);
}
#[test]
fn unimplemented_host_actions_are_those_the_registry_lacks() {
let ran = Arc::new(Mutex::new(Vec::new()));
let def = json!({
"initial": "a",
"states": { "a": { "on": { "go": { "actions": [{ "type": "audit" }, { "type": "note" }] } } } }
});
let mut r = Registry::new();
let notes = ran.clone();
r.action("note", move || notes.lock().unwrap().push("note")).host_actions(HostActions::Unimplemented);
let mut actor = Actor::start(load(def.clone(), &r), 0).unwrap();
let step = actor.apply(&[json!({ "type": "go" })]).unwrap();
assert_eq!(*ran.lock().unwrap(), ["note"]);
assert!(matches!(&step.work[..], [Work::Action { ty, .. }] if ty == "audit"));
assert!(Machine::<Value, Value>::from_json(&def, &Registry::new()).is_err());
}
#[test]
fn a_host_action_taken_in_the_step_its_actor_stops_is_kept() {
let child = json!({
"id": "child",
"initial": "working",
"states": {
"working": {
"exit": [{ "type": "track", "params": { "why": "exit" } }],
"on": { "finish": { "target": "finished", "actions": [{ "type": "track", "params": { "why": "finish" } }] } }
},
"finished": { "type": "final" }
}
});
let mut r = hosting(&["track"]);
let child = load(child, &r);
r.actor("child", child);
let parent = json!({
"id": "parent",
"initial": "idle",
"states": {
"idle": { "on": { "start": { "target": "running" } } },
"running": { "invoke": { "src": "child", "id": "worker", "onDone": { "target": "idle" } } }
}
});
let mut actor = Actor::start(load(parent, &r), 0).unwrap();
actor.apply(&[json!({ "type": "start" })]).unwrap();
actor.send_to("parent/worker", json!({ "type": "finish" }), 0).unwrap();
assert_eq!(actor.value(), Some(json!("idle")));
let work = serde_json::to_value(actor.work()).unwrap();
assert_eq!(
work,
json!([
{ "kind": "action", "id": "system:0", "actor": "parent/worker", "type": "track", "params": { "why": "exit" } },
{ "kind": "action", "id": "system:1", "actor": "parent/worker", "type": "track", "params": { "why": "finish" } }
])
);
let step = actor
.apply(&[
json!({ "kind": "work", "id": "system:0", "outcome": "done" }),
json!({ "kind": "work", "id": "system:1", "outcome": "done" }),
])
.unwrap();
assert!(step.work.is_empty());
}
#[test]
fn invoked_work_is_listed_by_its_src_and_input_and_settled() {
let def = json!({
"id": "user",
"initial": "loading",
"context": { "user": null },
"states": {
"loading": {
"invoke": {
"src": "fetchUser",
"input": { "id": 7 },
"onDone": { "target": "ready" },
"onError": { "target": "failed" }
}
},
"ready": {},
"failed": {}
}
});
let mut r = Registry::new();
r.actor("fetchUser", Arc::new(async_logic(Some("fetchUser".into()), None).unwrap()));
let machine = load(def, &r);
let mut actor = Actor::start(machine.clone(), 0).unwrap();
let work = actor.work();
let [Work::Invoke { id, src, input, .. }] = &work[..] else { panic!("{work:?}") };
assert_eq!((src.as_str(), input), ("fetchUser", &Some(json!({ "id": 7 }))));
let id = id.clone();
let before = actor.persist();
let error = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "done" })]).unwrap_err();
assert_eq!(error.code(), Some("WORKFLOW_INVALID_WORK_RESULT"));
let step = actor.apply(&[json!({ "kind": "work", "id": "system:99", "outcome": "resolved" })]).unwrap();
assert_eq!((step.root.value, step.work.len()), (json!("loading"), 1));
assert_eq!(actor.persist(), before);
let step = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "resolved", "data": null })]).unwrap();
assert_eq!(step.root.value, json!("ready"));
assert!(step.work.is_empty());
let mut actor = Actor::start(machine, 0).unwrap();
actor.settle(&id, Outcome::Rejected, Some(json!("down"))).unwrap();
assert_eq!(actor.value(), Some(json!("failed")));
}
fn emitting() -> Value {
json!({
"id": "m",
"initial": "a",
"context": { "n": 0 },
"states": {
"a": {
"entry": [{ "type": "@xstate.emit", "event": { "type": "inA" } }],
"on": {
"go": { "target": "b", "context": { "n": 1 } },
"boom": { "actions": [{ "type": "boom" }] }
},
"after": { "100": { "target": "c" } }
},
"b": {
"entry": [{ "type": "@xstate.emit", "event": { "type": "inB" } }],
"on": { "back": { "target": "a" }, "boom": { "actions": [{ "type": "boom" }] } }
},
"c": {}
}
})
}
fn booming() -> Registry<Value, Value> {
let mut r = Registry::new();
r.try_action_with("boom", |_: &Value| Err("boom".into()));
r
}
#[test]
fn an_event_that_fails_refuses_the_whole_chunk() {
let mut actor = Actor::start(load(emitting(), &booming()), 0).unwrap();
assert_eq!(actor.take_emitted(), [json!({ "type": "inA" })]);
let before = actor.persist();
let error = actor
.apply(&[json!({ "kind": "time", "now": 50 }), json!({ "type": "go" }), json!({ "type": "boom" })])
.unwrap_err();
assert_eq!(error, ApplyError::rejected("boom"));
assert_eq!(actor.persist(), before);
assert!(actor.take_emitted().is_empty());
assert_eq!((actor.now(), actor.status()), (0, Status::Active));
let step = actor.apply(&[json!({ "kind": "time", "now": 50 }), json!({ "type": "go" })]).unwrap();
assert_eq!(step.root.value, json!("b"));
assert_eq!(step.root.context, json!({ "n": 1 }));
assert_eq!(step.emitted, [json!({ "type": "inB" })]);
assert_eq!((step.time, step.deadline), (50, None));
let step = actor.apply(&[json!({ "type": "back" })]).unwrap();
assert_eq!((step.time, step.deadline), (50, Some(150)));
let step = actor.apply(&[json!({ "kind": "time", "now": 150 })]).unwrap();
assert_eq!(step.root.value, json!("c"));
}
fn failing_timer() -> Value {
json!({
"id": "armed",
"initial": "idle",
"options": { "maxIterations": 100 },
"states": {
"idle": { "on": { "arm": { "target": "armed", "actions": [{ "type": "audit" }] } } },
"armed": {
"after": { "25": { "target": "a" } },
"on": { "ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] } }
},
"a": { "always": { "target": "b" } },
"b": { "always": { "target": "a" } }
}
})
}
#[test]
fn a_time_input_that_fails_ends_the_run_in_error_and_keeps_what_came_before() {
let machine = load(failing_timer(), &hosting(&["audit"]));
let mut actor = Actor::start(machine.clone(), 0).unwrap();
actor.apply(&[json!({ "type": "arm" })]).unwrap();
let step = actor
.apply(&[
json!({ "kind": "time", "now": 10 }),
json!({ "type": "ping" }),
json!({ "kind": "time", "now": 30 }),
json!({ "type": "ping" }),
])
.unwrap();
assert_eq!(step.emitted, [json!({ "type": "pong" })]);
assert_eq!((step.root.status.as_str(), &step.root.value), ("error", &json!("armed")));
assert!(step.root.error.as_ref().is_some_and(|e| e["message"].is_string()), "{:?}", step.root.error);
assert_eq!((step.time, step.deadline), (10, None));
assert!(matches!(&step.work[..], [Work::Action { ty, .. }] if ty == "audit"));
let id = step.work[0].id().to_owned();
let mut actor = Actor::restore(machine, &actor.persist()).unwrap();
assert_eq!(actor.status(), Status::Error);
let step = actor.apply(&[json!({ "kind": "time", "now": 500 })]).unwrap();
assert_eq!((step.time, step.root.status.as_str()), (10, "error"));
let before = actor.persist();
let error = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "done" }), json!({ "type": "ping" })]);
assert_eq!(error.unwrap_err(), ApplyError::rejected("The run is in error."));
assert_eq!(actor.persist(), before);
let error = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "resolved" })]).unwrap_err();
assert_eq!(error.code(), Some("WORKFLOW_INVALID_WORK_RESULT"));
let step = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "done" })]).unwrap();
assert!(step.work.is_empty());
}
#[test]
fn a_work_input_that_fails_ends_the_run_in_error() {
let def = json!({
"id": "loader",
"initial": "loading",
"states": {
"loading": { "invoke": { "src": "fetch", "onDone": { "target": "done", "actions": [{ "type": "boom" }] } } },
"done": {}
}
});
let mut r = booming();
r.actor("fetch", Arc::new(async_logic(Some("fetch".into()), None).unwrap()));
let mut actor = Actor::start(load(def, &r), 0).unwrap();
let id = actor.work()[0].id().to_owned();
let step = actor
.apply(&[
json!({ "kind": "time", "now": 5 }),
json!({ "kind": "work", "id": id, "outcome": "resolved" }),
json!({ "kind": "time", "now": 9 }),
])
.unwrap();
assert_eq!((step.root.status.as_str(), &step.root.value, step.time), ("error", &json!("loading"), 5));
assert!(step.work.is_empty());
assert!(actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "resolved" })]).is_ok());
}
#[test]
fn an_event_to_a_run_that_is_done_is_rejected() {
let def =
json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": { "type": "final" } } });
let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
assert_eq!(actor.apply(&[json!({ "type": "go" })]).unwrap().root.status, "done");
let error = actor.apply(&[json!({ "kind": "time", "now": 5 }), json!({ "type": "go" })]).unwrap_err();
assert_eq!(error, ApplyError::rejected("The run is done."));
assert_eq!(actor.now(), 0);
assert_eq!(actor.apply(&[json!({ "kind": "time", "now": 5 })]).unwrap().time, 5);
}
#[test]
fn a_time_input_of_control_inputs_alone_fires_at_most_max_timers() {
let def = json!({
"id": "beat",
"initial": "on",
"states": {
"on": {
"after": {
"10": { "target": "on", "reenter": true, "actions": [{ "type": "@xstate.emit", "event": { "type": "tick" } }] }
},
"on": { "ping": {} }
}
}
});
let machine = load(def, &Registry::new());
let mut actor = Actor::start(machine.clone(), 0).unwrap();
assert_eq!(actor.max_timers(), work::DEFAULT_MAX_TIMERS);
actor.set_max_timers(3);
let step = actor.apply(&[json!({ "kind": "time", "now": 100 })]).unwrap();
assert_eq!((step.emitted.len(), step.time, step.deadline), (3, 30, Some(40)));
let step = actor.apply(&[json!({ "kind": "time", "now": 100 }), json!({ "type": "ping" })]).unwrap();
assert_eq!((step.emitted.len(), step.time), (7, 100));
for now in [json!(50), json!(-5)] {
assert_eq!(actor.apply(&[json!({ "kind": "time", "now": now })]).unwrap().time, 100);
}
let mut actor = Actor::restore(machine, &actor.persist()).unwrap();
actor.set_max_timers(1);
assert_eq!(actor.apply(&[json!({ "kind": "time", "now": 1000 })]).unwrap().time, 110);
}
#[test]
fn inputs_are_checked_before_anything_is_applied() {
let def = json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
for bad in [
json!({ "kind": "time", "now": 10.5 }),
json!({ "kind": "time", "now": 9007199254740992u64 }),
json!({ "kind": "time", "now": -9007199254740992i64 }),
json!({ "kind": "time", "now": "1" }),
json!({ "kind": "time", "now": 1, "type": "go" }),
json!({ "kind": "work", "id": "system:0", "outcome": "done", "type": "go" }),
json!({ "kind": "work", "id": "system:0", "outcome": "finished" }),
json!({ "kind": "work", "id": 0, "outcome": "done" }),
json!({ "kind": "work", "id": "system:0", "outcome": "done", "data": 1 }),
json!({ "kind": "work", "id": "system:0", "outcome": "done", "data": null }),
json!({ "kind": "nope" }),
json!({ "now": 1 }),
json!({ "type": 1 }),
json!("go"),
] {
let error = actor.apply(&[json!({ "type": "go" }), bad.clone()]).unwrap_err();
assert_eq!(error.code(), Some("WORKFLOW_INVALID_INPUT"), "{bad}");
}
assert_eq!(actor.value(), Some(json!("a")));
assert_eq!(actor.apply(&[json!({ "kind": "time", "now": 5.0, "note": 1 })]).unwrap().time, 5);
assert_eq!(actor.apply(&[json!({ "kind": "time", "now": -9007199254740991i64 })]).unwrap().time, 5);
let step = actor.apply(&[json!({ "type": "go", "kind": "book" })]).unwrap();
assert_eq!(step.root.value, json!("b"));
}
#[test]
fn a_failed_root_refuses_the_chunk_and_keeps_its_state() {
let def = json!({
"initial": "a",
"states": { "a": { "on": { "go": { "target": "b", "actions": [{ "type": "boom" }] } } }, "b": {} }
});
let mut actor = Actor::start(load(def, &booming()), 0).unwrap();
let error = actor.apply(&[json!({ "type": "go" })]).unwrap_err();
assert!(error.rejection().is_some_and(|r| r.message == "boom"), "{error}");
assert_eq!((actor.status(), actor.value()), (Status::Active, Some(json!("a"))));
}
#[test]
fn a_host_action_taken_as_the_root_starts_and_stops_is_kept() {
let def = json!({
"id": "once",
"initial": "a",
"states": { "a": { "always": { "target": "b", "actions": [{ "type": "audit" }] } }, "b": { "type": "final" } }
});
let actor = Actor::start(load(def, &hosting(&["audit"])), 0).unwrap();
assert_eq!(actor.status(), Status::Done);
assert!(matches!(&actor.work()[..], [Work::Action { ty, actor, .. }] if ty == "audit" && actor == "once"));
}
#[test]
fn a_host_action_a_child_takes_as_it_starts_and_stops_is_kept() {
let child = json!({
"id": "child",
"initial": "a",
"states": { "a": { "entry": [{ "type": "track" }], "always": { "target": "b" } }, "b": { "type": "final" } }
});
let mut r = hosting(&["track"]);
let child = load(child, &r);
r.actor("child", child);
let parent = json!({
"id": "parent",
"initial": "running",
"states": { "running": { "invoke": { "src": "child", "id": "worker", "onDone": { "target": "over" } } }, "over": {} }
});
let mut actor = Actor::start(load(parent, &r), 0).unwrap();
assert_eq!(actor.value(), Some(json!("over")));
let work = actor.work();
assert!(matches!(&work[..], [Work::Action { ty, actor, .. }] if ty == "track" && actor == "parent/worker"));
let step = actor.apply(&[json!({ "kind": "work", "id": work[0].id(), "outcome": "done" })]).unwrap();
assert!(step.work.is_empty());
}
#[test]
fn a_child_stopped_by_its_parent_runs_no_exit_action() {
let child = json!({
"id": "child",
"initial": "working",
"states": { "working": { "exit": [{ "type": "track", "params": { "why": "exit" } }] } }
});
let mut r = hosting(&["track"]);
let child = load(child, &r);
r.actor("child", child);
let parent = json!({
"id": "parent",
"initial": "idle",
"states": {
"idle": { "on": { "start": { "target": "running" } } },
"running": { "invoke": { "src": "child", "id": "worker" }, "on": { "cancel": { "target": "idle" } } }
}
});
let mut actor = Actor::start(load(parent, &r), 0).unwrap();
actor.apply(&[json!({ "type": "start" })]).unwrap();
let step = actor.apply(&[json!({ "type": "cancel" })]).unwrap();
assert_eq!(step.root.value, json!("idle"));
assert!(step.work.is_empty());
}
#[test]
fn can_is_whether_a_transition_is_selected() {
let def = json!({
"initial": "a",
"states": {
"a": { "on": {
"go": { "target": "b" },
"stay": {},
"maybe": { "target": "b", "guard": { "type": "no" } }
} },
"b": { "type": "final" }
}
});
let mut r = Registry::new();
r.guard("no", |_| false);
let mut actor = Actor::start(load(def, &r), 0).unwrap();
assert!(actor.can_json(&json!({ "type": "go" })).unwrap());
assert!(actor.can_json(&json!({ "type": "stay" })).unwrap());
assert_eq!(actor.check_json(&json!({ "type": "stay" })).unwrap(), TransitionCheck::Unhandled);
assert!(!actor.can_json(&json!({ "type": "maybe" })).unwrap());
assert!(!actor.can_json(&json!({ "type": "unknown" })).unwrap());
actor.apply(&[json!({ "type": "go" })]).unwrap();
assert!(!actor.can_json(&json!({ "type": "go" })).unwrap());
}
fn racing() -> Arc<Machine<Value, Value>> {
let mut r = booming();
let kid = json!({
"id": "kid",
"initial": "wait",
"states": { "wait": { "after": { "10": { "target": "done", "actions": [{ "type": "boom" }] } } }, "done": {} }
});
let kid = load(kid, &r);
r.actor("kid", kid);
let def = json!({
"id": "race",
"type": "parallel",
"states": {
"x": { "initial": "wait", "states": { "wait": { "invoke": { "src": "kid", "id": "kid" } } } },
"y": {
"initial": "wait",
"states": {
"wait": {
"after": { "5": { "target": "ticked", "actions": [{ "type": "@xstate.emit", "event": { "type": "tick" } }] } }
},
"ticked": {
"after": { "5": { "target": "late", "actions": [{ "type": "@xstate.emit", "event": { "type": "late" } }] } }
},
"late": {}
}
}
}
});
load(def, &r)
}
#[test]
fn a_time_input_that_puts_the_root_in_error_with_no_failure_ends_the_run() {
let mut actor = Actor::start(racing(), 0).unwrap();
let step = actor
.apply(&[
json!({ "kind": "time", "now": 5 }),
json!({ "kind": "time", "now": 20 }),
json!({ "kind": "time", "now": 30 }),
])
.unwrap();
assert_eq!(step.emitted, [json!({ "type": "tick" })]);
assert_eq!((step.root.status.as_str(), step.time, step.deadline), ("error", 5, None));
assert_eq!(step.root.value, json!({ "x": "wait", "y": "ticked" }));
assert_eq!(step.root.error, Some(json!({ "message": "boom" })));
let restored = Actor::restore(actor.machine().clone(), &actor.persist()).unwrap();
assert_eq!(restored.error(), Some(&json!({ "message": "boom" })));
assert_eq!((restored.status(), restored.next_deadline()), (Status::Error, None));
}
#[test]
fn invoked_work_rejected_that_no_on_error_handles_ends_the_run() {
let def = json!({
"id": "pay",
"initial": "idle",
"states": {
"idle": { "on": { "pay": { "target": "paying" } } },
"paying": {
"invoke": { "src": "charge", "id": "charge", "onDone": { "target": "paid" } },
"on": { "ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] } }
},
"paid": { "type": "final" }
}
});
let mut registry = Registry::new();
registry.actor("charge", Arc::new(async_logic(Some("charge".into()), None).unwrap()));
let mut actor = Actor::start(load(def, ®istry), 0).unwrap();
let id = actor.apply(&[json!({ "type": "pay" })]).unwrap().work[0].id().to_owned();
let step = actor
.apply(&[
json!({ "kind": "work", "id": id, "outcome": "rejected", "data": { "code": "declined" } }),
json!({ "type": "ping" }),
])
.unwrap();
assert!(step.emitted.is_empty());
assert_eq!(step.root.status, "error");
assert_eq!(step.root.error, Some(json!({ "message": "The machine failed.", "data": { "code": "declined" } })));
assert!(step.work.is_empty());
assert_eq!(actor.apply(&[json!({ "type": "ping" })]).unwrap_err(), ApplyError::rejected("The run is in error."));
}
#[test]
fn an_event_to_a_stopped_run_is_rejected() {
let def = json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
actor.stop().unwrap();
assert_eq!(actor.apply(&[json!({ "type": "go" })]).unwrap_err(), ApplyError::rejected("The run is stopped."));
assert_eq!(actor.status(), Status::Stopped);
}
#[test]
fn an_event_of_xstates_own_type_is_rejected_and_never_taken() {
let def = json!({
"initial": "a",
"states": { "a": { "on": { "xstate.done.actor": { "target": "b" }, "go": { "target": "b" } } }, "b": {} }
});
let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
for ty in ["xstate.done.actor", "xstate.error.execution", "xstate.stop"] {
assert!(!actor.can_json(&json!({ "type": ty })).unwrap(), "{ty}");
let error = actor.apply(&[json!({ "type": "go" }), json!({ "type": ty })]).unwrap_err();
assert!(error.rejection().is_some(), "{ty}: {error}");
assert_eq!(actor.value(), Some(json!("a")));
}
}
#[test]
fn a_rejection_and_a_fault_are_told_apart_as_json() {
let rejected = ApplyError::rejected_with(Failure { message: "no".into(), data: Some(json!({ "code": 1 })) });
assert_eq!(
serde_json::to_value(&rejected).unwrap(),
json!({ "rejected": { "message": "no", "data": { "code": 1 } } })
);
assert_eq!(serde_json::to_value(ApplyError::rejected("no")).unwrap(), json!({ "rejected": { "message": "no" } }));
let fault = ApplyError::invalid_input("bad");
assert_eq!(serde_json::to_value(&fault).unwrap(), json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "bad" }));
for error in [rejected, fault] {
let json = serde_json::to_value(&error).unwrap();
assert_eq!(serde_json::from_value::<ApplyError>(json).unwrap(), error);
}
}
fn parent_of_kid() -> Value {
json!({ "id": "p", "initial": "idle", "states": {
"idle": { "on": {
"go": { "target": "running" },
"ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] }
} },
"running": { "invoke": { "src": "kid", "id": "k" } }
} })
}
fn an_event_that_fails_the_root_through_its_child(registry: Registry<Value, Value>) {
let mut actor = Actor::start(load(parent_of_kid(), ®istry), 0).unwrap();
let error = actor.apply(&[json!({ "type": "ping" }), json!({ "type": "go" })]).unwrap_err();
let rejected = error.rejection().expect("a rejection, not a fault");
assert_eq!(rejected.message, "boom");
assert_eq!((actor.status(), actor.value()), (Status::Active, Some(json!("idle"))));
let step = actor.apply(&[]).unwrap();
assert!(step.emitted.is_empty(), "{:?}", step.emitted);
assert_eq!(actor.apply(&[json!({ "type": "ping" })]).unwrap().emitted, [json!({ "type": "pong" })]);
}
#[test]
fn an_event_whose_registry_child_fails_is_rejected() {
let mut r: Registry<Value, Value> = Registry::new();
r.try_action_with("boom", |_: &Value| Err("boom".into()));
let kid = load(json!({ "id": "kid", "initial": "a", "states": { "a": { "entry": [{ "type": "boom" }] } } }), &r);
r.actor("kid", kid);
an_event_that_fails_the_root_through_its_child(r);
}
#[test]
fn an_event_whose_child_of_json_fails_is_rejected() {
let mut r: Registry<Value, Value> = Registry::new();
r.expr("boom", |args| {
args.fail("boom");
Value::Null
});
let kid = load(
json!({ "id": "kid", "initial": "a", "context": { "n": 0 }, "states": { "a": {
"entry": [{ "type": "@xstate.assign", "context": { "n": { "@code": "boom", "@lang": "rust" } } }]
} } }),
&r,
);
r.actor("kid", kid);
an_event_that_fails_the_root_through_its_child(r);
}