durable-lambda-testing 1.2.0

MockDurableContext and assertion helpers for testing durable Lambda handlers without AWS credentials
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! MockDurableContext — pre-loaded step results for local testing.
//!
//! Implements FR37-FR38: create mock context with pre-loaded results,
//! run tests without AWS credentials.

use std::sync::Arc;

use aws_sdk_lambda::types::{
    CallbackDetails, ChainedInvokeDetails, Operation, OperationStatus, OperationType, StepDetails,
};
use durable_lambda_core::context::DurableContext;
use durable_lambda_core::operation_id::OperationIdGenerator;

use crate::mock_backend::{BatchCallCounter, CheckpointRecorder, MockBackend, OperationRecorder};

/// Builder for creating a [`DurableContext`] with pre-loaded step results.
///
/// `MockDurableContext` generates a `DurableContext` in **Replaying** mode
/// by pre-loading completed operations. When the handler calls `ctx.step()`,
/// the pre-loaded results are returned without executing the closure.
///
/// Operation IDs are generated deterministically using the same blake2b
/// algorithm as the core engine, ensuring the nth `with_step_result` call
/// corresponds to the nth `ctx.step()` call.
///
/// # Examples
///
/// ```no_run
/// # async fn example() {
/// use durable_lambda_testing::prelude::*;
///
/// let (mut ctx, calls, _ops) = MockDurableContext::new()
///     .with_step_result("validate", r#"{"valid": true}"#)
///     .with_step_result("charge", r#"100"#)
///     .build()
///     .await;
///
/// // Steps replay cached results — closures are NOT executed
/// let result: Result<serde_json::Value, String> = ctx.step("validate", || async {
///     panic!("not executed during replay");
/// }).await.unwrap();
///
/// assert_eq!(result.unwrap(), serde_json::json!({"valid": true}));
///
/// // Verify no checkpoints were made (pure replay)
/// assert_no_checkpoints(&calls).await;
/// # }
/// ```
pub struct MockDurableContext {
    id_gen: OperationIdGenerator,
    operations: Vec<Operation>,
}

impl MockDurableContext {
    /// Create a new `MockDurableContext` builder.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, calls, _ops) = MockDurableContext::new()
    ///     .with_step_result("my_step", r#""hello""#)
    ///     .build()
    ///     .await;
    /// # }
    /// ```
    pub fn new() -> Self {
        Self {
            id_gen: OperationIdGenerator::new(None),
            operations: Vec::new(),
        }
    }

    /// Add a successful step result to the mock history.
    ///
    /// The `result_json` is a JSON string representing the step's return value.
    /// It will be returned by `ctx.step()` during replay without executing
    /// the closure.
    ///
    /// # Arguments
    ///
    /// * `_name` — Step name (for documentation; the operation ID is position-based)
    /// * `result_json` — JSON string of the step result (e.g., `r#"{"valid": true}"#`)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, _, _ops) = MockDurableContext::new()
    ///     .with_step_result("validate", r#"42"#)
    ///     .build()
    ///     .await;
    ///
    /// let result: Result<i32, String> = ctx.step("validate", || async {
    ///     panic!("not executed");
    /// }).await.unwrap();
    ///
    /// assert_eq!(result.unwrap(), 42);
    /// # }
    /// ```
    pub fn with_step_result(mut self, _name: &str, result_json: &str) -> Self {
        let op_id = self.id_gen.next_id();
        let op = Operation::builder()
            .id(&op_id)
            .r#type(OperationType::Step)
            .status(OperationStatus::Succeeded)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
            .step_details(StepDetails::builder().result(result_json).build())
            .build()
            .unwrap_or_else(|e| panic!("failed to build mock Operation: {e}"));
        self.operations.push(op);
        self
    }

    /// Add a failed step result to the mock history.
    ///
    /// The step will replay as a typed error. The `error_type` is the type
    /// name and `error_json` is the serialized error data.
    ///
    /// # Arguments
    ///
    /// * `_name` — Step name (for documentation; the operation ID is position-based)
    /// * `error_type` — The error type name (e.g., `"my_crate::MyError"`)
    /// * `error_json` — JSON string of the error data
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, _, _ops) = MockDurableContext::new()
    ///     .with_step_error("charge", "PaymentError", r#""insufficient_funds""#)
    ///     .build()
    ///     .await;
    ///
    /// let result: Result<i32, String> = ctx.step("charge", || async {
    ///     panic!("not executed");
    /// }).await.unwrap();
    ///
    /// assert_eq!(result.unwrap_err(), "insufficient_funds");
    /// # }
    /// ```
    pub fn with_step_error(mut self, _name: &str, error_type: &str, error_json: &str) -> Self {
        let op_id = self.id_gen.next_id();
        let error_obj = aws_sdk_lambda::types::ErrorObject::builder()
            .error_type(error_type)
            .error_data(error_json)
            .build();
        let op = Operation::builder()
            .id(&op_id)
            .r#type(OperationType::Step)
            .status(OperationStatus::Failed)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
            .step_details(StepDetails::builder().error(error_obj).build())
            .build()
            .unwrap_or_else(|e| panic!("failed to build mock Operation: {e}"));
        self.operations.push(op);
        self
    }

    /// Add a completed wait to the mock history.
    ///
    /// Simulates a wait that has already completed (SUCCEEDED). During replay,
    /// `ctx.wait()` will return `Ok(())` immediately.
    ///
    /// # Arguments
    ///
    /// * `_name` — Wait name (for documentation; the operation ID is position-based)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, _, _ops) = MockDurableContext::new()
    ///     .with_step_result("validate", r#"42"#)
    ///     .with_wait("cooldown")
    ///     .with_step_result("charge", r#"100"#)
    ///     .build()
    ///     .await;
    /// # }
    /// ```
    pub fn with_wait(mut self, _name: &str) -> Self {
        let op_id = self.id_gen.next_id();
        let op = Operation::builder()
            .id(&op_id)
            .r#type(OperationType::Wait)
            .status(OperationStatus::Succeeded)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
            .build()
            .unwrap_or_else(|e| panic!("failed to build mock Wait Operation: {e}"));
        self.operations.push(op);
        self
    }

    /// Add a completed callback to the mock history.
    ///
    /// Simulates a callback that has been signaled with success. During replay,
    /// `ctx.create_callback()` will return a `CallbackHandle` with the given
    /// `callback_id`, and `ctx.callback_result()` will return the deserialized
    /// result.
    ///
    /// # Arguments
    ///
    /// * `_name` — Callback name (for documentation; the operation ID is position-based)
    /// * `callback_id` — The server-generated callback ID
    /// * `result_json` — JSON string of the callback result
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, _, _ops) = MockDurableContext::new()
    ///     .with_callback("approval", "cb-123", r#""approved""#)
    ///     .build()
    ///     .await;
    /// # }
    /// ```
    pub fn with_callback(mut self, _name: &str, callback_id: &str, result_json: &str) -> Self {
        let op_id = self.id_gen.next_id();
        let cb_details = CallbackDetails::builder()
            .callback_id(callback_id)
            .result(result_json)
            .build();
        let op = Operation::builder()
            .id(&op_id)
            .r#type(OperationType::Callback)
            .status(OperationStatus::Succeeded)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
            .callback_details(cb_details)
            .build()
            .unwrap_or_else(|e| panic!("failed to build mock Callback Operation: {e}"));
        self.operations.push(op);
        self
    }

    /// Add a completed invoke to the mock history.
    ///
    /// Simulates a chained invoke that has completed successfully. During replay,
    /// `ctx.invoke()` will return the deserialized result.
    ///
    /// # Arguments
    ///
    /// * `_name` — Invoke name (for documentation; the operation ID is position-based)
    /// * `result_json` — JSON string of the invoke result
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, _, _ops) = MockDurableContext::new()
    ///     .with_invoke("call_processor", r#"{"status":"ok"}"#)
    ///     .build()
    ///     .await;
    /// # }
    /// ```
    pub fn with_invoke(mut self, _name: &str, result_json: &str) -> Self {
        let op_id = self.id_gen.next_id();
        let details = ChainedInvokeDetails::builder().result(result_json).build();
        let op = Operation::builder()
            .id(&op_id)
            .r#type(OperationType::ChainedInvoke)
            .status(OperationStatus::Succeeded)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
            .chained_invoke_details(details)
            .build()
            .unwrap_or_else(|e| panic!("failed to build mock ChainedInvoke Operation: {e}"));
        self.operations.push(op);
        self
    }

    /// Build the mock context, returning a `DurableContext` and checkpoint call recorder.
    ///
    /// The returned `DurableContext` starts in **Replaying** mode if any
    /// operations were pre-loaded, or **Executing** mode if none were added.
    ///
    /// # Returns
    ///
    /// A tuple of:
    /// - `DurableContext` — ready for use with `ctx.step(...)` etc.
    /// - `Arc<Mutex<Vec<CheckpointCall>>>` — inspect checkpoint calls after test
    ///
    /// # Errors
    ///
    /// Returns [`DurableError`] if context construction fails (should not happen
    /// with mock data).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, calls, _ops) = MockDurableContext::new()
    ///     .with_step_result("step1", r#"true"#)
    ///     .build()
    ///     .await;
    /// # }
    /// ```
    pub async fn build(self) -> (DurableContext, CheckpointRecorder, OperationRecorder) {
        let (backend, calls, operations) = MockBackend::new("mock-token");

        let ctx = DurableContext::new(
            Arc::new(backend),
            "arn:aws:lambda:us-east-1:000000000000:durable-execution/mock".to_string(),
            "mock-checkpoint-token".to_string(),
            self.operations,
            None,
        )
        .await
        .expect("MockDurableContext::build should not fail");

        (ctx, calls, operations)
    }

    /// Build mock context and also return the batch checkpoint call counter.
    ///
    /// Use this when testing batch mode — the `BatchCallCounter` lets you
    /// assert how many times `batch_checkpoint()` was called.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() {
    /// use durable_lambda_testing::prelude::*;
    ///
    /// let (mut ctx, calls, _ops, batch_counter) = MockDurableContext::new()
    ///     .build_with_batch_counter()
    ///     .await;
    ///
    /// ctx.enable_batch_mode();
    /// let _: Result<i32, String> = ctx.step("s1", || async { Ok(1) }).await.unwrap();
    /// ctx.flush_batch().await.unwrap();
    ///
    /// assert_eq!(*batch_counter.lock().await, 1);
    /// # }
    /// ```
    pub async fn build_with_batch_counter(
        self,
    ) -> (
        DurableContext,
        CheckpointRecorder,
        OperationRecorder,
        BatchCallCounter,
    ) {
        let (backend, calls, operations) = MockBackend::new("mock-token");
        let batch_counter = backend.batch_call_counter();

        let ctx = DurableContext::new(
            Arc::new(backend),
            "arn:aws:lambda:us-east-1:000000000000:durable-execution/mock".to_string(),
            "mock-checkpoint-token".to_string(),
            self.operations,
            None,
        )
        .await
        .expect("MockDurableContext::build_with_batch_counter should not fail");

        (ctx, calls, operations, batch_counter)
    }
}

impl Default for MockDurableContext {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    #[tokio::test]
    async fn test_mock_context_replays_step_result() {
        let (mut ctx, calls, _ops) = MockDurableContext::new()
            .with_step_result("validate", r#"42"#)
            .build()
            .await;

        let executed = Arc::new(AtomicBool::new(false));
        let executed_clone = executed.clone();

        let result: Result<i32, String> = ctx
            .step("validate", move || {
                let executed = executed_clone.clone();
                async move {
                    executed.store(true, Ordering::SeqCst);
                    Ok(999) // should NOT be returned
                }
            })
            .await
            .unwrap();

        assert_eq!(result.unwrap(), 42);
        assert!(
            !executed.load(Ordering::SeqCst),
            "closure should not execute during replay"
        );

        // No checkpoints should be made during pure replay
        let captured = calls.lock().await;
        assert_eq!(captured.len(), 0);
    }

    #[tokio::test]
    async fn test_mock_context_replays_multiple_steps() {
        let (mut ctx, calls, _ops) = MockDurableContext::new()
            .with_step_result("step1", r#""hello""#)
            .with_step_result("step2", r#""world""#)
            .build()
            .await;

        let r1: Result<String, String> = ctx
            .step("step1", || async { panic!("not executed") })
            .await
            .unwrap();
        assert_eq!(r1.unwrap(), "hello");

        let r2: Result<String, String> = ctx
            .step("step2", || async { panic!("not executed") })
            .await
            .unwrap();
        assert_eq!(r2.unwrap(), "world");

        let captured = calls.lock().await;
        assert_eq!(captured.len(), 0);
    }

    #[tokio::test]
    async fn test_mock_context_replays_step_error() {
        let (mut ctx, _calls, _ops) = MockDurableContext::new()
            .with_step_error("charge", "PaymentError", r#""insufficient_funds""#)
            .build()
            .await;

        let result: Result<i32, String> = ctx
            .step("charge", || async { panic!("not executed") })
            .await
            .unwrap();

        assert_eq!(result.unwrap_err(), "insufficient_funds");
    }

    #[tokio::test]
    async fn test_mock_context_executing_mode_when_empty() {
        let (ctx, _calls, _ops) = MockDurableContext::new().build().await;

        assert!(!ctx.is_replaying());
        assert_eq!(
            ctx.execution_mode(),
            durable_lambda_core::types::ExecutionMode::Executing
        );
    }

    #[tokio::test]
    async fn test_mock_context_replaying_mode_with_operations() {
        let (ctx, _calls, _ops) = MockDurableContext::new()
            .with_step_result("step1", r#"1"#)
            .build()
            .await;

        assert!(ctx.is_replaying());
        assert_eq!(
            ctx.execution_mode(),
            durable_lambda_core::types::ExecutionMode::Replaying
        );
    }

    #[tokio::test]
    async fn test_mock_context_no_aws_credentials_needed() {
        // This test proves the mock works without any AWS env vars
        // by simply running successfully
        let (mut ctx, _calls, _ops) = MockDurableContext::new()
            .with_step_result("test", r#"true"#)
            .build()
            .await;

        let result: Result<bool, String> = ctx
            .step("test", || async { panic!("not executed") })
            .await
            .unwrap();

        assert!(result.unwrap());
    }
}