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.
This commit is contained in:
parent
616e7b2057
commit
eaaf3f2791
4 changed files with 531 additions and 0 deletions
0
tests/phase4/__init__.py
Normal file
0
tests/phase4/__init__.py
Normal file
178
tests/phase4/test_sprint41_custom_fields.py
Normal file
178
tests/phase4/test_sprint41_custom_fields.py
Normal file
|
|
@ -0,0 +1,178 @@
|
||||||
|
"""
|
||||||
|
Sprint 4.1 QA Gate: Custom __c fields on standard CRM objects.
|
||||||
|
All tests are contract stubs — they will fail (ImportError or NotImplementedError)
|
||||||
|
until Goose's Sprint 4.1 code lands. That is intentional.
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 4.1.1 entity_name / custom_object mutual exclusion
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestCustomFieldDefinitionEntityConstraint:
|
||||||
|
"""CustomFieldDefinition must have EITHER custom_object OR entity_name, not both, not neither."""
|
||||||
|
|
||||||
|
def test_entity_name_without_custom_object_is_valid(self, db):
|
||||||
|
"""A field attached to a standard object (entity_name='Account') is valid."""
|
||||||
|
from custom_objects.models import CustomFieldDefinition
|
||||||
|
field = CustomFieldDefinition(
|
||||||
|
name="annual_revenue_tier__c",
|
||||||
|
label="Annual Revenue Tier",
|
||||||
|
field_type="text",
|
||||||
|
entity_name="Account",
|
||||||
|
)
|
||||||
|
# Should not raise
|
||||||
|
field.full_clean()
|
||||||
|
|
||||||
|
def test_custom_object_without_entity_name_is_valid(self, db):
|
||||||
|
"""A field attached to a CustomObjectDefinition is valid."""
|
||||||
|
from custom_objects.models import CustomObjectDefinition, CustomFieldDefinition
|
||||||
|
obj = CustomObjectDefinition(name="Project__c", label="Project", plural_label="Projects")
|
||||||
|
obj.save()
|
||||||
|
field = CustomFieldDefinition(
|
||||||
|
name="budget__c",
|
||||||
|
label="Budget",
|
||||||
|
field_type="number",
|
||||||
|
custom_object=obj,
|
||||||
|
)
|
||||||
|
field.full_clean()
|
||||||
|
|
||||||
|
def test_both_entity_name_and_custom_object_raises(self, db):
|
||||||
|
"""Setting both entity_name and custom_object must be rejected."""
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from custom_objects.models import CustomObjectDefinition, CustomFieldDefinition
|
||||||
|
obj = CustomObjectDefinition(name="Project__c", label="Project", plural_label="Projects")
|
||||||
|
obj.save()
|
||||||
|
field = CustomFieldDefinition(
|
||||||
|
name="bad_field__c",
|
||||||
|
label="Bad Field",
|
||||||
|
field_type="text",
|
||||||
|
entity_name="Account",
|
||||||
|
custom_object=obj,
|
||||||
|
)
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
field.full_clean()
|
||||||
|
|
||||||
|
def test_neither_entity_name_nor_custom_object_raises(self, db):
|
||||||
|
"""Setting neither entity_name nor custom_object must be rejected."""
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from custom_objects.models import CustomFieldDefinition
|
||||||
|
field = CustomFieldDefinition(
|
||||||
|
name="orphan__c",
|
||||||
|
label="Orphan",
|
||||||
|
field_type="text",
|
||||||
|
)
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
field.full_clean()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 4.1.2 GIN index present in migration (not just model Meta)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestCustomFieldsGINIndex:
|
||||||
|
"""Verify the GIN index on custom_fields is declared in the migration SQL."""
|
||||||
|
|
||||||
|
def test_gin_index_in_migration_sql(self):
|
||||||
|
"""The migration adding custom_fields must include a GIN index creation."""
|
||||||
|
import os, re
|
||||||
|
migration_dir = os.path.join(
|
||||||
|
os.path.dirname(__file__), '..', '..', 'crm_core', 'migrations'
|
||||||
|
)
|
||||||
|
migration_files = sorted(f for f in os.listdir(migration_dir) if f.endswith('.py'))
|
||||||
|
gin_found = False
|
||||||
|
for fname in migration_files:
|
||||||
|
path = os.path.join(migration_dir, fname)
|
||||||
|
content = open(path).read()
|
||||||
|
if 'custom_fields' in content and re.search(r'gin|GIN|GinIndex', content):
|
||||||
|
gin_found = True
|
||||||
|
break
|
||||||
|
assert gin_found, (
|
||||||
|
"No migration found that adds a GIN index on custom_fields. "
|
||||||
|
"The index must be in the migration, not just model Meta."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 4.1.3 additionalProperties: False on standard object endpoints
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestStandardObjectCustomFieldValidation:
|
||||||
|
"""Standard object serializers must reject unknown custom_fields keys."""
|
||||||
|
|
||||||
|
def test_unknown_custom_field_key_rejected_on_account(self, db):
|
||||||
|
"""POST to Account with an unknown custom_fields key must return 400."""
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
user = User.objects.create_user('qa_user41', password='pass')
|
||||||
|
client = APIClient()
|
||||||
|
client.force_authenticate(user=user)
|
||||||
|
payload = {
|
||||||
|
'name': 'Acme Corp',
|
||||||
|
'custom_fields': {'nonexistent_field__c': 'some_value'},
|
||||||
|
}
|
||||||
|
response = client.post('/api/accounts/', payload, format='json')
|
||||||
|
assert response.status_code == 400, (
|
||||||
|
f"Expected 400 for unknown custom_fields key, got {response.status_code}. "
|
||||||
|
"additionalProperties: False must be enforced on standard object endpoints."
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_registered_custom_field_accepted_on_account(self, db):
|
||||||
|
"""POST with a registered __c field must be accepted (201)."""
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
from custom_objects.models import CustomFieldDefinition
|
||||||
|
# Register a custom field for Account
|
||||||
|
CustomFieldDefinition.objects.create(
|
||||||
|
name="region__c",
|
||||||
|
label="Region",
|
||||||
|
field_type="text",
|
||||||
|
entity_name="Account",
|
||||||
|
is_required=False,
|
||||||
|
)
|
||||||
|
user = User.objects.create_user('qa_user41b', password='pass')
|
||||||
|
client = APIClient()
|
||||||
|
client.force_authenticate(user=user)
|
||||||
|
payload = {
|
||||||
|
'name': 'Acme Corp',
|
||||||
|
'custom_fields': {'region__c': 'EMEA'},
|
||||||
|
}
|
||||||
|
response = client.post('/api/accounts/', payload, format='json')
|
||||||
|
assert response.status_code == 201, (
|
||||||
|
f"Expected 201 for valid registered custom field, got {response.status_code}."
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_custom_fields_preserved_on_lead_conversion(self, db):
|
||||||
|
"""Custom __c fields on Lead must transfer to the resulting Contact during conversion."""
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
from custom_objects.models import CustomFieldDefinition
|
||||||
|
CustomFieldDefinition.objects.create(
|
||||||
|
name="referral_source__c",
|
||||||
|
label="Referral Source",
|
||||||
|
field_type="text",
|
||||||
|
entity_name="Lead",
|
||||||
|
is_required=False,
|
||||||
|
)
|
||||||
|
user = User.objects.create_user('qa_user41c', password='pass')
|
||||||
|
client = APIClient()
|
||||||
|
client.force_authenticate(user=user)
|
||||||
|
# Create lead with custom field
|
||||||
|
lead_resp = client.post('/api/leads/', {
|
||||||
|
'first_name': 'Jane',
|
||||||
|
'last_name': 'Doe',
|
||||||
|
'email': 'jane@example.com',
|
||||||
|
'company': 'Acme',
|
||||||
|
'custom_fields': {'referral_source__c': 'Partner'},
|
||||||
|
}, format='json')
|
||||||
|
assert lead_resp.status_code == 201
|
||||||
|
lead_id = lead_resp.data['id']
|
||||||
|
# Convert
|
||||||
|
conv_resp = client.post(f'/api/leads/{lead_id}/convert/', {
|
||||||
|
'create_opportunity': False,
|
||||||
|
}, format='json')
|
||||||
|
assert conv_resp.status_code == 200
|
||||||
|
# Check Contact has the custom field value
|
||||||
|
contact_id = conv_resp.data.get('contact_id')
|
||||||
|
contact_resp = client.get(f'/api/contacts/{contact_id}/')
|
||||||
|
assert contact_resp.data.get('custom_fields', {}).get('referral_source__c') == 'Partner', (
|
||||||
|
"custom_fields must transfer from Lead to Contact during conversion."
|
||||||
|
)
|
||||||
203
tests/phase4/test_sprint42_flow_engine.py
Normal file
203
tests/phase4/test_sprint42_flow_engine.py
Normal file
|
|
@ -0,0 +1,203 @@
|
||||||
|
"""
|
||||||
|
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
|
||||||
150
tests/phase4/test_sprint43_triggers.py
Normal file
150
tests/phase4/test_sprint43_triggers.py
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
"""
|
||||||
|
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."
|
||||||
|
)
|
||||||
Loading…
Reference in a new issue