openforce/tests/flow_engine/test_dag.py
2026-09-26 07:31:43 +00:00

81 lines
3.2 KiB
Python

from django.test import TestCase
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_model
from workflows.models import FlowDefinition, FlowExecutionLog
from workflows.engine import validate_flow_dag, get_topological_execution_order, execute_flow_dag
User = get_user_model()
class TestDAGCycleDetection(TestCase):
def setUp(self):
self.user = User.objects.create_user('flowuser', 'fu@openforce.local', 'password123')
def test_linear_dag_accepted(self):
graph = {
'nodes': [{'id': '1'}, {'id': '2'}, {'id': '3'}],
'edges': [
{'source': '1', 'target': '2'},
{'source': '2', 'target': '3'},
]
}
flow = FlowDefinition(name='Linear Flow', graph=graph, created_by=self.user)
flow.save()
self.assertIsNotNone(flow.pk)
def test_cycle_rejected_on_save(self):
graph = {
'nodes': [{'id': 'A'}, {'id': 'B'}],
'edges': [
{'source': 'A', 'target': 'B'},
{'source': 'B', 'target': 'A'}
]
}
flow = FlowDefinition(name='Cyclic Flow', graph=graph, created_by=self.user)
with self.assertRaises(ValidationError):
flow.save()
def test_topological_order_correctness(self):
graph = {
'nodes': [{'id': 'start'}, {'id': 'middle'}, {'id': 'end'}],
'edges': [
{'source': 'start', 'target': 'middle'},
{'source': 'middle', 'target': 'end'}
]
}
order = get_topological_execution_order(graph)
self.assertEqual(order, ['start', 'middle', 'end'])
def test_dangling_edge_raises_validation_error(self):
graph = {
'nodes': [{'id': '1', 'type': 'action', 'data': {'action': 'set_stage', 'stage': 'Qualified'}}],
'edges': [{'source': '1', 'target': '999'}]
}
with self.assertRaises(ValidationError):
validate_flow_dag(graph)
class TestDAGExecution(TestCase):
def setUp(self):
self.user = User.objects.create_user('execuser', 'ex@openforce.local', 'password123')
graph = {
'nodes': [
{'id': '1', 'type': 'action', 'data': {'action': 'set_stage', 'stage': 'Qualification'}},
{'id': '2', 'type': 'action', 'data': {'action': 'increment_score', 'points': 10}}
],
'edges': [{'source': '1', 'target': '2'}]
}
self.flow = FlowDefinition.objects.create(name='Simple Flow', graph=graph, created_by=self.user)
def test_execution_completes_successfully(self):
log = execute_flow_dag(self.flow, initial_context={'score': 5})
self.assertEqual(log.status, 'completed')
self.assertEqual(log.context['score'], 15)
self.assertEqual(log.context['stage'], 'Qualification')
def test_execution_idempotency(self):
key = 'unique-key-12345'
log1 = execute_flow_dag(self.flow, idempotency_key=key)
log2 = execute_flow_dag(self.flow, idempotency_key=key)
self.assertEqual(log1.id, log2.id)
self.assertEqual(FlowExecutionLog.objects.filter(idempotency_key=key).count(), 1)