""" Sprint 4.2 QA Gate: Decision branching, loops, subflows in execute_flow_dag. Stubs — will fail until Goose's Sprint 4.2 code lands. """ import pytest # --------------------------------------------------------------------------- # 4.2.1 DecisionNode deterministic first-match ordering # --------------------------------------------------------------------------- class TestDecisionNode: def test_first_matching_branch_wins(self, db): """When two outcome branches both match, the first one in order wins.""" from workflows.engine import execute_flow_dag dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, { "id": "decision1", "type": "decision", "data": { "outcomes": [ { "id": "high", "label": "High Value", "conditions": [{"field": "amount", "operator": "gte", "value": 1000}], "logic": "AND", }, { "id": "medium", "label": "Medium Value", "conditions": [{"field": "amount", "operator": "gte", "value": 500}], "logic": "AND", }, ] } }, {"id": "action_high", "type": "update_record", "data": {"stage": "High"}}, {"id": "action_medium", "type": "update_record", "data": {"stage": "Medium"}}, ], "edges": [ {"source": "start", "target": "decision1"}, {"source": "decision1", "target": "action_high", "sourceHandle": "high"}, {"source": "decision1", "target": "action_medium", "sourceHandle": "medium"}, ], } # amount=2000 matches both; first branch (high) must win context = {"amount": 2000} result = execute_flow_dag(dag, context) assert result.get("stage") == "High", ( "First matching DecisionNode outcome must win. Got: " + str(result) ) def test_default_else_branch_taken_when_no_conditions_match(self, db): """The Default/Else outcome must execute when no other branch matches.""" from workflows.engine import execute_flow_dag dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, { "id": "dec", "type": "decision", "data": { "outcomes": [ { "id": "high", "label": "High", "conditions": [{"field": "amount", "operator": "gte", "value": 10000}], "logic": "AND", }, {"id": "default", "label": "Default", "conditions": [], "logic": "AND"}, ] } }, {"id": "action_default", "type": "update_record", "data": {"stage": "Default"}}, ], "edges": [ {"source": "start", "target": "dec"}, {"source": "dec", "target": "action_default", "sourceHandle": "default"}, ], } context = {"amount": 50} result = execute_flow_dag(dag, context) assert result.get("stage") == "Default" # --------------------------------------------------------------------------- # 4.2.2 SubflowNode recursion depth guard # --------------------------------------------------------------------------- class TestSubflowRecursionDepth: def test_subflow_depth_limit_raises_validation_error(self, db): """SubflowNode must raise ValidationError when recursion depth exceeds limit (10).""" from django.core.exceptions import ValidationError from workflows.engine import execute_flow_dag # Build a flow that calls itself (self-referential subflow) from workflows.models import FlowDefinition self_ref_dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, {"id": "sub", "type": "subflow", "data": {"flow_id": None}}, # patched below ], "edges": [{"source": "start", "target": "sub"}], } flow = FlowDefinition.objects.create( name="RecursiveFlow", trigger_type="manual", graph=self_ref_dag, ) # Patch the subflow node to reference itself self_ref_dag["nodes"][1]["data"]["flow_id"] = flow.id flow.graph = self_ref_dag flow.save() with pytest.raises((ValidationError, RecursionError, Exception)) as exc_info: execute_flow_dag(self_ref_dag, {}, depth=0) assert "depth" in str(exc_info.value).lower() or "recursion" in str(exc_info.value).lower(), ( "SubflowNode must raise a clear depth/recursion limit error, not silently hang." ) def test_subflow_within_depth_limit_executes(self, db): """A subflow at depth < 10 must execute normally.""" from workflows.engine import execute_flow_dag from workflows.models import FlowDefinition child_dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, {"id": "assign", "type": "assignment", "data": {"variable": "child_ran", "value": True}}, ], "edges": [{"source": "start", "target": "assign"}], } child = FlowDefinition.objects.create( name="ChildFlow", trigger_type="manual", graph=child_dag ) parent_dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, {"id": "sub", "type": "subflow", "data": {"flow_id": child.id}}, ], "edges": [{"source": "start", "target": "sub"}], } result = execute_flow_dag(parent_dag, {}, depth=0) assert result.get("child_ran") is True # --------------------------------------------------------------------------- # 4.2.3 LoopNode cycle detection still enforced # --------------------------------------------------------------------------- class TestLoopNodeCycleDetection: def test_loop_back_edge_rejected_at_save(self, db): """A graph where a LoopNode routes back to an ancestor must fail DAG validation.""" from django.core.exceptions import ValidationError from workflows.models import FlowDefinition cyclic_dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, {"id": "loop", "type": "loop", "data": {"collection": "contacts"}}, {"id": "action", "type": "update_record", "data": {}}, ], "edges": [ {"source": "start", "target": "loop"}, {"source": "loop", "target": "action", "sourceHandle": "for_each"}, # back-edge creating a cycle: {"source": "action", "target": "loop"}, ], } with pytest.raises(ValidationError): flow = FlowDefinition(name="CyclicLoop", trigger_type="manual", graph=cyclic_dag) flow.full_clean() # --------------------------------------------------------------------------- # 4.2.4 AssignmentNode execution # --------------------------------------------------------------------------- class TestAssignmentNode: def test_assignment_sets_context_variable(self, db): """AssignmentNode must update the execution context variable.""" from workflows.engine import execute_flow_dag dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, {"id": "assign", "type": "assignment", "data": {"variable": "score", "operator": "equals", "value": 42}}, ], "edges": [{"source": "start", "target": "assign"}], } result = execute_flow_dag(dag, {"score": 0}) assert result["score"] == 42 def test_assignment_add_operator(self, db): """AssignmentNode with 'add' operator must increment the variable.""" from workflows.engine import execute_flow_dag dag = { "nodes": [ {"id": "start", "type": "trigger", "data": {}}, {"id": "assign", "type": "assignment", "data": {"variable": "score", "operator": "add", "value": 10}}, ], "edges": [{"source": "start", "target": "assign"}], } result = execute_flow_dag(dag, {"score": 5}) assert result["score"] == 15