【问题标题】:Moto doesn't mock DynamoDBMoto 不模拟 DynamoDB
【发布时间】:2020-06-06 13:54:32
【问题描述】:

我正在尝试为与 DynamoDB 通信的 Lambda 函数编写单元测试。我正在使用moto,但它并没有嘲笑任何东西。每当我在 boto3 中调用某些内容时,它都会使用我的 AWS CLI 配置文件与实际 API 进行通信,而不是模拟 API。为什么会这样?

代码如下:

### Unit test for the visitorCounterLambda function

from visitorCounterLambda import handler
import boto3
from moto import mock_dynamodb2


def setUp(self):
  #pass
  self.region = 'us-east-2'

@mock_dynamodb2
def test_handler():
  dynamodb = boto3.client('dynamodb')
  ddbTableName = "myDDBtable"

  # table = dynamodb.create_table(
  #   TableName = ddbTableName,
  #   BillingMode='PAY_PER_REQUEST',
  #   AttributeDefinitions=[
  #       {
  #           'AttributeName': 'id',
  #           'AttributeType': 'S'
  #       },
  #   ],
  #   KeySchema=[
  #       {
  #           'AttributeName': 'id',
  #           'KeyType': 'HASH'
  #       },
  #   ]
  # )
  tablesListed = dynamodb.list_tables()
  print(tablesListed)



if __name__ == '__main__':
    test_handler()

print(tablesListed) 从我的实际账户返回我的实际表格。如果我取消注释 create_table 命令,它也会在我的 AWS 账户中创建表。

我在这里缺少什么? 谢谢

【问题讨论】:

  • 我刚刚试用了您的代码,它在这里工作得非常好。你使用的是什么版本的 Python 和 boto3moto
  • 我正在使用Python 3.7.3boto3 1.13.24moto 1.3.14。可能是因为我预先配置了 CLI 凭据?
  • @Dunedan 感谢您的帮助,我想通了,请在下面查看我的答案。我不得不提一下,我的帖子是由两个不同的人编辑的,目的是“清理代码”,他们删除了问题所在的部分。最好的代码监管......

标签: python aws-lambda boto3 moto


【解决方案1】:

我发现问题出在from visitorCounterLambda import handler 部分,因为该脚本在导入时已经建立了一个boto3 客户端,因此mock 无法破坏它。正确的做法在Moto documentation 中的“非常重要——推荐的用法” 下进行了概述。你应该先建立@mock_dynamodb2,然后在import你的外部资源进入函数。

例子:

import boto3
from moto import mock_dynamodb2

@mock_dynamodb2
def test_handler():
  from visitorCounterLambda import handler
  dynamodb = boto3.client('dynamodb')

  ## do your magic here

  tablesListed = dynamodb.list_tables()
  print(tablesListed)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多