openforce/tests/phase4/test_sprint43_triggers.py
Goose eaaf3f2791 test(phase4): add Sprint 4.1/4.2/4.3 QA gate stubs
Contract tests for:
- 4.1: entity_name/custom_object mutual exclusion, GIN index in migration,
       additionalProperties validation on standard objects, custom field
       transfer during lead conversion
- 4.2: DecisionNode first-match determinism, SubflowNode depth limit (10),
       LoopNode cycle detection, AssignmentNode operators
- 4.3: post_save dispatch, / context, re-entrancy
       guard, Celery Beat idempotency

All tests will fail until Sprint 4.x code lands — intentional.
2026-09-26 17:30:02 +00:00

150 lines
6 KiB
Python

"""
Sprint 4.3 QA Gate: post_save signals, re-entrancy guard, Celery Beat idempotency.
Stubs — will fail until Goose's Sprint 4.3 code lands.
"""
import pytest
# ---------------------------------------------------------------------------
# 4.3.1 post_save signal dispatches flow for record_created trigger
# ---------------------------------------------------------------------------
class TestRecordTriggeredFlows:
def test_record_created_trigger_fires_on_account_save(self, db):
"""Creating an Account must dispatch any active record_created flow for Account."""
from unittest.mock import patch
from workflows.models import FlowDefinition
from workflows import dispatcher # to be created in Sprint 4.3
flow = FlowDefinition.objects.create(
name="OnAccountCreate",
trigger_type="record_created",
trigger_object="Account",
is_active=True,
graph={
"nodes": [{"id": "start", "type": "trigger", "data": {}}],
"edges": [],
},
)
with patch.object(dispatcher, 'dispatch_flow', wraps=dispatcher.dispatch_flow) as mock_dispatch:
from crm_core.models import Account
Account.objects.create(name="TriggerTest Corp")
mock_dispatch.assert_called_once()
call_kwargs = mock_dispatch.call_args
assert call_kwargs[0][0].id == flow.id or call_kwargs[1].get('flow_id') == flow.id
def test_record_updated_trigger_includes_prior_record(self, db):
"""record_updated flow context must include $Record and $Record__Prior."""
from workflows import dispatcher
from workflows.models import FlowDefinition
from crm_core.models import Account
from unittest.mock import patch
FlowDefinition.objects.create(
name="OnAccountUpdate",
trigger_type="record_updated",
trigger_object="Account",
is_active=True,
graph={
"nodes": [{"id": "start", "type": "trigger", "data": {}}],
"edges": [],
},
)
acct = Account.objects.create(name="Before")
dispatched_contexts = []
original = dispatcher.dispatch_flow
def capture(*args, **kwargs):
dispatched_contexts.append(kwargs.get('context', args[1] if len(args) > 1 else {}))
return original(*args, **kwargs)
with patch.object(dispatcher, 'dispatch_flow', side_effect=capture):
acct.name = "After"
acct.save()
assert len(dispatched_contexts) == 1
ctx = dispatched_contexts[0]
assert '$Record' in ctx, "Context must include $Record"
assert '$Record__Prior' in ctx, "Context must include $Record__Prior"
assert ctx['$Record']['name'] == 'After'
assert ctx['$Record__Prior']['name'] == 'Before'
# ---------------------------------------------------------------------------
# 4.3.2 Re-entrancy guard prevents signal recursion
# ---------------------------------------------------------------------------
class TestSignalReentrancyGuard:
def test_flow_updating_record_does_not_retrigger(self, db):
"""A flow that updates the triggering record must not cause infinite signal recursion."""
from workflows.models import FlowDefinition
from crm_core.models import Account
# Flow that updates a field on the triggering Account
update_self_dag = {
"nodes": [
{"id": "start", "type": "trigger", "data": {}},
{"id": "upd", "type": "update_record", "data": {"field": "name", "value": "Updated by Flow"}},
],
"edges": [{"source": "start", "target": "upd"}],
}
FlowDefinition.objects.create(
name="SelfUpdateFlow",
trigger_type="record_updated",
trigger_object="Account",
is_active=True,
graph=update_self_dag,
)
acct = Account.objects.create(name="Original")
# This must complete without RecursionError or hitting Django's recursion limit
import threading
errors = []
def do_update():
try:
acct.name = "Trigger"
acct.save()
except Exception as e:
errors.append(e)
t = threading.Thread(target=do_update)
t.start()
t.join(timeout=5)
assert not t.is_alive(), "Signal handler appears to be in an infinite loop (timeout exceeded)"
assert not errors, f"Signal handler raised: {errors[0]}"
# ---------------------------------------------------------------------------
# 4.3.3 Scheduled flow Celery Beat idempotency
# ---------------------------------------------------------------------------
class TestScheduledFlowIdempotency:
def test_duplicate_scheduled_dispatch_is_noop(self, db):
"""A second Celery dispatch for the same FlowDefinition + time window must be a no-op."""
from workflows.models import FlowDefinition, FlowExecutionLog
from workflows import tasks as flow_tasks # Celery task module
flow = FlowDefinition.objects.create(
name="DailySync",
trigger_type="scheduled",
is_active=True,
graph={
"nodes": [{"id": "start", "type": "trigger", "data": {}}],
"edges": [],
},
)
window = "2026-09-26T00:00:00Z"
# First dispatch — should run
flow_tasks.run_scheduled_flow(flow.id, window)
count_after_first = FlowExecutionLog.objects.filter(flow_definition=flow).count()
assert count_after_first == 1
# Second dispatch with same window — must be a no-op
flow_tasks.run_scheduled_flow(flow.id, window)
count_after_second = FlowExecutionLog.objects.filter(flow_definition=flow).count()
assert count_after_second == 1, (
"Duplicate scheduled dispatch must not create a second FlowExecutionLog. "
f"Got {count_after_second} logs."
)