use crate::debugging::{CommandInspector, ExecutionTracer, StateSnapshot};
use crate::error::{Error, Result};
use crate::testing::mocks::MockRegistry;
use crate::testing::time::MockClock;
use crate::workflow::{WorkflowContext, WorkflowExecution};
use serde::{de::DeserializeOwned, Serialize};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};
use tokio::sync::Mutex;
pub struct TestEnv {
mocks: Arc<RwLock<MockRegistry>>,
traces: Arc<Mutex<HashMap<String, ExecutionTrace>>>,
workflows: Arc<RwLock<HashMap<String, WorkflowHandler>>>,
context_workflows: Arc<RwLock<HashMap<String, ContextWorkflowHandler>>>,
task_calls: Arc<Mutex<HashMap<String, Vec<TaskCall>>>>,
namespace: String,
task_queue: String,
tracer: Option<ExecutionTracer>,
capture_snapshots: bool,
snapshots: Arc<Mutex<HashMap<String, Vec<StateSnapshot>>>>,
mock_clock: Option<MockClock>,
}
#[derive(Debug, Clone)]
pub struct ExecutionTrace {
#[allow(dead_code)] pub workflow_id: String,
#[allow(dead_code)] pub workflow_type: String,
pub status: ExecutionStatus,
pub state: HashMap<String, Vec<u8>>,
pub tasks_executed: Vec<String>,
#[allow(dead_code)] pub commands: Vec<String>,
#[allow(dead_code)] pub events: Vec<String>,
#[allow(dead_code)] pub queries: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionStatus {
Running,
Completed,
Failed(String),
Cancelled,
}
#[derive(Debug, Clone)]
pub struct TaskCall {
pub task_type: String,
pub input: Vec<u8>,
pub timestamp: std::time::Instant,
}
type WorkflowHandler =
Arc<dyn Fn(Vec<u8>) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send>> + Send + Sync>;
type ContextWorkflowHandler = Arc<
dyn Fn(WorkflowContext, Vec<u8>) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send>>
+ Send
+ Sync,
>;
impl TestEnv {
pub fn new() -> Self {
Self {
mocks: Arc::new(RwLock::new(MockRegistry::new())),
traces: Arc::new(Mutex::new(HashMap::new())),
workflows: Arc::new(RwLock::new(HashMap::new())),
context_workflows: Arc::new(RwLock::new(HashMap::new())),
task_calls: Arc::new(Mutex::new(HashMap::new())),
namespace: "test".to_string(),
task_queue: "test-queue".to_string(),
tracer: None,
capture_snapshots: false,
snapshots: Arc::new(Mutex::new(HashMap::new())),
mock_clock: None,
}
}
pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
self.namespace = namespace.into();
self
}
pub fn with_task_queue(mut self, task_queue: impl Into<String>) -> Self {
self.task_queue = task_queue.into();
self
}
pub fn with_tracer(mut self, tracer: ExecutionTracer) -> Self {
self.tracer = Some(tracer);
self
}
pub fn with_snapshots(mut self, enabled: bool) -> Self {
self.capture_snapshots = enabled;
self
}
pub fn with_mock_clock(mut self, clock: MockClock) -> Self {
self.mock_clock = Some(clock);
self
}
pub fn clock(&self) -> Option<&MockClock> {
self.mock_clock.as_ref()
}
pub fn advance_time(&self, duration: std::time::Duration) {
self.mock_clock
.as_ref()
.expect("advance_time() requires with_mock_clock()")
.advance(duration);
}
pub fn advance_time_ms(&self, ms: u64) {
self.mock_clock
.as_ref()
.expect("advance_time_ms() requires with_mock_clock()")
.advance_ms(ms);
}
pub fn tracer(&self) -> Option<&ExecutionTracer> {
self.tracer.as_ref()
}
pub async fn get_snapshots(&self, workflow_id: &str) -> Vec<StateSnapshot> {
let snapshots = self.snapshots.lock().await;
snapshots.get(workflow_id).cloned().unwrap_or_else(Vec::new)
}
pub fn command_inspector(&self) -> CommandInspector {
CommandInspector::new()
}
pub fn register_workflow<F, Fut, I, O>(&mut self, workflow_type: &str, handler: F)
where
F: Fn(I) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<O>> + Send + 'static,
I: DeserializeOwned + Send + 'static,
O: Serialize + Send + 'static,
{
let wrapped_handler = Arc::new(move |input_bytes: Vec<u8>| {
let input: I = match serde_json::from_slice(&input_bytes) {
Ok(i) => i,
Err(e) => {
return Box::pin(async move {
Err(Error::Serialization(format!(
"Failed to deserialize input: {}",
e
)))
})
as std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send>,
>;
}
};
let fut = handler(input);
Box::pin(async move {
let output = fut.await?;
let output_bytes = serde_json::to_vec(&output).map_err(|e| {
Error::Serialization(format!("Failed to serialize output: {}", e))
})?;
Ok(output_bytes)
})
as std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send>>
});
let mut workflows = self.workflows.write().unwrap();
workflows.insert(workflow_type.to_string(), wrapped_handler);
}
pub fn register_workflow_with_context<F, Fut, I, O>(&mut self, workflow_type: &str, handler: F)
where
F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O>> + Send + 'static,
I: DeserializeOwned + Send + 'static,
O: Serialize + Send + 'static,
{
let wrapped_handler = Arc::new(move |ctx: WorkflowContext, input_bytes: Vec<u8>| {
let input: I = match serde_json::from_slice(&input_bytes) {
Ok(i) => i,
Err(e) => {
return Box::pin(async move {
Err(Error::Serialization(format!(
"Failed to deserialize input: {}",
e
)))
})
as Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send>>;
}
};
let fut = handler(ctx, input);
Box::pin(async move {
let output = fut.await?;
let output_bytes = serde_json::to_vec(&output).map_err(|e| {
Error::Serialization(format!("Failed to serialize output: {}", e))
})?;
Ok(output_bytes)
}) as Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send>>
});
let mut workflows = self.context_workflows.write().unwrap();
workflows.insert(workflow_type.to_string(), wrapped_handler);
}
pub fn mock_task(&mut self, task_type: &str) -> crate::testing::MockTaskBuilder {
crate::testing::MockTaskBuilder::new(task_type.to_string(), self.mocks.clone())
}
pub async fn execute_workflow<I, O>(&mut self, workflow_type: &str, input: I) -> Result<O>
where
I: Serialize,
O: DeserializeOwned,
{
let workflow_id = format!("test-wf-{}", uuid::Uuid::new_v4());
let input_bytes = serde_json::to_vec(&input)
.map_err(|e| Error::Serialization(format!("Failed to serialize input: {}", e)))?;
let execution = WorkflowExecution {
workflow_id: workflow_id.clone(),
run_id: format!("test-run-{}", uuid::Uuid::new_v4()),
workflow_type: workflow_type.to_string(),
attempt: 1,
namespace: self.namespace.clone(),
task_queue: self.task_queue.clone(),
};
if let Some(tracer) = &self.tracer {
tracer.start_trace(&workflow_id, workflow_type);
}
{
let mut traces = self.traces.lock().await;
traces.insert(
workflow_id.clone(),
ExecutionTrace {
workflow_id: workflow_id.clone(),
workflow_type: workflow_type.to_string(),
status: ExecutionStatus::Running,
state: HashMap::new(),
tasks_executed: Vec::new(),
commands: Vec::new(),
events: Vec::new(),
queries: Vec::new(),
},
);
}
let context_handler = {
let workflows = self.context_workflows.read().unwrap();
workflows.get(workflow_type).cloned()
};
let simple_handler = {
let workflows = self.workflows.read().unwrap();
workflows.get(workflow_type).cloned()
};
let ctx = WorkflowContext::new(execution.clone(), false, "1.0.0".to_string());
if self.capture_snapshots {
let snapshot = StateSnapshot::capture_with_label(&ctx, "initial");
let mut snapshots = self.snapshots.lock().await;
snapshots
.entry(workflow_id.clone())
.or_insert_with(Vec::new)
.push(snapshot);
}
let result_bytes = if let Some(handler) = context_handler {
match handler(ctx, input_bytes).await {
Ok(output) => {
if let Some(tracer) = &self.tracer {
tracer.record_event(
&workflow_id,
crate::debugging::ExecutionEvent::new(
crate::debugging::TraceLevel::Info,
"workflow_completed",
&workflow_id,
"Workflow completed successfully",
),
);
tracer.complete_trace(&workflow_id);
}
let mut traces = self.traces.lock().await;
if let Some(trace) = traces.get_mut(&workflow_id) {
trace.status = ExecutionStatus::Completed;
}
output
}
Err(e) => {
if let Some(tracer) = &self.tracer {
tracer.record_event(
&workflow_id,
crate::debugging::ExecutionEvent::new(
crate::debugging::TraceLevel::Error,
"workflow_failed",
&workflow_id,
format!("Workflow failed: {}", e),
),
);
tracer.complete_trace(&workflow_id);
}
let mut traces = self.traces.lock().await;
if let Some(trace) = traces.get_mut(&workflow_id) {
trace.status = ExecutionStatus::Failed(e.to_string());
}
return Err(e);
}
}
} else if let Some(handler) = simple_handler {
match handler(input_bytes).await {
Ok(output) => {
if let Some(tracer) = &self.tracer {
tracer.record_event(
&workflow_id,
crate::debugging::ExecutionEvent::new(
crate::debugging::TraceLevel::Info,
"workflow_completed",
&workflow_id,
"Workflow completed successfully",
),
);
tracer.complete_trace(&workflow_id);
}
let mut traces = self.traces.lock().await;
if let Some(trace) = traces.get_mut(&workflow_id) {
trace.status = ExecutionStatus::Completed;
}
output
}
Err(e) => {
if let Some(tracer) = &self.tracer {
tracer.record_event(
&workflow_id,
crate::debugging::ExecutionEvent::new(
crate::debugging::TraceLevel::Error,
"workflow_failed",
&workflow_id,
format!("Workflow failed: {}", e),
),
);
tracer.complete_trace(&workflow_id);
}
let mut traces = self.traces.lock().await;
if let Some(trace) = traces.get_mut(&workflow_id) {
trace.status = ExecutionStatus::Failed(e.to_string());
}
return Err(e);
}
}
} else {
return Err(Error::Workflow(crate::error::WorkflowError::StateError(
format!(
"Workflow '{}' not registered. Use register_workflow() or register_workflow_with_context().",
workflow_type
)
)));
};
let result: O = serde_json::from_slice(&result_bytes)
.map_err(|e| Error::Serialization(format!("Failed to deserialize output: {}", e)))?;
Ok(result)
}
pub fn get_workflow_state<T: DeserializeOwned>(
&self,
workflow_id: &str,
key: &str,
) -> Result<T> {
let traces = self.traces.blocking_lock();
let trace = traces.get(workflow_id).ok_or_else(|| {
Error::Workflow(crate::error::WorkflowError::StateError(format!(
"Workflow '{}' not found",
workflow_id
)))
})?;
let value_bytes = trace.state.get(key).ok_or_else(|| {
Error::Workflow(crate::error::WorkflowError::StateError(format!(
"State key '{}' not found",
key
)))
})?;
let value: T = serde_json::from_slice(value_bytes)
.map_err(|e| Error::Serialization(format!("Failed to deserialize state: {}", e)))?;
Ok(value)
}
pub fn workflow_state_keys(&self, workflow_id: &str) -> Vec<String> {
let traces = self.traces.blocking_lock();
traces
.get(workflow_id)
.map(|trace| trace.state.keys().cloned().collect())
.unwrap_or_default()
}
pub fn executed_tasks(&self, workflow_id: &str) -> Vec<String> {
let traces = self.traces.blocking_lock();
traces
.get(workflow_id)
.map(|trace| trace.tasks_executed.clone())
.unwrap_or_default()
}
pub fn workflow_status(&self, workflow_id: &str) -> Option<ExecutionStatus> {
let traces = self.traces.blocking_lock();
traces.get(workflow_id).map(|trace| trace.status.clone())
}
pub fn task_call_count(&self, task_type: &str) -> usize {
let calls = self.task_calls.blocking_lock();
calls.get(task_type).map(|v| v.len()).unwrap_or(0)
}
pub fn task_calls(&self, task_type: &str) -> Vec<TaskCall> {
let calls = self.task_calls.blocking_lock();
calls.get(task_type).cloned().unwrap_or_default()
}
pub fn assert_task_called(&self, task_type: &str, expected_count: usize) {
let actual_count = self.task_call_count(task_type);
assert_eq!(
actual_count, expected_count,
"Expected task '{}' to be called {} times, but was called {} times",
task_type, expected_count, actual_count
);
}
pub fn assert_workflow_completed(&self, workflow_id: &str) {
let status = self.workflow_status(workflow_id);
assert_eq!(
status,
Some(ExecutionStatus::Completed),
"Expected workflow '{}' to be completed, but status was {:?}",
workflow_id,
status
);
}
pub fn assert_state_equals<T>(&self, workflow_id: &str, key: &str, expected: &T)
where
T: DeserializeOwned + PartialEq + std::fmt::Debug,
{
let actual: T = self
.get_workflow_state(workflow_id, key)
.unwrap_or_else(|_| panic!("Failed to get state key '{}'", key));
assert_eq!(
actual, *expected,
"Expected state['{}'] to be {:?}, but was {:?}",
key, expected, actual
);
}
#[allow(dead_code)] pub(crate) fn record_task_call(&self, task_type: String, input: Vec<u8>) {
let mut calls = self.task_calls.blocking_lock();
calls.entry(task_type.clone()).or_default().push(TaskCall {
task_type,
input,
timestamp: std::time::Instant::now(),
});
}
}
impl Default for TestEnv {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_test_env_creation() {
let env = TestEnv::new();
assert_eq!(env.namespace, "test");
assert_eq!(env.task_queue, "test-queue");
}
#[test]
fn test_test_env_with_namespace() {
let env = TestEnv::new().with_namespace("custom");
assert_eq!(env.namespace, "custom");
}
#[test]
fn test_test_env_with_task_queue() {
let env = TestEnv::new().with_task_queue("custom-queue");
assert_eq!(env.task_queue, "custom-queue");
}
#[test]
fn test_task_call_count() {
let env = TestEnv::new();
env.record_task_call("task1".to_string(), vec![]);
env.record_task_call("task1".to_string(), vec![]);
env.record_task_call("task2".to_string(), vec![]);
assert_eq!(env.task_call_count("task1"), 2);
assert_eq!(env.task_call_count("task2"), 1);
assert_eq!(env.task_call_count("task3"), 0);
}
#[test]
fn test_execution_status() {
assert_eq!(ExecutionStatus::Running, ExecutionStatus::Running);
assert_eq!(ExecutionStatus::Completed, ExecutionStatus::Completed);
assert_ne!(ExecutionStatus::Running, ExecutionStatus::Completed);
}
#[tokio::test]
async fn test_register_and_execute_workflow() {
let mut env = TestEnv::new();
env.register_workflow("TestWorkflow", |input: String| async move {
Ok(format!("Processed: {}", input))
});
let result: String = env
.execute_workflow("TestWorkflow", "test input".to_string())
.await
.unwrap();
assert_eq!(result, "Processed: test input");
}
#[tokio::test]
async fn test_workflow_not_registered() {
let mut env = TestEnv::new();
let result: Result<String> = env
.execute_workflow("UnknownWorkflow", "input".to_string())
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_workflow_with_complex_types() {
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
struct Input {
value: i32,
}
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
struct Output {
result: i32,
}
let mut env = TestEnv::new();
env.register_workflow("ComplexWorkflow", |input: Input| async move {
Ok(Output {
result: input.value * 2,
})
});
let result: Output = env
.execute_workflow("ComplexWorkflow", Input { value: 21 })
.await
.unwrap();
assert_eq!(result, Output { result: 42 });
}
#[tokio::test]
async fn test_context_aware_workflow() {
let mut env = TestEnv::new();
env.register_workflow_with_context(
"ContextWorkflow",
|_ctx: WorkflowContext, input: i32| async move { Ok(input * 2) },
);
let result: i32 = env.execute_workflow("ContextWorkflow", 21).await.unwrap();
assert_eq!(result, 42);
}
#[test]
fn test_mock_clock_integration() {
use crate::testing::MockClock;
use std::time::Duration;
let clock = MockClock::new();
let env = TestEnv::new().with_mock_clock(clock.clone());
assert!(env.clock().is_some());
assert_eq!(env.clock().unwrap().elapsed_ms(), 0);
clock.advance(Duration::from_secs(5));
assert_eq!(env.clock().unwrap().elapsed_ms(), 5000);
env.advance_time(Duration::from_secs(3));
assert_eq!(clock.elapsed_ms(), 8000);
env.advance_time_ms(2000);
assert_eq!(clock.elapsed_ms(), 10000);
}
#[test]
fn test_no_mock_clock() {
let env = TestEnv::new();
assert!(env.clock().is_none());
}
#[tokio::test]
async fn test_workflow_with_both_registrations() {
let mut env = TestEnv::new();
env.register_workflow("SimpleWorkflow", |input: String| async move {
Ok(format!("Simple: {}", input))
});
env.register_workflow_with_context(
"ContextWorkflow",
|_ctx: WorkflowContext, input: String| async move { Ok(format!("Context: {}", input)) },
);
let result1: String = env
.execute_workflow("SimpleWorkflow", "test".to_string())
.await
.unwrap();
let result2: String = env
.execute_workflow("ContextWorkflow", "test".to_string())
.await
.unwrap();
assert_eq!(result1, "Simple: test");
assert_eq!(result2, "Context: test");
}
}