

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 测试和调试耐用函数
<a name="test-and-debug-durable-functions"></a>

本地测试和调试耐久函数的工作方式与常规 Lambda 函数类似，自动支持检查点和重播。本指南涵盖常见的测试场景和故障排除技术。

## 本地测试工作流程
<a name="test-and-debug-durable-functions-workflow"></a>

在本地测试耐久函数时，工作流程不同于常规 Lambda 函数：

**耐用功能测试工作流程**

1. 构建您的应用程序：

   ```
   $ sam build
   ```

1. 调用你的耐用函数：

   ```
   $ sam local invoke MyDurableFunction --durable-execution-name test 
   ```

1. 如有必要，请查看执行历史记录：

   ```
   $ sam local execution history execution-id
   ```

## 常见测试场景
<a name="test-and-debug-durable-functions-scenarios"></a>

### 测试检查点行为
<a name="test-and-debug-durable-functions-scenarios-checkpoints"></a>

要测试你的函数是否正确检查点状态，请执行以下操作：

```
# Example Python durable function
def handler(event, context):
    # This will create a checkpoint
    context.wait(10)  # Wait 10 seconds
    
    # Function resumes here after wait
    return {"message": "Function resumed after wait"}
```

当您在本地调用此函数时，会自动处理等待时间。

### 测试回调场景
<a name="test-and-debug-durable-functions-scenarios-callbacks"></a>

对于等待外部回调的函数：

1. 启动等待回调的耐用函数

1. 在另一个终端中，解析回调：

   ```
   $ sam local callback succeed callback-id
   ```

1. 观察函数恢复执行

## 问题排查
<a name="test-and-debug-durable-functions-troubleshooting"></a>

### 耐用函数无法正常执行
<a name="test-and-debug-durable-functions-troubleshooting-config"></a>

**问题：**该函数的行为不像一个持久的函数。

**解决方案**
+ 验证您`DurableConfig`的 SAM 模板中是否已设置
+ 确保您的函数代码使用耐用的函数 SDK 方法（例如`context.wait()`）
+ 检查你使用的是支持的运行时（TypeScript、 JavaScript、Python）

### 无法检索执行历史记录
<a name="test-and-debug-durable-functions-troubleshooting-history"></a>

**问题：**该`local execution history`命令未返回任何结果。

**解决方案**
+ 验证执行 ID 是否正确
+ 检查该函数是否至少被调用过一次

### 回调命令不起作用
<a name="test-and-debug-durable-functions-troubleshooting-callbacks"></a>

**问题：**回调命令无法解决待处理的操作。

**解决方案**
+ 验证回调 ID 是否正确
+ 确保该函数实际上是在等待回调
+ 验证您使用的回调命令语法是否正确

## 调试技巧
<a name="test-and-debug-durable-functions-debugging"></a>
+ **使用执行历史记录**-查看执行历史记录以了解持久函数的流程
+ **增量测试**-从简单的等待操作开始，然后再添加复杂的逻辑
+ **使用详细日志-启用详细日志**记录以跟踪执行流程

## 了解详情
<a name="test-and-debug-durable-functions-learn"></a>

有关测试和调试的更多信息，请参阅：
+ [使用 sam local invoke 进行测试简介](using-sam-cli-local-invoke.md)-本地调用文档
+ [sam local execution history](sam-cli-command-reference-sam-local-execution-history.md)-执行历史