Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/workflows/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ Notes on the newer filters:

Operators bind from loosest to tightest as `or`, `and`, `not`, then the comparisons. All comparisons (`==`, `!=`, `>`, `<`, `>=`, `<=`, `in`, `not in`) share one level and are evaluated left to right; none has priority over another. `{{ a == b > 0 }}` therefore means `{{ (a == b) > 0 }}`. To combine comparisons, use parentheses or `and`/`or`.

Comparisons follow Python's equality and ordering semantics, with numeric-string coercion applied when both operands are numbers or numeric strings (for example, captured stdout `"10"` compared with `10` or `"9"`). Booleans are not coerced against strings, so `"0" == false` and `"1" == true` evaluate to `false`, while `true == 1` remains `true` as in Python. Ordering comparisons between incompatible types (such as `"2" > true` or `10 > "abc"`) evaluate to `false` rather than raising an error.

The body of every `{{ }}` block must be a valid expression. Text that is not one, such as prose (`{{ some text }}`), a key with characters other than letters, digits, `_` and `-` (`{{ inputs.weird:key }}`), or arithmetic (`{{ count + 1 }}`), raises a `ValueError` naming the offending token. Numbers may be written as `5`, `-5`, `+5`, `1_000`, `0.5`, `.5`, `5.`, or `1.5e3`.

> **Compatibility:** Earlier releases could resolve an expression such as `{{ inputs.weird:key }}` when the key existed; this expression now fails at runtime. Rename keys you control (for example, `weird:key` to `weird_key`) and update their references. Quoted-key lookup is not supported. Workflow validation may not detect these expressions before execution.
Expand Down
11 changes: 10 additions & 1 deletion src/specify_cli/workflows/expressions/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,23 @@ def _coerce_number(value: Any) -> Any:
return value


def _is_number(value: Any) -> bool:
"""Return True for int/float values, excluding ``bool`` (a subclass of ``int``)."""
return isinstance(value, (int, float)) and not isinstance(value, bool)


def _coerce_numeric_pair(left: Any, right: Any) -> tuple[Any, Any]:
"""Return both operands as numbers if both look numeric, else unchanged.
Coercing only when *both* convert keeps a numeric string paired with a
plain string as two strings, rather than an int-vs-str mismatch.
Leaving ``bool`` values uncoerced keeps boolean comparisons aligned with
Python's semantics: ``"0" == False`` and ``"1" == True`` are ``False``,
``True == 1`` remains ``True``, and ordering a string against a boolean
(such as ``"2" > True``) raises ``TypeError`` and yields ``False``.
"""
cl, cr = _coerce_number(left), _coerce_number(right)
if isinstance(cl, (int, float)) and isinstance(cr, (int, float)):
if _is_number(cl) and _is_number(cr):
return cl, cr
return left, right

Expand Down
113 changes: 113 additions & 0 deletions tests/specify_cli/workflows/expressions/test_operators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Comparison and coercion semantics for workflow expression operators."""

from __future__ import annotations

import pytest

from specify_cli.workflows.base import StepContext
from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine
from specify_cli.workflows.expressions import evaluate_condition, evaluate_expression


class TestBooleanNumericStringComparisons:
"""Booleans must not trigger numeric-string coercion in comparisons.
Because ``bool`` subclasses ``int`` in Python, treating ``bool`` as a
number in ``_coerce_numeric_pair`` silently coerced strings such as
``"0"`` and ``"1"`` into integers when paired with ``false`` / ``true``.
"""

@pytest.mark.parametrize(
("expr", "value"),
[
("{{ inputs.v == true }}", "1"),
("{{ inputs.v == true }}", "1.0"),
("{{ true == inputs.v }}", "1"),
("{{ inputs.v == false }}", "0"),
("{{ inputs.v == false }}", "0.0"),
("{{ false == inputs.v }}", "0"),
],
)
def test_numeric_strings_do_not_equal_booleans(self, expr: str, value: str):
ctx = StepContext(inputs={"v": value})
assert evaluate_expression(expr, ctx) is False

@pytest.mark.parametrize(
("expr", "value"),
[
("{{ inputs.v != true }}", "1"),
("{{ inputs.v != true }}", "1.0"),
("{{ true != inputs.v }}", "1"),
("{{ inputs.v != false }}", "0"),
("{{ inputs.v != false }}", "0.0"),
("{{ false != inputs.v }}", "0"),
],
)
def test_numeric_strings_are_not_equal_to_booleans(self, expr: str, value: str):
ctx = StepContext(inputs={"v": value})
assert evaluate_expression(expr, ctx) is True

@pytest.mark.parametrize(
("expr", "value"),
[
("{{ inputs.v > true }}", "2"),
("{{ inputs.v < true }}", "0"),
("{{ inputs.v >= true }}", "1"),
("{{ inputs.v <= true }}", "1"),
("{{ inputs.v >= false }}", "0"),
("{{ inputs.v <= false }}", "0"),
("{{ inputs.v < false }}", "-1"),
("{{ true < inputs.v }}", "2"),
("{{ false >= inputs.v }}", "0"),
],
)
def test_numeric_strings_do_not_order_against_booleans(self, expr: str, value: str):
ctx = StepContext(inputs={"v": value})
assert evaluate_expression(expr, ctx) is False

def test_if_step_does_not_match_zero_stdout_as_false(self, tmp_path):
"""A captured numeric stdout string must not take a ``== false`` branch."""
(tmp_path / ".specify").mkdir()
wf = WorkflowDefinition.from_string(
"""
schema_version: "1.0"
workflow:
id: bool-vs-str
name: Bool vs Str
version: "1.0.0"
inputs:
raw:
type: string
steps:
- id: branch
type: if
condition: "{{ inputs.raw == false }}"
then:
- id: matched-false
type: shell
run: "echo wrong"
else:
- id: not-false
type: shell
run: "echo right"
"""
)
state = WorkflowEngine(tmp_path).execute(wf, {"raw": "0"})
assert state.status.value == "completed"
assert "not-false" in state.step_results
assert "matched-false" not in state.step_results

def test_numeric_string_and_bool_int_controls_unchanged(self):
"""Real numeric comparisons and non-string bool/int semantics stay intact."""
ctx = StepContext(inputs={"s0": "0", "s1": "1", "s10": "10", "s9": "9", "n": 1})
# Numeric strings still compare as numbers against ints and other numeric strings.
assert evaluate_condition("{{ inputs.s0 == 0 }}", ctx) is True
assert evaluate_condition("{{ inputs.s1 == 1 }}", ctx) is True
assert evaluate_condition("{{ inputs.s10 > inputs.s9 }}", ctx) is True
# Plain boolean equality is unchanged.
assert evaluate_condition("{{ true == true }}", ctx) is True
assert evaluate_condition("{{ false == false }}", ctx) is True
assert evaluate_condition("{{ true != false }}", ctx) is True
# Non-string bool vs int preserves documented `(a == b) > 0` behavior.
assert evaluate_condition("{{ (inputs.n == 1) > 0 }}", ctx) is True
assert evaluate_condition("{{ (inputs.n == 2) > 0 }}", ctx) is False
Loading