

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

# Amazon Q 开发者的代码示例
<a name="examples"></a>

本节提供了真实的示例，说明如何改善您的体验和代码生成，重点是 Python 以及 Java 语言。除了内联示例外，一些场景还展示了如何在编程时使用 Amazon Q Developer 的聊天功能来征求代码推荐的提示。

有关更多信息，请参阅以下主题：
+ [Python 例子 ](examples-python.md)
+ [Java 例子 ](examples-java.md)
+ [聊天示例](examples-chat.md)

# Python 示例
<a name="examples-python"></a>

以下 Python 示例演示了如何开始使用 Amazon Q Developer 生成行内代码建议。这些说明性示例向您展示了如何为自己的项目触发编码助手。以下大多数示例适用于其他语言：
+ [生成类和函数](#classes-python)
+ [文件代码](#code-python)
+ [生成算法](#algorithms-python)
+ [生成单元测试](#tests-python)

## 生成类和函数
<a name="classes-python"></a>

 要生成全部或部分类实现，请使用代码注释。该评论描述了该班的意图。从简单开始，必要时添加更多细节。生成类后。您可以继续在其骨架中生成函数。

当你写评论时，最好使用该语言的注释结构。In Python，对于单行注释，请使用`#`***。***对于多行注释，请使用`''' '''`或`""" """`。

输入:

```
'''
DocumentReader class. has a name, children and optional parent. 
Includes I/O functions to read and
write document
'''
```

输出：

```
class DocumentReader:
    def __init__(self, name, children, parent=None):
        self.name = name
        self.parent = parent
        self.children = children
        
    def read(self):
        """Reads current document and returns text"""
        pass
    
    def write(self, text):
        """Writes text to current document"""
        pass
```

现在有了初始类，可以生成一个带有额外注释的附加函数。

输入:

```
'''
function to read document from local directory path and print the first line of the document
'''
```

输出：

```
def read_document(self, path):
        """Reads document from path and prints first line"""
        import os
        if os.path.isfile(path):
            with open(path, 'r') as f:
                print(f.readline())
        else:
            print(f"File not found at {path}")
```

## 文件代码
<a name="code-python"></a>

依靠内联文档，缩短编写代码的时间。添加 Python 评论中断`''' '''`。

输入:

```
class S3Utils:
    '''
    <place cursor here>
    '''
    def __init__(self):
        self.base_url = "https://s3"

    def generate_s3_url(self, bucket_name, region):
        return f"{self.base_url}.{region}.amazonaws.com/{bucket_name}"

# Example usage:
if __name__ == "__main__":
    s3_util = S3Utils()
    bucket_name = "my-example-bucket"
    region = "us-west-1"
    s3_url = s3_util.generate_s3_url(bucket_name, region)
    print(f"S3 URL for bucket '{bucket_name}' in region '{region}': {s3_url}")
```

输出：

```
class S3Utils:
    '''
    Class to generate S3 URL from bucket name and region
    '''
    def __init__(self):
        self.base_url = "https://s3"

    def generate_s3_url(self, bucket_name, region):
        return f"{self.base_url}.{region}.amazonaws.com/{bucket_name}"

# Example usage:
if __name__ == "__main__":
    s3_util = S3Utils()
    bucket_name = "my-example-bucket"
    region = "us-west-1"
    s3_url = s3_util.generate_s3_url(bucket_name, region)
    print(f"S3 URL for bucket '{bucket_name}' in region '{region}': {s3_url}")
```

## 生成算法
<a name="algorithms-python"></a>

Amazon Q Developer 可以生成常用的算法，尤其是与之相关的算法 AWS SDKs。在你的脚本中，添加一个提示来指定你想要的函数。

此示例说明如何生成用于命名值的用户 ID 键的字典，然后使用冒泡排序算法生成排序函数。

输入:

```
class SortList:
    @staticmethod
    def get_user_id_name_map():
        user_id_name_map = {
            1: "Amit",
            2: "Rahul",
            3: "Vijay",
            4: "Raj",
            5: "Kumar"
        }
        return user_id_name_map
    

    '''
    Sort the list of user id's alphabetically using bubble sort
    '''
```

输出：

```
    @staticmethod
    def sort_user_id_name_map():
        user_id_name_map = SortList.get_user_id_name_map()
        list_of_user_ids = list(user_id_name_map.keys())
        list_of_user_names = list(user_id_name_map.values())
        print("Before sort: ", list_of_user_ids)
        for i in range(len(list_of_user_ids)):
            for j in range(len(list_of_user_ids) - i - 1):
                if list_of_user_names[j] > list_of_user_names[j + 1]:
                    list_of_user_ids[j], list_of_user_ids[j + 1] = list_of_user_ids[j + 1], list_of_user_ids[j]
                    list_of_user_names[j], list_of_user_names[j + 1] = list_of_user_names[j + 1], list_of_user_names[j]
        print("After sort: ", list_of_user_ids)
```

此外，您还可以为标准程序创建提示。在此示例中，用户创建了将字典存储到 Amazon DynamoDB 表的提示。在脚本的开头，用户添加了添加 DynamoDB 库的提示，以帮助为 Amazon Q 开发者提供更多背景信息。

输入:

```
'''
Add libraries for Amazon Dynamo DB
'''
```

输出：

```
'''
Add libraries for Amazon Dynamo DB and JSON.

iMport necessary libraries for working with Amazon DynamoDB and JSON data.
'''

import boto3
import json
from botocore.exceptions import ClientError

def load_data_to_dynamodb(table_name, data_file):
    # Create a DynamoDB resource
    dynamodb = boto3.resource('dynamodb')

    # Get a reference to the table
    table = dynamodb.Table(table_name)

    # Load data from the JSON file
    with open(data_file, 'r') as file:
        data = json.load(file)

    # Iterate over the data and load it to the table
    for item in data:
        try:
            table.put_item(Item=item)
            print(f"Successfully loaded data: {item}")
        except ClientError as e:
            print(f"Error loading data: {e.response['Error']['Message']}")

# Example usage
load_data_to_dynamodb('myTable', 'data.json')
```

现在，用户可以轻松地让 Amazon Q 帮助将字典存储在 DynamoDB 中。

输入:

```
'''
   function to store the above sorted dict to dynamodb table named users    
'''
```

输出：

```
@staticmethod
    def store_user_id_name_map_in_dynamodb():
        user_id_name_map = SortList.get_user_id_name_map()
        list_of_user_ids = list(user_id_name_map.keys())
        list_of_user_names = list(user_id_name_map.values())
        dynamodb = boto3.resource('dynamodb')
        table = dynamodb.Table('users')
        for i in range(len(list_of_user_ids)):
            try:
                response = table.put_item(
                    Item={
                        'user_id': list_of_user_ids[i],
                        'user_name': list_of_user_names[i]
                    }
                )
            except ClientError as e:
                print(e.response['Error']['Message'])
```

## 生成单元测试
<a name="tests-python"></a>

通过内嵌评论，Amazon Q Developer 可以生成单元测试来执行断言和其他测试。在此示例中，用户要求 Amazon Q 生成适用于单元测试的库，以设置测试脚本的上下文。然后，用户要求 Amazon Q 为该函数编写一个测试`sort_user_id_name_map`函数。

输入:

```
'''
Import all the required unit test libraries for python and then generate a unit test for sort_user_id_name_map function.
'''
```

输出：

```
import unittest
from unittest.mock import patch
from sort_user_id_name_map import sort_user_id_name_map

class TestSortUserIdNameMap(unittest.TestCase):
    @patch('sort_user_id_name_map.sort_user_id_name_map')
    def test_sort_user_id_name_map(self, mock_sort):
        mock_sort.return_value = {'id1': 'name1', 'id2': 'name2'}
        result = sort_user_id_name_map({'id2': 'name2', 'id1': 'name1'})
        self.assertEqual(result, {'id1': 'name1', 'id2': 'name2'})

if __name__ == '__main__':
    unittest.main()
```

此外，在用户与 Amazon Q Developer 之间的聊天中，它会根据用户的代码输入提示建议并生成单元测试。有关更多信息，请参阅[聊天示例](examples-chat.md)。

# Java 示例
<a name="examples-java"></a>

以下 Java 示例演示了用户如何开始生成内嵌代码建议。这些说明性示例向您展示了如何为自己的项目触发编码助手。以下大多数示例适用于其他语言：
+ [生成类和函数](#classes-java)
+ [文件代码](#code-java)
+ [生成算法](#algorithms-java)
+ [生成单元测试](#tests-java)

## 生成类和函数
<a name="classes-java"></a>

要生成全部或部分类实现，请使用代码注释。该评论描述了该班的意图。从简单开始，必要时添加更多细节。生成类后，可以继续在其框架内生成函数。

在撰写评论时，最好使用该语言的注释结构。In Java，这是`/** */`*。*

输入: 

```
/**
 * DocumentReader class. has a name, children and optional parent. 
 * Includes I/O functions to read and
 * write document
 */
```

输出：

```
/**
 * DocumentReader class. has a name, children and optional parent. 
 * Includes I/O functions to read and
 * write document
 */
import java.util.ArrayList;
public class DocumentReader {
    private String name;
    private DocumentReader parent;
    private ArrayList<DocumentReader> children;

    /**
     * Constructor
     * @param name name of the document
     * @param parent parent of the document
     */
    public DocumentReader(String name, DocumentReader parent) {
        this.name = name;
        this.parent = parent;
        this.children = new ArrayList<>();
    }

    /**
     * Constructor
     * @param name name of the document
     */
    public DocumentReader(String name) {
        this(name, null);
    }
    /**
     * Getter for name
     * @return name of the document
     */
    public String getName() {
        return name;
    }

    /**
     * Getter for parent
     * @return parent of the document
     */
    public DocumentReader getParent() {
        return parent;
    }

    /**
     * Getter for children
     * @return children of the document
     */
    public ArrayList<DocumentReader> getChildren() {
        return children;
    }

    /**
     * Adds a child to the document
     * @param child child to be added
     */
    public void addChild(DocumentReader child) {
        children.add(child);
    }

    /**
     * Removes a child from the document
     * @param child child to be removed
     */
    public void removeChild(DocumentReader child) {
        children.remove(child);
    }
}
```

现在有了初始类，可以生成一个带有额外注释的附加函数。

输入:

```
/**
* function to read document from local directory path
* and print first line of document
*/
```

输出：

```
/**
 * function to read document from local directory path
 * and print first line of document
 */
public void readDocument() {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(name));
        String line = reader.readLine();
        System.out.println(line);
        reader.close();
    } catch (IOException e) {
        System.out.println("Error reading document: " + e.getMessage());
    }
}
```

## 文件代码
<a name="code-java"></a>

依靠内联文档，缩短编写代码的时间。添加一个 Java 评论中断`/* */`。

输入: 

```
import java.util.function.Function;

public class S3Utils {
    /* 
     * <place cursor here>
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

如果未进行内联生成，请在将光标放在所需文档的位置后执行 Amazon Q Developer 内联建议。

输出：

```
import java.util.function.Function;

public class S3Utils {
    /* 
     * Generate a function that returns the S3 URL for a given key
     * @param bucketName the name of the bucket
     * @param region the region of the bucket
     * @return the function that generates the S3 URL
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

要更简单地解释代码（类、函数或脚本元素），请使用正向字符 (`//`)，这些字符策略性地放在要添加文档的代码部分之前。

输入:

```
// 
public class S3Utils {
    /* 
     * Generate a function that returns the S3 URL for a given key
     * @param bucketName the name of the bucket
     * @param region the region of the bucket
     * @return the function that generates the S3 URL
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

输出：

```
// This class is used to generate a function that returns the S3 URL for a given key
public class S3Utils {
    /* 
     * Generate a function that returns the S3 URL for a given key
     * @param bucketName the name of the bucket
     * @param region the region of the bucket
     * @return the function that generates the S3 URL
    */
    public static Function<String, String> generateS3Function(String bucketName, String region) {
        return (String key) -> {
            String url = generateS3Url(bucketName, key, region);
            return url;
        };
    }
}
```

## 生成算法
<a name="algorithms-java"></a>

Amazon Q 开发者可以生成常用的算法，尤其是与之相关的算法 AWS SDKs。在你的脚本中，添加一个提示来指定你想要的函数。

此示例生成用户名密钥到命名值的哈希映射，然后使用冒泡排序算法生成排序函数。

输入:

```
import java.util.HashMap;
public class SortList {

    // generate key value pair hash map for 
    // user id and name
    public static HashMap<Integer, String> getUserIdNameMap() {
        HashMap<Integer, String> userIdNameMap = new HashMap<Integer, String>();
        userIdNameMap.put(1, "Amit");
        userIdNameMap.put(2, "Rahul");
        userIdNameMap.put(3, "Vijay");
        userIdNameMap.put(4, "Raj");
        userIdNameMap.put(5, "Kumar");
        return userIdNameMap;
    }

    /*
    * Create function to sort UserIdName map by name alphabetically using bubble sort
    */ 
    
    
}
```

输出：

```
/*
* Create function to sort UserIdName map by name alphabetically using bubble sort
*/ 
public static HashMap<Integer, String> sortUserIdNameMap(HashMap<Integer, String> userIdNameMap) {
    int size = userIdNameMap.size();
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (userIdNameMap.get(i).compareTo(userIdNameMap.get(j)) > 0) {
                String temp = userIdNameMap.get(i);
                userIdNameMap.put(i, userIdNameMap.get(j));
                userIdNameMap.put(j, temp);
            }
        }
    }
    return userIdNameMap;
}
```

此外，用户还可以为标准程序创建提示。在此示例中，用户创建了将哈希映射存储到 Amazon DynamoDB 表的提示。在脚本的开头，用户添加了添加 DynamoDB 的提示 Java 库可帮助为 Amazon Q 开发者提供更多背景信息。

输入:

```
// add libraries for Amazon DynamoDB
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;

     /*
     * Store sorted UserIdName map into Amazon DynamoDB table named users
     */
```

输出：

```
// add libraries for Amazon DynamoDB
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;

     /*
     * Store sorted UserIdName map into Amazon DynamoDB table named users
     */
    public static void storeSortedUserIdNameMap(HashMap<Integer, String> userIdNameMap) {
        // create Amazon DynamoDB client
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();

        // store sorted UserIdName map into Amazon DynamoDB table named users
        for (int userId : userIdNameMap.keySet()) {
            String name = userIdNameMap.get(userId);
            client.putItem("users", new HashMap<String, Object>() {{
                put("userId", userId);
                put("name", name);
            }});
        }
    }
```

## 生成单元测试
<a name="tests-java"></a>

通过内嵌评论，Amazon Q Developer 可以生成单元测试来执行断言和其他 JUnit 测试。在此示例中，用户首先要求 Amazon Q 生成适用的库 JUnit 以设置测试脚本的上下文。接下来，用户创建一个公共类，后面是声明符和注释字符串。

输入:

```
// import libraries for java unit tests
import org.junit.Test;
import static org.junit.Assert.*;

public class UnitTests {

    @Test 
    /*
     * Create unit test for getUserIdNameMap
     */  
}
```

输出：

```
@Test 
/*
* Create unit test for getUserIdNameMap
*/
public void testGetUserIdNameMap() {
    // create a new instance of the UserIdNameMap class
    UserIdNameMap userIdNameMap = new UserIdNameMap();

    // create a new instance of the User class
    User user = new User("John", "Doe");

    // add the user to the map
    userIdNameMap.addUser(user);

    // get the user from the map
    User retrievedUser = userIdNameMap.getUser("John");

    // assert that the retrieved user is the same as the user added to the map
    assertEquals(user, retrievedUser);
}
```

此外，在用户与 Amazon Q Developer 之间的聊天中，它会根据用户的代码输入提示建议并生成单元测试。有关更多信息，请参阅[聊天示例](examples-chat.md)。

# 聊天示例
<a name="examples-chat"></a>

Amazon Q Developer 聊天可帮助开发者完成各种任务，从编码、测试和升级应用程序，到诊断错误、执行安全扫描和修复以及优化 AWS 资源。本节介绍与 Amazon Q 聊天如何支持开发者完成典型的编程任务，例如：
+ [询问 AWS 服务](#services-chat)
+ [生成代码](#code-chat)
+ [生成单元测试](#tests-chat)
+ [解释代码](#explain-chat)

## 询问 AWS 服务
<a name="services-chat"></a>

用户可以向 Amazon Q Developer 提问 AWS 服务，例如寻找合适的服务或了解最佳实践。

### 聊一聊 AWS 服务
<a name="chat-services"></a>

用户：

如果我需要保持较低的成本，哪种容器服务最适合用来运行我的工作负载？

亚马逊 Q：

根据提供的信息，您似乎正在寻找一种经济实惠的容器服务来运行您的工作负载。在这种情况下，我建议考虑将亚马逊弹性容器服务 (Amazon ECS) 与 Fargate 配合使用。[1]

带有 Fargate 的 Amazon ECS 是一款适用于容器的无服务器计算引擎，它允许您运行容器，而无需管理任何底层基础设施。有了 Fargate，你无需配置或管理服务器，Fargate 会为你处理这个问题。这有助于保持较低的成本，因为您只需为容器实际使用的计算资源付费，而不必为闲置的服务器容量付费。[2]

将 Amazon ECS 与 Fargate 配合使用的一些主要好处：

• 无需管理服务器或集群 — Fargate 为您处理基础设施的配置和管理。

• Pay-as-you-go 定价 — 您只需为容器使用的计算资源付费，无需为闲置容量付费。

• 自动扩展 — Fargate 可以根据需求自动向上和向下扩展容器。

• 与其他功能（ AWS 服务 例如负载平衡、日志记录和监控）紧密集成。

提供的资源还提到，ECS 服务在容器调度和放置方面提供了灵活性，这有助于进一步优化成本。

我建议您在 AWS 网站上查看带有 Fargate 的 Amazon ECS 的定价详情，以便根据您的具体工作负载要求更好地了解成本。当然，如果您还有其他问题，请随时告诉我！

源

[1] 哪种 AWS 容器服务最适合您？

[aptgetops.tech >--你 aws-container-services-which one-is-right-for](https://aptgetops.tech/aws-container-services-which-one-is-right-for-you)

[2] Java 非 HTTP 工作负载的容器选项

[stackoverflow.com > 问题 > 43417016](https://stackoverflow.com/questions/43417016/java-container-options-for-non-http-worloads)

**结束关于 Amazon Q 的聊天 AWS 服务**

## 生成代码
<a name="code-chat"></a>

用户可以向 Amazon Q 开发者寻求帮助以编写代码片段。

### 聊聊编写代码
<a name="chat-writing"></a>

用户：

能否举个例子，说明如何使用列出所有 S3 存储桶？ AWS SDK for Python (Boto)

亚马逊 Q：

当然，以下是如何使用 AWS SDK for Python (Boto)[1] 列出所有 S3 存储桶的示例：

```
import boto3
# Create an S3 client
s3 = boto3.client('s3')

# List all the buckets
response = s3.list_buckets()

# Print the name of each bucket
for bucket in response['Buckets']:
    print(bucket['Name'])
```

代码的工作原理如下：

1. 我们首先导入 boto3 库，这是适用于 Python 的软件开发工具包。

1. 我们使用创建 S3 客户端`boto3.client('s3')`。

1. 我们在 S3 客户端上调用该`list_buckets()`方法，它会返回一个包含账户中所有存储桶列表的响应。

1. 然后，我们遍历响应中的`Buckets`列表并打印出每个存储桶的名称。

这是一个基本示例，但为使用 Amazon S3 AWS SDK for Python (Boto) 提供了许多更高级的功能，例如创建、删除和管理存储桶中的对象，设置存储桶策略等。您可以在 AWS SDK for Python (Boto)) 文档中找到更多示例和文档。[2]

请记住，在使用时 AWS 服务，请务必遵循处理凭证和敏感信息的最佳实践，例如将 AWS 访问密钥存储在环境变量中，而不是在代码中对其进行硬编码。

来源：[1] [使用适用于 Python 的软件开发工具包的亚马逊 S3 示例 (Boto3)-SDK 代码示例 docs.aws.amazon.com > 代码 AWS 库 >](https://docs.aws.amazon.com/code-library/latest/ug/python_3_s3_code_examples.html) latest-1x >... > python-s3.html

[2] [开始使用 SDK 使用亚马逊 S3 存储桶和对象——S AWS D AWS K 代码示例 docs.aws.amazon.com > 代码库 > latest-1x >... > s3\$1example\$1s](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example_s3_Scenario_GettingStarted_section.html) 3\$1buckets\$1 \$1sect... GettingStarted 

**结束关于编写代码的 Amazon Q 聊天**

## 生成单元测试
<a name="tests-chat"></a>

用户可以将选定的代码作为提示发送给 Amazon Q Developer，在那里会应用其他说明，例如生成单元测试。有关 step-by-step说明，请参阅 [Amazon Q *开发者用户指南中的向 Amazon Q* 发送代码](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/explain-update-code.html#send-code)。

### 聊聊单元测试
<a name="chat-unit"></a>

用户：

为以下函数编写一个包含模拟数据的单元测试：

```
 // poll messages from Amazon SQS queue name
    public List<String> pollMessages(String queueName) {
        List<String> messages = new ArrayList<>();
        // poll messages from queue
        ReceiveMessageResult = sqsClient.receiveMessage(new ReceiveMessageRequest().
        for (Message : receiveMessageResult.getMessages()) {
            messages.add(message.getBody());
        }
        return messages;
        }
```

亚马逊 Q：

要为 PollMessages 函数编写带有模拟数据的单元测试，我们可以使用像 Mockito 这样的模拟框架。示例如下：

```
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Arrays;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

@ExtendWith(MockitoExtension.class)
public class SQSUtilsTest {

    @Mock
    private AmazonSQS sqsClient;

    @InjectMocks
    private SQSUtils sqsUtils;

    @Test
    public void testPollMessages() {
        // Arrange
        String queueName = "test-queue";
        Message message1 = new Message().withBody("message1");
        Message message2 = new Message().withBody("message2");
        ReceiveMessageResult receiveMessageResult = new ReceiveMessageResult().withMessages(message1, message2);
        Mockito.when(sqsClient.receiveMessage(new ReceiveMessageRequest().withQueueUrl(queueName)))
                .thenReturn(receiveMessageResult);

        // Act
        List<String> messages = sqsUtils.pollMessages(queueName);

        // Assert
        assertEquals(Arrays.asList("message1", "message2"), messages);
    }
}
```

在此示例中，我们使用 Mockito 来模拟 AmazonSQS 客户端，并设置 ReceiveMessage 方法的预期行为，以便它返回两条正文为 “message1” 和 “message2” 的模拟消息。然后，我们调用 pollMessages 方法并断言返回的消息列表与预期值相匹配。

关键点是：

1. 我们使用 @ ExtendWith (MockitoExtension.class) 注解来启用 Mockito 与的集成。 JUnit

1. 我们使用 @Mock 注解来创建 AmazonSQS 客户端的模拟实例。

1. 我们使用 @ InjectMocks 注解将模拟 AmazonSQS 客户端注入到课堂中。 SQSUtils 

1. 在测试方法中，我们使用 mockito.when () .thenReturn () 设置了 receiveMessage 方法的预期行为。

1. 我们调用 pollMessages 方法并断言返回的消息列表与预期值相匹配。

这种方法使我们能够在不实际与 Amazon SQS 服务交互的情况下测试 PollMessages 方法，这可以使测试更快、更可靠。

**结束****关于单元测试的 Amazon Q 聊天**

## 解释代码
<a name="explain-chat"></a>

对于代码审查流程，开发人员可以向 Amazon Q Developer 发送代码选择以更好地理解代码。此外，Amazon Q 提供的解释也可以用于文档目的。在以下示例中，Amazon Q 使用函数解释了处理 AWS Lambda 函数，然后提出了文档字符串。

### 聊一聊解释代码
<a name="chat-explain"></a>

用户：

解释一下我的代码的以下部分：

```
def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    s3_client = boto3.client('s3')
    table = dynamodb.Table('DYNAMODB_TABLE')
    # Get s3 object from the event
    print(event)
    print(context)
    # get object from event
    bucket_key = event['Records'][0]['s3']['object']['key']
    object_key = unquote_plus(bucket_key)
    fullText = detect_text(object_key, bucket)

    response = s3_client.head_object(Bucket=bucket, Key=object_key)
    print(response)
    print(fullText)
    metadata = response['ResponseMetadata']
    metadata = json.dumps(metadata)

    now = datetime.now()
    current_time = now.strftime("%A %d %B, %Y %H:%M:%S")
    print("Current Time =", current_time + "\n\n")
    reason, outcome = detect_restaurant_closure(fullText, current_time)
    table.put_item(
        Item={
            'id': object_key,
            'creationTime': now.strftime("%Y-%m-%d %H:%M:%S"),
            'reason': reason,
            'text': fullText,
            'metadata': metadata
        }
    )
```

亚马逊 Q：

提供的代码块似乎是一个写入的 AWS Lambda 函数 Python。 让我解释一下这段代码的关键方面：

1. 该函数名为 lambda\$1handler，它是 Lambda 函数的入口点。

1. 它使用 boto3 库与 AWS DynamoDB 和 S3 服务进行交互。

1. 该函数从传入的事件数据中检索 S3 对象密钥和存储桶名称。

1. 然后，它会调用 detect\$1text 函数（未显示在提供的代码中）来提取 S3 对象的全文内容。

1. 该函数还使用 head\$1object 方法检索有关 S3 对象的元数据。

1. 然后，它提取当前时间并调用 detect\$1restaurant\$1closure 函数（也未显示），以根据提取的文本确定餐厅关闭的原因和结果。

1. 最后，该函数将以下信息存储在 DynamoDB 表中：
   + 将 S3 对象密钥作为 id
   + 创建时间
   + 餐厅关闭的原因和结果
   + 提取的 S3 对象文本

总体而言，这个 Lambda 函数似乎是一个更大的系统的一部分，该系统处理 S3 对象，提取文本内容，分析其中的餐厅关闭信息，并将结果存储在 DynamoDB 表中。要完全理解此代码的功能，需要获取 detect\$1text 和 detect\$1restaurant\$1closure 函数的具体细节。

**亚马逊 Q 回复已结束**

用户：将此解释汇总成此 lambda\$1handler 函数的文档字符串

Amazon Q：以下是 lambda\$1handler 函数 [1] 的建议文档字符串：

```
def lambda_handler(event, context):
    """
    AWS Lambda function that processes an S3 object, extracts text content, analyzes it, and stores the results.
    Args:
        event (dict): The event data that triggered the Lambda function, containing information about the S3 object.
        context (object): The context object provided by AWS Lambda, containing information about the runtime environment.
    
    Returns:
        None
    """
    
    # function implementation details...
```

这个 docstring 概述了函数的用途、它期望的输入参数以及预期的返回值（在本例中为缺少返回值）。它使用户可以清楚地了解 lambda\$1handler 函数的作用，而无需深入研究实现细节。

来源：[1] 在 C\$1 中定义 Lambda 函数处理程序- AWS Lambda [https://docs.aws.amazon.com/lambda/latest/dg/csharp-handler.html-: \$1: text=Lambda 函数处理程序是、、退](https://docs.aws.amazon.com/lambda/latest/dg/csharp-handler.html#:~:text=The%20Lambda%20function%20handler%20is,%2C%20exits%2C%20or%20times%20out.)出或超时。

**关于解释代码的 Amazon Q 聊天已结束**