Files
pulse/tests/condition.test.js
T
jaredandClaude Opus 5.5 dc732a1ec5
CI / UI screenshots (before/after) (push) Skipped
CI / Test (jest) (push) Successful in 32s
CI / Security (npm audit) (push) Successful in 15s
CI / Integration (api) (push) Successful in 4m4s
CI / Scan (secrets, workflows, shell) (push) Successful in 3m26s
CI / Lint (eslint) (pull_request) Successful in 1m12s
CI / Test (jest) (pull_request) Successful in 1m11s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 7m1s
CI / Integration (api) (pull_request) Successful in 7m41s
CI / UI screenshots (before/after) (pull_request) Successful in 28s
CI / UI (playwright) (pull_request) Successful in 4m41s
CI / Lint (eslint) (push) Successful in 24s
CI / Security (npm audit) (pull_request) Successful in 23s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / UI (playwright) (push) Successful in 3m41s
CI / Deploy (push) Skipped
CI / Deploy worker (push) Skipped
CI / Notify (push) Skipped
Fix abort, missing goto, offline schedules and the cron 500 (#8, #20, #9)
The four known-bug tests from #59 now pass as normal tests.

- #8 abort: each workflow execution gets an AbortController. The abort
  route fires it; the engine checks it before every step and stops; wait
  steps, retry delays and waits for a worker's result end as soon as it
  fires. New test: aborting during a 20 s command stops the workflow
  within seconds and runs no further step.
- #20 goto to a missing step: the execution now fails (it reported
  completed). Workflows are also checked on save: a goto, route or prompt
  route to a step id that doesn't exist is a 400 ('end' is always valid).
  A workflow saved before the check still fails at runtime (tested by
  writing one directly).
- #9 schedules whose worker is offline: instead of skipping silently, the
  scheduler records a failed run ('Worker offline: the scheduled command
  was not sent'), visible in Executions.
- An invalid cron expression (or any bad schedule) is a 400 with the
  parser's message instead of a 500.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:54:32 -05:00

151 lines
6.9 KiB
JavaScript

'use strict';
const vm = require('vm');
const { evaluateCondition, checkCondition } = require('../lib/condition');
const { evalCondition, conditionErrors, gotoErrors } = require('../lib/utils');
// Every condition used by the production workflows (2026-11-22).
const PRODUCTION = [
"params.switch_ip && params.switch_ip.trim() !== ''",
"(state.carrier||'x') === 'error'",
"(state.carrier||'1') === '0' && (state.has_dom||'no') === 'yes'",
"(state.carrier||'1') === '0'",
"parseInt(state.carrier_changes||'0') > 100 && (state.has_dom||'no') === 'yes'",
"parseInt(state.carrier_changes||'0') > 100",
"parseInt(state.carrier_changes||'0') > 20 && (state.has_dom||'no') === 'yes'",
"parseInt(state.carrier_changes||'0') > 20",
"(state.duplex||'full') === 'half'",
"parseInt(state.crc_errors||'0') > 10 || parseInt(state.frame_errors||'0') > 10",
"(state.has_dom||'no') === 'no'",
"state.sfp_rx_dbm === 'no_dom' || parseFloat(state.sfp_rx_dbm||'0') < -26",
"parseFloat(state.sfp_rx_dbm||'0') < -18",
"parseFloat(state.sfp_tx_dbm||'0') < -10",
"(state.carrier||'0') === '1' && (state.operstate||'down') === 'up'",
"state.sfp_rx_dbm && state.sfp_rx_dbm !== 'no_dom' && parseFloat(state.sfp_rx_dbm||'0') < -25",
"state.sfp_rx_dbm && state.sfp_rx_dbm !== 'no_dom' && parseFloat(state.sfp_rx_dbm||'0') < -18",
"(state.carrier||'0') === '0'",
"(state.duplex||'half') === 'full' && parseInt(state.crc_errors||'0') < 10",
"(state.duplex||'half') === 'full'",
"(state.has_dom||'no') === 'yes' && state.sfp_rx_dbm !== 'no_dom' && parseFloat(state.sfp_rx_dbm||'0') < -18",
"(state.has_dom||'no') === 'yes'",
"state.ring_rx_cur && state.ring_rx_max && state.ring_rx_cur !== 'unknown' && state.ring_rx_max !== 'unknown' && parseInt(state.ring_rx_cur||'0') < parseInt(state.ring_rx_max||'0') && parseInt(state.rx_dropped||'0') + parseInt(state.rx_missed||'0') > 0",
"parseInt(state.rx_dropped||'0') + parseInt(state.rx_missed||'0') > 100",
"(state.flowctl_rx||'on') === 'on' || (state.flowctl_tx||'on') === 'on'",
"state.speed && state.speed !== '-1' && parseInt(state.speed||'0') > 0 && (state.duplex||'full') === 'full'",
];
const VALUES = [undefined, '', '0', '1', '-1', '5', '11', '25', '150', '1000', '-12', '-20', '-27', 'error', 'yes', 'no',
'no_dom', 'full', 'half', 'on', 'off', 'up', 'down', 'unknown', ' 10.0.0.1 '];
// Small deterministic PRNG so failures are reproducible.
function rng(seed) { return () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648; }
describe('production conditions behave exactly as plain JavaScript did', () => {
for (const cond of PRODUCTION) {
test(cond, () => {
expect(() => checkCondition(cond)).not.toThrow();
const keys = [...new Set([...cond.matchAll(/(?:state|params)\.([a-z_]+)/g)].map(m => m[1]))];
const rand = rng(cond.length);
for (let i = 0; i < 150; i++) {
const state = {}; const params = {};
for (const k of keys) {
const v = VALUES[Math.floor(rand() * VALUES.length)];
if (v !== undefined) { state[k] = v; params[k] = v; }
}
// Reference: the old behaviour (vm), on trusted test input only.
const expected = !!vm.runInNewContext(cond, { state, params, parseInt, parseFloat });
expect(evaluateCondition(cond, state, params)).toBe(expected);
}
});
}
});
describe('the language', () => {
const ev = (c, state = {}, params = {}) => evaluateCondition(c, state, params);
test('operators, precedence and literals', () => {
expect(ev('1 + 2 * 3 === 7')).toBe(true);
expect(ev('(1 + 2) * 3 === 9')).toBe(true);
expect(ev('!false && (null || "x") === "x"')).toBe(true);
expect(ev('-5 < -4 && 10 % 3 === 1 && 7 / 2 === 3.5')).toBe(true);
expect(ev("'a' + 1 === 'a1'")).toBe(true);
expect(ev('1 == "1" && 1 != 2')).toBe(true);
expect(ev("state.x === undefined", {})).toBe(true);
expect(ev("'it\\'s' === \"it's\"")).toBe(true);
});
test('functions and string methods', () => {
expect(ev("parseInt('42px') === 42 && parseFloat('-3.5') === -3.5")).toBe(true);
expect(ev("Number('7') === 7 && String(7) === '7' && Boolean('')=== false")).toBe(true);
expect(ev("state.h.toLowerCase().startsWith('web') && state.h.includes('01')", { h: 'WEB-01' })).toBe(true);
expect(ev("state.h.length === 6", { h: 'WEB-01' })).toBe(true);
expect(ev('promptResponse === "Yes"', { promptResponse: 'Yes' })).toBe(true);
});
});
describe('a condition can only read the workflow data', () => {
const rejected = [
'this',
'state.constructor',
'state.__proto__',
'params.prototype',
"state['x']",
'globalThis',
'process',
'require',
'Function',
'eval("1")',
'state.x = 1',
'(() => 1)()',
'`template`',
'1; 2',
"state.x.toString()",
"'a'.constructor",
"parseInt.call(null, '1')",
];
test.each(rejected)('%s is refused', cond => {
expect(() => checkCondition(cond)).toThrow();
expect(evalCondition(cond, {}, {})).toBe(false); // and the engine treats it as false
});
test('inherited properties are invisible', () => {
expect(evaluateCondition('state.toString === undefined && state.hasOwnProperty === undefined', {}, {})).toBe(true);
});
test('string methods only work on strings', () => {
expect(evalCondition('state.n.trim() === "1"', { n: 1 }, {})).toBe(false);
});
test('huge or deeply nested input is refused', () => {
expect(() => checkCondition('1+'.repeat(2000) + '1')).toThrow();
expect(() => checkCondition('('.repeat(200) + '1' + ')'.repeat(200))).toThrow();
});
});
describe('conditionErrors', () => {
test('lists every condition that does not parse, by step', () => {
const problems = conditionErrors({ steps: [
{ id: 'ok', type: 'execute', condition: "params.env === 'prod'" },
{ id: 'bad', type: 'execute', condition: 'state.constructor' },
{ id: 'route', type: 'route', conditions: [{ if: 'state.x ===' }, { default: true, goto: 'end' }] },
] });
expect(problems.map(p => p.step)).toEqual(['bad', 'route']);
});
test('accepts a JSON string definition and ignores malformed JSON', () => {
expect(conditionErrors(JSON.stringify({ steps: [{ condition: 'process' }] }))).toHaveLength(1);
expect(conditionErrors('{not json')).toEqual([]);
});
});
describe('gotoErrors (#20)', () => {
test('lists jumps to step ids that do not exist; end is always valid', () => {
const problems = gotoErrors({ steps: [
{ id: 'a', type: 'execute', goto: 'c' },
{ id: 'b', type: 'route', conditions: [{ if: 'true', goto: 'nope' }, { default: true, goto: 'end' }] },
{ id: 'c', type: 'prompt', routes: { Yes: 'a', No: '__end__', Maybe: 'missing' } },
] });
expect(problems.map(p => `${p.step}->${p.goto}`)).toEqual(['b->nope', 'c->missing']);
});
test('accepts a JSON string and ignores malformed JSON', () => {
expect(gotoErrors(JSON.stringify({ steps: [{ id: 'x', goto: 'y' }] }))).toHaveLength(1);
expect(gotoErrors('{oops')).toEqual([]);
});
});