Moto不模拟DynamoDB

问题描述 投票:0回答:1

我正在尝试为与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 aws-lambda boto3 moto
1个回答
0
投票

我发现问题出在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)

© www.soinside.com 2019 - 2024. All rights reserved.