Add a little tiny bit of testing for the fsm.

main
Zed A. Shaw 2 months ago
parent 5a96217188
commit ea192a515b
  1. 8
      js/fsm.mjs
  2. 56
      js/fsm_test.mjs

@ -117,8 +117,8 @@
names in the event handler class (`VideoEvents` above). names in the event handler class (`VideoEvents` above).
*/ */
import assert from "./assert.js";
import { log } from "./logging.js"; import assert from "assert";
/* /*
A very simple Finite State Machine class. Nothing fancy, just a state A very simple Finite State Machine class. Nothing fancy, just a state
@ -205,12 +205,12 @@ export class FSM {
assert(next_state.length == 2, `Returning an array only allows 2 elements (state, func) but you returned ${next_state}`); assert(next_state.length == 2, `Returning an array only allows 2 elements (state, func) but you returned ${next_state}`);
let [state, func] = next_state; let [state, func] = next_state;
log.debug(`FSM ${this.events.constructor.name}: (${event}) = ${this.state} -> ${state} (${args})`, "DATA:", this.data, func ? `THEN ${func.name}()` : undefined); console.debug(`FSM ${this.events.constructor.name}: (${event}) = ${this.state} -> ${state} (${args})`, "DATA:", this.data, func ? `THEN ${func.name}()` : undefined);
this.transition(state); this.transition(state);
await func(); await func();
} else { } else {
log.debug(`FSM ${this.events.constructor.name}: (${event}) = ${this.state} -> ${next_state} (${args})`, "DATA:", this.data); console.debug(`FSM ${this.events.constructor.name}: (${event}) = ${this.state} -> ${next_state} (${args})`, "DATA:", this.data);
this.transition(next_state); this.transition(next_state);
} }

@ -0,0 +1,56 @@
import FSM from "./fsm.mjs";
import assert from "assert";
const add_test = () => {
console.log("Additional function call on state transition passed.");
}
class TestMachine {
constructor(data) {
console.log("DATA IS", data);
this.data = data;
}
async open(state, inc) {
switch(state) {
case "START":
console.log("THIS", this);
this.data.count = this.data.count + inc;
return "OPEN";
default:
return "ERROR";
}
}
close(state, inc) {
switch(state) {
case "OPEN":
this.data.count = this.data.count + inc;
return ["CLOSED", add_test];
default:
return "ERROR";
}
}
}
let data = {count: 0};
let events = new TestMachine(data);
let fsm1 = new FSM(data, events);
fsm1.onTransition((fsm) => {
console.log("On transition: ", fsm.state);
});
await fsm1.do('open', 3);
assert(fsm1.state === "OPEN");
assert(data.count === 3);
await fsm1.do('close', 4);
assert(fsm1.state === "CLOSED");
assert(data.count === 7);
// test the errors
await fsm1.do('open');
assert(fsm1.state === "ERROR");
assert(data.count === 7); // still 2 after error
Loading…
Cancel
Save